#!/usr/bin/env python3 """Observe real rsync process interruption on private, disposable regular files.""" import argparse import datetime import hashlib import json import os from pathlib import Path import platform import re import shutil import signal import subprocess import tempfile import time SIZE = 4 * 1024 * 1024 BARRIER_BYTES = 65536 SOURCE_NS = 1700000000 * 10**9 DESTINATION_NS = 1600000000 * 10**9 POLICIES = { "update": ["--update"], "update-checksum": ["--update", "--checksum"], "update-ignore-times": ["--update", "--ignore-times"], "authoritative-checksum": ["--checksum"], } def require(condition, message): if not condition: raise RuntimeError(message) def digest(data): return hashlib.sha256(data).hexdigest() def state(path): data = path.read_bytes() st = path.stat() return { "bytes": len(data), "sha256": digest(data), "mtimeNs": str(st.st_mtime_ns), "device": st.st_dev, "inode": st.st_ino, "oldBytes": data.count(b"A"), "newBytes": data.count(b"B"), "otherBytes": len(data) - data.count(b"A") - data.count(b"B"), "newPrefixBytes": len(data) - len(data.lstrip(b"B")), "oldSuffixBytes": len(data) - len(data.rstrip(b"A")), } def content_state_equal(left, right): return all(left[key] == right[key] for key in ("bytes", "sha256", "mtimeNs")) def common(binary, mode): args = [binary, "--times", "--no-whole-file", "--block-size=4096", "--checksum-choice=md5", "--stats", "--info=skip2"] if mode == "inplace": args.append("--inplace") return args def kill_owned_group(process): if process.poll() is None: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass return process.communicate(timeout=10) def interrupt(command, mode, destination, env, timeout=12): # A fresh session isolates signals to this invocation and its rsync children. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True, env=env) started = time.monotonic() observed = None try: while time.monotonic() - started < timeout: require(process.poll() is None, "Transfer exited before write barrier") candidates = [destination] if mode == "inplace" else list( destination.parent.glob(".target.*")) for candidate in candidates: try: with candidate.open("rb") as stream: prefix = stream.read(BARRIER_BYTES) except FileNotFoundError: continue if prefix == b"B" * BARRIER_BYTES: observed = candidate break if observed is not None: # Stop future userspace work, then kill; inspect only after pipe EOF. os.killpg(process.pid, signal.SIGSTOP) break time.sleep(0.001) require(observed is not None, "No observed-write barrier before timeout") finally: stdout, stderr = kill_owned_group(process) require(process.returncode == -signal.SIGKILL, "Expected SIGKILL parent exit") return { "command": command, "returncode": process.returncode, "stdout": stdout, "stderr": stderr, "barrier": {"kind": "observed-new-prefix", "bytes": BARRIER_BYTES, "file": observed.name, "observedElapsedSeconds": time.monotonic() - started}, "writtenFile": state(observed), "remainingTemporaryFiles": sorted(path.name for path in destination.parent.glob(".target.*")), } def observe_case(binary, scratch, mode, policy, repetition): with tempfile.TemporaryDirectory(prefix="hesela-rsync-interruption-", dir=scratch) as root: root = Path(root) (root / "source").mkdir() (root / "destination").mkdir() source = root / "source" / "target" destination = root / "destination" / "target" source.write_bytes(b"B" * SIZE) destination.write_bytes(b"A" * SIZE) os.utime(source, ns=(SOURCE_NS, SOURCE_NS)) os.utime(destination, ns=(DESTINATION_NS, DESTINATION_NS)) before_source, before_destination = state(source), state(destination) require(before_source["mtimeNs"] == str(SOURCE_NS), "Source timestamp not retained") require(before_destination["mtimeNs"] == str(DESTINATION_NS), "Destination timestamp not retained") env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(root), "LC_ALL": "C", "TZ": "UTC"} initial = common(binary, mode) + ["--update", "--bwlimit=256", str(source), str(destination)] interruption = interrupt(initial, mode, destination, env) after_kill = state(destination) written = interruption["writtenFile"] require(written["newPrefixBytes"] >= BARRIER_BYTES, "Missing observed prefix") require(written["newBytes"] < SIZE, "Transfer completed before interruption") if mode == "inplace": require(after_kill["bytes"] == SIZE and after_kill["otherBytes"] == 0, "Unexpected mixed-file shape") require(after_kill["newPrefixBytes"] + after_kill["oldSuffixBytes"] == SIZE, "Expected exactly a new prefix and old suffix") require(after_kill["oldSuffixBytes"] > 0, "Missing old suffix") require(int(after_kill["mtimeNs"]) // 10**9 > SOURCE_NS // 10**9, "Write did not make destination newer") require(after_kill["inode"] == before_destination["inode"], "In-place inode changed") else: require(after_kill == before_destination, "Temporary-mode published destination changed") require(written["newBytes"] == written["bytes"] and written["otherBytes"] == 0, "Unexpected temporary-file content") require(content_state_equal(state(source), before_source), "Source changed during transfer") retry = common(binary, mode) + POLICIES[policy] + [str(source), str(destination)] result = subprocess.run(retry, text=True, capture_output=True, env=env, timeout=15) after_retry = state(destination) match = re.search(r"^Number of regular files transferred: ([0-9,]+)$", result.stdout, re.MULTILINE) require(match is not None, "Missing transfer count") transferred = int(match.group(1).replace(",", "")) equal = destination.read_bytes() == source.read_bytes() source_unchanged = content_state_equal(state(source), before_source) require(result.returncode == 0, "Retry returned nonzero") require(source_unchanged, "Source changed after retry") return { "mode": mode, "policy": policy, "repetition": repetition, "sourceBefore": before_source, "destinationBefore": before_destination, "interruption": interruption, "destinationAfterKill": after_kill, "retry": {"command": retry, "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr, "transferredFiles": transferred}, "destinationAfterRetry": after_retry, "exactlyEqualsSource": equal, "exactlyRetainsInterruptedBytes": after_retry["sha256"] == after_kill["sha256"], "sourceUnchanged": source_unchanged, } def verify(result): rows = result["cases"] repetitions = result["repetitions"] expected_keys = {(mode, policy, rep) for mode in ("inplace", "temporary") for policy in POLICIES for rep in range(1, repetitions + 1)} require(len(rows) == len(expected_keys), "Wrong case count") require({(r["mode"], r["policy"], r["repetition"]) for r in rows} == expected_keys, "Missing or duplicate cases") for row in rows: should_copy = row["mode"] == "temporary" or row["policy"] == "authoritative-checksum" require(row["retry"]["transferredFiles"] == int(should_copy), "Wrong selection result") require(row["exactlyEqualsSource"] == should_copy, "Wrong exact byte outcome") require(row["retry"]["returncode"] == 0 and row["sourceUnchanged"], "Invalid retry/source") require(row["interruption"]["returncode"] == -signal.SIGKILL, "Not a killed transfer") killed = row["destinationAfterKill"] final = row["destinationAfterRetry"] if should_copy: require(final["newBytes"] == SIZE and final["oldBytes"] == 0, "Not complete") require(final["mtimeNs"] == str(SOURCE_NS), "Completed mtime not preserved") else: require(row["exactlyRetainsInterruptedBytes"], "Skipped bytes changed") require(final == killed, "Skipped metadata or inode changed") require("is newer" in row["retry"]["stdout"], "No newer-file skip message") return True def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", default="rsync") parser.add_argument("--scratch", required=True) parser.add_argument("--output", required=True) parser.add_argument("--repetitions", type=int, default=2) args = parser.parse_args() require(1 <= args.repetitions <= 10, "Repetitions must be 1..10") require(platform.system() == "Linux", "This signal harness is scoped to Linux") output = Path(args.output) require(not output.exists(), "Refusing to overwrite existing evidence") scratch = Path(args.scratch).resolve(strict=True) require(shutil.disk_usage(scratch).free >= 64 * 1024 * 1024, "Insufficient scratch space") binary = shutil.which(args.binary) require(binary is not None, "rsync executable not found") binary = str(Path(binary).resolve(strict=True)) version = subprocess.run([binary, "--version"], text=True, capture_output=True, check=True) result = { "schemaVersion": 1, "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "scope": "Observed local process interruption; not crash consistency or power-loss durability", "environment": {"kernel": platform.release(), "machine": platform.machine(), "python": platform.python_version(), "scratch": str(scratch)}, "binary": {"path": binary, "sha256": digest(Path(binary).read_bytes()), "version": version.stdout}, "harnessSha256": digest(Path(__file__).read_bytes()), "testsSha256": digest(Path(__file__).with_name("test_observe.py").read_bytes()), "fixture": {"bytes": SIZE, "sourceByte": "B", "destinationByte": "A", "sourceMtimeNs": str(SOURCE_NS), "destinationMtimeNs": str(DESTINATION_NS), "initialBandwidthKiBPerSecond": 256, "barrierBytes": BARRIER_BYTES}, "repetitions": args.repetitions, "cases": [], } for rep in range(1, args.repetitions + 1): for mode in ("inplace", "temporary"): for policy in POLICIES: result["cases"].append(observe_case(binary, scratch, mode, policy, rep)) verify(result) with output.open("x") as stream: json.dump(result, stream, indent=2) stream.write("\n") print(json.dumps({"output": str(output), "cases": len(result["cases"]), "verified": True})) if __name__ == "__main__": main()