"""Replay six regular-file/stdio EOF controls; no durability or performance claim.""" import argparse import csv from datetime import datetime, timezone import hashlib import io import json from pathlib import Path import platform import subprocess import tempfile ROOT = Path(__file__).resolve().parent FIELDS = ["grow", "reset", "size_bytes", "position_before_retry", "eof_before_reset", "eof_before_retry", "result", "eof_after_retry", "error_after_retry", "position_after_retry"] def expected_rows(): rows = [] for grow in (0, 1): for reset in ("none", "clearerr", "fseek"): available = grow == 1 and reset != "none" rows.append(dict(zip(FIELDS, [grow, reset, 1 + grow, 1, 1, int(reset == "none"), "B" if available else "EOF", int(not available), 0, 2 if available else 1]))) return rows def parse_output(text): reader = csv.DictReader(io.StringIO(text)) if reader.fieldnames != FIELDS: raise ValueError("Unexpected CSV schema") rows = [] for row in reader: if None in row or any(value is None for value in row.values()): raise ValueError("Malformed CSV row") rows.append({key: value if key in ("reset", "result") else int(value) for key, value in row.items()}) if rows != expected_rows(): raise ValueError("Native observations differ from documented controls") return rows def replay(): source = ROOT / "probe.c" runs = [] with tempfile.TemporaryDirectory(prefix="hesela-eof-build-") as tmp: for optimization in ("-O0", "-O2"): binary = Path(tmp) / ("probe" + optimization) flags = ["-std=c11", "-Wall", "-Wextra", "-Werror", optimization] subprocess.run(["cc", *flags, str(source), "-o", str(binary)], check=True, timeout=30, capture_output=True, text=True) result = subprocess.run([str(binary)], check=True, timeout=10, capture_output=True, text=True) runs.append({"flags": flags, "rows": parse_output(result.stdout)}) if runs[0]["rows"] != runs[1]["rows"]: raise ValueError("Optimization variants disagree") return { "schemaVersion": 1, "kind": "native interface demonstration", "capturedAt": datetime.now(timezone.utc).isoformat(), "environment": { "system": platform.system(), "release": platform.release(), "machine": platform.machine(), "libc": list(platform.libc_ver()), "compiler": subprocess.check_output(["cc", "--version"], text=True).splitlines()[0], }, "sourceSha256": hashlib.sha256(source.read_bytes()).hexdigest(), "method": "Six fresh files, independently opened writer and unbuffered reader; completed pwrite before retry.", "limitations": "One host/libc; no concurrent scheduling, read-error injection, power-loss or allocation test.", "runs": runs, "rows": runs[0]["rows"], } def validate_capture(stored, observed): """Check capture structure without requiring the replay host to match.""" if not isinstance(stored, dict): raise ValueError("Capture must be an object") if type(stored.get("schemaVersion")) is not int or stored["schemaVersion"] != 1: raise ValueError("Unsupported capture schema") for field in ("kind", "method", "limitations"): if stored.get(field) != observed[field]: raise ValueError("Capture description differs: " + field) environment = stored.get("environment") if not isinstance(environment, dict): raise ValueError("Missing capture environment") for field in ("system", "release", "machine", "compiler"): if not isinstance(environment.get(field), str) or not environment[field].strip(): raise ValueError("Invalid environment field: " + field) libc = environment.get("libc") if not isinstance(libc, list) or len(libc) != 2 or not all( isinstance(value, str) and value.strip() for value in libc): raise ValueError("Missing libc provenance") captured = stored.get("capturedAt") if not isinstance(captured, str): raise ValueError("Missing capture timestamp") if datetime.fromisoformat(captured).utcoffset() is None: raise ValueError("Capture timestamp needs a timezone") if stored.get("sourceSha256") != observed["sourceSha256"]: raise ValueError("Published source hash differs") for field in ("rows", "runs"): # JSON distinguishes false/0 and 1.0/1; Python container equality does not. if json.dumps(stored.get(field), sort_keys=True, allow_nan=False) != json.dumps( observed[field], sort_keys=True, allow_nan=False): raise ValueError("Replay differs from published " + field) def load_capture(text): def unique_object(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("Duplicate capture key: " + key) result[key] = value return result return json.loads(text, object_pairs_hook=unique_object) def main(): parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--capture", type=Path) group.add_argument("--check", type=Path) args = parser.parse_args() observed = replay() if args.capture: args.capture.write_text(json.dumps(observed, indent=2) + "\n") else: validate_capture(load_capture(args.check.read_text()), observed) print("PASS: six controls at -O0 and -O2; 12 native executions") if __name__ == "__main__": main()