#!/usr/bin/env python3 """Contract-level model for parallel PID integration.""" from __future__ import annotations import csv import json import random import re from collections import Counter from dataclasses import dataclass from pathlib import Path from pid_model import CONFIG_PATH, IncrementalPid, PidConfig ACTUATOR_REASON_OK = "ok" ACTUATOR_REASON_HOST_DISABLED = "host_disabled" ACTUATOR_REASON_PID_OR_SENSOR_FAULT = "pid_or_sensor_fault" ACTUATOR_REASON_CHANNEL_INVALID = "channel_invalid" ACTUATOR_REASON_SENSOR_STALE = "sensor_stale" ACTUATOR_REASON_HOST_TIMEOUT = "host_timeout" ACTUATOR_REASON_OVERTEMP = "overtemp" ACTUATOR_REASON_INTERLOCK = "interlock" ACTUATOR_REASON_FAN_FALLBACK = "fan_fallback" SOURCE_FAKE = 0 SOURCE_I2C_MASTER = 1 SOURCE_I2C_SLAVE_INJECT = 2 SOURCE_RS232_UART_INJECT = 3 SOURCE_RS485_INJECT = 4 SOURCE_BMC_UART_TEXT = 5 SOURCE_FAKE_STRESS = 6 CONTROL_MODE_SAFE_OFF = 0 CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL = 1 CONTROL_MODE_MANUAL_LEVEL = 2 CONTROL_MODE_INCREMENTAL_PID_DEFAULT = 3 CONTROL_MODE_HYSTERESIS_PI_DEFAULT = CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL CONTROL_MODE_INCREMENTAL_PID_EXPERIMENTAL = CONTROL_MODE_INCREMENTAL_PID_DEFAULT ACTUATOR_KIND_PTC = "ptc" ACTUATOR_KIND_FAN = "fan" ACTUATOR_KIND_MOTOR = "motor" FAULT_CODE_OK = 0 FAULT_CODE_HOST_DISABLED = 1 FAULT_CODE_SENSOR_FAULT = 2 FAULT_CODE_SENSOR_STALE = 3 FAULT_CODE_HOST_TIMEOUT = 4 FAULT_CODE_OVERTEMP = 5 FAULT_CODE_INVALID_CHANNEL = 6 FAULT_CODE_INTERLOCK = 7 RAW_STATUS_OK = 0x00 RAW_STATUS_MISSING_DIMM = 0x01 RAW_STATUS_PARSER_ERROR = 0x02 RAW_STATUS_SENSOR_FAULT = 0x04 RAW_STATUS_STALE = 0x08 PARSER_STATUS_OK = "ok" PARSER_STATUS_BAD_LENGTH = "bad_length" PARSER_STATUS_NO_CANDIDATE = "no_candidate" PARSER_STATUS_BAD_FRACTION = "bad_fraction" BMC_POLL_COMMAND_ASCII = "ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03\n" BMC_POLL_COMMAND_BYTES = [0x36, 0x6C, 0xDF, 0xDD, 0x00, 0x03] BMC_DIMM_SINGLE_SNAPSHOT_HEX = """ 3c 4b 40 32 40 4b 4d 00 3f 19 38 00 ff ff ff ff 32 00 4c 00 3b 4b 36 00 3a 00 3e 00 3e 32 3e 4b 3d 00 36 4b 26 00 28 00 29 19 31 19 37 4b 35 00 """.strip() BMC_DIMM_USER_SAMPLE_TEXT = """ ("23", "4b", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "28", "00", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff", "ff") """.strip() @dataclass(frozen=True) class SensorSample: valid: bool fault: bool channel: int temp_q: int sample_seq: int source_id: int = SOURCE_FAKE @dataclass(frozen=True) class HostConfig: enable: bool target_q: int a0: int a1: int a2: int mode: int config_seq: int @dataclass(frozen=True) class PidResult: valid: bool channel: int error_q: int ctrl_q: int done: bool fault: bool sample_seq: int = 0 ctrl_prev_q: int = 0 delta_q: int = 0 clamped: bool = False history_cleared: bool = False control_mode: int = CONTROL_MODE_INCREMENTAL_PID_DEFAULT experimental: bool = False dimm_id: int = -1 target_q: int = 0 proportional_q: int = 0 integral_q: int = 0 manual_level_q: int = 0 @dataclass(frozen=True) class ActuatorCommand: enable: bool channel: int duty_or_level: int force_off: bool reason: str @dataclass(frozen=True) class SensorSampleV2: valid: bool ready: bool source_id: int channel: int temp_q: int fault: bool stale: bool sample_seq: int raw_status: int = 0 @dataclass(frozen=True) class DimmTempSampleV1: valid: bool ready: bool source_id: int frame_seq: int sample_seq: int raw_pair_index: int dimm_id: int channel: int raw_integer_byte: int raw_fraction_byte: int fraction_scale: int temp_q: int temp_c_x100: int missing: bool fault: bool stale: bool age_ms: int raw_status: int parser_status: str present: bool = True cpu_id: int = -1 airflow_zone: int = -1 @dataclass(frozen=True) class BmcDimmFrameParseResult: parser_status: str expected_dimm_count: int samples: list[DimmTempSampleV1] frame_seq: int source_id: int raw_token_count: int = 0 selected_window_start: int = -1 rejected_echo_windows: int = 0 missing_mask: int = 0 @dataclass(frozen=True) class ChannelTopology: channel: int dimm_id: int cpu_id: int airflow_zone: int ptc_id: int @dataclass(frozen=True) class FakeStressStep: sample_seq: int channel: int temp_q: int duty: int missing: bool stale: bool noise_q: int coupled_heat_q: float phase: str = "baseline" event_flags: tuple[str, ...] = () class FakeStressModel: """Deterministic verification-only thermal stress source. The coupling values are pressure-test defaults. They are not board thermal constants and are intentionally kept out of the CPLD control compensation. """ def __init__( self, *, channel_count: int = 24, base_temp_q: int = 35, ambient_q: int = 25, seed: int = 260626, self_coupling: float = 1.0, neighbor_coupling: float = 0.04, same_zone_coupling: float = 0.01, cross_zone_coupling: float = 0.005, missing_mask: int = 0, ) -> None: self.channel_count = channel_count self.ambient_q = ambient_q self.temperatures = [float(base_temp_q) for _ in range(channel_count)] self.rng = random.Random(seed) self.self_coupling = self_coupling self.neighbor_coupling = neighbor_coupling self.same_zone_coupling = same_zone_coupling self.cross_zone_coupling = cross_zone_coupling self.missing_mask = missing_mask self.topology = build_channel_topology() self.sample_seq = 0 self.long_scenario_epoch = 0 @classmethod def from_config(cls, path: Path = CONFIG_PATH, *, missing_mask: int = 0) -> "FakeStressModel": payload = load_contract_config(path) stress = payload.get("fake_stress", {}) if not isinstance(stress, dict): stress = {} channels = payload.get("channels", {}) channel_count = int(channels.get("logical_channel_count", 24)) if isinstance(channels, dict) else 24 return cls( channel_count=channel_count, seed=int(stress.get("scenario_seed", 260626)), self_coupling=float(stress.get("self_coupling", 1.0)), neighbor_coupling=float(stress.get("neighbor_channel_coupling", 0.04)), same_zone_coupling=float(stress.get("same_airflow_zone_non_neighbor_coupling", 0.01)), cross_zone_coupling=float(stress.get("cross_airflow_zone_coupling", 0.005)), missing_mask=missing_mask, ) def coupling(self, source_channel: int, target_channel: int) -> float: if source_channel == target_channel: return self.self_coupling if abs(source_channel - target_channel) == 1: return self.neighbor_coupling source_zone = self.topology[source_channel].airflow_zone target_zone = self.topology[target_channel].airflow_zone if source_zone == target_zone: return self.same_zone_coupling return self.cross_zone_coupling def step( self, duties: list[int], *, noise_q: int = 0, stale: bool = False, ) -> list[FakeStressStep]: if len(duties) != self.channel_count: raise ValueError("duties length must match channel_count") heat_by_channel = [] for target in range(self.channel_count): coupled_heat = 0.0 for source, duty in enumerate(duties): coupled_heat += (max(0, min(127, duty)) / 127.0) * self.coupling(source, target) heat_by_channel.append(coupled_heat) steps: list[FakeStressStep] = [] for channel, coupled_heat in enumerate(heat_by_channel): missing = bool(self.missing_mask & (1 << channel)) if missing: duty = 0 else: duty = duties[channel] cool = 0.02 * (self.temperatures[channel] - self.ambient_q) jitter = self.rng.randint(-noise_q, noise_q) if noise_q > 0 else 0 self.temperatures[channel] += coupled_heat - cool + (jitter * 0.01) self.sample_seq += 1 steps.append( FakeStressStep( sample_seq=self.sample_seq, channel=channel, temp_q=0 if missing else int(round(self.temperatures[channel])), duty=0 if missing else int(max(0, min(127, duty))), missing=missing, stale=stale, noise_q=noise_q, coupled_heat_q=coupled_heat, ) ) return steps def step_long_scenario(self, duties: list[int]) -> list[FakeStressStep]: """Run one deterministic long-soak fake-stress epoch. The sequence is intentionally periodic instead of random-at-runtime so a failing soak round can be reproduced from sample_seq and phase. """ phase_index = self.long_scenario_epoch % 8 phase_names = [ "ramp", "ramp", "step", "noise", "missing", "bmc_stale", "parser_garbage", "full_rate_sweep", ] phase = phase_names[phase_index] adjusted = list(duties) missing_mask = self.missing_mask stale = False noise_q = 0 event_flags: list[str] = [] if phase == "ramp": scale = 32 + (phase_index * 24) adjusted = [min(127, (max(0, duty) * scale) // 80) for duty in duties] elif phase == "step": adjusted = [127 if channel % 3 == 0 else 0 for channel in range(self.channel_count)] event_flags.append("host_step") elif phase == "noise": noise_q = 4 event_flags.append("noise") elif phase == "missing": missing_mask |= (1 << 5) | (1 << 11) | (1 << 18) event_flags.append("missing_mask") elif phase == "bmc_stale": stale = True event_flags.append("bmc_stale") elif phase == "parser_garbage": adjusted = [127 if channel < 12 else 16 for channel in range(self.channel_count)] event_flags.append("parser_garbage") elif phase == "full_rate_sweep": adjusted = [((self.long_scenario_epoch + channel) * 23) % 128 for channel in range(self.channel_count)] event_flags.append("full_rate_sweep") original_missing_mask = self.missing_mask self.missing_mask = missing_mask try: steps = self.step(adjusted, noise_q=noise_q, stale=stale) finally: self.missing_mask = original_missing_mask self.long_scenario_epoch += 1 enriched: list[FakeStressStep] = [] for step in steps: flags = list(event_flags) if step.missing and "missing_mask" not in flags: flags.append("missing_mask") enriched.append( FakeStressStep( sample_seq=step.sample_seq, channel=step.channel, temp_q=step.temp_q, duty=step.duty, missing=step.missing, stale=step.stale, noise_q=step.noise_q, coupled_heat_q=step.coupled_heat_q, phase=phase, event_flags=tuple(flags), ) ) return enriched @dataclass(frozen=True) class HostConfigV2: enable: bool target_q: int a0: int a1: int a2: int mode: int config_seq: int watchdog_kick: bool manual_override: bool = False @dataclass(frozen=True) class SystemSafetyState: global_enable: bool fault_latched: bool fault_code: int sensor_stale: bool overtemp: bool comm_timeout: bool interlock: bool @dataclass(frozen=True) class ActuatorCommandV2: channel: int kind: str duty_or_level: int enable: bool force_off: bool reason: str fault_code: int class PwmOutputModel: """Integer PWM model shared by report generation and tests.""" def __init__(self, *, sys_clk_hz: int, pwm_hz: int, duty_max: int = 127) -> None: if sys_clk_hz <= 0: raise ValueError("sys_clk_hz must be positive") if pwm_hz <= 0: raise ValueError("pwm_hz must be positive") if duty_max <= 0: raise ValueError("duty_max must be positive") self.sys_clk_hz = sys_clk_hz self.pwm_hz = pwm_hz self.duty_max = duty_max self.period_ticks = max(1, sys_clk_hz // pwm_hz) def clamp_duty(self, duty_or_level: int) -> int: return min(self.duty_max, max(0, duty_or_level)) def high_ticks(self, duty_or_level: int) -> int: duty = self.clamp_duty(duty_or_level) if duty <= 0: return 0 if duty >= self.duty_max: return self.period_ticks return (self.period_ticks * duty) // self.duty_max def logic_level_at(self, duty_or_level: int, tick: int) -> int: high_ticks = self.high_ticks(duty_or_level) if high_ticks <= 0: return 0 if high_ticks >= self.period_ticks: return 1 return 1 if (tick % self.period_ticks) < high_ticks else 0 class BoardIoMapping: """Semantic board IO mapping without binding real pins.""" @staticmethod def ptc_pwm_request(logic_high: int) -> int: return 1 if logic_high else 0 @staticmethod def fan_pwm_drive_low(logic_high: int) -> int: return 0 if logic_high else 1 class TachRpmEstimator: def __init__(self, *, pulses_per_revolution: int = 2, window_ms: int = 1000) -> None: if pulses_per_revolution <= 0: raise ValueError("pulses_per_revolution must be positive") if window_ms <= 0: raise ValueError("window_ms must be positive") self.pulses_per_revolution = pulses_per_revolution self.window_ms = window_ms def rpm_from_edges(self, edge_count: int) -> int: edges = max(0, edge_count) return (edges * 60_000) // (self.pulses_per_revolution * self.window_ms) @dataclass(frozen=True) class DebugSnapshotV2: trace_seq: int sample_seq: int source_id: int channel: int temp_q: int host_enable: bool config_seq: int pid_error_q: int pid_ctrl_q: int safety_fault_code: int safety_fault_latched: bool actuator_kind: str actuator_enable: bool actuator_force_off: bool actuator_reason: str def control_mode_name(mode: int) -> str: return { CONTROL_MODE_SAFE_OFF: "safe_off", CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL: "hysteresis_pi_experimental", CONTROL_MODE_MANUAL_LEVEL: "manual_level", CONTROL_MODE_INCREMENTAL_PID_DEFAULT: "incremental_pid_default", }.get(mode, f"unknown_{mode}") def build_channel_topology(path: Path = CONFIG_PATH) -> dict[int, ChannelTopology]: payload = load_contract_config(path) channels = payload.get("channels", {}) if not isinstance(channels, dict): raise ValueError("pid contract config has invalid channels section") dimm_map = list(channels.get("default_dimm_to_channel_map", range(24))) channel_to_cpu = list(channels.get("channel_to_cpu", [0] * 24)) channel_to_airflow = list(channels.get("channel_to_airflow_zone", [0] * 24)) topology: dict[int, ChannelTopology] = {} for dimm_id, channel in enumerate(dimm_map): channel_int = int(channel) cpu_id = int(channel_to_cpu[channel_int]) if channel_int < len(channel_to_cpu) else -1 airflow_zone = int(channel_to_airflow[channel_int]) if channel_int < len(channel_to_airflow) else -1 topology[channel_int] = ChannelTopology( channel=channel_int, dimm_id=dimm_id, cpu_id=cpu_id, airflow_zone=airflow_zone, ptc_id=channel_int, ) return topology @dataclass(frozen=True) class ActuatorPolicy: actuator_count: int output_kind: str out_min: int out_max: int safe_default: str notes: str @classmethod def ptc_24ch_default(cls) -> "ActuatorPolicy": config = load_contract_config() actuator = config["actuator"] if not isinstance(actuator, dict): raise ValueError("pid contract config has invalid actuator section") return cls( actuator_count=int(actuator["actuator_count"]), output_kind=str(actuator["kind"]), out_min=int(actuator["out_min"]), out_max=int(actuator["out_max"]), safe_default=str(actuator["safe_default"]), notes="24 logical PTC heater blocks from project IO notes; polarity/PWM driver remains undefined.", ) @dataclass(frozen=True) class ReplayExpectation: channel: int duty_or_level: int reason: str force_off: bool @dataclass(frozen=True) class ChannelProfile: adc_zone: int base_temp_q: int gradient_q: int = 0 thermal_lag_q: int = 0 @dataclass(frozen=True) class HostConfigStep: effective_sample_seq: int enable: bool target_q: int a0: int a1: int a2: int mode: int = 0 config_seq: int | None = None source: str = "fake_host" interface: str = "internal" command: str = "SET_CONFIG" @dataclass(frozen=True) class SensorReplayResult: sample_count: int command_count: int enabled_count: int force_off_count: int reason_counts: dict[str, int] per_channel_last_ctrl: dict[int, int] per_channel_last_reason: dict[int, str] per_channel_force_off: dict[int, bool] min_duty: int max_duty: int trace: list[dict[str, int | str | bool]] def to_dict(self) -> dict[str, object]: return { "sample_count": self.sample_count, "command_count": self.command_count, "enabled_count": self.enabled_count, "force_off_count": self.force_off_count, "reason_counts": dict(self.reason_counts), "per_channel_last_ctrl": {str(k): v for k, v in sorted(self.per_channel_last_ctrl.items())}, "per_channel_last_reason": {str(k): v for k, v in sorted(self.per_channel_last_reason.items())}, "per_channel_force_off": {str(k): v for k, v in sorted(self.per_channel_force_off.items())}, "min_duty": self.min_duty, "max_duty": self.max_duty, "trace": self.trace, } @dataclass(frozen=True) class SourceMuxResult: sample: SensorSample | None fake_ready: bool master_ready: bool slave_ready: bool rs232_ready: bool = False rs485_ready: bool = False class BmcDimmFrameParser: """Parser model for the currently observed BMC/IPMI DIMM temperature frame.""" def __init__( self, *, expected_dimm_count: int = 24, fraction_scale: int = 100, dimm_to_channel_map: dict[int, int] | None = None, ) -> None: if expected_dimm_count <= 0: raise ValueError("expected_dimm_count must be positive") if fraction_scale <= 0: raise ValueError("fraction_scale must be positive") self.expected_dimm_count = expected_dimm_count self.fraction_scale = fraction_scale self.dimm_to_channel_map = dimm_to_channel_map or { dimm_id: dimm_id for dimm_id in range(expected_dimm_count) } self.channel_topology = build_channel_topology() def parse_hex_frame( self, raw_hex: str, *, source_id: int, frame_seq: int, sample_seq_base: int, age_ms: int, stale: bool = False, ) -> BmcDimmFrameParseResult: values = self.tokenize_text_hex(raw_hex) pairs = list(zip(values[0::2], values[1::2])) if len(values) % 2 != 0: pairs = pairs[: len(pairs)] return self.parse_pairs( pairs, source_id=source_id, frame_seq=frame_seq, sample_seq_base=sample_seq_base, age_ms=age_ms, stale=stale, ) @staticmethod def tokenize_text_hex(text: str) -> list[int]: """Extract loose text-hex bytes from BMC output. Accepts `NN`, `0xNN`, quotes, commas, parentheses, multiline output, and echoed shell text. Tokens wider than one byte are ignored so words like `ipmitool` do not become accidental hex bytes. """ values: list[int] = [] for match in re.finditer(r"(?i)(?:0x)?([0-9a-f]{2})(?![0-9a-f])", text): prefix_start = max(0, match.start() - 2) prefix = text[prefix_start:match.start()].lower() token = match.group(1) if prefix.endswith("0x") or len(token) == 2: values.append(int(token, 16)) return values def parse_text_response( self, response_text: str, *, source_id: int = SOURCE_BMC_UART_TEXT, frame_seq: int, sample_seq_base: int, age_ms: int, stale: bool = False, ) -> BmcDimmFrameParseResult: values = self.tokenize_text_hex(response_text) frame_bytes = self.select_payload_window_from_text(response_text) if frame_bytes is None: return BmcDimmFrameParseResult( parser_status=PARSER_STATUS_NO_CANDIDATE, expected_dimm_count=self.expected_dimm_count, samples=[], frame_seq=frame_seq, source_id=source_id, raw_token_count=len(values), selected_window_start=-1, rejected_echo_windows=self._count_echo_windows(values), missing_mask=0, ) start, payload = frame_bytes pairs = list(zip(payload[0::2], payload[1::2])) result = self.parse_pairs( pairs, source_id=source_id, frame_seq=frame_seq, sample_seq_base=sample_seq_base, age_ms=age_ms, stale=stale, raw_token_count=len(values), selected_window_start=start, rejected_echo_windows=self._count_echo_windows(values), ) return result def select_payload_window_from_text(self, text: str) -> tuple[int, list[int]] | None: expected_len = self.expected_dimm_count * 2 for block_start, block_values in self._payload_token_blocks(text): for start in range(0, max(0, len(block_values) - expected_len + 1)): window = block_values[start:start + expected_len] if len(window) != expected_len: continue if self._looks_like_echo_window(window): continue if self._valid_payload_window(window): return block_start + start, window return None def _payload_token_blocks(self, text: str) -> list[tuple[int, list[int]]]: blocks: list[tuple[int, list[int]]] = [] current: list[int] = [] current_start = 0 token_cursor = 0 for line in text.splitlines(): line_tokens = self.tokenize_text_hex(line) if self._looks_like_payload_hex_line(line, line_tokens): if not current: current_start = token_cursor current.extend(line_tokens) elif current: blocks.append((current_start, current)) current = [] token_cursor += len(line_tokens) if current: blocks.append((current_start, current)) return blocks @staticmethod def _looks_like_payload_hex_line(line: str, tokens: list[int]) -> bool: if not tokens: return False without_tokens = re.sub(r"(?i)(?:0x)?[0-9a-f]{2}(?![0-9a-f])", "", line).strip() return without_tokens == "" or re.fullmatch(r"""[\s,;:()\[\]{}"'`]+""", without_tokens) is not None def select_payload_window(self, values: list[int]) -> tuple[int, list[int]] | None: expected_len = self.expected_dimm_count * 2 echo_spans = self._command_token_spans(values) for start in range(0, max(0, len(values) - expected_len + 1)): window = values[start:start + expected_len] if len(window) != expected_len: continue if self._overlaps_echo_span(start, expected_len, echo_spans): continue if self._looks_like_echo_window(window): continue if self._valid_payload_window(window): return start, window return None def _valid_payload_window(self, values: list[int]) -> bool: if len(values) != self.expected_dimm_count * 2: return False present_count = 0 for integer_byte, fraction_byte in zip(values[0::2], values[1::2]): if integer_byte == 0xFF and fraction_byte == 0xFF: continue if fraction_byte >= self.fraction_scale: return False present_count += 1 return present_count > 0 @staticmethod def _looks_like_echo_window(values: list[int]) -> bool: command = BMC_POLL_COMMAND_BYTES for index in range(0, len(values) - len(command) + 1): if values[index:index + len(command)] == command: return True return False def _count_echo_windows(self, values: list[int]) -> int: expected_len = self.expected_dimm_count * 2 count = 0 for start in range(0, max(0, len(values) - expected_len + 1)): if self._looks_like_echo_window(values[start:start + expected_len]): count += 1 return count @staticmethod def _command_token_spans(values: list[int]) -> list[tuple[int, int]]: command = BMC_POLL_COMMAND_BYTES spans: list[tuple[int, int]] = [] for index in range(0, len(values) - len(command) + 1): if values[index:index + len(command)] == command: spans.append((index, index + len(command))) return spans @staticmethod def _overlaps_echo_span(start: int, length: int, spans: list[tuple[int, int]]) -> bool: end = start + length return any(start < span_end and end > span_start for span_start, span_end in spans) def parse_pairs( self, pairs: list[tuple[int, int]], *, source_id: int, frame_seq: int, sample_seq_base: int, age_ms: int, stale: bool = False, raw_token_count: int = 0, selected_window_start: int = 0, rejected_echo_windows: int = 0, ) -> BmcDimmFrameParseResult: parser_status = PARSER_STATUS_OK if len(pairs) == self.expected_dimm_count else PARSER_STATUS_BAD_LENGTH if parser_status == PARSER_STATUS_OK: for integer_byte, fraction_byte in pairs: if not (integer_byte == 0xFF and fraction_byte == 0xFF) and fraction_byte >= self.fraction_scale: parser_status = PARSER_STATUS_BAD_FRACTION break samples: list[DimmTempSampleV1] = [] missing_mask = 0 for index, (integer_byte, fraction_byte) in enumerate(pairs): if not 0 <= integer_byte <= 0xFF or not 0 <= fraction_byte <= 0xFF: raise ValueError("BMC DIMM byte values must be in range 0..255") missing = integer_byte == 0xFF and fraction_byte == 0xFF if missing: missing_mask |= 1 << index raw_status = RAW_STATUS_OK if missing: raw_status |= RAW_STATUS_MISSING_DIMM if parser_status != PARSER_STATUS_OK: raw_status |= RAW_STATUS_PARSER_ERROR if stale: raw_status |= RAW_STATUS_STALE temp_c_x100 = 0 if missing else (integer_byte * 100) + ((fraction_byte * 100) // self.fraction_scale) temp_q = 0 if missing else (temp_c_x100 + 50) // 100 fault = missing or parser_status != PARSER_STATUS_OK dimm_id = index channel = self.dimm_to_channel_map.get(dimm_id, dimm_id) topology = self.channel_topology.get(channel, ChannelTopology(channel, dimm_id, -1, -1, channel)) samples.append( DimmTempSampleV1( valid=True, ready=True, source_id=source_id, frame_seq=frame_seq, sample_seq=sample_seq_base + index, raw_pair_index=index, dimm_id=dimm_id, channel=channel, raw_integer_byte=integer_byte, raw_fraction_byte=fraction_byte, fraction_scale=self.fraction_scale, temp_q=temp_q, temp_c_x100=temp_c_x100, missing=missing, fault=fault, stale=stale, age_ms=age_ms, raw_status=raw_status, parser_status=parser_status, present=not missing, cpu_id=topology.cpu_id, airflow_zone=topology.airflow_zone, ) ) return BmcDimmFrameParseResult( parser_status=parser_status, expected_dimm_count=self.expected_dimm_count, samples=samples, frame_seq=frame_seq, source_id=source_id, raw_token_count=raw_token_count, selected_window_start=selected_window_start, rejected_echo_windows=rejected_echo_windows, missing_mask=missing_mask, ) def dimm_sample_to_sensor_sample_v2(sample: DimmTempSampleV1) -> SensorSampleV2: return SensorSampleV2( valid=sample.valid, ready=sample.ready, source_id=sample.source_id, channel=sample.channel, temp_q=sample.temp_q, fault=sample.fault or sample.missing, stale=sample.stale, sample_seq=sample.sample_seq, raw_status=sample.raw_status, ) class SensorSourceMux: def __init__(self, source_select: int = SOURCE_FAKE) -> None: self.source_select = source_select def select( self, *, fake: SensorSample | None, master: SensorSample | None, slave: SensorSample | None, rs232: SensorSample | None = None, rs485: SensorSample | None = None, sensor_ready: bool, ) -> SourceMuxResult: fake_ready = sensor_ready and self.source_select == SOURCE_FAKE master_ready = sensor_ready and self.source_select == SOURCE_I2C_MASTER slave_ready = sensor_ready and self.source_select == SOURCE_I2C_SLAVE_INJECT rs232_ready = sensor_ready and self.source_select == SOURCE_RS232_UART_INJECT rs485_ready = sensor_ready and self.source_select == SOURCE_RS485_INJECT selected = None if self.source_select == SOURCE_FAKE: selected = fake elif self.source_select == SOURCE_I2C_MASTER: selected = master elif self.source_select == SOURCE_I2C_SLAVE_INJECT: selected = slave elif self.source_select == SOURCE_RS232_UART_INJECT: selected = rs232 elif self.source_select == SOURCE_RS485_INJECT: selected = rs485 return SourceMuxResult( sample=selected if selected is not None and selected.valid else None, fake_ready=fake_ready, master_ready=master_ready, slave_ready=slave_ready, rs232_ready=rs232_ready, rs485_ready=rs485_ready, ) class SafetySupervisor: """Contract-level safety gate for all actuator domains. This model intentionally consumes only standard contracts. It does not know I2C addresses, host packets, board pins, or actuator polarity. """ def __init__( self, channel_count: int = 24, overtemp_limit_q: int = 90, host_timeout_samples: int = 10, ) -> None: self.channel_count = channel_count self.overtemp_limit_q = overtemp_limit_q self.host_timeout_samples = host_timeout_samples self._watchdog_age = 0 self._fault_latched = False self._fault_code = FAULT_CODE_OK def clear_fault_latch(self) -> None: self._fault_latched = False self._fault_code = FAULT_CODE_OK self._watchdog_age = 0 def evaluate( self, sample: SensorSampleV2, config: HostConfigV2, *, interlock: bool = False, ) -> SystemSafetyState: if config.watchdog_kick: self._watchdog_age = 0 else: self._watchdog_age += 1 invalid_channel = sample.channel < 0 or sample.channel >= self.channel_count sensor_fault = sample.fault or invalid_channel sensor_stale = sample.stale overtemp = sample.valid and not invalid_channel and sample.temp_q >= self.overtemp_limit_q comm_timeout = self._watchdog_age > self.host_timeout_samples fault_code = FAULT_CODE_OK if interlock: fault_code = FAULT_CODE_INTERLOCK elif overtemp: fault_code = FAULT_CODE_OVERTEMP elif invalid_channel: fault_code = FAULT_CODE_INVALID_CHANNEL elif sensor_fault: fault_code = FAULT_CODE_SENSOR_FAULT elif sensor_stale: fault_code = FAULT_CODE_SENSOR_STALE elif comm_timeout: fault_code = FAULT_CODE_HOST_TIMEOUT elif not config.enable: fault_code = FAULT_CODE_HOST_DISABLED if fault_code in { FAULT_CODE_HOST_TIMEOUT, FAULT_CODE_OVERTEMP, FAULT_CODE_INTERLOCK, }: self._fault_latched = True self._fault_code = fault_code active_code = self._fault_code if self._fault_latched else fault_code global_enable = config.enable and active_code == FAULT_CODE_OK return SystemSafetyState( global_enable=global_enable, fault_latched=self._fault_latched, fault_code=active_code, sensor_stale=sensor_stale, overtemp=overtemp, comm_timeout=comm_timeout, interlock=interlock, ) class ActuatorDomain: """Routes abstract PID output into safe abstract actuator commands.""" def __init__( self, channel_count: int = 24, out_min: int = 0, out_max: int = 127, fan_background_level: int = 38, fan_fallback_level: int = 127, ) -> None: self.channel_count = channel_count self.out_min = out_min self.out_max = out_max self.fan_background_level = fan_background_level self.fan_fallback_level = fan_fallback_level def route_ptc(self, result: PidResult, safety: SystemSafetyState) -> ActuatorCommandV2: if result.channel < 0 or result.channel >= self.channel_count: return self._force_off(result.channel, ACTUATOR_KIND_PTC, FAULT_CODE_INVALID_CHANNEL) if not safety.global_enable: return self._force_off(result.channel, ACTUATOR_KIND_PTC, safety.fault_code) if result.fault or not result.valid: return self._force_off(result.channel, ACTUATOR_KIND_PTC, FAULT_CODE_SENSOR_FAULT) duty = min(self.out_max, max(self.out_min, result.ctrl_q)) return ActuatorCommandV2( channel=result.channel, kind=ACTUATOR_KIND_PTC, duty_or_level=duty, enable=True, force_off=False, reason=ACTUATOR_REASON_OK, fault_code=FAULT_CODE_OK, ) def route_fan(self, channel: int, safety: SystemSafetyState) -> ActuatorCommandV2: if safety.fault_code in { FAULT_CODE_SENSOR_FAULT, FAULT_CODE_SENSOR_STALE, FAULT_CODE_HOST_TIMEOUT, FAULT_CODE_OVERTEMP, }: return ActuatorCommandV2( channel=channel, kind=ACTUATOR_KIND_FAN, duty_or_level=self.fan_fallback_level, enable=True, force_off=False, reason=ACTUATOR_REASON_FAN_FALLBACK, fault_code=safety.fault_code, ) return ActuatorCommandV2( channel=channel, kind=ACTUATOR_KIND_FAN, duty_or_level=self.fan_background_level, enable=True, force_off=False, reason=ACTUATOR_REASON_OK, fault_code=FAULT_CODE_OK, ) def route_motor( self, *, open_request: bool, close_request: bool, open_limit: bool, close_limit: bool, safety: SystemSafetyState, ) -> ActuatorCommandV2: if not safety.global_enable or safety.interlock: return self._force_off(0, ACTUATOR_KIND_MOTOR, safety.fault_code or FAULT_CODE_INTERLOCK) if open_request and not open_limit and not close_request: return ActuatorCommandV2(0, ACTUATOR_KIND_MOTOR, 1, True, False, ACTUATOR_REASON_OK, FAULT_CODE_OK) if close_request and not close_limit and not open_request: return ActuatorCommandV2(0, ACTUATOR_KIND_MOTOR, 2, True, False, ACTUATOR_REASON_OK, FAULT_CODE_OK) return ActuatorCommandV2(0, ACTUATOR_KIND_MOTOR, 0, False, False, ACTUATOR_REASON_OK, FAULT_CODE_OK) def _force_off(self, channel: int, kind: str, fault_code: int) -> ActuatorCommandV2: return ActuatorCommandV2( channel=channel, kind=kind, duty_or_level=0, enable=False, force_off=True, reason=fault_code_to_reason(fault_code), fault_code=fault_code, ) class DebugTraceRecorder: def __init__(self) -> None: self.trace_seq = 0 def capture( self, *, sample: SensorSampleV2, config: HostConfigV2, pid_result: PidResult, safety: SystemSafetyState, actuator: ActuatorCommandV2, ) -> DebugSnapshotV2: self.trace_seq += 1 return DebugSnapshotV2( trace_seq=self.trace_seq, sample_seq=sample.sample_seq, source_id=sample.source_id, channel=sample.channel, temp_q=sample.temp_q, host_enable=config.enable, config_seq=config.config_seq, pid_error_q=pid_result.error_q, pid_ctrl_q=pid_result.ctrl_q, safety_fault_code=safety.fault_code, safety_fault_latched=safety.fault_latched, actuator_kind=actuator.kind, actuator_enable=actuator.enable, actuator_force_off=actuator.force_off, actuator_reason=actuator.reason, ) def fault_code_to_reason(fault_code: int) -> str: return { FAULT_CODE_OK: ACTUATOR_REASON_OK, FAULT_CODE_HOST_DISABLED: ACTUATOR_REASON_HOST_DISABLED, FAULT_CODE_SENSOR_FAULT: ACTUATOR_REASON_PID_OR_SENSOR_FAULT, FAULT_CODE_SENSOR_STALE: ACTUATOR_REASON_SENSOR_STALE, FAULT_CODE_HOST_TIMEOUT: ACTUATOR_REASON_HOST_TIMEOUT, FAULT_CODE_OVERTEMP: ACTUATOR_REASON_OVERTEMP, FAULT_CODE_INVALID_CHANNEL: ACTUATOR_REASON_CHANNEL_INVALID, FAULT_CODE_INTERLOCK: ACTUATOR_REASON_INTERLOCK, }.get(fault_code, ACTUATOR_REASON_PID_OR_SENSOR_FAULT) class FakeSensorSample: def __init__( self, base_temp_q: int | None = None, step_q: int | None = None, channel_count: int = 24, channel_profiles: list[ChannelProfile] | None = None, step_events: dict[int, int] | None = None, fault_events: dict[int, list[int]] | None = None, ) -> None: if channel_profiles is None: if base_temp_q is None or step_q is None: raise ValueError("base_temp_q and step_q are required when channel_profiles is not provided") channel_profiles = [ ChannelProfile( adc_zone=min(3, (channel * 4) // max(1, channel_count)), base_temp_q=base_temp_q + (channel * step_q), ) for channel in range(channel_count) ] if not channel_profiles: raise ValueError("channel_profiles must not be empty") self.channel_profiles = channel_profiles self.channel_count = len(channel_profiles) self.step_events = step_events or {} self.fault_events = fault_events or {} self.index = 0 self.sample_seq = 0 self.accumulated_step_q = 0 @classmethod def from_adc_zones(cls, zone_profiles: list[ChannelProfile], channels_per_zone: int = 6) -> "FakeSensorSample": channel_profiles: list[ChannelProfile] = [] for zone in zone_profiles: for offset in range(channels_per_zone): channel_profiles.append( ChannelProfile( adc_zone=zone.adc_zone, base_temp_q=zone.base_temp_q + (offset * zone.gradient_q), gradient_q=0, thermal_lag_q=zone.thermal_lag_q, ) ) return cls(channel_profiles=channel_profiles) def next_sample(self) -> SensorSample: channel = self.index % self.channel_count self.sample_seq += 1 self.accumulated_step_q += self.step_events.get(self.sample_seq, 0) profile = self.channel_profiles[channel] temp = profile.base_temp_q + self.accumulated_step_q - profile.thermal_lag_q fault_channels = self.fault_events.get(self.sample_seq, []) fault = channel in fault_channels self.index += 1 return SensorSample( valid=True, fault=fault, channel=channel, temp_q=temp, sample_seq=self.sample_seq, source_id=SOURCE_FAKE, ) class I2CMasterSensorProfileAdapter: """Offline model for the v1 virtual I2C sensor register profile.""" def __init__(self, channel_count: int = 24, channels_per_zone: int = 6) -> None: self.channel_count = channel_count self.channels_per_zone = channels_per_zone self.next_channel = 0 self.sample_seq = 0 self._pending: SensorSample | None = None def _profile_temp(self, channel: int) -> int: zone = channel // self.channels_per_zone offset = channel % self.channels_per_zone if zone == 0: return 70 + offset if zone == 1: return 78 + (offset * 2) if zone == 2: return 86 + (offset * 3) return 94 + (offset * 4) def next_sample(self, sensor_ready: bool) -> SensorSample: if self._pending is None: channel = self.next_channel self.sample_seq += 1 self._pending = SensorSample( valid=True, fault=False, channel=channel, temp_q=self._profile_temp(channel), sample_seq=self.sample_seq, source_id=SOURCE_I2C_MASTER, ) self.next_channel = (self.next_channel + 1) % self.channel_count pending = self._pending if sensor_ready: self._pending = None return pending class PidControlRegFile: """V1 byte register map model for the I2C slave control/status plane.""" REG_MAGIC = 0x00 REG_VERSION = 0x01 REG_CONTROL = 0x02 REG_SOURCE_SELECT = 0x03 REG_COMMAND = 0x04 REG_STATUS = 0x05 def __init__(self) -> None: self._regs = [0] * 256 self._regs[self.REG_MAGIC] = 0x50 self._regs[self.REG_VERSION] = 0x01 self._regs[self.REG_CONTROL] = 0x01 self._regs[self.REG_SOURCE_SELECT] = SOURCE_FAKE self._host_config = HostConfig(True, 100, 6, -2, 1, 0, 1) self._host_config_seq = 1 self._slave_sample_seq = 0 self._sample_pending = False self._clear_fault_latch_pending = False self._clear_history_all_pending = False self._write_host_shadow(self._host_config) @property def host_config(self) -> HostConfig: system_enable = bool(self._regs[self.REG_CONTROL] & 0x01) return HostConfig( enable=system_enable and self._host_config.enable, target_q=self._host_config.target_q, a0=self._host_config.a0, a1=self._host_config.a1, a2=self._host_config.a2, mode=self._host_config.mode, config_seq=self._host_config.config_seq, ) @property def source_select(self) -> int: return self._regs[self.REG_SOURCE_SELECT] & 0x03 def _write_host_shadow(self, config: HostConfig) -> None: self._regs[0x10] = 1 if config.enable else 0 self._regs[0x11] = config.mode & 0x03 self.write_int18(0x12, config.target_q) self.write_int18(0x15, config.a0) self.write_int18(0x18, config.a1) self.write_int18(0x1B, config.a2) @staticmethod def _encode_int18(value: int) -> int: return value & 0x3FFFF @staticmethod def _decode_int18(raw: int) -> int: raw &= 0x3FFFF return raw - (1 << 18) if raw & (1 << 17) else raw def write_int18(self, base: int, value: int) -> None: raw = self._encode_int18(value) self._regs[base] = raw & 0xFF self._regs[base + 1] = (raw >> 8) & 0xFF self._regs[base + 2] = (raw >> 16) & 0x03 def read_int18(self, base: int) -> int: raw = self._regs[base] | (self._regs[base + 1] << 8) | ((self._regs[base + 2] & 0x03) << 16) return self._decode_int18(raw) def read(self, addr: int) -> int: return self._regs[addr & 0xFF] & 0xFF def write(self, addr: int, value: int) -> None: addr &= 0xFF value &= 0xFF if addr in {self.REG_MAGIC, self.REG_VERSION}: return if addr == self.REG_CONTROL: self._regs[addr] = value & 0x01 if value & 0x02: self._clear_fault_latch_pending = True if value & 0x04: self._clear_history_all_pending = True return if addr == self.REG_SOURCE_SELECT: self._regs[addr] = value & 0x03 return if addr == self.REG_COMMAND: if value & 0x01: self._commit_host_config() if value & 0x02: self._commit_slave_sample() return self._regs[addr] = value def _commit_host_config(self) -> None: self._host_config_seq += 1 self._host_config = HostConfig( enable=bool(self._regs[0x10] & 0x01), target_q=self.read_int18(0x12), a0=self.read_int18(0x15), a1=self.read_int18(0x18), a2=self.read_int18(0x1B), mode=self._regs[0x11] & 0x03, config_seq=self._host_config_seq, ) def _commit_slave_sample(self) -> None: self._sample_pending = True self._regs[self.REG_STATUS] |= 0x10 def consume_clear_fault_latch(self) -> bool: pending = self._clear_fault_latch_pending self._clear_fault_latch_pending = False return pending def consume_clear_history_all(self) -> bool: pending = self._clear_history_all_pending self._clear_history_all_pending = False return pending def take_slave_sample(self, sensor_ready: bool) -> SensorSample | None: if not sensor_ready or not self._sample_pending or self.source_select != SOURCE_I2C_SLAVE_INJECT: return None self._sample_pending = False self._regs[self.REG_STATUS] &= ~0x10 self._slave_sample_seq += 1 return SensorSample( valid=True, fault=bool(self._regs[0x21] & 0x01), channel=self._regs[0x20] & 0x1F, temp_q=self.read_int18(0x22), sample_seq=self._slave_sample_seq, source_id=SOURCE_I2C_SLAVE_INJECT, ) def capture_status( self, *, sensor_ready: bool, pid_busy: bool, master_fault: bool, slave_fault: bool, sample: SensorSample, pid_result: PidResult, actuator: ActuatorCommand, ) -> None: status = 0 status |= 0x01 if pid_busy else 0 status |= 0x02 if sensor_ready else 0 status |= 0x04 if pid_result.fault else 0 status |= 0x08 if actuator.force_off else 0 status |= 0x10 if self._sample_pending else 0 status |= 0x20 if master_fault else 0 status |= 0x40 if slave_fault else 0 self._regs[self.REG_STATUS] = status self._regs[0x30] = pid_result.channel & 0x1F self._regs[0x31] = ( (1 if pid_result.valid else 0) | ((1 if pid_result.done else 0) << 1) | ((1 if pid_result.fault else 0) << 2) | ((1 if pid_result.clamped else 0) << 3) | ((1 if pid_result.history_cleared else 0) << 4) ) self._regs[0x32] = pid_result.sample_seq & 0xFF self._regs[0x33] = (pid_result.sample_seq >> 8) & 0xFF self.write_int18(0x36, pid_result.error_q) self.write_int18(0x39, pid_result.ctrl_q) self._regs[0x40] = actuator.channel & 0x1F self._regs[0x41] = ( (1 if actuator.enable else 0) | ((1 if actuator.force_off else 0) << 1) | ((self._reason_code(actuator.reason) & 0x03) << 2) ) self.write_int18(0x42, actuator.duty_or_level) trace_seq = (self._regs[0x60] | (self._regs[0x61] << 8)) + 1 self._regs[0x60] = trace_seq & 0xFF self._regs[0x61] = (trace_seq >> 8) & 0xFF self._regs[0x64] = sample.source_id & 0x03 self._regs[0x65] = 3 if pid_result.done else 0 self._regs[0x66] = 2 if pid_busy else 0 self._regs[0x68] = sample.sample_seq & 0xFF self._regs[0x69] = (sample.sample_seq >> 8) & 0xFF self._regs[0x6A] = self.host_config.config_seq & 0xFF self._regs[0x6B] = (self.host_config.config_seq >> 8) & 0xFF self._regs[0x6C] = sample.channel & 0x1F self._regs[0x6D] = ( (1 if pid_result.clamped else 0) | ((1 if pid_result.history_cleared else 0) << 1) | ((1 if pid_result.fault else 0) << 2) | ((1 if actuator.force_off else 0) << 3) ) @staticmethod def _reason_code(reason: str) -> int: return { ACTUATOR_REASON_OK: 0, ACTUATOR_REASON_HOST_DISABLED: 1, ACTUATOR_REASON_PID_OR_SENSOR_FAULT: 2, ACTUATOR_REASON_CHANNEL_INVALID: 3, }[reason] class FakeHostConfig: def __init__( self, enable: bool, target_q: int, a0: int = 6, a1: int = -2, a2: int = 1, mode: int = 0, steps: list[HostConfigStep] | None = None, ) -> None: self.base_config = HostConfig( enable=enable, target_q=target_q, a0=a0, a1=a1, a2=a2, mode=mode, config_seq=1, ) self.steps = sorted(steps or [], key=lambda step: step.effective_sample_seq) def current(self, sample_seq: int | None = None) -> HostConfig: if sample_seq is None: return self.base_config config = self.base_config for index, step in enumerate(self.steps, start=2): if sample_seq < step.effective_sample_seq: break config = HostConfig( enable=step.enable, target_q=step.target_q, a0=step.a0, a1=step.a1, a2=step.a2, mode=step.mode, config_seq=step.config_seq if step.config_seq is not None else index, ) return config def load_contract_config(path: Path = CONFIG_PATH) -> dict[str, object]: with path.open("r", encoding="utf-8") as handle: return json.load(handle) def config_contract_summary(path: Path = CONFIG_PATH) -> dict[str, int | str | bool]: payload = load_contract_config(path) channels = payload["channels"] host = payload["default_host_config"] actuator = payload["actuator"] pwm_outputs = payload.get("pwm_outputs", {}) control = payload.get("control", {}) safety = payload.get("safety", {}) topology = payload.get("physical_topology", {}) bmc_uart = payload.get("bmc_uart_poll", {}) fan_pwm = pwm_outputs.get("fan", {}) if isinstance(pwm_outputs, dict) else {} ptc_pwm = pwm_outputs.get("ptc", {}) if isinstance(pwm_outputs, dict) else {} if not isinstance(channels, dict) or not isinstance(host, dict) or not isinstance(actuator, dict): raise ValueError("pid contract config has invalid top-level sections") airflow_zone_count = int(channels.get("airflow_zone_count", channels.get("adc_zone_count", 0))) channels_per_airflow = channels.get("channels_per_airflow_zone", channels.get("channels_per_adc_zone", 0)) if isinstance(channels_per_airflow, list): channels_per_airflow_text = "/".join(str(int(item)) for item in channels_per_airflow) first_zone_count = int(channels_per_airflow[0]) if channels_per_airflow else 0 else: channels_per_airflow_text = str(channels_per_airflow) first_zone_count = int(channels_per_airflow) fan_policy = payload.get("fan_policy", {}) return { "logical_channel_count": int(channels["logical_channel_count"]), "adc_zone_count": airflow_zone_count, "channels_per_adc_zone": first_zone_count, "airflow_zone_count": airflow_zone_count, "channels_per_airflow_zone": channels_per_airflow_text, "channel_to_cpu": ",".join(str(int(item)) for item in channels.get("channel_to_cpu", [])), "channel_to_airflow_zone": ",".join(str(int(item)) for item in channels.get("channel_to_airflow_zone", [])), "fan_count": int(fan_pwm.get("fan_count", fan_policy.get("fan_count", 6))) if isinstance(fan_pwm, dict) else 6, "default_enable": bool(host["enable"]), "default_target_q": int(host["target_q"]), "default_a0": int(host["a0"]), "default_a1": int(host["a1"]), "default_a2": int(host["a2"]), "actuator_kind": str(actuator["kind"]), "actuator_out_min": int(actuator["out_min"]), "actuator_out_max": int(actuator["out_max"]), "default_control_mode": str(control.get("default_mode", "incremental_pid_default")) if isinstance(control, dict) else "incremental_pid_default", "default_tolerance_q": int(control.get("target_tolerance_q", 5)) if isinstance(control, dict) else 5, "default_stale_timeout_cycles": int(safety.get("stale_timeout_cycles", 10)) if isinstance(safety, dict) else 10, "overtemp_limit_q": int(safety.get("overtemp_limit_q", 90)) if isinstance(safety, dict) else 90, "first_real_pid_duty_limit_percent": int(control.get("first_real_pid_duty_limit_percent", 25)) if isinstance(control, dict) else 25, "bmc_poll_command_ascii": str(bmc_uart.get("command_ascii", BMC_POLL_COMMAND_ASCII)) if isinstance(bmc_uart, dict) else BMC_POLL_COMMAND_ASCII, "bmc_uart": str(bmc_uart.get("uart", "115200 8N1")) if isinstance(bmc_uart, dict) else "115200 8N1", "mapping_policy": str(topology.get("mapping_policy", "bmc_order_equals_physical_order_equals_ptc_channel_order")) if isinstance(topology, dict) else "bmc_order_equals_physical_order_equals_ptc_channel_order", "pwm_sys_clk_hz": int(pwm_outputs.get("sys_clk_hz", 25_000_000)) if isinstance(pwm_outputs, dict) else 25_000_000, "pwm_duty_max": int(pwm_outputs.get("duty_max", 127)) if isinstance(pwm_outputs, dict) else 127, "ptc_pwm_hz": int(ptc_pwm.get("default_pwm_hz", 10)) if isinstance(ptc_pwm, dict) else 10, "ptc_pwm_min_hz": int(ptc_pwm.get("min_pwm_hz", 1)) if isinstance(ptc_pwm, dict) else 1, "ptc_pwm_max_hz": int(ptc_pwm.get("max_pwm_hz", 500)) if isinstance(ptc_pwm, dict) else 500, "ptc_polarity": str(ptc_pwm.get("polarity", "active_high_request")) if isinstance(ptc_pwm, dict) else "active_high_request", "fan_pwm_hz": int(fan_pwm.get("default_pwm_hz", 25_000)) if isinstance(fan_pwm, dict) else 25_000, "fan_pwm_min_hz": int(fan_pwm.get("min_pwm_hz", 21_000)) if isinstance(fan_pwm, dict) else 21_000, "fan_pwm_max_hz": int(fan_pwm.get("max_pwm_hz", 28_000)) if isinstance(fan_pwm, dict) else 28_000, "fan_normal_level": int(fan_pwm.get("normal_level", fan_policy.get("background_level", 38))) if isinstance(fan_pwm, dict) else 38, "fan_fallback_level": int(fan_pwm.get("fallback_level", fan_policy.get("fallback_level", 127))) if isinstance(fan_pwm, dict) else 127, "fan_output_stage": str(fan_pwm.get("output_stage", "open_drain_low_true")) if isinstance(fan_pwm, dict) else "open_drain_low_true", "tach_pulses_per_revolution": int(fan_pwm.get("tach_pulses_per_revolution", 2)) if isinstance(fan_pwm, dict) else 2, "tach_window_ms": int(fan_pwm.get("tach_window_ms", 1000)) if isinstance(fan_pwm, dict) else 1000, } class TwentyFourChannelPid: def __init__(self, channel_count: int = 24, out_min: int = 0, out_max: int = 127) -> None: self.channel_count = channel_count self.out_min = out_min self.out_max = out_max self.channels: dict[int, IncrementalPid] = {} def clear_channel(self, channel: int) -> None: if 0 <= channel < self.channel_count: self.channels.pop(channel, None) def update(self, sample: SensorSample, config: HostConfig) -> PidResult: if sample.channel < 0 or sample.channel >= self.channel_count: return PidResult(False, sample.channel, 0, 0, True, True, sample_seq=sample.sample_seq) if not sample.valid or sample.fault: self.clear_channel(sample.channel) return PidResult( sample.valid, sample.channel, 0, 0, True, True, sample_seq=sample.sample_seq, history_cleared=True, ) error_q = config.target_q - sample.temp_q if not config.enable: self.clear_channel(sample.channel) return PidResult( True, sample.channel, error_q, 0, True, False, sample_seq=sample.sample_seq, history_cleared=True, ) channel = self.channels.get(sample.channel) if channel is None: channel = IncrementalPid( PidConfig( a0=config.a0, a1=config.a1, a2=config.a2, out_min=self.out_min, out_max=self.out_max, ) ) self.channels[sample.channel] = channel else: channel.config = PidConfig( a0=config.a0, a1=config.a1, a2=config.a2, out_min=self.out_min, out_max=self.out_max, ) ctrl_prev_q = channel.u_k1 delta_q = (config.a0 * error_q) + (config.a1 * channel.e_k1) + (config.a2 * channel.e_k2) ctrl_q = channel.update(error_q) unclamped = ctrl_prev_q + delta_q return PidResult( True, sample.channel, error_q, ctrl_q, True, False, sample_seq=sample.sample_seq, ctrl_prev_q=ctrl_prev_q, delta_q=delta_q, clamped=(unclamped < self.out_min or unclamped > self.out_max), history_cleared=False, ) class ThermalControlService24Ch: """Configurable 24-channel control service. V2 defaults to incremental PID. Hysteresis PI remains available as an explicit experimental mode for comparison. """ def __init__( self, channel_count: int = 24, out_min: int = 0, out_max: int = 127, *, target_tolerance_q: int = 5, power_limit: int | None = None, kp_q: int = 4, ki_q: int = 1, integral_min_q: int = -127, integral_max_q: int = 127, manual_level: int = 0, ) -> None: self.channel_count = channel_count self.out_min = out_min self.out_max = out_max self.target_tolerance_q = target_tolerance_q self.power_limit = out_max if power_limit is None else min(out_max, max(out_min, power_limit)) self.kp_q = kp_q self.ki_q = ki_q self.integral_min_q = integral_min_q self.integral_max_q = integral_max_q self.manual_level = manual_level self.integral_by_channel: dict[int, int] = {} self.incremental_pid = TwentyFourChannelPid(channel_count=channel_count, out_min=out_min, out_max=self.power_limit) def clear_channel(self, channel: int) -> None: if 0 <= channel < self.channel_count: self.integral_by_channel.pop(channel, None) self.incremental_pid.clear_channel(channel) def update(self, sample: SensorSample, config: HostConfig) -> PidResult: mode = config.mode if sample.channel < 0 or sample.channel >= self.channel_count: return PidResult( False, sample.channel, 0, 0, True, True, sample_seq=sample.sample_seq, control_mode=mode, ) if not sample.valid or sample.fault: self.clear_channel(sample.channel) return PidResult( sample.valid, sample.channel, 0, 0, True, True, sample_seq=sample.sample_seq, history_cleared=True, control_mode=mode, ) error_q = config.target_q - sample.temp_q if not config.enable or mode == CONTROL_MODE_SAFE_OFF: self.clear_channel(sample.channel) return PidResult( True, sample.channel, error_q, 0, True, False, sample_seq=sample.sample_seq, history_cleared=True, control_mode=mode, target_q=config.target_q, ) if mode == CONTROL_MODE_MANUAL_LEVEL: duty = self._clamp(self.manual_level) return PidResult( True, sample.channel, error_q, duty, True, False, sample_seq=sample.sample_seq, clamped=duty != self.manual_level, control_mode=mode, target_q=config.target_q, manual_level_q=self.manual_level, ) if mode == CONTROL_MODE_INCREMENTAL_PID_DEFAULT: result = self.incremental_pid.update(sample, config) return PidResult( result.valid, result.channel, result.error_q, result.ctrl_q, result.done, result.fault, sample_seq=result.sample_seq, ctrl_prev_q=result.ctrl_prev_q, delta_q=result.delta_q, clamped=result.clamped, history_cleared=result.history_cleared, control_mode=mode, experimental=False, target_q=config.target_q, ) return self._update_hysteresis_pi(sample, config, error_q) def _update_hysteresis_pi(self, sample: SensorSample, config: HostConfig, error_q: int) -> PidResult: channel = sample.channel lower_error = self.target_tolerance_q upper_error = -self.target_tolerance_q previous_integral = self.integral_by_channel.get(channel, 0) if error_q <= upper_error: self.integral_by_channel[channel] = 0 return PidResult( True, channel, error_q, 0, True, False, sample_seq=sample.sample_seq, clamped=True, history_cleared=True, control_mode=CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL, target_q=config.target_q, ) if error_q >= lower_error: integral = self._clamp_integral(previous_integral + error_q) raw_ctrl = (self.kp_q * error_q) + (self.ki_q * integral) else: integral = self._clamp_integral(previous_integral + max(0, error_q)) raw_ctrl = previous_integral if error_q <= 0 else (self.ki_q * integral) duty = min(self.power_limit, self._clamp(raw_ctrl)) self.integral_by_channel[channel] = integral return PidResult( True, channel, error_q, duty, True, False, sample_seq=sample.sample_seq, ctrl_prev_q=min(self.power_limit, self._clamp(previous_integral)), delta_q=duty - min(self.power_limit, self._clamp(previous_integral)), clamped=raw_ctrl != duty, history_cleared=False, control_mode=CONTROL_MODE_HYSTERESIS_PI_EXPERIMENTAL, target_q=config.target_q, proportional_q=self.kp_q * error_q, integral_q=integral, ) def _clamp(self, value: int) -> int: return min(self.out_max, max(self.out_min, value)) def _clamp_integral(self, value: int) -> int: return min(self.integral_max_q, max(self.integral_min_q, value)) class ActuatorSink: def __init__(self, out_min: int, out_max: int, channel_count: int = 24) -> None: self.out_min = out_min self.out_max = out_max self.channel_count = channel_count def consume(self, result: PidResult, config: HostConfig) -> ActuatorCommand: if result.channel < 0 or result.channel >= self.channel_count: return ActuatorCommand(False, result.channel, 0, True, ACTUATOR_REASON_CHANNEL_INVALID) if not config.enable: return ActuatorCommand(False, result.channel, 0, True, ACTUATOR_REASON_HOST_DISABLED) if result.fault or not result.valid: return ActuatorCommand(False, result.channel, 0, True, ACTUATOR_REASON_PID_OR_SENSOR_FAULT) duty = result.ctrl_q if duty < self.out_min: duty = self.out_min elif duty > self.out_max: duty = self.out_max return ActuatorCommand(True, result.channel, duty, False, ACTUATOR_REASON_OK) def _csv_bool(value: str) -> bool: return value.strip().lower() in {"1", "true", "yes", "y"} def load_sensor_csv(path: Path) -> list[SensorSample]: samples: list[SensorSample] = [] with path.open("r", newline="", encoding="utf-8") as handle: reader = csv.DictReader(handle) required = {"valid", "fault", "channel", "temp_q", "sample_seq"} missing = required - set(reader.fieldnames or []) if missing: raise ValueError(f"sensor CSV missing columns: {', '.join(sorted(missing))}") for row in reader: samples.append( SensorSample( valid=_csv_bool(row["valid"]), fault=_csv_bool(row["fault"]), channel=int(row["channel"]), temp_q=int(row["temp_q"]), sample_seq=int(row["sample_seq"]), ) ) return samples def load_host_csv(path: Path) -> FakeHostConfig: with path.open("r", newline="", encoding="utf-8") as handle: reader = csv.DictReader(handle) required = {"effective_sample_seq", "enable", "target_q", "a0", "a1", "a2", "mode", "config_seq"} missing = required - set(reader.fieldnames or []) if missing: raise ValueError(f"host CSV missing columns: {', '.join(sorted(missing))}") steps: list[HostConfigStep] = [] for row in reader: steps.append( HostConfigStep( effective_sample_seq=int(row["effective_sample_seq"]), enable=_csv_bool(row["enable"]), target_q=int(row["target_q"]), a0=int(row["a0"]), a1=int(row["a1"]), a2=int(row["a2"]), mode=int(row["mode"]), config_seq=int(row["config_seq"]), source=row.get("source", "fake_host"), interface=row.get("interface", "internal"), command=row.get("command", "SET_CONFIG"), ) ) if not steps: raise ValueError("host CSV must contain at least one config row") first, rest = steps[0], steps[1:] return FakeHostConfig( enable=first.enable, target_q=first.target_q, a0=first.a0, a1=first.a1, a2=first.a2, mode=first.mode, steps=rest, ) def load_replay_expectations_csv(path: Path) -> list[ReplayExpectation]: expectations: list[ReplayExpectation] = [] with path.open("r", newline="", encoding="utf-8") as handle: reader = csv.DictReader(handle) required = {"channel", "duty_or_level", "reason", "force_off"} missing = required - set(reader.fieldnames or []) if missing: raise ValueError(f"expectation CSV missing columns: {', '.join(sorted(missing))}") for row in reader: expectations.append( ReplayExpectation( channel=int(row["channel"]), duty_or_level=int(row["duty_or_level"]), reason=row["reason"], force_off=_csv_bool(row["force_off"]), ) ) return expectations def verify_replay_expectations(report: SensorReplayResult, expectations: list[ReplayExpectation]) -> None: for expectation in expectations: actual = report.per_channel_last_ctrl.get(expectation.channel) if actual != expectation.duty_or_level: raise AssertionError( f"channel {expectation.channel} duty expected {expectation.duty_or_level}, got {actual}" ) actual_reason = report.per_channel_last_reason.get(expectation.channel) if actual_reason != expectation.reason: raise AssertionError( f"channel {expectation.channel} reason expected {expectation.reason}, got {actual_reason}" ) actual_force_off = report.per_channel_force_off.get(expectation.channel) if actual_force_off != expectation.force_off: raise AssertionError( f"channel {expectation.channel} force_off expected {expectation.force_off}, got {actual_force_off}" ) def _sensor_to_v2(sample: SensorSample) -> SensorSampleV2: return SensorSampleV2( valid=sample.valid, ready=True, source_id=sample.source_id, channel=sample.channel, temp_q=sample.temp_q, fault=sample.fault, stale=False, sample_seq=sample.sample_seq, raw_status=RAW_STATUS_SENSOR_FAULT if sample.fault else RAW_STATUS_OK, ) def _host_to_v2(config: HostConfig) -> HostConfigV2: return HostConfigV2( enable=config.enable, target_q=config.target_q, a0=config.a0, a1=config.a1, a2=config.a2, mode=config.mode, config_seq=config.config_seq, watchdog_kick=True, ) def _actuator_v2_to_legacy(command: ActuatorCommandV2) -> ActuatorCommand: return ActuatorCommand( enable=command.enable, channel=command.channel, duty_or_level=command.duty_or_level, force_off=command.force_off, reason=command.reason, ) def _legacy_to_actuator_v2(command: ActuatorCommand) -> ActuatorCommandV2: return ActuatorCommandV2( channel=command.channel, kind=ACTUATOR_KIND_PTC, duty_or_level=command.duty_or_level, enable=command.enable, force_off=command.force_off, reason=command.reason, fault_code={ ACTUATOR_REASON_OK: FAULT_CODE_OK, ACTUATOR_REASON_HOST_DISABLED: FAULT_CODE_HOST_DISABLED, ACTUATOR_REASON_PID_OR_SENSOR_FAULT: FAULT_CODE_SENSOR_FAULT, ACTUATOR_REASON_CHANNEL_INVALID: FAULT_CODE_INVALID_CHANNEL, ACTUATOR_REASON_SENSOR_STALE: FAULT_CODE_SENSOR_STALE, ACTUATOR_REASON_HOST_TIMEOUT: FAULT_CODE_HOST_TIMEOUT, ACTUATOR_REASON_OVERTEMP: FAULT_CODE_OVERTEMP, ACTUATOR_REASON_INTERLOCK: FAULT_CODE_INTERLOCK, }.get(command.reason, FAULT_CODE_SENSOR_FAULT), ) def run_replay( samples: list[SensorSample], host: FakeHostConfig, pid: TwentyFourChannelPid | ThermalControlService24Ch, sink: ActuatorSink | ActuatorDomain, ) -> SensorReplayResult: commands: list[ActuatorCommand] = [] trace: list[dict[str, int | str | bool]] = [] trace_seq = 0 contract_config = load_contract_config() safety_config = contract_config.get("safety", {}) safety = SafetySupervisor( channel_count=getattr(pid, "channel_count", 24), overtemp_limit_q=int(safety_config.get("overtemp_limit_q", 90)) if isinstance(safety_config, dict) else 90, host_timeout_samples=int(safety_config.get("global_bmc_timeout_cycles", 10)) if isinstance(safety_config, dict) else 10, ) summary = config_contract_summary() ptc_pwm_model = PwmOutputModel( sys_clk_hz=int(summary["pwm_sys_clk_hz"]), pwm_hz=int(summary["ptc_pwm_hz"]), duty_max=int(summary["pwm_duty_max"]), ) fan_pwm_model = PwmOutputModel( sys_clk_hz=int(summary["pwm_sys_clk_hz"]), pwm_hz=int(summary["fan_pwm_hz"]), duty_max=int(summary["pwm_duty_max"]), ) fan_pwm_config = contract_config.get("pwm_outputs", {}).get("fan", {}) if isinstance(contract_config.get("pwm_outputs", {}), dict) else {} tach_estimator = TachRpmEstimator( pulses_per_revolution=int(fan_pwm_config.get("tach_pulses_per_revolution", 2)) if isinstance(fan_pwm_config, dict) else 2, window_ms=int(fan_pwm_config.get("tach_window_ms", 1000)) if isinstance(fan_pwm_config, dict) else 1000, ) board_io = BoardIoMapping() for sample in samples: config = host.current(sample.sample_seq) result = pid.update(sample, config) sample_v2 = _sensor_to_v2(sample) config_v2 = _host_to_v2(config) fan_command_v2: ActuatorCommandV2 | None = None if isinstance(sink, ActuatorDomain): safety_state = safety.evaluate(sample_v2, config_v2) command_v2 = sink.route_ptc(result, safety_state) fan_command_v2 = sink.route_fan(0, safety_state) command = _actuator_v2_to_legacy(command_v2) else: command = sink.consume(result, config) command_v2 = _legacy_to_actuator_v2(command) safety_state = SystemSafetyState( global_enable=command.enable, fault_latched=False, fault_code=command_v2.fault_code, sensor_stale=False, overtemp=False, comm_timeout=False, interlock=False, ) commands.append(command) trace_seq += 1 ptc_duty = command_v2.duty_or_level if command_v2.kind == ACTUATOR_KIND_PTC else command.duty_or_level fan_duty = fan_command_v2.duty_or_level if fan_command_v2 is not None else 0 ptc_logic = ptc_pwm_model.logic_level_at(0 if command_v2.force_off else ptc_duty, 0) fan_logic = fan_pwm_model.logic_level_at(fan_duty, 0) tach_edges = 0 trace.append({ "trace_seq": trace_seq, "source_id": sample.source_id, "channel": sample.channel, "dimm_id": sample.channel if 0 <= sample.channel < 24 else -1, "cpu_id": summary["channel_to_cpu"].split(",")[sample.channel] if 0 <= sample.channel < 24 else "-1", "airflow_zone": summary["channel_to_airflow_zone"].split(",")[sample.channel] if 0 <= sample.channel < 24 else "-1", "frame_seq": 0, "missing": bool(sample.fault and sample.temp_q == 0), "missing_mask": 0, "parser_state": "not_bmc_parser", "raw_status": RAW_STATUS_SENSOR_FAULT if sample.fault else RAW_STATUS_OK, "raw_integer_byte": -1, "raw_fraction_byte": -1, "sample_seq": sample.sample_seq, "config_seq": config.config_seq, "target_q": config.target_q, "temp_q": sample.temp_q, "age_ms": 0, "error_q": result.error_q, "ctrl_prev_q": result.ctrl_prev_q, "delta_q": result.delta_q, "control_mode": control_mode_name(result.control_mode), "ctrl_q": result.ctrl_q, "clamped": result.clamped, "history_cleared": result.history_cleared, "ptc_duty": ptc_duty, "ptc_pwm_out": board_io.ptc_pwm_request(ptc_logic), "ptc_pwm_high_ticks": ptc_pwm_model.high_ticks(0 if command_v2.force_off else ptc_duty), "ptc_pwm_period_ticks": ptc_pwm_model.period_ticks, "fan_duty": fan_duty, "fan_pwm_logic_high": fan_logic, "fan_pwm_drive_low": board_io.fan_pwm_drive_low(fan_logic), "fan_pwm_high_ticks": fan_pwm_model.high_ticks(fan_duty), "fan_pwm_period_ticks": fan_pwm_model.period_ticks, "tach_edge_count": tach_edges, "tach_window_edges": tach_edges, "rpm_estimate": tach_estimator.rpm_from_edges(tach_edges), "fault_code": command_v2.fault_code, "force_off": command.force_off, "reason": command.reason, "duty_or_level": command.duty_or_level, "safety_fault_latched": safety_state.fault_latched, }) reason_counts = Counter(command.reason for command in commands) for reason in [ ACTUATOR_REASON_OK, ACTUATOR_REASON_HOST_DISABLED, ACTUATOR_REASON_PID_OR_SENSOR_FAULT, ACTUATOR_REASON_CHANNEL_INVALID, ]: reason_counts.setdefault(reason, 0) duties = [command.duty_or_level for command in commands] per_channel_last_ctrl = {command.channel: command.duty_or_level for command in commands} per_channel_last_reason = {command.channel: command.reason for command in commands} per_channel_force_off = {command.channel: command.force_off for command in commands} return SensorReplayResult( sample_count=len(samples), command_count=len(commands), enabled_count=sum(1 for command in commands if command.enable), force_off_count=sum(1 for command in commands if command.force_off), reason_counts=dict(reason_counts), per_channel_last_ctrl=per_channel_last_ctrl, per_channel_last_reason=per_channel_last_reason, per_channel_force_off=per_channel_force_off, min_duty=min(duties) if duties else 0, max_duty=max(duties) if duties else 0, trace=trace, )