"""Validate the Test-only archive and records. This is not an answer scorer.""" from __future__ import annotations import argparse import hashlib import json from collections import Counter from pathlib import Path, PurePosixPath import zipfile TASKS = {"assembly_decision": 238, "atomic_action": 662, "minimal_rework": 100} FAMILIES = {"gearbox_structure", "luban_12_pillars", "parametric_box_lock_01", "parametric_tower_lock_10", "spherical_interlocking_structure", "triangle_dovetail_structure"} META = {"schema_version", "task_family", "split", "assembly_id", "variant_id", "episode_id", "problem_id", "experiment_group_id", "source_sample_id", "label_contract", "task_contract_version"} def file_hash(path): with Path(path).open("rb") as f: return hashlib.file_digest(f, "sha256").hexdigest() def safe_image_path(value): p = PurePosixPath(value) return (not p.is_absolute() and len(p.parts) > 1 and p.parts[0] == "images" and ".." not in p.parts and "\\" not in value and ":" not in value and p.suffix == ".png" and p.as_posix() == value) def verify(root): root = Path(root).resolve() rows = [json.loads(l) for l in (root / "test.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()] errors = [] if len(rows) != 1000: errors.append("Expected 1000 Test records") if len({r["id"] for r in rows}) != len(rows): errors.append("Duplicate sample IDs") counts = Counter(r["metadata"]["task_family"] for r in rows) if counts != Counter(TASKS): errors.append("Task counts do not match the Test split") if {r["metadata"]["assembly_id"] for r in rows} != FAMILIES: errors.append("Unexpected assembly families") for row in rows: if set(row) != {"id", "messages", "images", "metadata"}: errors.append(f"Unexpected top-level fields: {row['id']}") if set(row["metadata"]) != META or row["metadata"]["split"] != "test": errors.append(f"Non-public metadata or non-Test row: {row['id']}") if not row["messages"] or any(set(m) != {"role", "content"} or m["role"] != "user" or not isinstance(m["content"], str) for m in row["messages"]): errors.append(f"Non-user message or invalid prompt: {row['id']}") if not row["images"] or any(not safe_image_path(p) for p in row["images"]): errors.append(f"Invalid image references: {row['id']}") refs = {p for r in rows for p in r["images"]} if len(refs) != 1140: errors.append("Expected 1140 unique Test images") index = json.loads((root / "image_manifest.json").read_text(encoding="utf-8")) entries = index["images"] if len(entries) != len({e['path'] for e in entries}) or {e['path'] for e in entries} != refs: errors.append("Image index does not exactly match Test references") expected = {e["path"]: e for e in entries} with zipfile.ZipFile(root / "images.zip") as archive: names = archive.namelist() if len(names) != len(set(names)) or set(names) != refs: errors.append("Archive contains duplicate, missing or extra files") for info in archive.infolist(): if not safe_image_path(info.filename) or info.filename not in expected: errors.append(f"Unexpected archive entry: {info.filename}") continue content = archive.read(info) entry = expected[info.filename] if not content.startswith(b"\x89PNG\r\n\x1a\n"): errors.append(f"Not a PNG: {info.filename}") if len(content) != entry['bytes'] or hashlib.sha256(content).hexdigest() != entry['sha256']: errors.append(f"Image hash mismatch: {info.filename}") declared = {} for line in (root / "MANIFEST.sha256").read_text(encoding="utf-8").splitlines(): digest, name = line.split(" ", 1) if Path(name).name != name or "/" in name or "\\" in name or name in declared: errors.append(f"Invalid/duplicate manifest entry: {name}") continue declared[name] = digest if not (root / name).is_file() or file_hash(root / name) != digest: errors.append(f"Release hash mismatch: {name}") actual = {p.name for p in root.iterdir() if p.is_file() and p.name != "MANIFEST.sha256"} if actual != set(declared): errors.append("Release files differ from the checksum manifest") for path in root.iterdir(): if path.is_dir() and path.name not in {".git", ".cache", "__pycache__", "images"}: errors.append(f"Unexpected directory in upload root: {path.name}") # If users manually extracted images, they must still be Test-only and intact. if (root / 'images').exists(): extracted = {p.relative_to(root).as_posix(): p for p in (root/'images').rglob('*') if p.is_file()} if set(extracted) != refs: errors.append("Extracted images contain missing or extra files") else: for name, path in extracted.items(): if file_hash(path) != expected[name]['sha256']: errors.append(f"Extracted image hash mismatch: {name}") release = json.loads((root/'release_manifest.json').read_text(encoding='utf-8')) if release['counts']['test_rows'] != len(rows) or release['counts']['unique_images'] != len(refs): errors.append("Release manifest counts mismatch") if release['test_jsonl_sha256'] != file_hash(root/'test.jsonl'): errors.append("Release manifest JSONL hash mismatch") return {"test_rows": len(rows), "task_counts": dict(counts), "families": len(FAMILIES), "unique_images": len(refs), "assistant_messages": sum(m['role']=='assistant' for r in rows for m in r['messages']), "metadata_allowlist_checked": True, "errors": errors} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent) try: result = verify(parser.parse_args().root) except Exception as exc: result = {"errors": [f"{type(exc).__name__}: {exc}"]} print(json.dumps(result, ensure_ascii=False, indent=2)) raise SystemExit(bool(result["errors"]))