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
41 changes: 40 additions & 1 deletion orchestrator/health_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,11 @@ def set_current_phase(self, phase: str) -> None:
with self._lock:
self._current_phase = phase

def get_current_phase(self) -> str | None:
"""Return the phase last set via :meth:`set_current_phase`."""
with self._lock:
return self._current_phase

def _get_heartbeat_threshold(self) -> int:
"""Return the heartbeat timeout threshold for the current phase.

Expand Down Expand Up @@ -768,6 +773,19 @@ def check_brc_progress(self) -> list[dict[str, Any]]:
if agent_state:
agent_state.brc_progress_escalated = False

# Per-iteration breadcrumb so post-mortems can verify the check
# ran and what it observed (#2079).
if fully_acked:
logger.info(
"BRC progress check observed fully-acked producers",
pipeline_id=self._pipeline_id,
producers={
p: round(now - self._fully_acked_first_seen.get(p, now), 1)
for p in fully_acked
},
timeout_seconds=timeout,
)

# Timeout is measured from when the monitor first observed the
# fully-acked state (_fully_acked_first_seen), not from the
# original proposal timestamp, because the monitor may start
Expand All @@ -783,9 +801,20 @@ def check_brc_progress(self) -> list[dict[str, Any]]:
if elapsed <= timeout:
continue

# Skip producers with no agent state (never emitted heartbeat/progress)
# Skip producers with no agent state (never emitted
# heartbeat/progress). This branch is unexpected in
# practice — every producer in the fully-acked set has
# at minimum proposed, which routes through MESSAGE_SENT
# and registers agent_state. Log loudly so future
# post-mortems can audit (#2079).
agent_state = self._agents.get(producer)
if not agent_state:
logger.warning(
"BRC progress timeout but producer has no agent_state",
pipeline_id=self._pipeline_id,
producer=producer,
elapsed_seconds=int(elapsed),
)
continue
if agent_state.brc_progress_escalated:
continue
Expand All @@ -802,11 +831,21 @@ def check_brc_progress(self) -> list[dict[str, Any]]:
}
actions.append(action)

logger.warning(
"BRC progress timeout — escalating",
pipeline_id=self._pipeline_id,
producer=producer,
elapsed_seconds=int(elapsed),
timeout_seconds=timeout,
)

escalation_type = "overseer" if self._config.overseer_enabled else "hitl"
escalation = {
"type": escalation_type,
"agent_id": producer,
"reason": action["reason"],
"alert_type": "brc_confirmation_timeout",
"elapsed_seconds": int(elapsed),
"timestamp": datetime.now(UTC).isoformat(),
}
escalations.append(escalation)
Expand Down
113 changes: 113 additions & 0 deletions orchestrator/routes/pipelines.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,108 @@ def _check_and_respawn_overseer(
return overseer_container_id, overseer_respawn_count


def _send_brc_confirmation_nudge(
escalation: dict[str, Any],
pipeline_id: str,
phase: str | None,
) -> bool:
"""Wake a producer stuck post-ACK with a directed OVERSEER_ALERT (#2079).

Wired as an escalation callback for HealthMonitor's
``brc_confirmation_timeout`` alert. The deterministic detector in
``check_brc_progress`` knows the exact remediation, so we deliver
it directly to the stuck producer rather than relying on the
overseer agent's discretion.

Uses ``OVERSEER_ALERT`` (not ``STATUS`` or ``NUDGE``) because it is
the only message type that appears in **both** the producer's
pre-confirm wait_loop filter
(``CONSENSUS_ACK,CONSENSUS_NACK,CONSENSUS_RE_REVIEW,OVERSEER_ALERT``)
and post-confirm wait_loop filter
(``CONSENSUS_CONFIRMED,CONSENSUS_RE_REVIEW,OVERSEER_ALERT``), so it
wakes the producer regardless of which wait they are blocked on.
A wedged producer is in the ``fully_acked but not confirmed`` set,
which means they are most likely blocked on the pre-confirm wait.
The subject calls out that the alert originated from the
orchestrator's deterministic detector rather than the overseer
agent.

Returns True when a message was posted, False otherwise (wrong
alert type, missing fields, message store unavailable, send error).
"""
if escalation.get("alert_type") != "brc_confirmation_timeout":
return False

producer = escalation.get("agent_id")
if not producer:
return False

elapsed = escalation.get("elapsed_seconds")
# check_brc_progress always populates elapsed_seconds; treat
# missing or non-positive values as a malformed escalation rather
# than rendering "have not confirmed in 0s" in the body.
if elapsed is None or elapsed <= 0:
return False

store_fn = _get_message_store()
if store_fn is None:
return False

# _get_message_store already verified the package is importable;
# Message/MessageType live in the same module so a defensive
# try/except here would only add per-call import overhead.
from message_store import Message, MessageType

body = (
f"You are PROPOSED and fully ACKed but have not confirmed in "
f"{elapsed}s. Call `mcp__brc__confirm` now. If it returns "
"`status='pending_acks'`, read `message` for the guard reason and "
"wait on the prerequisite events instead: `CONSENSUS_PROPOSE` if a "
"producer hasn't proposed (`zero_proposal_producers`), "
"`CONSENSUS_ACK` / `CONSENSUS_RE_REVIEW` if a reviewer's ACK is "
"stale or unresolved. Then retry confirm."
)

try:
msg_store = store_fn()
# Bypass the POST /messages/send route on purpose: this is an
# orchestrator-internal nudge, and we do not want HealthMonitor's
# MESSAGE_SENT handler (rate-limit + HEARTBEAT tracking) to see it.
# Future audit/observability subscribers should be aware this path
# does not emit EventType.MESSAGE_SENT.
msg_store.add_message(
Message(
pipeline_id=pipeline_id,
from_role="orchestrator",
to_role=producer,
message_type=MessageType.OVERSEER_ALERT,
subject="BRC confirmation timeout — call mcp__brc__confirm",
body=body,
phase=phase,
metadata={
"alert_type": "brc_confirmation_timeout",
"elapsed_seconds": elapsed,
"source": "health_monitor",
},
)
)
logger.info(
"Sent BRC confirmation-timeout nudge",
pipeline_id=pipeline_id,
producer=producer,
elapsed_seconds=elapsed,
)
return True
except Exception as send_err:
logger.warning(
"Failed to send BRC confirmation-timeout nudge (non-fatal)",
pipeline_id=pipeline_id,
producer=producer,
error=str(send_err),
)
return False


def _teardown_phase_overseer(
spawner: "ContainerSpawner",
container_id: str,
Expand Down Expand Up @@ -11454,6 +11556,17 @@ def _run_pipeline(pipeline_id: str, repo_path: Path) -> None:
# Sync the phase-aware threshold with the current pipeline phase
health_monitor_instance.set_current_phase(pipeline.current_phase.value)

# Wake stuck producers directly when check_brc_progress fires
# so the deterministic detector actually drives remediation
# instead of relying on the overseer agent's discretion (#2079).
# The closure reads the monitor's current phase at fire time so
# the message records the phase the producer is actually in.
def _on_health_escalation(escalation: dict[str, Any]) -> None:
phase = health_monitor_instance.get_current_phase()
_send_brc_confirmation_nudge(escalation, pipeline_id, phase)

health_monitor_instance.on_escalation(_on_health_escalation)

# Start a background polling thread for time-based tripwires
health_monitor_timer = threading.Event()

Expand Down
Loading
Loading