#!/usr/bin/env python3 """Evidence consistency checks; hashes are not independent provenance. CC0-1.0.""" import hashlib import itertools import json from pathlib import Path import sys MODES = ("live", "reset_live", "clean_exit", "killed_reaped", "killed_unreaped") MAP_FULL = -30792 VALUE_BYTES = 16384 def check(condition, message): if not condition: raise ValueError(message) def digest_for(generations): digest = hashlib.sha256() for key, generation in enumerate(generations): token = f"key={key};generation={generation};".encode("ascii") digest.update((token * (VALUE_BYTES // len(token) + 1))[:VALUE_BYTES]) return digest.hexdigest() def validate_row(row): mode, readers, size = row["mode"], row["readers"], row["map_bytes"] check(mode in MODES and readers in (1, 3) and size in (1048576, 2097152), "invalid configuration") check(row["repetition"] in (1, 2), "invalid repetition") for name in ("readers", "map_bytes", "repetition", "pressure_rc", "before_check_rc", "after_check_rc", "total_commits"): check(type(row[name]) is int, "noninteger field: " + name) check(all(type(v) is int for v in row["followup_rcs"] + row["final_generations"]), "noninteger sequence field") check(all(type(row["cleanup"][k]) is int for k in ("rc", "cleared_slots")), "noninteger cleanup field") if row["wait"] is not None: check(type(row["wait"]["reaped_before_check"]) is bool, "invalid wait boolean") for name in ("before_action", "after_action", "before_check", "after_check", "final_state"): state = row[name] check(all(type(state[k]) is int for k in ("reader_high_water", "extent_bytes", "page_bytes", "map_bytes", "last_txnid")), "noninteger state field") check(all(s["txnid"] is None or type(s["txnid"]) is int for s in state["slots"]), "noninteger transaction ID") pressure = row["pressure_commits"] check(type(pressure) is int and 0 < pressure < 256, "invalid pressure count") check(row["pressure_rc"] == MAP_FULL, "missing initial exhaustion") check(row["old_digests"] == [digest_for([0] * 8)] * readers, "old snapshot oracle mismatch") killed = mode.startswith("killed") before_rc = 0 if mode in ("reset_live", "clean_exit") else MAP_FULL after_rc = MAP_FULL if mode == "live" else 0 check(row["before_check_rc"] == before_rc, "unexpected pre-cleanup result") check(row["after_check_rc"] == after_rc, "unexpected post-cleanup result") check(row["cleanup"] == {"rc": 0, "cleared_slots": readers if killed else 0}, "cleanup did not match slot ownership") check(type(row["pid_present_after_action"]) is bool, "invalid PID observation") check(row["pid_present_after_action"] == (mode not in ("clean_exit", "killed_reaped")), "PID observation mismatch") expected_wait = ({"code": "CLD_KILLED", "signal": "SIGKILL", "reaped_before_check": mode == "killed_reaped"} if killed else None) check(row["wait"] == expected_wait, "termination receipt mismatch") check(row["followup_rcs"] == [0] * 64, "follow-up write failure") total = pressure + (before_rc == 0) + (after_rc == 0) + 64 check(row["total_commits"] == total, "commit count mismatch") generations = [0] * 8 for index in range(total): generations[index % 8] = index + 1 check(row["final_generations"] == generations, "committed history mismatch") check(row["final_digest"] == digest_for(generations), "final byte oracle mismatch") check(row["reopened_digest"] == row["final_digest"], "reopen oracle mismatch") check(isinstance(row["database_sha256"], str) and len(row["database_sha256"]) == 64 and all(c in "0123456789abcdef" for c in row["database_sha256"]), "invalid database hash") active = [{"owner": "child", "txnid": 1}] * readers inactive = [{"owner": "child", "txnid": None}] * readers action_slots = [] if mode == "clean_exit" else inactive if mode == "reset_live" else active checked_slots = [] if killed else action_slots expected_slots = {"before_action": active, "after_action": action_slots, "before_check": action_slots, "after_check": checked_slots, "final_state": []} expected_txnids = {"before_action": pressure + 1, "after_action": pressure + 1, "before_check": pressure + 1 + (before_rc == 0), "after_check": pressure + 1 + (before_rc == 0), "final_state": total + 1} previous_extent = 0 for name, slots in expected_slots.items(): state = row[name] check(state["slots"] == slots, f"incorrect reader listing at {name}") check(state["reader_high_water"] == readers, f"incorrect high-water count at {name}") check(state["map_bytes"] == size and state["page_bytes"] == 4096, "unsupported map/page geometry") check(type(state["extent_bytes"]) is int and previous_extent <= state["extent_bytes"] < size and state["extent_bytes"] % 4096 == 0, "invalid or shrinking extent") check(state["last_txnid"] == expected_txnids[name], "transaction ID mismatch") previous_extent = state["extent_bytes"] check(row["after_check"]["extent_bytes"] == row["before_check"]["extent_bytes"], "cleanup changed database extent") def validate(result): check(type(result["schema_version"]) is int and result["schema_version"] == 1, "unsupported schema") check(result["runner_sha256"] == hashlib.sha256( (Path(__file__).parent / "run.py").read_bytes()).hexdigest(), "runner hash mismatch") check(result["source"] == json.loads((Path(__file__).parent / "source-lock.json").read_text()), "source lock mismatch") check(result["environment"]["flags"] == ["MDB_NOTLS"], "unexpected environment flags") check(result["environment"]["build_flags"] == ["-std=c11", "-O2", "-fPIC", "-shared", "-pthread"], "unexpected build flags") cases = result["cases"] expected = set(itertools.product(MODES, (1048576, 2097152), (1, 3), (1, 2))) keys = [(r["mode"], r["map_bytes"], r["readers"], r["repetition"]) for r in cases] check(len(keys) == 40 and len(set(keys)) == 40 and set(keys) == expected, "incomplete or duplicate matrix") for row in cases: validate_row(row) groups = {} for row in cases: normalized = {k: v for k, v in row.items() if k != "repetition"} key = (row["mode"], row["map_bytes"], row["readers"]) if key in groups: check(normalized == groups[key], "repeat outcome differs") groups[key] = normalized return {"cases": len(cases), "killed_cases": sum(r["mode"].startswith("killed") for r in cases), "unreaped_cases": sum(r["mode"] == "killed_unreaped" for r in cases), "all_followup_writes_succeeded": True} if __name__ == "__main__": check(len(sys.argv) == 2, "usage: validate.py results.json") print(json.dumps(validate(json.loads(Path(sys.argv[1]).read_text())), indent=2))