COMPONENT_STARTUP, COMPONENT_TABLE and COMPONENT_KERNEL record schemas (schema_component.json), validate_component.py (record / --negative-suite / merge), one sample per level (two for start-up: ours and vanilla), a negative-case table and 41 unittest tests. Shares the STRA-246 evaluator and definitions; stdlib only, Python >= 3.9. Classes are computed elsewhere (STRA-313); the validator checks presence and consistency. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
405 lines
19 KiB
Python
405 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Validator for COMPONENT evidence records (STRA-287, S0.1b). Offline, stdlib only, Python >= 3.9.
|
|
|
|
Levels: COMPONENT_STARTUP, COMPONENT_TABLE, COMPONENT_KERNEL (schema_component.json). The END_TO_END level is STRA-246 (validate.py).
|
|
|
|
CLI v1 (fixed here; later leaves and acceptance commands use it):
|
|
|
|
validate_component.py <record.json> exit 0 and `OK <level>` when valid, exit 1 and the reasons when rejected
|
|
validate_component.py --negative-suite [--dir <dir>]
|
|
every case of negative_component_cases.json (a sample plus edits) must be rejected
|
|
for the code it names; exit 0 and `rejected: N/N` when all are
|
|
validate_component.py merge <a.json> <b.json> COMPONENT records of one level and one machine only;
|
|
`COMPONENT with END_TO_END refused` (exit 1) when an END_TO_END record is involved
|
|
|
|
The schema evaluator and the shared definitions (sha256, commit, utc, text, build_id, vanilla_cpu_family, ...) come from STRA-246
|
|
(validate.py, schema.json); this file adds the COMPONENT blocks and the cross-field rules. It checks presence and consistency only:
|
|
classes (FASTER / SLOWER / EQUAL / INCONCLUSIVE / CONFIRMED-SLOWER / NOT-CONFIRMED) and the A/A verdict are computed by STRA-313,
|
|
the statistics by STRA-290. Paired log ratio = ln(vanilla_cost / ours_cost), positive means ours is better.
|
|
"""
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import sys
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, HERE)
|
|
import validate as E2E # noqa: E402 (STRA-246: schema evaluator, shared definitions)
|
|
|
|
SCHEMA_PATH = os.path.join(HERE, "schema_component.json")
|
|
NEGATIVE_INDEX = "negative_component_cases.json"
|
|
E2E_LEVEL = "END_TO_END"
|
|
REFUSED_MESSAGE = "COMPONENT with END_TO_END refused"
|
|
|
|
|
|
def load_json(path):
|
|
return E2E.load_json(path)
|
|
|
|
|
|
def load_schema():
|
|
return load_json(SCHEMA_PATH)
|
|
|
|
|
|
def all_definitions(schema):
|
|
"""Definitions shared with STRA-246 first, then the COMPONENT ones. A name used by both is a schema bug."""
|
|
shared = E2E.load_schema()["definitions"]
|
|
own = schema["definitions"]
|
|
clash = sorted(set(shared) & set(own))
|
|
if clash:
|
|
raise ValueError("schema_component.json redefines STRA-246 definitions: %s" % clash)
|
|
merged = dict(shared)
|
|
merged.update(own)
|
|
return merged
|
|
|
|
|
|
# ---------------------------------------------------------------- helpers for the rules
|
|
|
|
def _ci_errors(block, path, errors):
|
|
low, mean, high = block["ci95_low"], block["log_ratio_mean"], block["ci95_high"]
|
|
if not low <= mean <= high:
|
|
errors.append(("RULE_CI_ORDER", path, "ci95_low <= log_ratio_mean <= ci95_high does not hold"))
|
|
|
|
|
|
def _contains_zero(pair):
|
|
return pair["ci95_low"] <= 0 <= pair["ci95_high"]
|
|
|
|
|
|
def _bad_pair(pair, path, errors):
|
|
if pair["ci95_low"] > pair["ci95_high"]:
|
|
errors.append(("RULE_CI_ORDER", path, "ci95_low is above ci95_high"))
|
|
|
|
|
|
def _distribution_errors(dist, path, errors):
|
|
ok = dist["min"] <= dist["p05"] <= dist["median"] <= dist["p95"] <= dist["max"] and dist["min"] <= dist["mean"] <= dist["max"]
|
|
if not ok:
|
|
errors.append(("RULE_DISTRIBUTION_ORDER", path, "min <= p05 <= median <= p95 <= max and min <= mean <= max does not hold"))
|
|
|
|
|
|
# ---------------------------------------------------------------- COMPONENT_STARTUP
|
|
|
|
def startup_rules(rec, constants, definitions):
|
|
errors = []
|
|
arm = rec["arm"]
|
|
lines = rec.get("kernel_lines", [])
|
|
bare = re.compile(constants["bare_cpu_line_regex"])
|
|
ours_cpu = re.compile(constants["ours_cpu_line_regex"])
|
|
identity = rec["build_identity"]
|
|
if arm == "ours":
|
|
found = []
|
|
E2E.interpret(definitions["build_id"], identity, "/build_identity", definitions, found)
|
|
if found:
|
|
errors.append(("RULE_BUILD_IDENTITY_FORM", "/build_identity", "an ours record carries a build_id: %s" % found[0][2]))
|
|
if not any(ours_cpu.search(line) for line in lines):
|
|
errors.append(("RULE_OURS_CPU_LINE", "/kernel_lines", "an ours record needs 'leleka-serve cpu: ' lines (verbatim stderr of cpu_kernel_report)"))
|
|
if "vanilla_cpu_family" in rec:
|
|
errors.append(("RULE_OURS_NO_VANILLA_BLOCK", "/vanilla_cpu_family", "an ours record does not carry vanilla_cpu_family"))
|
|
return errors
|
|
found = []
|
|
E2E.interpret(definitions["vanilla_build_identity"], identity, "/build_identity", definitions, found)
|
|
if found:
|
|
errors.append(("RULE_BUILD_IDENTITY_FORM", "/build_identity", "a vanilla record carries engine_version, binary_sha256, strata_upstream_commit: %s" % found[0][2]))
|
|
if lines:
|
|
errors.append(("RULE_VANILLA_CLAIMS_CPU", "/kernel_lines", "the vanilla engine prints no cpu: line; use the vanilla_cpu_family block"))
|
|
block = rec.get("vanilla_cpu_family")
|
|
if block is None:
|
|
errors.append(("RULE_VANILLA_BLOCK", "/vanilla_cpu_family", "a vanilla record needs the vanilla_cpu_family block"))
|
|
return errors
|
|
for where in (block["printed"], block["control"]["printed"]):
|
|
if isinstance(where, list) and any(bare.search(line) for line in where):
|
|
errors.append(("RULE_VANILLA_CLAIMS_CPU", "/vanilla_cpu_family", "a printed line starts with 'cpu:'; the vanilla engine prints none"))
|
|
if not found:
|
|
binary = block["binary_identity"]
|
|
if binary["engine_version"] != identity["engine_version"] or binary["sha256"] != identity["binary_sha256"]:
|
|
errors.append(("RULE_BUILD_IDENTITY_MISMATCH", "/build_identity",
|
|
"engine_version and binary_sha256 differ from vanilla_cpu_family.binary_identity"))
|
|
return errors
|
|
|
|
|
|
# ---------------------------------------------------------------- COMPONENT_TABLE
|
|
|
|
def table_rules(rec, constants):
|
|
errors = []
|
|
min_n = constants["min_classified_n"]
|
|
eq_low = math.log(constants["equal_ratio_low"])
|
|
eq_high = math.log(constants["equal_ratio_high"])
|
|
|
|
stages = set()
|
|
for index, entry in enumerate(rec["stage_to_component"]):
|
|
if entry["stage"] in stages:
|
|
errors.append(("RULE_MAPPING_DUPLICATE", "/stage_to_component/%d/stage" % index, "stage %s is mapped twice" % entry["stage"]))
|
|
stages.add(entry["stage"])
|
|
mapped = set(entry["component"] for entry in rec["stage_to_component"])
|
|
|
|
seen = set()
|
|
for index, row in enumerate(rec["rows"]):
|
|
where = "/rows/%d" % index
|
|
component = row["component"]
|
|
if component not in mapped:
|
|
errors.append(("RULE_COMPONENT_UNMAPPED", where + "/component", "component %s is not in stage_to_component" % component))
|
|
if component in seen:
|
|
errors.append(("RULE_COMPONENT_UNMAPPED", where + "/component", "component %s appears in two rows" % component))
|
|
seen.add(component)
|
|
_distribution_errors(row["ours"], where + "/ours", errors)
|
|
_distribution_errors(row["vanilla"], where + "/vanilla", errors)
|
|
|
|
cls = row.get("class")
|
|
paired = row.get("paired")
|
|
aa = row.get("aa")
|
|
n = row["n"]
|
|
if paired is not None:
|
|
_ci_errors(paired, where + "/paired", errors)
|
|
if aa is not None:
|
|
for key in ("ours_vs_ours", "vanilla_vs_vanilla"):
|
|
_bad_pair(aa[key], "%s/aa/%s" % (where, key), errors)
|
|
both_zero = _contains_zero(aa["ours_vs_ours"]) and _contains_zero(aa["vanilla_vs_vanilla"])
|
|
if aa["valid"] != both_zero:
|
|
errors.append(("RULE_AA_VALID", where + "/aa/valid", "must be %s: the A/A CIs %s 0" % (str(both_zero).lower(), "both contain" if both_zero else "do not both contain")))
|
|
if not aa["valid"] and cls not in (None, "INCONCLUSIVE"):
|
|
errors.append(("RULE_AA_INVALID_CLASS", where + "/class", "the A/A control is invalid, the cell must be INCONCLUSIVE and re-run, not %s" % cls))
|
|
|
|
if n >= min_n:
|
|
if cls is None:
|
|
errors.append(("RULE_CLASS_REQUIRED", where + "/class", "n=%d >= %d: a class is required" % (n, min_n)))
|
|
if paired is None:
|
|
errors.append(("RULE_PAIRED_REQUIRED", where + "/paired", "n=%d >= %d: the paired difference and its CI are required" % (n, min_n)))
|
|
elif cls not in (None, "INCONCLUSIVE"):
|
|
errors.append(("RULE_SMALL_N_CLASS", where + "/class", "n=%d < %d is screening: class absent or INCONCLUSIVE, not %s" % (n, min_n, cls)))
|
|
|
|
if row["suspected"] != (cls == "SLOWER"):
|
|
errors.append(("RULE_SUSPECTED", where + "/suspected", "must be %s: suspected is true iff class is SLOWER" % str(cls == "SLOWER").lower()))
|
|
|
|
if paired is not None and cls is not None:
|
|
if cls == "FASTER" and not paired["ci95_low"] > 0:
|
|
errors.append(("RULE_FASTER_CI", where + "/paired/ci95_low", "FASTER needs ci95_low > 0, got %s" % paired["ci95_low"]))
|
|
if cls in ("SLOWER", "CONFIRMED-SLOWER") and not paired["ci95_high"] < 0:
|
|
errors.append(("RULE_SLOWER_CI", where + "/paired/ci95_high", "%s needs ci95_high < 0, got %s" % (cls, paired["ci95_high"])))
|
|
if cls == "EQUAL":
|
|
if not (paired["ci95_low"] <= 0 <= paired["ci95_high"] and paired["ci95_low"] >= eq_low and paired["ci95_high"] <= eq_high):
|
|
errors.append(("RULE_EQUAL_INTERVAL", where + "/paired",
|
|
"EQUAL needs the CI [%s, %s] to contain 0 and lie inside [ln 0.99, ln 1.01] = [%.6f, %.6f]"
|
|
% (paired["ci95_low"], paired["ci95_high"], eq_low, eq_high)))
|
|
if cls == "EQUAL" and (aa is None or not aa["valid"]):
|
|
errors.append(("RULE_EQUAL_AA", where + "/aa", "EQUAL needs a valid A/A result"))
|
|
|
|
confirmation = row.get("confirmation")
|
|
if cls in ("CONFIRMED-SLOWER", "NOT-CONFIRMED"):
|
|
if confirmation is None:
|
|
errors.append(("RULE_CONFIRMATION", where + "/confirmation", "%s needs the confirm-run block" % cls))
|
|
else:
|
|
if confirmation["n"] < min_n:
|
|
errors.append(("RULE_CONFIRMATION", where + "/confirmation/n", "the confirm run needs n >= %d, got %d" % (min_n, confirmation["n"])))
|
|
_ci_errors(confirmation["paired"], where + "/confirmation/paired", errors)
|
|
high = confirmation["paired"]["ci95_high"]
|
|
if cls == "CONFIRMED-SLOWER" and not high < 0:
|
|
errors.append(("RULE_CONFIRMATION", where + "/confirmation/paired/ci95_high", "CONFIRMED-SLOWER needs the confirm CI upper bound < 0, got %s" % high))
|
|
if cls == "NOT-CONFIRMED" and not high >= 0:
|
|
errors.append(("RULE_CONFIRMATION", where + "/confirmation/paired/ci95_high", "NOT-CONFIRMED needs the confirm CI upper bound >= 0, got %s" % high))
|
|
elif confirmation is not None:
|
|
errors.append(("RULE_CONFIRMATION", where + "/confirmation", "only CONFIRMED-SLOWER / NOT-CONFIRMED rows carry a confirmation block"))
|
|
return errors
|
|
|
|
|
|
# ---------------------------------------------------------------- COMPONENT_KERNEL
|
|
|
|
def kernel_rules(rec):
|
|
errors = []
|
|
clock = rec["clock_calibration"]
|
|
if clock["slices_dropped"] > clock["slices_total"]:
|
|
errors.append(("RULE_CLOCK", "/clock_calibration/slices_dropped", "more slices dropped than measured"))
|
|
|
|
streamed = rec.get("streamed")
|
|
if rec["regime"] == "streamed":
|
|
if streamed is None:
|
|
errors.append(("RULE_REGIME_STREAMED", "/streamed", "regime streamed needs the streamed block (copies, expert_bytes, llc_bytes)"))
|
|
elif streamed["copies"] * streamed["expert_bytes"] <= streamed["llc_bytes"]:
|
|
errors.append(("RULE_REGIME_STREAMED", "/streamed", "copies * expert_bytes must exceed llc_bytes, else the cycle stays in cache"))
|
|
elif streamed is not None:
|
|
errors.append(("RULE_REGIME_STREAMED", "/streamed", "regime resident has no streamed block"))
|
|
|
|
for key in ("ours_vs_ours", "reference_vs_reference"):
|
|
_bad_pair(rec["aa_noise_floor"][key], "/aa_noise_floor/" + key, errors)
|
|
|
|
equality = rec["equality"]
|
|
tolerance = equality.get("tolerance")
|
|
if equality["mode"] == "bitwise":
|
|
if tolerance is not None:
|
|
errors.append(("RULE_EQUALITY_MODE", "/equality/tolerance", "mode bitwise has no tolerance block"))
|
|
if equality["verdict"] == "EQUAL" and equality["mismatches"] != 0:
|
|
errors.append(("RULE_EQUALITY_MODE", "/equality/mismatches", "a bitwise EQUAL verdict has mismatches 0"))
|
|
if equality["verdict"] == "NOT_EQUAL" and equality["mismatches"] == 0:
|
|
errors.append(("RULE_EQUALITY_MODE", "/equality/mismatches", "a bitwise NOT_EQUAL verdict has mismatches > 0"))
|
|
else:
|
|
if tolerance is None:
|
|
errors.append(("RULE_EQUALITY_MODE", "/equality/tolerance", "mode tolerance needs the tolerance block with its basis"))
|
|
elif tolerance["basis_written_utc"] > rec["run_started_utc"]:
|
|
errors.append(("RULE_TOLERANCE_BASIS_ORDER", "/equality/tolerance/basis_written_utc",
|
|
"the basis was written %s, after the run started %s" % (tolerance["basis_written_utc"], rec["run_started_utc"])))
|
|
if equality["mismatches"] > equality["compared_values"]:
|
|
errors.append(("RULE_EQUALITY_MODE", "/equality/mismatches", "more mismatches than compared values"))
|
|
|
|
seen = set()
|
|
for index, row in enumerate(rec["rows"]):
|
|
if row["row_type"] in seen:
|
|
errors.append(("RULE_KERNEL_ROW_DUPLICATE", "/rows/%d/row_type" % index, "row type %s appears twice" % row["row_type"]))
|
|
seen.add(row["row_type"])
|
|
return errors
|
|
|
|
|
|
# ---------------------------------------------------------------- driver
|
|
|
|
def validate_record(rec, schema):
|
|
"""Return the list of (code, path, message) reasons; empty means valid."""
|
|
if not isinstance(rec, dict):
|
|
return [("WRONG_TYPE", "", "a record is a JSON object")]
|
|
level = rec.get("level")
|
|
if level == E2E_LEVEL:
|
|
return [("LEVEL_NOT_COMPONENT", "/level", "an END_TO_END record is checked by validate.py (STRA-246), not here")]
|
|
if level not in schema["levels_list"]:
|
|
return [("LEVEL_NOT_COMPONENT", "/level", "level is %s, expected one of %s" % (E2E._short(level), schema["levels_list"]))]
|
|
definitions = all_definitions(schema)
|
|
errors = []
|
|
E2E.interpret(schema["levels"][level], rec, "", definitions, errors)
|
|
if errors:
|
|
return errors
|
|
constants = schema["constants"]
|
|
if level == "COMPONENT_STARTUP":
|
|
return startup_rules(rec, constants, definitions)
|
|
if level == "COMPONENT_TABLE":
|
|
return table_rules(rec, constants)
|
|
return kernel_rules(rec)
|
|
|
|
|
|
def format_errors(errors):
|
|
return E2E.format_errors(errors)
|
|
|
|
|
|
def cmd_validate(path):
|
|
errors = validate_record(load_json(path), load_schema())
|
|
if errors:
|
|
for line in format_errors(errors):
|
|
print(line)
|
|
return 1
|
|
print("OK %s" % load_json(path)["level"])
|
|
return 0
|
|
|
|
|
|
def _levels(doc):
|
|
records = doc["series_records"] if isinstance(doc, dict) and isinstance(doc.get("series_records"), list) else [doc]
|
|
return [r.get("level") if isinstance(r, dict) else None for r in records]
|
|
|
|
|
|
def cmd_merge(path_a, path_b):
|
|
docs = [load_json(path_a), load_json(path_b)]
|
|
levels = _levels(docs[0]) + _levels(docs[1])
|
|
if E2E_LEVEL in levels:
|
|
print(REFUSED_MESSAGE)
|
|
return 1
|
|
schema = load_schema()
|
|
records = []
|
|
for doc in docs:
|
|
if not isinstance(doc, dict) or "series_records" in doc:
|
|
print("merge refused: a COMPONENT file is one record")
|
|
return 1
|
|
errors = validate_record(doc, schema)
|
|
if errors:
|
|
for line in format_errors(errors):
|
|
print(line)
|
|
return 1
|
|
records.append(doc)
|
|
if records[0]["level"] != records[1]["level"]:
|
|
print("merge refused: COMPONENT levels differ (%s, %s); levels are never pooled" % (records[0]["level"], records[1]["level"]))
|
|
return 1
|
|
roles = [r["machine"]["machine_role"] for r in records]
|
|
if roles[0] != roles[1]:
|
|
print("merge refused: different machines (%s, %s)" % (roles[0], roles[1]))
|
|
return 1
|
|
print("MERGED 2 records of %s on %s" % (records[0]["level"], roles[0]))
|
|
return 0
|
|
|
|
|
|
def _pointer_parts(path):
|
|
return [part for part in path.split("/") if part != ""]
|
|
|
|
|
|
def _walk(node, parts):
|
|
for part in parts:
|
|
node = node[int(part)] if isinstance(node, list) else node[part]
|
|
return node
|
|
|
|
|
|
def apply_ops(record, ops):
|
|
"""Edit a copy of a sample: op is set (path, value) or delete (path); paths are JSON pointers with list indexes."""
|
|
for op in ops:
|
|
parts = _pointer_parts(op["path"])
|
|
parent = _walk(record, parts[:-1])
|
|
last = parts[-1]
|
|
key = int(last) if isinstance(parent, list) else last
|
|
if op["op"] == "set":
|
|
parent[key] = op["value"]
|
|
elif op["op"] == "delete":
|
|
del parent[key]
|
|
else:
|
|
raise ValueError("unknown op %s" % op["op"])
|
|
return record
|
|
|
|
|
|
def cmd_negative_suite(directory):
|
|
schema = load_schema()
|
|
index = load_json(os.path.join(directory, NEGATIVE_INDEX))
|
|
problems = []
|
|
for sample in index["samples"]:
|
|
errors = validate_record(load_json(os.path.join(directory, sample)), schema)
|
|
if errors:
|
|
problems.append("sample %s is rejected: %s" % (sample, format_errors(errors)[0]))
|
|
cases = index["cases"]
|
|
ids = [case["id"] for case in cases]
|
|
if len(set(ids)) != len(ids):
|
|
problems.append("duplicate case ids")
|
|
rejected = 0
|
|
for case in cases:
|
|
record = apply_ops(load_json(os.path.join(directory, case["base"])), case.get("ops", []))
|
|
errors = validate_record(record, schema)
|
|
codes = [code for code, _, _ in errors]
|
|
if not errors:
|
|
problems.append("%s: ACCEPTED, expected %s" % (case["id"], case["expect"]))
|
|
elif case["expect"] not in codes:
|
|
problems.append("%s: rejected for %s, expected %s" % (case["id"], format_errors(errors)[0], case["expect"]))
|
|
else:
|
|
rejected += 1
|
|
wanted = [e for e in errors if e[0] == case["expect"]][0]
|
|
print("%s: %s %s: %s" % (case["id"], wanted[0], wanted[1] or "/", wanted[2]))
|
|
if len(cases) < schema["constants"]["min_negative_cases"]:
|
|
problems.append("only %d negative cases, at least %d are required" % (len(cases), schema["constants"]["min_negative_cases"]))
|
|
for problem in problems:
|
|
print("PROBLEM " + problem)
|
|
print("rejected: %d/%d" % (rejected, len(cases)))
|
|
return 0 if not problems and rejected == len(cases) else 1
|
|
|
|
|
|
USAGE = ("usage: validate_component.py <record.json>\n"
|
|
" validate_component.py --negative-suite [--dir <dir>]\n"
|
|
" validate_component.py merge <a.json> <b.json>\n")
|
|
|
|
|
|
def main(argv):
|
|
try:
|
|
if argv[:1] == ["merge"] and len(argv) == 3:
|
|
return cmd_merge(argv[1], argv[2])
|
|
if argv[:1] == ["--negative-suite"]:
|
|
if len(argv) == 1:
|
|
return cmd_negative_suite(HERE)
|
|
if len(argv) == 3 and argv[1] == "--dir":
|
|
return cmd_negative_suite(argv[2])
|
|
elif len(argv) == 1 and not argv[0].startswith("-"):
|
|
return cmd_validate(argv[0])
|
|
except (OSError, ValueError, KeyError, IndexError) as exc:
|
|
sys.stderr.write("error: %s\n" % exc)
|
|
return 2
|
|
sys.stderr.write(USAGE)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv[1:]))
|