# SPDX-License-Identifier: MIT """Native rsync observations; modifies only a private temporary directory.""" import argparse import hashlib import json import os from pathlib import Path import platform import re import shutil import subprocess import tempfile from datetime import datetime, timezone BASE_NS = 1_700_000_000_100_000_000 POLICIES = { "default": [], "nanoseconds": ["--modify-window=-1"], "checksum": ["--checksum"], "ignore-times": ["--ignore-times"], "size-only": ["--size-only"], "size-and-ignore": ["--size-only", "--ignore-times"], "checksum-and-ignore": ["--checksum", "--ignore-times"], } FIXTURES = ["identical", "changed-same-time", "changed-nanoseconds", "changed-seconds", "identical-new-time", "changed-size"] def sha(data): return hashlib.sha256(data).hexdigest() def fixture(name): basis = hashlib.shake_256(b"hesela-rsync-selection-v1").digest(8192) edited = basis[:4097] + bytes([basis[4097] ^ 1]) + basis[4098:] source = basis if name.startswith("identical") else edited if name == "changed-size": source += b"x" src_ns = BASE_NS if name == "changed-nanoseconds": src_ns += 400_000_000 if name in ("changed-seconds", "identical-new-time"): src_ns += 2_000_000_000 return source, basis, src_ns, BASE_NS def expected_transfer(name, policy): if name == "changed-size": return True if policy in ("checksum", "checksum-and-ignore"): return not name.startswith("identical") if policy in ("size-only", "size-and-ignore"): return False if policy == "ignore-times": return True return name in ("changed-seconds", "identical-new-time") or ( policy == "nanoseconds" and name == "changed-nanoseconds") def parse_count(output, label): match = re.search(r"^" + re.escape(label) + r": ([0-9,]+)(?: bytes)?$", output, re.M) if not match: raise ValueError("Missing or malformed rsync statistic: " + label) return int(match.group(1).replace(",", "")) def observe(scratch, binary="rsync"): executable = shutil.which(binary) if not executable: raise RuntimeError("rsync executable required") executable = str(Path(executable).resolve()) env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "LC_ALL": "C"} version = subprocess.run([executable, "--version"], env=env, check=True, text=True, capture_output=True, timeout=10).stdout cases = [] with tempfile.TemporaryDirectory(prefix="hesela-rsync-selection-", dir=scratch) as root: env["HOME"] = root for name in FIXTURES: for policy, flags in POLICIES.items(): directory = Path(root) / (name + "-" + policy) directory.mkdir() source, basis, src_ns, dst_ns = fixture(name) src, dst = directory / "source", directory / "destination" src.write_bytes(source) dst.write_bytes(basis) os.utime(src, ns=(src_ns, src_ns)) os.utime(dst, ns=(dst_ns, dst_ns)) before = {"sourceBytes": src.stat().st_size, "destinationBytes": dst.stat().st_size, "sourceMtimeNs": src.stat().st_mtime_ns, "destinationMtimeNs": dst.stat().st_mtime_ns, "sourceSha256": sha(source), "destinationSha256": sha(basis), "byteEqual": source == basis} if (before["sourceMtimeNs"], before["destinationMtimeNs"]) != (src_ns, dst_ns): raise RuntimeError("Filesystem lost requested timestamp precision") args = [executable, "--times", "--no-whole-file", "--block-size=512", "--checksum-choice=xxh128", "--stats", "--itemize-changes", *flags, str(src), str(dst)] run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=15) if run.returncode: raise RuntimeError(run.stderr) transferred = parse_count(run.stdout, "Number of regular files transferred") literal = parse_count(run.stdout, "Literal data") matched = parse_count(run.stdout, "Matched data") expected = expected_transfer(name, policy) if transferred != int(expected): raise AssertionError((name, policy, transferred, expected)) actual = dst.read_bytes() if src.read_bytes() != source or src.stat().st_mtime_ns != src_ns: raise AssertionError("Source changed") if actual != (source if expected else basis): raise AssertionError("Exact destination oracle failed") if literal + matched != (len(source) if expected else 0): raise AssertionError("Payload accounting failed") cases.append({"fixture": name, "policy": policy, "before": before, "command": args[:-2] + ["$CASE/source", "$CASE/destination"], "exitCode": run.returncode, "transferredFiles": transferred, "literalBytes": literal, "matchedBytes": matched, "byteEqualAfter": actual == source, "sourceUnchanged": True, "destinationSha256After": sha(actual), "stdout": run.stdout, "stderr": run.stderr}) here = Path(__file__).resolve().parent return {"schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "kind": "constructed native software observations", "environment": {"system": platform.system(), "kernel": platform.release(), "python": platform.python_version(), "rsyncVersionOutput": version, "binarySha256": sha(Path(executable).read_bytes()), "scratchFilesystem": subprocess.run( ["stat", "-f", "-c", "%T", str(scratch)], check=True, text=True, capture_output=True, timeout=10).stdout.strip()}, "sourceHashes": {p.name: sha(p.read_bytes()) for p in sorted(here.iterdir()) if p.name in ("observe.py", "test_observe.py", "README.md", "LICENSE")}, "fixtureRecipe": "SHAKE-256(ASCII hesela-rsync-selection-v1), first 8192 bytes; XOR byte 4097 with 1; changed-size also appends ASCII x.", "cases": cases, "limits": ["One run per deterministic configuration, not a performance or frequency sample.", "No network, concurrent writers, power failure or media verification.", "Version identified for reproducibility, not recommended for deployment.", "Exact bytes are checked; checksum equality is not authentication."]} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--scratch", type=Path, default=Path(tempfile.gettempdir())) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() result = observe(args.scratch) with args.output.open("x", encoding="utf8") as output: json.dump(result, output, indent=2) output.write("\n") print(json.dumps({"cases": len(result["cases"]), "output": str(args.output)}))