#!/usr/bin/env python3 """Measure decoder failure, pipeline status and destination replacement. Synthetic, bounded files only. This is a contract demonstration, not a restore utility: there is no fsync, concurrency, crash or hostile-input safety claim. """ import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import re import shutil import subprocess import tempfile SENTINEL = b"previous-accepted-generation\n" MODES = ("pipeline-default", "pipeline-pipefail", "staged") CASES = ("complete", "checksum-damaged", "last-byte-truncated", "last-frame-removed") ENV = {"PATH": os.environ.get("PATH", os.defpath), "LC_ALL": "C"} PIPELINE = r""" set +e set +o pipefail if [[ "$3" == "pipeline-pipefail" ]]; then set -o pipefail; fi zstd -q -d -c --check -- "$1" | tee -- "$2" > /dev/null status=( "$?" "${PIPESTATUS[@]}" ) printf '\nHESELA_STATUS %s %s %s\n' "${status[@]}" >&2 exit "${status[0]}" """ def require(condition, message): if not condition: raise ValueError(message) def digest(data): return hashlib.sha256(data).hexdigest() def run(args, **kwargs): return subprocess.run(args, stderr=subprocess.PIPE, timeout=15, env=ENV, **kwargs) def compress(data): result = run(["zstd", "-q", "-3", "-T1", "-c", "--check"], input=data, stdout=subprocess.PIPE) require(result.returncode == 0, "Compression failed") require(result.stdout[:4] == bytes.fromhex("28b52ffd"), "Unexpected frame magic") require(result.stdout[4] & 4 != 0, "Fixture checksum is absent") return result.stdout def payload_matches(data, expected_size, expected_digest): return len(data) == expected_size and digest(data) == expected_digest def observe(case, mode, encoded, expected, root): directory = root / (case + "-" + mode) directory.mkdir() (directory / "input.zst").write_bytes(encoded) destination = directory / "destination.bin" destination.write_bytes(SENTINEL) expected_hash = digest(expected) if mode == "staged": staged = directory / "staged.bin" with staged.open("wb") as output: proc = run(["zstd", "-q", "-d", "-c", "--check", "--", "input.zst"], cwd=directory, stdout=output) emitted = staged.read_bytes() decoder_status = proc.returncode consumer_status = None pipeline_status = None accepted = (decoder_status == 0 and payload_matches(emitted, len(expected), expected_hash)) if accepted: os.replace(staged, destination) else: staged.unlink() stderr = proc.stderr.decode("utf-8", errors="replace").strip() else: proc = run(["bash", "--noprofile", "--norc", "-c", PIPELINE, "hesela-pipeline", "input.zst", "destination.bin", mode], cwd=directory, stdout=subprocess.PIPE) stderr = proc.stderr.decode("utf-8", errors="replace") match = re.search(r"\nHESELA_STATUS (\d+) (\d+) (\d+)\n$", stderr) require(match is not None, "Missing pipeline status receipt") pipeline_status, decoder_status, consumer_status = map(int, match.groups()) require(proc.returncode == pipeline_status, "Shell exit/status mismatch") stderr = stderr[:match.start()].strip() emitted = destination.read_bytes() accepted = pipeline_status == 0 final = destination.read_bytes() exact = payload_matches(emitted, len(expected), expected_hash) return { "case": case, "mode": mode, "compressedBytes": len(encoded), "compressedSha256": digest(encoded), "expectedBytes": len(expected), "expectedSha256": expected_hash, "decoderExit": decoder_status, "consumerExit": consumer_status, "pipelineExit": pipeline_status, "emittedBytes": len(emitted), "emittedSha256": digest(emitted), "payloadMatches": exact, "oracleAccepted": decoder_status == 0 and exact, "policyAccepted": accepted, "destinationBytes": len(final), "destinationSha256": digest(final), "previousDestinationPreserved": final == SENTINEL, "stderr": stderr, } def validate(rows): require(len(rows) == len(CASES) * len(MODES), "Unexpected row count") by_key = {(r["case"], r["mode"]): r for r in rows} require(set(by_key) == {(c, m) for c in CASES for m in MODES}, "Invalid case matrix") for row in rows: for key in ("payloadMatches", "oracleAccepted", "policyAccepted", "previousDestinationPreserved"): require(type(row[key]) is bool, "Invalid boolean: " + key) for key in ("compressedBytes", "expectedBytes", "emittedBytes", "destinationBytes", "decoderExit"): require(type(row[key]) is int and row[key] >= 0, "Invalid integer: " + key) for key in ("compressedSha256", "expectedSha256", "emittedSha256", "destinationSha256"): require(re.fullmatch(r"[0-9a-f]{64}", row[key]) is not None, "Invalid digest") exact = (row["emittedBytes"] == row["expectedBytes"] and row["emittedSha256"] == row["expectedSha256"]) require(row["payloadMatches"] == exact, "Inconsistent payload oracle") require(row["oracleAccepted"] == (row["decoderExit"] == 0 and exact), "Inconsistent acceptance oracle") decoder_success = row["case"] in ("complete", "last-frame-removed") require((row["decoderExit"] == 0) == decoder_success, "Changed decoder result") require(row["oracleAccepted"] == (row["case"] == "complete"), "Changed oracle") require(row["emittedBytes"] > 0, "This build did not demonstrate emitted bytes") if row["mode"] == "staged": require(row["pipelineExit"] is None and row["consumerExit"] is None, "Staged mode has no pipeline") require(row["policyAccepted"] == row["oracleAccepted"], "Invalid staged gate") require(row["previousDestinationPreserved"] == (not row["oracleAccepted"]), "Failed staging did not preserve the previous destination") final_hash = row["expectedSha256"] if row["oracleAccepted"] else digest(SENTINEL) final_size = row["expectedBytes"] if row["oracleAccepted"] else len(SENTINEL) require(row["destinationSha256"] == final_hash and row["destinationBytes"] == final_size, "Invalid staged destination") else: require(type(row["consumerExit"]) is int and row["consumerExit"] == 0, "Consumer failed") require(type(row["pipelineExit"]) is int, "Invalid pipeline status") expected_exit = row["decoderExit"] if row["mode"] == "pipeline-pipefail" else 0 require(row["pipelineExit"] == expected_exit, "Changed pipeline semantics") require(row["policyAccepted"] == (expected_exit == 0), "Invalid policy flag") require(not row["previousDestinationPreserved"], "Direct consumer did not write") require(row["destinationSha256"] == row["emittedSha256"] and row["destinationBytes"] == row["emittedBytes"], "Invalid direct output") for case in CASES: group = [by_key[case, mode] for mode in MODES] for key in ("compressedSha256", "compressedBytes", "expectedSha256", "expectedBytes", "decoderExit", "emittedSha256", "emittedBytes"): require(len({row[key] for row in group}) == 1, "Modes differ in " + key) def experiment(): for command in ("zstd", "bash", "tee"): require(shutil.which(command) is not None, command + " is required") payload = b"".join(hashlib.sha256(("hesela-stream-" + str(i)).encode()).digest() for i in range(32768)) tail = b"archive-generation-end\n" expected = payload + tail first, last = compress(payload), compress(tail) damaged = first[:-1] + bytes([first[-1] ^ 1]) fixtures = { "complete": first + last, "checksum-damaged": damaged + last, "last-byte-truncated": (first + last)[:-1], "last-frame-removed": first, } with tempfile.TemporaryDirectory(prefix="hesela-zstd-output-") as temp: rows = [observe(case, mode, fixtures[case], expected, Path(temp)) for case in CASES for mode in MODES] validate(rows) versions = {} for tool in ("zstd", "bash", "tee"): proc = run([tool, "--version"], stdout=subprocess.PIPE) require(proc.returncode == 0, "Cannot read tool version") versions[tool] = proc.stdout.decode().splitlines()[0] return { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "sourceSha256": digest(Path(__file__).read_bytes()), "environment": {**versions, "python": platform.python_version(), "system": platform.system(), "machine": platform.machine()}, "method": { "type": "synthetic-cli-output-publication-demonstration", "firstFramePayloadBytes": len(payload), "lastFramePayloadBytes": len(tail), "compressionLevel": 3, "compressionThreads": 1, "checksumPolicy": "verify", "timeoutSeconds": 15, "previousDestinationBytes": len(SENTINEL), "previousDestinationSha256": digest(SENTINEL), "mutation": "XOR final checksum byte of first frame with 1; data blocks unchanged", "oracle": "decoder exit zero AND expected full decoded length AND SHA-256", "expectationOrigin": "Full synthetic input created before any mutation", "directConsumer": "tee truncates and writes the existing destination while reading decoder stdout", "stagedConsumer": "private same-directory file; replace only after status and oracle pass", "scope": "No fsync, crash, concurrency, malicious-input, performance or frequency claim", }, "observations": rows, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path) args = parser.parse_args() result = json.dumps(experiment(), indent=2) + "\n" if args.output: args.output.write_text(result, encoding="utf-8") else: print(result, end="") if __name__ == "__main__": main()