Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 64 additions & 3 deletions orchestrator/routes/phases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1034,7 +1034,13 @@ def populate_contract(pipeline_id: str) -> tuple[Response, int]:
worktree_path = resolve_worktree_path(pipeline_id, store.repo_path)

# Import and call the populate function
from routes.pipelines import _populate_contract_from_plan
from routes.pipelines import (
_commit_statefiles_to_worktree,
_compute_gateway_mode,
_get_spawner,
_pipeline_identifier,
_populate_contract_from_plan,
)

_populate_contract_from_plan(
repo_path=worktree_path,
Expand All @@ -1043,6 +1049,55 @@ def populate_contract(pipeline_id: str) -> tuple[Response, int]:
issue_number=pipeline.issue_number,
)

# Persist the populated contract back to origin so fresh agent
# spawns (restart_phase, restart_agent, post-cancel restart) pull
# the populated state on respawn rather than the empty contract
# on origin. Without this, the route mutates only the
# orchestrator's local worktree and is unusable as a recovery
# primitive — the implement-start guard would refuse to demote
# to monolithic and the pipeline would wedge. See #2629.
#
# Failures here are fail-soft: ``pushed_to_origin`` in the
# response data tells the caller whether the contract is
# visible to agents. ``False`` means the operator must commit
# and push themselves before respawning.
pushed_to_origin = False
if pipeline.branch and worktree_path != store.repo_path:
try:
identifier = _pipeline_identifier(pipeline.issue_number, pipeline_id)
committed = _commit_statefiles_to_worktree(
worktree_path,
f"Populate contract for {identifier} (#2629)",
pipeline_identifier=identifier,
pipeline_id=pipeline_id,
)
# Skip the push when the commit was a no-op — the helper
# is idempotent and the contents on origin already
# match. An unconditional push would still fast-forward
# to a no-op but would burn a gateway round-trip.
if committed:
gateway_mode, _ = _compute_gateway_mode(pipeline)
push_result = _get_spawner().gateway.push_worktree_branch(
pipeline_id=pipeline_id,
repo_path=str(worktree_path),
branch=pipeline.branch,
mode=gateway_mode,
base_branch=pipeline.base_branch,
)
pushed_to_origin = bool(push_result)
if not pushed_to_origin:
logger.warning(
"populate_contract: push failed (continuing)",
pipeline_id=pipeline_id,
detail=push_result.describe(),
)
except Exception as persist_err: # noqa: BLE001
logger.warning(
"populate_contract: persist to origin failed (continuing)",
pipeline_id=pipeline_id,
error=str(persist_err),
)

# Read back the contract to report counts. Contracts are keyed by
# pipeline_id; the loader's compat shim covers legacy paths.
try:
Expand All @@ -1055,11 +1110,17 @@ def populate_contract(pipeline_id: str) -> tuple[Response, int]:
data={
"phase_count": len(contract.slices),
"task_count": task_count,
"pushed_to_origin": pushed_to_origin,
},
)
except Exception:
# Populate succeeded but we can't read counts — still success
return make_success_response("Contract populated from plan")
# Populate succeeded but we can't read counts — still success.
# Surface ``pushed_to_origin`` so the caller can tell whether
# the recovery is visible to agents.
return make_success_response(
"Contract populated from plan",
data={"pushed_to_origin": pushed_to_origin},
)

