Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions backend/tests/test_evidence_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""
from __future__ import annotations

import importlib.util
import json
import tomllib
from pathlib import Path
Expand All @@ -19,10 +20,20 @@
PROFILES_DIR = REPO_ROOT / "community" / "profiles"
EVIDENCE_DIR = REPO_ROOT / "docs" / "evidence"
LEDGER_PATH = EVIDENCE_DIR / "coverage.toml"
PACK_VALIDATOR_PATH = REPO_ROOT / "scripts" / "validate_evidence_packs.py"
MARKER = "needs verification"
VALID_STATUS = {"gap", "evidence"}


def _load_pack_validator():
spec = importlib.util.spec_from_file_location(
"validate_evidence_packs", PACK_VALIDATOR_PATH)
assert spec is not None and spec.loader is not None
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod) # type: ignore[union-attr]
return mod


def _collect_markers() -> set[tuple[str, str]]:
"""(profile_id, param_id) for every live marker; '*' = profile-level."""
out: set[tuple[str, str]] = set()
Expand Down Expand Up @@ -94,6 +105,7 @@ def test_gap_entries_reference_defined_gaps(ledger):


def test_evidence_entries_reference_real_packs(ledger):
pack_validator = _load_pack_validator()
for e in ledger.get("entry", []):
if e.get("status") == "evidence":
pack = EVIDENCE_DIR / e.get("evidence", "")
Expand All @@ -102,6 +114,20 @@ def test_evidence_entries_reference_real_packs(ledger):
f"{e.get('evidence')!r} not found in docs/evidence/"
)
json.loads(pack.read_text(encoding="utf-8")) # must parse
# Promotion discipline: a marker flips to evidence only on a
# real-car pass for that exact parameter — never on a fail or
# inconclusive capture, and never at the profile level ("*")
# where no single pack can prove a whole profile.
assert e["param"] != "*", (
f"{e['profile']}/*: profile-level markers are removed once "
"core params carry evidence, not promoted via one pack"
)
assert pack_validator.pack_has_passing_record(
pack, e["profile"], e["param"]
), (
f"{e['profile']}/{e['param']}: pack {e.get('evidence')!r} "
"holds no result=pass record for this parameter"
)


def test_gap_definitions_are_actionable(ledger):
Expand Down
148 changes: 148 additions & 0 deletions backend/tests/test_evidence_packs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""Tests for scripts/validate_evidence_packs.py.

The validator is the enforced half of the docs/evidence/ contracts
(schema.json for CAN broadcast packs, schema-uds.json for UDS DID packs).
These tests exercise the validator against in-test fixtures and validate
whatever real packs ship in docs/evidence/.
"""
from __future__ import annotations

import importlib.util
import json
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parents[2]
SCRIPT_PATH = REPO_ROOT / "scripts" / "validate_evidence_packs.py"


@pytest.fixture(scope="module")
def validator():
spec = importlib.util.spec_from_file_location(
"validate_evidence_packs", SCRIPT_PATH)
assert spec is not None and spec.loader is not None
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod) # type: ignore[union-attr]
return mod


@pytest.fixture(scope="module")
def profiles(validator):
return validator.load_profiles()


def _good_uds_record() -> dict:
"""A valid UDS record for b58/hpfp_rail (did:44F0, u16_tenths).

