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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Judge generation stage: execute the candidate's pipeline patch, Judge-owned.
|
| 2 |
+
|
| 3 |
+
Binds the scored task set to execution of the submitted inputs:
|
| 4 |
+
|
| 5 |
+
1. Scope check. Every hunk of the candidate diff must target a path in the
|
| 6 |
+
editable set; binary hunks, any other path, and a configuration that sets
|
| 7 |
+
`skip_validation` or `limit` are candidate-invalid (exit 3, no task set).
|
| 8 |
+
2. Apply. A fresh copy of the pinned Repo2RLEnv tree receives the patch
|
| 9 |
+
(`git apply --check` first, then `git apply`).
|
| 10 |
+
3. Run. The patched pipeline runs over the DEV repositories with the fixed
|
| 11 |
+
configuration through the same LocalSandbox driver Work uses, from a
|
| 12 |
+
subprocess with no network. Only the DEV corpus, bootstrap.json files and
|
| 13 |
+
this adapter are needed on the filesystem.
|
| 14 |
+
4. Emit. `<out>/tasks/<owner__name>/<task_id>/...`, `<out>/generation.json`
|
| 15 |
+
(per-repository PipelineResult), `<out>/scope_check.json`.
|
| 16 |
+
|
| 17 |
+
Judge then re-verifies its frozen assets against the dataset manifest
|
| 18 |
+
(verify_manifest below) before admission, training and grading.
|
| 19 |
+
|
| 20 |
+
Usage:
|
| 21 |
+
python -m r2e_local.judge_generate --patch candidate.diff --config candidate_options.json \
|
| 22 |
+
--r2e-src <pinned Repo2RLEnv checkout> --corpus corpus.tsv --mirrors <repos root> \
|
| 23 |
+
--sandboxes <sandbox root> --bootstrap <bootstrap root> --out <dir> \
|
| 24 |
+
[--llm-endpoint http://127.0.0.1:8000/v1 --llm hosted_vllm/Qwen/Qwen3.5-4B] [--parallel 4]
|
| 25 |
+
python -m r2e_local.judge_generate verify-manifest --release <dir> --manifest manifest.json
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
import argparse
|
| 31 |
+
import hashlib
|
| 32 |
+
import json
|
| 33 |
+
import re
|
| 34 |
+
import shutil
|
| 35 |
+
import subprocess
|
| 36 |
+
import sys
|
| 37 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
|
| 40 |
+
EDITABLE_FILES = {
|
| 41 |
+
"src/repo2rlenv/pipelines/commit_runtime.py",
|
| 42 |
+
"src/repo2rlenv/pipelines/pr_runtime.py",
|
| 43 |
+
"src/repo2rlenv/spec/options.py",
|
| 44 |
+
}
|
| 45 |
+
# pr_runtime.py: only these functions may change; enforced by symbol diff below.
|
| 46 |
+
EDITABLE_PR_RUNTIME_FUNCS = {
|
| 47 |
+
"split_patch_and_test_patch", "_strip_info_leak", "_reflow_pr_body", "_count_new_test_funcs",
|
| 48 |
+
"_diff_loc_changed", "_difficulty_bucket", "_files_in_patch", "_linked_issue_number",
|
| 49 |
+
}
|
| 50 |
+
FROZEN_IN_COMMIT_RUNTIME = {"_start_validation_sandbox"}
|
| 51 |
+
FROZEN_OPTIONS = {"skip_validation": False, "limit": 100000}
|
| 52 |
+
|
| 53 |
+
_DIFF_FILE = re.compile(r"^diff --git a/(\S+) b/(\S+)$", re.M)
|
| 54 |
+
_HUNK_HEADER = re.compile(r"^@@ .* @@\s*(?:(?:async )?def (\w+)|class (\w+))?", re.M)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def sha256(p: Path) -> str:
|
| 58 |
+
h = hashlib.sha256()
|
| 59 |
+
with p.open("rb") as f:
|
| 60 |
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
| 61 |
+
h.update(chunk)
|
| 62 |
+
return h.hexdigest()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _defs_of(src: str) -> dict[str, tuple[int, int]]:
|
| 66 |
+
"""Top-level def/class name -> (start_line, end_line) using indentation."""
|
| 67 |
+
lines = src.splitlines()
|
| 68 |
+
out: dict[str, tuple[int, int]] = {}
|
| 69 |
+
current: str | None = None
|
| 70 |
+
start = 0
|
| 71 |
+
for i, line in enumerate(lines):
|
| 72 |
+
m = re.match(r"^(?:async\s+)?(?:def|class)\s+(\w+)", line)
|
| 73 |
+
if m:
|
| 74 |
+
if current is not None:
|
| 75 |
+
out[current] = (start, i)
|
| 76 |
+
current, start = m.group(1), i
|
| 77 |
+
elif current is not None and line and not line[0].isspace() and not line.startswith(("#", ")", "]", "}")):
|
| 78 |
+
out[current] = (start, i)
|
| 79 |
+
current = None
|
| 80 |
+
if current is not None:
|
| 81 |
+
out[current] = (start, len(lines))
|
| 82 |
+
return out
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def changed_symbols(before: str, after: str) -> set[str]:
|
| 86 |
+
"""Top-level symbols whose text differs, plus '<module>' for changes outside any def/class."""
|
| 87 |
+
db, da = _defs_of(before), _defs_of(after)
|
| 88 |
+
lb, la = before.splitlines(), after.splitlines()
|
| 89 |
+
changed: set[str] = set()
|
| 90 |
+
for name in set(db) | set(da):
|
| 91 |
+
tb = "\n".join(lb[db[name][0]:db[name][1]]) if name in db else None
|
| 92 |
+
ta = "\n".join(la[da[name][0]:da[name][1]]) if name in da else None
|
| 93 |
+
if tb != ta:
|
| 94 |
+
changed.add(name)
|
| 95 |
+
def module_text(lines, defs):
|
| 96 |
+
keep = [True] * len(lines)
|
| 97 |
+
for s, e in defs.values():
|
| 98 |
+
for i in range(s, e):
|
| 99 |
+
keep[i] = False
|
| 100 |
+
return "\n".join(l for l, k in zip(lines, keep) if k)
|
| 101 |
+
if module_text(lb, db) != module_text(la, da):
|
| 102 |
+
changed.add("<module>")
|
| 103 |
+
return changed
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def scope_check(patch_text: str, r2e_src: Path, config: dict) -> dict:
|
| 107 |
+
problems: list[str] = []
|
| 108 |
+
files = [m.group(2) for m in _DIFF_FILE.finditer(patch_text)]
|
| 109 |
+
if not files:
|
| 110 |
+
problems.append("no file hunks in patch")
|
| 111 |
+
for f in files:
|
| 112 |
+
if f not in EDITABLE_FILES:
|
| 113 |
+
problems.append(f"path outside editable set: {f}")
|
| 114 |
+
if "GIT binary patch" in patch_text or "Binary files" in patch_text:
|
| 115 |
+
problems.append("binary hunk")
|
| 116 |
+
for k, v in FROZEN_OPTIONS.items():
|
| 117 |
+
if k in config and config[k] != v:
|
| 118 |
+
problems.append(f"frozen option {k} set to {config[k]!r}")
|
| 119 |
+
# Symbol-level check for pr_runtime.py and the frozen sandbox hook.
|
| 120 |
+
if not problems and files:
|
| 121 |
+
tmp = Path(shutil.copytree(r2e_src, r2e_src.parent / (r2e_src.name + ".scopecheck"), dirs_exist_ok=True))
|
| 122 |
+
try:
|
| 123 |
+
(tmp / "candidate.diff").write_text(patch_text)
|
| 124 |
+
r = subprocess.run(["git", "apply", "--check", "candidate.diff"], cwd=tmp, capture_output=True, text=True)
|
| 125 |
+
if r.returncode != 0:
|
| 126 |
+
problems.append("patch does not apply: " + r.stderr.strip()[-300:])
|
| 127 |
+
else:
|
| 128 |
+
subprocess.run(["git", "apply", "candidate.diff"], cwd=tmp, check=True, capture_output=True)
|
| 129 |
+
for f in files:
|
| 130 |
+
before = (r2e_src / f).read_text()
|
| 131 |
+
after = (tmp / f).read_text()
|
| 132 |
+
syms = changed_symbols(before, after)
|
| 133 |
+
if f.endswith("pr_runtime.py"):
|
| 134 |
+
bad = syms - EDITABLE_PR_RUNTIME_FUNCS
|
| 135 |
+
if bad:
|
| 136 |
+
problems.append(f"pr_runtime.py: non-editable symbols changed: {sorted(bad)}")
|
| 137 |
+
if f.endswith("commit_runtime.py") and syms & FROZEN_IN_COMMIT_RUNTIME:
|
| 138 |
+
problems.append("commit_runtime.py: frozen _start_validation_sandbox changed")
|
| 139 |
+
finally:
|
| 140 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 141 |
+
return {"ok": not problems, "files": files, "problems": problems}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def run_generation(args) -> int:
|
| 145 |
+
out = Path(args.out)
|
| 146 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 147 |
+
patch_text = Path(args.patch).read_text()
|
| 148 |
+
config = json.loads(Path(args.config).read_text()) if args.config else {}
|
| 149 |
+
check = scope_check(patch_text, Path(args.r2e_src), config)
|
| 150 |
+
(out / "scope_check.json").write_text(json.dumps(check, indent=2))
|
| 151 |
+
if not check["ok"]:
|
| 152 |
+
print(json.dumps({"status": "candidate_invalid", "problems": check["problems"]}))
|
| 153 |
+
return 3
|
| 154 |
+
|
| 155 |
+
# Fresh patched tree, installed into the Judge interpreter in place.
|
| 156 |
+
tree = out / "repo2rlenv_patched"
|
| 157 |
+
if tree.exists():
|
| 158 |
+
shutil.rmtree(tree)
|
| 159 |
+
shutil.copytree(Path(args.r2e_src), tree, ignore=shutil.ignore_patterns(".git", "__pycache__"))
|
| 160 |
+
(tree / "candidate.diff").write_text(patch_text)
|
| 161 |
+
subprocess.run(["git", "init", "-q"], cwd=tree, check=True)
|
| 162 |
+
subprocess.run(["git", "apply", "candidate.diff"], cwd=tree, check=True, capture_output=True)
|
| 163 |
+
|
| 164 |
+
corpus = [l.split("\t") for l in Path(args.corpus).read_text().splitlines() if l.strip()]
|
| 165 |
+
dev = [(repo, sha) for split, repo, sha in corpus if split == "dev"]
|
| 166 |
+
opts = {**{k: v for k, v in config.items() if k not in FROZEN_OPTIONS}, **FROZEN_OPTIONS}
|
| 167 |
+
opt_flags = [f"--opt {k}={json.dumps(v) if not isinstance(v, (bool, int, float, str)) else v}" for k, v in opts.items()]
|
| 168 |
+
adapter_dir = Path(__file__).resolve().parent.parent
|
| 169 |
+
|
| 170 |
+
def one(item):
|
| 171 |
+
repo, sha = item
|
| 172 |
+
key = repo.replace("/", "__")
|
| 173 |
+
cmd = [
|
| 174 |
+
sys.executable, "-m", "r2e_local.driver", "--repo", repo, "--sha", sha,
|
| 175 |
+
"--mirror", str(Path(args.mirrors) / key), "--sandbox", str(Path(args.sandboxes) / key),
|
| 176 |
+
"--bootstrap", str(Path(args.bootstrap) / key / "bootstrap.json"),
|
| 177 |
+
"--out", str(out / "tasks" / key),
|
| 178 |
+
]
|
| 179 |
+
if args.llm:
|
| 180 |
+
cmd += ["--llm", args.llm]
|
| 181 |
+
if args.llm_endpoint:
|
| 182 |
+
cmd += ["--llm-endpoint", args.llm_endpoint]
|
| 183 |
+
if args.llm_key_env:
|
| 184 |
+
cmd += ["--llm-key-env", args.llm_key_env]
|
| 185 |
+
for f in opt_flags:
|
| 186 |
+
cmd += f.split(" ", 1)
|
| 187 |
+
env = {"PYTHONPATH": f"{tree / 'src'}:{adapter_dir}", "PATH": "/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin", "HOME": str(out / ".home")}
|
| 188 |
+
(out / ".home").mkdir(exist_ok=True)
|
| 189 |
+
r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=args.repo_timeout)
|
| 190 |
+
res_path = out / "tasks" / key / "result.json"
|
| 191 |
+
res = json.loads(res_path.read_text()) if res_path.exists() else {"repo": repo, "error": r.stderr[-800:]}
|
| 192 |
+
res["returncode"] = r.returncode
|
| 193 |
+
return res
|
| 194 |
+
|
| 195 |
+
with ThreadPoolExecutor(max_workers=args.parallel) as ex:
|
| 196 |
+
results = list(ex.map(one, dev))
|
| 197 |
+
summary = {
|
| 198 |
+
"repos": len(dev),
|
| 199 |
+
"emitted": sum(r.get("emitted", 0) for r in results),
|
| 200 |
+
"failed_repos": [r["repo"] for r in results if r.get("returncode", 0) != 0],
|
| 201 |
+
"options": opts,
|
| 202 |
+
"patch_sha256": hashlib.sha256(patch_text.encode()).hexdigest(),
|
| 203 |
+
"per_repo": results,
|
| 204 |
+
}
|
| 205 |
+
(out / "generation.json").write_text(json.dumps(summary, indent=2))
|
| 206 |
+
print(json.dumps({k: summary[k] for k in ("repos", "emitted", "failed_repos")}))
|
| 207 |
+
return 0
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def verify_manifest(args) -> int:
|
| 211 |
+
rel = Path(args.release)
|
| 212 |
+
manifest = json.loads(Path(args.manifest).read_text())
|
| 213 |
+
bad = []
|
| 214 |
+
for relpath, digest in manifest["files"].items():
|
| 215 |
+
p = rel / relpath
|
| 216 |
+
if not p.is_file() or sha256(p) != digest:
|
| 217 |
+
bad.append(relpath)
|
| 218 |
+
print(json.dumps({"verified": len(manifest["files"]) - len(bad), "mismatched": bad[:50], "ok": not bad}))
|
| 219 |
+
return 0 if not bad else 4
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def main(argv: list[str] | None = None) -> int:
|
| 223 |
+
ap = argparse.ArgumentParser()
|
| 224 |
+
sub = ap.add_subparsers(dest="cmd")
|
| 225 |
+
g = sub.add_parser("generate")
|
| 226 |
+
g.add_argument("--patch", required=True)
|
| 227 |
+
g.add_argument("--config", default=None)
|
| 228 |
+
g.add_argument("--r2e-src", required=True)
|
| 229 |
+
g.add_argument("--corpus", required=True)
|
| 230 |
+
g.add_argument("--mirrors", required=True)
|
| 231 |
+
g.add_argument("--sandboxes", required=True)
|
| 232 |
+
g.add_argument("--bootstrap", required=True)
|
| 233 |
+
g.add_argument("--out", required=True)
|
| 234 |
+
g.add_argument("--llm", default=None)
|
| 235 |
+
g.add_argument("--llm-endpoint", default=None)
|
| 236 |
+
g.add_argument("--llm-key-env", default=None)
|
| 237 |
+
g.add_argument("--parallel", type=int, default=4)
|
| 238 |
+
g.add_argument("--repo-timeout", type=int, default=7200)
|
| 239 |
+
v = sub.add_parser("verify-manifest")
|
| 240 |
+
v.add_argument("--release", required=True)
|
| 241 |
+
v.add_argument("--manifest", required=True)
|
| 242 |
+
args = ap.parse_args(argv)
|
| 243 |
+
if args.cmd == "generate":
|
| 244 |
+
return run_generation(args)
|
| 245 |
+
if args.cmd == "verify-manifest":
|
| 246 |
+
return verify_manifest(args)
|
| 247 |
+
ap.print_help()
|
| 248 |
+
return 2
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
if __name__ == "__main__":
|
| 252 |
+
sys.exit(main())
|