diff --git a/phoenix/backend.py b/phoenix/backend.py index c20a9cb..6e4bffb 100644 --- a/phoenix/backend.py +++ b/phoenix/backend.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path +import shutil import socket import subprocess import sys @@ -30,6 +31,19 @@ def log_tail(path, limit=200_000): return stream.read().decode(errors="replace") +def publish_author_trajectory(stage, attempt, observed, rc): + # Submission replay can finish without a model call. Keep the last actual author trace. + source = observed["trajectory"] + completed = attempt / "generate/author/author.traj" + if rc == 0 and completed.is_file(): + source = completed + if source is None: + return + temporary = stage / ".author.traj.tmp" + shutil.copyfile(source, temporary) + temporary.replace(stage / "author.traj") + + class DockerBackend: def __init__(self, settings, key): from phoenix.runtime import validate @@ -304,6 +318,8 @@ def generate(self, task, stage, *, allowance, final_stage, candidate=None, summa # On controller interruption _monitor raises before cleanup: # the exact live worker is adopted by the next --resume. observed = self._read_attempt(request, attempt, rc, timed_out) + if self.settings["method"] in REPAIR_METHODS: + publish_author_trajectory(stage, attempt, observed, rc) if observed["exit_status"] == "exit_api" and observed["patch"] is None: # Keep the original checkout if neither capture succeeded. # A failed snapshot must not destroy the only copy of work. diff --git a/phoenix/pipeline.py b/phoenix/pipeline.py index 04194bd..cb96530 100644 --- a/phoenix/pipeline.py +++ b/phoenix/pipeline.py @@ -10,7 +10,7 @@ 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.run_state import bind, digest, read from phoenix.backend import DockerBackend, ControllerInterrupted @@ -20,13 +20,13 @@ def task_jobs(candidates=1, max_calls=200): if max_calls <= 40: raise ValueError("This experiment requires max_steps > 40 and releases the review reservation") if candidates == 1: - return [dict(stage="candidate-1", kind="candidate", final=True, allowance=max_calls)] + return [dict(stage="location-1", kind="candidate", final=True, allowance=max_calls)] candidate_pool = max_calls // 2 if candidates > candidate_pool: raise ValueError("Too many candidates for the shared task budget") - return [dict(stage=f"candidate-{i+1}", kind="candidate", final=False, + return [dict(stage=f"location-{i+1}", kind="candidate", final=False, allowance=candidate_pool // candidates + (i < candidate_pool % candidates)) for i in range(candidates)] + [ - dict(stage="summary", kind="summary", final=False), + dict(stage="final/comparison", kind="summary", final=False), dict(stage="final", kind="final", final=True, allowance=max_calls - candidate_pool - 1)] @@ -72,6 +72,15 @@ def run_task(task, settings, backend, key, candidates=None, summary_fn=summarize jobs = [dict(stage="sample-1", kind="sample", final=True, allowance=settings["max_steps"])] else: jobs = task_jobs(len(candidates or []), settings["max_steps"]) + # Older runs bind their stage paths into task and worker identities. + # Keep those paths on resume, but recompute budgets and validate the full identity. + previous_jobs = read(directory / "task-identity.json").get("value", {}).get("jobs", []) + if previous_jobs and previous_jobs[0]["stage"] == "candidate-1": + for job in jobs: + if job["kind"] == "candidate": + job["stage"] = job["stage"].replace("location-", "candidate-", 1) + elif job["kind"] == "summary": + job["stage"] = "summary" 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/summary.py b/phoenix/summary.py index 1883b51..cc9b28d 100644 --- a/phoenix/summary.py +++ b/phoenix/summary.py @@ -79,9 +79,18 @@ def summarize(task, candidates, settings, directory, key, *, shared_budget=False "usage": dict(prompt_tokens=0, completion_tokens=0, total_tokens=0), "usage_applied": [], "unknown_requests": []} receipt = read(directory / "result.json") + trajectory_path = directory.parent / "comparison.traj" if directory.name == "comparison" else None + + def publish_trajectory(response): + message = {"role": "assistant", **response["choices"][0]["message"]} + write_json(trajectory_path, {"model": payload["model"], "history": [*payload["messages"], message], + "usage": response.get("usage", {})}) + if receipt.get("status") == "completed": if digest(directory / "summary.txt") != receipt["summary_sha256"]: raise ValueError("Completed summary changed; refusing to regenerate or continue") + if trajectory_path is not None and not trajectory_path.exists(): + publish_trajectory(read(directory / f"response-{receipt['api_attempts']}.json")) return (directory / "summary.txt").read_text() if state["phase"] == "failed": raise RuntimeError("Summary exhausted its original bounded attempts; no budget reset on resume") @@ -178,6 +187,8 @@ def transport_failure(): if kimi and choice.get("finish_reason") == "length": valid = False if valid: + if trajectory_path is not None: + publish_trajectory(response) (directory / "summary.txt").write_text(answer) write_json(directory / "result.json", {"status": "completed", "summary_sha256": digest(directory / "summary.txt"), "model": settings["model"], diff --git a/tests/test_repair.py b/tests/test_repair.py index b0fa7c5..3698529 100644 --- a/tests/test_repair.py +++ b/tests/test_repair.py @@ -177,6 +177,19 @@ 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() + assert (output / "location-1/final.patch").is_file() + if candidate_count == 1: + assert not (output / "final").exists() + else: + assert (output / "location-2/final.patch").is_file() + assert (output / "final/final.patch").read_bytes() == (output / "final.patch").read_bytes() + comparison = output / "final/comparison" + trace = json.loads((output / "final/comparison.traj").read_text()) + request = json.loads((comparison / "request.json").read_text()) + assert trace["history"][:-1] == request["messages"] + assert trace["history"][-1] == {"role": "assistant", "content": (comparison / "summary.txt").read_text()} + assert not (output / "candidate-1").exists() + def test_single_trajectory_runs_without_location_or_summary(monkeypatch, task, settings): @@ -192,3 +205,37 @@ def test_single_trajectory_runs_without_location_or_summary(monkeypatch, task, s str(Path(report["patch"]).parent / "sample-1/final.patch")] assert Path(report["patch"]).is_file() assert not (Path(settings["output"]) / "localization").exists() + + +def test_publish_author_trajectory_preserves_last_author_on_submission_replay(tmp_path): + from phoenix.backend import publish_author_trajectory + stage = tmp_path / "location-1" + attempt = stage / "attempts/001" + official = attempt / "generate/author/author.traj" + checkpoint = attempt / "checkpoint.json" + write_json(checkpoint, {"history": [{"content": "checkpoint"}]}) + publish_author_trajectory(stage, attempt, {"trajectory": checkpoint}, 1) + assert (stage / "author.traj").read_bytes() == checkpoint.read_bytes() + write_json(official, {"history": [{"content": "completed"}]}) + publish_author_trajectory(stage, attempt, {"trajectory": checkpoint}, 0) + publish_author_trajectory(stage, stage / "attempts/002", {"trajectory": None}, 0) + assert (stage / "author.traj").read_bytes() == official.read_bytes() + + +def test_resume_uses_bound_stage_paths(task, candidate, settings): + from phoenix.run_state import bind + directory = Path(settings["output"]) / settings["model"] / task["instance_id"] + second = {**candidate, "id": "C2"} + candidates = [candidate, second] + jobs = task_jobs(2) + for job, stage in zip(jobs, ["candidate-1", "candidate-2", "summary", "final"]): + job["stage"] = stage + bind(directory / "task-identity.json", dict(task=task, jobs=jobs, candidates=candidates, + model=settings["model"], method=settings["method"])) + def compare(task, results, settings, stage, key, *, shared_budget): + assert stage == directory / "summary" + return "Use the second strategy." + result = run_task(task, settings, Backend(), "fixture", candidates, summary_fn=compare) + assert result["status"] == "completed" + assert json.loads((directory / "plan.json").read_text()) == jobs + assert not (directory / "location-1").exists()