#!/usr/bin/env python3 """Observe Git backup boundaries using only disposable, locally created repositories.""" import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import shutil import subprocess import tempfile import zlib EXPECTED_IDS = { "shared", "local-repack", "full-repack", "dissociate", "intact-blob", "changed-blob", "missing-blob", "incremental-bundle", "full-bundle", "changed-bundle-trailer", } def require(condition, message): if not condition: raise RuntimeError(message) def sha256(data): return hashlib.sha256(data).hexdigest() def manifest(path): return {str(p.relative_to(path)): sha256(p.read_bytes()) for p in sorted(path.rglob("*")) if p.is_file()} class Lab: def __init__(self, root): self.root = root self.log = [] self.env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} home = root / "home" home.mkdir() empty = root / "empty" empty.mkdir() self.empty = empty self.env.update({ "HOME": str(home), "XDG_CONFIG_HOME": str(home), "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_TERMINAL_PROMPT": "0", "GIT_ALLOW_PROTOCOL": "file", "GIT_AUTHOR_NAME": "Synthetic fixture", "GIT_AUTHOR_EMAIL": "fixture@example.invalid", "GIT_COMMITTER_NAME": "Synthetic fixture", "GIT_COMMITTER_EMAIL": "fixture@example.invalid", "GIT_AUTHOR_DATE": "2000-01-01T00:00:00+0000", "GIT_COMMITTER_DATE": "2000-01-01T00:00:00+0000", "LC_ALL": "C", "TZ": "UTC", }) def git(self, cwd, *args, data=None, ok=True): command = ["git", "-c", "gc.auto=0", "-c", "maintenance.auto=false", "-c", "core.hooksPath=" + str(self.empty), "-c", "init.templateDir=" + str(self.empty), *map(str, args)] result = subprocess.run(command, cwd=cwd, env=self.env, input=data, capture_output=True, timeout=20) clean = lambda s: s.replace(str(self.root), "") row = { "cwd": clean(str(cwd)), "argv": [clean(s) for s in command], "returncode": result.returncode, "stdout": clean(result.stdout.decode("utf-8", "replace")), "stderr": clean(result.stderr.decode("utf-8", "replace")), } self.log.append(row) if ok: require(result.returncode == 0, "Git command failed: " + repr(row)) return row def init(self, path, bare=False): args = ["init", "--quiet", "--template=" + str(self.empty), "--object-format=sha1", "--initial-branch=main"] if bare: args.append("--bare") self.git(self.root, *args, path) return path def fixture(self, name): repo = self.init(self.root / name) commits = [] blobs = [] for n in (1, 2): payload = ("archived-generation-%d\n" % n).encode() blob = self.git(repo, "hash-object", "-w", "--stdin", data=payload)["stdout"].strip() tree = self.git(repo, "mktree", data=("100644 blob %s\tpayload.txt\n" % blob).encode())["stdout"].strip() args = ["commit-tree", tree] if commits: args += ["-p", commits[-1]] commit = self.git(repo, *args, data=("fixture %d\n" % n).encode())["stdout"].strip() self.git(repo, "update-ref", "refs/heads/main", commit) commits.append(commit) blobs.append(blob) return repo, commits, blobs def check(self, repo, connectivity=False): args = ["fsck", "--no-dangling"] args.append("--connectivity-only" if connectivity else "--full") return self.git(repo, *args, ok=False) def show(self, repo): return self.git(repo, "show", "HEAD:payload.txt", ok=False) def run_once(root): lab = Lab(root) cases = [] for mode in ("shared", "local-repack", "full-repack", "dissociate"): source, _, _ = lab.fixture("source-" + mode) copy = root / ("copy-" + mode) flags = ["--bare", "--shared"] if mode == "dissociate": flags = ["--bare", "--reference", str(source), "--dissociate"] lab.git(root, "clone", "--quiet", *flags, source, copy) alternate = copy / "objects/info/alternates" created_alternate = alternate.exists() if mode == "local-repack": lab.git(copy, "repack", "-a", "-l") if mode == "full-repack": lab.git(copy, "repack", "-a") # Remove only the disposable fixture's lookup configuration after copying objects. require(alternate.exists(), "Expected the shared alternate") alternate.unlink() present = lab.check(copy) present_read = lab.show(copy) before = manifest(copy) hidden = source.with_name(source.name + "-offline") source.rename(hidden) try: absent = lab.check(copy) absent_read = lab.show(copy) after = manifest(copy) finally: hidden.rename(source) cases.append({ "id": mode, "alternate_created": created_alternate, "alternate_remaining": alternate.exists(), "provider_present_fsck": present["returncode"], "provider_present_payload": present_read["stdout"], "provider_absent_fsck": absent["returncode"], "provider_absent_read": absent_read["returncode"], "provider_absent_payload": absent_read["stdout"], "copy_manifest_unchanged": before == after, "copy_manifest": before, }) for mode in ("intact-blob", "changed-blob", "missing-blob"): repo, _, blobs = lab.fixture(mode) blob = repo / ".git/objects" / blobs[-1][:2] / blobs[-1][2:] original = blob.read_bytes() object_bytes = zlib.decompress(original) replacement = object_bytes.replace(b"generation-2", b"generation-X") require(len(replacement) == len(object_bytes), "Keep the object length fixed") if mode == "changed-blob": # Deliberate fault injection into a disposable loose object, never a user repository. blob.chmod(0o600) blob.write_bytes(zlib.compress(replacement)) elif mode == "missing-blob": blob.unlink() connectivity = lab.check(repo, connectivity=True) full = lab.check(repo) read = lab.show(repo) cases.append({ "id": mode, "object_id": blobs[-1], "original_loose_sha256": sha256(original), "current_loose_sha256": sha256(blob.read_bytes()) if blob.exists() else None, "connectivity_fsck": connectivity["returncode"], "full_fsck": full["returncode"], "read_returncode": read["returncode"], "read_payload": read["stdout"], "full_diagnostic": full["stdout"] + full["stderr"], }) source, commits, _ = lab.fixture("bundle-source") (source / "not-committed.txt").write_text("local-only measurement\n") incremental = root / "incremental.bundle" complete = root / "complete.bundle" lab.git(source, "bundle", "create", incremental, commits[0] + "..main") lab.git(source, "bundle", "create", complete, "--all") recipient = lab.init(root / "empty-recipient", bare=True) verify_source = lab.git(source, "bundle", "verify", incremental, ok=False) verify_empty = lab.git(recipient, "bundle", "verify", incremental, ok=False) cases.append({ "id": "incremental-bundle", "sha256": sha256(incremental.read_bytes()), "prerequisite_commit": commits[0], "verify_with_prerequisite": verify_source["returncode"], "verify_empty_recipient": verify_empty["returncode"], "empty_diagnostic": verify_empty["stdout"] + verify_empty["stderr"], }) verify_complete = lab.git(recipient, "bundle", "verify", complete, ok=False) restored = root / "restored" clone_complete = lab.git(root, "clone", "--bare", complete, restored, ok=False) require(clone_complete["returncode"] == 0, "Full-bundle control must clone") restored_check = lab.check(restored) restored_read = lab.show(restored) local_file = lab.git(restored, "cat-file", "-e", "HEAD:not-committed.txt", ok=False) cases.append({ "id": "full-bundle", "sha256": sha256(complete.read_bytes()), "verify_empty_recipient": verify_complete["returncode"], "clone_returncode": clone_complete["returncode"], "restored_fsck": restored_check["returncode"], "restored_payload": restored_read["stdout"], "uncommitted_file_lookup": local_file["returncode"], }) corrupt = root / "changed.bundle" data = bytearray(complete.read_bytes()) data[-1] ^= 1 # Change only the final byte of the embedded pack checksum. corrupt.write_bytes(data) verify_corrupt = lab.git(recipient, "bundle", "verify", corrupt, ok=False) clone_corrupt = lab.git(root, "clone", "--bare", corrupt, root / "corrupt-restored", ok=False) cases.append({ "id": "changed-bundle-trailer", "sha256": sha256(data), "original_sha256": sha256(complete.read_bytes()), "changed_byte_count": sum(a != b for a, b in zip(complete.read_bytes(), data)), "verify_empty_recipient": verify_corrupt["returncode"], "clone_returncode": clone_corrupt["returncode"], "clone_diagnostic": clone_corrupt["stdout"] + clone_corrupt["stderr"], }) return {"cases": cases, "commands": lab.log} def validate_run(run): cases = run["cases"] require(len(cases) == len(EXPECTED_IDS), "Unexpected case count") by_id = {row["id"]: row for row in cases} require(set(by_id) == EXPECTED_IDS, "Missing or duplicate case") for name in ("shared", "local-repack", "full-repack", "dissociate"): row = by_id[name] independent = name in ("full-repack", "dissociate") require(row["provider_present_fsck"] == 0, name + ": initial fsck") require(row["provider_present_payload"] == "archived-generation-2\n", name + ": initial payload") require((row["provider_absent_fsck"] == 0) == independent, name + ": disconnected fsck") require((row["provider_absent_read"] == 0) == independent, name + ": disconnected read") if independent: require(row["provider_absent_payload"] == "archived-generation-2\n", name + ": recovered payload") require(row["copy_manifest_unchanged"], name + ": copy bytes changed") row = by_id["intact-blob"] require(row["connectivity_fsck"] == row["full_fsck"] == row["read_returncode"] == 0, "Intact blob control") row = by_id["changed-blob"] require(row["connectivity_fsck"] == 0 and row["full_fsck"] != 0, "Changed blob detection boundary") require(row["read_returncode"] == 0 and row["read_payload"] == "archived-generation-X\n", "Changed blob read") require(row["original_loose_sha256"] != row["current_loose_sha256"], "Mutation did not change bytes") require("hash-path mismatch" in row["full_diagnostic"], "Unexpected full-fsck failure") row = by_id["missing-blob"] require(row["connectivity_fsck"] != 0 and row["full_fsck"] != 0 and row["read_returncode"] != 0, "Missing blob control") row = by_id["incremental-bundle"] require(row["verify_with_prerequisite"] == 0 and row["verify_empty_recipient"] != 0, "Incremental prerequisites") require(row["prerequisite_commit"] in row["empty_diagnostic"], "Missing prerequisite not identified") row = by_id["full-bundle"] require(row["verify_empty_recipient"] == row["clone_returncode"] == row["restored_fsck"] == 0, "Full bundle control") require(row["restored_payload"] == "archived-generation-2\n", "Full bundle restored payload") require(row["uncommitted_file_lookup"] != 0, "Uncommitted content unexpectedly included") row = by_id["changed-bundle-trailer"] require(row["changed_byte_count"] == 1 and row["sha256"] != row["original_sha256"], "Trailer mutation") require(row["verify_empty_recipient"] == 0 and row["clone_returncode"] != 0, "Bundle verify/unpack boundary") require("pack is corrupted (SHA1 mismatch)" in row["clone_diagnostic"], "Clone did not fail on pack checksum") def experiment(repeats, work_root=None): require(isinstance(repeats, int) and not isinstance(repeats, bool) and 1 <= repeats <= 5, "Repeat count must be an integer from 1 through 5") git = shutil.which("git") require(git is not None, "git must be on PATH") result = { "schema_version": 1, "generated_at": datetime.now(timezone.utc).isoformat(), "kind": "controlled native-Git observation", "harness_sha256": sha256(Path(__file__).read_bytes()), "environment": { "git_version": subprocess.check_output([git, "--version"], text=True).strip(), "git_binary_sha256": sha256(Path(git).read_bytes()), "python": platform.python_version(), "kernel": platform.release(), "system": platform.system(), "zlib": zlib.ZLIB_RUNTIME_VERSION, }, "method": { "repetitions": repeats, "cases_per_repetition": len(EXPECTED_IDS), "object_format": "sha1", "network_protocols_allowed": ["file"], "global_and_system_git_config": "disabled", "fixture_commits": 2, "payload_bytes": 22, "seed": None, "randomness": "none in experimental inputs", "limits": [ "Designed fixtures, not sampled repositories or failure rates.", "No hardware fault, crash durability, concurrency or application build tested.", "No partial clones, LFS, submodules, worktrees or custom repository extensions tested.", "Provider loss is a pathname rename, not a measurement of garbage collection.", "Repetition checks repeatability; no confidence interval or frequency estimate.", ], }, "runs": [], } for _ in range(repeats): with tempfile.TemporaryDirectory(prefix="hesela-git-fixture-", dir=work_root) as name: run = run_once(Path(name).resolve()) validate_run(run) result["runs"].append(run) result["summary"] = {"passed_cases": repeats * len(EXPECTED_IDS), "all_expected_outcomes_observed": True} return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--work-root", type=Path) parser.add_argument("--repeats", type=int, default=3) args = parser.parse_args() require(not args.output.exists(), "Refusing to replace an existing result") result = experiment(args.repeats, args.work_root) with args.output.open("x") as handle: json.dump(result, handle, indent=2, sort_keys=True) handle.write("\n") print(json.dumps(result["summary"], sort_keys=True)) if __name__ == "__main__": main()