Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
67 changes: 63 additions & 4 deletions orchestrator/routes/pipelines.py
Original file line number Diff line number Diff line change
Expand Up @@ -3134,16 +3134,75 @@ def restart_phase(pipeline_id: str, phase: str) -> tuple[Response, int]:
f"Phase {phase} not found in pipeline {pipeline_id}", status_code=404
)

# 1. Collect agent roles from the phase execution for respawning
agent_roles = []
# 1. Collect agent roles for respawning. Prefer the runtime cache
# on ``phase_exec.agents`` since it reflects the roster from
# the most recent spawn, but fall back to the deterministic
# source the executor itself consults — ``pipeline.active_roles``
# first (CUSTOM-mode / BABYSIT overrides, #1762), then
# ``get_roles_for_phase`` for ISSUE-mode pipelines. Without
# this fallback a restart whose clear step ran
# (``phase_exec.agents = []`` below) but whose spawn step
# failed leaves the pipeline unrecoverable: every subsequent
# ``restart_phase`` 400s on the now-empty cache, and
# ``start_pipeline`` 409s on the CANCELLED state (#2515).
agent_roles: list[AgentRole] = []
for agent in phase_exec.agents:
if hasattr(agent, "role"):
role = agent.role if isinstance(agent.role, AgentRole) else AgentRole(agent.role)
agent_roles.append(role)

