# SPDX-License-Identifier: MIT """Native rsync transfer-rule observations using private temporary regular files.""" 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 BASE_NS = 1_700_000_000_500_000_000 POLICIES = { "checksum": ["--checksum"], "update-checksum": ["--update", "--checksum"], "update-checksum-ns": ["--update", "--checksum", "--modify-window=-1"], "update-checksum-window1": ["--update", "--checksum", "--modify-window=1"], "update-ignore-times": ["--update", "--ignore-times"], "ignore-existing-checksum": ["--ignore-existing", "--checksum"], } FIXTURES = [ "identical-same-time", "identical-destination-plus-2s", "changed-same-time", "changed-destination-plus-400ms", "changed-destination-plus-1s", "changed-destination-plus-2s", "changed-destination-minus-400ms", "changed-destination-minus-1s", "changed-destination-minus-2s", "shorter-destination-plus-2s", "missing-destination", ] def sha(data): return hashlib.sha256(data).hexdigest() def fixture(name): if name not in FIXTURES: raise ValueError("Unknown fixture: " + name) source = hashlib.shake_256(b"hesela-rsync-update-v1").digest(8192) basis = source if name.startswith("identical") else ( source[:4097] + bytes([source[4097] ^ 1]) + source[4098:]) if name.startswith("shorter"): basis = basis[:4096] delta = 0 for suffix, amount in [ ("plus-400ms", 400_000_000), ("minus-400ms", -400_000_000), ("plus-1s", 1_000_000_000), ("minus-1s", -1_000_000_000), ("plus-2s", 2_000_000_000), ("minus-2s", -2_000_000_000), ]: if name.endswith(suffix): delta = amount return source, None if name == "missing-destination" else basis, BASE_NS + delta def parse_count(output, label): matches = re.findall(r"^" + re.escape(label) + r": ([0-9,]+)(?: bytes)?$", output, re.M) if len(matches) != 1: raise ValueError("Expected exactly one statistic: " + label) return int(matches[0].replace(",", "")) def snapshot(path): if not path.exists(): return {"exists": False} data = path.read_bytes() info = path.stat() return {"exists": True, "bytes": len(data), "mtimeNs": info.st_mtime_ns, "sha256": sha(data)} def observe(scratch, binary="rsync"): executable = shutil.which(binary) if not executable: raise RuntimeError("rsync executable required") executable = str(Path(executable).resolve()) cases = [] with tempfile.TemporaryDirectory(prefix="hesela-rsync-update-", dir=scratch) as root: env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "LC_ALL": "C", "HOME": root} version = subprocess.run([executable, "--version"], env=env, check=True, capture_output=True, text=True, timeout=10).stdout for name in FIXTURES: for policy, flags in POLICIES.items(): directory = Path(root) / (name + "-" + policy) directory.mkdir() source, basis, dst_ns = fixture(name) src, dst = directory / "source", directory / "destination" src.write_bytes(source) os.utime(src, ns=(BASE_NS, BASE_NS)) if basis is not None: dst.write_bytes(basis) os.utime(dst, ns=(dst_ns, dst_ns)) before = {"source": snapshot(src), "destination": snapshot(dst)} if before["source"]["mtimeNs"] != BASE_NS or ( basis is not None and before["destination"]["mtimeNs"] != dst_ns ): raise RuntimeError("Filesystem did not preserve requested timestamps") args = [executable, "--times", "--no-whole-file", "--block-size=512", "--checksum-choice=md5", "--stats", "--itemize-changes", "--info=skip2", *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") actual = dst.read_bytes() if dst.exists() else None if transferred not in (0, 1): raise AssertionError("Expected at most one transfer") if actual != (source if transferred else basis): raise AssertionError("Exact destination oracle failed") if snapshot(src) != before["source"]: raise AssertionError("Source content, size or mtime changed") if literal + matched != (len(source) if transferred else 0): raise AssertionError("Payload accounting failed") cases.append({ "fixture": name, "policy": policy, "command": args[:-2] + ["$CASE/source", "$CASE/destination"], "before": before, "after": {"destination": snapshot(dst)}, "exitCode": run.returncode, "transferredFiles": transferred, "literalBytes": literal, "matchedBytes": matched, "byteEqualAfter": actual == source, "sourceUnchanged": True, "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-update-v1), first 8192 bytes. Changed destinations XOR byte 4097 with 1. Shorter destination truncates to 4096 bytes. Source mtime is 1700000000.5 seconds.", "cases": cases, "limits": [ "One observation per deterministic case, not a sample of backup failure frequency.", "Local regular files only; no interrupted transfer, network or power-loss experiment.", "Version identification is not a deployment recommendation.", "MD5 is fixed for compatibility, not authenticity; exact bytes independently checked.", "Checksum-enabled sender may read source data even when receiver skips transfer.", ], } if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--scratch", type=Path, default=Path(tempfile.gettempdir())) parser.add_argument("--binary", default="rsync") parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists(): parser.error("Output already exists; use a fresh output path") result = observe(args.scratch, args.binary) 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)}))