STRA-256's thresholds schema names the source S3.7; rename the enum value from S3.7_FILE in schema.json, the test and the countable-without-summary fixture. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
357 lines
18 KiB
Python
357 lines
18 KiB
Python
"""Tests of the END_TO_END evidence validator (STRA-246). Run: python -m unittest discover -s scripts/e2e/evidence -p "test_validate.py" -v
|
|
Stdlib only, Python >= 3.9."""
|
|
import copy
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
|
|
sys.path.insert(0, HERE)
|
|
sys.path.insert(0, os.path.join(HERE, ".."))
|
|
import validate as V # noqa: E402
|
|
|
|
VALIDATE = os.path.join(HERE, "validate.py")
|
|
SAMPLES = ["sample_ours.json", "sample_vanilla_default.json", "sample_vanilla_noskip.json"]
|
|
|
|
|
|
def load(name):
|
|
return V.load_json(os.path.join(HERE, name))
|
|
|
|
|
|
def run_cli(*args):
|
|
proc = subprocess.run([sys.executable, VALIDATE] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd=REPO)
|
|
return proc.returncode, proc.stdout, proc.stderr
|
|
|
|
|
|
def codes(rec, row_b=None):
|
|
return [c for c, _, _ in V.validate_record(rec, V.load_schema(), row_b)]
|
|
|
|
|
|
class SchemaInterpreter(unittest.TestCase):
|
|
def check(self, schema, value, defs=None):
|
|
errors = []
|
|
V.interpret(schema, value, "", defs or {}, errors)
|
|
return [c for c, _, _ in errors]
|
|
|
|
def test_bool_is_not_a_number_or_integer(self):
|
|
self.assertEqual(self.check({"type": "number"}, True), ["WRONG_TYPE"])
|
|
self.assertEqual(self.check({"type": "integer"}, True), ["WRONG_TYPE"])
|
|
self.assertEqual(self.check({"type": "integer"}, 3), [])
|
|
self.assertEqual(self.check({"type": "number"}, 3), [])
|
|
self.assertEqual(self.check({"type": "integer"}, 3.5), ["WRONG_TYPE"])
|
|
|
|
def test_required_enum_const_pattern_range(self):
|
|
schema = {"type": "object", "required": ["a"], "additionalProperties": False, "properties": {"a": {"type": "string", "enum": ["x"]}}}
|
|
self.assertEqual(self.check(schema, {}), ["MISSING_FIELD"])
|
|
self.assertEqual(self.check(schema, {"a": "y"}), ["BAD_VALUE"])
|
|
self.assertEqual(self.check(schema, {"a": "x", "b": 1}), ["UNKNOWN_FIELD"])
|
|
self.assertEqual(self.check({"type": "string", "pattern": "^a"}, "ba"), ["BAD_PATTERN"])
|
|
self.assertEqual(self.check({"type": "number", "exclusiveMinimum": 0}, 0), ["OUT_OF_RANGE"])
|
|
self.assertEqual(self.check({"type": "number", "minimum": 0, "maximum": 1}, 1.5), ["OUT_OF_RANGE"])
|
|
self.assertEqual(self.check({"type": "array", "minItems": 1}, []), ["TOO_FEW_ITEMS"])
|
|
|
|
def test_anyof_and_ref(self):
|
|
defs = {"s": {"type": "string", "minLength": 1}}
|
|
schema = {"anyOf": [{"$ref": "#/definitions/s"}, {"type": "null"}]}
|
|
self.assertEqual(self.check(schema, None, defs), [])
|
|
self.assertEqual(self.check(schema, "x", defs), [])
|
|
self.assertEqual(self.check(schema, "", defs), ["TOO_SHORT"])
|
|
self.assertEqual(self.check(schema, 5, defs), ["NO_ALTERNATIVE_MATCHES"])
|
|
with self.assertRaises(ValueError):
|
|
self.check({"$ref": "#/definitions/missing"}, 1, defs)
|
|
|
|
def test_schema_uses_only_supported_keywords(self):
|
|
supported = {"$comment", "$ref", "anyOf", "type", "const", "enum", "minLength", "pattern", "minimum", "exclusiveMinimum", "maximum",
|
|
"required", "properties", "additionalProperties", "minItems", "items"}
|
|
|
|
def walk(node, path):
|
|
if isinstance(node, dict):
|
|
for key, child in node.items():
|
|
if key in ("properties", "definitions"):
|
|
for name, sub in child.items():
|
|
walk(sub, path + "/" + name)
|
|
elif key in ("anyOf",):
|
|
for index, sub in enumerate(child):
|
|
walk(sub, "%s/%s/%d" % (path, key, index))
|
|
elif key in ("items", "root"):
|
|
walk(child, path + "/" + key)
|
|
else:
|
|
self.assertIn(key, supported, "unsupported keyword %s at %s" % (key, path))
|
|
schema = V.load_schema()
|
|
walk(schema["root"], "root")
|
|
for name, sub in schema["definitions"].items():
|
|
walk(sub, "definitions/" + name)
|
|
|
|
|
|
class SamplesAndCli(unittest.TestCase):
|
|
def test_samples_valid_via_cli_without_edit(self):
|
|
for name, arm in zip(SAMPLES, ["ours", "vanilla_default", "vanilla_noskip"]):
|
|
code, out, _ = run_cli(os.path.join("scripts", "e2e", "evidence", name))
|
|
self.assertEqual((code, out.strip()), (0, "OK " + arm), name)
|
|
|
|
def test_noskip_sample_matches_placeholder_row_b(self):
|
|
code, out, err = run_cli(os.path.join(HERE, "sample_vanilla_noskip.json"), "--row-b-env", os.path.join(HERE, "row_b_env_placeholder.txt"))
|
|
self.assertEqual((code, out.strip(), err), (0, "OK vanilla_noskip", ""))
|
|
|
|
def test_row_b_env_json_list_form(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = os.path.join(tmp, "row_b.json")
|
|
with open(path, "w", encoding="utf-8") as handle:
|
|
json.dump(["STRATA_PREFILL_CPU_SHARE=0", "STRATA_ROUTE_TAIL_SKIP=0"], handle)
|
|
code, out, _ = run_cli(os.path.join(HERE, "sample_vanilla_noskip.json"), "--row-b-env", path)
|
|
self.assertEqual((code, out.strip()), (0, "OK vanilla_noskip"))
|
|
|
|
def test_negative_suite_all_rejected(self):
|
|
code, out, _ = run_cli("--negative-suite")
|
|
match = re.search(r"^rejected: (\d+)/(\d+)$", out, re.M)
|
|
self.assertEqual(code, 0, out)
|
|
self.assertIsNotNone(match)
|
|
self.assertEqual(match.group(1), match.group(2))
|
|
self.assertGreaterEqual(int(match.group(2)), 17)
|
|
|
|
def test_negative_fixtures_and_index_agree(self):
|
|
index = load("negative_cases.json")
|
|
listed = sorted(c["file"] for c in index["cases"])
|
|
on_disk = sorted(n for n in os.listdir(HERE) if n.startswith("neg_") and n.endswith(".json"))
|
|
self.assertEqual(listed, on_disk)
|
|
for case in index["cases"]:
|
|
self.assertTrue(case["expect"])
|
|
|
|
def test_merge_refuses_component(self):
|
|
code, out, _ = run_cli("merge", os.path.join(HERE, "sample_ours.json"), os.path.join(HERE, "neg_component_level.json"))
|
|
self.assertEqual(code, 1)
|
|
self.assertIn("END_TO_END with COMPONENT refused", out)
|
|
|
|
def test_merge_accepts_one_series(self):
|
|
code, out, _ = run_cli("merge", os.path.join(HERE, "sample_ours.json"), os.path.join(HERE, "sample_vanilla_default.json"))
|
|
self.assertEqual(code, 0, out)
|
|
self.assertIn("MERGED 2 records", out)
|
|
|
|
def test_merge_refuses_cold_with_warm(self):
|
|
cold = load("sample_vanilla_default.json")
|
|
cold["cache"]["state"] = "COLD"
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = os.path.join(tmp, "cold.json")
|
|
with open(path, "w", encoding="utf-8") as handle:
|
|
json.dump(cold, handle)
|
|
code, out, _ = run_cli("merge", os.path.join(HERE, "sample_ours.json"), path)
|
|
self.assertEqual(code, 1)
|
|
self.assertIn("SERIES_CACHE_MIXED", out)
|
|
|
|
def test_usage_and_io_errors_exit_2(self):
|
|
self.assertEqual(run_cli()[0], 2)
|
|
self.assertEqual(run_cli("no_such_file.json")[0], 2)
|
|
|
|
def test_rejection_exit_code_and_reason(self):
|
|
code, out, _ = run_cli(os.path.join(HERE, "neg_context_131072.json"))
|
|
self.assertEqual(code, 1)
|
|
self.assertIn("RULE_256K_CONTEXT", out)
|
|
|
|
def test_schema_validator_is_python39_syntax(self):
|
|
import ast
|
|
for name in ("validate.py", "test_validate.py"):
|
|
with open(os.path.join(HERE, name), "r", encoding="utf-8") as handle:
|
|
ast.parse(handle.read(), filename=name, feature_version=(3, 9))
|
|
|
|
def test_long_session_still_has_the_256k_default(self):
|
|
# the 256k constant of schema.json mirrors long_session.py's --context default; long_session.py is read, never edited
|
|
import inspect
|
|
import long_session
|
|
self.assertIn("default=%d" % V.load_schema()["constants"]["context_tokens_256k"], inspect.getsource(long_session.main))
|
|
|
|
|
|
class Rules(unittest.TestCase):
|
|
def setUp(self):
|
|
self.ours = load("sample_ours.json")
|
|
self.van = load("sample_vanilla_default.json")
|
|
self.noskip = load("sample_vanilla_noskip.json")
|
|
|
|
def test_constants_are_the_256k_class(self):
|
|
constants = V.load_schema()["constants"]
|
|
self.assertEqual((constants["context_tokens_256k"], constants["min_max_prompt_tokens_256k"]), (262144, 200000))
|
|
|
|
def test_prompt_tokens_boundary(self):
|
|
self.ours["metrics"]["turns"][-1]["prompt_tokens"] = 200000
|
|
self.assertEqual(codes(self.ours), [])
|
|
self.ours["metrics"]["turns"][-1]["prompt_tokens"] = 199999
|
|
self.assertEqual(codes(self.ours), ["RULE_256K_PROMPT"])
|
|
|
|
def test_context_must_be_exactly_262144(self):
|
|
for value in (131072, 262143, 524288):
|
|
self.ours["configuration"]["context_tokens"] = value
|
|
self.assertEqual(codes(self.ours), ["RULE_256K_CONTEXT"])
|
|
|
|
def test_bare_cpu_prefix_rejected_prefixed_accepted(self):
|
|
self.ours["kernel_lines"] = ["cpu: x"]
|
|
self.assertIn("BAD_PATTERN", codes(self.ours))
|
|
self.ours["kernel_lines"] = ["leleka-serve cpu: x"]
|
|
self.assertEqual(codes(self.ours), [])
|
|
self.ours["kernel_lines"] = ["xleleka-serve cpu: x"]
|
|
self.assertIn("BAD_PATTERN", codes(self.ours))
|
|
|
|
def test_vanilla_printed_cpu_line_rejected(self):
|
|
self.van["vanilla_cpu_family"]["printed"] = ["cpu: kernel family avx512"]
|
|
self.assertEqual(codes(self.van), ["RULE_VANILLA_CLAIMS_CPU"])
|
|
|
|
def test_vanilla_family_block_shapes(self):
|
|
self.van["vanilla_cpu_family"]["predicate"] = {"tool": "iq_avx2_parity", "output": "avx2=1 avx512=1"}
|
|
self.van["vanilla_cpu_family"]["printed"] = ["note line"]
|
|
self.assertEqual(codes(self.van), [])
|
|
self.van["vanilla_cpu_family"]["predicate"] = "no predicate"
|
|
self.assertEqual(codes(self.van), ["BAD_PATTERN"])
|
|
self.van["vanilla_cpu_family"]["predicate"] = 5
|
|
self.assertEqual(codes(self.van), ["NO_ALTERNATIVE_MATCHES"])
|
|
self.van["vanilla_cpu_family"]["predicate"] = "unavailable: no compiler"
|
|
self.van["vanilla_cpu_family"]["printed"] = "printed nothing"
|
|
self.assertEqual(codes(self.van), ["BAD_VALUE"])
|
|
|
|
def test_ours_cannot_carry_vanilla_block(self):
|
|
self.ours["vanilla_cpu_family"] = copy.deepcopy(self.van["vanilla_cpu_family"])
|
|
self.assertEqual(codes(self.ours), ["RULE_OURS_NO_VANILLA_BLOCK"])
|
|
|
|
def test_observed_build_id_by_arm(self):
|
|
self.van["ours_build_id_observed"] = copy.deepcopy(self.ours["ours_build_id_observed"])
|
|
self.assertEqual(codes(self.van), ["RULE_OBSERVED_BUILD"])
|
|
self.ours["ours_build_id_observed"] = None
|
|
self.assertEqual(codes(self.ours), ["RULE_OBSERVED_BUILD"])
|
|
|
|
def test_build_id_needs_triple_and_features_and_profile_hash(self):
|
|
for key in ("target_triple", "cargo_features", "profile_value_sha256", "commit"):
|
|
rec = copy.deepcopy(self.ours)
|
|
del rec["ours_build_id_frozen"][key]
|
|
self.assertEqual(codes(rec), ["MISSING_FIELD"], key)
|
|
|
|
def test_countable_rules(self):
|
|
rec = copy.deepcopy(self.ours)
|
|
rec.update({"countable": True, "invalid_reasons": [], "thresholds_source": "S3.7"})
|
|
self.assertEqual(codes(rec), [])
|
|
no_summary = copy.deepcopy(rec)
|
|
del no_summary["power_sample_summary"]
|
|
self.assertEqual(codes(no_summary), ["RULE_COUNTABLE_POWER_SUMMARY"])
|
|
bootstrap = copy.deepcopy(rec)
|
|
bootstrap["thresholds_source"] = "BOOTSTRAP"
|
|
self.assertEqual(codes(bootstrap), ["RULE_COUNTABLE_BOOTSTRAP"])
|
|
# a non-countable record may lack the summary (the run is invalid anyway)
|
|
invalid = copy.deepcopy(self.ours)
|
|
del invalid["power_sample_summary"]
|
|
self.assertEqual(codes(invalid), [])
|
|
|
|
def test_power_limit_na_and_zero_rejected(self):
|
|
self.ours["hardware"]["enforced_power_limit_w_end"] = "N/A"
|
|
self.assertEqual(codes(self.ours), ["WRONG_TYPE"])
|
|
self.ours["hardware"]["enforced_power_limit_w_end"] = 0
|
|
self.assertEqual(codes(self.ours), ["OUT_OF_RANGE"])
|
|
|
|
def test_power_limit_changed_flag_follows_limits(self):
|
|
self.ours["hardware"]["enforced_power_limit_w_end"] = 110.0
|
|
self.assertEqual(codes(self.ours), ["RULE_POWER_LIMIT_CHANGED"])
|
|
self.ours["power_sample_summary"]["power_limit_changed"] = True
|
|
self.assertEqual(codes(self.ours), [])
|
|
|
|
def test_power_source_enum(self):
|
|
self.ours["power_sample_summary"]["power_limit_source"] = "guess"
|
|
self.assertEqual(codes(self.ours), ["BAD_VALUE"])
|
|
|
|
def test_attestation_rules(self):
|
|
self.ours["hardware"]["owner_attestation"] = {"present": False, "identifier": None, "time_utc": None}
|
|
self.assertEqual(codes(self.ours), [])
|
|
self.ours["hardware"]["owner_attestation"] = {"present": True, "identifier": None, "time_utc": None}
|
|
self.assertEqual(codes(self.ours), ["RULE_ATTESTATION"])
|
|
self.ours["hardware"]["owner_attestation"] = {"present": False, "identifier": "x", "time_utc": None}
|
|
self.assertEqual(codes(self.ours), ["RULE_ATTESTATION"])
|
|
|
|
def test_noskip_environment_comparison(self):
|
|
row_b = ["STRATA_PREFILL_CPU_SHARE=0", "STRATA_ROUTE_TAIL_SKIP=0"]
|
|
self.assertEqual(codes(self.noskip, row_b), [])
|
|
self.noskip["vanilla_noskip_environment"].append("STRATA_EXTRA=1")
|
|
self.assertEqual(codes(self.noskip, row_b), ["RULE_NOSKIP_ENV"])
|
|
self.assertEqual(codes(self.noskip), [])
|
|
self.van["vanilla_noskip_environment"] = ["A=1"]
|
|
self.assertEqual(codes(self.van), ["RULE_NOSKIP_ENV"])
|
|
|
|
def test_quality_block_rules(self):
|
|
self.ours["quality"]["experimental"] = True
|
|
self.assertEqual(codes(self.ours), [])
|
|
self.ours["quality"]["tool_call_integrity"] = {"verdict": "PASS", "detail": "x"}
|
|
self.assertEqual(codes(self.ours), [])
|
|
del self.ours["quality"]["tool_call_integrity"]
|
|
self.assertEqual(codes(self.ours), ["MISSING_FIELD"])
|
|
|
|
def test_position_and_predecessor(self):
|
|
self.ours["arm_identity"]["predecessor_arm"] = "vanilla_default"
|
|
self.assertEqual(codes(self.ours), ["RULE_POSITION"])
|
|
self.van["arm_identity"]["predecessor_arm"] = "vanilla_default"
|
|
self.assertEqual(codes(self.van), ["RULE_POSITION"])
|
|
|
|
def test_turn_rules(self):
|
|
self.ours["metrics"]["turns"][2]["cached_tokens"] = 999999
|
|
self.assertEqual(codes(self.ours), ["RULE_TURN_ORDER"])
|
|
self.ours["metrics"]["turns"][2]["cached_tokens"] = 0
|
|
self.ours["metrics"]["turns"][1]["turn"] = 7
|
|
self.assertEqual(codes(self.ours), ["RULE_TURN_ORDER"])
|
|
self.ours["metrics"]["turns"][1]["turn"] = 2
|
|
self.ours["workload"]["turn1_tokens"] = 1
|
|
self.assertEqual(codes(self.ours), ["RULE_TURN1_TOKENS"])
|
|
|
|
def test_no_statistics_fields_per_record(self):
|
|
for key in ("mean", "median", "p95", "ci"):
|
|
rec = copy.deepcopy(self.ours)
|
|
rec["metrics"][key] = 1.0
|
|
self.assertEqual(codes(rec), ["UNKNOWN_FIELD"], key)
|
|
|
|
def test_series_rules(self):
|
|
records = [self.ours, self.van, self.noskip]
|
|
self.assertEqual(V.series_errors(records), [])
|
|
other = copy.deepcopy(self.van)
|
|
other["arm_identity"]["series_id"] = "other"
|
|
other["arm_identity"]["schedule_sha256"] = "0" * 64
|
|
other["ours_build_id_frozen"]["commit"] = "f" * 40
|
|
self.assertEqual(sorted(c for c, _, _ in V.series_errors([self.ours, other])), ["SERIES_BUILD_MIXED", "SERIES_ID_MIXED", "SERIES_SCHEDULE_MIXED"])
|
|
self.assertEqual([c for c, _, _ in V.series_errors([self.ours, copy.deepcopy(self.ours)])], ["SERIES_DUPLICATE_ARM"])
|
|
|
|
def test_bundle_document(self):
|
|
schema = V.load_schema()
|
|
errors, label = V.validate_document({"series_records": [self.ours, self.van, self.noskip]}, schema)
|
|
self.assertEqual((errors, label), ([], "series sample-series-0001"))
|
|
errors, _ = V.validate_document({"series_records": []}, schema)
|
|
self.assertEqual([c for c, _, _ in errors], ["BAD_BUNDLE"])
|
|
broken = copy.deepcopy(self.ours)
|
|
del broken["countable"]
|
|
errors, _ = V.validate_document({"series_records": [self.ours, broken]}, schema)
|
|
self.assertEqual([(c, p) for c, p, _ in errors], [("MISSING_FIELD", "/series_records/1/countable")])
|
|
|
|
def test_level_other_than_end_to_end_rejected(self):
|
|
self.ours["level"] = "COMPONENT_TABLE"
|
|
self.assertEqual(codes(self.ours), ["LEVEL_NOT_END_TO_END"])
|
|
|
|
def test_samples_are_marked_synthetic_and_carry_no_paths(self):
|
|
for name in SAMPLES:
|
|
with open(os.path.join(HERE, name), "r", encoding="utf-8") as handle:
|
|
text = handle.read()
|
|
self.assertTrue(json.loads(text)["synthetic"])
|
|
self.assertNotRegex(text, r"[A-Za-z]:\\\\|/home/|/Users/")
|
|
|
|
|
|
class CharterMap(unittest.TestCase):
|
|
def test_one_row_per_charter_4_3_bullet(self):
|
|
with open(os.path.join(REPO, "PROJECT_CHARTER.md"), "r", encoding="utf-8") as handle:
|
|
lines = handle.read().splitlines()
|
|
start = next(i for i, line in enumerate(lines) if line.startswith("### 4.3"))
|
|
end = next(i for i, line in enumerate(lines) if line.startswith("### 4.4"))
|
|
bullets = [line for line in lines[start:end] if line.startswith("- ")]
|
|
with open(os.path.join(HERE, "charter_map.md"), "r", encoding="utf-8") as handle:
|
|
rows = [line for line in handle.read().splitlines() if line.startswith("| ")]
|
|
self.assertEqual(len(rows) - 1, len(bullets))
|
|
stats = [row for row in rows if "mean" in row and "median" in row and "percentiles" in row]
|
|
self.assertEqual(len(stats), 1)
|
|
self.assertIn("STRA-290", stats[0])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|