diff --git a/.cursor/rules/project-overview.mdc b/.cursor/rules/project-overview.mdc index c01dffe..0fefa4e 100644 --- a/.cursor/rules/project-overview.mdc +++ b/.cursor/rules/project-overview.mdc @@ -5,7 +5,7 @@ alwaysApply: true --- # PhoenixRepair -Run PhoenixRepair with `./run.sh --model MODEL --instances MANIFEST`. +Run PhoenixRepair with `./run_our_method.sh --model MODEL --instances MANIFEST`. The CLI in `phoenix/cli.py` loads the model configuration. The pipeline in `phoenix/pipeline.py` coordinates localization, candidate generation and the final patch. The worker uses the agent implementation in `sweagent/agent/` diff --git a/.devcontainer/bashrc_epilog.sh b/.devcontainer/bashrc_epilog.sh index 880c2e6..8ec57af 100644 --- a/.devcontainer/bashrc_epilog.sh +++ b/.devcontainer/bashrc_epilog.sh @@ -1 +1 @@ -echo "Run ./run.sh --help to see PhoenixRepair options." +echo "Run ./run_our_method.sh --help to see PhoenixRepair options." diff --git a/README.md b/README.md index b8dab82..eead79e 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,62 @@ export PHOENIX_RUNTIME="$PWD/.runtime" Supply `PHOENIX_API_KEY` through your environment. Set `API_BASE` for a custom OpenAI-compatible endpoint. Provide a JSON or JSONL task manifest with a string value for each of `instance_id`, `problem_statement`, `base_commit`, `repo_name`, and `image_name`. ```bash -./run.sh --model glm-5.2 --instances /path/to/tasks.jsonl --dry-run -./run.sh --model glm-5.2 --instances /path/to/tasks.jsonl --output runs/glm-repair +./run_our_method.sh --model glm-5.2 --instances /path/to/tasks.jsonl --dry-run +./run_our_method.sh --model glm-5.2 --instances /path/to/tasks.jsonl --output runs/glm-repair ``` -Each completed task writes `PhoenixRepair.patch` under `///`. Use `--resume` with the same inputs to continue an interrupted run. +## Run a single SWE-agent trajectory + +Use the same setup and manifest. SWE-agent starts from the issue and runs one independent trajectory per selected task. + +```bash +./run_swe_agent.sh --model glm-5.2 --instances /path/to/tasks.jsonl --output runs/glm-single +``` + +For either script, add `--instance-id TASK_ID` to select one task, `--dry-run` to inspect the plan, or `--resume` with the original inputs and output directory to continue an interrupted run. + +## Find the trajectories and patches + +Let `TASK=//`. Each completed task has a final patch at `$TASK/final.patch`. PhoenixRepair also writes `$TASK/PhoenixRepair.patch`. + +| Artifact | Path | +| --- | --- | +| PhoenixRepair localization trajectory (when generated in this run) | `/localization///trajectory.jsonl` | +| PhoenixRepair candidate trajectory | `$TASK/candidate-/attempts//generate/author/author.traj` | +| PhoenixRepair final author trajectory (multiple candidates) | `$TASK/final/attempts//generate/author/author.traj` | +| SWE-agent single trajectory | `$TASK/sample-1/attempts//generate/author/author.traj` | + +Attempt directories start at `001`. Recovery can create additional attempts for the same stage. With one PhoenixRepair candidate, `candidate-1` produces the final patch. Each task's `plan.json` lists its stages and `report.json` records the outcome. + +## Evaluate final patches + +Set `RUN` to either script's output directory. Use a fresh export directory for each evaluation. Export includes every task in the run manifest; failed tasks receive an empty patch. + +**SWE-bench Verified.** Install the official `swebench` Python package in your evaluation environment and start Docker. From the PhoenixRepair repository root: + +```bash +RUN="$PWD/runs/glm-single" +python evaluation/export_predictions.py --run-dir "$RUN" --benchmark verified --output "$RUN/eval-verified" +mapfile -t IDS < "$RUN/eval-verified/ids.txt" +python -m swebench.harness.run_evaluation \ + --dataset_name princeton-nlp/SWE-bench_Verified \ + --predictions_path "$RUN/eval-verified/predictions.jsonl" \ + --instance_ids "${IDS[@]}" --run_id glm-single-verified --max_workers 4 +``` + +Use a distinct run ID for each evaluation. The harness prints its report path and writes per-instance logs under `logs/run_evaluation//`. + +**SWE-bench Pro V2, including HARD-51.** Clone the official [Pro V2 repository](https://github.com/scaleapi/SWE-bench_Pro-os) and follow its Harbor and Modal setup. Set `PRO_V2` to that repository's absolute checkout path. The commands below replay the final patches on clean task images and run the supplied verifiers for the selected task IDs. + +```bash +RUN="$PWD/runs/glm-single" +EXPORT="$RUN/eval-pro-v2" +PRO_V2=/path/to/SWE-bench_Pro-os +python evaluation/export_predictions.py --run-dir "$RUN" --benchmark pro-v2 --output "$EXPORT" +python "$PRO_V2/v2/tooling/make_subset.py" "$PRO_V2/v2/tasks" "$EXPORT/ids.txt" "$EXPORT/tasks" +PYTHONPATH="$PRO_V2/v2/tooling" harbor run -p "$EXPORT/tasks" -e modal -n 4 \ + -a patch_replay:PatchReplayAgent -m replay --ak "source_job=$EXPORT/source_job" \ + --jobs-dir "$EXPORT/jobs" --job-name regrade +``` + +Harbor writes the job result to `$EXPORT/jobs/regrade/result.json` and each trial's score to its verifier output. diff --git a/configs/swe-agent.yaml b/configs/swe-agent.yaml new file mode 100644 index 0000000..465e72a --- /dev/null +++ b/configs/swe-agent.yaml @@ -0,0 +1,2 @@ +max_steps: 200 +concurrency: 4 diff --git a/evaluation/export_predictions.py b/evaluation/export_predictions.py new file mode 100644 index 0000000..e103aa6 --- /dev/null +++ b/evaluation/export_predictions.py @@ -0,0 +1,58 @@ +"""Export final run patches for the SWE-bench Verified or Pro V2 harness.""" +import argparse +import json +import tempfile +from pathlib import Path + + +def export(run, destination, benchmark): + plan = json.loads((run / "plan.json").read_text()) + progress = json.loads((run / "progress.json").read_text()) + ids = plan["instance_ids"] + reports = {row["instance_id"]: row for row in progress["tasks"]} + if progress["status"] != "completed" or set(ids) != set(reports) or len(ids) != len(reports): + raise ValueError("The run needs a terminal report for every selected instance") + settings = plan["settings"] + model = settings["model"] + for value in [model, *ids]: + if not value or value in (".", "..") or Path(value).name != value: + raise ValueError(f"Invalid run path component: {value!r}") + if settings["stage"] == "localization": + raise ValueError("Localization-only runs have no generated predictions") + if destination.exists(): + raise ValueError(f"Choose a new export directory: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=destination.parent) as tmp: + out = Path(tmp) / "export" + out.mkdir() + predictions = [] + for iid in ids: + status = reports[iid]["status"] + if status not in ("completed", "failed", "infrastructure_failed"): + raise ValueError(f"{iid}: cannot evaluate task with status {status}") + patch = (run / model / iid / "final.patch").read_bytes() if status == "completed" else b"" + if benchmark == "verified": + predictions.append(dict(instance_id=iid, model_name_or_path=f"{settings['method']}-{model}", + model_patch=patch.decode("utf-8"))) + else: + if not iid.startswith("instance_"): + raise ValueError(f"Expected a Pro V2 instance ID: {iid}") + trial = out / "source_job" / iid + (trial / "agent").mkdir(parents=True) + (trial / "result.json").write_text(json.dumps({"task_name": iid})) + (trial / "agent/model.patch").write_bytes(patch) + if benchmark == "verified": + (out / "predictions.jsonl").write_text("".join(json.dumps(row) + "\n" for row in predictions)) + (out / "ids.txt").write_text("\n".join(ids) + "\n") + out.rename(destination) + return len(ids) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", required=True, type=Path) + parser.add_argument("--benchmark", required=True, choices=("verified", "pro-v2")) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + count = export(args.run_dir, args.output, args.benchmark) + print(f"Exported {count} predictions to {args.output}") diff --git a/phoenix/backend.py b/phoenix/backend.py index 8cec88e..c20a9cb 100644 --- a/phoenix/backend.py +++ b/phoenix/backend.py @@ -15,7 +15,7 @@ from phoenix.run_state import (bind, digest, find_worker, lock, owned_alive, process_identity, read, reserve_retry, retry_reason, stop_owned, verified_result) -from phoenix.settings import LEGACY_METHOD, REPAIR_METHODS, ROOT, fingerprint, model_config, write_json +from phoenix.settings import LEGACY_METHOD, REPAIR_METHODS, SINGLE_METHOD, ROOT, fingerprint, model_config, write_json class ControllerInterrupted(Exception): @@ -39,7 +39,7 @@ def __init__(self, settings, key): self.output = Path(settings["output"]) self.output.mkdir(parents=True, exist_ok=True) self.base = prepare_tools(self.output)["agent"] - if settings["method"] == LEGACY_METHOD: + if settings["method"] in (LEGACY_METHOD, SINGLE_METHOD): templates = self.base["templates"] templates["system_template"] = templates["system_template"].removeprefix("You are PhoenixRepair.\n") self.profile = recovery_profile(settings) @@ -270,6 +270,9 @@ def generate(self, task, stage, *, allowance, final_stage, candidate=None, summa now = time.time() history_path = (state.get("recovery") or {}).get("trajectory") offset = state["steps"] - (len(read(history_path).get("trajectory", [])) if history_path else 0) + reserve = 0 + if self.settings["method"] == SINGLE_METHOD and self.settings["model"] != "kimi-k2.7-code": + reserve = min(60, remaining / 2) request = dict(task=task, settings=self.settings, stage_dir=str(attempt), base_agent=self.base, run_id=self.run_id, job_id=fingerprint([str(stage), state["attempts"]])[:24], port=self.allocate_port(), image_id=image_id, candidate=candidate, summary=summary, @@ -277,8 +280,8 @@ def generate(self, task, stage, *, allowance, final_stage, candidate=None, summa prior_calls=state["calls"], prior_steps=state["steps"], recovery=state.get("recovery"), prior_execution_seconds=state.get("execution_seconds", 0), steps_offset=max(0, offset), - managed_recovery=True, started_at=now, deadline=now + remaining, - capture_reserve=60) + managed_recovery=True, started_at=now, deadline=now + remaining - reserve, + capture_reserve=reserve or 60) if (attempt / "request.json").exists(): self.ports.discard(request["port"]) request = read(attempt / "request.json") diff --git a/phoenix/cli.py b/phoenix/cli.py index 9bb522e..b3ae785 100644 --- a/phoenix/cli.py +++ b/phoenix/cli.py @@ -11,12 +11,13 @@ import sys import signal -from phoenix.settings import LEGACY_METHOD, METHOD_NAME, REPAIR_METHODS, ROOT, PROFILES, fingerprint, load_instances, load_settings, write_json +from phoenix.settings import LEGACY_METHOD, METHOD_NAME, REPAIR_METHODS, SINGLE_METHOD, ROOT, PROFILES, fingerprint, load_instances, load_settings, write_json def main(argv=None): parser = argparse.ArgumentParser(prog=METHOD_NAME, description=__doc__) - parser.set_defaults(method=METHOD_NAME) + parser.add_argument("--single-trajectory", dest="method", action="store_const", const=SINGLE_METHOD, + default=METHOD_NAME, help="Run one SWE-agent trajectory per task") parser.add_argument("--config", type=Path) parser.add_argument("--model", choices=tuple(PROFILES)) parser.add_argument("--instances", type=Path, help="JSON array or JSONL task manifest") @@ -44,7 +45,13 @@ def main(argv=None): help="Validate configuration and task inputs; no model or Docker calls") args = parser.parse_args(argv) try: - settings = load_settings(args.method, args.config or ROOT / "configs/models" / (args.model or "glm-5.2") / "PhoenixRepair.yaml", { + config = args.config + if config is None: + if args.method == SINGLE_METHOD: + config = ROOT / "configs/swe-agent.yaml" + else: + config = ROOT / "configs/models" / (args.model or "glm-5.2") / "PhoenixRepair.yaml" + settings = load_settings(args.method, config, { k: getattr(args, k) for k in ("model", "instances", "output", "runtime", "api_base", "concurrency", "max_steps", "task_timeout", "localization_max_steps", "localization_timeout", "docker_host", "locations", "stage", "adaptive_io", "io_device", @@ -99,7 +106,7 @@ def main(argv=None): raise ValueError("Saved inference profile differs; resume with the original code or start a new run") if previous.get("recovery_format") != 1: raise ValueError("This run predates durable recovery; use a new output directory") - if previous["settings"].get("method") == LEGACY_METHOD: + if args.method == METHOD_NAME and previous["settings"].get("method") == LEGACY_METHOD: settings["method"] = LEGACY_METHOD immutable = ("model", "method", "api_base", "max_steps", "task_timeout", "samples", "localization_max_steps", "localization_timeout", "locations", "stage", diff --git a/phoenix/pipeline.py b/phoenix/pipeline.py index 9379bce..04194bd 100644 --- a/phoenix/pipeline.py +++ b/phoenix/pipeline.py @@ -8,7 +8,7 @@ import threading import time -from phoenix.settings import REPAIR_METHODS, localization_config, write_json +from phoenix.settings import REPAIR_METHODS, SINGLE_METHOD, localization_config, write_json from phoenix.summary import summarize from phoenix.run_state import bind, digest from phoenix.backend import DockerBackend, ControllerInterrupted @@ -68,7 +68,10 @@ def run_task(task, settings, backend, key, candidates=None, summary_fn=summarize directory.mkdir(parents=True, exist_ok=True) write_json(directory / "instance.json", task) method = settings["method"] - jobs = task_jobs(len(candidates or []), settings["max_steps"]) + if method == SINGLE_METHOD: + jobs = [dict(stage="sample-1", kind="sample", final=True, allowance=settings["max_steps"])] + else: + jobs = task_jobs(len(candidates or []), settings["max_steps"]) bind(directory / "task-identity.json", dict(task=task, jobs=jobs, candidates=candidates, model=settings["model"], method=method)) write_json(directory / "plan.json", jobs) diff --git a/phoenix/settings.py b/phoenix/settings.py index e91253c..548bb96 100644 --- a/phoenix/settings.py +++ b/phoenix/settings.py @@ -14,6 +14,7 @@ API_BASE = "https://dashscope.aliyuncs.com/compatible-mode/v1" FIELDS = ("instance_id", "problem_statement", "base_commit", "repo_name", "image_name") METHOD_NAME = "PhoenixRepair" +SINGLE_METHOD = "SWE-agent" LEGACY_METHOD = "our_method" REPAIR_METHODS = (METHOD_NAME, LEGACY_METHOD) @@ -147,7 +148,8 @@ def load_settings(mode, config_path, overrides): data[key] = os.environ[env] data.setdefault("api_base", API_BASE) data["api_base"] = data["api_base"] or API_BASE - data.setdefault("output", "runs/" + mode) + default_output = f"runs/{data['model']}-single" if mode == SINGLE_METHOD else "runs/" + mode + data.setdefault("output", default_output) data.setdefault("concurrency", 4) data.setdefault("max_steps", 200) data.setdefault("localization_max_steps", 150) diff --git a/run_our_method.sh b/run_our_method.sh new file mode 100755 index 0000000..636a68e --- /dev/null +++ b/run_our_method.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +exec "$repo_dir/scripts/run_agent.sh" "$@" diff --git a/run_swe_agent.sh b/run_swe_agent.sh new file mode 100755 index 0000000..4793353 --- /dev/null +++ b/run_swe_agent.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +exec "$repo_dir/scripts/run_agent.sh" --single-trajectory "$@" diff --git a/run.sh b/scripts/run_agent.sh similarity index 81% rename from run.sh rename to scripts/run_agent.sh index f303372..adeb1e8 100755 --- a/run.sh +++ b/scripts/run_agent.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" python_bin="${PYTHON_BIN:-python3}" if [[ -z "${PYTHON_BIN:-}" && -x "$repo_dir/.venv/bin/python" ]]; then python_bin="$repo_dir/.venv/bin/python" diff --git a/tests/test_repair.py b/tests/test_repair.py index 9fccc4c..b0fa7c5 100644 --- a/tests/test_repair.py +++ b/tests/test_repair.py @@ -177,3 +177,18 @@ def generate(*args, **kwargs): assert events[len(actions):] == (["generate"] if candidate_count == 1 else ["generate", "generate", "summary", "generate"]) output = Path(settings["output"]) / model / task["instance_id"] assert (output / "PhoenixRepair.patch").read_bytes() == (output / "final.patch").read_bytes() + + +def test_single_trajectory_runs_without_location_or_summary(monkeypatch, task, settings): + from phoenix import pipeline + from phoenix.settings import SINGLE_METHOD + settings.update(method=SINGLE_METHOD, max_steps=10) + backend = Backend() + monkeypatch.setattr(pipeline, "DockerBackend", lambda *args: backend) + report, = pipeline.run([task], settings, "fixture") + assert report["status"] == "completed" + assert backend.calls == [dict(allowance=10, final_stage=True, candidate=None, summary=None, num_candidates=0)] + assert [stage["patch"] for stage in report["stages"]] == [ + str(Path(report["patch"]).parent / "sample-1/final.patch")] + assert Path(report["patch"]).is_file() + assert not (Path(settings["output"]) / "localization").exists()