|
| 1 | +# SPDX-License-Identifier: MIT |
| 2 | +"""Cross-validation harness — proves Python evaluator matches golden vectors. |
| 3 | +
|
| 4 | +Each vector in tests/vectors/<name>/vector.json contains an inline ARB model, |
| 5 | +input facts/timestamps, and expected outputs. The Python evaluator is the |
| 6 | +reference implementation; these vectors will also be consumed by the C engine |
| 7 | +under Zephyr to prove cross-platform equivalence. |
| 8 | +
|
| 9 | +Tests: |
| 10 | + 1. Parametrised golden-vector evaluation (10+ vectors). |
| 11 | + 2. Determinism: same input, 100 runs → identical output. |
| 12 | + 3. Compile-to-C: each vector model compiles and the generated source |
| 13 | + contains the required ARBITER_generated_model symbol. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import json |
| 19 | +import tempfile |
| 20 | +from pathlib import Path |
| 21 | + |
| 22 | +import pytest |
| 23 | + |
| 24 | +from arbiter.compiler import CompileOptions, compile_model |
| 25 | +from arbiter.evaluator import ArbiterEvaluator |
| 26 | + |
| 27 | +VECTORS_DIR = Path(__file__).resolve().parent.parent / "vectors" |
| 28 | + |
| 29 | + |
| 30 | +# --------------------------------------------------------------------------- |
| 31 | +# Helpers |
| 32 | +# --------------------------------------------------------------------------- |
| 33 | + |
| 34 | + |
| 35 | +def _discover_vectors() -> list[str]: |
| 36 | + """Return sorted list of vector directory names that contain vector.json.""" |
| 37 | + if not VECTORS_DIR.exists(): |
| 38 | + return [] |
| 39 | + return sorted( |
| 40 | + d.name |
| 41 | + for d in VECTORS_DIR.iterdir() |
| 42 | + if d.is_dir() and (d / "vector.json").exists() |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +def _load_vector(name: str) -> dict: |
| 47 | + """Load and parse a vector.json file.""" |
| 48 | + path = VECTORS_DIR / name / "vector.json" |
| 49 | + return json.loads(path.read_text(encoding="utf-8")) |
| 50 | + |
| 51 | + |
| 52 | +def _run_vector(vec: dict) -> tuple[ArbiterEvaluator, dict]: |
| 53 | + """Run the Python evaluator on a vector and return (evaluator, result_dict).""" |
| 54 | + model_data = vec["model"] |
| 55 | + ev = ArbiterEvaluator(model_data) |
| 56 | + |
| 57 | + # Set fact values |
| 58 | + for fact_name, value in vec.get("facts", {}).items(): |
| 59 | + ev.set_fact(fact_name, value) |
| 60 | + |
| 61 | + # Set timestamps |
| 62 | + for fact_name, ms in vec.get("timestamps", {}).items(): |
| 63 | + ev.set_timestamp(fact_name, ms) |
| 64 | + |
| 65 | + # Set snapshot timestamp |
| 66 | + snap_ts = vec.get("snapshot_timestamp_ms", 0) |
| 67 | + if snap_ts: |
| 68 | + ev.set_snapshot_timestamp(snap_ts) |
| 69 | + |
| 70 | + result = ev.eval() |
| 71 | + return ev, result |
| 72 | + |
| 73 | + |
| 74 | +# --------------------------------------------------------------------------- |
| 75 | +# 1. Golden vector evaluation |
| 76 | +# --------------------------------------------------------------------------- |
| 77 | + |
| 78 | +_VECTOR_NAMES = _discover_vectors() |
| 79 | + |
| 80 | + |
| 81 | +@pytest.mark.parametrize("vector_name", _VECTOR_NAMES or ["_no_vectors_"]) |
| 82 | +def test_golden_vector(vector_name: str) -> None: |
| 83 | + """Evaluate each golden vector and assert output matches expected.""" |
| 84 | + if vector_name == "_no_vectors_": |
| 85 | + pytest.fail("No golden vectors found in tests/vectors/") |
| 86 | + |
| 87 | + vec = _load_vector(vector_name) |
| 88 | + expected = vec["expected"] |
| 89 | + |
| 90 | + ev, result = _run_vector(vec) |
| 91 | + |
| 92 | + # --- fired_rules: exact ordered list --- |
| 93 | + assert result.fired_rules == expected["fired_rules"], ( |
| 94 | + f"[{vector_name}] fired_rules mismatch" |
| 95 | + ) |
| 96 | + |
| 97 | + # --- current_mode --- |
| 98 | + assert result.current_mode == expected.get("current_mode"), ( |
| 99 | + f"[{vector_name}] current_mode mismatch" |
| 100 | + ) |
| 101 | + |
| 102 | + # --- raised_faults: sorted set comparison --- |
| 103 | + assert sorted(result.raised_faults) == sorted(expected.get("raised_faults", [])), ( |
| 104 | + f"[{vector_name}] raised_faults mismatch" |
| 105 | + ) |
| 106 | + |
| 107 | + # --- requested_actions: ordered list --- |
| 108 | + assert result.requested_actions == expected.get("requested_actions", []), ( |
| 109 | + f"[{vector_name}] requested_actions mismatch" |
| 110 | + ) |
| 111 | + |
| 112 | + # --- fact_values: spot-check only the facts listed in expected --- |
| 113 | + expected_facts = expected.get("fact_values", {}) |
| 114 | + for fact_name, expected_val in expected_facts.items(): |
| 115 | + actual = ev._fact_values.get(fact_name) |
| 116 | + assert actual == expected_val, ( |
| 117 | + f"[{vector_name}] fact {fact_name}: expected {expected_val}, got {actual}" |
| 118 | + ) |
| 119 | + |
| 120 | + |
| 121 | +# --------------------------------------------------------------------------- |
| 122 | +# 2. Determinism — same input, 100 runs, identical output |
| 123 | +# --------------------------------------------------------------------------- |
| 124 | + |
| 125 | + |
| 126 | +@pytest.mark.parametrize("vector_name", _VECTOR_NAMES[:3] or ["_no_vectors_"]) |
| 127 | +def test_determinism(vector_name: str) -> None: |
| 128 | + """Run the same vector 100 times and assert all outputs are identical.""" |
| 129 | + if vector_name == "_no_vectors_": |
| 130 | + pytest.skip("No vectors for determinism test") |
| 131 | + |
| 132 | + vec = _load_vector(vector_name) |
| 133 | + results: list[dict] = [] |
| 134 | + |
| 135 | + for _ in range(100): |
| 136 | + _, result = _run_vector(vec) |
| 137 | + results.append(result.to_dict()) |
| 138 | + |
| 139 | + baseline = results[0] |
| 140 | + for i, r in enumerate(results[1:], start=1): |
| 141 | + assert r == baseline, ( |
| 142 | + f"[{vector_name}] Non-deterministic result on iteration {i}" |
| 143 | + ) |
| 144 | + |
| 145 | + |
| 146 | +# --------------------------------------------------------------------------- |
| 147 | +# 3. Compile-to-C — verify each vector model compiles to valid C source |
| 148 | +# --------------------------------------------------------------------------- |
| 149 | + |
| 150 | + |
| 151 | +@pytest.mark.parametrize("vector_name", _VECTOR_NAMES or ["_no_vectors_"]) |
| 152 | +def test_compile_to_c(vector_name: str) -> None: |
| 153 | + """Compile each vector model to C and verify the source contains required symbols.""" |
| 154 | + if vector_name == "_no_vectors_": |
| 155 | + pytest.skip("No vectors for compile test") |
| 156 | + |
| 157 | + vec = _load_vector(vector_name) |
| 158 | + model_data = vec["model"] |
| 159 | + |
| 160 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 161 | + tmp = Path(tmpdir) |
| 162 | + # Write model as YAML for the compiler |
| 163 | + import yaml |
| 164 | + |
| 165 | + model_path = tmp / "model.arb.yaml" |
| 166 | + model_path.write_text( |
| 167 | + yaml.dump(model_data, default_flow_style=False), encoding="utf-8" |
| 168 | + ) |
| 169 | + |
| 170 | + opts = CompileOptions( |
| 171 | + out_c=tmp / "model.c", |
| 172 | + out_h=tmp / "model.h", |
| 173 | + ) |
| 174 | + result = compile_model(model_path, opts) |
| 175 | + |
| 176 | + assert result.success, ( |
| 177 | + f"[{vector_name}] Compilation failed: " |
| 178 | + + "; ".join( |
| 179 | + d.message |
| 180 | + for d in result.diagnostics.errors |
| 181 | + ) |
| 182 | + ) |
| 183 | + |
| 184 | + # Verify generated C source contains required symbols |
| 185 | + c_source = (tmp / "model.c").read_text(encoding="utf-8") |
| 186 | + h_source = (tmp / "model.h").read_text(encoding="utf-8") |
| 187 | + |
| 188 | + assert "ARBITER_generated_model" in c_source, ( |
| 189 | + f"[{vector_name}] Missing ARBITER_generated_model in C source" |
| 190 | + ) |
| 191 | + assert "ARBITER_generated_model" in h_source, ( |
| 192 | + f"[{vector_name}] Missing ARBITER_generated_model in header" |
| 193 | + ) |
| 194 | + assert "ARBITER_MODEL_HASH" in h_source, ( |
| 195 | + f"[{vector_name}] Missing ARBITER_MODEL_HASH in header" |
| 196 | + ) |
0 commit comments