#!/usr/bin/env python3 """Native Git closure experiment. Changes only fresh temporary fixture repos.""" import argparse import datetime import hashlib import json import os from pathlib import Path import platform import re import shutil import subprocess import tempfile CASES = ("full", "partial-cold", "partial-head", "partial-materialized", "partial-online-read", "full-missing-blob", "shallow-full") OID = re.compile(r"^[0-9a-f]{40}$") def digest(data): return hashlib.sha256(data).hexdigest() def require(condition, message): if not condition: raise RuntimeError(message) def parse_missing(text): missing = [] for line in text.splitlines(): first = line.split(" ", 1)[0] oid = first.removeprefix("?") require(bool(OID.fullmatch(oid)), "Malformed object inventory") if first.startswith("?"): missing.append(oid) require(len(set(missing)) == len(missing), "Duplicate missing object") return sorted(missing) class Runner: def __init__(self, root, binary): self.root, self.binary, self.trace = root, binary, [] home, template = root / "home", root / "template" home.mkdir() template.mkdir() self.env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_") and k not in ("HOME", "XDG_CONFIG_HOME")} self.env.update(HOME=str(home), XDG_CONFIG_HOME=str(home), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0", LC_ALL="C", TZ="UTC", GIT_AUTHOR_NAME="Hesela fixture", GIT_AUTHOR_EMAIL="fixture@example.invalid", GIT_COMMITTER_NAME="Hesela 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", GIT_TEMPLATE_DIR=str(template)) def git(self, repo, *args, online=False, check=True): # Only file transport is permitted, and only when explicitly enabled. env = dict(self.env, GIT_ALLOW_PROTOCOL="file" if online else "") cmd = [self.binary, "-c", "protocol.allow=never", "-c", "protocol.file.allow=" + ("always" if online else "never"), "-c", "gc.auto=0", "-c", "maintenance.auto=false", "-C", str(repo), *args] p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, timeout=20) normalize = lambda x: x.replace(str(self.root), "$FIXTURE") row = {"cwd": str(repo.relative_to(self.root)), "args": [normalize(a) for a in args], "file_transport_allowed": online, "returncode": p.returncode, "stdout": normalize(p.stdout.decode("utf-8", "backslashreplace")), "stderr": normalize(p.stderr.decode("utf-8", "backslashreplace"))} self.trace.append(row) require(not check or p.returncode == 0, "Git failed: " + repr(row)) return p def inventory(self, repo): p = self.git(repo, "rev-list", "--objects", "--all", "--missing=print") return parse_missing(p.stdout.decode()) def make_source(r): source = r.root / "source" r.git(r.root, "init", "--object-format=sha1", "-b", "main", str(source)) r.git(source, "config", "uploadpack.allowFilter", "true") commits, payloads = [], {} for i in range(1, 4): (source / "current.txt").write_bytes(("version " + str(i) + "\n").encode()) (source / "stable.txt").write_bytes(b"stable payload\n") if i == 1: (source / "deleted.txt").write_bytes(b"historical only\n") elif i == 2: (source / "deleted.txt").unlink() r.git(source, "add", "-A") r.git(source, "commit", "-m", "fixture version " + str(i)) commits.append(r.git(source, "rev-parse", "HEAD").stdout.decode().strip()) for name in ("current.txt", "stable.txt", "deleted.txt"): if (source / name).exists(): oid = r.git(source, "rev-parse", "HEAD:" + name).stdout.decode().strip() payloads[oid] = (source / name).read_bytes() r.git(source, "tag", "archive-tip") require(len(payloads) == 5, "Expected five distinct blobs") return source, commits, payloads def read_result(r, repo, spec, expected): p = r.git(repo, "show", spec, check=False) return {"returncode": p.returncode, "bytes": len(p.stdout), "sha256": digest(p.stdout), "expected_sha256": digest(expected), "matches": p.returncode == 0 and p.stdout == expected} def one_case(root, binary, case): r = Runner(root, binary) source, commits, payloads = make_source(r) clone = root / "candidate" args = ["clone", "--no-checkout"] if case.startswith("partial"): args += ["--filter=blob:none"] if case == "shallow-full": args += ["--depth=1"] if case == "full-missing-blob": args += ["--no-hardlinks", str(source), str(clone)] else: args += [source.as_uri(), str(clone)] r.git(root, *args, online=True) initial = r.inventory(clone) online_read = None if case == "partial-head": r.git(clone, "checkout", "main", online=True) require((clone / "current.txt").read_bytes() == b"version 3\n", "HEAD differs") elif case == "partial-materialized": # Independent source manifest: a control, not a generic repair recipe. for oid, expected in sorted(payloads.items()): require(r.git(clone, "cat-file", "blob", oid, online=True).stdout == expected, "Materialized payload differs") elif case == "partial-online-read": p = r.git(clone, "show", "HEAD:current.txt", online=True) online_read = {"returncode": p.returncode, "matches": p.stdout == b"version 3\n"} elif case == "full-missing-blob": oid = r.git(source, "rev-parse", commits[0] + ":current.txt").stdout.decode().strip() loose = clone / ".git" / "objects" / oid[:2] / oid[2:] require(loose.is_file(), "Negative control needs a copied loose object") loose.unlink() before = r.inventory(clone) shallow = r.git(clone, "rev-parse", "--is-shallow-repository").stdout == b"true\n" refs = r.git(clone, "show-ref", "--heads", "--tags").stdout.decode() packs = len(list((clone / ".git" / "objects" / "pack").glob("*.promisor"))) source.rename(root / "provider-unavailable") fsck = r.git(clone, "fsck", "--full", check=False) strict = r.git(clone, "fsck", "--full", "--strict", check=False) inv = r.git(clone, "rev-list", "--objects", "--all", "--missing=print") missing = parse_missing(inv.stdout.decode()) head = read_result(r, clone, "HEAD:current.txt", b"version 3\n") historical = read_result(r, clone, commits[0] + ":current.txt", b"version 1\n") deleted = read_result(r, clone, commits[0] + ":deleted.txt", b"historical only\n") bundle = root / "candidate.bundle" created = r.git(clone, "bundle", "create", str(bundle), "--all", check=False) restore = None if created.returncode == 0: target = root / "restore" cp = r.git(root, "clone", "--bare", str(bundle), str(target), online=True, check=False) restore = {"clone_returncode": cp.returncode} if cp.returncode == 0: restore.update( fsck_returncode=r.git(target, "fsck", "--full", check=False).returncode, head=read_result(r, target, "HEAD:current.txt", b"version 3\n"), historical=read_result(r, target, commits[0] + ":current.txt", b"version 1\n"), deleted=read_result(r, target, commits[0] + ":deleted.txt", b"historical only\n")) return { "case": case, "initial_missing": initial, "before_offline_missing": before, "offline_missing": missing, "after_offline_missing": r.inventory(clone), "provider_path_absent": not source.exists(), "inventory_returncode": inv.returncode, "fsck_returncode": fsck.returncode, "strict_fsck_returncode": strict.returncode, "head": head, "historical": historical, "deleted": deleted, "online_read": online_read, "is_shallow": shallow, "promisor_pack_count": packs, "refs": refs, "source_commits": commits, "bundle_create_returncode": created.returncode, "restore": restore, "expected_blob_manifest": [{"oid": oid, "bytes": len(data), "sha256": digest(data)} for oid, data in sorted(payloads.items())]}, r.trace def run(binary, repeats): rows, traces = [], [] with tempfile.TemporaryDirectory(prefix="git-partial-closure-") as temp: for repeat in range(repeats): for case in CASES: root = Path(temp) / (str(repeat) + "-" + case) root.mkdir() row, trace = one_case(root, binary, case) row["repeat"] = repeat rows.append(row) traces.append({"repeat": repeat, "case": case, "commands": trace}) return {"schema_version": 1, "generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "harness_sha256": digest(Path(__file__).read_bytes()), "environment": {"git_version": subprocess.check_output([binary, "--version"], text=True).strip(), "git_binary_sha256": digest(Path(binary).read_bytes()), "python": platform.python_version(), "platform": platform.platform()}, "method": {"repeats": repeats, "cases": list(CASES), "transport": "file:// during setup/materialization; none during checks", "history": "three commits, five distinct blobs, two HEAD files", "scope": "synthetic native-Git fixtures, not device failure or field incidence"}, "observations": rows, "traces": traces} def main(): p = argparse.ArgumentParser() p.add_argument("--output", type=Path, required=True) p.add_argument("--repeats", type=int, default=3, choices=range(1, 6)) p.add_argument("--git", default=shutil.which("git")) a = p.parse_args() require(not a.output.exists(), "Refusing to overwrite a capture") result = run(str(Path(a.git).resolve()), a.repeats) with a.output.open("x") as f: json.dump(result, f, indent=2) f.write("\n") print(json.dumps([{"case": x["case"], "missing": len(x["offline_missing"]), "fsck": x["fsck_returncode"], "head": x["head"]["matches"], "history": x["historical"]["matches"], "bundle": x["bundle_create_returncode"], "restore": x["restore"] and x["restore"]["clone_returncode"]} for x in result["observations"]], indent=2)) if __name__ == "__main__": main()