File size: 13,434 Bytes
131944e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"""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)))