Download scripts/package_harbor_runtime_release.py from laion/inferredbugs-rootless-apptainer: direct link, hf CLI and curl.
- Browser
- Download file 23 kB
-
https://huggingface.co/datasets/laion/inferredbugs-rootless-apptainer/resolve/main/scripts/package_harbor_runtime_release.py
- Command line
-
hf download hf://datasets/laion/inferredbugs-rootless-apptainer/scripts/package_harbor_runtime_release.py
-
curl -L -o package_harbor_runtime_release.py https://huggingface.co/datasets/laion/inferredbugs-rootless-apptainer/resolve/main/scripts/package_harbor_runtime_release.py
23 kB
| #!/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()) | |