#!/usr/bin/env python3 """Run a bounded, self-owned-file cachestat observation; no privileged operations.""" import argparse import hashlib import json import os from pathlib import Path import platform import subprocess import tempfile from datetime import datetime, timezone HERE = Path(__file__).resolve().parent def validate(run): page = run["page_size"] if not isinstance(page, int) or page <= 0: raise ValueError("invalid page size") expected = { "first_byte": (0, 1, 1), "first_page": (0, page, 1), "last_byte_first_page": (page - 1, 1, 1), "cross_boundary": (page - 1, 2, 2), "second_page": (page, page, 1), "zero_length_to_end": (page, 0, 1), } rows = {row["name"]: row for row in run["samples"]} if len(rows) != 7 or len(run["samples"]) != 7 or set(rows) != {"after_write", *expected}: raise ValueError("missing or repeated sample") for name, (off, length, count) in expected.items(): row = rows[name] if (row["off"], row["len"], row["nr_cache"]) != (off, length, count): raise ValueError(f"range boundary differs: {name}") if rows["after_write"]["nr_cache"] != 2 or run["locked_pages"] != 2: raise ValueError("fixture not fully resident") for row in rows.values(): for key in ("nr_cache", "nr_dirty", "nr_writeback", "nr_evicted", "nr_recently_evicted"): if type(row[key]) is not int or row[key] < 0: raise ValueError(f"invalid counter: {key}") if run["negative_controls"] != {"bad_fd_errno": 9, "bad_flags_errno": 22}: raise ValueError("error controls differ") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True, type=Path) parser.add_argument("--temp-dir", type=Path, default=Path.cwd()) parser.add_argument("--repetitions", type=int, default=5) args = parser.parse_args() if not 1 <= args.repetitions <= 20: parser.error("repetitions must be 1..20") if args.output.exists(): parser.error("output already exists") compiler = os.environ.get("CC", "cc") with tempfile.TemporaryDirectory(prefix="cachestat-range-", dir=args.temp_dir) as directory: executable = Path(directory) / "probe" flags = ["-std=c11", "-Wall", "-Wextra", "-Werror", "-O2"] subprocess.run([compiler, *flags, str(HERE / "probe.c"), "-o", str(executable)], check=True, timeout=30) observations = [] for _ in range(args.repetitions): result = subprocess.run([str(executable)], cwd=directory, capture_output=True, text=True, timeout=10) if result.returncode == 77: raise SystemExit("Unsupported/denied environment; no observation published: " + result.stderr) if result.returncode: raise RuntimeError(result.stderr or result.stdout or "probe failed") run = json.loads(result.stdout) validate(run) observations.append(run) record = { "schemaVersion": 1, "kind": "bounded-native-api-observation", "generatedAt": datetime.now(timezone.utc).isoformat(), "repetitions": args.repetitions, "sourceSha256": {name: hashlib.sha256((HERE / name).read_bytes()).hexdigest() for name in ("probe.c", "observe.py")}, "compiler": subprocess.run([compiler, "--version"], check=True, capture_output=True, text=True, timeout=10).stdout.splitlines()[0], "compilerFlags": flags, "python": platform.python_version(), "method": "Fresh two-page self-owned file per trial, unlinked immediately, bytes checked and mapping mlocked; query after write, fsync, six range queries and two error controls.", "limits": "One host, locked tiny fixtures, no performance, eviction, permissions, race, power-loss or attack experiment. Dirty/writeback counts are observations, not required reproducibility invariants.", "observations": observations, } with args.output.open("x") as output: json.dump(record, output, indent=2) output.write("\n") print(f"Validated {len(observations)} native trials; output: {args.output}") if __name__ == "__main__": main()