From c35ce0d0c718b4b7c0f8d6a8c0b1cc8c3b384c10 Mon Sep 17 00:00:00 2001 From: sama Pyb Date: Tue, 1 Dec 2026 18:45:57 +0800 Subject: [PATCH] hub: reset and clean staging and snapshot scratch directories --- src/repo2rlenv/hub.py | 338 ++++++++++++++++---------------- tests/test_hub_metadata_read.py | 113 ++++++++++- 2 files changed, 284 insertions(+), 167 deletions(-) diff --git a/src/repo2rlenv/hub.py b/src/repo2rlenv/hub.py index 8f3b184e..d237271d 100644 --- a/src/repo2rlenv/hub.py +++ b/src/repo2rlenv/hub.py @@ -30,6 +30,7 @@ import json import logging import os +import shutil from dataclasses import dataclass from pathlib import Path from typing import Any @@ -385,6 +386,14 @@ def _build_dataset_card( """ +def _remove_scratch_path(path: Path) -> None: + """Remove a scratch directory, file, or symlink if present.""" + if path.is_symlink() or path.is_file(): + path.unlink() + elif path.exists(): + shutil.rmtree(path) + + def _read_task_metadata(task_toml: Path) -> dict[str, Any]: """Extract `[metadata.repo2env]` from a task.toml. Empty dict on parse failure.""" import tomllib @@ -466,139 +475,134 @@ def push_to_hub( # Layout we expect locally: //... # We'll re-stage it as /tasks//... staging = local_dataset_dir / ".r2e_staging" - staging.mkdir(exist_ok=True) - tasks_dir = staging / "tasks" - tasks_dir.mkdir(exist_ok=True) - - task_names = [] - first_metadata: dict[str, Any] = {} - source_repos: set[str] = set() - has_environment = False - for child in _list_task_dirs(local_dataset_dir): - toml_path = child / "task.toml" - meta = _read_task_metadata(toml_path) - if not first_metadata: - first_metadata = meta - if r := meta.get("repo"): - source_repos.add(r) - if (child / "environment" / "Dockerfile").exists(): - has_environment = True - target = tasks_dir / child.name - if target.exists(): - import shutil + _remove_scratch_path(staging) + staging.mkdir() + try: + tasks_dir = staging / "tasks" + tasks_dir.mkdir() + + task_names = [] + first_metadata: dict[str, Any] = {} + source_repos: set[str] = set() + has_environment = False + for child in _list_task_dirs(local_dataset_dir): + toml_path = child / "task.toml" + meta = _read_task_metadata(toml_path) + if not first_metadata: + first_metadata = meta + if r := meta.get("repo"): + source_repos.add(r) + if (child / "environment" / "Dockerfile").exists(): + has_environment = True + target = tasks_dir / child.name + if target.exists(): + shutil.rmtree(target) + shutil.copytree(child, target) + task_names.append(child.name) + + if not task_names: + raise RuntimeError(f"no Harbor tasks found in {local_dataset_dir}") + + # Pull authoritative values from the first task's [metadata.repo2env]. + # Caller-supplied overrides win (back-compat for legacy callers). + if not pipeline: + pipeline = first_metadata.get("pipeline", "pr_diff") + if not repo_source: + repo_source = first_metadata.get("repo", "") + + # Write manifest.json — a machine-checkable per-task composition record + # (repo, PR, base commit, F2P/P2P counts, difficulty, reward kind). Built + # from the staged task.toml files so every published dataset carries it. + # Top-level file → survives the tasks/** clean-sync on re-push. + # + # Exception: if the source dir already carries an *enriched* manifest (one + # with a `validation` block — e.g. stamped launch-side after an oracle gate + # with per-task build/oracle status + checksums), preserve it verbatim. + # `push` can't run an oracle, so it must not clobber validation provenance. + src_manifest = local_dataset_dir / "manifest.json" + enriched = False + if src_manifest.exists(): + try: + enriched = "validation" in json.loads(src_manifest.read_text(encoding="utf-8")) + except (OSError, ValueError): + enriched = False + manifest_summary: dict[str, Any] | None = None + if enriched: + manifest_text = src_manifest.read_text(encoding="utf-8") + (staging / "manifest.json").write_text(manifest_text, encoding="utf-8") + logger.info("preserving enriched manifest.json (has validation block)") + try: + m = json.loads(manifest_text) + manifest_summary = { + "task_count": m.get("task_count"), + "validation": m.get("validation", {}), + "repo_distribution": m.get("repo_distribution", {}), + } + except (OSError, ValueError): + manifest_summary = None + else: + (staging / "manifest.json").write_text( + _build_manifest(tasks_dir, repo_id=repo_id, pipeline=pipeline or "pr_diff"), + encoding="utf-8", + ) - shutil.rmtree(target) - import shutil as _sh - - _sh.copytree(child, target) - task_names.append(child.name) - - if not task_names: - raise RuntimeError(f"no Harbor tasks found in {local_dataset_dir}") - - # Pull authoritative values from the first task's [metadata.repo2env]. - # Caller-supplied overrides win (back-compat for legacy callers). - if not pipeline: - pipeline = first_metadata.get("pipeline", "pr_diff") - if not repo_source: - repo_source = first_metadata.get("repo", "") - - # Write manifest.json — a machine-checkable per-task composition record - # (repo, PR, base commit, F2P/P2P counts, difficulty, reward kind). Built - # from the staged task.toml files so every published dataset carries it. - # Top-level file → survives the tasks/** clean-sync on re-push. - # - # Exception: if the source dir already carries an *enriched* manifest (one - # with a `validation` block — e.g. stamped launch-side after an oracle gate - # with per-task build/oracle status + checksums), preserve it verbatim. - # `push` can't run an oracle, so it must not clobber validation provenance. - src_manifest = local_dataset_dir / "manifest.json" - enriched = False - if src_manifest.exists(): - try: - enriched = "validation" in json.loads(src_manifest.read_text(encoding="utf-8")) - except (OSError, ValueError): - enriched = False - manifest_summary: dict[str, Any] | None = None - if enriched: - manifest_text = src_manifest.read_text(encoding="utf-8") - (staging / "manifest.json").write_text(manifest_text, encoding="utf-8") - logger.info("preserving enriched manifest.json (has validation block)") - try: - m = json.loads(manifest_text) - manifest_summary = { - "task_count": m.get("task_count"), - "validation": m.get("validation", {}), - "repo_distribution": m.get("repo_distribution", {}), - } - except (OSError, ValueError): - manifest_summary = None - else: - (staging / "manifest.json").write_text( - _build_manifest(tasks_dir, repo_id=repo_id, pipeline=pipeline or "pr_diff"), + # Write README.md (dataset card) + dataset_name = repo_id.split("/")[-1] + (staging / "README.md").write_text( + _build_dataset_card( + repo_id=repo_id, + dataset_name=dataset_name, + task_count=len(task_names), + repo_source=repo_source, + pipeline=pipeline, + visibility="private" if private else "public", + source_repos=sorted(source_repos), + has_environment=has_environment, + manifest_summary=manifest_summary, + ), encoding="utf-8", ) - # Write README.md (dataset card) - dataset_name = repo_id.split("/")[-1] - (staging / "README.md").write_text( - _build_dataset_card( + # First upload — without registry.json (we need the commit SHA first) + logger.info("uploading %d tasks to %s", len(task_names), repo_id) + op = api.upload_folder( + folder_path=str(staging), repo_id=repo_id, - dataset_name=dataset_name, - task_count=len(task_names), - repo_source=repo_source, - pipeline=pipeline, - visibility="private" if private else "public", - source_repos=sorted(source_repos), - has_environment=has_environment, - manifest_summary=manifest_summary, - ), - encoding="utf-8", - ) - - # First upload — without registry.json (we need the commit SHA first) - logger.info("uploading %d tasks to %s", len(task_names), repo_id) - op = api.upload_folder( - folder_path=str(staging), - repo_id=repo_id, - repo_type="dataset", - commit_message=commit_message or f"Repo2RLEnv: add {len(task_names)} tasks", - # Clean-sync the task tree: prune remote tasks/ dirs that aren't in - # this push, so removing a task locally (e.g. dropping a low-quality - # one) actually removes it from the Hub. Without this, re-pushes only - # add/update and stale tasks linger. Scoped to tasks/** so it never - # touches README.md / registry.json. - delete_patterns=["tasks/**"], - ) - commit_sha = ( - op.oid - if hasattr(op, "oid") - else api.list_repo_commits(repo_id, repo_type="dataset")[0].commit_id - ) - - # Now write registry.json that pins the commit SHA we just got - registry = _build_registry_json( - repo_id=repo_id, - commit_sha=commit_sha, - dataset_name=dataset_name, - description=description or f"Repo2RLEnv {pipeline} from {repo_source}", - task_dirs=task_names, - ) - registry_path = staging / "registry.json" - registry_path.write_text(json.dumps(registry, indent=2), encoding="utf-8") - - api.upload_file( - path_or_fileobj=str(registry_path), - path_in_repo="registry.json", - repo_id=repo_id, - repo_type="dataset", - commit_message="Add registry.json pinned to previous commit", - ) + repo_type="dataset", + commit_message=commit_message or f"Repo2RLEnv: add {len(task_names)} tasks", + # Clean-sync the task tree: prune remote tasks/ dirs that aren't in + # this push, so removing a task locally (e.g. dropping a low-quality + # one) actually removes it from the Hub. Without this, re-pushes only + # add/update and stale tasks linger. Scoped to tasks/** so it never + # touches README.md / registry.json. + delete_patterns=["tasks/**"], + ) + commit_sha = ( + op.oid + if hasattr(op, "oid") + else api.list_repo_commits(repo_id, repo_type="dataset")[0].commit_id + ) - # Cleanup staging - import shutil + # Now write registry.json that pins the commit SHA we just got + registry = _build_registry_json( + repo_id=repo_id, + commit_sha=commit_sha, + dataset_name=dataset_name, + description=description or f"Repo2RLEnv {pipeline} from {repo_source}", + task_dirs=task_names, + ) + registry_path = staging / "registry.json" + registry_path.write_text(json.dumps(registry, indent=2), encoding="utf-8") - shutil.rmtree(staging) + api.upload_file( + path_or_fileobj=str(registry_path), + path_in_repo="registry.json", + repo_id=repo_id, + repo_type="dataset", + commit_message="Add registry.json pinned to previous commit", + ) + finally: + shutil.rmtree(staging, ignore_errors=True) registry_url = f"https://huggingface.co/datasets/{repo_id}/resolve/main/registry.json" return PushResult( @@ -642,8 +646,6 @@ def pull_from_hub( # token is optional for public datasets; pass-through if present if force and local_dir.exists(): - import shutil - shutil.rmtree(local_dir) local_dir.mkdir(parents=True, exist_ok=True) @@ -657,48 +659,52 @@ def pull_from_hub( "README.md", ] - snapshot = Path( - snapshot_download( - repo_id=repo_id, - repo_type="dataset", - token=token, - local_dir=str(local_dir / ".r2e_snapshot"), - allow_patterns=allow_patterns, - revision=revision, - ) - ) + snapshot_dir = local_dir / ".r2e_snapshot" + _remove_scratch_path(snapshot_dir) - # Flatten staged `tasks//` → `//` - staged_tasks = snapshot / "tasks" - if not staged_tasks.exists(): - raise RuntimeError( - f"{repo_id} doesn't look like a Repo2RLEnv dataset " - f"(no `tasks/` subdir under {snapshot})" + snapshot: Path | None = None + try: + snapshot = Path( + snapshot_download( + repo_id=repo_id, + repo_type="dataset", + token=token, + local_dir=str(snapshot_dir), + allow_patterns=allow_patterns, + revision=revision, + ) ) - import shutil - - task_count = 0 - for child in sorted(staged_tasks.iterdir()): - if not child.is_dir(): - continue - if not (child / "task.toml").exists(): - continue - target = local_dir / child.name - if target.exists(): - shutil.rmtree(target) - shutil.copytree(child, target) - task_count += 1 - - # Also surface the registry.json + README.md at the dataset root so the - # local layout matches what `push_to_hub` originally staged. - for top in ("registry.json", "README.md"): - src = snapshot / top - if src.exists(): - shutil.copyfile(src, local_dir / top) + # Flatten staged `tasks//` → `//` + staged_tasks = snapshot / "tasks" + if not staged_tasks.exists(): + raise RuntimeError( + f"{repo_id} doesn't look like a Repo2RLEnv dataset " + f"(no `tasks/` subdir under {snapshot})" + ) - # Clean up the snapshot scratch dir - shutil.rmtree(snapshot, ignore_errors=True) + task_count = 0 + for child in sorted(staged_tasks.iterdir()): + if not child.is_dir(): + continue + if not (child / "task.toml").exists(): + continue + target = local_dir / child.name + if target.exists(): + shutil.rmtree(target) + shutil.copytree(child, target) + task_count += 1 + + # Also surface the registry.json + README.md at the dataset root so the + # local layout matches what `push_to_hub` originally staged. + for top in ("registry.json", "README.md"): + src = snapshot / top + if src.exists(): + shutil.copyfile(src, local_dir / top) + finally: + if snapshot is not None and snapshot != snapshot_dir: + shutil.rmtree(snapshot, ignore_errors=True) + shutil.rmtree(snapshot_dir, ignore_errors=True) if task_count == 0: raise RuntimeError( diff --git a/tests/test_hub_metadata_read.py b/tests/test_hub_metadata_read.py index 32f21e65..cc6e9af2 100644 --- a/tests/test_hub_metadata_read.py +++ b/tests/test_hub_metadata_read.py @@ -13,7 +13,7 @@ import pytest -from repo2rlenv.hub import _read_task_metadata, push_to_hub +from repo2rlenv.hub import _read_task_metadata, pull_from_hub, push_to_hub from repo2rlenv.spec.input import AuthSpec @@ -314,3 +314,114 @@ def upload_file(self, *a, **k): ... assert "validation" in m and m["validation"]["command_resolved"] == 1 # preserved assert m["tasks"][0]["title"] == title assert "Validation & composition" in uploaded["readme"] # card reflects it + + +def test_push_discards_stale_staging_tasks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A leftover .r2e_staging dir from an interrupted push must not leak deleted tasks.""" + import json + + _make_task(tmp_path, pipeline="pr_runtime", repo="o/r", name="current-task") + stale_tasks = tmp_path / ".r2e_staging" / "tasks" + stale_tasks.mkdir(parents=True) + _make_task(stale_tasks, pipeline="pr_runtime", repo="o/r", name="deleted-task") + + monkeypatch.setattr("repo2rlenv.hub.resolve_hf_token", lambda _auth: "fake-token") + observed: dict[str, object] = {} + + class _Api: + def create_repo(self, *a, **k): ... + + def upload_folder(self, *, folder_path, **k): + staging = Path(folder_path) + observed["staged_tasks"] = sorted(p.name for p in (staging / "tasks").iterdir()) + observed["manifest"] = json.loads( + (staging / "manifest.json").read_text(encoding="utf-8") + ) + + class _Op: + oid = "deadbeef" + + return _Op() + + def upload_file(self, *a, **k): ... + + monkeypatch.setattr("huggingface_hub.HfApi", lambda token=None: _Api()) + + result = push_to_hub(tmp_path, "owner/ds", AuthSpec()) + + assert result.task_count == 1 + assert observed["staged_tasks"] == ["current-task"] + manifest = observed["manifest"] + assert isinstance(manifest, dict) + assert [row["task_id"] for row in manifest["tasks"]] == ["current-task"] + assert not (tmp_path / ".r2e_staging").exists() + + +def test_push_cleans_staging_on_upload_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Upload errors must not leave .r2e_staging behind in the dataset directory.""" + _make_task(tmp_path, pipeline="pr_runtime", repo="o/r") + monkeypatch.setattr("repo2rlenv.hub.resolve_hf_token", lambda _auth: "fake-token") + + class _FailingApi: + def create_repo(self, *a, **k): ... + + def upload_folder(self, *a, **k): + raise RuntimeError("upload failed") + + monkeypatch.setattr("huggingface_hub.HfApi", lambda token=None: _FailingApi()) + + with pytest.raises(RuntimeError, match="upload failed"): + push_to_hub(tmp_path, "owner/ds", AuthSpec()) + + assert not (tmp_path / ".r2e_staging").exists() + + +def test_pull_discards_stale_snapshot_tasks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A leftover .r2e_snapshot dir must not leak stale tasks into a fresh pull.""" + local_dir = tmp_path / "out" + stale_tasks = local_dir / ".r2e_snapshot" / "tasks" + stale_tasks.mkdir(parents=True) + _make_task(stale_tasks, pipeline="pr_runtime", repo="o/r", name="stale-task") + + monkeypatch.setattr("repo2rlenv.hub.resolve_hf_token", lambda _auth: "fake-token") + + def fake_snapshot_download(*, local_dir: str, **_kwargs): + snap = Path(local_dir) + tasks = snap / "tasks" + tasks.mkdir(parents=True, exist_ok=True) + _make_task(tasks, pipeline="pr_runtime", repo="o/r", name="fresh-task") + return str(snap) + + monkeypatch.setattr("huggingface_hub.snapshot_download", fake_snapshot_download) + + result = pull_from_hub("owner/ds", local_dir, task="fresh-task") + + assert result.task_count == 1 + assert (local_dir / "fresh-task" / "task.toml").is_file() + assert not (local_dir / "stale-task").exists() + assert not (local_dir / ".r2e_snapshot").exists() + + +def test_pull_cleans_snapshot_on_invalid_layout( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Missing tasks/ in the downloaded snapshot must still clean up .r2e_snapshot.""" + local_dir = tmp_path / "out" + monkeypatch.setattr("repo2rlenv.hub.resolve_hf_token", lambda _auth: "fake-token") + + def fake_snapshot_download(*, local_dir: str, **_kwargs): + snap = Path(local_dir) + snap.mkdir(parents=True, exist_ok=True) + (snap / "README.md").write_text("empty", encoding="utf-8") + return str(snap) + + monkeypatch.setattr("huggingface_hub.snapshot_download", fake_snapshot_download) + + with pytest.raises(RuntimeError, match="no `tasks/` subdir"): + pull_from_hub("owner/ds", local_dir) + + assert not (local_dir / ".r2e_snapshot").exists()