File size: 8,426 Bytes
7a01b44 | 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 | #!/usr/bin/env python3
"""Build and verify the canonical zero-copy Full-2554 benchmark view."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any
VIEW_ROOT = Path(__file__).resolve().parent
REPO_ROOT = VIEW_ROOT.parents[1]
REGISTRY_ROOT = (
REPO_ROOT
/ "output/evaluation/core8_full2554_registry_v1_20260717_213712"
)
SOURCE_MANIFEST = REGISTRY_ROOT / "full2554.jsonl"
FAMILY_DIRS = {
"l2_passive": "passive_observation",
"l2_dynamic": "dynamic_tracking",
"l2_interaction": "interaction_experience",
"l3_owner_habit": "experience_generalization",
}
EXPECTED_COUNTS = {
"l2_passive": 1036,
"l2_dynamic": 1052,
"l2_interaction": 263,
"l3_owner_habit": 203,
}
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def read_jsonl(path: Path) -> list[dict[str, Any]]:
rows = []
with path.open("r", encoding="utf-8") as handle:
for line_number, line in enumerate(handle, 1):
if line.strip():
row = json.loads(line)
if not isinstance(row, dict):
raise ValueError(f"Non-object row at {path}:{line_number}")
rows.append(row)
return rows
def atomic_text(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(content, encoding="utf-8")
temporary.replace(path)
def write_json(path: Path, payload: Any) -> None:
atomic_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
atomic_text(
path,
"".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows),
)
def source_for(row: dict[str, Any]) -> tuple[str, str, Path]:
source = row.get("source") or {}
family = str(source.get("task_family") or "")
episode_id = str(source.get("episode_id") or "")
relative_path = str(source.get("episode_path") or "")
if family not in FAMILY_DIRS:
raise ValueError(f"Unknown task family: {family!r}")
if not episode_id or not relative_path:
raise ValueError(f"Incomplete source metadata for row {row.get('id')}")
episode_json = REPO_ROOT / relative_path
return family, episode_id, episode_json
def validate_source(rows: list[dict[str, Any]], *, check_hashes: bool) -> None:
if len(rows) != sum(EXPECTED_COUNTS.values()):
raise ValueError(f"Expected 2,554 rows, found {len(rows):,}")
counts = Counter()
ids: set[str] = set()
episode_ids: set[str] = set()
for row in rows:
row_id = str(row.get("id") or "")
family, episode_id, episode_json = source_for(row)
if not row_id or row_id in ids:
raise ValueError(f"Duplicate or empty manifest ID: {row_id!r}")
if episode_id in episode_ids:
raise ValueError(f"Duplicate episode ID: {episode_id}")
if not episode_json.is_file():
raise FileNotFoundError(episode_json)
expected_hash = str((row.get("source") or {}).get("episode_sha256") or "")
if check_hashes and (not expected_hash or sha256(episode_json) != expected_hash):
raise ValueError(f"Episode hash mismatch: {episode_json}")
ids.add(row_id)
episode_ids.add(episode_id)
counts[family] += 1
if dict(counts) != EXPECTED_COUNTS:
raise ValueError(f"Family counts differ: {dict(counts)}")
def ensure_link(link: Path, source_dir: Path) -> None:
expected_target = os.path.relpath(source_dir, link.parent)
if link.is_symlink():
if os.readlink(link) != expected_target:
raise ValueError(f"Existing link has the wrong target: {link}")
return
if link.exists():
raise FileExistsError(f"Refusing to replace existing path: {link}")
link.symlink_to(expected_target, target_is_directory=True)
def build_view(rows: list[dict[str, Any]]) -> None:
family_rows: dict[str, list[dict[str, Any]]] = defaultdict(list)
browse_lines = ["family\tepisode_id\tepisode_json\n"]
for row in rows:
family, episode_id, episode_json = source_for(row)
family_dir = FAMILY_DIRS[family]
link = VIEW_ROOT / "episodes" / family_dir / episode_id
link.parent.mkdir(parents=True, exist_ok=True)
ensure_link(link, episode_json.parent)
local_json = Path("episodes") / family_dir / episode_id / episode_json.name
organized_row = dict(row)
organized_row["organized_view"] = {
"family_directory": family_dir,
"episode_directory": str(Path("episodes") / family_dir / episode_id),
"episode_json": str(local_json),
}
family_rows[family].append(organized_row)
browse_lines.append(f"{family_dir}\t{episode_id}\t{local_json}\n")
manifests_dir = VIEW_ROOT / "manifests"
manifests_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(SOURCE_MANIFEST, manifests_dir / "full2554.jsonl")
shutil.copy2(REGISTRY_ROOT / "audit_report.json", manifests_dir / "audit_report.json")
shutil.copy2(REGISTRY_ROOT / "core8_registry.json", manifests_dir / "core8_registry.json")
for family, rows_for_family in family_rows.items():
write_jsonl(manifests_dir / f"{FAMILY_DIRS[family]}.jsonl", rows_for_family)
atomic_text(VIEW_ROOT / "browse.tsv", "".join(browse_lines))
write_json(
VIEW_ROOT / "metadata.json",
{
"schema": "embodied_memorizer_benchmark_full2554_organized_view_v1",
"organization": "relative_symlink_view",
"canonical_manifest": "manifests/full2554.jsonl",
"canonical_manifest_sha256": sha256(SOURCE_MANIFEST),
"episode_count": len(rows),
"family_counts": {
FAMILY_DIRS[family]: count
for family, count in EXPECTED_COUNTS.items()
},
"source_data_modified": False,
},
)
def verify_view(rows: list[dict[str, Any]]) -> dict[str, Any]:
counts = Counter()
failures = []
for row in rows:
family, episode_id, episode_json = source_for(row)
link = VIEW_ROOT / "episodes" / FAMILY_DIRS[family] / episode_id
local_json = link / episode_json.name
if not link.is_symlink():
failures.append(f"not a symlink: {link}")
continue
if link.resolve() != episode_json.parent.resolve():
failures.append(f"wrong link target: {link}")
continue
if not local_json.is_file():
failures.append(f"missing local JSON: {local_json}")
continue
expected_hash = str((row.get("source") or {}).get("episode_sha256") or "")
if sha256(local_json) != expected_hash:
failures.append(f"hash mismatch: {local_json}")
continue
counts[family] += 1
report = {
"schema": "embodied_memorizer_benchmark_full2554_view_verification_v1",
"status": "pass" if not failures and dict(counts) == EXPECTED_COUNTS else "fail",
"expected_episodes": sum(EXPECTED_COUNTS.values()),
"verified_episodes": sum(counts.values()),
"family_counts": {
FAMILY_DIRS[family]: counts[family] for family in FAMILY_DIRS
},
"source_manifest_sha256": sha256(SOURCE_MANIFEST),
"issues": failures,
}
write_json(VIEW_ROOT / "verification_report.json", report)
if report["status"] != "pass":
raise RuntimeError(json.dumps(report, indent=2))
return report
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--verify-only",
action="store_true",
help="Verify the existing organized view without creating links.",
)
args = parser.parse_args()
rows = read_jsonl(SOURCE_MANIFEST)
validate_source(rows, check_hashes=not args.verify_only)
if not args.verify_only:
build_view(rows)
print(json.dumps(verify_view(rows), indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|