except InvalidPipelineIdError:
return make_error_response(
Expand Down
174 changes: 170 additions & 4 deletions orchestrator/tests/test_populate_contract_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,33 @@ def test_populate_function_exception(
assert data["success"] is False
assert "plan draft not found" in data["message"]

@patch("routes.pipelines._get_spawner")
@patch("routes.pipelines._compute_gateway_mode")
@patch("routes.pipelines._commit_statefiles_to_worktree")
@patch("routes.pipelines._populate_contract_from_plan")
@patch("routes.resolve_worktree_path")
@patch("routes.phases.get_state_store_for_pipeline")
def test_success_with_counts_and_issue_number(
self, mock_get_store, mock_resolve_wt, mock_populate, client
self,
mock_get_store,
mock_resolve_wt,
mock_populate,
mock_commit,
mock_gw_mode,
mock_spawner,
client,
):
"""Successful populate returns phase/task counts and forwards issue_number."""
pipeline = _make_pipeline()
mock_store = MagicMock()
mock_store.repo_path = Path("/home/egg/repos/egg")
mock_get_store.return_value = (mock_store, pipeline)
mock_resolve_wt.return_value = Path("/home/egg/.egg-worktrees/issue-42/egg")
mock_commit.return_value = True
mock_gw_mode.return_value = ("public", None)
push_result = MagicMock()
push_result.__bool__.return_value = True
mock_spawner.return_value.gateway.push_worktree_branch.return_value = push_result

# Mock the contract read-back
mock_phase_obj = MagicMock()
Expand All @@ -148,24 +163,40 @@ def test_success_with_counts_and_issue_number(
assert data["success"] is True
assert data["data"]["phase_count"] == 1
assert data["data"]["task_count"] == 2
assert data["data"]["pushed_to_origin"] is True

# Verify populate was called with pipeline.mode (defaults to 'issue')
call_kwargs = mock_populate.call_args[1]
assert str(call_kwargs["pipeline_mode"]) == "issue"
assert call_kwargs["issue_number"] == 42

@patch("routes.pipelines._get_spawner")
@patch("routes.pipelines._compute_gateway_mode")
@patch("routes.pipelines._commit_statefiles_to_worktree")
@patch("routes.pipelines._populate_contract_from_plan")
@patch("routes.resolve_worktree_path")
@patch("routes.phases.get_state_store_for_pipeline")
def test_success_count_readback_fails_still_succeeds(
self, mock_get_store, mock_resolve_wt, mock_populate, client
self,
mock_get_store,
mock_resolve_wt,
mock_populate,
mock_commit,
mock_gw_mode,
mock_spawner,
client,
):
"""When contract read-back fails, still return success without counts."""
"""When contract read-back fails, still return success with pushed_to_origin."""
pipeline = _make_pipeline()
mock_store = MagicMock()
mock_store.repo_path = Path("/home/egg/repos/egg")
mock_get_store.return_value = (mock_store, pipeline)
mock_resolve_wt.return_value = Path("/home/egg/.egg-worktrees/issue-42/egg")
mock_commit.return_value = True
mock_gw_mode.return_value = ("public", None)
push_result = MagicMock()
push_result.__bool__.return_value = True
mock_spawner.return_value.gateway.push_worktree_branch.return_value = push_result

with patch(
"egg_contracts.loader.load_contract",
Expand All @@ -176,7 +207,142 @@ def test_success_count_readback_fails_still_succeeds(
assert resp.status_code == 200
data = json.loads(resp.data)
assert data["success"] is True
assert "data" not in data # No counts on fallback
# Counts are absent (read-back failed) but the persist-result is
# still surfaced so the caller can tell whether agents will see
# the populated contract on respawn (#2629).
assert data["data"] == {"pushed_to_origin": True}

@patch("routes.pipelines._get_spawner")
@patch("routes.pipelines._compute_gateway_mode")
@patch("routes.pipelines._commit_statefiles_to_worktree")
@patch("routes.pipelines._populate_contract_from_plan")
@patch("routes.resolve_worktree_path")
@patch("routes.phases.get_state_store_for_pipeline")
def test_success_commits_and_pushes_contract_to_origin(
self,
mock_get_store,
mock_resolve_wt,
mock_populate,
mock_commit,
mock_gw_mode,
mock_spawner,
client,
):
"""populate_contract commits and pushes the contract so fresh agent
spawns see the populated state on origin (#2629)."""
pipeline = _make_pipeline()
mock_store = MagicMock()
mock_store.repo_path = Path("/home/egg/repos/egg")
mock_get_store.return_value = (mock_store, pipeline)
worktree_path = Path("/home/egg/.egg-worktrees/issue-42/egg")
mock_resolve_wt.return_value = worktree_path
mock_commit.return_value = True
mock_gw_mode.return_value = ("public", None)
push_result = MagicMock()
push_result.__bool__.return_value = True
gateway = mock_spawner.return_value.gateway
gateway.push_worktree_branch.return_value = push_result

with patch(
"egg_contracts.loader.load_contract",
side_effect=Exception("skip"),
):
client.post("/api/v1/pipelines/issue-42/phase/populate-contract")

mock_commit.assert_called_once()
commit_kwargs = mock_commit.call_args.kwargs
assert commit_kwargs["pipeline_identifier"] == 42
assert commit_kwargs["pipeline_id"] == "issue-42"

gateway.push_worktree_branch.assert_called_once_with(
pipeline_id="issue-42",
repo_path=str(worktree_path),
branch="egg/issue-42",
mode="public",
base_branch=pipeline.base_branch,
)

@patch("routes.pipelines._get_spawner")
@patch("routes.pipelines._compute_gateway_mode")
@patch("routes.pipelines._commit_statefiles_to_worktree")
@patch("routes.pipelines._populate_contract_from_plan")
@patch("routes.resolve_worktree_path")
@patch("routes.phases.get_state_store_for_pipeline")
def test_push_failure_reports_pushed_to_origin_false(
self,
mock_get_store,
mock_resolve_wt,
mock_populate,
mock_commit,
mock_gw_mode,
mock_spawner,
client,
):
"""When the push fails, populate still returns success but reports
``pushed_to_origin=False`` so the operator knows the contract is
only on the orchestrator's local worktree (#2629)."""
pipeline = _make_pipeline()
mock_store = MagicMock()
mock_store.repo_path = Path("/home/egg/repos/egg")
mock_get_store.return_value = (mock_store, pipeline)
mock_resolve_wt.return_value = Path("/home/egg/.egg-worktrees/issue-42/egg")
mock_commit.return_value = True
mock_gw_mode.return_value = ("public", None)
gateway = mock_spawner.return_value.gateway
gateway.push_worktree_branch.side_effect = RuntimeError("network down")

mock_phase_obj = MagicMock()
mock_phase_obj.tasks = [MagicMock()]
mock_contract = MagicMock()
mock_contract.slices = [mock_phase_obj]

with patch("egg_contracts.loader.load_contract", return_value=mock_contract):
resp = client.post("/api/v1/pipelines/issue-42/phase/populate-contract")

assert resp.status_code == 200
data = json.loads(resp.data)
assert data["success"] is True
assert data["data"]["pushed_to_origin"] is False
# Counts still come back so the caller can confirm populate worked.
assert data["data"]["task_count"] == 1

@patch("routes.pipelines._get_spawner")
@patch("routes.pipelines._compute_gateway_mode")
@patch("routes.pipelines._commit_statefiles_to_worktree")
@patch("routes.pipelines._populate_contract_from_plan")
@patch("routes.resolve_worktree_path")
@patch("routes.phases.get_state_store_for_pipeline")
def test_commit_noop_skips_push(
self,
mock_get_store,
mock_resolve_wt,
mock_populate,
mock_commit,
mock_gw_mode,
mock_spawner,
client,
):
"""When the commit short-circuits (nothing staged), skip the push —
contents on origin already match (#2629)."""
pipeline = _make_pipeline()
mock_store = MagicMock()
mock_store.repo_path = Path("/home/egg/repos/egg")
mock_get_store.return_value = (mock_store, pipeline)
mock_resolve_wt.return_value = Path("/home/egg/.egg-worktrees/issue-42/egg")
mock_commit.return_value = False
mock_gw_mode.return_value = ("public", None)
gateway = mock_spawner.return_value.gateway

with patch(
"egg_contracts.loader.load_contract",
side_effect=Exception("skip"),
):
resp = client.post("/api/v1/pipelines/issue-42/phase/populate-contract")

assert resp.status_code == 200
data = json.loads(resp.data)
assert data["data"]["pushed_to_origin"] is False
gateway.push_worktree_branch.assert_not_called()

@patch("routes.pipelines._populate_contract_from_plan")
@patch("routes.resolve_worktree_path")
Expand Down
Loading