New files only under scripts/e2e/evidence/: schema.json (v1), a stdlib-only Python 3.9 validator that interprets it (validate.py, CLI v1: record, --negative-suite, merge), three synthetic sample records, 33 neg_*.json fixtures with their expected reasons, a placeholder row (b) environment list, the charter 4.3 field map and 40 unittest tests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
411 lines
21 KiB
Python
411 lines
21 KiB
Python
#!/usr/bin/env python3
|
|
"""Validator for END_TO_END evidence records (STRA-246, S0.1). Offline, stdlib only, Python >= 3.9.
|
|
|
|
CLI v1 (fixed here; later leaves and acceptance commands use it):
|
|
|
|
validate.py <record.json> [--row-b-env <file>] exit 0 and `OK <arm>` when valid, exit 1 and the reasons when rejected
|
|
validate.py --negative-suite [--dir <dir>] every neg_*.json must be rejected for the reason named in negative_cases.json;
|
|
exit 0 and `rejected: N/N` when all are
|
|
validate.py merge <a.json> <b.json> END_TO_END records only; `END_TO_END with COMPONENT refused` (exit 1) otherwise
|
|
|
|
A file is one record, or a series bundle {"series_records": [record, ...]} (checked for the series rules). The schema is
|
|
schema.json, interpreted by the small evaluator below (no jsonschema); the cross-field rules are the RULE_* / SERIES_* functions.
|
|
`countable` is derived elsewhere (STRA-312); this validator only rejects countable=true without the power-sample summary or under
|
|
BOOTSTRAP thresholds. No statistics are computed here (STRA-290).
|
|
|
|
--row-b-env file: the literal environment list of row (b) of S0.7, either a JSON list of "NAME=VALUE" strings or a text file with
|
|
one NAME=VALUE per line (blank lines and lines starting with # are ignored). Without the option the vanilla_noskip environment
|
|
is not compared (a note goes to stderr).
|
|
"""
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
SCHEMA_PATH = os.path.join(HERE, "schema.json")
|
|
NEGATIVE_INDEX = "negative_cases.json"
|
|
LEVEL = "END_TO_END"
|
|
REFUSED_MESSAGE = "END_TO_END with COMPONENT refused"
|
|
OURS = "ours"
|
|
VANILLA_ARMS = ("vanilla_default", "vanilla_noskip")
|
|
|
|
|
|
def load_json(path):
|
|
with open(path, "r", encoding="utf-8") as handle:
|
|
return json.load(handle)
|
|
|
|
|
|
def load_schema():
|
|
return load_json(SCHEMA_PATH)
|
|
|
|
|
|
# ---------------------------------------------------------------- schema interpreter
|
|
|
|
def _type_ok(value, name):
|
|
if name == "null":
|
|
return value is None
|
|
if name == "boolean":
|
|
return isinstance(value, bool)
|
|
if name == "integer":
|
|
return isinstance(value, int) and not isinstance(value, bool)
|
|
if name == "number":
|
|
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
if name == "string":
|
|
return isinstance(value, str)
|
|
if name == "object":
|
|
return isinstance(value, dict)
|
|
if name == "array":
|
|
return isinstance(value, list)
|
|
raise ValueError("schema uses an unsupported type: %s" % name)
|
|
|
|
|
|
def _short(value):
|
|
text = json.dumps(value, sort_keys=True)
|
|
return text if len(text) <= 60 else text[:57] + "..."
|
|
|
|
|
|
def interpret(schema, value, path, definitions, errors):
|
|
"""Append (code, path, message) to errors for every violation of schema by value."""
|
|
if "$ref" in schema:
|
|
prefix = "#/definitions/"
|
|
ref = schema["$ref"]
|
|
if not ref.startswith(prefix) or ref[len(prefix):] not in definitions:
|
|
raise ValueError("schema has an unresolvable $ref: %s" % ref)
|
|
interpret(definitions[ref[len(prefix):]], value, path, definitions, errors)
|
|
return
|
|
if "anyOf" in schema:
|
|
failures = []
|
|
for branch in schema["anyOf"]:
|
|
found = []
|
|
interpret(branch, value, path, definitions, found)
|
|
if not found:
|
|
return
|
|
failures.append(found)
|
|
# a branch that failed on the type of this very value is not the intended form; report the branches that fit the type
|
|
fitting = [f for f in failures if not (f[0][0] == "WRONG_TYPE" and f[0][1] == path)]
|
|
if len(fitting) == 1:
|
|
errors.extend(fitting[0])
|
|
else:
|
|
errors.append(("NO_ALTERNATIVE_MATCHES", path, "matches none of the allowed forms (%s)" % "; ".join(f[0][2] for f in failures)))
|
|
return
|
|
if "type" in schema:
|
|
names = schema["type"] if isinstance(schema["type"], list) else [schema["type"]]
|
|
if not any(_type_ok(value, name) for name in names):
|
|
errors.append(("WRONG_TYPE", path, "expected %s, got %s" % ("/".join(names), _short(value))))
|
|
return
|
|
if "const" in schema and value != schema["const"]:
|
|
errors.append(("BAD_VALUE", path, "must be %s, got %s" % (_short(schema["const"]), _short(value))))
|
|
return
|
|
if "enum" in schema and value not in schema["enum"]:
|
|
errors.append(("BAD_VALUE", path, "must be one of %s, got %s" % (_short(schema["enum"]), _short(value))))
|
|
return
|
|
if isinstance(value, str):
|
|
if "minLength" in schema and len(value) < schema["minLength"]:
|
|
errors.append(("TOO_SHORT", path, "string shorter than %d" % schema["minLength"]))
|
|
if "pattern" in schema and re.search(schema["pattern"], value) is None:
|
|
errors.append(("BAD_PATTERN", path, "%s does not match %s" % (_short(value), schema["pattern"])))
|
|
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
if "minimum" in schema and value < schema["minimum"]:
|
|
errors.append(("OUT_OF_RANGE", path, "%s is below %s" % (_short(value), schema["minimum"])))
|
|
if "exclusiveMinimum" in schema and value <= schema["exclusiveMinimum"]:
|
|
errors.append(("OUT_OF_RANGE", path, "%s must be above %s" % (_short(value), schema["exclusiveMinimum"])))
|
|
if "maximum" in schema and value > schema["maximum"]:
|
|
errors.append(("OUT_OF_RANGE", path, "%s is above %s" % (_short(value), schema["maximum"])))
|
|
if isinstance(value, dict):
|
|
for key in schema.get("required", []):
|
|
if key not in value:
|
|
errors.append(("MISSING_FIELD", path + "/" + key, "required field is absent"))
|
|
props = schema.get("properties", {})
|
|
for key in sorted(value):
|
|
if key in props:
|
|
interpret(props[key], value[key], path + "/" + key, definitions, errors)
|
|
elif schema.get("additionalProperties") is False:
|
|
errors.append(("UNKNOWN_FIELD", path + "/" + key, "field is not in the schema"))
|
|
if isinstance(value, list):
|
|
if "minItems" in schema and len(value) < schema["minItems"]:
|
|
errors.append(("TOO_FEW_ITEMS", path, "fewer than %d items" % schema["minItems"]))
|
|
if "items" in schema:
|
|
for index, item in enumerate(value):
|
|
interpret(schema["items"], item, "%s/%d" % (path, index), definitions, errors)
|
|
|
|
|
|
# ---------------------------------------------------------------- cross-field rules
|
|
|
|
def _read_row_b_env(path):
|
|
with open(path, "r", encoding="utf-8") as handle:
|
|
text = handle.read()
|
|
if path.lower().endswith(".json"):
|
|
entries = json.loads(text)
|
|
else:
|
|
entries = [line.strip() for line in text.splitlines() if line.strip() and not line.lstrip().startswith("#")]
|
|
if not isinstance(entries, list) or not all(isinstance(e, str) for e in entries):
|
|
raise ValueError("--row-b-env file must hold a list of NAME=VALUE strings")
|
|
return entries
|
|
|
|
|
|
def rule_errors(rec, constants, row_b_env):
|
|
"""Cross-field rules. Runs only on a record that already passed the schema, so the shapes are known."""
|
|
errors = []
|
|
arm = rec["arm_identity"]["arm"]
|
|
turns = rec["metrics"]["turns"]
|
|
|
|
if rec["configuration"]["context_tokens"] != constants["context_tokens_256k"]:
|
|
errors.append(("RULE_256K_CONTEXT", "/configuration/context_tokens",
|
|
"not the 256k class: context_tokens %d, required %d" % (rec["configuration"]["context_tokens"], constants["context_tokens_256k"])))
|
|
largest = max(t["prompt_tokens"] for t in turns)
|
|
if largest < constants["min_max_prompt_tokens_256k"]:
|
|
errors.append(("RULE_256K_PROMPT", "/metrics/turns",
|
|
"not the 256k class: largest prompt_tokens %d, required >= %d" % (largest, constants["min_max_prompt_tokens_256k"])))
|
|
if rec["workload"]["turn1_tokens"] != turns[0]["prompt_tokens"]:
|
|
errors.append(("RULE_TURN1_TOKENS", "/workload/turn1_tokens", "differs from metrics.turns[0].prompt_tokens"))
|
|
for index, turn in enumerate(turns):
|
|
if turn["turn"] != index + 1:
|
|
errors.append(("RULE_TURN_ORDER", "/metrics/turns/%d/turn" % index, "turn numbers must run 1..n in order"))
|
|
if turn["cached_tokens"] > turn["prompt_tokens"]:
|
|
errors.append(("RULE_TURN_ORDER", "/metrics/turns/%d/cached_tokens" % index, "cached_tokens exceeds prompt_tokens"))
|
|
|
|
ident = rec["arm_identity"]
|
|
if ident["position"] == 1 and ident["predecessor_arm"] != "none":
|
|
errors.append(("RULE_POSITION", "/arm_identity/predecessor_arm", "position 1 has no predecessor, must be 'none'"))
|
|
if ident["position"] > 1 and ident["predecessor_arm"] in ("none", ident["arm"]):
|
|
errors.append(("RULE_POSITION", "/arm_identity/predecessor_arm", "position %d needs another arm as predecessor" % ident["position"]))
|
|
|
|
observed = rec["ours_build_id_observed"]
|
|
if arm == OURS and observed is None:
|
|
errors.append(("RULE_OBSERVED_BUILD", "/ours_build_id_observed", "an ours record carries the observed build id"))
|
|
if arm != OURS and observed is not None:
|
|
errors.append(("RULE_OBSERVED_BUILD", "/ours_build_id_observed", "a vanilla record has no observed ours build id, must be null"))
|
|
|
|
lines = rec.get("kernel_lines", [])
|
|
bare = re.compile(constants["bare_cpu_line_regex"])
|
|
if arm == OURS:
|
|
cpu = re.compile(constants["ours_cpu_line_regex"])
|
|
if not any(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)"))
|
|
for key in ("vanilla_cpu_family", "vanilla_noskip_environment"):
|
|
if key in rec:
|
|
errors.append(("RULE_OURS_NO_VANILLA_BLOCK", "/" + key, "an ours record does not carry " + key))
|
|
else:
|
|
if lines:
|
|
errors.append(("RULE_VANILLA_CLAIMS_CPU", "/kernel_lines", "the vanilla engine prints no cpu: line; use the vanilla_cpu_family block"))
|
|
if "vanilla_cpu_family" not in rec:
|
|
errors.append(("RULE_VANILLA_BLOCK", "/vanilla_cpu_family", "a vanilla record needs the vanilla_cpu_family block"))
|
|
else:
|
|
for where in (rec["vanilla_cpu_family"]["printed"], rec["vanilla_cpu_family"]["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 arm == "vanilla_noskip":
|
|
env = rec.get("vanilla_noskip_environment")
|
|
if env is None:
|
|
errors.append(("RULE_NOSKIP_ENV", "/vanilla_noskip_environment", "a vanilla_noskip record carries its environment"))
|
|
elif row_b_env is not None and sorted(env) != sorted(row_b_env):
|
|
missing = sorted(set(row_b_env) - set(env))
|
|
extra = sorted(set(env) - set(row_b_env))
|
|
errors.append(("RULE_NOSKIP_ENV", "/vanilla_noskip_environment",
|
|
"differs from the --row-b-env list (missing %s, extra %s)" % (missing, extra)))
|
|
elif "vanilla_noskip_environment" in rec:
|
|
errors.append(("RULE_NOSKIP_ENV", "/vanilla_noskip_environment", "only a vanilla_noskip record carries an environment"))
|
|
|
|
hardware = rec["hardware"]
|
|
attestation = hardware["owner_attestation"]
|
|
if attestation["present"] and (attestation["identifier"] is None or attestation["time_utc"] is None):
|
|
errors.append(("RULE_ATTESTATION", "/hardware/owner_attestation", "a present attestation needs identifier and time_utc"))
|
|
if not attestation["present"] and (attestation["identifier"] is not None or attestation["time_utc"] is not None):
|
|
errors.append(("RULE_ATTESTATION", "/hardware/owner_attestation", "an absent attestation has identifier and time_utc null"))
|
|
|
|
summary = rec.get("power_sample_summary")
|
|
if summary is not None:
|
|
if not summary["min_w"] <= summary["mean_w"] <= summary["max_w"]:
|
|
errors.append(("RULE_POWER_SUMMARY_ORDER", "/power_sample_summary", "min_w <= mean_w <= max_w does not hold"))
|
|
changed = hardware["enforced_power_limit_w_start"] != hardware["enforced_power_limit_w_end"]
|
|
if summary["power_limit_changed"] != changed:
|
|
errors.append(("RULE_POWER_LIMIT_CHANGED", "/power_sample_summary/power_limit_changed",
|
|
"must be %s: start and end enforced limits %s" % (str(changed).lower(), "differ" if changed else "are equal")))
|
|
if rec["countable"]:
|
|
if summary is None:
|
|
errors.append(("RULE_COUNTABLE_POWER_SUMMARY", "/power_sample_summary", "countable=true needs the power-sample summary"))
|
|
if rec["thresholds_source"] == "BOOTSTRAP":
|
|
errors.append(("RULE_COUNTABLE_BOOTSTRAP", "/thresholds_source", "countable=true is not allowed under BOOTSTRAP thresholds"))
|
|
return errors
|
|
|
|
|
|
def validate_record(rec, schema, row_b_env=None):
|
|
"""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 != LEVEL:
|
|
return [("LEVEL_NOT_END_TO_END", "/level", "level is %s, this validator takes %s records only" % (_short(level), LEVEL))]
|
|
errors = []
|
|
interpret(schema["root"], rec, "", schema["definitions"], errors)
|
|
if not errors:
|
|
errors.extend(rule_errors(rec, schema["constants"], row_b_env))
|
|
return errors
|
|
|
|
|
|
def series_errors(records):
|
|
"""Rules over several records that must be one series: never mix identities, never pool WARM with COLD."""
|
|
errors = []
|
|
first = records[0]
|
|
first_ident = first["arm_identity"]
|
|
seen = {}
|
|
for index, rec in enumerate(records):
|
|
ident = rec["arm_identity"]
|
|
where = "/series_records/%d" % index
|
|
if ident["series_id"] != first_ident["series_id"]:
|
|
errors.append(("SERIES_ID_MIXED", where, "series_id differs from record 0"))
|
|
if ident["schedule_sha256"] != first_ident["schedule_sha256"]:
|
|
errors.append(("SERIES_SCHEDULE_MIXED", where, "schedule_sha256 differs from record 0"))
|
|
if rec["ours_build_id_frozen"] != first["ours_build_id_frozen"]:
|
|
errors.append(("SERIES_BUILD_MIXED", where, "ours_build_id_frozen differs from record 0"))
|
|
if rec["cache"]["state"] != first["cache"]["state"]:
|
|
errors.append(("SERIES_CACHE_MIXED", where, "cache state %s differs from %s in record 0: WARM and COLD are never pooled"
|
|
% (rec["cache"]["state"], first["cache"]["state"])))
|
|
key = (ident["block"], ident["arm"])
|
|
if key in seen:
|
|
errors.append(("SERIES_DUPLICATE_ARM", where, "block %d already has a record of arm %s (record %d)" % (key[0], key[1], seen[key])))
|
|
seen[key] = index
|
|
return errors
|
|
|
|
|
|
def validate_document(doc, schema, row_b_env=None):
|
|
"""A file holds one record or a series bundle. Returns (errors, label)."""
|
|
if isinstance(doc, dict) and "series_records" in doc:
|
|
records = doc["series_records"]
|
|
extra = [k for k in doc if k != "series_records"]
|
|
if extra or not isinstance(records, list) or not records:
|
|
return [("BAD_BUNDLE", "/series_records", "a bundle is {\"series_records\": [record, ...]} with at least one record")], "bundle"
|
|
errors = []
|
|
for index, rec in enumerate(records):
|
|
for code, path, message in validate_record(rec, schema, row_b_env):
|
|
errors.append((code, "/series_records/%d%s" % (index, path), message))
|
|
if not errors:
|
|
errors.extend(series_errors(records))
|
|
if errors:
|
|
return errors, "bundle"
|
|
return errors, "series %s" % records[0]["arm_identity"]["series_id"]
|
|
errors = validate_record(doc, schema, row_b_env)
|
|
if errors:
|
|
return errors, "record"
|
|
return errors, doc["arm_identity"]["arm"]
|
|
|
|
|
|
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]
|
|
|
|
|
|
# ---------------------------------------------------------------- commands
|
|
|
|
def format_errors(errors):
|
|
return ["REJECTED %s %s: %s" % (code, path or "/", message) for code, path, message in errors]
|
|
|
|
|
|
def cmd_validate(path, row_b_path):
|
|
schema = load_schema()
|
|
row_b = _read_row_b_env(row_b_path) if row_b_path else None
|
|
doc = load_json(path)
|
|
errors, label = validate_document(doc, schema, row_b)
|
|
if errors:
|
|
for line in format_errors(errors):
|
|
print(line)
|
|
return 1
|
|
if row_b is None and _has_noskip(doc):
|
|
sys.stderr.write("note: no --row-b-env given, the vanilla_noskip environment was not compared\n")
|
|
print("OK %s" % label)
|
|
return 0
|
|
|
|
|
|
def _has_noskip(doc):
|
|
records = doc["series_records"] if "series_records" in doc else [doc]
|
|
return any(r["arm_identity"]["arm"] == "vanilla_noskip" 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 any(level != LEVEL for level in levels):
|
|
print(REFUSED_MESSAGE if LEVEL in levels else "merge refused: no END_TO_END record in %s" % sorted(set(map(str, levels))))
|
|
return 1
|
|
schema = load_schema()
|
|
records = []
|
|
for doc in docs:
|
|
errors, _ = validate_document(doc, schema)
|
|
if errors:
|
|
for line in format_errors(errors):
|
|
print(line)
|
|
return 1
|
|
records.extend(doc["series_records"] if "series_records" in doc else [doc])
|
|
errors = series_errors(records)
|
|
if errors:
|
|
for line in format_errors(errors):
|
|
print(line)
|
|
return 1
|
|
print("MERGED %d records of series %s" % (len(records), records[0]["arm_identity"]["series_id"]))
|
|
return 0
|
|
|
|
|
|
def cmd_negative_suite(directory):
|
|
schema = load_schema()
|
|
index = load_json(os.path.join(directory, NEGATIVE_INDEX))
|
|
cases = index["cases"]
|
|
problems = []
|
|
on_disk = sorted(name for name in os.listdir(directory) if name.startswith("neg_") and name.endswith(".json"))
|
|
listed = sorted(case["file"] for case in cases)
|
|
if on_disk != listed:
|
|
problems.append("fixtures and %s disagree: only on disk %s, only in index %s"
|
|
% (NEGATIVE_INDEX, sorted(set(on_disk) - set(listed)), sorted(set(listed) - set(on_disk))))
|
|
for sample in index["samples"]:
|
|
errors, _ = validate_document(load_json(os.path.join(directory, sample)), schema)
|
|
if errors:
|
|
problems.append("sample %s is rejected: %s" % (sample, format_errors(errors)[0]))
|
|
rejected = 0
|
|
for case in cases:
|
|
row_b = _read_row_b_env(os.path.join(directory, case["row_b_env"])) if case.get("row_b_env") else None
|
|
errors, _ = validate_document(load_json(os.path.join(directory, case["file"])), schema, row_b)
|
|
codes = [code for code, _, _ in errors]
|
|
if not errors:
|
|
problems.append("%s: ACCEPTED, expected %s" % (case["file"], case["expect"]))
|
|
elif case["expect"] not in codes:
|
|
problems.append("%s: rejected for %s, expected %s" % (case["file"], 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["file"], 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.py <record.json> [--row-b-env <file>]\n"
|
|
" validate.py --negative-suite [--dir <dir>]\n"
|
|
" validate.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], None)
|
|
elif len(argv) == 3 and argv[1] == "--row-b-env" and not argv[0].startswith("-"):
|
|
return cmd_validate(argv[0], argv[2])
|
|
except (OSError, ValueError) 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:]))
|