| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704 |
- #!/usr/bin/env python3
- """Offline validator for the Prod2U P4 evidence, campaign, and final gate JSON."""
- from __future__ import annotations
- import argparse
- import json
- import math
- import re
- import sys
- from pathlib import Path
- from typing import Any, Mapping, Sequence
- SCHEMAS = {
- "evidence": "prod2u-p4-evidence-v2",
- "campaign": "prod2u-p4-campaign-v2",
- "final_gate": "prod2u-p4-final-gate-v2",
- }
- FAN_STATUSES = {"detected", "absent", "intermittent"}
- LAYER_STATUSES = {"pass", "fail", "blocked", "not_run"}
- SPEARMAN_MIN = 0.60
- ROUND_COUNT = 10
- FAN_SETTINGS = (0, 20, 40, 60, 80, 100)
- TREND_SETTINGS = (20, 40, 60, 80, 100)
- LOW_SETTINGS = (20, 40)
- HIGH_SETTINGS = (80, 100)
- SAMPLES_PER_SETTING = 5
- SETTLE_WINDOWS_PER_SETTING = 2
- WINDOWS_PER_ROUND = len(FAN_SETTINGS) * (SAMPLES_PER_SETTING + SETTLE_WINDOWS_PER_SETTING)
- REQUIRED_DYNAMIC_LAYERS = (
- "program_sram",
- "fresh_ready",
- "host_ack",
- "pwm_state",
- "fan3_tach_trend",
- "timeout_fallback",
- "disable",
- "ptc_command_path",
- )
- REQUIRED_STATIC_LAYERS = (
- "source",
- "protocol",
- "rtl",
- "formal",
- "td_normal",
- "td_trace",
- "package",
- )
- STATIC_LAYER_ARTIFACTS = {
- "source": ("normal_source_manifest", "trace_source_manifest"),
- "protocol": ("protocol_junit",),
- "rtl": ("rtl_sim_receipt",),
- "formal": ("formal_receipt",),
- "td_normal": ("normal_td_receipt",),
- "td_trace": ("trace_td_receipt",),
- "package": ("package_manifest", "package_inventory", "static_receipt"),
- }
- SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
- IDENTITY_FIELDS = ("dut_id", "build_id", "bitstream_sha256", "variant", "profile", "source_manifest_sha256")
- BOUND_ARTIFACTS = (
- "programmer_receipt",
- "pre_program_raw",
- "combined_rx_raw",
- "raw_transcript",
- "td_receipt",
- "source_manifest",
- "package_manifest",
- "package_inventory",
- )
- EVIDENCE_REQUIRED = (
- "schema",
- "evidence_id",
- "campaign_id",
- "campaign_identity",
- "round",
- "identity",
- "bmc",
- "layers",
- "fan",
- "windows",
- "raw_samples",
- "correlation",
- "rpm",
- "ptc",
- "evidence_binding",
- )
- FINAL_GATE_REQUIRED = (
- "schema",
- "status",
- "campaign_id",
- "campaign_identity",
- "bmc",
- "qualification",
- "layers",
- "round_count",
- "evidence_bindings",
- "failures",
- )
- def _mapping(value: Any) -> Mapping[str, Any]:
- return value if isinstance(value, Mapping) else {}
- def _number(value: Any) -> float | None:
- if isinstance(value, bool) or not isinstance(value, (int, float)):
- return None
- result = float(value)
- return result if math.isfinite(result) else None
- def _rank(values: Sequence[float]) -> list[float]:
- ordered = sorted((value, index) for index, value in enumerate(values))
- ranks = [0.0] * len(values)
- position = 0
- while position < len(ordered):
- end = position + 1
- while end < len(ordered) and ordered[end][0] == ordered[position][0]:
- end += 1
- average = (position + 1 + end) / 2.0
- for _, index in ordered[position:end]:
- ranks[index] = average
- position = end
- return ranks
- def spearman_rho(x_values: Sequence[float], y_values: Sequence[float]) -> float | None:
- """Return Spearman rank correlation without scipy or another dependency."""
- if len(x_values) != len(y_values) or len(x_values) < 2:
- return None
- x_rank = _rank(x_values)
- y_rank = _rank(y_values)
- x_mean = sum(x_rank) / len(x_rank)
- y_mean = sum(y_rank) / len(y_rank)
- numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_rank, y_rank))
- x_denominator = math.sqrt(sum((x - x_mean) ** 2 for x in x_rank))
- y_denominator = math.sqrt(sum((y - y_mean) ** 2 for y in y_rank))
- if x_denominator == 0 or y_denominator == 0:
- return None
- return numerator / (x_denominator * y_denominator)
- def _validate_layers(layers: Any, round_number: int | None = None) -> list[str]:
- failures: list[str] = []
- payload = _mapping(layers)
- required = _mapping(payload.get("required"))
- optional = _mapping(payload.get("optional"))
- prefix = f"{round_number}:" if round_number is not None else ""
- if not required:
- failures.append(f"required_layers_missing:{prefix[:-1] if prefix else 'campaign'}")
- for name in REQUIRED_DYNAMIC_LAYERS:
- if name not in required:
- failures.append(f"required_layer_missing:{prefix}{name}" if prefix else f"required_layer_missing:campaign:{name}")
- for name, status in required.items():
- if status not in LAYER_STATUSES:
- failures.append(f"invalid_layer_status:{prefix}{name}")
- elif status != "pass":
- failures.append(f"required_layer_not_pass:{prefix}{name}")
- for name, status in optional.items():
- if status not in LAYER_STATUSES:
- failures.append(f"invalid_optional_layer_status:{prefix}{name}")
- return failures
- def _validate_windows(windows: Any, round_number: int) -> list[str]:
- failures: list[str] = []
- if not isinstance(windows, list) or not windows:
- return [f"windows_missing:{round_number}"]
- if len(windows) != WINDOWS_PER_ROUND:
- failures.append(f"windows_count:{round_number}:{len(windows)}")
- previous_end: float | None = None
- previous_index: int | None = None
- previous_snapshot_seq: int | None = None
- for expected_index, item in enumerate(windows):
- window = _mapping(item)
- index = window.get("index", window.get("window_index"))
- start = _number(window.get("start_s"))
- end = _number(window.get("end_s"))
- continuous = window.get("continuous")
- snapshot_seq = window.get("snapshot_seq")
- overflow_mask = window.get("overflow_mask")
- if not isinstance(index, int) or isinstance(index, bool) or start is None or end is None or end <= start:
- failures.append(f"invalid_window:{round_number}")
- continue
- if continuous is not True or (previous_end is not None and not math.isclose(start, previous_end, abs_tol=1e-9)):
- failures.append(f"window_not_continuous:{round_number}")
- if index != expected_index or (previous_index is not None and index != previous_index + 1):
- failures.append(f"window_index_not_contiguous:{round_number}")
- if not isinstance(snapshot_seq, int) or isinstance(snapshot_seq, bool) or not 0 <= snapshot_seq <= 0xFFFFFFFF:
- failures.append(f"window_snapshot_seq_invalid:{round_number}:{expected_index}")
- elif previous_snapshot_seq is not None and snapshot_seq != ((previous_snapshot_seq + 1) & 0xFFFFFFFF):
- failures.append(f"window_snapshot_seq_not_contiguous:{round_number}")
- if not isinstance(overflow_mask, int) or isinstance(overflow_mask, bool) or not 0 <= overflow_mask <= 0xFF:
- failures.append(f"window_overflow_mask_invalid:{round_number}:{expected_index}")
- previous_end = end
- previous_index = index
- if isinstance(snapshot_seq, int) and not isinstance(snapshot_seq, bool):
- previous_snapshot_seq = snapshot_seq
- return list(dict.fromkeys(failures))
- def _validate_correlation(correlation: Any, round_number: int) -> list[str]:
- failures: list[str] = []
- payload = _mapping(correlation)
- samples = payload.get("samples")
- if not isinstance(samples, list) or len(samples) != len(FAN_SETTINGS):
- failures.append(f"trend_samples_must_cover_all_settings:{round_number}")
- samples = []
- by_setting: dict[float, float] = {}
- for sample in samples:
- row = _mapping(sample)
- x = _number(row.get("fan_setting_percent", row.get("fan_percent")))
- y = _number(row.get("rpm"))
- if x is None or y is None:
- failures.append(f"invalid_correlation_sample:{round_number}")
- continue
- if x in by_setting:
- failures.append(f"duplicate_correlation_setting:{round_number}:{int(x)}")
- by_setting[x] = y
- if tuple(by_setting) != FAN_SETTINGS:
- failures.append(f"trend_settings_must_be_0_20_40_60_80_100:{round_number}")
- x_values = [float(setting) for setting in TREND_SETTINGS if float(setting) in by_setting]
- y_values = [by_setting[setting] for setting in x_values]
- computed = spearman_rho(x_values, y_values) if len(x_values) == len(TREND_SETTINGS) else None
- declared = _number(payload.get("spearman_rho"))
- if computed is None:
- failures.append(f"spearman_not_computable:{round_number}")
- elif declared is None:
- failures.append(f"spearman_declared_missing:{round_number}")
- elif not math.isclose(declared, computed, abs_tol=1e-6):
- failures.append(f"spearman_declared_mismatch:{round_number}")
- if computed is None or computed < SPEARMAN_MIN:
- failures.append(f"spearman_below_threshold:{round_number}")
- low = _number(payload.get("low_mean_rpm"))
- high = _number(payload.get("high_mean_rpm"))
- expected_low = (
- sum(by_setting[float(setting)] for setting in LOW_SETTINGS) / len(LOW_SETTINGS)
- if all(float(setting) in by_setting for setting in LOW_SETTINGS)
- else None
- )
- expected_high = (
- sum(by_setting[float(setting)] for setting in HIGH_SETTINGS) / len(HIGH_SETTINGS)
- if all(float(setting) in by_setting for setting in HIGH_SETTINGS)
- else None
- )
- if low is None or expected_low is None or not math.isclose(low, expected_low, abs_tol=1e-9):
- failures.append(f"low_setting_mean_mismatch:{round_number}")
- if high is None or expected_high is None or not math.isclose(high, expected_high, abs_tol=1e-9):
- failures.append(f"high_setting_mean_mismatch:{round_number}")
- significant = payload.get("high_significantly_higher") is True
- if expected_low is None or expected_high is None or not significant or expected_high < expected_low + max(100.0, expected_low * 0.10):
- failures.append(f"high_setting_not_significantly_higher:{round_number}")
- return failures
- def _validate_raw_samples(raw_samples: Any, fan3: Mapping[str, Any], round_number: int) -> list[str]:
- failures: list[str] = []
- expected_total = len(FAN_SETTINGS) * SAMPLES_PER_SETTING
- if not isinstance(raw_samples, list):
- return [f"raw_samples_missing:{round_number}"]
- if len(raw_samples) != expected_total:
- failures.append(f"raw_samples_count:{round_number}:{len(raw_samples)}")
- rows_by_setting: dict[int, list[Mapping[str, Any]]] = {setting: [] for setting in FAN_SETTINGS}
- valid_rows: list[Mapping[str, Any]] = []
- for row_index, item in enumerate(raw_samples):
- row = _mapping(item)
- setting = row.get("fan_setting_percent")
- if not isinstance(setting, int) or isinstance(setting, bool) or setting not in rows_by_setting:
- failures.append(f"raw_sample_setting_invalid:{round_number}:{row_index}")
- else:
- rows_by_setting[setting].append(row)
- snapshot_seq = row.get("snapshot_seq")
- if not isinstance(snapshot_seq, int) or isinstance(snapshot_seq, bool) or snapshot_seq < 0:
- failures.append(f"snapshot_seq_invalid:{round_number}:{row_index}")
- overflow_mask = row.get("overflow_mask")
- if not isinstance(overflow_mask, int) or isinstance(overflow_mask, bool) or not 0 <= overflow_mask <= 0xFF:
- failures.append(f"overflow_mask_invalid:{round_number}:{row_index}")
- for signal in ("FG5", "FG6"):
- channel = _mapping(row.get(signal))
- edges = channel.get("window_edges")
- if not isinstance(edges, int) or isinstance(edges, bool) or edges < 0:
- failures.append(f"window_edges_invalid:{round_number}:{row_index}:{signal}")
- valid_rows.append(row)
- for setting in FAN_SETTINGS:
- count = len(rows_by_setting[setting])
- if count != SAMPLES_PER_SETTING:
- failures.append(f"raw_samples_setting_count:{round_number}:{setting}:{count}")
- for setting, setting_rows in rows_by_setting.items():
- setting_sequences = [
- row.get("snapshot_seq")
- for row in setting_rows
- if isinstance(row.get("snapshot_seq"), int) and not isinstance(row.get("snapshot_seq"), bool)
- ]
- if len(setting_sequences) == SAMPLES_PER_SETTING:
- for previous, current in zip(setting_sequences, setting_sequences[1:]):
- if current != ((previous + 1) & 0xFFFFFFFF):
- failures.append(f"snapshot_seq_not_contiguous:{round_number}")
- break
- computed_statuses: dict[str, str] = {}
- for signal, bit_index in (("FG5", 4), ("FG6", 5)):
- nonzero_counts = []
- high_edges: list[int] = []
- for setting in HIGH_SETTINGS:
- edges = [
- int(_mapping(row.get(signal)).get("window_edges", 0))
- for row in rows_by_setting[setting]
- if isinstance(_mapping(row.get(signal)).get("window_edges"), int)
- and not isinstance(_mapping(row.get(signal)).get("window_edges"), bool)
- ]
- high_edges.extend(edges)
- nonzero_counts.append(sum(value > 0 for value in edges))
- if any(count >= 4 for count in nonzero_counts):
- computed = "detected"
- elif len(high_edges) == len(HIGH_SETTINGS) * SAMPLES_PER_SETTING and all(value == 0 for value in high_edges):
- computed = "absent"
- else:
- computed = "intermittent"
- computed_statuses[signal] = computed
- declared = fan3.get(signal)
- if declared in FAN_STATUSES and declared != computed:
- failures.append(f"fan_status_mismatch:{round_number}:FAN3:{signal}:{computed}")
- if computed == "detected" and any(
- isinstance(row.get("overflow_mask"), int) and row["overflow_mask"] & (1 << bit_index)
- for row in valid_rows
- ):
- failures.append(f"detected_channel_overflow:{round_number}:{signal}")
- if "detected" not in computed_statuses.values():
- failures.append(f"fan3_signal_not_detected:{round_number}")
- return failures
- def _validate_binding_artifact(binding: Any, name: str, round_number: int) -> list[str]:
- failures: list[str] = []
- payload = _mapping(binding)
- if not payload:
- return [f"missing_binding:{name}:{round_number}"]
- path = payload.get("path")
- digest = payload.get("sha256")
- if not isinstance(path, str) or not path:
- failures.append(f"binding_path_invalid:{round_number}:{name}")
- if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest):
- failures.append(f"binding_sha256_invalid:{round_number}:{name}")
- if name == "programmer_receipt" and payload.get("status") != "pass":
- failures.append(f"programmer_receipt_not_pass:{round_number}")
- receipt = payload.get("receipt")
- if isinstance(receipt, Mapping) and receipt.get("status") != "pass":
- failures.append(f"programmer_receipt_payload_not_pass:{round_number}")
- return failures
- def _validate_static_qualification(qualification: Any) -> list[str]:
- failures: list[str] = []
- payload = _mapping(qualification)
- if not payload:
- return ["static_qualification_missing"]
- if payload.get("schema") != "prod2u-p4-static-qualification-v1":
- failures.append("static_qualification_schema_mismatch")
- if payload.get("status") != "pass":
- failures.append("static_qualification_not_pass")
- if payload.get("profile") != "prod2u-fan-tach-binary921-v2" or payload.get("profile_id") != 4:
- failures.append("static_qualification_profile_mismatch")
- declared_failures = payload.get("failures")
- if not isinstance(declared_failures, list):
- failures.append("static_qualification_failures_invalid")
- elif declared_failures:
- failures.append("static_qualification_declares_failures")
- layers = _mapping(payload.get("layers"))
- for layer_name in REQUIRED_STATIC_LAYERS:
- layer = _mapping(layers.get(layer_name))
- if not layer:
- failures.append(f"static_layer_missing:{layer_name}")
- continue
- if layer.get("status") != "pass":
- failures.append(f"static_layer_not_pass:{layer_name}")
- artifacts = _mapping(layer.get("artifacts"))
- for artifact_name in STATIC_LAYER_ARTIFACTS[layer_name]:
- if artifact_name not in artifacts:
- failures.append(f"static_artifact_missing:{layer_name}:{artifact_name}")
- continue
- for failure in _validate_binding_artifact(artifacts.get(artifact_name), artifact_name, 0):
- failures.append(f"static_{failure}")
- return failures
- def _qualification_artifact_sha256(qualification: Any, layer: str, artifact: str) -> str | None:
- payload = _mapping(qualification)
- layer_payload = _mapping(_mapping(payload.get("layers")).get(layer))
- artifact_payload = _mapping(_mapping(layer_payload.get("artifacts")).get(artifact))
- digest = artifact_payload.get("sha256")
- return str(digest).casefold() if isinstance(digest, str) and SHA256_RE.fullmatch(digest) else None
- def _validate_qualification_binding(
- qualification: Any,
- evidence_binding: Any,
- variant: Any,
- round_number: int,
- ) -> list[str]:
- failures: list[str] = []
- binding = _mapping(evidence_binding)
- if variant not in {"normal", "trace"}:
- return [f"qualification_binding_variant_invalid:{round_number}"]
- expected = {
- "source_manifest": _qualification_artifact_sha256(
- qualification, "source", f"{variant}_source_manifest"
- ),
- "td_receipt": _qualification_artifact_sha256(
- qualification, f"td_{variant}", f"{variant}_td_receipt"
- ),
- "package_manifest": _qualification_artifact_sha256(
- qualification, "package", "package_manifest"
- ),
- "package_inventory": _qualification_artifact_sha256(
- qualification, "package", "package_inventory"
- ),
- }
- for artifact_name, expected_hash in expected.items():
- actual_hash = _mapping(binding.get(artifact_name)).get("sha256")
- if expected_hash is None or not isinstance(actual_hash, str) or actual_hash.casefold() != expected_hash:
- failures.append(f"qualification_binding_mismatch:{round_number}:{artifact_name}")
- return failures
- def _validate_evidence_binding(binding: Any, identity: Mapping[str, Any], round_number: int) -> list[str]:
- failures: list[str] = []
- payload = _mapping(binding)
- if not payload:
- return [f"missing_required:evidence:evidence_binding:{round_number}"]
- for name in BOUND_ARTIFACTS:
- failures.extend(_validate_binding_artifact(payload.get(name), name, round_number))
- bound_identity = _mapping(payload.get("identity"))
- if not bound_identity:
- failures.append(f"binding_identity_missing:{round_number}")
- variant_identity = _mapping(identity.get("variants")).get(bound_identity.get("variant"))
- for name in IDENTITY_FIELDS:
- expected = identity.get(name)
- if name in ("build_id", "bitstream_sha256") and isinstance(variant_identity, Mapping):
- expected = variant_identity.get(name, expected)
- if name in identity and expected is not None and bound_identity.get(name) != expected:
- failures.append(f"binding_identity_mismatch:{round_number}:{name}")
- source_manifest = _mapping(payload.get("source_manifest"))
- expected_source_hash = identity.get("source_manifest_sha256")
- if expected_source_hash:
- declared_source_hash = source_manifest.get("declared_sha256")
- if declared_source_hash is not None:
- if declared_source_hash != expected_source_hash:
- failures.append(f"source_manifest_binding_mismatch:{round_number}")
- elif source_manifest.get("sha256") != expected_source_hash:
- failures.append(f"source_manifest_binding_mismatch:{round_number}")
- return failures
- def validate_evidence(evidence: Mapping[str, Any]) -> dict[str, Any]:
- failures: list[str] = []
- failures.extend(f"missing_required:evidence:{name}" for name in EVIDENCE_REQUIRED if name not in evidence)
- if evidence.get("schema") != SCHEMAS["evidence"]:
- failures.append("schema_mismatch")
- round_number = evidence.get("round")
- if not isinstance(round_number, int) or isinstance(round_number, bool) or not 1 <= round_number <= ROUND_COUNT:
- failures.append("round_invalid")
- round_number = 0
- if _mapping(evidence.get("bmc")).get("status") != "out_of_scope":
- failures.append("bmc_must_be_out_of_scope")
- actual_identity = _mapping(evidence.get("identity"))
- for name in IDENTITY_FIELDS:
- if not actual_identity.get(name):
- failures.append(f"identity_field_missing:{round_number}:{name}")
- if evidence.get("variant") is not None and evidence.get("variant") != actual_identity.get("variant"):
- failures.append(f"variant_identity_mismatch:{round_number}")
- failures.extend(_validate_layers(evidence.get("layers"), round_number))
- fan3 = _mapping(_mapping(evidence.get("fan")).get("FAN3"))
- for signal in ("FG5", "FG6"):
- if fan3.get(signal) not in FAN_STATUSES:
- failures.append(f"invalid_fan_status:{round_number}:FAN3:{signal}")
- failures.extend(_validate_windows(evidence.get("windows"), round_number))
- failures.extend(_validate_raw_samples(evidence.get("raw_samples"), fan3, round_number))
- failures.extend(_validate_correlation(evidence.get("correlation"), round_number))
- if _mapping(evidence.get("rpm")).get("status") != "not_qualified":
- failures.append(f"rpm_not_qualified:{round_number}")
- ptc = _mapping(evidence.get("ptc"))
- if ptc.get("actuation") is not True:
- failures.append(f"ptc_actuation_must_be_true:{round_number}")
- if ptc.get("measurement") != "not_run":
- failures.append(f"ptc_measurement_must_be_not_run:{round_number}")
- failures.extend(_validate_evidence_binding(evidence.get("evidence_binding"), actual_identity, round_number))
- return {
- "status": "pass" if not failures else "fail",
- "round": round_number,
- "failures": list(dict.fromkeys(failures)),
- }
- def _identity_failures(expected: Mapping[str, Any], actual: Mapping[str, Any], round_number: int) -> list[str]:
- failures: list[str] = []
- for name in ("dut_id", "profile"):
- if actual.get(name) != expected.get(name):
- failures.append(f"identity_mismatch:{round_number}:{name}")
- variant_identity = _mapping(expected.get("variants")).get(actual.get("variant"))
- for name in ("build_id", "bitstream_sha256", "source_manifest_sha256"):
- expected_value = expected.get(name)
- if name in ("build_id", "bitstream_sha256") and isinstance(variant_identity, Mapping):
- expected_value = variant_identity.get(name, expected_value)
- if expected_value is not None and actual.get(name) != expected_value:
- failures.append(f"identity_mismatch:{round_number}:{name}")
- return failures
- def validate_campaign(campaign: Mapping[str, Any]) -> dict[str, Any]:
- failures: list[str] = []
- if campaign.get("schema") != SCHEMAS["campaign"]:
- failures.append("schema_mismatch")
- campaign_identity = _mapping(campaign.get("campaign_identity"))
- if campaign_identity.get("planned_rounds") != ROUND_COUNT:
- failures.append("planned_rounds_must_be_10")
- if _mapping(campaign.get("bmc")).get("status") != "out_of_scope":
- failures.append("bmc_must_be_out_of_scope")
- qualification = campaign.get("qualification")
- failures.extend(_validate_static_qualification(qualification))
- evidence_bindings = campaign.get("evidence_bindings")
- if not isinstance(evidence_bindings, list) or len(evidence_bindings) != ROUND_COUNT:
- failures.append("evidence_bindings_must_contain_10_rounds")
- if "layers" in campaign:
- failures.extend(_validate_layers(campaign.get("layers")))
- rounds = campaign.get("rounds")
- if not isinstance(rounds, list) or len(rounds) != ROUND_COUNT:
- failures.append("round_count_must_be_10")
- rounds = rounds if isinstance(rounds, list) else []
- numbers = [round_item.get("round") for round_item in rounds if isinstance(round_item, Mapping)]
- if numbers != list(range(1, ROUND_COUNT + 1)):
- failures.append("round_sequence_not_1_to_10")
- for position, round_item in enumerate(rounds, start=1):
- if not isinstance(round_item, Mapping):
- failures.append(f"round_not_object:{position}")
- continue
- round_number = round_item.get("round", position)
- result = validate_evidence(
- {
- **round_item,
- "schema": SCHEMAS["evidence"],
- "evidence_id": f"{campaign.get('campaign_id', 'campaign')}-R{position:02d}",
- "campaign_id": campaign.get("campaign_id"),
- "campaign_identity": campaign_identity,
- "bmc": campaign.get("bmc"),
- }
- )
- failures.extend(result["failures"])
- failures.extend(_identity_failures(campaign_identity, _mapping(round_item.get("identity")), position))
- failures.extend(
- _validate_qualification_binding(
- qualification,
- round_item.get("evidence_binding"),
- _mapping(round_item.get("identity")).get("variant"),
- position,
- )
- )
- if round_item.get("variant") is not None and round_item.get("variant") != _mapping(round_item.get("identity")).get("variant"):
- failures.append(f"variant_identity_mismatch:{position}")
- if isinstance(evidence_bindings, list) and len(evidence_bindings) == ROUND_COUNT:
- for position, item in enumerate(evidence_bindings, start=1):
- wrapper = _mapping(item)
- if wrapper.get("round") != position:
- failures.append(f"evidence_binding_round_mismatch:{position}")
- round_item = rounds[position - 1] if position <= len(rounds) and isinstance(rounds[position - 1], Mapping) else {}
- expected_binding = _mapping(round_item.get("evidence_binding"))
- if wrapper.get("evidence_binding") != expected_binding:
- failures.append(f"evidence_binding_not_preserved:{position}")
- return {
- "status": "pass" if not failures else "fail",
- "campaign_id": campaign.get("campaign_id"),
- "round_count": len(rounds),
- "bmc": _mapping(campaign.get("bmc")).get("status"),
- "failures": list(dict.fromkeys(failures)),
- }
- def validate_final_gate(gate: Mapping[str, Any]) -> dict[str, Any]:
- failures: list[str] = []
- failures.extend(f"missing_required:final_gate:{name}" for name in FINAL_GATE_REQUIRED if name not in gate)
- if gate.get("schema") != SCHEMAS["final_gate"]:
- failures.append("schema_mismatch")
- if _mapping(gate.get("bmc")).get("status") != "out_of_scope":
- failures.append("bmc_must_be_out_of_scope")
- qualification = gate.get("qualification")
- failures.extend(_validate_static_qualification(qualification))
- failures.extend(_validate_layers(gate.get("layers")))
- if gate.get("round_count") != ROUND_COUNT:
- failures.append("round_count_must_be_10")
- declared = gate.get("failures")
- if not isinstance(declared, list):
- failures.append("failures_must_be_array")
- elif gate.get("status") == "pass" and declared:
- failures.append("pass_gate_has_failures")
- bindings = gate.get("evidence_bindings")
- if not isinstance(bindings, list) or len(bindings) != ROUND_COUNT:
- failures.append("evidence_bindings_must_contain_10_rounds")
- else:
- gate_identity = _mapping(gate.get("campaign_identity"))
- for position, item in enumerate(bindings, start=1):
- wrapper = _mapping(item)
- if wrapper.get("round") != position:
- failures.append(f"evidence_binding_round_mismatch:{position}")
- failures.extend(_validate_evidence_binding(wrapper.get("evidence_binding"), gate_identity, position))
- binding_identity = _mapping(_mapping(wrapper.get("evidence_binding")).get("identity"))
- failures.extend(
- _validate_qualification_binding(
- qualification,
- wrapper.get("evidence_binding"),
- binding_identity.get("variant"),
- position,
- )
- )
- if gate.get("status") == "pass" and failures:
- failures.append("final_gate_pass_inconsistent")
- return {
- "status": "pass" if not failures else "fail",
- "campaign_id": gate.get("campaign_id"),
- "bmc": _mapping(gate.get("bmc")).get("status"),
- "failures": list(dict.fromkeys(failures)),
- }
- def build_final_gate(campaign: Mapping[str, Any]) -> dict[str, Any]:
- """Build the strict P4 final-gate document without performing live I/O."""
- campaign_result = validate_campaign(campaign)
- rounds = campaign.get("rounds") if isinstance(campaign.get("rounds"), list) else []
- required_layers: dict[str, str] = {}
- optional_layers: dict[str, str] = {}
- for round_item in rounds:
- layers = _mapping(round_item.get("layers")) if isinstance(round_item, Mapping) else {}
- for name, status in _mapping(layers.get("required")).items():
- if name not in required_layers:
- required_layers[name] = status
- elif required_layers[name] != "pass" or status != "pass":
- required_layers[name] = "fail"
- for name, status in _mapping(layers.get("optional")).items():
- if name not in optional_layers:
- optional_layers[name] = status
- bindings = campaign.get("evidence_bindings")
- if not isinstance(bindings, list):
- bindings = []
- return {
- "schema": SCHEMAS["final_gate"],
- "status": "pass" if campaign_result["status"] == "pass" else "fail",
- "campaign_id": campaign.get("campaign_id"),
- "campaign_identity": _mapping(campaign.get("campaign_identity")),
- "bmc": _mapping(campaign.get("bmc")),
- "qualification": _mapping(campaign.get("qualification")),
- "layers": {"required": required_layers, "optional": optional_layers},
- "round_count": len(rounds),
- "evidence_bindings": bindings,
- "failures": list(campaign_result["failures"]),
- "summary": {"campaign_status": campaign_result["status"], "round_count": len(rounds)},
- }
- def load_json(source: str | Path | Mapping[str, Any]) -> Mapping[str, Any]:
- if isinstance(source, Mapping):
- return source
- payload = json.loads(Path(source).read_text(encoding="utf-8-sig"))
- if not isinstance(payload, Mapping):
- raise ValueError("document must be a JSON object")
- return payload
- def validate_document(source: str | Path | Mapping[str, Any], kind: str | None = None) -> dict[str, Any]:
- document = load_json(source)
- selected = kind
- if selected is None:
- selected = next((name for name, schema_id in SCHEMAS.items() if document.get("schema") == schema_id), None)
- if selected == "evidence":
- return validate_evidence(document)
- if selected == "campaign":
- return validate_campaign(document)
- if selected == "final_gate":
- return validate_final_gate(document)
- return {"status": "fail", "failures": ["unknown_schema"]}
- def main(argv: Sequence[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("document", type=Path)
- parser.add_argument("--kind", choices=sorted(SCHEMAS), help="document kind; inferred from schema when omitted")
- args = parser.parse_args(argv)
- try:
- result = validate_document(args.document, args.kind)
- except (OSError, ValueError, json.JSONDecodeError) as exc:
- result = {"status": "fail", "failures": [f"input_error:{exc}"]}
- print(json.dumps(result, ensure_ascii=True, sort_keys=True))
- return 0 if result.get("status") == "pass" else 1
- if __name__ == "__main__":
- sys.exit(main())
|