From 069f44f22a15edc9bba6c0af0e87a8d81550ca89 Mon Sep 17 00:00:00 2001 From: egg Date: Sat, 11 Apr 2026 06:22:53 +0000 Subject: [PATCH 1/6] Fix pipeline failure after BRC consensus when timeout fires first (#1691) --- orchestrator/routes/pipelines.py | 79 ++++ .../tests/test_consensus_timeout_recheck.py | 392 ++++++++++++++++++ 2 files changed, 471 insertions(+) create mode 100644 orchestrator/tests/test_consensus_timeout_recheck.py diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index 89969c7d72..9909925be6 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -6351,12 +6351,32 @@ def _update_agents_complete() -> None: pip = store.load_pipeline(pipeline_id) pe = pip.get_phase_execution(PipelinePhase(phase_str)) completed_container_ids: set[str] = set() + + # Look up proposal commit SHAs from the BRC tracker so we can + # populate agent.commit (issue #1691). + _brc = None + try: + from peer_consensus import get_peer_consensus_tracker as _get_brc + except ImportError: + from ..peer_consensus import get_peer_consensus_tracker as _get_brc # type: ignore[no-redef] + try: + _brc = _get_brc(pipeline_id) + except Exception: + pass + for agent in pe.agents: if agent.status in (StateAgentStatus.RUNNING, StateAgentStatus.FAILED): agent.status = StateAgentStatus.COMPLETE agent.completed_at = datetime.now(UTC) if agent.container_id: completed_container_ids.add(agent.container_id) + # Populate commit SHA from the consensus tracker's proposal + # records. Only producers have SHAs; reviewers get "". + if _brc is not None and not agent.commit: + sha = _brc.get_proposal_commit_sha(agent.role.value) + if sha: + agent.commit = sha + # Also mark containers as exited so the container monitor # doesn't find stale RUNNING entries and mark pipeline FAILED. # See issue #1294. @@ -6789,6 +6809,12 @@ def _wait_remaining(exec_info): timeout=3600, ) except (ContainerNotFoundError, ContainerOperationError): + # Timeout or lost — stop the container so it doesn't + # keep running as an orphan (issue #1691). + try: + docker_client.stop_container(exec_info.container_id, timeout=30) + except Exception: + pass final_info = ContainerInfo( container_id=exec_info.container_id, container_name=f"{pipeline_id}-{exec_info.role.value}", @@ -6812,6 +6838,59 @@ def _wait_remaining(exec_info): combined_logs = "\n".join(all_logs) if has_failures[0]: + # Consensus recheck: consensus may have completed during the + # ThreadPoolExecutor wait window (issue #1691). Without this + # recheck, containers that were force-killed after consensus + # was already confirmed would cause the phase to fail. + try: + _timeout_consensus = executor.check_consensus() + except Exception as e: + logger.warning( + "Consensus recheck after timeout failed, treating as incomplete", + pipeline_id=pipeline_id, + error=str(e), + ) + _timeout_consensus = {"is_complete": False} + + if _timeout_consensus.get("is_complete"): + # Consensus reached during the wait — recover pipeline + if store is not None: + try: + _current_pip = store.load_pipeline(pipeline_id) + if _current_pip.status == PipelineStatus.FAILED: + logger.warning( + "Pipeline externally marked FAILED but consensus is complete — recovering (timeout path)", + pipeline_id=pipeline_id, + ) + with get_pipeline_state_lock(pipeline_id): + _current_pip = store.load_pipeline(pipeline_id) + if _current_pip.status == PipelineStatus.FAILED: + _current_pip.status = PipelineStatus.RUNNING + _current_pip.error = None + store.save_pipeline(_current_pip) + except Exception as recovery_err: + logger.warning( + "External FAILED recovery check failed (timeout path)", + pipeline_id=pipeline_id, + error=str(recovery_err), + ) + + if _emit_event is not None: + _emit_event( + EventType.CONSENSUS_REACHED, + pipeline_id, + data={"elapsed_seconds": elapsed}, + ) + logger.info( + "Consensus reached on recheck after timeout, treating as success", + pipeline_id=pipeline_id, + elapsed_seconds=round(elapsed, 1), + has_failures=has_failures[0], + ) + _update_agents_complete() + _stop_running_containers() + return 0, combined_logs + return 1, combined_logs # After timeout, check the BRC approval matrix for unresolved diff --git a/orchestrator/tests/test_consensus_timeout_recheck.py b/orchestrator/tests/test_consensus_timeout_recheck.py new file mode 100644 index 0000000000..55a51f5b8e --- /dev/null +++ b/orchestrator/tests/test_consensus_timeout_recheck.py @@ -0,0 +1,392 @@ +"""Tests for consensus recheck after timeout fallback (issue #1691). + +When the consensus timeout fires (step 6) and the code falls back to +waiting for containers via ThreadPoolExecutor, consensus may still be +reached during the wait window. If containers are force-killed after +consensus was confirmed, the phase should succeed — not fail due to +exit_code=-1 from timed-out waits. +""" + +from datetime import UTC, datetime +from pathlib import Path +from unittest.mock import MagicMock, patch + +from docker_client import ContainerOperationError +from models import ( + AgentExecution, + AgentExecutionStatus, + AgentRole, + ContainerInfo, + ContainerStatus, + PhaseExecution, + Pipeline, + PipelineConfig, + PipelinePhase, + PipelineStatus, +) +from routes.pipelines import _run_concurrent_phase + + +def _make_concurrent_pipeline(pipeline_id: str = "issue-1691") -> Pipeline: + """Create a pipeline with concurrent_execution enabled.""" + config = PipelineConfig() + for key, val in { + "concurrent_execution": True, + "max_concurrent_agents": 5, + "message_poll_hint_seconds": 30, + "consensus_timeout_minutes": 30, + }.items(): + try: + setattr(config, key, val) + except (AttributeError, ValueError): + config.__dict__[key] = val + + return Pipeline( + id=pipeline_id, + issue_number=1691, + repo="owner/repo", + branch="egg/issue-1691", + status=PipelineStatus.RUNNING, + current_phase=PipelinePhase.IMPLEMENT, + config=config, + ) + + +def _make_execution(role: AgentRole, container_id: str, status=AgentExecutionStatus.RUNNING): + return AgentExecution( + role=role, + status=status, + container_id=container_id, + started_at=datetime.now(UTC), + ) + + +def _make_phase_execution(): + return PhaseExecution( + phase=PipelinePhase.IMPLEMENT, + status=PipelineStatus.RUNNING, + ) + + +_CALL_ARGS = { + "repo_volumes": {}, + "gateway_mode": "public", + "repos": ["owner/repo"], + "sandbox_env": {}, + "certs_volume": None, + "worktree_repo_path": Path("/tmp/test-repo"), +} + + +class TestConsensusTimeoutRecheck: + """Consensus reached during the timeout wait should return exit 0.""" + + @patch("routes.pipelines.time.sleep") + @patch("routes.pipelines.time.monotonic") + @patch("routes.pipelines._emit_event") + @patch("routes.pipelines.get_pipeline_state_lock") + @patch("routes.pipelines._build_agent_prompt", return_value="test prompt") + @patch("concurrent_executor.ConcurrentPhaseExecutor", autospec=False) + def test_timeout_with_consensus_reached_returns_zero( + self, MockExecutor, mock_prompt, mock_lock, mock_emit, mock_monotonic, mock_sleep + ): + """When consensus timeout fires but consensus is reached during the + ThreadPoolExecutor wait, the phase should succeed (exit code 0). + + Reproduces the scenario from issue #1691: + 1. Timeout fires at 30 min (step 6) + 2. Containers wait via ThreadPoolExecutor + 3. Some containers timeout (exit -1) — wait_for_container raises + 4. But consensus IS complete + 5. Recheck should detect consensus and return 0 + """ + # Simulate time: first call returns a value past the 30-min timeout + # so the loop enters step 6 immediately after the first consensus check. + call_count = [0] + + def _monotonic(): + call_count[0] += 1 + # First few calls: past the timeout threshold + return call_count[0] * 2000.0 + + mock_monotonic.side_effect = _monotonic + + executions = [ + _make_execution(AgentRole.CODER, "coder-1"), + _make_execution(AgentRole.TESTER, "tester-1"), + _make_execution(AgentRole.REVIEWER_CODE, "reviewer-1"), + ] + + # All containers initially RUNNING — they haven't exited yet when + # the timeout fires. + container_infos = { + "coder-1": ContainerInfo( + container_id="coder-1", + container_name="issue-1691-coder", + status=ContainerStatus.RUNNING, + exit_code=None, + ), + "tester-1": ContainerInfo( + container_id="tester-1", + container_name="issue-1691-tester", + status=ContainerStatus.RUNNING, + exit_code=None, + ), + "reviewer-1": ContainerInfo( + container_id="reviewer-1", + container_name="issue-1691-reviewer_code", + status=ContainerStatus.RUNNING, + exit_code=None, + ), + } + + pipeline = _make_concurrent_pipeline() + phase_exec = _make_phase_execution() + + mock_store = MagicMock() + mock_pipeline_state = MagicMock() + mock_pipeline_state.get_phase_execution.return_value = phase_exec + mock_pipeline_state.status = PipelineStatus.RUNNING + mock_store.load_pipeline.return_value = mock_pipeline_state + + mock_docker = MagicMock() + mock_docker.get_container_info.side_effect = lambda cid: container_infos.get(cid) + + # Simulate: tester exits cleanly (0), coder and reviewer timeout (-1) + def _wait_side_effect(container_id, timeout=300): + if container_id == "tester-1": + return ContainerInfo( + container_id="tester-1", + container_name="issue-1691-tester", + status=ContainerStatus.EXITED, + exit_code=0, + exited_at=datetime.now(UTC), + ) + # Other containers: wait times out + raise ContainerOperationError(f"Wait timed out for {container_id}") + + mock_docker.wait_for_container.side_effect = _wait_side_effect + mock_docker.stop_container.return_value = ContainerInfo( + container_id="stopped", + container_name="stopped", + status=ContainerStatus.EXITED, + exit_code=137, + ) + + mock_spawner = MagicMock() + mock_spawner.docker = mock_docker + mock_spawner.create_concurrent_spawn_fn.return_value = MagicMock() + + # Consensus: NOT complete on first check (triggers timeout path), + # then IS complete on the recheck after containers exit. + consensus_call_count = [0] + + def _check_consensus(): + consensus_call_count[0] += 1 + if consensus_call_count[0] == 1: + # First check: consensus not yet reached (triggers timeout) + return { + "is_complete": False, + "has_objections": False, + "blocking_agents": ["coder"], + } + # Subsequent checks (recheck after timeout wait): consensus reached + return { + "is_complete": True, + "has_objections": False, + "blocking_agents": [], + } + + mock_executor_instance = MagicMock() + mock_executor_instance.spawn_all.return_value = executions + mock_executor_instance.check_consensus.side_effect = _check_consensus + MockExecutor.return_value = mock_executor_instance + + mock_lock.return_value.__enter__ = MagicMock(return_value=None) + mock_lock.return_value.__exit__ = MagicMock(return_value=False) + + exit_code, logs = _run_concurrent_phase( + pipeline_id="issue-1691", + pipeline=pipeline, + phase="implement", + spawner=mock_spawner, + store=mock_store, + **_CALL_ARGS, + ) + + # The fix: exit code should be 0 because consensus was reached + assert exit_code == 0, ( + f"Expected exit code 0 (consensus reached during timeout wait), got {exit_code}. " + f"Consensus was called {consensus_call_count[0]} times. Logs: {logs}" + ) + + @patch("routes.pipelines.time.sleep") + @patch("routes.pipelines.time.monotonic") + @patch("routes.pipelines._emit_event") + @patch("routes.pipelines.get_pipeline_state_lock") + @patch("routes.pipelines._build_agent_prompt", return_value="test prompt") + @patch("concurrent_executor.ConcurrentPhaseExecutor", autospec=False) + def test_timeout_without_consensus_still_fails( + self, MockExecutor, mock_prompt, mock_lock, mock_emit, mock_monotonic, mock_sleep + ): + """When consensus timeout fires and consensus is NOT reached during + the wait, the phase should still fail (exit code 1). + + Ensures the recheck doesn't accidentally make all timeouts succeed. + """ + call_count = [0] + + def _monotonic(): + call_count[0] += 1 + return call_count[0] * 2000.0 + + mock_monotonic.side_effect = _monotonic + + executions = [ + _make_execution(AgentRole.CODER, "coder-1"), + _make_execution(AgentRole.TESTER, "tester-1"), + ] + + container_infos = { + "coder-1": ContainerInfo( + container_id="coder-1", + container_name="issue-1691-coder", + status=ContainerStatus.RUNNING, + exit_code=None, + ), + "tester-1": ContainerInfo( + container_id="tester-1", + container_name="issue-1691-tester", + status=ContainerStatus.RUNNING, + exit_code=None, + ), + } + + pipeline = _make_concurrent_pipeline() + phase_exec = _make_phase_execution() + + mock_store = MagicMock() + mock_pipeline_state = MagicMock() + mock_pipeline_state.get_phase_execution.return_value = phase_exec + mock_pipeline_state.status = PipelineStatus.RUNNING + mock_store.load_pipeline.return_value = mock_pipeline_state + + mock_docker = MagicMock() + mock_docker.get_container_info.side_effect = lambda cid: container_infos.get(cid) + # All containers timeout + mock_docker.wait_for_container.side_effect = ContainerOperationError("Timed out") + mock_docker.stop_container.return_value = ContainerInfo( + container_id="stopped", + container_name="stopped", + status=ContainerStatus.EXITED, + exit_code=137, + ) + + mock_spawner = MagicMock() + mock_spawner.docker = mock_docker + mock_spawner.create_concurrent_spawn_fn.return_value = MagicMock() + + # Consensus never reached + mock_executor_instance = MagicMock() + mock_executor_instance.spawn_all.return_value = executions + mock_executor_instance.check_consensus.return_value = { + "is_complete": False, + "has_objections": False, + "blocking_agents": ["coder", "tester"], + } + MockExecutor.return_value = mock_executor_instance + + mock_lock.return_value.__enter__ = MagicMock(return_value=None) + mock_lock.return_value.__exit__ = MagicMock(return_value=False) + + exit_code, logs = _run_concurrent_phase( + pipeline_id="issue-1691", + pipeline=pipeline, + phase="implement", + spawner=mock_spawner, + store=mock_store, + **_CALL_ARGS, + ) + + assert exit_code == 1, ( + f"Expected exit code 1 (no consensus after timeout), got {exit_code}. Logs: {logs}" + ) + + @patch("routes.pipelines.time.sleep") + @patch("routes.pipelines.time.monotonic") + @patch("routes.pipelines._emit_event") + @patch("routes.pipelines.get_pipeline_state_lock") + @patch("routes.pipelines._build_agent_prompt", return_value="test prompt") + @patch("concurrent_executor.ConcurrentPhaseExecutor", autospec=False) + def test_timeout_stops_orphaned_containers( + self, MockExecutor, mock_prompt, mock_lock, mock_emit, mock_monotonic, mock_sleep + ): + """Containers that timeout during the wait should be explicitly stopped + to prevent orphaned containers.""" + call_count = [0] + + def _monotonic(): + call_count[0] += 1 + return call_count[0] * 2000.0 + + mock_monotonic.side_effect = _monotonic + + executions = [ + _make_execution(AgentRole.CODER, "coder-1"), + ] + + container_infos = { + "coder-1": ContainerInfo( + container_id="coder-1", + container_name="issue-1691-coder", + status=ContainerStatus.RUNNING, + exit_code=None, + ), + } + + pipeline = _make_concurrent_pipeline() + phase_exec = _make_phase_execution() + + mock_store = MagicMock() + mock_pipeline_state = MagicMock() + mock_pipeline_state.get_phase_execution.return_value = phase_exec + mock_pipeline_state.status = PipelineStatus.RUNNING + mock_store.load_pipeline.return_value = mock_pipeline_state + + mock_docker = MagicMock() + mock_docker.get_container_info.side_effect = lambda cid: container_infos.get(cid) + mock_docker.wait_for_container.side_effect = ContainerOperationError("Timed out") + mock_docker.stop_container.return_value = ContainerInfo( + container_id="coder-1", + container_name="issue-1691-coder", + status=ContainerStatus.EXITED, + exit_code=137, + ) + + mock_spawner = MagicMock() + mock_spawner.docker = mock_docker + mock_spawner.create_concurrent_spawn_fn.return_value = MagicMock() + + mock_executor_instance = MagicMock() + mock_executor_instance.spawn_all.return_value = executions + mock_executor_instance.check_consensus.return_value = { + "is_complete": False, + "has_objections": False, + "blocking_agents": ["coder"], + } + MockExecutor.return_value = mock_executor_instance + + mock_lock.return_value.__enter__ = MagicMock(return_value=None) + mock_lock.return_value.__exit__ = MagicMock(return_value=False) + + _run_concurrent_phase( + pipeline_id="issue-1691", + pipeline=pipeline, + phase="implement", + spawner=mock_spawner, + store=mock_store, + **_CALL_ARGS, + ) + + # Verify stop_container was called for the timed-out container + mock_docker.stop_container.assert_called_with("coder-1", timeout=30) From bf2b684b9e88c90bcbb42b0584196ce3299aa244 Mon Sep 17 00:00:00 2001 From: egg Date: Sat, 11 Apr 2026 06:24:22 +0000 Subject: [PATCH 2/6] Fix checks: apply automated formatting fixes --- orchestrator/routes/pipelines.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index 9909925be6..fcdb19d57c 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -6358,7 +6358,9 @@ def _update_agents_complete() -> None: try: from peer_consensus import get_peer_consensus_tracker as _get_brc except ImportError: - from ..peer_consensus import get_peer_consensus_tracker as _get_brc # type: ignore[no-redef] + from ..peer_consensus import ( + get_peer_consensus_tracker as _get_brc, # type: ignore[no-redef] + ) try: _brc = _get_brc(pipeline_id) except Exception: From a329e833703e6ff267a5161ef2244dc65b3a89b5 Mon Sep 17 00:00:00 2001 From: "egg-reviewer[bot]" <261018737+egg-reviewer[bot]@users.noreply.github.com> Date: Sat, 11 Apr 2026 15:46:31 +0000 Subject: [PATCH 3/6] Address review feedback: filter RECONSTRUCTED_NO_SHA sentinel, add NACK guard to timeout path - Filter RECONSTRUCTED_NO_SHA sentinel from get_proposal_commit_sha() so it never leaks into agent.commit as a garbage SHA value - Add has_unresolved_nacks guard to the timeout consensus recheck path, mirroring the step 5 NACK escalation (creates HITL decision, returns 1) - Hoist peer_consensus import from nested _update_agents_complete() to the enclosing function scope to avoid re-running import machinery under lock - Add tests for NACK-during-timeout and RECONSTRUCTED_NO_SHA filtering --- orchestrator/routes/pipelines.py | 57 ++++- .../tests/test_consensus_timeout_recheck.py | 209 ++++++++++++++++++ 2 files changed, 255 insertions(+), 11 deletions(-) diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index fcdb19d57c..1001721776 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -6342,6 +6342,16 @@ def _stop_running_containers() -> None: except Exception: pass + # Import peer_consensus tracker once at function scope so we don't + # re-run import machinery inside _update_agents_complete under the lock. + _get_brc_tracker = None + try: + from peer_consensus import get_peer_consensus_tracker as _get_brc_tracker + except ImportError: + from ..peer_consensus import ( + get_peer_consensus_tracker as _get_brc_tracker, # type: ignore[no-redef] + ) + def _update_agents_complete() -> None: """Mark all running agents as COMPLETE in pipeline state (consensus path).""" if store is None: @@ -6355,16 +6365,11 @@ def _update_agents_complete() -> None: # Look up proposal commit SHAs from the BRC tracker so we can # populate agent.commit (issue #1691). _brc = None - try: - from peer_consensus import get_peer_consensus_tracker as _get_brc - except ImportError: - from ..peer_consensus import ( - get_peer_consensus_tracker as _get_brc, # type: ignore[no-redef] - ) - try: - _brc = _get_brc(pipeline_id) - except Exception: - pass + if _get_brc_tracker is not None: + try: + _brc = _get_brc_tracker(pipeline_id) + except Exception: + pass for agent in pe.agents: if agent.status in (StateAgentStatus.RUNNING, StateAgentStatus.FAILED): @@ -6376,7 +6381,7 @@ def _update_agents_complete() -> None: # records. Only producers have SHAs; reviewers get "". if _brc is not None and not agent.commit: sha = _brc.get_proposal_commit_sha(agent.role.value) - if sha: + if sha and sha != "RECONSTRUCTED_NO_SHA": agent.commit = sha # Also mark containers as exited so the container monitor @@ -6855,6 +6860,36 @@ def _wait_remaining(exec_info): _timeout_consensus = {"is_complete": False} if _timeout_consensus.get("is_complete"): + # Guard: consensus may be "complete" by quorum but still + # have unresolved NACKs — mirror the step 5 NACK check. + if _timeout_consensus.get("has_unresolved_nacks"): + nack_details = _timeout_consensus.get("unresolved_nacks", []) + nack_summary = _format_nack_summary(nack_details) + logger.warning( + "Consensus complete on timeout recheck but unresolved NACKs remain", + pipeline_id=pipeline_id, + nack_count=len(nack_details), + nack_summary=nack_summary, + ) + try: + pipeline.add_decision( + question=( + f"Consensus reached after timeout but {len(nack_details)} NACK(s) " + f"remain unresolved: {nack_summary}. How to proceed?" + ), + options=["Retry phase", "Accept current state", "Abort phase"], + phase=pipeline.current_phase, + ) + except Exception: + logger.warning( + "Failed to create NACK escalation decision (timeout path)", + exc_info=True, + ) + combined_logs += ( + f"\n--- UNRESOLVED NACKs ({len(nack_details)}) ---\n{nack_summary}" + ) + return 1, combined_logs + # Consensus reached during the wait — recover pipeline if store is not None: try: diff --git a/orchestrator/tests/test_consensus_timeout_recheck.py b/orchestrator/tests/test_consensus_timeout_recheck.py index 55a51f5b8e..bc59632d08 100644 --- a/orchestrator/tests/test_consensus_timeout_recheck.py +++ b/orchestrator/tests/test_consensus_timeout_recheck.py @@ -390,3 +390,212 @@ def _monotonic(): # Verify stop_container was called for the timed-out container mock_docker.stop_container.assert_called_with("coder-1", timeout=30) + + @patch("routes.pipelines.time.sleep") + @patch("routes.pipelines.time.monotonic") + @patch("routes.pipelines._emit_event") + @patch("routes.pipelines.get_pipeline_state_lock") + @patch("routes.pipelines._build_agent_prompt", return_value="test prompt") + @patch("concurrent_executor.ConcurrentPhaseExecutor", autospec=False) + def test_timeout_with_consensus_and_unresolved_nacks_returns_failure( + self, MockExecutor, mock_prompt, mock_lock, mock_emit, mock_monotonic, mock_sleep + ): + """When consensus is complete on timeout recheck but has unresolved + NACKs, the phase should fail (exit code 1) and escalate to HITL. + + Mirrors the step 5 NACK guard — consensus "complete" by quorum does + not mean all feedback was addressed. + """ + call_count = [0] + + def _monotonic(): + call_count[0] += 1 + return call_count[0] * 2000.0 + + mock_monotonic.side_effect = _monotonic + + executions = [ + _make_execution(AgentRole.CODER, "coder-1"), + _make_execution(AgentRole.REVIEWER_CODE, "reviewer-1"), + ] + + container_infos = { + "coder-1": ContainerInfo( + container_id="coder-1", + container_name="issue-1691-coder", + status=ContainerStatus.RUNNING, + exit_code=None, + ), + "reviewer-1": ContainerInfo( + container_id="reviewer-1", + container_name="issue-1691-reviewer_code", + status=ContainerStatus.RUNNING, + exit_code=None, + ), + } + + pipeline = _make_concurrent_pipeline() + phase_exec = _make_phase_execution() + + mock_store = MagicMock() + mock_pipeline_state = MagicMock() + mock_pipeline_state.get_phase_execution.return_value = phase_exec + mock_pipeline_state.status = PipelineStatus.RUNNING + mock_store.load_pipeline.return_value = mock_pipeline_state + + mock_docker = MagicMock() + mock_docker.get_container_info.side_effect = lambda cid: container_infos.get(cid) + mock_docker.wait_for_container.side_effect = ContainerOperationError("Timed out") + mock_docker.stop_container.return_value = ContainerInfo( + container_id="stopped", + container_name="stopped", + status=ContainerStatus.EXITED, + exit_code=137, + ) + + mock_spawner = MagicMock() + mock_spawner.docker = mock_docker + mock_spawner.create_concurrent_spawn_fn.return_value = MagicMock() + + # Consensus: NOT complete first, then complete WITH unresolved NACKs + consensus_call_count = [0] + + def _check_consensus(): + consensus_call_count[0] += 1 + if consensus_call_count[0] == 1: + return { + "is_complete": False, + "has_objections": False, + "blocking_agents": ["coder"], + } + return { + "is_complete": True, + "has_objections": False, + "has_unresolved_nacks": True, + "unresolved_nacks": [ + {"reviewer": "reviewer_code", "producer": "coder", "reason": "Missing tests"}, + ], + "blocking_agents": [], + } + + mock_executor_instance = MagicMock() + mock_executor_instance.spawn_all.return_value = executions + mock_executor_instance.check_consensus.side_effect = _check_consensus + MockExecutor.return_value = mock_executor_instance + + mock_lock.return_value.__enter__ = MagicMock(return_value=None) + mock_lock.return_value.__exit__ = MagicMock(return_value=False) + + exit_code, logs = _run_concurrent_phase( + pipeline_id="issue-1691", + pipeline=pipeline, + phase="implement", + spawner=mock_spawner, + store=mock_store, + **_CALL_ARGS, + ) + + assert exit_code == 1, ( + f"Expected exit code 1 (consensus complete but unresolved NACKs), got {exit_code}. " + f"Logs: {logs}" + ) + assert "UNRESOLVED NACKs" in logs + + +class TestReconstructedNoShaFiltering: + """The RECONSTRUCTED_NO_SHA sentinel must not leak into agent.commit.""" + + @patch("routes.pipelines.time.sleep") + @patch("routes.pipelines.time.monotonic") + @patch("routes.pipelines._emit_event") + @patch("routes.pipelines.get_pipeline_state_lock") + @patch("routes.pipelines._build_agent_prompt", return_value="test prompt") + @patch("concurrent_executor.ConcurrentPhaseExecutor", autospec=False) + def test_reconstructed_no_sha_not_stored_as_commit( + self, MockExecutor, mock_prompt, mock_lock, mock_emit, mock_monotonic, mock_sleep + ): + """When get_proposal_commit_sha returns RECONSTRUCTED_NO_SHA, agent.commit + should remain empty — the sentinel must not be stored as a real SHA.""" + call_count = [0] + + def _monotonic(): + call_count[0] += 1 + return call_count[0] * 2000.0 + + mock_monotonic.side_effect = _monotonic + + executions = [ + _make_execution(AgentRole.CODER, "coder-1"), + ] + + pipeline = _make_concurrent_pipeline() + + # Create a mock agent with no commit set + mock_agent = MagicMock() + mock_agent.status = AgentExecutionStatus.RUNNING + mock_agent.commit = None + mock_agent.container_id = "coder-1" + mock_agent.role = AgentRole.CODER + mock_agent.completed_at = None + + mock_pe = MagicMock() + mock_pe.agents = [mock_agent] + mock_pe.containers = [] + + mock_store = MagicMock() + mock_pipeline_state = MagicMock() + mock_pipeline_state.get_phase_execution.return_value = mock_pe + mock_pipeline_state.status = PipelineStatus.RUNNING + mock_store.load_pipeline.return_value = mock_pipeline_state + + mock_docker = MagicMock() + mock_docker.get_container_info.return_value = ContainerInfo( + container_id="coder-1", + container_name="issue-1691-coder", + status=ContainerStatus.EXITED, + exit_code=0, + exited_at=datetime.now(UTC), + ) + mock_docker.wait_for_container.return_value = ContainerInfo( + container_id="coder-1", + container_name="issue-1691-coder", + status=ContainerStatus.EXITED, + exit_code=0, + exited_at=datetime.now(UTC), + ) + + mock_spawner = MagicMock() + mock_spawner.docker = mock_docker + mock_spawner.create_concurrent_spawn_fn.return_value = MagicMock() + + # BRC tracker returns RECONSTRUCTED_NO_SHA for the coder + mock_brc = MagicMock() + mock_brc.get_proposal_commit_sha.return_value = "RECONSTRUCTED_NO_SHA" + + # Consensus: complete on first check (container exited cleanly) + mock_executor_instance = MagicMock() + mock_executor_instance.spawn_all.return_value = executions + mock_executor_instance.check_consensus.return_value = { + "is_complete": True, + "has_objections": False, + "blocking_agents": [], + } + MockExecutor.return_value = mock_executor_instance + + mock_lock.return_value.__enter__ = MagicMock(return_value=None) + mock_lock.return_value.__exit__ = MagicMock(return_value=False) + + with patch("peer_consensus.get_peer_consensus_tracker", return_value=mock_brc): + _run_concurrent_phase( + pipeline_id="issue-1691", + pipeline=pipeline, + phase="implement", + spawner=mock_spawner, + store=mock_store, + **_CALL_ARGS, + ) + + # The sentinel should NOT have been stored as agent.commit + assert mock_agent.commit != "RECONSTRUCTED_NO_SHA", ( + "RECONSTRUCTED_NO_SHA sentinel was stored as agent.commit" + ) From b8d85c3f60bf336e9280c186480520523b79b6ab Mon Sep 17 00:00:00 2001 From: "egg-reviewer[bot]" <261018737+egg-reviewer[bot]@users.noreply.github.com> Date: Sat, 11 Apr 2026 15:57:19 +0000 Subject: [PATCH 4/6] Strengthen RECONSTRUCTED_NO_SHA test to verify BRC path is exercised Add assert_called_with to confirm the mock BRC tracker was actually invoked during the test, preventing vacuous pass when the mock patch doesn't reach the code path. Also assert agent.commit is None (not just != sentinel) for a stronger postcondition. Addresses re-review suggestion #2 from egg-reviewer. --- orchestrator/tests/test_consensus_timeout_recheck.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/orchestrator/tests/test_consensus_timeout_recheck.py b/orchestrator/tests/test_consensus_timeout_recheck.py index bc59632d08..33b55a117e 100644 --- a/orchestrator/tests/test_consensus_timeout_recheck.py +++ b/orchestrator/tests/test_consensus_timeout_recheck.py @@ -595,7 +595,14 @@ def _monotonic(): **_CALL_ARGS, ) + # Verify the BRC code path was actually exercised — the mock must have + # been called, proving the sentinel filter ran (not a vacuous pass). + mock_brc.get_proposal_commit_sha.assert_called_with(AgentRole.CODER.value) + # The sentinel should NOT have been stored as agent.commit assert mock_agent.commit != "RECONSTRUCTED_NO_SHA", ( "RECONSTRUCTED_NO_SHA sentinel was stored as agent.commit" ) + assert mock_agent.commit is None, ( + "agent.commit should remain None when only a sentinel SHA is available" + ) From 36127e6b3c56be14fa1f84d0d087fb67a8579c65 Mon Sep 17 00:00:00 2001 From: "egg-reviewer[bot]" <261018737+egg-reviewer[bot]@users.noreply.github.com> Date: Sat, 11 Apr 2026 16:09:36 +0000 Subject: [PATCH 5/6] Add NACK guard to step 5 has_failures consensus recheck path --- orchestrator/routes/pipelines.py | 31 +++++ .../tests/test_consensus_timeout_recheck.py | 121 ++++++++++++++++++ 2 files changed, 152 insertions(+) diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index 1001721776..25023ab0fc 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -6625,6 +6625,37 @@ def _update_agents_complete() -> None: final_consensus = {"is_complete": False} if final_consensus.get("is_complete"): + # Guard: consensus may be "complete" by quorum but still + # have unresolved NACKs — mirror the step 5 no-failure + # NACK check and the timeout path NACK check. + if final_consensus.get("has_unresolved_nacks"): + nack_details = final_consensus.get("unresolved_nacks", []) + nack_summary = _format_nack_summary(nack_details) + logger.warning( + "Consensus complete on final recheck but unresolved NACKs remain (has_failures path)", + pipeline_id=pipeline_id, + nack_count=len(nack_details), + nack_summary=nack_summary, + ) + try: + pipeline.add_decision( + question=( + f"Consensus reached but {len(nack_details)} NACK(s) " + f"remain unresolved: {nack_summary}. How to proceed?" + ), + options=["Retry phase", "Accept current state", "Abort phase"], + phase=pipeline.current_phase, + ) + except Exception: + logger.warning( + "Failed to create NACK escalation decision (step 5 has_failures path)", + exc_info=True, + ) + combined_logs += ( + f"\n--- UNRESOLVED NACKs ({len(nack_details)}) ---\n{nack_summary}" + ) + return 1, combined_logs + # Consensus reached after all — recover pipeline if needed if store is not None: try: diff --git a/orchestrator/tests/test_consensus_timeout_recheck.py b/orchestrator/tests/test_consensus_timeout_recheck.py index 33b55a117e..df1bb26a4b 100644 --- a/orchestrator/tests/test_consensus_timeout_recheck.py +++ b/orchestrator/tests/test_consensus_timeout_recheck.py @@ -501,6 +501,127 @@ def _check_consensus(): ) assert "UNRESOLVED NACKs" in logs + @patch("routes.pipelines.time.sleep") + @patch("routes.pipelines.time.monotonic") + @patch("routes.pipelines._emit_event") + @patch("routes.pipelines.get_pipeline_state_lock") + @patch("routes.pipelines._build_agent_prompt", return_value="test prompt") + @patch("concurrent_executor.ConcurrentPhaseExecutor", autospec=False) + def test_step5_has_failures_with_consensus_and_nacks_returns_failure( + self, MockExecutor, mock_prompt, mock_lock, mock_emit, mock_monotonic, mock_sleep + ): + """When containers exit with failures (step 5), consensus is complete on + final recheck, but there are unresolved NACKs, the phase should fail + (exit code 1) and escalate to HITL. + + This mirrors the timeout path NACK guard — step 5's has_failures branch + must also check for unresolved NACKs before returning success. + """ + # Use a short monotonic sequence so step 5 fires (containers exit) + # before the consensus timeout (step 6). + call_count = [0] + + def _monotonic(): + call_count[0] += 1 + # Stay well under the 30-min timeout so step 5 handles exit + return call_count[0] * 5.0 + + mock_monotonic.side_effect = _monotonic + + executions = [ + _make_execution(AgentRole.CODER, "coder-1"), + _make_execution(AgentRole.REVIEWER_CODE, "reviewer-1"), + ] + + # Both containers EXITED — coder with failure, reviewer clean + container_infos = { + "coder-1": ContainerInfo( + container_id="coder-1", + container_name="issue-1691-coder", + status=ContainerStatus.EXITED, + exit_code=1, + exited_at=datetime.now(UTC), + ), + "reviewer-1": ContainerInfo( + container_id="reviewer-1", + container_name="issue-1691-reviewer_code", + status=ContainerStatus.EXITED, + exit_code=0, + exited_at=datetime.now(UTC), + ), + } + + pipeline = _make_concurrent_pipeline() + phase_exec = _make_phase_execution() + + mock_store = MagicMock() + mock_pipeline_state = MagicMock() + mock_pipeline_state.get_phase_execution.return_value = phase_exec + mock_pipeline_state.status = PipelineStatus.RUNNING + mock_store.load_pipeline.return_value = mock_pipeline_state + + mock_docker = MagicMock() + mock_docker.get_container_info.side_effect = lambda cid: container_infos.get(cid) + mock_docker.stop_container.return_value = ContainerInfo( + container_id="stopped", + container_name="stopped", + status=ContainerStatus.EXITED, + exit_code=137, + ) + + mock_spawner = MagicMock() + mock_spawner.docker = mock_docker + mock_spawner.create_concurrent_spawn_fn.return_value = MagicMock() + + # Consensus: NOT complete on first check, then complete WITH + # unresolved NACKs on final recheck (step 5 has_failures path). + consensus_call_count = [0] + + def _check_consensus(): + consensus_call_count[0] += 1 + if consensus_call_count[0] == 1: + return { + "is_complete": False, + "has_objections": False, + "blocking_agents": ["coder"], + } + return { + "is_complete": True, + "has_objections": False, + "has_unresolved_nacks": True, + "unresolved_nacks": [ + { + "reviewer": "reviewer_code", + "producer": "coder", + "reason": "Security concern", + }, + ], + "blocking_agents": [], + } + + mock_executor_instance = MagicMock() + mock_executor_instance.spawn_all.return_value = executions + mock_executor_instance.check_consensus.side_effect = _check_consensus + MockExecutor.return_value = mock_executor_instance + + mock_lock.return_value.__enter__ = MagicMock(return_value=None) + mock_lock.return_value.__exit__ = MagicMock(return_value=False) + + exit_code, logs = _run_concurrent_phase( + pipeline_id="issue-1691", + pipeline=pipeline, + phase="implement", + spawner=mock_spawner, + store=mock_store, + **_CALL_ARGS, + ) + + assert exit_code == 1, ( + f"Expected exit code 1 (consensus complete but unresolved NACKs in has_failures path), " + f"got {exit_code}. Logs: {logs}" + ) + assert "UNRESOLVED NACKs" in logs + class TestReconstructedNoShaFiltering: """The RECONSTRUCTED_NO_SHA sentinel must not leak into agent.commit.""" From a092d398a15898d6215e722498ff69df07d43b36 Mon Sep 17 00:00:00 2001 From: "egg-reviewer[bot]" <261018737+egg-reviewer[bot]@users.noreply.github.com> Date: Sat, 11 Apr 2026 16:20:44 +0000 Subject: [PATCH 6/6] Recompute elapsed time before logging in consensus recheck paths The elapsed variable was computed at the top of the while-loop iteration but used after potentially long ThreadPoolExecutor waits (up to 3600s), causing significantly stale values in event data and log messages. Now recompute elapsed from start_time immediately before use in both step 5 and timeout consensus recheck paths. --- orchestrator/routes/pipelines.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index 25023ab0fc..f1dc44410e 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -6678,16 +6678,17 @@ def _update_agents_complete() -> None: error=str(recovery_err), ) + _elapsed_final = time.monotonic() - start_time if _emit_event is not None: _emit_event( EventType.CONSENSUS_REACHED, pipeline_id, - data={"elapsed_seconds": elapsed}, + data={"elapsed_seconds": _elapsed_final}, ) logger.info( "Consensus reached on final recheck, stopping containers", pipeline_id=pipeline_id, - elapsed_seconds=round(elapsed, 1), + elapsed_seconds=round(_elapsed_final, 1), has_failures=has_failures[0], ) _update_agents_complete() @@ -6943,16 +6944,17 @@ def _wait_remaining(exec_info): error=str(recovery_err), ) + _elapsed_timeout = time.monotonic() - start_time if _emit_event is not None: _emit_event( EventType.CONSENSUS_REACHED, pipeline_id, - data={"elapsed_seconds": elapsed}, + data={"elapsed_seconds": _elapsed_timeout}, ) logger.info( "Consensus reached on recheck after timeout, treating as success", pipeline_id=pipeline_id, - elapsed_seconds=round(elapsed, 1), + elapsed_seconds=round(_elapsed_timeout, 1), has_failures=has_failures[0], ) _update_agents_complete()