Просмотр исходного кода

test(control): add bit-exact 6400 PI differential

root 3 месяцев назад
Родитель
Сommit
d27256fb22

+ 5 - 2
src/control/thermal_control_core.v

@@ -392,8 +392,11 @@ module thermal_control_core #(
                             safety_override_mask[work_index] <= 1;
                             ptc_shutdown_mask[work_index] <= 1;
                             thermal_protection_mask[work_index] <= 0;
-                            previous_error[work_index] <= 0;
-                            previous_output[work_index] <= 0;
+                            // A single invalid sample quarantines the physical
+                            // PTC but freezes, rather than clears, its PI state.
+                            // This permits a bumpless resume when that channel
+                            // becomes valid again; lane/global clamps below
+                            // still clear hidden state before fault recovery.
                             epoch_safe <= 0;
                             control_state <= SENSOR_DEGRADED;
                             case (lane_for_channel(work_index))

+ 60 - 0
tests/cocotb/run_6400_pi_differential.py

@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+"""Run L7 bit-exact thermal-control-lab versus production RTL differential."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import tempfile
+import xml.etree.ElementTree as ET
+
+try:
+    from cocotb_tools.runner import get_runner
+except ModuleNotFoundError:
+    from cocotb.runner import get_runner
+
+
+ROOT = Path(__file__).resolve().parents[2]
+TEST_DIR = Path(__file__).resolve().parent
+
+
+def main() -> int:
+    lab = ROOT.parent / "thermal-control-lab" / "thermal_control_lab" / "fixed_point" / "pi.py"
+    if not lab.is_file():
+        raise RuntimeError(f"thermal-control-lab reference model is missing: {lab}")
+    with tempfile.TemporaryDirectory(prefix="prod2u-6400-pi-differential-") as directory:
+        build_dir = Path(directory)
+        os.environ["HYPOTHESIS_STORAGE_DIRECTORY"] = str(build_dir / "hypothesis")
+        runner = get_runner("icarus")
+        runner.build(
+            sources=[
+                ROOT / "src/control/thermal_control_core.v",
+                TEST_DIR / "thermal_control_core_cocotb_top.v",
+            ],
+            hdl_toplevel="thermal_control_core_cocotb_top",
+            build_dir=build_dir,
+            build_args=["-g2012"],
+            always=True,
+        )
+        result = Path(runner.test(
+            hdl_toplevel="thermal_control_core_cocotb_top",
+            test_module="test_6400_pi_differential",
+            test_dir=TEST_DIR,
+            build_dir=build_dir,
+            results_xml=str(build_dir / "results.xml"),
+        ))
+        root = ET.parse(result).getroot()
+        cases = root.findall(".//testcase")
+        failures = root.findall(".//failure") + root.findall(".//error")
+        skipped = root.findall(".//skipped")
+        if not cases or failures or skipped:
+            raise RuntimeError(
+                f"PI differential incomplete: cases={len(cases)} failures={len(failures)} "
+                f"skipped={len(skipped)} results={result}"
+            )
+    print("PASS: L7 bit-exact Python/RTL PI differential")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 339 - 0
tests/cocotb/test_6400_pi_differential.py

@@ -0,0 +1,339 @@
+"""L7 bit-exact differential checks against the thermal-control-lab model."""
+
+from __future__ import annotations
+
+from pathlib import Path
+import sys
+
+import cocotb
+from cocotb.triggers import FallingEdge, ReadOnly, RisingEdge, Timer, with_timeout
+
+
+ROOT = Path(__file__).resolve().parents[2]
+LAB_ROOT = ROOT.parent / "thermal-control-lab"
+if not LAB_ROOT.is_dir():
+    raise RuntimeError(f"thermal-control-lab sibling is required for L7: {LAB_ROOT}")
+sys.path.insert(0, str(LAB_ROOT))
+
+from thermal_control_lab.fixed_point import ControllerBank, PIConfig  # noqa: E402
+
+
+FULL_VALID = (1 << 24) - 1
+
+
+def raw_from_centi(value: int) -> int:
+    if not 0 <= value <= 25_499:
+        raise ValueError(f"BMC test temperature out of range: {value}")
+    integer, fraction = divmod(value, 100)
+    return (integer << 8) | fraction
+
+
+def errors_for(target_c: int, temperatures: list[int]) -> list[int]:
+    return [target_c * 100 - value for value in temperatures]
+
+
+async def clock_cycles(dut, count: int) -> None:
+    for _ in range(count):
+        await RisingEdge(dut.sys_clk)
+
+
+async def wait_for(dut, predicate, *, cycles: int, label: str) -> None:
+    for _ in range(cycles):
+        await RisingEdge(dut.sys_clk)
+        await ReadOnly()
+        if predicate():
+            return
+    raise AssertionError(f"timeout waiting for {label}")
+
+
+async def load_temperatures(dut, temperatures: list[int]) -> None:
+    assert len(temperatures) == 24
+    await FallingEdge(dut.sys_clk)
+    dut.bmc_wr_en.value = 1
+    for index, value in enumerate(temperatures):
+        dut.bmc_wr_index.value = index
+        dut.bmc_wr_raw.value = raw_from_centi(value)
+        await FallingEdge(dut.sys_clk)
+    dut.bmc_wr_en.value = 0
+
+
+async def set_epoch(
+    dut,
+    epoch: int,
+    temperatures: list[int],
+    *,
+    valid_mask: int = FULL_VALID,
+) -> None:
+    await load_temperatures(dut, temperatures)
+    await FallingEdge(dut.sys_clk)
+    dut.bmc_valid_mask_test.value = valid_mask
+    dut.bmc_epoch_test.value = epoch & 0xFFFF
+
+
+async def wait_commit(dut, previous_count: int, label: str) -> None:
+    await wait_for(
+        dut,
+        lambda: int(dut.commit_count_mon.value) > previous_count,
+        cycles=500,
+        label=label,
+    )
+
+
+async def read_outputs(dut) -> tuple[list[int], list[int], list[int], list[int]]:
+    requested: list[int] = []
+    applied: list[int] = []
+    previous_error: list[int] = []
+    previous_output: list[int] = []
+    await FallingEdge(dut.sys_clk)
+    for index in range(32):
+        dut.rd_index.value = index
+        await Timer(1, units="ns")
+        requested.append(int(dut.requested_data.value))
+        applied.append(int(dut.applied_data.value))
+        if index < 24:
+            error = int(dut.previous_error_data.value)
+            previous_error.append(error - 0x10000 if error & 0x8000 else error)
+            previous_output.append(int(dut.previous_output_data.value))
+    return requested, applied, previous_error, previous_output
+
+
+async def compare_epoch(
+    dut,
+    model: ControllerBank,
+    epoch: int,
+    temperatures: list[int],
+    *,
+    target_c: int = 70,
+    valid_mask: int = FULL_VALID,
+    override: list[bool] | None = None,
+    expected_fans: list[int] | None = None,
+    label: str,
+) -> tuple[list[int], list[int]]:
+    before = int(dut.commit_count_mon.value)
+    await set_epoch(dut, epoch, temperatures, valid_mask=valid_mask)
+    await wait_commit(dut, before, label)
+    valid = [bool(valid_mask & (1 << index)) for index in range(24)]
+    expected = model.update(
+        epoch,
+        errors_for(target_c, temperatures),
+        valid,
+        safety_override=override,
+    )
+    requested, applied, previous_error, previous_output = await read_outputs(dut)
+    assert applied[:24] == expected, f"{label}: applied RTL/Python mismatch"
+    assert all(0 <= value <= 100 for value in requested + applied)
+    if override is None and valid_mask == FULL_VALID:
+        assert requested[:24] == expected, f"{label}: requested RTL/Python mismatch"
+        expected_state_error = [state.previous_error_centi for state in model.states]
+        expected_state_output = [state.previous_output_q8_8 for state in model.states]
+        assert previous_error == expected_state_error, f"{label}: error-state mismatch"
+        assert previous_output == expected_state_output, f"{label}: output-state mismatch"
+    fans = expected_fans or [30] * 8
+    assert applied[24:] == fans, f"{label}: fan safety mismatch"
+    return requested, applied
+
+
+async def bootstrap_auto(dut, temperatures: list[int], start_epoch: int = 1) -> int:
+    await wait_for(
+        dut,
+        lambda: int(dut.control_state.value) == 2,
+        cycles=50,
+        label="PREHEAT_CT",
+    )
+    await set_epoch(dut, start_epoch, temperatures)
+    await wait_for(
+        dut,
+        lambda: int(dut.control_state.value) == 3,
+        cycles=50,
+        label="WAIT_BMC_STABLE",
+    )
+    for epoch in (start_epoch + 1, start_epoch + 2):
+        await set_epoch(dut, epoch, temperatures)
+        await clock_cycles(dut, 8)
+    return start_epoch + 3
+
+
+@cocotb.test()
+async def test_pi_python_rtl_differential_safety_epoch_target_and_recovery(dut):
+    dut.tick_1s_test.value = 0
+    dut.target_commit_test.value = 0
+    dut.target_celsius_test.value = 70
+    dut.bmc_epoch_test.value = 0
+    dut.bmc_stale_test.value = 0
+    dut.bmc_valid_mask_test.value = FULL_VALID
+    dut.bmc_wr_en.value = 0
+    dut.bmc_wr_index.value = 0
+    dut.bmc_wr_raw.value = 0
+    dut.ct_epoch_test.value = 1
+    dut.ct_stale_test.value = 0
+    dut.ct_valid_mask_test.value = (1 << 27) - 1
+    dut.rd_index.value = 0
+    await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
+
+    model = ControllerBank(PIConfig(32, 4), PIConfig(24, 3))
+    temperatures = [6500 + ((index * 37) % 400) for index in range(24)]
+    epoch = await bootstrap_auto(dut, temperatures)
+    await compare_epoch(dut, model, epoch, temperatures, label="initial mixed edge/center pass")
+
+    # The same BMC epoch is a strict hold: no reintegration and no new bank flip.
+    held_commit = int(dut.commit_count_mon.value)
+    held_outputs = (await read_outputs(dut))[1]
+    assert model.update(epoch, errors_for(70, temperatures), [True] * 24) == held_outputs[:24]
+    await clock_cycles(dut, 300)
+    assert int(dut.commit_count_mon.value) == held_commit
+    assert (await read_outputs(dut))[1] == held_outputs
+
+    # Mixed fractional errors cover both coefficient classes and half-away
+    # rounding.  Repeated cold epochs then hit slew and upper anti-windup.
+    epoch += 1
+    temperatures = [6999 - ((index * 7) % 180) for index in range(24)]
+    await compare_epoch(dut, model, epoch, temperatures, label="fractional rounding")
+    for iteration in range(24):
+        epoch += 1
+        temperatures = [2000 + ((index * 11 + iteration) % 90) for index in range(24)]
+        await compare_epoch(dut, model, epoch, temperatures, label=f"positive slew {iteration}")
+    assert max(model.outputs_q8_8) == 25_600
+
+    # Hold at saturation, then prove the negative slew path is equally exact.
+    for iteration in range(2):
+        epoch += 1
+        await compare_epoch(dut, model, epoch, temperatures, label=f"anti-windup hold {iteration}")
+    for iteration in range(5):
+        epoch += 1
+        temperatures = [7399 - (index % 5) for index in range(24)]
+        await compare_epoch(dut, model, epoch, temperatures, label=f"negative slew {iteration}")
+
+    # A single invalid channel is off while its PI state freezes.  When the
+    # channel becomes valid, the Python and RTL paths resume from that state.
+    invalid_mask = FULL_VALID ^ 1
+    frozen_state = model.states[0]
+    epoch += 1
+    await compare_epoch(
+        dut,
+        model,
+        epoch,
+        temperatures,
+        valid_mask=invalid_mask,
+        label="single invalid freeze",
+    )
+    assert model.states[0] == frozen_state
+    temperatures = [7100] * 24
+    for iteration in range(3):
+        epoch += 1
+        await compare_epoch(dut, model, epoch, temperatures, label=f"invalid recovery {iteration}")
+    assert int(dut.control_state.value) == 4
+
+    # Pretrip clears one production controller, forces its PTC off, and raises
+    # both lane fans.  The reference is explicitly rebased for safe recovery.
+    epoch += 1
+    temperatures = [6900] * 24
+    temperatures[6] = 7600
+    override = [index == 6 for index in range(24)]
+    await compare_epoch(
+        dut,
+        model,
+        epoch,
+        temperatures,
+        override=override,
+        expected_fans=[30, 80, 30, 30, 30, 80, 30, 30],
+        label="76 C pretrip",
+    )
+    model.clear_channels([6])
+    temperatures = [6900] * 24
+    for iteration in range(3):
+        epoch += 1
+        await compare_epoch(dut, model, epoch, temperatures, label=f"pretrip recovery {iteration}")
+
+    # A 77 C sample clamps and clears the complete six-channel lane.  Three
+    # safe epochs retain zero duty; the next epoch ramps from the cleared state.
+    epoch += 1
+    temperatures[12] = 7700
+    lane_override = [12 <= index < 18 for index in range(24)]
+    await compare_epoch(
+        dut,
+        model,
+        epoch,
+        temperatures,
+        override=lane_override,
+        expected_fans=[30, 30, 100, 30, 30, 30, 100, 30],
+        label="77 C lane hard clamp",
+    )
+    assert int(dut.lane_fault_mask.value) & (1 << 2)
+    model.clear_channels(range(12, 18))
+    temperatures[12] = 6900
+    for iteration in range(3):
+        epoch += 1
+        recovery_fans = (
+            [30, 30, 100, 30, 30, 30, 100, 30]
+            if iteration < 2
+            else [30] * 8
+        )
+        await compare_epoch(
+            dut,
+            model,
+            epoch,
+            temperatures,
+            override=lane_override,
+            expected_fans=recovery_fans,
+            label=f"hard-clamp recovery hold {iteration}",
+        )
+    assert int(dut.lane_fault_mask.value) == 0
+    epoch += 1
+    await compare_epoch(dut, model, epoch, temperatures, label="hard-clamp limited restart")
+
+    # Runtime stale preempts without a new epoch, atomically fills 0/100 safe
+    # outputs, and requires three fresh recovery epochs before limited restart.
+    before = int(dut.commit_count_mon.value)
+    await FallingEdge(dut.sys_clk)
+    dut.bmc_stale_test.value = 1
+    await wait_commit(dut, before, "global stale safe fill")
+    _, stale_applied, _, _ = await read_outputs(dut)
+    assert stale_applied == [0] * 24 + [100] * 8
+    assert model.update(epoch, errors_for(70, temperatures), [True] * 24, stale=True) == [0] * 24
+    model.stop()
+    await FallingEdge(dut.sys_clk)
+    dut.bmc_stale_test.value = 0
+    all_override = [True] * 24
+    for iteration in range(3):
+        epoch += 1
+        recovery_fans = [100] * 8 if iteration < 2 else [30] * 8
+        await compare_epoch(
+            dut,
+            model,
+            epoch,
+            temperatures,
+            override=all_override,
+            expected_fans=recovery_fans,
+            label=f"stale recovery hold {iteration}",
+        )
+    assert int(dut.global_fault.value) == 0
+    epoch += 1
+    await compare_epoch(dut, model, epoch, temperatures, label="stale limited restart")
+
+    # Target changes clear the PI path, commit a safe image, and require the
+    # CT/BMC qualification sequence before the new-target Python path runs.
+    before = int(dut.commit_count_mon.value)
+    await FallingEdge(dut.sys_clk)
+    dut.target_celsius_test.value = 60
+    dut.target_commit_test.value = 1
+    await FallingEdge(dut.sys_clk)
+    dut.target_commit_test.value = 0
+    await wait_commit(dut, before, "target-change safe fill")
+    assert (await read_outputs(dut))[1][:24] == [0] * 24
+    model.stop()
+    await FallingEdge(dut.sys_clk)
+    dut.ct_epoch_test.value = 2
+    temperatures = [5500 + (index % 20) for index in range(24)]
+    next_epoch = await bootstrap_auto(dut, temperatures, start_epoch=epoch + 1)
+    await compare_epoch(
+        dut,
+        model,
+        next_epoch,
+        temperatures,
+        target_c=60,
+        label="new-target qualified restart",
+    )
+
+    assert int(dut.current_target_celsius.value) == 60
+    assert int(dut.control_state.value) == 4
+    assert int(dut.work_state_mon.value) == 0

+ 108 - 0
tests/cocotb/thermal_control_core_cocotb_top.v

@@ -0,0 +1,108 @@
+`timescale 1ns/1ps
+
+module thermal_control_core_cocotb_top (
+    input  wire        tick_1s_test,
+    input  wire        target_commit_test,
+    input  wire [7:0]  target_celsius_test,
+    input  wire [15:0] bmc_epoch_test,
+    input  wire        bmc_stale_test,
+    input  wire [23:0] bmc_valid_mask_test,
+    input  wire        bmc_wr_en,
+    input  wire [4:0]  bmc_wr_index,
+    input  wire [15:0] bmc_wr_raw,
+    input  wire [15:0] ct_epoch_test,
+    input  wire        ct_stale_test,
+    input  wire [26:0] ct_valid_mask_test,
+    input  wire [4:0]  rd_index,
+    output wire        sys_clk,
+    output reg         rst_n_mon = 1'b0,
+    output wire [7:0]  requested_data,
+    output wire [7:0]  applied_data,
+    output wire [15:0] previous_error_data,
+    output wire [15:0] previous_output_data,
+    output wire        active_output_bank,
+    output wire [2:0]  control_state,
+    output wire [3:0]  work_state_mon,
+    output wire [7:0]  current_target_celsius,
+    output wire [15:0] control_epoch,
+    output wire [23:0] safety_override_mask,
+    output wire [3:0]  lane_fault_mask,
+    output wire        global_fault,
+    output wire        output_commit,
+    output reg  [15:0] commit_count_mon = 0
+);
+    reg clk = 1'b0;
+    reg [3:0] reset_count = 0;
+    reg [15:0] bmc_mem [0:23];
+    wire [4:0] bmc_rd_index;
+    wire [15:0] bmc_rd_raw = bmc_mem[bmc_rd_index];
+    wire bmc_rd_valid = bmc_valid_mask_test[bmc_rd_index];
+    wire [7:0] pwm_rd_data;
+    wire host_target_seen;
+    wire stimulus_active;
+    integer i;
+
+    always #20 clk = ~clk;
+    assign sys_clk = clk;
+
+    always @(posedge clk) begin
+        if (reset_count < 8) begin
+            reset_count <= reset_count + 1'b1;
+            rst_n_mon <= 1'b0;
+        end else begin
+            rst_n_mon <= 1'b1;
+        end
+        if (!rst_n_mon) begin
+            for (i = 0; i < 24; i = i + 1) bmc_mem[i] <= 16'd0;
+            commit_count_mon <= 0;
+        end else begin
+            if (bmc_wr_en && bmc_wr_index < 24) bmc_mem[bmc_wr_index] <= bmc_wr_raw;
+            if (output_commit) commit_count_mon <= commit_count_mon + 1'b1;
+        end
+    end
+
+    thermal_control_core u_dut (
+        .clk(clk),
+        .rst_n(rst_n_mon),
+        .tick_1s(tick_1s_test),
+        .target_commit(target_commit_test),
+        .target_celsius(target_celsius_test),
+        .stimulus_wr_en(1'b0),
+        .stimulus_wr_addr(5'd0),
+        .stimulus_wr_data(8'd0),
+        .stimulus_commit(1'b0),
+        .stimulus_duration_seconds(8'd0),
+        .bmc_epoch(bmc_epoch_test),
+        .bmc_stale(bmc_stale_test),
+        .bmc_valid_mask(bmc_valid_mask_test),
+        .bmc_rd_index(bmc_rd_index),
+        .bmc_rd_raw(bmc_rd_raw),
+        .bmc_rd_valid(bmc_rd_valid),
+        .ct_epoch(ct_epoch_test),
+        .ct_stale(ct_stale_test),
+        .ct_valid_mask(ct_valid_mask_test),
+        .snapshot_lock(1'b0),
+        .snapshot_lock_bank(1'b0),
+        .pwm_rd_addr(rd_index),
+        .pwm_rd_data(pwm_rd_data),
+        .snapshot_output_bank(active_output_bank),
+        .snapshot_rd_addr(rd_index),
+        .snapshot_requested_data(requested_data),
+        .snapshot_applied_data(applied_data),
+        .active_output_bank(active_output_bank),
+        .control_state(control_state),
+        .current_target_celsius(current_target_celsius),
+        .host_target_seen(host_target_seen),
+        .control_epoch(control_epoch),
+        .safety_override_mask(safety_override_mask),
+        .lane_fault_mask(lane_fault_mask),
+        .global_fault(global_fault),
+        .output_commit(output_commit),
+        .stimulus_active(stimulus_active)
+    );
+
+    assign work_state_mon = u_dut.work_state;
+    assign previous_error_data = (rd_index < 24) ? u_dut.previous_error[rd_index] : 16'd0;
+    assign previous_output_data = (rd_index < 24) ? u_dut.previous_output[rd_index] : 16'd0;
+    wire unused = &{1'b0, pwm_rd_data, host_target_seen, stimulus_active};
+endmodule

+ 7 - 1
tools/run_6400_v1.py

@@ -101,11 +101,15 @@ def bmc_fuzz() -> None:
     run(["python3", "tests/cocotb/run_6400_bmc_fuzz.py"])
 
 
+def pi_differential() -> None:
+    run(["python3", "tests/cocotb/run_6400_pi_differential.py"])
+
+
 def main() -> int:
     parser = argparse.ArgumentParser()
     parser.add_argument(
         "action",
-        choices=("generate", "lint", "sim", "cocotb", "bmc", "pwm", "unit", "all"),
+        choices=("generate", "lint", "sim", "cocotb", "bmc", "pwm", "pi", "unit", "all"),
     )
     args = parser.parse_args()
     if args.action in ("generate", "all"):
@@ -120,6 +124,8 @@ def main() -> int:
         cocotb_integration()
     if args.action in ("bmc", "all"):
         bmc_fuzz()
+    if args.action in ("pi", "all"):
+        pi_differential()
     if args.action in ("unit", "all"):
         unit()
     return 0