if not agent_roles:
return make_error_response(
f"No agents found in phase {phase} to restart", status_code=400
# Mirror ``_run_concurrent_phase`` exactly so the route's
# response (and the downstream worktree-delete / health-
# monitor reset) matches the roster the spawn will actually
# produce: when ``active_roles`` is set, use it verbatim
# and do NOT fall through to ``get_roles_for_phase``.
# Otherwise the all-unknown-override edge case would have
# the route promise a phase-default roster while the spawn
# produced nothing.
_roster_override = getattr(pipeline, "active_roles", None)
if _roster_override:
for r_value in _roster_override:
try:
agent_roles.append(AgentRole(r_value))
except ValueError:
# Unknown role from a newer schema — skip so
# BRC doesn't wait on an unspawnable agent.
continue
else:
try:
from egg_contracts.agent_roles import (
get_roles_for_phase as _get_roles_for_phase,
)

for r in _get_roles_for_phase(
phase,
include_reviewers=True,
repo=pipeline.repo,
has_contract=getattr(pipeline, "has_contract", True),
):
try:
agent_roles.append(AgentRole(r.value))
except ValueError:
continue
except Exception as exc: # noqa: BLE001
logger.warning(
"restart_phase: failed to derive default roster fallback",
pipeline_id=pipeline_id,
phase=phase,
error=str(exc),
)

if not agent_roles:
return make_error_response(
f"No agents found in phase {phase} to restart", status_code=400
)

logger.info(
"restart_phase: phase_exec.agents empty, derived roster from pipeline config",
pipeline_id=pipeline_id,
phase=phase,
agent_roles=[r.value for r in agent_roles],
)

# 2. Snapshot container IDs for teardown outside the lock
Expand Down
166 changes: 166 additions & 0 deletions orchestrator/tests/test_restart_phase.py
Original file line number Diff line number Diff line change
Expand Up @@ -1025,3 +1025,169 @@ def test_restart_phase_calls_reset_agent_for_each_role(
assert response.status_code == 200
reset_calls = {call.args[0] for call in mock_hm.reset_agent.call_args_list}
assert reset_calls == {"coder", "tester", "documenter"}


# ---------------------------------------------------------------------------
# Issue #2515: empty phase_exec.agents must not wedge restart_phase
# ---------------------------------------------------------------------------


def _make_pipeline_with_empty_phase_agents(
pipeline_id="issue-2515",
phase=PipelinePhase.IMPLEMENT,
*,
active_roles: list[str] | None = None,
):
"""Build a pipeline in CANCELLED state with phase_exec.agents=[].

Reproduces the post-failed-restart state from #2515: a prior
``restart_phase`` cleared ``phase_exec.agents`` (its own clear
step) but the spawn step failed before re-populating it, then
``cancel_task(cleanup=false)`` returned the pipeline to a
restartable status with an empty roster cache.
"""
pipeline = Pipeline(
id=pipeline_id,
issue_number=2515,
repo="owner/repo",
branch=f"egg/{pipeline_id}",
status=PipelineStatus.CANCELLED,
current_phase=phase,
active_roles=active_roles,
)
pipeline.phases = {
phase.value: PhaseExecution(
phase=phase,
status=PipelineStatus.PENDING,
review_cycles=0,
containers=[],
agents=[],
),
}
return pipeline


@pytest.mark.skipif(not _HAS_FLASK, reason="Flask not available")
class TestRestartPhaseEmptyAgentsFallback:
"""Issue #2515: ``restart_phase`` must derive the roster from the
pipeline-level config when ``phase_exec.agents`` is empty.

Without the fallback, a prior failed restart leaves the pipeline
permanently unrecoverable: ``restart_phase`` 400s on the empty
cache and ``start_pipeline`` 409s on the CANCELLED status.
"""

@patch("routes.pipelines.threading.Thread")
@patch("routes.pipelines.get_container_spawner")
@patch("routes.pipelines._resolve_pipeline")
@patch("routes.pipelines.get_repo_path")
def test_empty_agents_falls_back_to_phase_default_roster(
self, mock_repo, mock_resolve, mock_spawner_fn, mock_thread, client
):
mock_repo.return_value = "/repo"
pipeline = _make_pipeline_with_empty_phase_agents()

mock_store = MagicMock()
mock_store.load_pipeline.return_value = pipeline
mock_store.repo_path = Path("/repo")
mock_resolve.return_value = (mock_store, pipeline)

mock_spawner = MagicMock()
mock_spawner_fn.return_value = mock_spawner

response = client.post(
"/api/v1/pipelines/issue-2515/phases/implement/restart",
json={"reason": "Recover from failed prior restart"},
)

assert response.status_code == 200, response.get_json()
data = response.get_json()
agents = data["data"]["agents_to_restart"]
# Implement phase has stable producer roles; reviewers vary by
# repo / has_contract gating, so assert producers are present
# rather than pinning the exact list.
assert "coder" in agents
assert "tester" in agents
assert "documenter" in agents
# Pipeline must transition out of CANCELLED so it is no longer
# stuck.
assert pipeline.status == PipelineStatus.RUNNING

@patch("routes.pipelines.threading.Thread")
@patch("routes.pipelines.get_container_spawner")
@patch("routes.pipelines._resolve_pipeline")
@patch("routes.pipelines.get_repo_path")
def test_empty_agents_uses_active_roles_override_when_set(
self, mock_repo, mock_resolve, mock_spawner_fn, mock_thread, client
):
"""CUSTOM-mode / BABYSIT pipelines persist their roster on
``Pipeline.active_roles``; the fallback must honour it rather
than expanding to the full phase-default roster."""
mock_repo.return_value = "/repo"
pipeline = _make_pipeline_with_empty_phase_agents(
active_roles=["coder", "tester"],
)

mock_store = MagicMock()
mock_store.load_pipeline.return_value = pipeline
mock_store.repo_path = Path("/repo")
mock_resolve.return_value = (mock_store, pipeline)

mock_spawner = MagicMock()
mock_spawner_fn.return_value = mock_spawner

response = client.post(
"/api/v1/pipelines/issue-2515/phases/implement/restart",
json={"reason": "Recover CUSTOM-mode pipeline after failed restart"},
)

assert response.status_code == 200, response.get_json()
data = response.get_json()
assert set(data["data"]["agents_to_restart"]) == {"coder", "tester"}

@patch("routes.pipelines.threading.Thread")
@patch("routes.pipelines.get_container_spawner")
@patch("routes.pipelines._resolve_pipeline")
@patch("routes.pipelines.get_repo_path")
def test_active_roles_set_but_all_unknown_returns_400_not_phase_default(
self, mock_repo, mock_resolve, mock_spawner_fn, mock_thread, client
):
"""Strict parity with ``_run_concurrent_phase``: when
``active_roles`` is set but every entry is unknown to this
orchestrator's ``AgentRole`` (e.g. an in-flight pipeline on a
newer schema after a role removal), the route must NOT silently
expand to the phase-default roster — that would have the route
promise agents the spawn would never produce. The 400 is the
honest signal so the operator can intervene.
"""
mock_repo.return_value = "/repo"
# Build with valid roles to satisfy the validator, then mutate
# the field to inject an unknown value (simulating an older
# pipeline persisted before a role rename / removal).
pipeline = _make_pipeline_with_empty_phase_agents(
active_roles=["coder"],
)
# ``active_roles`` is a plain list field; mutate post-construct
# to bypass ``_validate_active_roles`` (which rejects unknown
# values at write time but cannot guard load-time drift).
pipeline.active_roles = ["__role_removed_in_newer_schema__"]

mock_store = MagicMock()
mock_store.load_pipeline.return_value = pipeline
mock_store.repo_path = Path("/repo")
mock_resolve.return_value = (mock_store, pipeline)

mock_spawner = MagicMock()
mock_spawner_fn.return_value = mock_spawner

response = client.post(
"/api/v1/pipelines/issue-2515/phases/implement/restart",
json={"reason": "All-unknown override edge case"},
)

assert response.status_code == 400, response.get_json()
data = response.get_json()
assert "No agents found" in data["message"]
# Pipeline status must NOT have transitioned — the route should
# have failed before mutating state.
assert pipeline.status == PipelineStatus.CANCELLED
Loading