Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .cursor/rules/project-overview.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -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/`
Expand Down
2 changes: 1 addition & 1 deletion .devcontainer/bashrc_epilog.sh
Original file line number Diff line number Diff line change
@@ -1 +1 @@
echo "Run ./run.sh --help to see PhoenixRepair options."
echo "Run ./run_our_method.sh --help to see PhoenixRepair options."
60 changes: 57 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<output>/<model>/<instance_id>/`. 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=<output>/<model>/<instance_id>`. 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) | `<output>/localization/<model>/<instance_id>/trajectory.jsonl` |
| PhoenixRepair candidate trajectory | `$TASK/candidate-<n>/attempts/<attempt>/generate/author/author.traj` |
| PhoenixRepair final author trajectory (multiple candidates) | `$TASK/final/attempts/<attempt>/generate/author/author.traj` |
| SWE-agent single trajectory | `$TASK/sample-1/attempts/<attempt>/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/<run_id>/`.

**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.
2 changes: 2 additions & 0 deletions configs/swe-agent.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
max_steps: 200
concurrency: 4
58 changes: 58 additions & 0 deletions evaluation/export_predictions.py
Original file line number Diff line number Diff line change
@@ -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}")
11 changes: 7 additions & 4 deletions phoenix/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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)
Expand Down Expand Up @@ -270,15 +270,18 @@ 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,
num_candidates=num_candidates, generation_allowance=allowance, final_stage=final_stage,
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")
Expand Down
15 changes: 11 additions & 4 deletions phoenix/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
7 changes: 5 additions & 2 deletions phoenix/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion phoenix/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions run_our_method.sh
Original file line number Diff line number Diff line change
@@ -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" "$@"
5 changes: 5 additions & 0 deletions run_swe_agent.sh
Original file line number Diff line number Diff line change
@@ -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 "$@"
2 changes: 1 addition & 1 deletion run.sh → scripts/run_agent.sh
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
15 changes: 15 additions & 0 deletions tests/test_repair.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading