#!/usr/bin/env python3 """Observe rsync selection and hard-link backup mutation in disposable files. No user source/destination paths are accepted. Requires Python 3 and local rsync. """ import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import shutil import stat import subprocess import tempfile OLD = b"generation=1\n" + b"A" * 4096 NEW = b"generation=2\n" + b"B" * 4096 STAMP = 1700000000000000000 CASES = [ ("quick-check", "Changed bytes, same size and mtime", [], "hidden", "current"), ("checksum-check", "Same change, with --checksum", ["--checksum"], "hidden", "current"), ("replace-content", "Changed bytes and mtime, default replacement", [], "visible", "current"), ("inplace-content", "Same visible change, with --inplace", ["--inplace"], "visible", "current"), ("metadata-rerun", "Only permissions change, reuse destination", [], "mode", "current"), ("checksum-metadata", "Only permissions change, with --checksum", ["--checksum"], "mode", "current"), ("fresh-metadata", "Only permissions change, empty destination", [], "mode", "fresh"), ("ignore-existing", "Only permissions change, skip existing files", ["--ignore-existing"], "mode", "current"), ] EXPECTED = { "quick-check": ("old", "old", "0600", "0600", True), "checksum-check": ("old", "new", "0600", "0600", False), "replace-content": ("old", "new", "0600", "0600", False), "inplace-content": ("new", "new", "0600", "0600", True), "metadata-rerun": ("old", "old", "0644", "0644", True), "checksum-metadata": ("old", "old", "0644", "0644", True), "fresh-metadata": ("old", "old", "0600", "0644", False), "ignore-existing": ("old", "old", "0600", "0600", True), } def require(condition, message): if not condition: raise RuntimeError(message) def digest(data): return hashlib.sha256(data).hexdigest() def identity(path): value = path.stat() return value.st_dev, value.st_ino def inspect(path): data = path.read_bytes() value = path.stat() label = "old" if data == OLD else "new" if data == NEW else "unexpected" return {"bytes": len(data), "sha256": digest(data), "payload": label, "mode": format(stat.S_IMODE(value.st_mode), "04o"), "mtimeNs": value.st_mtime_ns, "linkCount": value.st_nlink} def run_rsync(binary, root, args): env = {k: v for k, v in os.environ.items() if not k.startswith("RSYNC_")} env["LC_ALL"] = "C" proc = subprocess.run([binary, "-a", "--itemize-changes", *args], cwd=root, env=env, text=True, capture_output=True, timeout=20) record = {"argv": ["rsync", "-a", "--itemize-changes", *args], "exitCode": proc.returncode, "stdout": proc.stdout, "stderr": proc.stderr} require(proc.returncode == 0, f"rsync failed: {record}") return record def observe_case(binary, root, case): key, schedule, options, mutation, target_name = case root.mkdir() for name in ("source", "older", "current", "fresh"): (root / name).mkdir() source = root / "source/file" source.write_bytes(OLD) source.chmod(0o600) os.utime(source, ns=(STAMP, STAMP)) setup = [ run_rsync(binary, root, ["source/", "older/"]), run_rsync(binary, root, ["--link-dest=../older", "source/", "current/"]), ] older = root / "older/file" current = root / "current/file" require(identity(older) == identity(current), "setup did not create a hard link") require(identity(source) != identity(older), "source must be independent") before = {"older": inspect(older), "current": inspect(current), "olderAndCurrentShareInode": True} if mutation in ("hidden", "visible"): source.write_bytes(NEW) stamp = STAMP if mutation == "hidden" else STAMP + 10000000000 os.utime(source, ns=(STAMP, stamp)) else: source.chmod(0o644) source_before = inspect(source) require(source_before["bytes"] == before["older"]["bytes"], "unequal test sizes") operation = run_rsync(binary, root, [*options, "--link-dest=../older", "source/", target_name + "/"]) target = root / target_name / "file" after = {"older": inspect(older), "destination": inspect(target), "olderAndDestinationShareInode": identity(older) == identity(target)} require(inspect(source) == source_before, "source changed during operation") observed = (after["older"]["payload"], after["destination"]["payload"], after["older"]["mode"], after["destination"]["mode"], after["olderAndDestinationShareInode"]) require(observed == EXPECTED[key], f"unexpected outcome for {key}: {observed}") expected_old, expected_dest, _, _, _ = EXPECTED[key] require(older.read_bytes() == (OLD if expected_old == "old" else NEW), "complete older payload mismatch") require(target.read_bytes() == (OLD if expected_dest == "old" else NEW), "complete destination payload mismatch") return {"case": key, "schedule": schedule, "setup": setup, "before": before, "sourceBeforeTransfer": source_before, "operation": operation, "after": after, "olderBytesPreserved": older.read_bytes() == OLD, "olderModePreserved": after["older"]["mode"] == "0600", "destinationBytesMatchSource": target.read_bytes() == source.read_bytes(), "destinationModeMatchesSource": after["destination"]["mode"] == source_before["mode"], "completePayloadOraclePassed": True} def experiment(work_root=None): binary = shutil.which("rsync") require(binary is not None, "rsync is required") with tempfile.TemporaryDirectory(prefix="hesela-rsync-", dir=work_root) as folder: root = Path(folder) fs = subprocess.run(["stat", "-f", "-c", "%T", str(root)], capture_output=True, text=True, check=True).stdout.strip() rows = [observe_case(binary, root / case[0], case) for case in CASES] version = subprocess.run([binary, "--version"], capture_output=True, text=True, check=True).stdout return { "schemaVersion": 1, "experiment": "rsync-hardlink-backup-boundaries", "generatedAt": datetime.now(timezone.utc).isoformat(), "kind": "measured-software-behavior-on-synthetic-files", "environment": {"python": platform.python_version(), "kernel": platform.release(), "system": platform.system(), "filesystem": fs, "rsyncVersion": version.splitlines()[0], "rsyncBuild": version, "rsyncBinarySha256": digest(Path(binary).read_bytes()), "unprivileged": os.geteuid() != 0}, "scriptSha256": digest(Path(__file__).read_bytes()), "method": {"cases": len(rows), "filesPerCase": 1, "payloadBytes": len(OLD), "oldPayloadSha256": digest(OLD), "newPayloadSha256": digest(NEW), "mtimeNs": STAMP, "localOnly": True, "sourceQuiescentDuringEachRun": True, "checksum": "rsync default negotiation; SHA-256 is a separate evidence digest", "oracle": "complete byte equality, permission bits, and device/inode identity"}, "limitations": [ "Eight constructed schedules on one local filesystem, not failure-rate samples.", "No network, concurrent source writes, crash, power cut, ACL or xattr testing.", "Reopened reads can be served from cache; no durability or cold-media verification.", "Recorded software version identifies this observation, not a patch recommendation.", "Fresh destination isolates this permission change, not every metadata field or failure domain." ], "sources": [ {"url": "https://download.samba.org/pub/rsync/rsync.1.html", "sections": ["DESCRIPTION", "--checksum", "--inplace", "--link-dest", "--ignore-existing"], "accessed": "2026-10-17"}, {"url": "https://github.com/RsyncProject/rsync/blob/v3.2.7/generator.c", "sections": ["quick_check_ok", "unchanged_attrs", "try_dests_reg", "recv_generator"], "accessed": "2026-10-17"}, {"url": "https://man7.org/linux/man-pages/man2/link.2.html", "sections": ["DESCRIPTION"], "accessed": "2026-10-17"} ], "cases": rows, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, help="existing directory for disposable test files") parser.add_argument("--output", type=Path, required=True, help="new JSON output path (never overwritten)") args = parser.parse_args() if args.output.exists(): parser.error("output already exists") result = experiment(args.work_root) with args.output.open("x") as stream: json.dump(result, stream, indent=2) stream.write("\n") print(f"{len(result['cases'])} cases passed; output: {args.output}") if __name__ == "__main__": main()