Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
338 changes: 172 additions & 166 deletions src/repo2rlenv/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import json
import logging
import os
import shutil
from dataclasses import dataclass
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -466,139 +475,134 @@ def push_to_hub(
# Layout we expect locally: <root>/<task-id>/...
# We'll re-stage it as <root>/tasks/<task-id>/...
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/<id> 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/<id> 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(
Expand Down Expand Up @@ -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)

Expand All @@ -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/<id>/` → `<local_dir>/<id>/`
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/<id>/` → `<local_dir>/<id>/`
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(
Expand Down
Loading