LegoReview-Bench / tools /restore_instance.py
Codex
Release LegoReview-Bench
131944e
Raw History Blame Contribute Delete
13.4 kB
"""Portable, hash-checked source bundles for LegoReview-Bench (standard library only)."""
from __future__ import annotations
import argparse
import gzip
import hashlib
import io
import json
import os
import shutil
import subprocess
import tarfile
import tempfile
from collections import defaultdict
from contextlib import ExitStack
from pathlib import Path, PurePosixPath
def digest(raw: bytes) -> str:
return hashlib.sha256(raw).hexdigest()
def fingerprint(path: Path, root: Path) -> dict:
hasher = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
hasher.update(block)
return {
"path": path.relative_to(root).as_posix(),
"sha256": hasher.hexdigest(),
"size_bytes": path.stat().st_size,
}
def checked(root: Path, binding: dict) -> Path:
path = root / safe_path(binding["path"])
if fingerprint(path, root) != binding:
raise ValueError(f"file binding differs: {binding['path']}")
return path
def safe_path(name: str) -> Path:
parts = PurePosixPath(name).parts
if (
not parts
or name.startswith("/")
or ".." in parts
or ".git" in parts
or "\\" in name
):
raise ValueError("invalid source member path")
return Path(*parts)
def inventory_files(inventories: dict) -> dict:
blobs = {}
for inventory in inventories.values():
seen = set()
for entry in inventory["files"]:
safe_path(entry["path"])
if entry["path"] in seen:
raise ValueError("duplicate inventory path")
seen.add(entry["path"])
if entry["mode"] not in {"100644", "100755", "120000"}:
raise ValueError("unsupported source file mode")
sha = entry["sha256"]
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
raise ValueError("invalid source hash")
previous = blobs.setdefault(sha, entry)
if previous["size_bytes"] != entry["size_bytes"]:
raise ValueError("inconsistent blob size")
for name in seen:
if any(p.as_posix() in seen for p in PurePosixPath(name).parents):
raise ValueError("source file is also an ancestor")
return blobs
def checked_blob(raw: bytes, entry: dict) -> None:
if len(raw) != entry["size_bytes"] or digest(raw) != entry["sha256"]:
raise ValueError(f"source bytes differ: {entry['path']}")
git_blob = b"blob " + str(len(raw)).encode() + b"\0" + raw
if hashlib.sha1(git_blob).hexdigest() != entry["oid"]:
raise ValueError(f"Git object differs: {entry['path']}")
class GitBlobs:
"""Read known blobs in one process, avoiding a Lustre open per source file."""
def __init__(self, cache: Path):
self.process = subprocess.Popen(
["git", "--git-dir", str(cache), "cat-file", "--batch"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
def read(self, entry: dict) -> bytes:
process = self.process
process.stdin.write((entry["oid"] + "\n").encode())
process.stdin.flush()
header = process.stdout.readline().decode().strip().split()
if header != [entry["oid"], "blob", str(entry["size_bytes"])]:
raise ValueError(f"Git blob unavailable: {entry['path']}")
raw = process.stdout.read(entry["size_bytes"])
if process.stdout.read(1) != b"\n":
raise ValueError("Git batch stream framing")
return raw
def close(self) -> None:
self.process.stdin.close()
self.process.stdout.close()
if self.process.wait(timeout=30):
raise ValueError("Git batch process failed")
def verify_git_tree(cache: Path, inventory: dict) -> None:
sha = inventory["snapshot"]
tree = (
subprocess.check_output(
["git", "--git-dir", str(cache), "rev-parse", f"{sha}^{{tree}}"],
stderr=subprocess.DEVNULL,
)
.decode()
.strip()
)
if tree != inventory["tree_oid"]:
raise ValueError("commit tree differs from frozen inventory")
raw = subprocess.check_output(
["git", "--git-dir", str(cache), "ls-tree", "-rz", "--full-tree", sha],
stderr=subprocess.DEVNULL,
)
actual = {}
for item in raw.split(b"\0"):
if not item:
continue
head, name = item.split(b"\t", 1)
mode, kind, oid = head.decode().split()
actual[os.fsdecode(name)] = (mode, kind, oid)
expected = {
e["path"]: (e["mode"], e["kind"], e["oid"])
for e in inventory["files"] + inventory["unavailable"]
}
if actual != expected:
raise ValueError("Git tree member set differs from frozen inventory")
def build_bundle(archive: Path, inventories: dict, trees: dict) -> dict:
"""Deduplicate baseline/target contents; only inventory-bound blobs are exported."""
blobs = inventory_files(inventories)
owners = {}
readers = {}
archive.parent.mkdir(parents=True, exist_ok=True)
fd, temp = tempfile.mkstemp(dir=archive.parent, suffix=".partial")
os.close(fd)
try:
with ExitStack() as stack:
for role, inventory in inventories.items():
tree = Path(trees[role])
cache = tree.parents[2] / "git" / f"{tree.parent.name}.git"
if cache.is_dir():
verify_git_tree(cache, inventory)
reader = GitBlobs(cache)
stack.callback(reader.close)
readers[role] = reader
for entry in inventory["files"]:
owners.setdefault(entry["sha256"], (role, entry))
with open(temp, "wb") as stream:
with gzip.GzipFile(
fileobj=stream, mode="wb", filename="", mtime=0, compresslevel=5
) as compressed:
with tarfile.open(
fileobj=compressed, mode="w|", format=tarfile.USTAR_FORMAT
) as output:
for sha in sorted(blobs):
role, entry = owners[sha]
if role in readers:
raw = readers[role].read(entry)
else:
source = Path(trees[role]) / safe_path(entry["path"])
raw = (
os.fsencode(os.readlink(source))
if entry["mode"] == "120000"
else source.read_bytes()
)
checked_blob(raw, entry)
member = tarfile.TarInfo("blobs/" + sha)
member.size = len(raw)
member.mode = 0o444
member.mtime = 0
output.addfile(member, io.BytesIO(raw))
Path(temp).replace(archive)
return verify_bundle(archive, inventories)
finally:
Path(temp).unlink(missing_ok=True)
def stream_bundle(archive: Path, inventories: dict):
expected = inventory_files(inventories)
seen = set()
with tarfile.open(archive, "r|gz") as source:
for member in source:
sha = member.name.removeprefix("blobs/")
if (
member.name != "blobs/" + sha
or sha not in expected
or sha in seen
or not member.isfile()
):
raise ValueError("unexpected source archive member")
raw = source.extractfile(member).read()
checked_blob(raw, expected[sha])
seen.add(sha)
yield sha, raw
if seen != set(expected):
raise ValueError("missing source archive members")
def verify_bundle(archive: Path, inventories: dict) -> dict:
sizes = [len(raw) for _, raw in stream_bundle(archive, inventories)]
return {
"unique_blobs": len(sizes),
"unique_bytes": sum(sizes),
"snapshot_files": sum(len(i["files"]) for i in inventories.values()),
}
def restore(dataset: Path, instance_id: str, destination: Path) -> dict:
"""Restore source-only model workspace without reading reference annotations."""
safe_path(instance_id)
input_file = dataset / "inputs" / instance_id / "input.json"
inp = json.loads(input_file.read_text())
if inp["instance_id"] != instance_id:
raise ValueError("input instance identity mismatch")
if destination.exists():
raise ValueError("restore destination must not exist")
inventories = {
role: json.loads(checked(dataset, inp[f"{role}_inventory"]).read_text())
for role in ("baseline", "target")
}
for role, inventory in inventories.items():
field = "base_commit" if role == "baseline" else "review_commit"
if inventory["snapshot"] != inp[field]:
raise ValueError("snapshot commit binding mismatch")
archive = checked(dataset, inp["source_archive"])
patch = checked(dataset, inp["patch_file"])
instruction = checked(dataset, inp["instruction_file"])
metadata_path = checked(dataset, inp["pr_metadata_file"])
metadata_fields = (
"pr_title",
"pr_description",
"pr_description_status",
"pr_metadata_version_status",
"pr_metadata_collected_at",
"pr_metadata_source_url",
)
metadata = json.loads(metadata_path.read_text())
if metadata["instance_id"] != instance_id or any(
metadata[key] != inp[key] for key in metadata_fields
):
raise ValueError("PR metadata differs from review input")
if inp["title"] != inp["pr_title"] or inp["body"] != inp["pr_description"]:
raise ValueError("PR title/body aliases differ")
targets = defaultdict(list)
for role, inventory in inventories.items():
for entry in inventory["files"]:
targets[entry["sha256"]].append((role, entry))
destination.parent.mkdir(parents=True, exist_ok=True)
stage = Path(
tempfile.mkdtemp(prefix=destination.name + ".partial-", dir=destination.parent)
)
symlinks = []
try:
for sha, raw in stream_bundle(archive, inventories):
for role, entry in targets[sha]:
output = stage / role / safe_path(entry["path"])
output.parent.mkdir(parents=True, exist_ok=True)
if entry["mode"] == "120000":
symlinks.append((output, os.fsdecode(raw)))
else:
with output.open("xb") as stream:
stream.write(raw)
output.chmod(0o755 if entry["mode"] == "100755" else 0o644)
# All ordinary file writes precede link creation, including external links.
for output, link in symlinks:
output.symlink_to(link)
shutil.copyfile(patch, stage / "change.diff")
shutil.copyfile(instruction, stage / "instruction.md")
shutil.copyfile(metadata_path, stage / "pr_metadata.json")
restored_input = {
"schema_version": "legoreview-bench.review-input",
**{key: inp[key] for key in metadata_fields},
"title": inp["title"],
"body": inp["body"],
"pr_metadata_file": fingerprint(stage / "pr_metadata.json", stage),
"task_id": instance_id,
"cutoff": inp["review_cutoff"],
"available_task_description": inp["body"],
"description_status": inp["description_status"],
"requirements_status": inp["requirements_status"],
"changed_paths": inp["changed_files"],
"input_boundary": inp["input_boundary"],
"diff": fingerprint(stage / "change.diff", stage),
"instruction": fingerprint(stage / "instruction.md", stage),
}
for role, inventory in inventories.items():
inventory_path = stage / f"{role}.inventory.json"
inventory_path.write_text(json.dumps(inventory, indent=2) + "\n")
restored_input[role] = {
"directory": role,
"commit": inventory["snapshot"],
"receipt": fingerprint(inventory_path, stage),
"files": len(inventory["files"]),
"inventory_status": inp[f"{role}_status"],
"unavailable": inventory["unavailable"],
"lfs_pointers": inventory["lfs_pointers"],
}
(stage / "input.json").write_text(json.dumps(restored_input, indent=2) + "\n")
stage.rename(destination)
finally:
if stage.exists():
shutil.rmtree(stage)
return {
"instance_id": instance_id,
"destination": str(destination),
"files": sum(len(i["files"]) for i in inventories.values()),
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset", type=Path, required=True)
parser.add_argument("--instance-id", required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
print(json.dumps(restore(args.dataset, args.instance_id, args.output)))