#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Observe Linux stdio output boundaries without changing device configuration. Run: python3 run-stdio-boundary.py --repeats 5 > stdio-boundary.json Place stdio-boundary.c next to this runner. Requires Linux, /dev/full and cc. """ import argparse from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import shutil import subprocess import sys import tempfile CASE_IDS = [ "buffer-before-file-sync", "full-device-flush", "full-device-close", "fwrite-item-units", ] def check_cases(cases): """Expected observations for the recorded fully buffered Linux setup.""" if [case.get("id") for case in cases] != CASE_IDS: raise ValueError("unexpected case sequence") a, b, c, d = cases return [ a["fputc_return"] == ord("A") and a["size_before_sync"] == a["size_after_sync"] == 0 and a["fsync_before_return"] == a["fflush_return"] == 0 and a["size_after_flush"] == a["pread_return"] == 1 and a["read_byte"] == ord("A") and a["stream_error"] == 0 and a["fsync_after_return"] == a["fclose_return"] == 0, b["fputc_return"] == ord("B") and b["error_before"] == 0 and b["fflush_return"] != 0 and b["fflush_errno_name"] == "ENOSPC" and b["error_after"] == 1, c["fputc_return"] == ord("B") and c["error_before"] == 0 and c["fclose_return"] != 0 and c["fclose_errno_name"] == "ENOSPC", d["returned_items"] == 3 and d["file_size"] == d["pread_return"] == 12 and d["stream_error"] == 0 and d["payload_matches"] == 1 and d["fclose_return"] == 0, ] def bounded_repeats(value): try: result = int(value) except ValueError as exc: raise argparse.ArgumentTypeError("repeats must be 1 to 20") from exc if not 1 <= result <= 20: raise argparse.ArgumentTypeError("repeats must be 1 to 20") return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repeats", type=bounded_repeats, default=5) args = parser.parse_args() if platform.system() != "Linux": parser.error("Linux is required") compiler = shutil.which("cc") if compiler is None: parser.error("cc is required") here = Path(__file__).resolve().parent source = here / "stdio-boundary.c" flags = ["-std=c11", "-Wall", "-Wextra", "-Werror"] compiler_version = subprocess.run( [compiler, "--version"], check=True, capture_output=True, text=True, timeout=10, ).stdout.splitlines()[0] runs = [] with tempfile.TemporaryDirectory(prefix="hesela-stdio-boundary-") as temporary: root = Path(temporary) executable = root / "stdio-boundary" subprocess.run( [compiler, *flags, str(source), "-o", str(executable)], check=True, capture_output=True, text=True, timeout=30, ) for index in range(1, args.repeats + 1): trial = root / f"repeat-{index}" trial.mkdir(mode=0o700) result = subprocess.run( [str(executable)], cwd=trial, check=True, capture_output=True, text=True, timeout=10, ) observation = json.loads(result.stdout) checks = check_cases(observation["cases"]) for case, passed in zip(observation["cases"], checks): case["passed"] = passed runs.append({"repeat": index, **observation}) passed = sum(case["passed"] for run in runs for case in run["cases"]) payload = { "schema_version": 1, "experiment": "linux-stdio-output-boundary", "evidence_type": "deterministic-api-observation", "license": "MIT (Hesela harness and runner); observations are factual output", "generated_at_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "environment": { "os": platform.system(), "kernel_release": platform.release(), "architecture": platform.machine(), "libc": list(platform.libc_ver()), "python": platform.python_version(), "compiler": compiler_version, "compile_flags": flags, }, "method": { "repeat_count": args.repeats, "cases_per_repeat": 4, "sequence": CASE_IDS, "one_fresh_process_per_repeat": True, "single_threaded": True, "private_temporary_files": True, "controlled_error_sink": "/dev/full", "randomization": "none; deterministic ordered API calls", "errno_convention": "captured immediately on API failure; zero sentinel otherwise", }, "sources_sha256": { p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in (source, Path(__file__).resolve()) }, "references": [ "https://man7.org/linux/man-pages/man3/fflush.3.html", "https://man7.org/linux/man-pages/man3/fclose.3.html", "https://man7.org/linux/man-pages/man3/fwrite.3.html", "https://man7.org/linux/man-pages/man3/setbuf.3.html", "https://man7.org/linux/man-pages/man4/full.4.html", "https://man7.org/linux/man-pages/man2/fsync.2.html", ], "runs": runs, "summary": { "passed_cases": passed, "total_cases": 4 * args.repeats, "all_passed": passed == 4 * args.repeats, "temporary_directory_removed": not root.exists(), }, "limitations": [ "One Linux/libc host; exact buffering timing is an observation, not a universal API guarantee.", "Repeats check repeatability, not independent statistical samples or failure rates.", "fstat size and pread bytes observe file visibility, not physical persistence.", "/dev/full rejects writes; it is not a full filesystem or delayed writeback/errseq fault injection.", "No power loss, crash recovery, concurrent writers, partial item or storage-device failure was tested.", "A successful cleanup close cannot erase a preceding recorded output error.", ], } print(json.dumps(payload, indent=2)) return 0 if payload["summary"]["all_passed"] else 1 if __name__ == "__main__": try: sys.exit(main()) except (OSError, ValueError, subprocess.SubprocessError) as error: print(f"stdio-boundary: {error}", file=sys.stderr) if isinstance(error, subprocess.CalledProcessError) and error.stderr: print(error.stderr, file=sys.stderr) sys.exit(1)