openswe-harbor / convert_openswe.py
ritvik-sarvam's picture
Add files using upload-large-folder tool
c962b98 verified
"""Convert GAIR/OpenSWE → Harbor task dataset + NeMo Gym routing JSONL.
Layout produced (relative to --output-dir):
routing/
openswe_oss.jsonl NeMo Gym routing rows (all 36,884)
openswe_other.jsonl NeMo Gym routing rows (all 8,436)
openswe_oss_filtered.jsonl quality-filtered subset
openswe_other_filtered.jsonl quality-filtered subset
tasks/
openswe_oss/<instance_id>/
instruction.md
task.toml
environment/Dockerfile
solution/solve.sh
tests/test.sh
openswe_other/<instance_id>/
... (same shape)
Routing row schema (per `convert-dataset-to-harbor-gym` contract):
{"instance_id":"<alias>::<task_name>","responses_create_params":{"input":[]},"agent_ref":{"name":"harbor_agent"}}
The `<alias>` is one of `openswe_oss` / `openswe_other` (matches the HF dataset config name),
and `<task_name>` is the original OpenSWE `instance_id` (e.g. `Zac-HD__shed-91`).
OpenSWE task images are NOT pre-built and not hosted on a registry: each row carries
its own `Dockerfile` body plus an `image_name` like `openswe--<owner>__<repo>-<id>`.
We write the Dockerfile to `environment/Dockerfile` verbatim and record the suggested
local tag in `task.toml`'s metadata (`metadata.suggested_image_tag`); we do NOT set
`environment.docker_image` because Harbor's Modal backend would try to pull it.
The Dockerfile uses `FROM openswe-python-3.11` and `COPY repo /testbed` — meaning
the build expects an `openswe-python-3.11` base image and a `repo/` subdirectory.
Building these is the user's responsibility (see OpenSWE's `daVinci-Dev` pipeline);
this script does NOT clone repos or pre-build images. The `--rewrite-dockerfile`
flag replaces `COPY repo /testbed` with a `git clone + checkout` step so the image
can build standalone if the upstream repo is still public.
No datapoint is silently dropped. Rows missing `instance_id` / `Dockerfile` /
`eval_script` / `patch` are written to a `_skipped.jsonl` file with the reason,
so the caller can decide what to do.
"""
from __future__ import annotations
import argparse
import csv
import dataclasses
import json
import logging
import os
import re
import shutil
import sys
from collections.abc import Iterable, Iterator
from pathlib import Path
logger = logging.getLogger("convert_openswe")
CONFIGS = ("openswe_oss", "openswe_other")
# `patch` is intentionally missing from openswe_other (per README: only Dockerfile +
# eval_script are shipped for non-redistributable repos). solve.sh is left as a no-op
# in that case so the task is still runnable as an agent eval (just not via oracle).
REQUIRED_FIELDS = ("instance_id", "Dockerfile", "eval_script")
@dataclasses.dataclass
class Counters:
total: int = 0
written: int = 0
skipped: int = 0
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Convert GAIR/OpenSWE JSONL → Harbor task dataset + NeMo Gym routing JSONL.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
p.add_argument(
"--source-dir",
type=Path,
required=True,
help="Directory containing openswe_oss.jsonl, openswe_other.jsonl, filtered_ids.csv "
"(as downloaded via `hf download GAIR/OpenSWE`).",
)
p.add_argument(
"--output-dir",
type=Path,
default=Path(__file__).parent,
help="Where to write tasks/ and routing/ trees. Defaults to this script's directory.",
)
p.add_argument(
"--configs",
nargs="+",
default=list(CONFIGS),
choices=CONFIGS,
help="Which OpenSWE configs to process.",
)
p.add_argument(
"--limit",
type=int,
default=None,
help="Stop after writing N tasks per config (for smoke tests).",
)
p.add_argument(
"--skip-tasks",
action="store_true",
help="Only emit the routing JSONL; do not materialize per-task directories. "
"Useful when iterating on routing-side logic without touching ~45k directories.",
)
p.add_argument(
"--filtered-only",
action="store_true",
help="Output only the rows in filtered_ids.csv (~8,876 ids). This is the curated "
"subset GAIR uses to train OpenSWE-32B/72B — see paper Sec 4 for filter details. "
"When set, routing files are named `<config>.jsonl` (no _filtered suffix) and "
"`<config>_filtered.jsonl` is not produced as a separate file.",
)
p.add_argument(
"--rewrite-dockerfile",
action="store_true",
help="Replace `COPY repo /testbed` with `git clone + checkout <base_commit>` so the "
"image can build without a local repo/ subdir. Only safe if the upstream repo is "
"still public and reachable.",
)
p.add_argument(
"--dockerhub-user",
default=None,
help="If set, rewrite `FROM openswe-python-X.Y` to "
"`FROM docker.io/<user>/openswe-python-X.Y:latest` for the versions listed in "
"--dockerhub-versions. Tasks that need a version NOT in that list are left with "
"the original (local) FROM line and tagged metadata.base_image_published = false.",
)
p.add_argument(
"--dockerhub-versions",
default="3.7,3.9,3.10,3.11,3.12,3.13",
help="Comma-separated list of Python versions published under --dockerhub-user "
"as `openswe-python-X.Y:latest`. Tasks whose FROM matches one of these get "
"rewritten to the Docker Hub path; others stay local.",
)
p.add_argument(
"--agent-name",
default="harbor_agent",
help="agent_ref.name written into every routing row.",
)
p.add_argument(
"--verifier-timeout",
type=float,
default=900.0,
help="task.toml [verifier].timeout_sec",
)
p.add_argument(
"--agent-timeout",
type=float,
default=1800.0,
help="task.toml [agent].timeout_sec",
)
p.add_argument(
"--build-timeout",
type=float,
default=1800.0,
help="task.toml [environment].build_timeout_sec",
)
p.add_argument(
"--memory-mb",
type=int,
default=8192,
help="task.toml [environment].memory_mb",
)
p.add_argument(
"--storage-mb",
type=int,
default=20480,
help="task.toml [environment].storage_mb",
)
p.add_argument(
"--clean",
action="store_true",
help="Remove tasks/<alias>/ and routing/<alias>*.jsonl before writing.",
)
p.add_argument(
"--log-level",
default="INFO",
choices=("DEBUG", "INFO", "WARNING", "ERROR"),
)
return p.parse_args()
def iter_jsonl(path: Path) -> Iterator[dict]:
with path.open("r", encoding="utf-8") as fh:
for line_no, line in enumerate(fh, 1):
line = line.strip()
if not line:
continue
try:
yield json.loads(line)
except json.JSONDecodeError as exc:
logger.error("malformed JSON in %s at line %d: %s", path, line_no, exc)
raise
def load_filter_ids(path: Path) -> set[str]:
"""Read filtered_ids.csv (column: instance_id) into a set."""
ids: set[str] = set()
if not path.exists():
logger.warning("filtered_ids.csv not found at %s; filtered routing files will be skipped", path)
return ids
with path.open("r", encoding="utf-8", newline="") as fh:
reader = csv.DictReader(fh)
for row in reader:
iid = row.get("instance_id")
if iid:
ids.add(iid.strip())
logger.info("loaded %d filtered instance_ids from %s", len(ids), path)
return ids
def rewrite_dockerfile_for_git_clone(dockerfile: str, repo: str, commit: str) -> str:
"""Swap `COPY repo /testbed` for a git-clone step so the image is buildable standalone."""
needle = "COPY repo /testbed"
if needle not in dockerfile:
return dockerfile
replacement = (
"# Auto-rewritten by convert_openswe.py: clone the repo at build time instead of\n"
"# expecting a local repo/ subdirectory.\n"
f"RUN git clone https://github.com/{repo}.git /testbed && \\\n"
f" cd /testbed && \\\n"
f" git reset --hard {commit}\n"
)
return dockerfile.replace(needle, replacement)
_FROM_LOCAL_OPENSWE_RE = re.compile(
r"^(\s*FROM\s+)openswe-python-([0-9]+\.[0-9]+)(?::\w+)?\s*$",
re.MULTILINE,
)
def rewrite_dockerfile_for_dockerhub_base(
dockerfile: str,
dockerhub_user: str,
published_versions: set[str],
) -> tuple[str, bool]:
"""Rewrite `FROM openswe-python-X.Y` → `FROM docker.io/<user>/openswe-python-X.Y:latest`
when X.Y is in `published_versions`. Returns (new_dockerfile, was_rewritten).
Tasks whose base version isn't published are returned unchanged with `False`.
"""
rewritten = False
def repl(m: re.Match[str]) -> str:
nonlocal rewritten
prefix, version = m.group(1), m.group(2)
if version not in published_versions:
return m.group(0)
rewritten = True
return f"{prefix}docker.io/{dockerhub_user}/openswe-python-{version}:latest"
return _FROM_LOCAL_OPENSWE_RE.sub(repl, dockerfile), rewritten
def render_test_sh() -> str:
"""Render the Harbor test.sh that wraps OpenSWE's eval_script.
OpenSWE's eval_script is a bash script that runs the test suite via the embedded
test_patch + repo state. It exits 0 on full pass, non-zero on any failure.
Harbor verifier contract:
- test.sh runs in the container (workdir = /tests by default)
- It must write the reward (numeric scalar) to /logs/verifier/reward.txt
"""
return (
"#!/usr/bin/env bash\n"
"# Auto-generated by convert_openswe.py: wraps the original OpenSWE eval_script\n"
"# and emits a Harbor-compatible reward (1.0 on success, 0.0 otherwise).\n"
"set -u\n"
"mkdir -p /logs/verifier\n"
"\n"
"/tests/openswe_eval.sh\n"
"exit_code=$?\n"
"if [ $exit_code -eq 0 ]; then\n"
' echo "1.0" > /logs/verifier/reward.txt\n'
"else\n"
' echo "0.0" > /logs/verifier/reward.txt\n'
"fi\n"
"exit 0\n"
)
def render_solve_sh(patch: str) -> str:
"""Wrap the OpenSWE gold patch so it can be applied inside the container.
If `patch` is empty (true for every `openswe_other` row), emit a no-op script
that exits successfully with a comment explaining why — OpenSWE doesn't ship
gold patches for non-redistributable repos.
"""
if not patch:
return (
"#!/usr/bin/env bash\n"
"# OpenSWE does not ship a gold patch for this row (openswe_other config).\n"
"# This script is a no-op so Harbor's oracle agent treats the task as\n"
"# unsolvable-by-oracle rather than crashing.\n"
"exit 0\n"
)
return (
"#!/usr/bin/env bash\n"
"# Auto-generated by convert_openswe.py: applies the OpenSWE gold patch to /testbed.\n"
"set -euo pipefail\n"
"cd /testbed\n"
"git apply --whitespace=nowarn --allow-empty - <<'OPENSWE_GOLD_PATCH_EOF'\n"
+ patch
+ ("" if patch.endswith("\n") else "\n")
+ "OPENSWE_GOLD_PATCH_EOF\n"
)
def render_task_toml(
row: dict,
alias: str,
in_filtered_set: bool,
base_image_published: bool,
*,
verifier_timeout: float,
agent_timeout: float,
build_timeout: float,
memory_mb: int,
storage_mb: int,
) -> str:
"""Render the task.toml. Embeds OpenSWE-specific bookkeeping under [metadata]."""
instance_id = row["instance_id"]
repo = row.get("repo", "")
base_commit = row.get("base_commit", "")
image_name = row.get("image_name", "")
license_name = row.get("license_name") or row.get("license") or ""
version = row.get("version") or ""
# TOML escape: only need to worry about double-quotes in metadata strings.
def esc(s: str) -> str:
return s.replace("\\", "\\\\").replace('"', '\\"')
# NOTE: `local_image_tag` is a LOCAL Docker tag (not a registry path). It is what
# OpenSWE's `scripts/build_images.py` produces and what Harbor's Docker backend
# tags the built image with. There is NO public registry hosting these images.
# `in_filtered_set` mirrors membership in GAIR's filtered_ids.csv — true = task
# survived GAIR's difficulty + trajectory-sampling curation, recommended for RL.
return (
'version = "1.0"\n'
"\n"
"[metadata]\n"
f'dataset = "GAIR/OpenSWE"\n'
f'config = "{alias}"\n'
f'instance_id = "{esc(instance_id)}"\n'
f'repo = "{esc(repo)}"\n'
f'base_commit = "{esc(base_commit)}"\n'
f'upstream_version = "{esc(str(version))}"\n'
f'license_name = "{esc(license_name)}"\n'
f'local_image_tag = "{esc(image_name)}" # LOCAL build tag, not a registry path. See README.\n'
f'in_filtered_set = {str(in_filtered_set).lower()} # true = in GAIR filtered_ids.csv (RL default)\n'
f'base_image_published = {str(base_image_published).lower()} # true = FROM line rewritten to docker.io/<user>/openswe-python-X.Y:latest\n'
"\n"
"[verifier]\n"
f"timeout_sec = {verifier_timeout}\n"
"\n"
"[agent]\n"
f"timeout_sec = {agent_timeout}\n"
"\n"
"[environment]\n"
f"build_timeout_sec = {build_timeout}\n"
f"memory_mb = {memory_mb}\n"
f"storage_mb = {storage_mb}\n"
"allow_internet = true\n"
)
def materialize_task(
row: dict,
alias: str,
out_root: Path,
args: argparse.Namespace,
in_filtered_set: bool,
published_versions: set[str],
) -> bool:
"""Write the per-task Harbor directory. Returns True if the base image is published."""
instance_id = row["instance_id"]
task_dir = out_root / "tasks" / alias / instance_id
task_dir.mkdir(parents=True, exist_ok=True)
(task_dir / "environment").mkdir(exist_ok=True)
(task_dir / "solution").mkdir(exist_ok=True)
(task_dir / "tests").mkdir(exist_ok=True)
# instruction.md = problem_statement
(task_dir / "instruction.md").write_text(
row.get("problem_statement") or "", encoding="utf-8"
)
# Dockerfile
dockerfile = row.get("Dockerfile") or ""
base_image_published = False
if args.dockerhub_user and dockerfile:
dockerfile, base_image_published = rewrite_dockerfile_for_dockerhub_base(
dockerfile, args.dockerhub_user, published_versions
)
if args.rewrite_dockerfile and dockerfile:
dockerfile = rewrite_dockerfile_for_git_clone(
dockerfile, row.get("repo", ""), row.get("base_commit", "")
)
(task_dir / "environment" / "Dockerfile").write_text(dockerfile, encoding="utf-8")
# tests/test.sh wraps OpenSWE's eval_script
(task_dir / "tests" / "test.sh").write_text(render_test_sh(), encoding="utf-8")
# Keep the original eval_script verbatim — test.sh calls it.
(task_dir / "tests" / "openswe_eval.sh").write_text(
row.get("eval_script") or "", encoding="utf-8"
)
os.chmod(task_dir / "tests" / "test.sh", 0o755)
os.chmod(task_dir / "tests" / "openswe_eval.sh", 0o755)
# solution/solve.sh applies the gold patch
(task_dir / "solution" / "solve.sh").write_text(
render_solve_sh(row.get("patch") or ""), encoding="utf-8"
)
os.chmod(task_dir / "solution" / "solve.sh", 0o755)
# task.toml
(task_dir / "task.toml").write_text(
render_task_toml(
row,
alias,
in_filtered_set,
base_image_published,
verifier_timeout=args.verifier_timeout,
agent_timeout=args.agent_timeout,
build_timeout=args.build_timeout,
memory_mb=args.memory_mb,
storage_mb=args.storage_mb,
),
encoding="utf-8",
)
return base_image_published
def write_routing_jsonl(
fh,
instance_ids: Iterable[str],
alias: str,
agent_name: str,
) -> int:
count = 0
for iid in instance_ids:
fh.write(
json.dumps(
{
"instance_id": f"{alias}::{iid}",
"responses_create_params": {"input": []},
"agent_ref": {"name": agent_name},
},
ensure_ascii=False,
)
+ "\n"
)
count += 1
return count
def validate_row(row: dict) -> str | None:
"""Return None if row is convertible, else a reason string."""
missing = [f for f in REQUIRED_FIELDS if not row.get(f)]
if missing:
return f"missing required fields: {','.join(missing)}"
# instance_id must not contain "::" (would break routing parsing).
if "::" in row["instance_id"]:
return "instance_id contains '::' (reserved as alias separator)"
# 4 rows in the upstream dataset have an unsubstituted Dockerfile template
# variable: `FROM openswe-python-${PYTHON_VERSION}`. Docker can't resolve this
# at build time without --build-arg, and OpenSWE's pipeline never substitutes
# it — confirmed broken upstream. Skip rather than ship broken envs.
if "openswe-python-${PYTHON_VERSION}" in (row.get("Dockerfile") or ""):
return "Dockerfile has unsubstituted ${PYTHON_VERSION} template variable (broken upstream)"
return None
def process_config(
alias: str,
source_dir: Path,
out_root: Path,
filtered_ids: set[str],
published_versions: set[str],
args: argparse.Namespace,
) -> Counters:
jsonl_path = source_dir / f"{alias}.jsonl"
if not jsonl_path.exists():
logger.error("missing source file: %s", jsonl_path)
sys.exit(2)
if args.clean:
tasks_dir = out_root / "tasks" / alias
if tasks_dir.exists():
logger.warning("removing existing %s", tasks_dir)
shutil.rmtree(tasks_dir)
for fname in (f"{alias}.jsonl", f"{alias}_filtered.jsonl", f"{alias}_skipped.jsonl"):
p = out_root / "routing" / fname
if p.exists():
p.unlink()
(out_root / "tasks" / alias).mkdir(parents=True, exist_ok=True)
(out_root / "routing").mkdir(parents=True, exist_ok=True)
routing_path = out_root / "routing" / f"{alias}.jsonl"
filtered_path = out_root / "routing" / f"{alias}_filtered.jsonl"
skipped_path = out_root / "routing" / f"{alias}_skipped.jsonl"
# When --filtered-only is on, skip the parallel _filtered.jsonl entirely; the
# main routing file IS the filtered set.
emit_filtered_file = not args.filtered_only and bool(filtered_ids)
counters = Counters()
filtered_only_skipped = 0
seen_ids: set[str] = set()
routing_fh = routing_path.open("w", encoding="utf-8")
filtered_fh = filtered_path.open("w", encoding="utf-8") if emit_filtered_file else None
skipped_fh = skipped_path.open("w", encoding="utf-8")
try:
for row in iter_jsonl(jsonl_path):
counters.total += 1
reason = validate_row(row)
if reason is not None:
skipped_fh.write(
json.dumps(
{"instance_id": row.get("instance_id"), "reason": reason},
ensure_ascii=False,
)
+ "\n"
)
counters.skipped += 1
continue
iid = row["instance_id"]
if iid in seen_ids:
skipped_fh.write(
json.dumps(
{"instance_id": iid, "reason": "duplicate instance_id"},
ensure_ascii=False,
)
+ "\n"
)
counters.skipped += 1
continue
seen_ids.add(iid)
# --filtered-only: drop rows that aren't in filtered_ids.csv.
if args.filtered_only and iid not in filtered_ids:
filtered_only_skipped += 1
continue
if not args.skip_tasks:
materialize_task(
row, alias, out_root, args, iid in filtered_ids, published_versions
)
routing_row = json.dumps(
{
"instance_id": f"{alias}::{iid}",
"responses_create_params": {"input": []},
"agent_ref": {"name": args.agent_name},
},
ensure_ascii=False,
)
routing_fh.write(routing_row + "\n")
if filtered_fh is not None and iid in filtered_ids:
filtered_fh.write(routing_row + "\n")
counters.written += 1
if counters.written % 2500 == 0:
logger.info("[%s] written=%d skipped=%d", alias, counters.written, counters.skipped)
if args.limit is not None and counters.written >= args.limit:
logger.info("[%s] hit --limit=%d, stopping", alias, args.limit)
break
finally:
routing_fh.close()
if filtered_fh is not None:
filtered_fh.close()
skipped_fh.close()
if args.filtered_only:
logger.info(
"[%s] --filtered-only excluded %d non-filtered rows",
alias,
filtered_only_skipped,
)
logger.info(
"[%s] DONE: total=%d written=%d skipped=%d → routing=%s",
alias,
counters.total,
counters.written,
counters.skipped,
routing_path,
)
return counters
def validate_output(out_root: Path, alias: str, counters: Counters) -> None:
"""Spot-check the routing JSONL and (if produced) a few task dirs."""
routing_path = out_root / "routing" / f"{alias}.jsonl"
with routing_path.open() as fh:
lines = sum(1 for _ in fh)
assert lines == counters.written, (
f"routing line count {lines} != written {counters.written} for {alias}"
)
with routing_path.open() as fh:
for line_no, line in enumerate(fh, 1):
row = json.loads(line)
iid = row["instance_id"]
if iid.count("::") != 1:
raise AssertionError(f"{alias} line {line_no}: instance_id must contain exactly one '::': {iid!r}")
if not iid.startswith(f"{alias}::"):
raise AssertionError(f"{alias} line {line_no}: instance_id must start with '{alias}::': {iid!r}")
if line_no >= 50: # sample first 50
break
logger.info("[%s] routing validated: %d rows, instance_id format OK", alias, lines)
def main() -> None:
args = parse_args()
logging.basicConfig(
level=getattr(logging, args.log_level),
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
args.source_dir = args.source_dir.expanduser().resolve()
args.output_dir = args.output_dir.expanduser().resolve()
logger.info("source-dir=%s output-dir=%s", args.source_dir, args.output_dir)
filtered_ids = load_filter_ids(args.source_dir / "filtered_ids.csv")
# Mirror filtered_ids as a top-level file so downstream tools can grep without
# opening every task.toml.
if filtered_ids:
(args.output_dir).mkdir(parents=True, exist_ok=True)
(args.output_dir / "filtered_ids.txt").write_text(
"\n".join(sorted(filtered_ids)) + "\n", encoding="utf-8"
)
published_versions = {
v.strip() for v in args.dockerhub_versions.split(",") if v.strip()
}
if args.dockerhub_user:
logger.info(
"Docker Hub rewrite: FROM openswe-python-{X.Y} → docker.io/%s/openswe-python-{X.Y}:latest for versions %s",
args.dockerhub_user,
sorted(published_versions),
)
overall = Counters()
for alias in args.configs:
c = process_config(alias, args.source_dir, args.output_dir, filtered_ids, published_versions, args)
validate_output(args.output_dir, alias, c)
overall.total += c.total
overall.written += c.written
overall.skipped += c.skipped
logger.info(
"ALL DONE: total=%d written=%d skipped=%d (skip_tasks=%s, rewrite_dockerfile=%s, dockerhub_user=%s)",
overall.total,
overall.written,
overall.skipped,
args.skip_tasks,
args.rewrite_dockerfile,
args.dockerhub_user,
)
if __name__ == "__main__":
main()