0x044C = 1100 -> u16_tenths -> 110.0 bar. Fixture only; not a real
capture and never shipped under docs/evidence/.
"""
return {
"profile": "b58",
"param": "hpfp_rail",
"did": "0x44F0",
"decode": "u16_tenths",
"request": "22 44 F0",
"response": [0x62, 0x44, 0xF0, 0x04, 0x4C],
"expected": {"value": 110.0, "unit": "bar"},
"result": "pass",
"vehicle": {"chassis": "G20", "engine": "B58"},
"firmware": {"sw": "08.14", "integration_level": "F020-21-03-500"},
"adapter": {"kind": "enet"},
"source": "validator fixture",
"captured_at": "2026-11-29T00:00:00Z",
}


def _uds_errors(validator, profiles, records):
return validator.validate_uds_records(records, "fixture.uds.json", profiles)


def test_repo_packs_are_valid(validator):
errors = validator.validate_repo_packs()
assert not errors, f"docs/evidence/ packs fail validation: {errors}"


def test_good_uds_record_passes(validator, profiles):
assert _uds_errors(validator, profiles, [_good_uds_record()]) == []


def test_missing_required_field_is_caught(validator, profiles):
rec = _good_uds_record()
del rec["adapter"]
errors = _uds_errors(validator, profiles, [rec])
assert any("adapter" in e for e in errors)


def test_decode_must_match_profile(validator, profiles):
rec = _good_uds_record()
rec["decode"] = "u16"
errors = _uds_errors(validator, profiles, [rec])
assert any("decode" in e for e in errors)


def test_did_must_match_profile_query(validator, profiles):
rec = _good_uds_record()
rec["did"] = "0x44F1"
rec["response"] = [0x62, 0x44, 0xF1, 0x04, 0x4C]
errors = _uds_errors(validator, profiles, [rec])
assert any("disagrees with profile query" in e for e in errors)


def test_pass_requires_positive_response(validator, profiles):
rec = _good_uds_record()
del rec["response"]
errors = _uds_errors(validator, profiles, [rec])
assert any("result=pass requires" in e for e in errors)


def test_response_echo_must_match_did(validator, profiles):
rec = _good_uds_record()
rec["response"] = [0x62, 0x44, 0xF1, 0x04, 0x4C]
errors = _uds_errors(validator, profiles, [rec])
assert any("DID echo" in e for e in errors)


def test_nrc_only_record_is_valid_evidence_of_failure(validator, profiles):
rec = _good_uds_record()
del rec["response"]
rec["nrc"] = "0x31"
rec["result"] = "fail"
assert _uds_errors(validator, profiles, [rec]) == []


def test_expected_requires_unit(validator, profiles):
rec = _good_uds_record()
rec["expected"] = {"value": 110.0}
errors = _uds_errors(validator, profiles, [rec])
assert any("unit" in e for e in errors)


def test_unknown_profile_is_caught(validator, profiles):
rec = _good_uds_record()
rec["profile"] = "w12"
errors = _uds_errors(validator, profiles, [rec])
assert any("unknown profile" in e for e in errors)


def test_obd_param_rejected_in_uds_pack(validator, profiles):
rec = _good_uds_record()
rec["profile"] = "n52"
rec["param"] = "fuel_rate_lh"
rec["did"] = "0x005E"
rec["decode"] = "u16_fiftieths"
rec["response"] = [0x62, 0x00, 0x5E, 0x01, 0x90]
errors = _uds_errors(validator, profiles, [rec])
assert any("did: query" in e for e in errors)


def test_pack_has_passing_record(validator, tmp_path):
pack = tmp_path / "b58.uds.json"
pack.write_text(json.dumps([_good_uds_record()]), encoding="utf-8")
assert validator.pack_has_passing_record(pack, "b58", "hpfp_rail")
assert not validator.pack_has_passing_record(pack, "b58", "maf")
fail_only = _good_uds_record()
fail_only["result"] = "fail"
pack.write_text(json.dumps([fail_only]), encoding="utf-8")
assert not validator.pack_has_passing_record(pack, "b58", "hpfp_rail")
51 changes: 44 additions & 7 deletions docs/evidence/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,50 @@ whose marker disappears fails, so the ledger cannot silently rot.

Today every entry is a named gap — no profile DID has a real-car
capture yet (`n55.example.json` is a simulator baseline for the CAN
broadcast decoders, adjacent but not DID validation). The gap
definitions name the record form that closes them: for UDS parameters,
a `<family>.uds.json` pack of DID request, raw positive-response
payload, expected decoded value and provenance; the schema extension
for that form is part of the January beat. To close a gap: land the
capture, flip the entry to `status = "evidence"`, and only then remove
the marker from the profile label.
broadcast decoders, adjacent but not DID validation). To close a gap:
land the capture, flip the entry to `status = "evidence"`, and only
then remove the marker from the profile label. The coverage guard
enforces the promotion discipline: an evidence entry must point at a
pack holding a `result = "pass"` record for that exact parameter —
a fail or inconclusive capture keeps the marker on, and profile-level
(`*`) markers are never promoted by a single pack.

## UDS DID packs

CAN broadcast packs (above) validate the decoders; UDS packs validate
the polled parameters that carry the `[needs verification]` markers.
One file per engine family: `docs/evidence/<family>.uds.json`, an array
of DID read records per `schema-uds.json`:

```json
[
{
"profile": "b58",
"param": "hpfp_rail",
"did": "0x44F0",
"decode": "u16_tenths",
"request": "22 44 F0",
"response": [98, 68, 240, 4, 76],
"expected": { "value": 110.0, "unit": "bar" },
"result": "pass",
"vehicle": { "chassis": "G20", "engine": "B58" },
"firmware": { "sw": "08.14", "integration_level": "F020-21-03-500" },
"adapter": { "kind": "enet" },
"source": "real-car capture via ENET, cross-checked against ISTA",
"captured_at": "2026-12-14T10:30:00Z"
}
]
```

Every record identifies chassis, firmware, adapter, parameter, units
and result — the update-3 identity contract. `did` and `decode` must
match the profile's own claims; `response` is the full raw positive
response including the `0x62` service byte and DID echo. A DID the car
refuses is evidence too: record the `nrc` with `result = "fail"` — it
keeps the marker on with proof instead of silence.
`scripts/validate_evidence_packs.py` checks all of this, cross-references
each record against the profile it claims, and runs in CI via
`backend/tests/test_evidence_packs.py`.

## Security

Expand Down
109 changes: 109 additions & 0 deletions docs/evidence/schema-uds.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://beemuu.com/evidence/schema-uds.json",
"title": "Beemuu UDS Evidence Pack",
"description": "Real-car UDS readDataByIdentifier capture with expected decoder output, for the v0.22 evidence program (update 3). One file per engine family: docs/evidence/<family>.uds.json. The companion CAN broadcast format lives in schema.json; this schema covers polled DID reads, the shape that retires [needs verification] markers in community/profiles/*.toml.",
"type": "array",
"items": {
"type": "object",
"required": ["profile", "param", "did", "decode", "expected", "result", "vehicle", "firmware", "adapter", "source", "captured_at"],
"properties": {
"profile": {
"type": "string",
"pattern": "^[a-z0-9_]+$",
"description": "Community profile id the parameter belongs to (e.g. b58). Must match a community/profiles/<id>.toml profile."
},
"param": {
"type": "string",
"pattern": "^[a-z0-9_]+$",
"description": "Parameter id within that profile (e.g. hpfp_rail)."
},
"did": {
"type": "string",
"pattern": "^0x[0-9A-Fa-f]{4}$",
"description": "The DID read, as a hex string (e.g. 0x44F0). Must equal the profile param's did: query."
},
"decode": {
"type": "string",
"minLength": 2,
"description": "Decode function the record claims (e.g. u16_tenths). Must equal the profile param's decode."
},
"request": {
"type": "string",
"description": "Human-readable request bytes sent (e.g. \"22 44 F0\"). Optional context; response is the normative capture."
},
"response": {
"type": "array",
"items": { "type": "integer", "minimum": 0, "maximum": 255 },
"minItems": 4,
"description": "Full raw positive response, including the 0x62 service byte and DID echo (e.g. [0x62, 0x44, 0xF0, 0x01, 0x2C]). Required when result is pass."
},
"nrc": {
"type": "string",
"pattern": "^0x[0-9A-Fa-f]{2}$",
"description": "Negative response code instead of a positive response (e.g. 0x31 requestOutOfRange). A DID the car refuses is evidence too — record it with result fail or inconclusive."
},
"expected": {
"type": "object",
"required": ["value", "unit"],
"properties": {
"value": { "type": ["number", "boolean", "string"] },
"unit": { "type": "string", "minLength": 0 }
},
"description": "Decoded value the profile's decode MUST produce from this payload, and its unit. Units are part of the claim: a record without a unit cannot retire a marker."
},
"result": {
"type": "string",
"enum": ["pass", "fail", "inconclusive"],
"description": "pass = car answered and decoded value matched the known-good reference. fail = car refused the DID or the decode disagreed with the reference (keeps the marker on). inconclusive = captured but no trustworthy reference at capture time."
},
"vehicle": {
"type": "object",
"required": ["chassis"],
"properties": {
"vin": { "type": "string", "minLength": 17, "maxLength": 17 },
"wmi": { "type": "string", "minLength": 3, "maxLength": 3 },
"serial_last6": { "type": "string", "minLength": 6, "maxLength": 6 },
"engine": { "type": "string" },
"chassis": { "type": "string", "minLength": 2 }
},
"description": "Vehicle identification. Chassis is required (e.g. G20); VIN preferred, WMI+serial_last6 acceptable for privacy."
},
"firmware": {
"type": "object",
"minProperties": 1,
"properties": {
"ecu": { "type": "string" },
"hw": { "type": "string" },
"sw": { "type": "string" },
"integration_level": { "type": "string" }
},
"description": "Firmware identity of the answering ECU — at least one of sw / hw / integration_level. DID applicability can change across integration levels; a record without firmware identity cannot be reproduced."
},
"adapter": {
"type": "object",
"required": ["kind"],
"properties": {
"kind": { "type": "string", "enum": ["enet", "kdcan"] },
"cable": { "type": "string" },
"latency_timer_ms": { "type": "integer", "minimum": 1 }
},
"description": "Capture path. kind is required; K+DCAN records should carry latency_timer_ms (the repo invariant is 1 ms)."
},
"source": {
"type": "string",
"minLength": 5,
"description": "Provenance: who captured, with what tool, cross-checked against what reference (e.g. ISTA, INPA, known-good scanner)."
},
"captured_at": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 timestamp of the capture."
},
"notes": {
"type": "string",
"description": "Capture conditions (engine warm/cold, idle/load) and anything a reviewer needs to reproduce."
}
}
}
}
2 changes: 1 addition & 1 deletion docs/product_calendar.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
|---|---|---|
| Nov 30 – Dec 6 | Update 2 close-out: physical adapter health probe design note; real-cable recovery checklist (K+DCAN on E70, ENET on F/G) — both landed early (Nov 28, `docs/adapter-health-probe.md` + checklist staged) | Done Nov 28 — all eleven polling paths have a stated freshness story in `docs/connection-recovery.md` |
| Dec 7 – 13 | Update 2 real-cable recovery pass on the bench car | Reconnect after cable pull recovers without app restart, or the failure is documented and surfaced |
| Dec 14 – 20 | Update 3 open: hardware validation and coverage — evidence-record schema (chassis, firmware, adapter, parameter, units, result) | Schema reviewed against the existing `docs/evidence/` skeleton; no unverified coverage promoted |
| Dec 14 – 20 | Update 3 open: hardware validation and coverage — evidence-record schema (chassis, firmware, adapter, parameter, units, result) — landed early (Nov 29, `docs/evidence/schema-uds.json` + validator + CI guard) | Schema reviewed against the existing `docs/evidence/` skeleton; no unverified coverage promoted |
| Dec 21 – Jan 4 | Holiday pause. Community call for N52/N54/N62 bench reports (`docs/validation/n5x-real-car.md`, `n62-real-car.md`) | At least the call posted; reports are opportunistic, not gated |

**Release candidate:** none. Update 2 closes into whatever version the
Expand Down
Loading
Loading