File size: 22,976 Bytes
59b4e16 | 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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 | #!/usr/bin/env python3
"""Build a portable Harbor task + rootless Apptainer runtime release.
This packager is intentionally distinct from the Gate-1-clean SWEGym/R2EGym
packagers. It supports datasets without reference solutions, but records that
limitation explicitly and never labels such a release Gate-1-clean.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
import shutil
import subprocess
import tarfile
import tempfile
from pathlib import Path, PurePosixPath
from stat import S_ISLNK, S_ISREG
from typing import Any
import pyarrow as pa
import pyarrow.parquet as pq
import zstandard as zstd
CORE_FILES = ("task.toml", "instruction.md", "environment/Dockerfile", "tests/test.sh")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--release-id", required=True)
parser.add_argument("--release-label", required=True)
parser.add_argument("--hf-repo", required=True)
parser.add_argument("--tasks", required=True, type=Path)
parser.add_argument("--source-parquet", required=True, type=Path)
parser.add_argument("--upstream-repo", required=True)
parser.add_argument("--upstream-revision", required=True)
parser.add_argument("--upstream-subdirectory")
parser.add_argument("--sif-cache", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--license", default="other")
parser.add_argument("--expected-source-tasks", required=True, type=int)
parser.add_argument("--expected-compatible-tasks", required=True, type=int)
parser.add_argument("--allow-offline-test-patch", action="store_true")
parser.add_argument("--runtime-evidence", action="append", default=[])
parser.add_argument("--validation-note", required=True)
parser.add_argument("--harbor-root", type=Path)
parser.add_argument("--overfit-count", type=int, default=64)
parser.add_argument("--diagnostic-count", type=int, default=64)
parser.add_argument("--release-date", default="2026-09-24")
return parser.parse_args()
def sha256_bytes(value: bytes) -> str:
return hashlib.sha256(value).hexdigest()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def sha256_text(value: str) -> str:
return sha256_bytes(value.encode())
def docker_build_context_hash(context: Path, dockerfile: Path) -> str:
"""Mirror Harbor's stable 64-bit BLAKE2 build-context cache key."""
entries: list[Path] = []
for root, dirs, files in context.walk(top_down=True, follow_symlinks=False):
dirs.sort()
entries.extend(root / name for name in sorted(files))
digest = hashlib.blake2b(digest_size=8)
digest.update(dockerfile.name.encode())
digest.update(dockerfile.read_bytes())
for path in entries:
stat = path.lstat()
digest.update(str(path.relative_to(context)).encode())
digest.update(stat.st_mode.to_bytes(4, "little"))
digest.update(stat.st_size.to_bytes(8, "little"))
if S_ISLNK(stat.st_mode):
digest.update(os.readlink(path).encode())
elif S_ISREG(stat.st_mode):
digest.update(path.read_bytes())
return digest.hexdigest()
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
path.write_text("".join(json.dumps(row, sort_keys=True) + "\n" for row in rows))
def normalized_member_name(name: str) -> str:
parts = [part for part in PurePosixPath(name).parts if part not in ("", ".")]
if parts and parts[0] == "tasks":
parts = parts[1:]
return PurePosixPath(*parts).as_posix()
def archive_inventory(payload: bytes) -> dict[str, str]:
files: dict[str, str] = {}
with tarfile.open(fileobj=io.BytesIO(payload), mode="r:*") as archive:
for member in archive.getmembers():
if not member.isfile():
continue
name = normalized_member_name(member.name)
if not name:
continue
stream = archive.extractfile(member)
if stream is None:
raise RuntimeError(f"cannot extract {member.name}")
files[name] = sha256_bytes(stream.read())
return files
def local_inventory(task: Path) -> dict[str, str]:
root = task.resolve()
return {
path.relative_to(root).as_posix(): sha256_file(path)
for path in sorted(root.rglob("*"))
if path.is_file()
}
def source_rows(path: Path) -> dict[str, tuple[bytes, dict[str, str]]]:
parquet = pq.ParquetFile(path)
rows: dict[str, tuple[bytes, dict[str, str]]] = {}
for row_group in range(parquet.num_row_groups):
table = parquet.read_row_group(row_group, columns=["path", "task_binary"])
for row in table.to_pylist():
task_id = str(row["path"])
if task_id in rows:
raise RuntimeError(f"duplicate source task: {task_id}")
payload = bytes(row["task_binary"])
rows[task_id] = (payload, archive_inventory(payload))
return rows
def add_tar_entry(archive: tarfile.TarFile, path: Path, arcname: str) -> None:
info = archive.gettarinfo(str(path), arcname=arcname)
info.uid = info.gid = 0
info.uname = info.gname = ""
info.mtime = 0
if path.is_file():
with path.open("rb") as stream:
archive.addfile(info, stream)
else:
archive.addfile(info)
def deterministic_task_tar(task: Path) -> bytes:
root = task.resolve()
payload = io.BytesIO()
with tarfile.open(fileobj=payload, mode="w", format=tarfile.PAX_FORMAT) as archive:
for path in sorted(root.rglob("*")):
add_tar_entry(archive, path, path.relative_to(root).as_posix())
return payload.getvalue()
def write_tasks_archive(tasks: Path, task_ids: list[str], output: Path) -> None:
compressor = zstd.ZstdCompressor(level=19, threads=0)
with output.open("wb") as raw:
with compressor.stream_writer(raw, closefd=False) as compressed:
with tarfile.open(fileobj=compressed, mode="w|", format=tarfile.PAX_FORMAT) as archive:
for task_id in task_ids:
root = (tasks / task_id).resolve()
add_tar_entry(archive, root, f"tasks/{task_id}")
for path in sorted(root.rglob("*")):
add_tar_entry(
archive,
path,
f"tasks/{task_id}/{path.relative_to(root).as_posix()}",
)
def stable_order(task_ids: list[str], seed: str) -> list[str]:
return sorted(
task_ids,
key=lambda task: (sha256_text(f"{seed}\0{task}"), task),
)
def copy_large_file(source: Path, target: Path) -> None:
try:
os.link(source, target)
except OSError:
shutil.copy2(source, target)
def runtime_provenance(harbor_root: Path | None, output: Path) -> dict[str, Any] | None:
if harbor_root is None:
return None
root = harbor_root.resolve()
revision = subprocess.run(
["git", "rev-parse", "HEAD"], cwd=root, check=True, capture_output=True, text=True
).stdout.strip()
patch = subprocess.run(
["git", "diff", "--binary"], cwd=root, check=True, capture_output=True
).stdout
patch_path = output / "harbor-runtime.patch"
patch_path.write_bytes(patch)
return {
"repository": "harbor",
"revision": revision,
"dirty_patch": patch_path.name,
"dirty_patch_sha256": sha256_bytes(patch),
"dirty_patch_bytes": len(patch),
}
def write_materializer(path: Path) -> None:
path.write_text(
'''#!/usr/bin/env python3
"""Materialize Harbor task and SIF-cache views from this release."""
import argparse
import json
import os
import subprocess
import tempfile
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("--release", type=Path, default=Path(__file__).resolve().parents[1])
parser.add_argument("--runtime-root", type=Path, required=True)
args = parser.parse_args()
release = args.release.resolve()
runtime = args.runtime_root.resolve()
if runtime.exists():
raise SystemExit(f"refusing to overwrite {runtime}")
runtime.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="harbor-runtime-", dir=runtime.parent) as temporary:
stage = Path(temporary) / "runtime"
stage.mkdir()
subprocess.run(
["tar", "--use-compress-program=zstd", "-xf", str(release / "tasks.tar.zst"), "-C", str(stage)],
check=True,
)
sif_cache = stage / "sif-cache"
sif_cache.mkdir()
for line in (release / "manifests" / "task-sif-routing.jsonl").read_text().splitlines():
row = json.loads(line)
(sif_cache / f"{row['task_id']}.sif").symlink_to(release / row["sif_image"])
os.replace(stage, runtime)
print(f"materialized runtime at {runtime}")
'''
)
def write_readme(
path: Path,
args: argparse.Namespace,
task_count: int,
excluded_count: int,
image_count: int,
image_bytes: int,
patch_count: int,
) -> None:
source_location = args.upstream_repo
if args.upstream_subdirectory:
source_location += f"/{args.upstream_subdirectory}"
patch_text = (
f" The release records **{patch_count:,}** offline-only `tests/test.sh` patches that "
"neutralize redundant runtime package-download commands; verifier test logic is unchanged."
if patch_count
else " Task contents are byte-identical to the selected upstream task archives."
)
path.write_text(
"---\n"
f"license: {args.license}\n"
"task_categories:\n- reinforcement-learning\n"
"language:\n- en\n"
"tags:\n- harbor\n- apptainer\n- offline\n- agentic-coding\n"
"configs:\n- config_name: default\n data_files:\n - split: train\n path: tasks.parquet\n"
"---\n\n"
f"# {args.release_label}: rootless Apptainer runtime release\n\n"
f"This release contains **{task_count:,}** runnable Harbor tasks from "
f"`{source_location}@{args.upstream_revision}` and bundles the exact aarch64 SIF images "
"used on Jupiter with rootless Apptainer 1.4.5."
f"{patch_text}\n\n"
f"{excluded_count:,} source tasks are excluded for missing required task/verifier files. "
"The source does **not** provide reference solutions, so this is a production-runtime-tested "
"release rather than an all-task oracle-certified Gate-1 release. The validation summary "
"preserves that distinction.\n\n"
"## Contents\n\n"
"- `tasks.parquet`: deterministic Harbor task payloads.\n"
"- `tasks.tar.zst`: materialized task directories.\n"
f"- `sif-images/`: {image_count} content-addressed aarch64 image(s), "
f"{image_bytes / (1024**3):.2f} GiB total.\n"
"- `manifests/`: compatible tasks, routing, exclusions, splits, and patches.\n"
"- `validation/summary.json`: exact validation scope and limitations.\n"
"- `scripts/materialize_release.py`: fresh runtime materializer.\n"
"- `SHA256SUMS`: checksums for every published file.\n\n"
"## Use with Harbor\n\n"
"```bash\n"
f"hf download {args.hf_repo} --repo-type dataset --local-dir release\n"
"cd release && sha256sum -c SHA256SUMS\n"
"python scripts/materialize_release.py --runtime-root runtime\n"
"harbor run -p runtime/tasks -e apptainer --environment-kwarg sif_cache=$PWD/runtime/sif-cache ...\n"
"```\n\n"
"The images are **aarch64**, not x86_64. See `dataset_manifest.json` and `provenance/` "
"for immutable source and Harbor-runtime details.\n"
)
def main() -> int:
args = parse_args()
tasks = args.tasks.resolve()
source_parquet = args.source_parquet.resolve()
sif_cache = args.sif_cache.resolve()
output = args.output.resolve()
if output.exists():
raise SystemExit(f"refusing to overwrite {output}")
upstream = source_rows(source_parquet)
if len(upstream) != args.expected_source_tasks:
raise SystemExit(
f"source task count mismatch: expected {args.expected_source_tasks}, found {len(upstream)}"
)
local_ids = {path.name for path in tasks.iterdir() if path.is_dir()}
extra_local = sorted(local_ids - upstream.keys())
if extra_local:
raise SystemExit(f"local tasks absent upstream: {extra_local[:10]}")
decisions: list[dict[str, Any]] = []
patches: list[dict[str, Any]] = []
compatible: list[dict[str, Any]] = []
sif_by_source: dict[Path, dict[str, Any]] = {}
for task_id in sorted(upstream):
task = (tasks / task_id).resolve()
missing = [name for name in CORE_FILES if not (task / name).is_file()]
if missing:
decisions.append(
{"task_id": task_id, "decision": "excluded", "reason": "missing_core_files", "missing": missing}
)
continue
current = local_inventory(task)
original = upstream[task_id][1]
all_paths = sorted(set(current) | set(original))
changes = [name for name in all_paths if current.get(name) != original.get(name)]
if changes:
allowed = args.allow_offline_test_patch and changes == ["tests/test.sh"]
marker_present = "patched-offline:" in (task / "tests/test.sh").read_text(errors="replace")
if not allowed or not marker_present:
raise RuntimeError(f"unexpected local changes for {task_id}: {changes}")
patches.append(
{
"task_id": task_id,
"path": "tests/test.sh",
"operation": "neutralize_redundant_network_install_commands",
"source_sha256": original.get("tests/test.sh"),
"release_sha256": current.get("tests/test.sh"),
}
)
dockerfile = task / "environment" / "Dockerfile"
docker_sha = sha256_file(dockerfile)
context_hash = docker_build_context_hash(dockerfile.parent, dockerfile)
sif_source = sif_cache / f"build_{context_hash}.sif"
if not sif_source.is_file():
raise FileNotFoundError(f"missing SIF for {task_id}: {sif_source}")
if sif_source not in sif_by_source:
sif_sha = sha256_file(sif_source)
sif_by_source[sif_source] = {
"source": str(sif_source),
"sha256": sif_sha,
"size": sif_source.stat().st_size,
"path": f"sif-images/{sif_sha[:16]}--{sif_source.name}",
}
tree_text = "".join(f"{name}\0{digest}\n" for name, digest in sorted(current.items()))
compatible.append(
{
"task_id": task_id,
"task_tree_sha256": sha256_text(tree_text),
"dockerfile_sha256": docker_sha,
"docker_build_context_hash": context_hash,
"sif_image": sif_by_source[sif_source]["path"],
"sif_sha256": sif_by_source[sif_source]["sha256"],
}
)
decisions.append({"task_id": task_id, "decision": "accepted", "reason": "runtime_compatible"})
if len(compatible) != args.expected_compatible_tasks:
raise SystemExit(
f"compatible task count mismatch: expected {args.expected_compatible_tasks}, found {len(compatible)}"
)
task_ids = [row["task_id"] for row in compatible]
task_id_text = "".join(f"{task_id}\n" for task_id in task_ids)
overfit_ids = stable_order(task_ids, f"{args.release_id}-overfit-v1")[: args.overfit_count]
overfit = set(overfit_ids)
diagnostic_ids = stable_order(
[task_id for task_id in task_ids if task_id not in overfit],
f"{args.release_id}-diagnostic-v1",
)[: args.diagnostic_count]
diagnostic = set(diagnostic_ids)
try:
for name in ("sif-images", "manifests", "provenance", "scripts", "validation"):
(output / name).mkdir(parents=True, exist_ok=True)
for source, row in sif_by_source.items():
copy_large_file(source, output / row["path"])
for row in compatible:
row["in_overfit_train"] = row["task_id"] in overfit
row["in_diagnostic_validation"] = row["task_id"] in diagnostic
write_jsonl(output / "manifests" / "compatible.jsonl", compatible)
write_jsonl(
output / "manifests" / "task-sif-routing.jsonl",
[{key: row[key] for key in ("task_id", "sif_image", "sif_sha256")} for row in compatible],
)
write_jsonl(output / "manifests" / "source-task-decisions.jsonl", decisions)
write_jsonl(output / "manifests" / "offline-patches.jsonl", patches)
write_jsonl(
output / "manifests" / "overfit-train.jsonl",
[{"task_id": task_id, "rank": rank} for rank, task_id in enumerate(overfit_ids, 1)],
)
write_jsonl(
output / "manifests" / "diagnostic-validation.jsonl",
[{"task_id": task_id, "rank": rank} for rank, task_id in enumerate(diagnostic_ids, 1)],
)
(output / "manifests" / "task-ids.txt").write_text(task_id_text)
write_jsonl(output / "manifests" / "sif-images.jsonl", list(sif_by_source.values()))
schema = pa.schema(
[
("path", pa.string()),
("task_binary", pa.binary()),
("task_id", pa.string()),
("instruction", pa.string()),
("sif_image", pa.string()),
("in_overfit_train", pa.bool_()),
("in_diagnostic_validation", pa.bool_()),
]
)
route_by_task = {row["task_id"]: row for row in compatible}
with pq.ParquetWriter(output / "tasks.parquet", schema, compression="zstd", use_dictionary=False) as writer:
for offset in range(0, len(task_ids), 32):
rows = []
for task_id in task_ids[offset : offset + 32]:
task = (tasks / task_id).resolve()
rows.append(
{
"path": task_id,
"task_binary": deterministic_task_tar(task),
"task_id": task_id,
"instruction": (task / "instruction.md").read_text(errors="replace"),
"sif_image": route_by_task[task_id]["sif_image"],
"in_overfit_train": task_id in overfit,
"in_diagnostic_validation": task_id in diagnostic,
}
)
writer.write_table(pa.Table.from_pylist(rows, schema=schema))
write_tasks_archive(tasks, task_ids, output / "tasks.tar.zst")
provenance = {
"schema_version": 1,
"upstream_repo": args.upstream_repo,
"upstream_revision": args.upstream_revision,
"upstream_subdirectory": args.upstream_subdirectory,
"source_parquet_sha256": sha256_file(source_parquet),
"source_task_count": len(upstream),
"release_task_count": len(task_ids),
"release_task_ids_sha256": sha256_text(task_id_text),
"local_source": str(tasks),
}
(output / "provenance" / "source.json").write_text(
json.dumps(provenance, indent=2, sort_keys=True) + "\n"
)
harbor = runtime_provenance(args.harbor_root, output / "provenance")
validation = {
"schema_version": 1,
"profile": "jupiter-apptainer-1.4.5-aarch64-rootless-offline-v1",
"status": "production_runtime_tested_gate1_provisional",
"task_count": len(task_ids),
"static_source_comparison": "pass",
"missing_core_exclusions": len(upstream) - len(task_ids),
"oracle_available": False,
"oracle_attempts": 0,
"negative_control_scope": "not_complete_all_tasks",
"runtime_evidence": args.runtime_evidence,
"note": args.validation_note,
}
(output / "validation" / "summary.json").write_text(
json.dumps(validation, indent=2, sort_keys=True) + "\n"
)
manifest = {
"schema_version": 1,
"id": args.release_id,
"release_label": args.release_label,
"release_date": args.release_date,
"status": validation["status"],
"publication": {"hf_repo": args.hf_repo, "revision": None},
"license": args.license,
"task_format": "harbor",
"task_count": len(task_ids),
"source_task_count": len(upstream),
"excluded_task_count": len(upstream) - len(task_ids),
"offline_patch_count": len(patches),
"architectures": ["aarch64"],
"sif_image_count": len(sif_by_source),
"sif_image_bytes": sum(row["size"] for row in sif_by_source.values()),
"task_ids_sha256": sha256_text(task_id_text),
"upstream": provenance,
"harbor_runtime": harbor,
"validation": validation,
"splits": {
"compatible": len(task_ids),
"overfit_train": len(overfit_ids),
"diagnostic_validation": len(diagnostic_ids),
},
}
(output / "dataset_manifest.json").write_text(
json.dumps(manifest, indent=2, sort_keys=True) + "\n"
)
write_materializer(output / "scripts" / "materialize_release.py")
shutil.copy2(Path(__file__), output / "scripts" / Path(__file__).name)
if args.license == "apache-2.0" and args.harbor_root:
shutil.copy2(args.harbor_root.resolve() / "LICENSE", output / "LICENSE")
write_readme(
output / "README.md",
args,
len(task_ids),
len(upstream) - len(task_ids),
len(sif_by_source),
manifest["sif_image_bytes"],
len(patches),
)
checksums = []
for path in sorted(item for item in output.rglob("*") if item.is_file()):
if path.name == "SHA256SUMS":
continue
checksums.append(f"{sha256_file(path)} {path.relative_to(output).as_posix()}\n")
(output / "SHA256SUMS").write_text("".join(checksums))
except Exception:
shutil.rmtree(output, ignore_errors=True)
raise
print(json.dumps(manifest, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|