File size: 8,210 Bytes
cb0011e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | """SWE-DockerLess evaluation harness.
No Docker, no network, no prebuilt images: every instance carries its own repo
snapshot inside the JSONL row, so the harness only needs Python, git and pytest.
Usage
-----
# sanity check: score the gold patches (expect 4/4 resolved)
python run_harness.py --dataset SWE-DockerLess.jsonl --gold
# score a predictions file: one JSON object per line with
# {"instance_id": ..., "model_name_or_path": ..., "model_patch": ...}
python run_harness.py --dataset SWE-DockerLess.jsonl \
--predictions predictions.jsonl --out report.json
A prediction is "resolved" when every FAIL_TO_PASS test passes and every
PASS_TO_PASS test still passes, which is the SWE-bench rule.
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
GIT_FLAGS = [
"-c", "core.autocrlf=false",
"-c", "core.safecrlf=false",
"-c", "user.name=harness",
"-c", "user.email=harness@example.invalid",
"-c", "commit.gpgsign=false",
]
RESULT_RE = re.compile(
r"^(tests/[^\s:]+::[^\s]+)\s+(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)"
)
def run(cmd, cwd, check=True):
env = os.environ.copy()
env.setdefault("GIT_AUTHOR_NAME", "harness")
env.setdefault("GIT_AUTHOR_EMAIL", "harness@example.invalid")
env.setdefault("GIT_COMMITTER_NAME", "harness")
env.setdefault("GIT_COMMITTER_EMAIL", "harness@example.invalid")
proc = subprocess.run(
cmd, cwd=str(cwd), capture_output=True, text=True, encoding="utf-8", env=env
)
if check and proc.returncode != 0:
raise RuntimeError(
"command failed (%d): %s\n%s\n%s"
% (proc.returncode, " ".join(cmd), proc.stdout[-4000:], proc.stderr[-4000:])
)
return proc
def git(args, cwd, check=True):
return run(["git"] + GIT_FLAGS + args, cwd, check=check)
def write_snapshot(files, dest):
for rel, content in files.items():
path = dest / rel
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8", newline="\n") as handle:
handle.write(content)
def apply_patch(patch_text, work, tmp, label):
"""Apply a unified diff; return (ok, message)."""
if not patch_text or not patch_text.strip():
return False, "empty patch"
patch_file = Path(tmp) / (label + ".patch")
patch_file.write_text(patch_text, encoding="utf-8", newline="\n")
first = git(["apply", "--check", str(patch_file)], work, check=False)
if first.returncode == 0:
git(["apply", str(patch_file)], work)
return True, "applied"
second = git(["apply", "--check", "--recount", "-C1", str(patch_file)], work, check=False)
if second.returncode == 0:
git(["apply", "--recount", "-C1", str(patch_file)], work)
return True, "applied (recount)"
return False, (first.stderr or first.stdout).strip().splitlines()[0:3]
def run_tests(work, test_files, cmd_template):
cmd = [sys.executable, "-m", "pytest", "-v", "--tb=no", "-p", "no:cacheprovider"]
cmd += list(test_files)
proc = run(cmd, work, check=False)
outcomes = {}
for raw in proc.stdout.splitlines():
match = RESULT_RE.match(raw.strip())
if match:
outcomes[match.group(1)] = match.group(2)
return outcomes, proc
def evaluate(row, model_patch):
test_files = row["dockerless"]["test_files"]
f2p = json.loads(row["FAIL_TO_PASS"])
p2p = json.loads(row["PASS_TO_PASS"])
with tempfile.TemporaryDirectory(prefix="swedl-eval-") as tmp:
work = Path(tmp) / "work"
work.mkdir()
write_snapshot(row["dockerless"]["files"], work)
git(["init", "-q", "-b", "main"], work)
git(["add", "-A"], work)
git(["commit", "-q", "-m", row["base_commit"]], work)
ok, message = apply_patch(row["test_patch"], work, tmp, "test")
if not ok:
return {
"instance_id": row["instance_id"],
"resolved": False,
"reason": "test_patch failed to apply: %s" % (message,),
"f2p_passed": 0,
"f2p_total": len(f2p),
"p2p_passed": 0,
"p2p_total": len(p2p),
}
ok, message = apply_patch(model_patch, work, tmp, "model")
if not ok:
return {
"instance_id": row["instance_id"],
"resolved": False,
"reason": "model patch failed to apply: %s" % (message,),
"f2p_passed": 0,
"f2p_total": len(f2p),
"p2p_passed": 0,
"p2p_total": len(p2p),
}
outcomes, proc = run_tests(work, test_files, row["dockerless"]["test_cmd"])
if not outcomes:
return {
"instance_id": row["instance_id"],
"resolved": False,
"reason": "no tests collected (collection error?)",
"f2p_passed": 0,
"f2p_total": len(f2p),
"p2p_passed": 0,
"p2p_total": len(p2p),
}
f2p_pass = [t for t in f2p if outcomes.get(t) == "PASSED"]
p2p_pass = [t for t in p2p if outcomes.get(t) == "PASSED"]
resolved = len(f2p_pass) == len(f2p) and len(p2p_pass) == len(p2p)
failing = sorted(t for t in f2p + p2p if outcomes.get(t) != "PASSED")
return {
"instance_id": row["instance_id"],
"resolved": resolved,
"reason": "ok" if resolved else "unmet tests: %d" % (len(failing),),
"f2p_passed": len(f2p_pass),
"f2p_total": len(f2p),
"p2p_passed": len(p2p_pass),
"p2p_total": len(p2p),
"failing": failing[:12],
}
def load_predictions(path):
predictions = {}
with open(path, encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
record = json.loads(line)
predictions[record["instance_id"]] = (
record.get("model_patch") or record.get("patch") or ""
)
return predictions
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset", default="SWE-DockerLess.jsonl")
parser.add_argument("--predictions", help="JSONL of {instance_id, model_patch}")
parser.add_argument("--gold", action="store_true", help="score the gold patches")
parser.add_argument("--out", help="write a JSON report here")
args = parser.parse_args()
rows = [json.loads(line) for line in open(args.dataset, encoding="utf-8") if line.strip()]
if args.gold:
predictions = {row["instance_id"]: row["patch"] for row in rows}
elif args.predictions:
predictions = load_predictions(args.predictions)
else:
parser.error("pass --gold or --predictions")
started = time.time()
results = []
print("%-22s %-9s %-7s %-7s %s" % ("instance", "resolved", "F2P", "P2P", "note"))
for row in rows:
result = evaluate(row, predictions.get(row["instance_id"], ""))
results.append(result)
print(
"%-22s %-9s %d/%-5d %d/%-5d %s"
% (
result["instance_id"],
"yes" if result["resolved"] else "no",
result["f2p_passed"],
result["f2p_total"],
result["p2p_passed"],
result["p2p_total"],
result["reason"],
)
)
resolved = sum(1 for result in results if result["resolved"])
elapsed = time.time() - started
summary = {
"dataset": str(Path(args.dataset).name),
"instances": len(rows),
"resolved": resolved,
"resolve_rate": round(resolved / len(rows), 4) if rows else 0.0,
"seconds": round(elapsed, 2),
"results": results,
}
print(
"\nresolved %d/%d (%.1f%%) in %.1fs"
% (resolved, len(rows), 100.0 * summary["resolve_rate"], elapsed)
)
if args.out:
Path(args.out).write_text(json.dumps(summary, indent=2), encoding="utf-8")
print("report -> %s" % args.out)
if __name__ == "__main__":
main()
|