#!/usr/bin/env python3 """Materialize an auditable Endless Terminals dataset for Jupiter Apptainer. The upstream dataset is already Harbor-shaped and ships both Dockerfiles and Apptainer definition files. This derivation deliberately keeps task semantics unchanged and applies only execution-contract fixes: * replace the identical online verifier bootstrap (apt + curl + uvx) with the pytest already present in every task image; * make one synthetic dummy Debian package architecture-independent so it can build on Jupiter aarch64; and * repair one reference solution whose heredoc is followed by an invalid shell operator; and * inventory runtime package/network requirements. Python packages are served from Harbor's bound wheelhouse at runtime, so this script does not modify an image merely to add a Python package. Without ``--apply`` the command audits the source and prints the planned summary. With ``--apply``, ``--output-dir`` must not exist; the source is copied without its Git metadata and deterministic manifests are written under ``metadata/``. """ from __future__ import annotations import argparse import hashlib import json import re import shlex import shutil import stat import subprocess import tempfile from collections import Counter from pathlib import Path from urllib.parse import urlparse UPSTREAM_REPO = "obiwan96/endless-terminals" UPSTREAM_REVISION = "26ecf78458e7f756e4d06780d5fbf3dd78e91815" EXPECTED_TASK_COUNT = 2492 EXPECTED_TEST_SH_SHA256 = ( "52d87e5cb768634d6a7bda203b72ea77c802fdb9e8700d3d7cdcf631080c3298" ) VERIFIER_PATCH_ID = "offline-verifier-system-pytest-isolated-v2" ARM_PATCH_ID = "dummy-deb-architecture-all-v1" ARM_PATCH_TASK = "task_000000_c6317e51" ORACLE_SYNTAX_PATCH_ID = "oracle-heredoc-chain-syntax-v1" ORACLE_SYNTAX_PATCH_TASK = "task_000000_15619148" REQUIRED_TASK_FILES = ( "task.toml", "instruction.md", "environment/Dockerfile", "environment/container.def", "environment/test_initial_state.py", "tests/test.sh", "tests/test_final_state.py", "solution/solve.sh", ) OFFLINE_TEST_SH = """#!/usr/bin/env bash # harbor-endless-offline-patched-v1 set +e mkdir -p /logs/verifier cd /home/user || { echo 0 > /logs/verifier/reward.txt exit 0 } # pytest is already installed in every upstream task image. Runtime package # installs performed by the task use Harbor's read-only wheelhouse through # PIP_NO_INDEX/PIP_FIND_LINKS; grading itself performs no download or install. # Remove the image's verifier-only PYTHONPATH while grading so subprocesses # that inspect a task-created virtualenv cannot see /opt/harbor-python as if # those packages had been installed inside the virtualenv. env -u PYTHONPATH python3 -m pytest /tests/test_final_state.py -v status=$? if [ "$status" -eq 0 ]; then echo 1 > /logs/verifier/reward.txt else echo 0 > /logs/verifier/reward.txt fi exit 0 """ ARM_REPLACEMENTS = ( ("Architecture: amd64", "Architecture: all"), ("curl_7.74.0-1ubuntu2.18_amd64.deb", "curl_7.74.0-1ubuntu2.18_all.deb"), ) PIP_INSTALL_RE = re.compile( r"(?:(?:python\S*|/[^\s;&|]+/python\S*)\s+-m\s+)?" r"(?:pip3?|/[^\s;&|]+/pip)\s+install\s+([^\n;&|]+)", re.IGNORECASE, ) OS_INSTALL_RE = re.compile( r"\b(?:apt-get|apt|yum|dnf|apk)\s+(?:install|add)\b", re.IGNORECASE ) RAW_NETWORK_RE = re.compile( r"\b(?:ping|traceroute|tracepath)\b", re.IGNORECASE ) SERVICE_RE = re.compile(r"\b(?:systemctl|service\s+\S+)\b", re.IGNORECASE) SUDO_RE = re.compile(r"\bsudo\b", re.IGNORECASE) URL_RE = re.compile(r"https?://[^\s\"'<>|)]+", re.IGNORECASE) LOCAL_HOSTS = {"localhost", "127.0.0.1", "0.0.0.0"} PIP_OPTIONS_WITH_VALUE = { "-c", "--constraint", "-e", "--editable", "-f", "--find-links", "-i", "--index-url", "--extra-index-url", "--proxy", "--root", "--target", "--timeout", "--trusted-host", } LITERAL_REQUIREMENT_RE = re.compile( r"^[A-Za-z0-9][A-Za-z0-9._-]*" r"(?:\[[A-Za-z0-9._,-]+\])?" r"(?:(?:===|==|~=|!=|<=|>=|<|>)[^\s]+)?$" ) def sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for block in iter(lambda: stream.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def git_revision(path: Path) -> str | None: try: return subprocess.check_output( ["git", "-C", str(path), "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL, ).strip() except (OSError, subprocess.CalledProcessError): return None def task_dirs(root: Path) -> list[Path]: return sorted(path for path in root.glob("task_*") if path.is_dir()) def validate_source(source: Path, allow_unpinned_source: bool) -> list[Path]: tasks = task_dirs(source) if len(tasks) != EXPECTED_TASK_COUNT: raise ValueError( f"Expected {EXPECTED_TASK_COUNT} tasks at pinned upstream revision; " f"found {len(tasks)}" ) revision = git_revision(source) if not allow_unpinned_source and revision != UPSTREAM_REVISION: raise ValueError( "Source Git revision does not match the pinned upstream revision: " f"expected {UPSTREAM_REVISION}, got {revision!r}. Pass " "--allow-unpinned-source only for an explicitly reviewed materialization." ) failures: list[str] = [] for task in tasks: for relative in REQUIRED_TASK_FILES: if not (task / relative).is_file(): failures.append(f"{task.name}/{relative}") if failures: preview = ", ".join(failures[:20]) raise ValueError(f"Missing {len(failures)} required task files: {preview}") bad_verifiers = [ task.name for task in tasks if sha256_file(task / "tests/test.sh") != EXPECTED_TEST_SH_SHA256 ] if bad_verifiers: raise ValueError( f"Refusing to rewrite {len(bad_verifiers)} unrecognized test.sh files: " + ", ".join(bad_verifiers[:20]) ) return tasks def extract_python_requirements(script: str) -> tuple[list[str], bool]: """Return literal pip requirements and whether dynamic inputs remain.""" requirements: set[str] = set() dynamic = False for match in PIP_INSTALL_RE.finditer(script): try: tokens = shlex.split(match.group(1), comments=False, posix=True) except ValueError: dynamic = True continue index = 0 while index < len(tokens): token = tokens[index] if token in {"-r", "--requirement"}: dynamic = True index += 2 continue if token in PIP_OPTIONS_WITH_VALUE: index += 2 continue if token.startswith("-"): index += 1 continue if ( any(char in token for char in ("$", "`", "*")) or token.startswith(("/", ".", ">")) or not LITERAL_REQUIREMENT_RE.fullmatch(token) ): dynamic = True index += 1 continue if token in {"then", "fi", "do", "done"}: break requirements.add(token) index += 1 return sorted(requirements, key=str.lower), dynamic def external_url_hosts(script: str) -> list[str]: hosts: set[str] = set() for raw in URL_RE.findall(script): host = urlparse(raw.rstrip(".,;")).hostname if host and host not in LOCAL_HOSTS and not host.startswith("$"): hosts.add(host) return sorted(hosts) def analyze_task(task: Path) -> dict[str, object]: solution = (task / "solution/solve.sh").read_text(errors="replace") requirements, dynamic = extract_python_requirements(solution) hosts = external_url_hosts(solution) return { "runtime_python_install": bool(PIP_INSTALL_RE.search(solution)), "runtime_python_requirements": requirements, "runtime_python_dynamic_requirements": dynamic, "runtime_os_package_install": bool(OS_INSTALL_RE.search(solution)), "external_url_hosts": hosts, "raw_network_candidate": bool(RAW_NETWORK_RE.search(solution)), "service_manager_candidate": bool(SERVICE_RE.search(solution)), "sudo_in_oracle": bool(SUDO_RE.search(solution)), } def tree_hash(task: Path) -> str: digest = hashlib.sha256() for path in sorted(candidate for candidate in task.rglob("*") if candidate.is_file()): relative = path.relative_to(task).as_posix() digest.update(relative.encode()) digest.update(b"\0") digest.update(bytes.fromhex(sha256_file(path))) digest.update(b"\n") return digest.hexdigest() def patch_file( path: Path, new_content: str, patch_id: str, reason: str, records: list[dict[str, object]], *, executable: bool = False, ) -> None: old = path.read_bytes() old_mode = stat.S_IMODE(path.stat().st_mode) encoded = new_content.encode() path.write_bytes(encoded) if executable: path.chmod(0o755) new_mode = stat.S_IMODE(path.stat().st_mode) records.append( { "task": path.parents[1].name, "path": path.relative_to(path.parents[1]).as_posix(), "patch_id": patch_id, "reason": reason, "before_sha256": sha256_bytes(old), "after_sha256": sha256_bytes(encoded), "before_mode": oct(old_mode), "after_mode": oct(new_mode), } ) def apply_patches(root: Path) -> list[dict[str, object]]: records: list[dict[str, object]] = [] for task in task_dirs(root): patch_file( task / "tests/test.sh", OFFLINE_TEST_SH, VERIFIER_PATCH_ID, "Use image-provided pytest; remove verifier-time apt, curl, uv, and uvx downloads.", records, executable=True, ) arm_task = root / ARM_PATCH_TASK for relative in ("environment/Dockerfile", "environment/container.def"): path = arm_task / relative content = path.read_text() patched = content for old, new in ARM_REPLACEMENTS: patched = patched.replace(old, new) if patched == content: raise ValueError(f"Expected ARM compatibility substitutions not found in {path}") patch_file( path, patched, ARM_PATCH_ID, "The dummy package contains no architecture-specific payload; mark it Architecture: all for aarch64 builds.", records, ) oracle_path = root / ORACLE_SYNTAX_PATCH_TASK / "solution/solve.sh" oracle_content = oracle_path.read_text() oracle_patched = oracle_content.replace( "PY\n && cat /home/user/work/output/orders_report.csv", "PY\ncat /home/user/work/output/orders_report.csv", ) if oracle_patched == oracle_content: raise ValueError(f"Expected oracle syntax substitution not found in {oracle_path}") patch_file( oracle_path, oracle_patched, ORACLE_SYNTAX_PATCH_ID, "Remove an invalid shell operator after a heredoc; task output and grading remain unchanged.", records, executable=True, ) return records def relative_files(root: Path, *, exclude_git: bool = False) -> set[Path]: files: set[Path] = set() for path in root.rglob("*"): if not path.is_file(): continue relative = path.relative_to(root) if exclude_git and relative.parts[0] == ".git": continue if relative.parts[0] == "metadata": continue files.add(relative) return files def validate_materialization( source: Path, output: Path, patch_records: list[dict[str, object]], ) -> dict[str, object]: """Prove that only the declared execution-contract files changed.""" expected_changes = { Path(task.name) / "tests/test.sh" for task in task_dirs(source) } expected_changes.update( { Path(ARM_PATCH_TASK) / "environment/Dockerfile", Path(ARM_PATCH_TASK) / "environment/container.def", Path(ORACLE_SYNTAX_PATCH_TASK) / "solution/solve.sh", } ) source_files = relative_files(source, exclude_git=True) output_files = relative_files(output) if source_files != output_files: missing = sorted(str(path) for path in source_files - output_files) extra = sorted(str(path) for path in output_files - source_files) raise ValueError( "Materialized file set differs from source outside metadata: " f"missing={missing[:10]}, extra={extra[:10]}" ) changed: set[Path] = set() for relative in sorted(source_files): if sha256_file(source / relative) != sha256_file(output / relative): changed.add(relative) if changed != expected_changes: unexpected = sorted(str(path) for path in changed - expected_changes) absent = sorted(str(path) for path in expected_changes - changed) raise ValueError( "Materialized content changes do not match the patch contract: " f"unexpected={unexpected[:10]}, absent={absent[:10]}" ) if len(patch_records) != len(expected_changes): raise ValueError( f"Expected {len(expected_changes)} patch records, got {len(patch_records)}" ) offline_sha = sha256_bytes(OFFLINE_TEST_SH.encode()) for task in task_dirs(output): verifier = task / "tests/test.sh" if sha256_file(verifier) != offline_sha or not (verifier.stat().st_mode & 0o111): raise ValueError(f"Offline verifier validation failed: {verifier}") return { "status": "passed", "source_file_count": len(source_files), "declared_changed_file_count": len(changed), "unchanged_file_count": len(source_files) - len(changed), } def copy_source(source: Path, output: Path) -> None: if output.exists(): raise FileExistsError(f"Refusing to replace existing output directory: {output}") output.parent.mkdir(parents=True, exist_ok=True) staging = Path( tempfile.mkdtemp(prefix=f".{output.name}.tmp-", dir=str(output.parent)) ) try: for child in source.iterdir(): if child.name == ".git": continue target = staging / child.name if child.is_dir(): shutil.copytree(child, target, copy_function=shutil.copy2) else: shutil.copy2(child, target) staging.rename(output) except Exception: shutil.rmtree(staging, ignore_errors=True) raise def write_json(path: Path, value: object) -> None: path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") def write_jsonl(path: Path, rows: list[dict[str, object]]) -> None: with path.open("w") as stream: for row in rows: stream.write(json.dumps(row, sort_keys=True) + "\n") def materialize_metadata( output: Path, patch_records: list[dict[str, object]], validation: dict[str, object], ) -> dict[str, object]: metadata = output / "metadata" metadata.mkdir() tasks_rows: list[dict[str, object]] = [] requirements: set[str] = set() risk_counts: Counter[str] = Counter() for task in task_dirs(output): analysis = analyze_task(task) for requirement in analysis["runtime_python_requirements"]: requirements.add(str(requirement)) for key in ( "runtime_python_install", "runtime_python_dynamic_requirements", "runtime_os_package_install", "raw_network_candidate", "service_manager_candidate", "sudo_in_oracle", ): if analysis[key]: risk_counts[key] += 1 if analysis["external_url_hosts"]: risk_counts["external_url_reference"] += 1 tasks_rows.append( { "task": task.name, "tree_sha256": tree_hash(task), "patch_ids": [ VERIFIER_PATCH_ID, *([ARM_PATCH_ID] if task.name == ARM_PATCH_TASK else []), *( [ORACLE_SYNTAX_PATCH_ID] if task.name == ORACLE_SYNTAX_PATCH_TASK else [] ), ], **analysis, } ) write_jsonl(metadata / "tasks.jsonl", tasks_rows) write_jsonl(metadata / "patches.jsonl", patch_records) (metadata / "runtime-python-requirements.txt").write_text( "\n".join(sorted(requirements, key=str.lower)) + ("\n" if requirements else "") ) patch_definitions = { "schema_version": 1, "patches": [ { "id": VERIFIER_PATCH_ID, "scope": "all tasks", "expected_before_sha256": EXPECTED_TEST_SH_SHA256, "after_sha256": sha256_bytes(OFFLINE_TEST_SH.encode()), "semantics": "Reward and final-state tests unchanged; only dependency acquisition is removed.", }, { "id": ARM_PATCH_ID, "scope": ARM_PATCH_TASK, "replacements": [list(item) for item in ARM_REPLACEMENTS], "semantics": "Dummy package payload and tested version remain unchanged.", }, { "id": ORACLE_SYNTAX_PATCH_ID, "scope": ORACLE_SYNTAX_PATCH_TASK, "replacement": [ "PY\\n && cat /home/user/work/output/orders_report.csv", "PY\\ncat /home/user/work/output/orders_report.csv", ], "semantics": "Fix shell parsing only; generated report and final-state tests are unchanged.", }, ], } write_json(metadata / "patch-definitions.json", patch_definitions) provenance = { "schema_version": 1, "kind": "derived_dataset_provenance", "upstream_repo": UPSTREAM_REPO, "upstream_revision": UPSTREAM_REVISION, "task_count": len(tasks_rows), "execution_profiles": [ "jupiter-aarch64-rootless-apptainer-wheelhouse-v1", "jupiter-aarch64-rootless-apptainer-proxy-v1", ], } write_json(metadata / "provenance.json", provenance) summary: dict[str, object] = { "schema_version": 1, "kind": "endless_terminals_offline_patch_summary", "upstream_repo": UPSTREAM_REPO, "upstream_revision": UPSTREAM_REVISION, "task_count": len(tasks_rows), "patched_verifiers": sum( record["patch_id"] == VERIFIER_PATCH_ID for record in patch_records ), "patched_environment_files": sum( record["patch_id"] == ARM_PATCH_ID for record in patch_records ), "patched_oracle_files": sum( record["patch_id"] == ORACLE_SYNTAX_PATCH_ID for record in patch_records ), "unique_runtime_python_requirements": len(requirements), "risk_counts": dict(sorted(risk_counts.items())), "validation": validation, } write_json(metadata / "summary.json", summary) checksummed = [ metadata / "patch-definitions.json", metadata / "patches.jsonl", metadata / "provenance.json", metadata / "runtime-python-requirements.txt", metadata / "summary.json", metadata / "tasks.jsonl", ] with (metadata / "SHA256SUMS").open("w") as stream: for path in checksummed: stream.write(f"{sha256_file(path)} {path.name}\n") return summary def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path) parser.add_argument("--output-dir", type=Path) parser.add_argument("--apply", action="store_true") parser.add_argument( "--allow-unpinned-source", action="store_true", help="Accept a source without the pinned Git revision (recorded as a deviation).", ) return parser.parse_args() def main() -> int: args = parse_args() source = args.source.expanduser().resolve() if not source.is_dir(): raise SystemExit(f"Source directory does not exist: {source}") try: tasks = validate_source(source, args.allow_unpinned_source) except (OSError, ValueError) as error: raise SystemExit(f"Invalid source: {error}") from error analyses = [analyze_task(task) for task in tasks] planned = { "mode": "apply" if args.apply else "dry-run", "upstream_revision": git_revision(source), "tasks": len(tasks), "verifiers_to_patch": len(tasks), "environment_files_to_patch": 2, "oracle_files_to_patch": 1, "runtime_python_install_tasks": sum( bool(row["runtime_python_install"]) for row in analyses ), "runtime_os_package_install_tasks": sum( bool(row["runtime_os_package_install"]) for row in analyses ), "external_url_reference_tasks": sum( bool(row["external_url_hosts"]) for row in analyses ), "raw_network_candidate_tasks": sum( bool(row["raw_network_candidate"]) for row in analyses ), } print(json.dumps(planned, indent=2, sort_keys=True)) if not args.apply: return 0 if args.output_dir is None: raise SystemExit("--output-dir is required with --apply") output = args.output_dir.expanduser().resolve() copy_source(source, output) patch_records = apply_patches(output) validation = validate_materialization(source, output, patch_records) summary = materialize_metadata(output, patch_records, validation) print(json.dumps(summary, indent=2, sort_keys=True)) print(f"output={output}") return 0 if __name__ == "__main__": raise SystemExit(main())