pid_contract_model.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193
  1. #!/usr/bin/env python3
  2. """Contract-level model for parallel PID integration."""
  3. from __future__ import annotations
  4. import csv
  5. import json
  6. import random
  7. import re
  8. from collections import Counter
  9. from dataclasses import dataclass
  10. from pathlib import Path
  11. from pid_model import CONFIG_PATH, IncrementalPid, PidConfig
  12. ACTUATOR_REASON_OK = "ok"
  13. ACTUATOR_REASON_HOST_DISABLED = "host_disabled"
  14. ACTUATOR_REASON_PID_OR_SENSOR_FAULT = "pid_or_sensor_fault"
  15. ACTUATOR_REASON_CHANNEL_INVALID = "channel_invalid"
  16. ACTUATOR_REASON_SENSOR_STALE = "sensor_stale"
  17. ACTUATOR_REASON_HOST_TIMEOUT = "host_timeout"
  18. ACTUATOR_REASON_OVERTEMP = "overtemp"
  19. ACTUATOR_REASON_INTERLOCK = "interlock"
  20. ACTUATOR_REASON_FAN_FALLBACK = "fan_fallback"
  21. SOURCE_FAKE = 0
  22. SOURCE_I2C_MASTER = 1
  23. SOURCE_I2C_SLAVE_INJECT = 2
  24. SOURCE_RS232_UART_INJECT = 3
  25. SOURCE_RS485_INJECT = 4
  26. SOURCE_BMC_UART_TEXT = 5
  27. SOURCE_FAKE_STRESS = 6
  28. CONTROL_MODE_SAFE_OFF = 0
  29. CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL = 1
  30. CONTROL_MODE_MANUAL_LEVEL = 2
  31. CONTROL_MODE_INCREMENTAL_PID_DEFAULT = 3
  32. CONTROL_MODE_HYSTERESIS_PI_DEFAULT = CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL
  33. CONTROL_MODE_INCREMENTAL_PID_EXPERIMENTAL = CONTROL_MODE_INCREMENTAL_PID_DEFAULT
  34. ACTUATOR_KIND_PTC = "ptc"
  35. ACTUATOR_KIND_FAN = "fan"
  36. ACTUATOR_KIND_MOTOR = "motor"
  37. FAULT_CODE_OK = 0
  38. FAULT_CODE_HOST_DISABLED = 1
  39. FAULT_CODE_SENSOR_FAULT = 2
  40. FAULT_CODE_SENSOR_STALE = 3
  41. FAULT_CODE_HOST_TIMEOUT = 4
  42. FAULT_CODE_OVERTEMP = 5
  43. FAULT_CODE_INVALID_CHANNEL = 6
  44. FAULT_CODE_INTERLOCK = 7
  45. RAW_STATUS_OK = 0x00
  46. RAW_STATUS_MISSING_DIMM = 0x01
  47. RAW_STATUS_PARSER_ERROR = 0x02
  48. RAW_STATUS_SENSOR_FAULT = 0x04
  49. RAW_STATUS_STALE = 0x08
  50. PARSER_STATUS_OK = "ok"
  51. PARSER_STATUS_BAD_LENGTH = "bad_length"
  52. PARSER_STATUS_NO_CANDIDATE = "no_candidate"
  53. PARSER_STATUS_BAD_FRACTION = "bad_fraction"
  54. BMC_POLL_COMMAND_ASCII = "ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03\n"
  55. BMC_POLL_COMMAND_BYTES = [0x36, 0x6C, 0xDF, 0xDD, 0x00, 0x03]
  56. BMC_DIMM_SINGLE_SNAPSHOT_HEX = """
  57. 3c 4b 40 32 40 4b 4d 00 3f 19 38 00 ff ff ff ff
  58. 32 00 4c 00 3b 4b 36 00 3a 00 3e 00 3e 32 3e 4b
  59. 3d 00 36 4b 26 00 28 00 29 19 31 19 37 4b 35 00
  60. """.strip()
  61. BMC_DIMM_USER_SAMPLE_TEXT = """
  62. ("23", "4b", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff",
  63. "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff",
  64. "ff", "ff", "28", "00", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff",
  65. "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff")
  66. """.strip()
  67. @dataclass(frozen=True)
  68. class SensorSample:
  69. valid: bool
  70. fault: bool
  71. channel: int
  72. temp_q: int
  73. sample_seq: int
  74. source_id: int = SOURCE_FAKE
  75. @dataclass(frozen=True)
  76. class HostConfig:
  77. enable: bool
  78. target_q: int
  79. a0: int
  80. a1: int
  81. a2: int
  82. mode: int
  83. config_seq: int
  84. @dataclass(frozen=True)
  85. class PidResult:
  86. valid: bool
  87. channel: int
  88. error_q: int
  89. ctrl_q: int
  90. done: bool
  91. fault: bool
  92. sample_seq: int = 0
  93. ctrl_prev_q: int = 0
  94. delta_q: int = 0
  95. clamped: bool = False
  96. history_cleared: bool = False
  97. control_mode: int = CONTROL_MODE_INCREMENTAL_PID_DEFAULT
  98. experimental: bool = False
  99. dimm_id: int = -1
  100. target_q: int = 0
  101. proportional_q: int = 0
  102. integral_q: int = 0
  103. manual_level_q: int = 0
  104. @dataclass(frozen=True)
  105. class ActuatorCommand:
  106. enable: bool
  107. channel: int
  108. duty_or_level: int
  109. force_off: bool
  110. reason: str
  111. @dataclass(frozen=True)
  112. class SensorSampleV2:
  113. valid: bool
  114. ready: bool
  115. source_id: int
  116. channel: int
  117. temp_q: int
  118. fault: bool
  119. stale: bool
  120. sample_seq: int
  121. raw_status: int = 0
  122. @dataclass(frozen=True)
  123. class DimmTempSampleV1:
  124. valid: bool
  125. ready: bool
  126. source_id: int
  127. frame_seq: int
  128. sample_seq: int
  129. raw_pair_index: int
  130. dimm_id: int
  131. channel: int
  132. raw_integer_byte: int
  133. raw_fraction_byte: int
  134. fraction_scale: int
  135. temp_q: int
  136. temp_c_x100: int
  137. missing: bool
  138. fault: bool
  139. stale: bool
  140. age_ms: int
  141. raw_status: int
  142. parser_status: str
  143. present: bool = True
  144. cpu_id: int = -1
  145. airflow_zone: int = -1
  146. @dataclass(frozen=True)
  147. class BmcDimmFrameParseResult:
  148. parser_status: str
  149. expected_dimm_count: int
  150. samples: list[DimmTempSampleV1]
  151. frame_seq: int
  152. source_id: int
  153. raw_token_count: int = 0
  154. selected_window_start: int = -1
  155. rejected_echo_windows: int = 0
  156. missing_mask: int = 0
  157. @dataclass(frozen=True)
  158. class ChannelTopology:
  159. channel: int
  160. dimm_id: int
  161. cpu_id: int
  162. airflow_zone: int
  163. ptc_id: int
  164. @dataclass(frozen=True)
  165. class FakeStressStep:
  166. sample_seq: int
  167. channel: int
  168. temp_q: int
  169. duty: int
  170. missing: bool
  171. stale: bool
  172. noise_q: int
  173. coupled_heat_q: float
  174. phase: str = "baseline"
  175. event_flags: tuple[str, ...] = ()
  176. class FakeStressModel:
  177. """Deterministic verification-only thermal stress source.
  178. The coupling values are pressure-test defaults. They are not board thermal
  179. constants and are intentionally kept out of the CPLD control compensation.
  180. """
  181. def __init__(
  182. self,
  183. *,
  184. channel_count: int = 24,
  185. base_temp_q: int = 35,
  186. ambient_q: int = 25,
  187. seed: int = 260626,
  188. self_coupling: float = 1.0,
  189. neighbor_coupling: float = 0.04,
  190. same_zone_coupling: float = 0.01,
  191. cross_zone_coupling: float = 0.005,
  192. missing_mask: int = 0,
  193. ) -> None:
  194. self.channel_count = channel_count
  195. self.ambient_q = ambient_q
  196. self.temperatures = [float(base_temp_q) for _ in range(channel_count)]
  197. self.rng = random.Random(seed)
  198. self.self_coupling = self_coupling
  199. self.neighbor_coupling = neighbor_coupling
  200. self.same_zone_coupling = same_zone_coupling
  201. self.cross_zone_coupling = cross_zone_coupling
  202. self.missing_mask = missing_mask
  203. self.topology = build_channel_topology()
  204. self.sample_seq = 0
  205. self.long_scenario_epoch = 0
  206. @classmethod
  207. def from_config(cls, path: Path = CONFIG_PATH, *, missing_mask: int = 0) -> "FakeStressModel":
  208. payload = load_contract_config(path)
  209. stress = payload.get("fake_stress", {})
  210. if not isinstance(stress, dict):
  211. stress = {}
  212. channels = payload.get("channels", {})
  213. channel_count = int(channels.get("logical_channel_count", 24)) if isinstance(channels, dict) else 24
  214. return cls(
  215. channel_count=channel_count,
  216. seed=int(stress.get("scenario_seed", 260626)),
  217. self_coupling=float(stress.get("self_coupling", 1.0)),
  218. neighbor_coupling=float(stress.get("neighbor_channel_coupling", 0.04)),
  219. same_zone_coupling=float(stress.get("same_airflow_zone_non_neighbor_coupling", 0.01)),
  220. cross_zone_coupling=float(stress.get("cross_airflow_zone_coupling", 0.005)),
  221. missing_mask=missing_mask,
  222. )
  223. def coupling(self, source_channel: int, target_channel: int) -> float:
  224. if source_channel == target_channel:
  225. return self.self_coupling
  226. if abs(source_channel - target_channel) == 1:
  227. return self.neighbor_coupling
  228. source_zone = self.topology[source_channel].airflow_zone
  229. target_zone = self.topology[target_channel].airflow_zone
  230. if source_zone == target_zone:
  231. return self.same_zone_coupling
  232. return self.cross_zone_coupling
  233. def step(
  234. self,
  235. duties: list[int],
  236. *,
  237. noise_q: int = 0,
  238. stale: bool = False,
  239. ) -> list[FakeStressStep]:
  240. if len(duties) != self.channel_count:
  241. raise ValueError("duties length must match channel_count")
  242. heat_by_channel = []
  243. for target in range(self.channel_count):
  244. coupled_heat = 0.0
  245. for source, duty in enumerate(duties):
  246. coupled_heat += (max(0, min(127, duty)) / 127.0) * self.coupling(source, target)
  247. heat_by_channel.append(coupled_heat)
  248. steps: list[FakeStressStep] = []
  249. for channel, coupled_heat in enumerate(heat_by_channel):
  250. missing = bool(self.missing_mask & (1 << channel))
  251. if missing:
  252. duty = 0
  253. else:
  254. duty = duties[channel]
  255. cool = 0.02 * (self.temperatures[channel] - self.ambient_q)
  256. jitter = self.rng.randint(-noise_q, noise_q) if noise_q > 0 else 0
  257. self.temperatures[channel] += coupled_heat - cool + (jitter * 0.01)
  258. self.sample_seq += 1
  259. steps.append(
  260. FakeStressStep(
  261. sample_seq=self.sample_seq,
  262. channel=channel,
  263. temp_q=0 if missing else int(round(self.temperatures[channel])),
  264. duty=0 if missing else int(max(0, min(127, duty))),
  265. missing=missing,
  266. stale=stale,
  267. noise_q=noise_q,
  268. coupled_heat_q=coupled_heat,
  269. )
  270. )
  271. return steps
  272. def step_long_scenario(self, duties: list[int]) -> list[FakeStressStep]:
  273. """Run one deterministic long-soak fake-stress epoch.
  274. The sequence is intentionally periodic instead of random-at-runtime so a
  275. failing soak round can be reproduced from sample_seq and phase.
  276. """
  277. phase_index = self.long_scenario_epoch % 8
  278. phase_names = [
  279. "ramp",
  280. "ramp",
  281. "step",
  282. "noise",
  283. "missing",
  284. "bmc_stale",
  285. "parser_garbage",
  286. "full_rate_sweep",
  287. ]
  288. phase = phase_names[phase_index]
  289. adjusted = list(duties)
  290. missing_mask = self.missing_mask
  291. stale = False
  292. noise_q = 0
  293. event_flags: list[str] = []
  294. if phase == "ramp":
  295. scale = 32 + (phase_index * 24)
  296. adjusted = [min(127, (max(0, duty) * scale) // 80) for duty in duties]
  297. elif phase == "step":
  298. adjusted = [127 if channel % 3 == 0 else 0 for channel in range(self.channel_count)]
  299. event_flags.append("host_step")
  300. elif phase == "noise":
  301. noise_q = 4
  302. event_flags.append("noise")
  303. elif phase == "missing":
  304. missing_mask |= (1 << 5) | (1 << 11) | (1 << 18)
  305. event_flags.append("missing_mask")
  306. elif phase == "bmc_stale":
  307. stale = True
  308. event_flags.append("bmc_stale")
  309. elif phase == "parser_garbage":
  310. adjusted = [127 if channel < 12 else 16 for channel in range(self.channel_count)]
  311. event_flags.append("parser_garbage")
  312. elif phase == "full_rate_sweep":
  313. adjusted = [((self.long_scenario_epoch + channel) * 23) % 128 for channel in range(self.channel_count)]
  314. event_flags.append("full_rate_sweep")
  315. original_missing_mask = self.missing_mask
  316. self.missing_mask = missing_mask
  317. try:
  318. steps = self.step(adjusted, noise_q=noise_q, stale=stale)
  319. finally:
  320. self.missing_mask = original_missing_mask
  321. self.long_scenario_epoch += 1
  322. enriched: list[FakeStressStep] = []
  323. for step in steps:
  324. flags = list(event_flags)
  325. if step.missing and "missing_mask" not in flags:
  326. flags.append("missing_mask")
  327. enriched.append(
  328. FakeStressStep(
  329. sample_seq=step.sample_seq,
  330. channel=step.channel,
  331. temp_q=step.temp_q,
  332. duty=step.duty,
  333. missing=step.missing,
  334. stale=step.stale,
  335. noise_q=step.noise_q,
  336. coupled_heat_q=step.coupled_heat_q,
  337. phase=phase,
  338. event_flags=tuple(flags),
  339. )
  340. )
  341. return enriched
  342. @dataclass(frozen=True)
  343. class HostConfigV2:
  344. enable: bool
  345. target_q: int
  346. a0: int
  347. a1: int
  348. a2: int
  349. mode: int
  350. config_seq: int
  351. watchdog_kick: bool
  352. manual_override: bool = False
  353. @dataclass(frozen=True)
  354. class SystemSafetyState:
  355. global_enable: bool
  356. fault_latched: bool
  357. fault_code: int
  358. sensor_stale: bool
  359. overtemp: bool
  360. comm_timeout: bool
  361. interlock: bool
  362. @dataclass(frozen=True)
  363. class ActuatorCommandV2:
  364. channel: int
  365. kind: str
  366. duty_or_level: int
  367. enable: bool
  368. force_off: bool
  369. reason: str
  370. fault_code: int
  371. class PwmOutputModel:
  372. """Integer PWM model shared by report generation and tests."""
  373. def __init__(self, *, sys_clk_hz: int, pwm_hz: int, duty_max: int = 127) -> None:
  374. if sys_clk_hz <= 0:
  375. raise ValueError("sys_clk_hz must be positive")
  376. if pwm_hz <= 0:
  377. raise ValueError("pwm_hz must be positive")
  378. if duty_max <= 0:
  379. raise ValueError("duty_max must be positive")
  380. self.sys_clk_hz = sys_clk_hz
  381. self.pwm_hz = pwm_hz
  382. self.duty_max = duty_max
  383. self.period_ticks = max(1, sys_clk_hz // pwm_hz)
  384. def clamp_duty(self, duty_or_level: int) -> int:
  385. return min(self.duty_max, max(0, duty_or_level))
  386. def high_ticks(self, duty_or_level: int) -> int:
  387. duty = self.clamp_duty(duty_or_level)
  388. if duty <= 0:
  389. return 0
  390. if duty >= self.duty_max:
  391. return self.period_ticks
  392. return (self.period_ticks * duty) // self.duty_max
  393. def logic_level_at(self, duty_or_level: int, tick: int) -> int:
  394. high_ticks = self.high_ticks(duty_or_level)
  395. if high_ticks <= 0:
  396. return 0
  397. if high_ticks >= self.period_ticks:
  398. return 1
  399. return 1 if (tick % self.period_ticks) < high_ticks else 0
  400. class BoardIoMapping:
  401. """Semantic board IO mapping without binding real pins."""
  402. @staticmethod
  403. def ptc_pwm_request(logic_high: int) -> int:
  404. return 1 if logic_high else 0
  405. @staticmethod
  406. def fan_pwm_drive_low(logic_high: int) -> int:
  407. return 0 if logic_high else 1
  408. class TachRpmEstimator:
  409. def __init__(self, *, pulses_per_revolution: int = 2, window_ms: int = 1000) -> None:
  410. if pulses_per_revolution <= 0:
  411. raise ValueError("pulses_per_revolution must be positive")
  412. if window_ms <= 0:
  413. raise ValueError("window_ms must be positive")
  414. self.pulses_per_revolution = pulses_per_revolution
  415. self.window_ms = window_ms
  416. def rpm_from_edges(self, edge_count: int) -> int:
  417. edges = max(0, edge_count)
  418. return (edges * 60_000) // (self.pulses_per_revolution * self.window_ms)
  419. @dataclass(frozen=True)
  420. class DebugSnapshotV2:
  421. trace_seq: int
  422. sample_seq: int
  423. source_id: int
  424. channel: int
  425. temp_q: int
  426. host_enable: bool
  427. config_seq: int
  428. pid_error_q: int
  429. pid_ctrl_q: int
  430. safety_fault_code: int
  431. safety_fault_latched: bool
  432. actuator_kind: str
  433. actuator_enable: bool
  434. actuator_force_off: bool
  435. actuator_reason: str
  436. def control_mode_name(mode: int) -> str:
  437. return {
  438. CONTROL_MODE_SAFE_OFF: "safe_off",
  439. CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL: "hysteresis_pi_experimental",
  440. CONTROL_MODE_MANUAL_LEVEL: "manual_level",
  441. CONTROL_MODE_INCREMENTAL_PID_DEFAULT: "incremental_pid_default",
  442. }.get(mode, f"unknown_{mode}")
  443. def build_channel_topology(path: Path = CONFIG_PATH) -> dict[int, ChannelTopology]:
  444. payload = load_contract_config(path)
  445. channels = payload.get("channels", {})
  446. if not isinstance(channels, dict):
  447. raise ValueError("pid contract config has invalid channels section")
  448. dimm_map = list(channels.get("default_dimm_to_channel_map", range(24)))
  449. channel_to_cpu = list(channels.get("channel_to_cpu", [0] * 24))
  450. channel_to_airflow = list(channels.get("channel_to_airflow_zone", [0] * 24))
  451. topology: dict[int, ChannelTopology] = {}
  452. for dimm_id, channel in enumerate(dimm_map):
  453. channel_int = int(channel)
  454. cpu_id = int(channel_to_cpu[channel_int]) if channel_int < len(channel_to_cpu) else -1
  455. airflow_zone = int(channel_to_airflow[channel_int]) if channel_int < len(channel_to_airflow) else -1
  456. topology[channel_int] = ChannelTopology(
  457. channel=channel_int,
  458. dimm_id=dimm_id,
  459. cpu_id=cpu_id,
  460. airflow_zone=airflow_zone,
  461. ptc_id=channel_int,
  462. )
  463. return topology
  464. @dataclass(frozen=True)
  465. class ActuatorPolicy:
  466. actuator_count: int
  467. output_kind: str
  468. out_min: int
  469. out_max: int
  470. safe_default: str
  471. notes: str
  472. @classmethod
  473. def ptc_24ch_default(cls) -> "ActuatorPolicy":
  474. config = load_contract_config()
  475. actuator = config["actuator"]
  476. if not isinstance(actuator, dict):
  477. raise ValueError("pid contract config has invalid actuator section")
  478. return cls(
  479. actuator_count=int(actuator["actuator_count"]),
  480. output_kind=str(actuator["kind"]),
  481. out_min=int(actuator["out_min"]),
  482. out_max=int(actuator["out_max"]),
  483. safe_default=str(actuator["safe_default"]),
  484. notes="24 logical PTC heater blocks from project IO notes; polarity/PWM driver remains undefined.",
  485. )
  486. @dataclass(frozen=True)
  487. class ReplayExpectation:
  488. channel: int
  489. duty_or_level: int
  490. reason: str
  491. force_off: bool
  492. @dataclass(frozen=True)
  493. class ChannelProfile:
  494. adc_zone: int
  495. base_temp_q: int
  496. gradient_q: int = 0
  497. thermal_lag_q: int = 0
  498. @dataclass(frozen=True)
  499. class HostConfigStep:
  500. effective_sample_seq: int
  501. enable: bool
  502. target_q: int
  503. a0: int
  504. a1: int
  505. a2: int
  506. mode: int = 0
  507. config_seq: int | None = None
  508. source: str = "fake_host"
  509. interface: str = "internal"
  510. command: str = "SET_CONFIG"
  511. @dataclass(frozen=True)
  512. class SensorReplayResult:
  513. sample_count: int
  514. command_count: int
  515. enabled_count: int
  516. force_off_count: int
  517. reason_counts: dict[str, int]
  518. per_channel_last_ctrl: dict[int, int]
  519. per_channel_last_reason: dict[int, str]
  520. per_channel_force_off: dict[int, bool]
  521. min_duty: int
  522. max_duty: int
  523. trace: list[dict[str, int | str | bool]]
  524. def to_dict(self) -> dict[str, object]:
  525. return {
  526. "sample_count": self.sample_count,
  527. "command_count": self.command_count,
  528. "enabled_count": self.enabled_count,
  529. "force_off_count": self.force_off_count,
  530. "reason_counts": dict(self.reason_counts),
  531. "per_channel_last_ctrl": {str(k): v for k, v in sorted(self.per_channel_last_ctrl.items())},
  532. "per_channel_last_reason": {str(k): v for k, v in sorted(self.per_channel_last_reason.items())},
  533. "per_channel_force_off": {str(k): v for k, v in sorted(self.per_channel_force_off.items())},
  534. "min_duty": self.min_duty,
  535. "max_duty": self.max_duty,
  536. "trace": self.trace,
  537. }
  538. @dataclass(frozen=True)
  539. class SourceMuxResult:
  540. sample: SensorSample | None
  541. fake_ready: bool
  542. master_ready: bool
  543. slave_ready: bool
  544. rs232_ready: bool = False
  545. rs485_ready: bool = False
  546. class BmcDimmFrameParser:
  547. """Parser model for the currently observed BMC/IPMI DIMM temperature frame."""
  548. def __init__(
  549. self,
  550. *,
  551. expected_dimm_count: int = 24,
  552. fraction_scale: int = 100,
  553. dimm_to_channel_map: dict[int, int] | None = None,
  554. ) -> None:
  555. if expected_dimm_count <= 0:
  556. raise ValueError("expected_dimm_count must be positive")
  557. if fraction_scale <= 0:
  558. raise ValueError("fraction_scale must be positive")
  559. self.expected_dimm_count = expected_dimm_count
  560. self.fraction_scale = fraction_scale
  561. self.dimm_to_channel_map = dimm_to_channel_map or {
  562. dimm_id: dimm_id for dimm_id in range(expected_dimm_count)
  563. }
  564. self.channel_topology = build_channel_topology()
  565. def parse_hex_frame(
  566. self,
  567. raw_hex: str,
  568. *,
  569. source_id: int,
  570. frame_seq: int,
  571. sample_seq_base: int,
  572. age_ms: int,
  573. stale: bool = False,
  574. ) -> BmcDimmFrameParseResult:
  575. values = self.tokenize_text_hex(raw_hex)
  576. pairs = list(zip(values[0::2], values[1::2]))
  577. if len(values) % 2 != 0:
  578. pairs = pairs[: len(pairs)]
  579. return self.parse_pairs(
  580. pairs,
  581. source_id=source_id,
  582. frame_seq=frame_seq,
  583. sample_seq_base=sample_seq_base,
  584. age_ms=age_ms,
  585. stale=stale,
  586. )
  587. @staticmethod
  588. def tokenize_text_hex(text: str) -> list[int]:
  589. """Extract loose text-hex bytes from BMC output.
  590. Accepts `NN`, `0xNN`, quotes, commas, parentheses, multiline output,
  591. and echoed shell text. Tokens wider than one byte are ignored so words
  592. like `ipmitool` do not become accidental hex bytes.
  593. """
  594. values: list[int] = []
  595. for match in re.finditer(r"(?i)(?:0x)?([0-9a-f]{2})(?![0-9a-f])", text):
  596. prefix_start = max(0, match.start() - 2)
  597. prefix = text[prefix_start:match.start()].lower()
  598. token = match.group(1)
  599. if prefix.endswith("0x") or len(token) == 2:
  600. values.append(int(token, 16))
  601. return values
  602. def parse_text_response(
  603. self,
  604. response_text: str,
  605. *,
  606. source_id: int = SOURCE_BMC_UART_TEXT,
  607. frame_seq: int,
  608. sample_seq_base: int,
  609. age_ms: int,
  610. stale: bool = False,
  611. ) -> BmcDimmFrameParseResult:
  612. values = self.tokenize_text_hex(response_text)
  613. frame_bytes = self.select_payload_window_from_text(response_text)
  614. if frame_bytes is None:
  615. return BmcDimmFrameParseResult(
  616. parser_status=PARSER_STATUS_NO_CANDIDATE,
  617. expected_dimm_count=self.expected_dimm_count,
  618. samples=[],
  619. frame_seq=frame_seq,
  620. source_id=source_id,
  621. raw_token_count=len(values),
  622. selected_window_start=-1,
  623. rejected_echo_windows=self._count_echo_windows(values),
  624. missing_mask=0,
  625. )
  626. start, payload = frame_bytes
  627. pairs = list(zip(payload[0::2], payload[1::2]))
  628. result = self.parse_pairs(
  629. pairs,
  630. source_id=source_id,
  631. frame_seq=frame_seq,
  632. sample_seq_base=sample_seq_base,
  633. age_ms=age_ms,
  634. stale=stale,
  635. raw_token_count=len(values),
  636. selected_window_start=start,
  637. rejected_echo_windows=self._count_echo_windows(values),
  638. )
  639. return result
  640. def select_payload_window_from_text(self, text: str) -> tuple[int, list[int]] | None:
  641. expected_len = self.expected_dimm_count * 2
  642. for block_start, block_values in self._payload_token_blocks(text):
  643. for start in range(0, max(0, len(block_values) - expected_len + 1)):
  644. window = block_values[start:start + expected_len]
  645. if len(window) != expected_len:
  646. continue
  647. if self._looks_like_echo_window(window):
  648. continue
  649. if self._valid_payload_window(window):
  650. return block_start + start, window
  651. return None
  652. def _payload_token_blocks(self, text: str) -> list[tuple[int, list[int]]]:
  653. blocks: list[tuple[int, list[int]]] = []
  654. current: list[int] = []
  655. current_start = 0
  656. token_cursor = 0
  657. for line in text.splitlines():
  658. line_tokens = self.tokenize_text_hex(line)
  659. if self._looks_like_payload_hex_line(line, line_tokens):
  660. if not current:
  661. current_start = token_cursor
  662. current.extend(line_tokens)
  663. elif current:
  664. blocks.append((current_start, current))
  665. current = []
  666. token_cursor += len(line_tokens)
  667. if current:
  668. blocks.append((current_start, current))
  669. return blocks
  670. @staticmethod
  671. def _looks_like_payload_hex_line(line: str, tokens: list[int]) -> bool:
  672. if not tokens:
  673. return False
  674. without_tokens = re.sub(r"(?i)(?:0x)?[0-9a-f]{2}(?![0-9a-f])", "", line).strip()
  675. return without_tokens == "" or re.fullmatch(r"""[\s,;:()\[\]{}"'`]+""", without_tokens) is not None
  676. def select_payload_window(self, values: list[int]) -> tuple[int, list[int]] | None:
  677. expected_len = self.expected_dimm_count * 2
  678. echo_spans = self._command_token_spans(values)
  679. for start in range(0, max(0, len(values) - expected_len + 1)):
  680. window = values[start:start + expected_len]
  681. if len(window) != expected_len:
  682. continue
  683. if self._overlaps_echo_span(start, expected_len, echo_spans):
  684. continue
  685. if self._looks_like_echo_window(window):
  686. continue
  687. if self._valid_payload_window(window):
  688. return start, window
  689. return None
  690. def _valid_payload_window(self, values: list[int]) -> bool:
  691. if len(values) != self.expected_dimm_count * 2:
  692. return False
  693. present_count = 0
  694. for integer_byte, fraction_byte in zip(values[0::2], values[1::2]):
  695. if integer_byte == 0xFF and fraction_byte == 0xFF:
  696. continue
  697. if fraction_byte >= self.fraction_scale:
  698. return False
  699. present_count += 1
  700. return present_count > 0
  701. @staticmethod
  702. def _looks_like_echo_window(values: list[int]) -> bool:
  703. command = BMC_POLL_COMMAND_BYTES
  704. for index in range(0, len(values) - len(command) + 1):
  705. if values[index:index + len(command)] == command:
  706. return True
  707. return False
  708. def _count_echo_windows(self, values: list[int]) -> int:
  709. expected_len = self.expected_dimm_count * 2
  710. count = 0
  711. for start in range(0, max(0, len(values) - expected_len + 1)):
  712. if self._looks_like_echo_window(values[start:start + expected_len]):
  713. count += 1
  714. return count
  715. @staticmethod
  716. def _command_token_spans(values: list[int]) -> list[tuple[int, int]]:
  717. command = BMC_POLL_COMMAND_BYTES
  718. spans: list[tuple[int, int]] = []
  719. for index in range(0, len(values) - len(command) + 1):
  720. if values[index:index + len(command)] == command:
  721. spans.append((index, index + len(command)))
  722. return spans
  723. @staticmethod
  724. def _overlaps_echo_span(start: int, length: int, spans: list[tuple[int, int]]) -> bool:
  725. end = start + length
  726. return any(start < span_end and end > span_start for span_start, span_end in spans)
  727. def parse_pairs(
  728. self,
  729. pairs: list[tuple[int, int]],
  730. *,
  731. source_id: int,
  732. frame_seq: int,
  733. sample_seq_base: int,
  734. age_ms: int,
  735. stale: bool = False,
  736. raw_token_count: int = 0,
  737. selected_window_start: int = 0,
  738. rejected_echo_windows: int = 0,
  739. ) -> BmcDimmFrameParseResult:
  740. parser_status = PARSER_STATUS_OK if len(pairs) == self.expected_dimm_count else PARSER_STATUS_BAD_LENGTH
  741. if parser_status == PARSER_STATUS_OK:
  742. for integer_byte, fraction_byte in pairs:
  743. if not (integer_byte == 0xFF and fraction_byte == 0xFF) and fraction_byte >= self.fraction_scale:
  744. parser_status = PARSER_STATUS_BAD_FRACTION
  745. break
  746. samples: list[DimmTempSampleV1] = []
  747. missing_mask = 0
  748. for index, (integer_byte, fraction_byte) in enumerate(pairs):
  749. if not 0 <= integer_byte <= 0xFF or not 0 <= fraction_byte <= 0xFF:
  750. raise ValueError("BMC DIMM byte values must be in range 0..255")
  751. missing = integer_byte == 0xFF and fraction_byte == 0xFF
  752. if missing:
  753. missing_mask |= 1 << index
  754. raw_status = RAW_STATUS_OK
  755. if missing:
  756. raw_status |= RAW_STATUS_MISSING_DIMM
  757. if parser_status != PARSER_STATUS_OK:
  758. raw_status |= RAW_STATUS_PARSER_ERROR
  759. if stale:
  760. raw_status |= RAW_STATUS_STALE
  761. temp_c_x100 = 0 if missing else (integer_byte * 100) + ((fraction_byte * 100) // self.fraction_scale)
  762. temp_q = 0 if missing else (temp_c_x100 + 50) // 100
  763. fault = missing or parser_status != PARSER_STATUS_OK
  764. dimm_id = index
  765. channel = self.dimm_to_channel_map.get(dimm_id, dimm_id)
  766. topology = self.channel_topology.get(channel, ChannelTopology(channel, dimm_id, -1, -1, channel))
  767. samples.append(
  768. DimmTempSampleV1(
  769. valid=True,
  770. ready=True,
  771. source_id=source_id,
  772. frame_seq=frame_seq,
  773. sample_seq=sample_seq_base + index,
  774. raw_pair_index=index,
  775. dimm_id=dimm_id,
  776. channel=channel,
  777. raw_integer_byte=integer_byte,
  778. raw_fraction_byte=fraction_byte,
  779. fraction_scale=self.fraction_scale,
  780. temp_q=temp_q,
  781. temp_c_x100=temp_c_x100,
  782. missing=missing,
  783. fault=fault,
  784. stale=stale,
  785. age_ms=age_ms,
  786. raw_status=raw_status,
  787. parser_status=parser_status,
  788. present=not missing,
  789. cpu_id=topology.cpu_id,
  790. airflow_zone=topology.airflow_zone,
  791. )
  792. )
  793. return BmcDimmFrameParseResult(
  794. parser_status=parser_status,
  795. expected_dimm_count=self.expected_dimm_count,
  796. samples=samples,
  797. frame_seq=frame_seq,
  798. source_id=source_id,
  799. raw_token_count=raw_token_count,
  800. selected_window_start=selected_window_start,
  801. rejected_echo_windows=rejected_echo_windows,
  802. missing_mask=missing_mask,
  803. )
  804. def dimm_sample_to_sensor_sample_v2(sample: DimmTempSampleV1) -> SensorSampleV2:
  805. return SensorSampleV2(
  806. valid=sample.valid,
  807. ready=sample.ready,
  808. source_id=sample.source_id,
  809. channel=sample.channel,
  810. temp_q=sample.temp_q,
  811. fault=sample.fault or sample.missing,
  812. stale=sample.stale,
  813. sample_seq=sample.sample_seq,
  814. raw_status=sample.raw_status,
  815. )
  816. class SensorSourceMux:
  817. def __init__(self, source_select: int = SOURCE_FAKE) -> None:
  818. self.source_select = source_select
  819. def select(
  820. self,
  821. *,
  822. fake: SensorSample | None,
  823. master: SensorSample | None,
  824. slave: SensorSample | None,
  825. rs232: SensorSample | None = None,
  826. rs485: SensorSample | None = None,
  827. sensor_ready: bool,
  828. ) -> SourceMuxResult:
  829. fake_ready = sensor_ready and self.source_select == SOURCE_FAKE
  830. master_ready = sensor_ready and self.source_select == SOURCE_I2C_MASTER
  831. slave_ready = sensor_ready and self.source_select == SOURCE_I2C_SLAVE_INJECT
  832. rs232_ready = sensor_ready and self.source_select == SOURCE_RS232_UART_INJECT
  833. rs485_ready = sensor_ready and self.source_select == SOURCE_RS485_INJECT
  834. selected = None
  835. if self.source_select == SOURCE_FAKE:
  836. selected = fake
  837. elif self.source_select == SOURCE_I2C_MASTER:
  838. selected = master
  839. elif self.source_select == SOURCE_I2C_SLAVE_INJECT:
  840. selected = slave
  841. elif self.source_select == SOURCE_RS232_UART_INJECT:
  842. selected = rs232
  843. elif self.source_select == SOURCE_RS485_INJECT:
  844. selected = rs485
  845. return SourceMuxResult(
  846. sample=selected if selected is not None and selected.valid else None,
  847. fake_ready=fake_ready,
  848. master_ready=master_ready,
  849. slave_ready=slave_ready,
  850. rs232_ready=rs232_ready,
  851. rs485_ready=rs485_ready,
  852. )
  853. class SafetySupervisor:
  854. """Contract-level safety gate for all actuator domains.
  855. This model intentionally consumes only standard contracts. It does not know
  856. I2C addresses, host packets, board pins, or actuator polarity.
  857. """
  858. def __init__(
  859. self,
  860. channel_count: int = 24,
  861. overtemp_limit_q: int = 90,
  862. host_timeout_samples: int = 10,
  863. ) -> None:
  864. self.channel_count = channel_count
  865. self.overtemp_limit_q = overtemp_limit_q
  866. self.host_timeout_samples = host_timeout_samples
  867. self._watchdog_age = 0
  868. self._fault_latched = False
  869. self._fault_code = FAULT_CODE_OK
  870. def clear_fault_latch(self) -> None:
  871. self._fault_latched = False
  872. self._fault_code = FAULT_CODE_OK
  873. self._watchdog_age = 0
  874. def evaluate(
  875. self,
  876. sample: SensorSampleV2,
  877. config: HostConfigV2,
  878. *,
  879. interlock: bool = False,
  880. ) -> SystemSafetyState:
  881. if config.watchdog_kick:
  882. self._watchdog_age = 0
  883. else:
  884. self._watchdog_age += 1
  885. invalid_channel = sample.channel < 0 or sample.channel >= self.channel_count
  886. sensor_fault = sample.fault or invalid_channel
  887. sensor_stale = sample.stale
  888. overtemp = sample.valid and not invalid_channel and sample.temp_q >= self.overtemp_limit_q
  889. comm_timeout = self._watchdog_age > self.host_timeout_samples
  890. fault_code = FAULT_CODE_OK
  891. if interlock:
  892. fault_code = FAULT_CODE_INTERLOCK
  893. elif overtemp:
  894. fault_code = FAULT_CODE_OVERTEMP
  895. elif invalid_channel:
  896. fault_code = FAULT_CODE_INVALID_CHANNEL
  897. elif sensor_fault:
  898. fault_code = FAULT_CODE_SENSOR_FAULT
  899. elif sensor_stale:
  900. fault_code = FAULT_CODE_SENSOR_STALE
  901. elif comm_timeout:
  902. fault_code = FAULT_CODE_HOST_TIMEOUT
  903. elif not config.enable:
  904. fault_code = FAULT_CODE_HOST_DISABLED
  905. if fault_code in {
  906. FAULT_CODE_HOST_TIMEOUT,
  907. FAULT_CODE_OVERTEMP,
  908. FAULT_CODE_INTERLOCK,
  909. }:
  910. self._fault_latched = True
  911. self._fault_code = fault_code
  912. active_code = self._fault_code if self._fault_latched else fault_code
  913. global_enable = config.enable and active_code == FAULT_CODE_OK
  914. return SystemSafetyState(
  915. global_enable=global_enable,
  916. fault_latched=self._fault_latched,
  917. fault_code=active_code,
  918. sensor_stale=sensor_stale,
  919. overtemp=overtemp,
  920. comm_timeout=comm_timeout,
  921. interlock=interlock,
  922. )
  923. class ActuatorDomain:
  924. """Routes abstract PID output into safe abstract actuator commands."""
  925. def __init__(
  926. self,
  927. channel_count: int = 24,
  928. out_min: int = 0,
  929. out_max: int = 127,
  930. fan_background_level: int = 38,
  931. fan_fallback_level: int = 127,
  932. ) -> None:
  933. self.channel_count = channel_count
  934. self.out_min = out_min
  935. self.out_max = out_max
  936. self.fan_background_level = fan_background_level
  937. self.fan_fallback_level = fan_fallback_level
  938. def route_ptc(self, result: PidResult, safety: SystemSafetyState) -> ActuatorCommandV2:
  939. if result.channel < 0 or result.channel >= self.channel_count:
  940. return self._force_off(result.channel, ACTUATOR_KIND_PTC, FAULT_CODE_INVALID_CHANNEL)
  941. if not safety.global_enable:
  942. return self._force_off(result.channel, ACTUATOR_KIND_PTC, safety.fault_code)
  943. if result.fault or not result.valid:
  944. return self._force_off(result.channel, ACTUATOR_KIND_PTC, FAULT_CODE_SENSOR_FAULT)
  945. duty = min(self.out_max, max(self.out_min, result.ctrl_q))
  946. return ActuatorCommandV2(
  947. channel=result.channel,
  948. kind=ACTUATOR_KIND_PTC,
  949. duty_or_level=duty,
  950. enable=True,
  951. force_off=False,
  952. reason=ACTUATOR_REASON_OK,
  953. fault_code=FAULT_CODE_OK,
  954. )
  955. def route_fan(self, channel: int, safety: SystemSafetyState) -> ActuatorCommandV2:
  956. if safety.fault_code in {
  957. FAULT_CODE_SENSOR_FAULT,
  958. FAULT_CODE_SENSOR_STALE,
  959. FAULT_CODE_HOST_TIMEOUT,
  960. FAULT_CODE_OVERTEMP,
  961. }:
  962. return ActuatorCommandV2(
  963. channel=channel,
  964. kind=ACTUATOR_KIND_FAN,
  965. duty_or_level=self.fan_fallback_level,
  966. enable=True,
  967. force_off=False,
  968. reason=ACTUATOR_REASON_FAN_FALLBACK,
  969. fault_code=safety.fault_code,
  970. )
  971. return ActuatorCommandV2(
  972. channel=channel,
  973. kind=ACTUATOR_KIND_FAN,
  974. duty_or_level=self.fan_background_level,
  975. enable=True,
  976. force_off=False,
  977. reason=ACTUATOR_REASON_OK,
  978. fault_code=FAULT_CODE_OK,
  979. )
  980. def route_motor(
  981. self,
  982. *,
  983. open_request: bool,
  984. close_request: bool,
  985. open_limit: bool,
  986. close_limit: bool,
  987. safety: SystemSafetyState,
  988. ) -> ActuatorCommandV2:
  989. if not safety.global_enable or safety.interlock:
  990. return self._force_off(0, ACTUATOR_KIND_MOTOR, safety.fault_code or FAULT_CODE_INTERLOCK)
  991. if open_request and not open_limit and not close_request:
  992. return ActuatorCommandV2(0, ACTUATOR_KIND_MOTOR, 1, True, False, ACTUATOR_REASON_OK, FAULT_CODE_OK)
  993. if close_request and not close_limit and not open_request:
  994. return ActuatorCommandV2(0, ACTUATOR_KIND_MOTOR, 2, True, False, ACTUATOR_REASON_OK, FAULT_CODE_OK)
  995. return ActuatorCommandV2(0, ACTUATOR_KIND_MOTOR, 0, False, False, ACTUATOR_REASON_OK, FAULT_CODE_OK)
  996. def _force_off(self, channel: int, kind: str, fault_code: int) -> ActuatorCommandV2:
  997. return ActuatorCommandV2(
  998. channel=channel,
  999. kind=kind,
  1000. duty_or_level=0,
  1001. enable=False,
  1002. force_off=True,
  1003. reason=fault_code_to_reason(fault_code),
  1004. fault_code=fault_code,
  1005. )
  1006. class DebugTraceRecorder:
  1007. def __init__(self) -> None:
  1008. self.trace_seq = 0
  1009. def capture(
  1010. self,
  1011. *,
  1012. sample: SensorSampleV2,
  1013. config: HostConfigV2,
  1014. pid_result: PidResult,
  1015. safety: SystemSafetyState,
  1016. actuator: ActuatorCommandV2,
  1017. ) -> DebugSnapshotV2:
  1018. self.trace_seq += 1
  1019. return DebugSnapshotV2(
  1020. trace_seq=self.trace_seq,
  1021. sample_seq=sample.sample_seq,
  1022. source_id=sample.source_id,
  1023. channel=sample.channel,
  1024. temp_q=sample.temp_q,
  1025. host_enable=config.enable,
  1026. config_seq=config.config_seq,
  1027. pid_error_q=pid_result.error_q,
  1028. pid_ctrl_q=pid_result.ctrl_q,
  1029. safety_fault_code=safety.fault_code,
  1030. safety_fault_latched=safety.fault_latched,
  1031. actuator_kind=actuator.kind,
  1032. actuator_enable=actuator.enable,
  1033. actuator_force_off=actuator.force_off,
  1034. actuator_reason=actuator.reason,
  1035. )
  1036. def fault_code_to_reason(fault_code: int) -> str:
  1037. return {
  1038. FAULT_CODE_OK: ACTUATOR_REASON_OK,
  1039. FAULT_CODE_HOST_DISABLED: ACTUATOR_REASON_HOST_DISABLED,
  1040. FAULT_CODE_SENSOR_FAULT: ACTUATOR_REASON_PID_OR_SENSOR_FAULT,
  1041. FAULT_CODE_SENSOR_STALE: ACTUATOR_REASON_SENSOR_STALE,
  1042. FAULT_CODE_HOST_TIMEOUT: ACTUATOR_REASON_HOST_TIMEOUT,
  1043. FAULT_CODE_OVERTEMP: ACTUATOR_REASON_OVERTEMP,
  1044. FAULT_CODE_INVALID_CHANNEL: ACTUATOR_REASON_CHANNEL_INVALID,
  1045. FAULT_CODE_INTERLOCK: ACTUATOR_REASON_INTERLOCK,
  1046. }.get(fault_code, ACTUATOR_REASON_PID_OR_SENSOR_FAULT)
  1047. class FakeSensorSample:
  1048. def __init__(
  1049. self,
  1050. base_temp_q: int | None = None,
  1051. step_q: int | None = None,
  1052. channel_count: int = 24,
  1053. channel_profiles: list[ChannelProfile] | None = None,
  1054. step_events: dict[int, int] | None = None,
  1055. fault_events: dict[int, list[int]] | None = None,
  1056. ) -> None:
  1057. if channel_profiles is None:
  1058. if base_temp_q is None or step_q is None:
  1059. raise ValueError("base_temp_q and step_q are required when channel_profiles is not provided")
  1060. channel_profiles = [
  1061. ChannelProfile(
  1062. adc_zone=min(3, (channel * 4) // max(1, channel_count)),
  1063. base_temp_q=base_temp_q + (channel * step_q),
  1064. )
  1065. for channel in range(channel_count)
  1066. ]
  1067. if not channel_profiles:
  1068. raise ValueError("channel_profiles must not be empty")
  1069. self.channel_profiles = channel_profiles
  1070. self.channel_count = len(channel_profiles)
  1071. self.step_events = step_events or {}
  1072. self.fault_events = fault_events or {}
  1073. self.index = 0
  1074. self.sample_seq = 0
  1075. self.accumulated_step_q = 0
  1076. @classmethod
  1077. def from_adc_zones(cls, zone_profiles: list[ChannelProfile], channels_per_zone: int = 6) -> "FakeSensorSample":
  1078. channel_profiles: list[ChannelProfile] = []
  1079. for zone in zone_profiles:
  1080. for offset in range(channels_per_zone):
  1081. channel_profiles.append(
  1082. ChannelProfile(
  1083. adc_zone=zone.adc_zone,
  1084. base_temp_q=zone.base_temp_q + (offset * zone.gradient_q),
  1085. gradient_q=0,
  1086. thermal_lag_q=zone.thermal_lag_q,
  1087. )
  1088. )
  1089. return cls(channel_profiles=channel_profiles)
  1090. def next_sample(self) -> SensorSample:
  1091. channel = self.index % self.channel_count
  1092. self.sample_seq += 1
  1093. self.accumulated_step_q += self.step_events.get(self.sample_seq, 0)
  1094. profile = self.channel_profiles[channel]
  1095. temp = profile.base_temp_q + self.accumulated_step_q - profile.thermal_lag_q
  1096. fault_channels = self.fault_events.get(self.sample_seq, [])
  1097. fault = channel in fault_channels
  1098. self.index += 1
  1099. return SensorSample(
  1100. valid=True,
  1101. fault=fault,
  1102. channel=channel,
  1103. temp_q=temp,
  1104. sample_seq=self.sample_seq,
  1105. source_id=SOURCE_FAKE,
  1106. )
  1107. class I2CMasterSensorProfileAdapter:
  1108. """Offline model for the v1 virtual I2C sensor register profile."""
  1109. def __init__(self, channel_count: int = 24, channels_per_zone: int = 6) -> None:
  1110. self.channel_count = channel_count
  1111. self.channels_per_zone = channels_per_zone
  1112. self.next_channel = 0
  1113. self.sample_seq = 0
  1114. self._pending: SensorSample | None = None
  1115. def _profile_temp(self, channel: int) -> int:
  1116. zone = channel // self.channels_per_zone
  1117. offset = channel % self.channels_per_zone
  1118. if zone == 0:
  1119. return 70 + offset
  1120. if zone == 1:
  1121. return 78 + (offset * 2)
  1122. if zone == 2:
  1123. return 86 + (offset * 3)
  1124. return 94 + (offset * 4)
  1125. def next_sample(self, sensor_ready: bool) -> SensorSample:
  1126. if self._pending is None:
  1127. channel = self.next_channel
  1128. self.sample_seq += 1
  1129. self._pending = SensorSample(
  1130. valid=True,
  1131. fault=False,
  1132. channel=channel,
  1133. temp_q=self._profile_temp(channel),
  1134. sample_seq=self.sample_seq,
  1135. source_id=SOURCE_I2C_MASTER,
  1136. )
  1137. self.next_channel = (self.next_channel + 1) % self.channel_count
  1138. pending = self._pending
  1139. if sensor_ready:
  1140. self._pending = None
  1141. return pending
  1142. class PidControlRegFile:
  1143. """V1 byte register map model for the I2C slave control/status plane."""
  1144. REG_MAGIC = 0x00
  1145. REG_VERSION = 0x01
  1146. REG_CONTROL = 0x02
  1147. REG_SOURCE_SELECT = 0x03
  1148. REG_COMMAND = 0x04
  1149. REG_STATUS = 0x05
  1150. def __init__(self) -> None:
  1151. self._regs = [0] * 256
  1152. self._regs[self.REG_MAGIC] = 0x50
  1153. self._regs[self.REG_VERSION] = 0x01
  1154. self._regs[self.REG_CONTROL] = 0x01
  1155. self._regs[self.REG_SOURCE_SELECT] = SOURCE_FAKE
  1156. self._host_config = HostConfig(True, 100, 6, -2, 1, 0, 1)
  1157. self._host_config_seq = 1
  1158. self._slave_sample_seq = 0
  1159. self._sample_pending = False
  1160. self._clear_fault_latch_pending = False
  1161. self._clear_history_all_pending = False
  1162. self._write_host_shadow(self._host_config)
  1163. @property
  1164. def host_config(self) -> HostConfig:
  1165. system_enable = bool(self._regs[self.REG_CONTROL] & 0x01)
  1166. return HostConfig(
  1167. enable=system_enable and self._host_config.enable,
  1168. target_q=self._host_config.target_q,
  1169. a0=self._host_config.a0,
  1170. a1=self._host_config.a1,
  1171. a2=self._host_config.a2,
  1172. mode=self._host_config.mode,
  1173. config_seq=self._host_config.config_seq,
  1174. )
  1175. @property
  1176. def source_select(self) -> int:
  1177. return self._regs[self.REG_SOURCE_SELECT] & 0x03
  1178. def _write_host_shadow(self, config: HostConfig) -> None:
  1179. self._regs[0x10] = 1 if config.enable else 0
  1180. self._regs[0x11] = config.mode & 0x03
  1181. self.write_int18(0x12, config.target_q)
  1182. self.write_int18(0x15, config.a0)
  1183. self.write_int18(0x18, config.a1)
  1184. self.write_int18(0x1B, config.a2)
  1185. @staticmethod
  1186. def _encode_int18(value: int) -> int:
  1187. return value & 0x3FFFF
  1188. @staticmethod
  1189. def _decode_int18(raw: int) -> int:
  1190. raw &= 0x3FFFF
  1191. return raw - (1 << 18) if raw & (1 << 17) else raw
  1192. def write_int18(self, base: int, value: int) -> None:
  1193. raw = self._encode_int18(value)
  1194. self._regs[base] = raw & 0xFF
  1195. self._regs[base + 1] = (raw >> 8) & 0xFF
  1196. self._regs[base + 2] = (raw >> 16) & 0x03
  1197. def read_int18(self, base: int) -> int:
  1198. raw = self._regs[base] | (self._regs[base + 1] << 8) | ((self._regs[base + 2] & 0x03) << 16)
  1199. return self._decode_int18(raw)
  1200. def read(self, addr: int) -> int:
  1201. return self._regs[addr & 0xFF] & 0xFF
  1202. def write(self, addr: int, value: int) -> None:
  1203. addr &= 0xFF
  1204. value &= 0xFF
  1205. if addr in {self.REG_MAGIC, self.REG_VERSION}:
  1206. return
  1207. if addr == self.REG_CONTROL:
  1208. self._regs[addr] = value & 0x01
  1209. if value & 0x02:
  1210. self._clear_fault_latch_pending = True
  1211. if value & 0x04:
  1212. self._clear_history_all_pending = True
  1213. return
  1214. if addr == self.REG_SOURCE_SELECT:
  1215. self._regs[addr] = value & 0x03
  1216. return
  1217. if addr == self.REG_COMMAND:
  1218. if value & 0x01:
  1219. self._commit_host_config()
  1220. if value & 0x02:
  1221. self._commit_slave_sample()
  1222. return
  1223. self._regs[addr] = value
  1224. def _commit_host_config(self) -> None:
  1225. self._host_config_seq += 1
  1226. self._host_config = HostConfig(
  1227. enable=bool(self._regs[0x10] & 0x01),
  1228. target_q=self.read_int18(0x12),
  1229. a0=self.read_int18(0x15),
  1230. a1=self.read_int18(0x18),
  1231. a2=self.read_int18(0x1B),
  1232. mode=self._regs[0x11] & 0x03,
  1233. config_seq=self._host_config_seq,
  1234. )
  1235. def _commit_slave_sample(self) -> None:
  1236. self._sample_pending = True
  1237. self._regs[self.REG_STATUS] |= 0x10
  1238. def consume_clear_fault_latch(self) -> bool:
  1239. pending = self._clear_fault_latch_pending
  1240. self._clear_fault_latch_pending = False
  1241. return pending
  1242. def consume_clear_history_all(self) -> bool:
  1243. pending = self._clear_history_all_pending
  1244. self._clear_history_all_pending = False
  1245. return pending
  1246. def take_slave_sample(self, sensor_ready: bool) -> SensorSample | None:
  1247. if not sensor_ready or not self._sample_pending or self.source_select != SOURCE_I2C_SLAVE_INJECT:
  1248. return None
  1249. self._sample_pending = False
  1250. self._regs[self.REG_STATUS] &= ~0x10
  1251. self._slave_sample_seq += 1
  1252. return SensorSample(
  1253. valid=True,
  1254. fault=bool(self._regs[0x21] & 0x01),
  1255. channel=self._regs[0x20] & 0x1F,
  1256. temp_q=self.read_int18(0x22),
  1257. sample_seq=self._slave_sample_seq,
  1258. source_id=SOURCE_I2C_SLAVE_INJECT,
  1259. )
  1260. def capture_status(
  1261. self,
  1262. *,
  1263. sensor_ready: bool,
  1264. pid_busy: bool,
  1265. master_fault: bool,
  1266. slave_fault: bool,
  1267. sample: SensorSample,
  1268. pid_result: PidResult,
  1269. actuator: ActuatorCommand,
  1270. ) -> None:
  1271. status = 0
  1272. status |= 0x01 if pid_busy else 0
  1273. status |= 0x02 if sensor_ready else 0
  1274. status |= 0x04 if pid_result.fault else 0
  1275. status |= 0x08 if actuator.force_off else 0
  1276. status |= 0x10 if self._sample_pending else 0
  1277. status |= 0x20 if master_fault else 0
  1278. status |= 0x40 if slave_fault else 0
  1279. self._regs[self.REG_STATUS] = status
  1280. self._regs[0x30] = pid_result.channel & 0x1F
  1281. self._regs[0x31] = (
  1282. (1 if pid_result.valid else 0)
  1283. | ((1 if pid_result.done else 0) << 1)
  1284. | ((1 if pid_result.fault else 0) << 2)
  1285. | ((1 if pid_result.clamped else 0) << 3)
  1286. | ((1 if pid_result.history_cleared else 0) << 4)
  1287. )
  1288. self._regs[0x32] = pid_result.sample_seq & 0xFF
  1289. self._regs[0x33] = (pid_result.sample_seq >> 8) & 0xFF
  1290. self.write_int18(0x36, pid_result.error_q)
  1291. self.write_int18(0x39, pid_result.ctrl_q)
  1292. self._regs[0x40] = actuator.channel & 0x1F
  1293. self._regs[0x41] = (
  1294. (1 if actuator.enable else 0)
  1295. | ((1 if actuator.force_off else 0) << 1)
  1296. | ((self._reason_code(actuator.reason) & 0x03) << 2)
  1297. )
  1298. self.write_int18(0x42, actuator.duty_or_level)
  1299. trace_seq = (self._regs[0x60] | (self._regs[0x61] << 8)) + 1
  1300. self._regs[0x60] = trace_seq & 0xFF
  1301. self._regs[0x61] = (trace_seq >> 8) & 0xFF
  1302. self._regs[0x64] = sample.source_id & 0x03
  1303. self._regs[0x65] = 3 if pid_result.done else 0
  1304. self._regs[0x66] = 2 if pid_busy else 0
  1305. self._regs[0x68] = sample.sample_seq & 0xFF
  1306. self._regs[0x69] = (sample.sample_seq >> 8) & 0xFF
  1307. self._regs[0x6A] = self.host_config.config_seq & 0xFF
  1308. self._regs[0x6B] = (self.host_config.config_seq >> 8) & 0xFF
  1309. self._regs[0x6C] = sample.channel & 0x1F
  1310. self._regs[0x6D] = (
  1311. (1 if pid_result.clamped else 0)
  1312. | ((1 if pid_result.history_cleared else 0) << 1)
  1313. | ((1 if pid_result.fault else 0) << 2)
  1314. | ((1 if actuator.force_off else 0) << 3)
  1315. )
  1316. @staticmethod
  1317. def _reason_code(reason: str) -> int:
  1318. return {
  1319. ACTUATOR_REASON_OK: 0,
  1320. ACTUATOR_REASON_HOST_DISABLED: 1,
  1321. ACTUATOR_REASON_PID_OR_SENSOR_FAULT: 2,
  1322. ACTUATOR_REASON_CHANNEL_INVALID: 3,
  1323. }[reason]
  1324. class FakeHostConfig:
  1325. def __init__(
  1326. self,
  1327. enable: bool,
  1328. target_q: int,
  1329. a0: int = 6,
  1330. a1: int = -2,
  1331. a2: int = 1,
  1332. mode: int = 0,
  1333. steps: list[HostConfigStep] | None = None,
  1334. ) -> None:
  1335. self.base_config = HostConfig(
  1336. enable=enable,
  1337. target_q=target_q,
  1338. a0=a0,
  1339. a1=a1,
  1340. a2=a2,
  1341. mode=mode,
  1342. config_seq=1,
  1343. )
  1344. self.steps = sorted(steps or [], key=lambda step: step.effective_sample_seq)
  1345. def current(self, sample_seq: int | None = None) -> HostConfig:
  1346. if sample_seq is None:
  1347. return self.base_config
  1348. config = self.base_config
  1349. for index, step in enumerate(self.steps, start=2):
  1350. if sample_seq < step.effective_sample_seq:
  1351. break
  1352. config = HostConfig(
  1353. enable=step.enable,
  1354. target_q=step.target_q,
  1355. a0=step.a0,
  1356. a1=step.a1,
  1357. a2=step.a2,
  1358. mode=step.mode,
  1359. config_seq=step.config_seq if step.config_seq is not None else index,
  1360. )
  1361. return config
  1362. def load_contract_config(path: Path = CONFIG_PATH) -> dict[str, object]:
  1363. with path.open("r", encoding="utf-8") as handle:
  1364. return json.load(handle)
  1365. def config_contract_summary(path: Path = CONFIG_PATH) -> dict[str, int | str | bool]:
  1366. payload = load_contract_config(path)
  1367. channels = payload["channels"]
  1368. host = payload["default_host_config"]
  1369. actuator = payload["actuator"]
  1370. pwm_outputs = payload.get("pwm_outputs", {})
  1371. control = payload.get("control", {})
  1372. safety = payload.get("safety", {})
  1373. topology = payload.get("physical_topology", {})
  1374. bmc_uart = payload.get("bmc_uart_poll", {})
  1375. fan_pwm = pwm_outputs.get("fan", {}) if isinstance(pwm_outputs, dict) else {}
  1376. ptc_pwm = pwm_outputs.get("ptc", {}) if isinstance(pwm_outputs, dict) else {}
  1377. if not isinstance(channels, dict) or not isinstance(host, dict) or not isinstance(actuator, dict):
  1378. raise ValueError("pid contract config has invalid top-level sections")
  1379. airflow_zone_count = int(channels.get("airflow_zone_count", channels.get("adc_zone_count", 0)))
  1380. channels_per_airflow = channels.get("channels_per_airflow_zone", channels.get("channels_per_adc_zone", 0))
  1381. if isinstance(channels_per_airflow, list):
  1382. channels_per_airflow_text = "/".join(str(int(item)) for item in channels_per_airflow)
  1383. first_zone_count = int(channels_per_airflow[0]) if channels_per_airflow else 0
  1384. else:
  1385. channels_per_airflow_text = str(channels_per_airflow)
  1386. first_zone_count = int(channels_per_airflow)
  1387. fan_policy = payload.get("fan_policy", {})
  1388. return {
  1389. "logical_channel_count": int(channels["logical_channel_count"]),
  1390. "adc_zone_count": airflow_zone_count,
  1391. "channels_per_adc_zone": first_zone_count,
  1392. "airflow_zone_count": airflow_zone_count,
  1393. "channels_per_airflow_zone": channels_per_airflow_text,
  1394. "channel_to_cpu": ",".join(str(int(item)) for item in channels.get("channel_to_cpu", [])),
  1395. "channel_to_airflow_zone": ",".join(str(int(item)) for item in channels.get("channel_to_airflow_zone", [])),
  1396. "fan_count": int(fan_pwm.get("fan_count", fan_policy.get("fan_count", 6))) if isinstance(fan_pwm, dict) else 6,
  1397. "default_enable": bool(host["enable"]),
  1398. "default_target_q": int(host["target_q"]),
  1399. "default_a0": int(host["a0"]),
  1400. "default_a1": int(host["a1"]),
  1401. "default_a2": int(host["a2"]),
  1402. "actuator_kind": str(actuator["kind"]),
  1403. "actuator_out_min": int(actuator["out_min"]),
  1404. "actuator_out_max": int(actuator["out_max"]),
  1405. "default_control_mode": str(control.get("default_mode", "incremental_pid_default"))
  1406. if isinstance(control, dict)
  1407. else "incremental_pid_default",
  1408. "default_tolerance_q": int(control.get("target_tolerance_q", 5)) if isinstance(control, dict) else 5,
  1409. "default_stale_timeout_cycles": int(safety.get("stale_timeout_cycles", 10)) if isinstance(safety, dict) else 10,
  1410. "overtemp_limit_q": int(safety.get("overtemp_limit_q", 90)) if isinstance(safety, dict) else 90,
  1411. "first_real_pid_duty_limit_percent": int(control.get("first_real_pid_duty_limit_percent", 25))
  1412. if isinstance(control, dict)
  1413. else 25,
  1414. "bmc_poll_command_ascii": str(bmc_uart.get("command_ascii", BMC_POLL_COMMAND_ASCII))
  1415. if isinstance(bmc_uart, dict)
  1416. else BMC_POLL_COMMAND_ASCII,
  1417. "bmc_uart": str(bmc_uart.get("uart", "115200 8N1")) if isinstance(bmc_uart, dict) else "115200 8N1",
  1418. "mapping_policy": str(topology.get("mapping_policy", "bmc_order_equals_physical_order_equals_ptc_channel_order"))
  1419. if isinstance(topology, dict)
  1420. else "bmc_order_equals_physical_order_equals_ptc_channel_order",
  1421. "pwm_sys_clk_hz": int(pwm_outputs.get("sys_clk_hz", 25_000_000)) if isinstance(pwm_outputs, dict) else 25_000_000,
  1422. "pwm_duty_max": int(pwm_outputs.get("duty_max", 127)) if isinstance(pwm_outputs, dict) else 127,
  1423. "ptc_pwm_hz": int(ptc_pwm.get("default_pwm_hz", 10)) if isinstance(ptc_pwm, dict) else 10,
  1424. "ptc_pwm_min_hz": int(ptc_pwm.get("min_pwm_hz", 1)) if isinstance(ptc_pwm, dict) else 1,
  1425. "ptc_pwm_max_hz": int(ptc_pwm.get("max_pwm_hz", 500)) if isinstance(ptc_pwm, dict) else 500,
  1426. "ptc_polarity": str(ptc_pwm.get("polarity", "active_high_request"))
  1427. if isinstance(ptc_pwm, dict)
  1428. else "active_high_request",
  1429. "fan_pwm_hz": int(fan_pwm.get("default_pwm_hz", 25_000)) if isinstance(fan_pwm, dict) else 25_000,
  1430. "fan_pwm_min_hz": int(fan_pwm.get("min_pwm_hz", 21_000)) if isinstance(fan_pwm, dict) else 21_000,
  1431. "fan_pwm_max_hz": int(fan_pwm.get("max_pwm_hz", 28_000)) if isinstance(fan_pwm, dict) else 28_000,
  1432. "fan_normal_level": int(fan_pwm.get("normal_level", fan_policy.get("background_level", 38)))
  1433. if isinstance(fan_pwm, dict)
  1434. else 38,
  1435. "fan_fallback_level": int(fan_pwm.get("fallback_level", fan_policy.get("fallback_level", 127)))
  1436. if isinstance(fan_pwm, dict)
  1437. else 127,
  1438. "fan_output_stage": str(fan_pwm.get("output_stage", "open_drain_low_true"))
  1439. if isinstance(fan_pwm, dict)
  1440. else "open_drain_low_true",
  1441. "tach_pulses_per_revolution": int(fan_pwm.get("tach_pulses_per_revolution", 2))
  1442. if isinstance(fan_pwm, dict)
  1443. else 2,
  1444. "tach_window_ms": int(fan_pwm.get("tach_window_ms", 1000)) if isinstance(fan_pwm, dict) else 1000,
  1445. }
  1446. class TwentyFourChannelPid:
  1447. def __init__(self, channel_count: int = 24, out_min: int = 0, out_max: int = 127) -> None:
  1448. self.channel_count = channel_count
  1449. self.out_min = out_min
  1450. self.out_max = out_max
  1451. self.channels: dict[int, IncrementalPid] = {}
  1452. def clear_channel(self, channel: int) -> None:
  1453. if 0 <= channel < self.channel_count:
  1454. self.channels.pop(channel, None)
  1455. def update(self, sample: SensorSample, config: HostConfig) -> PidResult:
  1456. if sample.channel < 0 or sample.channel >= self.channel_count:
  1457. return PidResult(False, sample.channel, 0, 0, True, True, sample_seq=sample.sample_seq)
  1458. if not sample.valid or sample.fault:
  1459. self.clear_channel(sample.channel)
  1460. return PidResult(
  1461. sample.valid,
  1462. sample.channel,
  1463. 0,
  1464. 0,
  1465. True,
  1466. True,
  1467. sample_seq=sample.sample_seq,
  1468. history_cleared=True,
  1469. )
  1470. error_q = config.target_q - sample.temp_q
  1471. if not config.enable:
  1472. self.clear_channel(sample.channel)
  1473. return PidResult(
  1474. True,
  1475. sample.channel,
  1476. error_q,
  1477. 0,
  1478. True,
  1479. False,
  1480. sample_seq=sample.sample_seq,
  1481. history_cleared=True,
  1482. )
  1483. channel = self.channels.get(sample.channel)
  1484. if channel is None:
  1485. channel = IncrementalPid(
  1486. PidConfig(
  1487. a0=config.a0,
  1488. a1=config.a1,
  1489. a2=config.a2,
  1490. out_min=self.out_min,
  1491. out_max=self.out_max,
  1492. )
  1493. )
  1494. self.channels[sample.channel] = channel
  1495. else:
  1496. channel.config = PidConfig(
  1497. a0=config.a0,
  1498. a1=config.a1,
  1499. a2=config.a2,
  1500. out_min=self.out_min,
  1501. out_max=self.out_max,
  1502. )
  1503. ctrl_prev_q = channel.u_k1
  1504. delta_q = (config.a0 * error_q) + (config.a1 * channel.e_k1) + (config.a2 * channel.e_k2)
  1505. ctrl_q = channel.update(error_q)
  1506. unclamped = ctrl_prev_q + delta_q
  1507. return PidResult(
  1508. True,
  1509. sample.channel,
  1510. error_q,
  1511. ctrl_q,
  1512. True,
  1513. False,
  1514. sample_seq=sample.sample_seq,
  1515. ctrl_prev_q=ctrl_prev_q,
  1516. delta_q=delta_q,
  1517. clamped=(unclamped < self.out_min or unclamped > self.out_max),
  1518. history_cleared=False,
  1519. )
  1520. class ThermalControlService24Ch:
  1521. """Configurable 24-channel control service.
  1522. V2 defaults to incremental PID. Hysteresis PI remains available as an
  1523. explicit experimental mode for comparison.
  1524. """
  1525. def __init__(
  1526. self,
  1527. channel_count: int = 24,
  1528. out_min: int = 0,
  1529. out_max: int = 127,
  1530. *,
  1531. target_tolerance_q: int = 5,
  1532. power_limit: int | None = None,
  1533. kp_q: int = 4,
  1534. ki_q: int = 1,
  1535. integral_min_q: int = -127,
  1536. integral_max_q: int = 127,
  1537. manual_level: int = 0,
  1538. ) -> None:
  1539. self.channel_count = channel_count
  1540. self.out_min = out_min
  1541. self.out_max = out_max
  1542. self.target_tolerance_q = target_tolerance_q
  1543. self.power_limit = out_max if power_limit is None else min(out_max, max(out_min, power_limit))
  1544. self.kp_q = kp_q
  1545. self.ki_q = ki_q
  1546. self.integral_min_q = integral_min_q
  1547. self.integral_max_q = integral_max_q
  1548. self.manual_level = manual_level
  1549. self.integral_by_channel: dict[int, int] = {}
  1550. self.incremental_pid = TwentyFourChannelPid(channel_count=channel_count, out_min=out_min, out_max=self.power_limit)
  1551. def clear_channel(self, channel: int) -> None:
  1552. if 0 <= channel < self.channel_count:
  1553. self.integral_by_channel.pop(channel, None)
  1554. self.incremental_pid.clear_channel(channel)
  1555. def update(self, sample: SensorSample, config: HostConfig) -> PidResult:
  1556. mode = config.mode
  1557. if sample.channel < 0 or sample.channel >= self.channel_count:
  1558. return PidResult(
  1559. False,
  1560. sample.channel,
  1561. 0,
  1562. 0,
  1563. True,
  1564. True,
  1565. sample_seq=sample.sample_seq,
  1566. control_mode=mode,
  1567. )
  1568. if not sample.valid or sample.fault:
  1569. self.clear_channel(sample.channel)
  1570. return PidResult(
  1571. sample.valid,
  1572. sample.channel,
  1573. 0,
  1574. 0,
  1575. True,
  1576. True,
  1577. sample_seq=sample.sample_seq,
  1578. history_cleared=True,
  1579. control_mode=mode,
  1580. )
  1581. error_q = config.target_q - sample.temp_q
  1582. if not config.enable or mode == CONTROL_MODE_SAFE_OFF:
  1583. self.clear_channel(sample.channel)
  1584. return PidResult(
  1585. True,
  1586. sample.channel,
  1587. error_q,
  1588. 0,
  1589. True,
  1590. False,
  1591. sample_seq=sample.sample_seq,
  1592. history_cleared=True,
  1593. control_mode=mode,
  1594. target_q=config.target_q,
  1595. )
  1596. if mode == CONTROL_MODE_MANUAL_LEVEL:
  1597. duty = self._clamp(self.manual_level)
  1598. return PidResult(
  1599. True,
  1600. sample.channel,
  1601. error_q,
  1602. duty,
  1603. True,
  1604. False,
  1605. sample_seq=sample.sample_seq,
  1606. clamped=duty != self.manual_level,
  1607. control_mode=mode,
  1608. target_q=config.target_q,
  1609. manual_level_q=self.manual_level,
  1610. )
  1611. if mode == CONTROL_MODE_INCREMENTAL_PID_DEFAULT:
  1612. result = self.incremental_pid.update(sample, config)
  1613. return PidResult(
  1614. result.valid,
  1615. result.channel,
  1616. result.error_q,
  1617. result.ctrl_q,
  1618. result.done,
  1619. result.fault,
  1620. sample_seq=result.sample_seq,
  1621. ctrl_prev_q=result.ctrl_prev_q,
  1622. delta_q=result.delta_q,
  1623. clamped=result.clamped,
  1624. history_cleared=result.history_cleared,
  1625. control_mode=mode,
  1626. experimental=False,
  1627. target_q=config.target_q,
  1628. )
  1629. return self._update_hysteresis_pi(sample, config, error_q)
  1630. def _update_hysteresis_pi(self, sample: SensorSample, config: HostConfig, error_q: int) -> PidResult:
  1631. channel = sample.channel
  1632. lower_error = self.target_tolerance_q
  1633. upper_error = -self.target_tolerance_q
  1634. previous_integral = self.integral_by_channel.get(channel, 0)
  1635. if error_q <= upper_error:
  1636. self.integral_by_channel[channel] = 0
  1637. return PidResult(
  1638. True,
  1639. channel,
  1640. error_q,
  1641. 0,
  1642. True,
  1643. False,
  1644. sample_seq=sample.sample_seq,
  1645. clamped=True,
  1646. history_cleared=True,
  1647. control_mode=CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL,
  1648. target_q=config.target_q,
  1649. )
  1650. if error_q >= lower_error:
  1651. integral = self._clamp_integral(previous_integral + error_q)
  1652. raw_ctrl = (self.kp_q * error_q) + (self.ki_q * integral)
  1653. else:
  1654. integral = self._clamp_integral(previous_integral + max(0, error_q))
  1655. raw_ctrl = previous_integral if error_q <= 0 else (self.ki_q * integral)
  1656. duty = min(self.power_limit, self._clamp(raw_ctrl))
  1657. self.integral_by_channel[channel] = integral
  1658. return PidResult(
  1659. True,
  1660. channel,
  1661. error_q,
  1662. duty,
  1663. True,
  1664. False,
  1665. sample_seq=sample.sample_seq,
  1666. ctrl_prev_q=min(self.power_limit, self._clamp(previous_integral)),
  1667. delta_q=duty - min(self.power_limit, self._clamp(previous_integral)),
  1668. clamped=raw_ctrl != duty,
  1669. history_cleared=False,
  1670. control_mode=CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL,
  1671. target_q=config.target_q,
  1672. proportional_q=self.kp_q * error_q,
  1673. integral_q=integral,
  1674. )
  1675. def _clamp(self, value: int) -> int:
  1676. return min(self.out_max, max(self.out_min, value))
  1677. def _clamp_integral(self, value: int) -> int:
  1678. return min(self.integral_max_q, max(self.integral_min_q, value))
  1679. class ActuatorSink:
  1680. def __init__(self, out_min: int, out_max: int, channel_count: int = 24) -> None:
  1681. self.out_min = out_min
  1682. self.out_max = out_max
  1683. self.channel_count = channel_count
  1684. def consume(self, result: PidResult, config: HostConfig) -> ActuatorCommand:
  1685. if result.channel < 0 or result.channel >= self.channel_count:
  1686. return ActuatorCommand(False, result.channel, 0, True, ACTUATOR_REASON_CHANNEL_INVALID)
  1687. if not config.enable:
  1688. return ActuatorCommand(False, result.channel, 0, True, ACTUATOR_REASON_HOST_DISABLED)
  1689. if result.fault or not result.valid:
  1690. return ActuatorCommand(False, result.channel, 0, True, ACTUATOR_REASON_PID_OR_SENSOR_FAULT)
  1691. duty = result.ctrl_q
  1692. if duty < self.out_min:
  1693. duty = self.out_min
  1694. elif duty > self.out_max:
  1695. duty = self.out_max
  1696. return ActuatorCommand(True, result.channel, duty, False, ACTUATOR_REASON_OK)
  1697. def _csv_bool(value: str) -> bool:
  1698. return value.strip().lower() in {"1", "true", "yes", "y"}
  1699. def load_sensor_csv(path: Path) -> list[SensorSample]:
  1700. samples: list[SensorSample] = []
  1701. with path.open("r", newline="", encoding="utf-8") as handle:
  1702. reader = csv.DictReader(handle)
  1703. required = {"valid", "fault", "channel", "temp_q", "sample_seq"}
  1704. missing = required - set(reader.fieldnames or [])
  1705. if missing:
  1706. raise ValueError(f"sensor CSV missing columns: {', '.join(sorted(missing))}")
  1707. for row in reader:
  1708. samples.append(
  1709. SensorSample(
  1710. valid=_csv_bool(row["valid"]),
  1711. fault=_csv_bool(row["fault"]),
  1712. channel=int(row["channel"]),
  1713. temp_q=int(row["temp_q"]),
  1714. sample_seq=int(row["sample_seq"]),
  1715. )
  1716. )
  1717. return samples
  1718. def load_host_csv(path: Path) -> FakeHostConfig:
  1719. with path.open("r", newline="", encoding="utf-8") as handle:
  1720. reader = csv.DictReader(handle)
  1721. required = {"effective_sample_seq", "enable", "target_q", "a0", "a1", "a2", "mode", "config_seq"}
  1722. missing = required - set(reader.fieldnames or [])
  1723. if missing:
  1724. raise ValueError(f"host CSV missing columns: {', '.join(sorted(missing))}")
  1725. steps: list[HostConfigStep] = []
  1726. for row in reader:
  1727. steps.append(
  1728. HostConfigStep(
  1729. effective_sample_seq=int(row["effective_sample_seq"]),
  1730. enable=_csv_bool(row["enable"]),
  1731. target_q=int(row["target_q"]),
  1732. a0=int(row["a0"]),
  1733. a1=int(row["a1"]),
  1734. a2=int(row["a2"]),
  1735. mode=int(row["mode"]),
  1736. config_seq=int(row["config_seq"]),
  1737. source=row.get("source", "fake_host"),
  1738. interface=row.get("interface", "internal"),
  1739. command=row.get("command", "SET_CONFIG"),
  1740. )
  1741. )
  1742. if not steps:
  1743. raise ValueError("host CSV must contain at least one config row")
  1744. first, rest = steps[0], steps[1:]
  1745. return FakeHostConfig(
  1746. enable=first.enable,
  1747. target_q=first.target_q,
  1748. a0=first.a0,
  1749. a1=first.a1,
  1750. a2=first.a2,
  1751. mode=first.mode,
  1752. steps=rest,
  1753. )
  1754. def load_replay_expectations_csv(path: Path) -> list[ReplayExpectation]:
  1755. expectations: list[ReplayExpectation] = []
  1756. with path.open("r", newline="", encoding="utf-8") as handle:
  1757. reader = csv.DictReader(handle)
  1758. required = {"channel", "duty_or_level", "reason", "force_off"}
  1759. missing = required - set(reader.fieldnames or [])
  1760. if missing:
  1761. raise ValueError(f"expectation CSV missing columns: {', '.join(sorted(missing))}")
  1762. for row in reader:
  1763. expectations.append(
  1764. ReplayExpectation(
  1765. channel=int(row["channel"]),
  1766. duty_or_level=int(row["duty_or_level"]),
  1767. reason=row["reason"],
  1768. force_off=_csv_bool(row["force_off"]),
  1769. )
  1770. )
  1771. return expectations
  1772. def verify_replay_expectations(report: SensorReplayResult, expectations: list[ReplayExpectation]) -> None:
  1773. for expectation in expectations:
  1774. actual = report.per_channel_last_ctrl.get(expectation.channel)
  1775. if actual != expectation.duty_or_level:
  1776. raise AssertionError(
  1777. f"channel {expectation.channel} duty expected {expectation.duty_or_level}, got {actual}"
  1778. )
  1779. actual_reason = report.per_channel_last_reason.get(expectation.channel)
  1780. if actual_reason != expectation.reason:
  1781. raise AssertionError(
  1782. f"channel {expectation.channel} reason expected {expectation.reason}, got {actual_reason}"
  1783. )
  1784. actual_force_off = report.per_channel_force_off.get(expectation.channel)
  1785. if actual_force_off != expectation.force_off:
  1786. raise AssertionError(
  1787. f"channel {expectation.channel} force_off expected {expectation.force_off}, got {actual_force_off}"
  1788. )
  1789. def _sensor_to_v2(sample: SensorSample) -> SensorSampleV2:
  1790. return SensorSampleV2(
  1791. valid=sample.valid,
  1792. ready=True,
  1793. source_id=sample.source_id,
  1794. channel=sample.channel,
  1795. temp_q=sample.temp_q,
  1796. fault=sample.fault,
  1797. stale=False,
  1798. sample_seq=sample.sample_seq,
  1799. raw_status=RAW_STATUS_SENSOR_FAULT if sample.fault else RAW_STATUS_OK,
  1800. )
  1801. def _host_to_v2(config: HostConfig) -> HostConfigV2:
  1802. return HostConfigV2(
  1803. enable=config.enable,
  1804. target_q=config.target_q,
  1805. a0=config.a0,
  1806. a1=config.a1,
  1807. a2=config.a2,
  1808. mode=config.mode,
  1809. config_seq=config.config_seq,
  1810. watchdog_kick=True,
  1811. )
  1812. def _actuator_v2_to_legacy(command: ActuatorCommandV2) -> ActuatorCommand:
  1813. return ActuatorCommand(
  1814. enable=command.enable,
  1815. channel=command.channel,
  1816. duty_or_level=command.duty_or_level,
  1817. force_off=command.force_off,
  1818. reason=command.reason,
  1819. )
  1820. def _legacy_to_actuator_v2(command: ActuatorCommand) -> ActuatorCommandV2:
  1821. return ActuatorCommandV2(
  1822. channel=command.channel,
  1823. kind=ACTUATOR_KIND_PTC,
  1824. duty_or_level=command.duty_or_level,
  1825. enable=command.enable,
  1826. force_off=command.force_off,
  1827. reason=command.reason,
  1828. fault_code={
  1829. ACTUATOR_REASON_OK: FAULT_CODE_OK,
  1830. ACTUATOR_REASON_HOST_DISABLED: FAULT_CODE_HOST_DISABLED,
  1831. ACTUATOR_REASON_PID_OR_SENSOR_FAULT: FAULT_CODE_SENSOR_FAULT,
  1832. ACTUATOR_REASON_CHANNEL_INVALID: FAULT_CODE_INVALID_CHANNEL,
  1833. ACTUATOR_REASON_SENSOR_STALE: FAULT_CODE_SENSOR_STALE,
  1834. ACTUATOR_REASON_HOST_TIMEOUT: FAULT_CODE_HOST_TIMEOUT,
  1835. ACTUATOR_REASON_OVERTEMP: FAULT_CODE_OVERTEMP,
  1836. ACTUATOR_REASON_INTERLOCK: FAULT_CODE_INTERLOCK,
  1837. }.get(command.reason, FAULT_CODE_SENSOR_FAULT),
  1838. )
  1839. def run_replay(
  1840. samples: list[SensorSample],
  1841. host: FakeHostConfig,
  1842. pid: TwentyFourChannelPid | ThermalControlService24Ch,
  1843. sink: ActuatorSink | ActuatorDomain,
  1844. ) -> SensorReplayResult:
  1845. commands: list[ActuatorCommand] = []
  1846. trace: list[dict[str, int | str | bool]] = []
  1847. trace_seq = 0
  1848. contract_config = load_contract_config()
  1849. safety_config = contract_config.get("safety", {})
  1850. safety = SafetySupervisor(
  1851. channel_count=getattr(pid, "channel_count", 24),
  1852. overtemp_limit_q=int(safety_config.get("overtemp_limit_q", 90)) if isinstance(safety_config, dict) else 90,
  1853. host_timeout_samples=int(safety_config.get("global_bmc_timeout_cycles", 10)) if isinstance(safety_config, dict) else 10,
  1854. )
  1855. summary = config_contract_summary()
  1856. ptc_pwm_model = PwmOutputModel(
  1857. sys_clk_hz=int(summary["pwm_sys_clk_hz"]),
  1858. pwm_hz=int(summary["ptc_pwm_hz"]),
  1859. duty_max=int(summary["pwm_duty_max"]),
  1860. )
  1861. fan_pwm_model = PwmOutputModel(
  1862. sys_clk_hz=int(summary["pwm_sys_clk_hz"]),
  1863. pwm_hz=int(summary["fan_pwm_hz"]),
  1864. duty_max=int(summary["pwm_duty_max"]),
  1865. )
  1866. fan_pwm_config = contract_config.get("pwm_outputs", {}).get("fan", {}) if isinstance(contract_config.get("pwm_outputs", {}), dict) else {}
  1867. tach_estimator = TachRpmEstimator(
  1868. pulses_per_revolution=int(fan_pwm_config.get("tach_pulses_per_revolution", 2))
  1869. if isinstance(fan_pwm_config, dict)
  1870. else 2,
  1871. window_ms=int(fan_pwm_config.get("tach_window_ms", 1000)) if isinstance(fan_pwm_config, dict) else 1000,
  1872. )
  1873. board_io = BoardIoMapping()
  1874. for sample in samples:
  1875. config = host.current(sample.sample_seq)
  1876. result = pid.update(sample, config)
  1877. sample_v2 = _sensor_to_v2(sample)
  1878. config_v2 = _host_to_v2(config)
  1879. fan_command_v2: ActuatorCommandV2 | None = None
  1880. if isinstance(sink, ActuatorDomain):
  1881. safety_state = safety.evaluate(sample_v2, config_v2)
  1882. command_v2 = sink.route_ptc(result, safety_state)
  1883. fan_command_v2 = sink.route_fan(0, safety_state)
  1884. command = _actuator_v2_to_legacy(command_v2)
  1885. else:
  1886. command = sink.consume(result, config)
  1887. command_v2 = _legacy_to_actuator_v2(command)
  1888. safety_state = SystemSafetyState(
  1889. global_enable=command.enable,
  1890. fault_latched=False,
  1891. fault_code=command_v2.fault_code,
  1892. sensor_stale=False,
  1893. overtemp=False,
  1894. comm_timeout=False,
  1895. interlock=False,
  1896. )
  1897. commands.append(command)
  1898. trace_seq += 1
  1899. ptc_duty = command_v2.duty_or_level if command_v2.kind == ACTUATOR_KIND_PTC else command.duty_or_level
  1900. fan_duty = fan_command_v2.duty_or_level if fan_command_v2 is not None else 0
  1901. ptc_logic = ptc_pwm_model.logic_level_at(0 if command_v2.force_off else ptc_duty, 0)
  1902. fan_logic = fan_pwm_model.logic_level_at(fan_duty, 0)
  1903. tach_edges = 0
  1904. trace.append({
  1905. "trace_seq": trace_seq,
  1906. "source_id": sample.source_id,
  1907. "channel": sample.channel,
  1908. "dimm_id": sample.channel if 0 <= sample.channel < 24 else -1,
  1909. "cpu_id": summary["channel_to_cpu"].split(",")[sample.channel] if 0 <= sample.channel < 24 else "-1",
  1910. "airflow_zone": summary["channel_to_airflow_zone"].split(",")[sample.channel] if 0 <= sample.channel < 24 else "-1",
  1911. "frame_seq": 0,
  1912. "missing": bool(sample.fault and sample.temp_q == 0),
  1913. "missing_mask": 0,
  1914. "parser_state": "not_bmc_parser",
  1915. "raw_status": RAW_STATUS_SENSOR_FAULT if sample.fault else RAW_STATUS_OK,
  1916. "raw_integer_byte": -1,
  1917. "raw_fraction_byte": -1,
  1918. "sample_seq": sample.sample_seq,
  1919. "config_seq": config.config_seq,
  1920. "target_q": config.target_q,
  1921. "temp_q": sample.temp_q,
  1922. "age_ms": 0,
  1923. "error_q": result.error_q,
  1924. "ctrl_prev_q": result.ctrl_prev_q,
  1925. "delta_q": result.delta_q,
  1926. "control_mode": control_mode_name(result.control_mode),
  1927. "ctrl_q": result.ctrl_q,
  1928. "clamped": result.clamped,
  1929. "history_cleared": result.history_cleared,
  1930. "ptc_duty": ptc_duty,
  1931. "ptc_pwm_out": board_io.ptc_pwm_request(ptc_logic),
  1932. "ptc_pwm_high_ticks": ptc_pwm_model.high_ticks(0 if command_v2.force_off else ptc_duty),
  1933. "ptc_pwm_period_ticks": ptc_pwm_model.period_ticks,
  1934. "fan_duty": fan_duty,
  1935. "fan_pwm_logic_high": fan_logic,
  1936. "fan_pwm_drive_low": board_io.fan_pwm_drive_low(fan_logic),
  1937. "fan_pwm_high_ticks": fan_pwm_model.high_ticks(fan_duty),
  1938. "fan_pwm_period_ticks": fan_pwm_model.period_ticks,
  1939. "tach_edge_count": tach_edges,
  1940. "tach_window_edges": tach_edges,
  1941. "rpm_estimate": tach_estimator.rpm_from_edges(tach_edges),
  1942. "fault_code": command_v2.fault_code,
  1943. "force_off": command.force_off,
  1944. "reason": command.reason,
  1945. "duty_or_level": command.duty_or_level,
  1946. "safety_fault_latched": safety_state.fault_latched,
  1947. })
  1948. reason_counts = Counter(command.reason for command in commands)
  1949. for reason in [
  1950. ACTUATOR_REASON_OK,
  1951. ACTUATOR_REASON_HOST_DISABLED,
  1952. ACTUATOR_REASON_PID_OR_SENSOR_FAULT,
  1953. ACTUATOR_REASON_CHANNEL_INVALID,
  1954. ]:
  1955. reason_counts.setdefault(reason, 0)
  1956. duties = [command.duty_or_level for command in commands]
  1957. per_channel_last_ctrl = {command.channel: command.duty_or_level for command in commands}
  1958. per_channel_last_reason = {command.channel: command.reason for command in commands}
  1959. per_channel_force_off = {command.channel: command.force_off for command in commands}
  1960. return SensorReplayResult(
  1961. sample_count=len(samples),
  1962. command_count=len(commands),
  1963. enabled_count=sum(1 for command in commands if command.enable),
  1964. force_off_count=sum(1 for command in commands if command.force_off),
  1965. reason_counts=dict(reason_counts),
  1966. per_channel_last_ctrl=per_channel_last_ctrl,
  1967. per_channel_last_reason=per_channel_last_reason,
  1968. per_channel_force_off=per_channel_force_off,
  1969. min_duty=min(duties) if duties else 0,
  1970. max_duty=max(duties) if duties else 0,
  1971. trace=trace,
  1972. )