Skip to content

The agent that grows with you

fix(agent): keep Codex first-progress deadline attempt-local

JoaoMarcos4448b300843e43
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 9a1f83e7d7a..cd6fbe50b75 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -1124,6 +1124,7 @@ class _NonStreamWatchdogs:
idle_enabled: bool
idle_timeout: float
idle_requires_progress: bool
+ progress_timeout: float = 0.0
def _resolve_nonstream_watchdogs(agent, api_kwargs: dict) -> _NonStreamWatchdogs:
@@ -1209,12 +1210,13 @@ def _resolve_nonstream_watchdogs(agent, api_kwargs: dict) -> _NonStreamWatchdogs
# default for unset AND unparseable values, so both count as implicit.
idle_explicit = env_float("HERMES_CODEX_EVENT_STALE_TIMEOUT_SECONDS", -1.0) != -1.0
idle_timeout = env_float("HERMES_CODEX_EVENT_STALE_TIMEOUT_SECONDS", idle_default)
+ progress_gated = codex and openai_codex_backend and codex_floor > 0 and not idle_explicit
return _NonStreamWatchdogs(stale_timeout=stale_timeout, codex=codex, est_tokens=est_tokens,
ttfb_enabled=ttfb_enabled, ttfb_timeout=ttfb_timeout, idle_enabled=codex and idle_timeout > 0,
- idle_timeout=idle_timeout,
- idle_requires_progress=(
- codex and openai_codex_backend and codex_floor > 0 and not idle_explicit
- ))
+ idle_timeout=idle_timeout, idle_requires_progress=progress_gated,
+ # A lifecycle frame proves transport liveness, not model progress. Bound that phase
+ # from the physical-attempt start; events cannot restart the grace period.
+ progress_timeout=HIGH_EFFORT_SILENCE_FLOOR_SECONDS if progress_gated else 0.0)
def _codex_silent_hang_hint(agent, api_kwargs: dict) -> Optional[str]:
diff --git a/agent/chat_completion_nonstream.py b/agent/chat_completion_nonstream.py
index 8d12aff8db6..f43fa87d17e 100644
--- a/agent/chat_completion_nonstream.py
+++ b/agent/chat_completion_nonstream.py
@@ -129,9 +129,12 @@ class _NonStreamRequest:
wd = self.wd
try:
last_event_ts, last_progress_ts, retry_started_ts = self._codex_watchdog_snapshot()
- activity_ts = retry_started_ts if retry_started_ts is not None else last_event_ts
- # Only undo a notice this request owns, promptly rather than at the
- # next heartbeat: reasoning callbacks do not reset the CLI spinner.
+ pre_progress = bool(wd.progress_timeout and last_event_ts is not None and last_progress_ts is None)
+ attempt_started_ts = retry_started_ts if retry_started_ts is not None else self.call_start
+ activity_ts = attempt_started_ts if pre_progress else (
+ last_event_ts if last_event_ts is not None else retry_started_ts)
+ # Lifecycle chatter is not progress: once pre-progress begins it must not
+ # clear/reset this notice. Real progress changes phase and clears it.
if (self.wait_notice_started_ts is not None and activity_ts is not None
and activity_ts > self.wait_notice_started_ts):
self.agent._emit_wait_notice("")
@@ -147,7 +150,9 @@ class _NonStreamRequest:
if retry_started_ts is not None else "waiting for provider response")
return
phase = "first_event"
- if retry_started_ts is not None:
+ if pre_progress:
+ phase = "pre_progress"
+ elif retry_started_ts is not None:
phase = "reconnect"
elif last_event_ts is not None:
phase = "post_event"
@@ -156,7 +161,7 @@ class _NonStreamRequest:
last_event_ts=last_event_ts, last_progress_ts=last_progress_ts,
retry_started_ts=retry_started_ts,
call_start=self.call_start, idle_enabled=wd.idle_enabled, idle_timeout=wd.idle_timeout,
- idle_requires_progress=wd.idle_requires_progress,
+ idle_requires_progress=wd.idle_requires_progress, progress_timeout=wd.progress_timeout,
elapsed=elapsed)
# One neutral notice per silence; repeating it every heartbeat made
# healthy long calls read as provider trouble (#92550).
@@ -189,6 +194,21 @@ class _NonStreamRequest:
f"(TTFB threshold: {int(wd.ttfb_timeout)}s)"
+ (f". {silent_hint}" if silent_hint else ""))
+ def _progress_kill(self, elapsed: float) -> None:
+ """The stream opened, but this physical attempt never made model progress."""
+ agent, wd = self.agent, self.wd
+ h.logger.warning("Codex stream produced lifecycle events but no substantive model progress "
+ "for %.0fs (threshold %.0fs, model=%s, context=~%s tokens). Reconnecting.",
+ elapsed, wd.progress_timeout, self._model(), f"{wd.est_tokens:,}")
+ agent._buffer_diagnostic_status(
+ f"⚠️ Codex stream opened but made no model progress for {int(elapsed)}s "
+ f"(model: {self._model()}). Reconnecting.")
+ self._abort_request("codex_progress_kill")
+ agent._touch_activity(f"codex stream killed after {int(elapsed)}s without model progress")
+ self._await_worker_after_kill(
+ f"Codex stream produced no substantive model progress for {int(elapsed)}s "
+ f"(progress threshold: {int(wd.progress_timeout)}s)")
+
def _idle_kill(self, event_stale_elapsed: float) -> None:
"""SSE events stopped after the phase-specific idle arm point.
@@ -263,13 +283,14 @@ class _NonStreamRequest:
elapsed = now - self.call_start
self._emit_wait_notice(elapsed, heartbeat=poll_count % 100 == 0)
last_event_ts, last_progress_ts, retry_started_ts = self._codex_watchdog_snapshot()
- retry_ttfb_elapsed = now - retry_started_ts if retry_started_ts is not None else None
- if wd.ttfb_enabled and retry_ttfb_elapsed is not None and retry_ttfb_elapsed > wd.ttfb_timeout:
- self._ttfb_kill(retry_ttfb_elapsed)
+ attempt_started_ts = retry_started_ts if retry_started_ts is not None else self.call_start
+ attempt_elapsed = now - attempt_started_ts
+ if (wd.ttfb_enabled and last_event_ts is None and attempt_elapsed > wd.ttfb_timeout):
+ self._ttfb_kill(attempt_elapsed)
break
- if (retry_started_ts is None and wd.ttfb_enabled
- and elapsed > wd.ttfb_timeout and last_event_ts is None):
- self._ttfb_kill(elapsed)
+ if (wd.progress_timeout > 0 and last_event_ts is not None and last_progress_ts is None
+ and attempt_elapsed > wd.progress_timeout):
+ self._progress_kill(attempt_elapsed)
break
idle_elapsed = now - last_event_ts if last_event_ts is not None else None
if (retry_started_ts is None and wd.idle_enabled and idle_elapsed is not None
diff --git a/agent/chat_completion_wait_notice.py b/agent/chat_completion_wait_notice.py
index 20b47b1f290..5fc15959ccf 100644
--- a/agent/chat_completion_wait_notice.py
+++ b/agent/chat_completion_wait_notice.py
@@ -22,6 +22,7 @@ _PHASE_TEXT = {
# Codex Responses (non-stream request path)
"first_event": "{n}s waiting for the first provider event",
"reconnect": "{n}s waiting for the first provider event after reconnect",
+ "pre_progress": "provider stream open; {n}s without substantive model progress",
"post_event": "provider stream active; {n}s without stream events",
# Chat-completions streaming path
"first_chunk": "{n}s waiting for the first stream chunk",
@@ -43,18 +44,19 @@ def wait_notice_text(model: str, silence_secs: float, phase: str,
def codex_watchdog_deadline(*, stale_timeout: float, ttfb_enabled: bool, ttfb_timeout: float,
last_event_ts: Optional[float], last_progress_ts: Optional[float],
retry_started_ts: Optional[float], call_start: float, idle_enabled: bool,
- idle_timeout: float, idle_requires_progress: bool, elapsed: float) -> Optional[tuple[str, float]]:
+ idle_timeout: float, idle_requires_progress: bool, elapsed: float,
+ progress_timeout: float = 0.0) -> Optional[tuple[str, float]]:
"""Earliest enabled Codex watchdog as ``(label, seconds_until_it_fires)``; None when
none applies (disabled/infinite, or its deadline already passed)."""
deadlines: list[tuple[str, float]] = []
if math.isfinite(stale_timeout):
deadlines.append(("wall-clock stale", stale_timeout))
- if retry_started_ts is not None:
+ attempt_offset = max(0.0, retry_started_ts - call_start) if retry_started_ts is not None else 0.0
+ if last_event_ts is None:
if ttfb_enabled and math.isfinite(ttfb_timeout):
- deadlines.append(("TTFB", max(0.0, retry_started_ts - call_start) + ttfb_timeout))
- elif last_event_ts is None:
- if ttfb_enabled and math.isfinite(ttfb_timeout):
- deadlines.append(("TTFB", ttfb_timeout))
+ deadlines.append(("TTFB", attempt_offset + ttfb_timeout))
+ elif progress_timeout > 0 and last_progress_ts is None:
+ deadlines.append(("first progress", attempt_offset + progress_timeout))
elif (not idle_requires_progress or last_progress_ts is not None) and idle_enabled and math.isfinite(idle_timeout):
deadlines.append(("stream idle", max(0.0, last_event_ts - call_start) + idle_timeout))
if not deadlines:
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py
index 14ba9d17c50..0a0daad7b2c 100644
--- a/agent/codex_runtime.py
+++ b/agent/codex_runtime.py
@@ -1058,14 +1058,22 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta
if getattr(agent, "_last_api_first_chunk_at", None) is None:
agent._last_api_first_chunk_at = now
has_progress = _codex_event_has_content(event)
+ first_event = first_progress = False
if watchdog_state is not None:
with watchdog_state.lock:
- if watchdog_state.retry_started_ts is not None:
- watchdog_state.retry_started_ts = None
- watchdog_state.last_progress_ts = None
+ first_event = watchdog_state.last_event_ts is None
watchdog_state.last_event_ts = now
if has_progress:
+ first_progress = watchdog_state.last_progress_ts is None
watchdog_state.last_progress_ts = now
+ if watchdog_state.phase_aware:
+ watchdog_state.retry_started_ts = None
+ if first_event:
+ logger.info("Codex stream first parsed event at %.3f (attempt=%s/%s, model=%s)",
+ now, attempt + 1, max_stream_retries + 1, model)
+ if first_progress:
+ logger.info("Codex stream first substantive progress at %.3f (attempt=%s/%s, model=%s)",
+ now, attempt + 1, max_stream_retries + 1, model)
agent._touch_activity("receiving stream response")
def _interrupt_or_superseded() -> bool:
@@ -1105,6 +1113,8 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta
# Claim the delta sink for THIS attempt; a newer attempt supersedes this token.
writer_token["value"] = claim_stream_writer(agent)
writer_token["raw_stream"] = _raw_stream
+ logger.info("Codex stream opened at %.3f (attempt=%s/%s, model=%s)",
+ time.time(), attempt + 1, max_stream_retries + 1, model)
def _drain_for_finalizer(event_stream: Any) -> None:
# ``final`` is already assembled; draining only lets Relay run its finalizer. A transport error
@@ -1166,10 +1176,14 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta
if agent._interrupt_requested:
raise InterruptedError("Agent interrupted before Codex stream retry")
if attempt > 0 and watchdog_state is not None and watchdog_state.phase_aware:
- # A physical reconnect has its own no-event TTFB phase. Its first parsed
- # event clears this marker and starts a fresh model-progress phase.
+ # One origin for the whole physical attempt: lifecycle frames may change
+ # diagnostics, but cannot restart the first-progress budget.
with watchdog_state.lock:
watchdog_state.retry_started_ts = time.time()
+ watchdog_state.last_event_ts = None
+ watchdog_state.last_progress_ts = None
+ logger.info("Codex physical stream retry at %.3f (attempt=%s/%s, model=%s)",
+ watchdog_state.retry_started_ts, attempt + 1, max_stream_retries + 1, model)
intercepted_events: list = []
writer_token["value"] = writer_token["raw_stream"] = event_stream = None
writer_token["superseded_logged"] = False
diff --git a/tests/agent/test_codex_ttfb_watchdog.py b/tests/agent/test_codex_ttfb_watchdog.py
index 907b7838cec..318db3ec3ac 100644
--- a/tests/agent/test_codex_ttfb_watchdog.py
+++ b/tests/agent/test_codex_ttfb_watchdog.py
@@ -10,10 +10,11 @@ emitting SSE events.
Parsed-event activity is recorded on the request-local watchdog state;
substantive model progress is recorded separately. For the implicit official
-OpenAI Codex policy on large contexts, lifecycle frames satisfy TTFB without
-arming the short post-progress idle budget. Small requests, explicit overrides,
-and compatible backends retain their first-parsed-event semantics. Raw SSE
-comments are outside this layer.
+OpenAI Codex policy on large contexts, lifecycle frames prove transport liveness
+but do not restart the attempt-local first-progress budget; substantive progress
+moves the attempt into the normal event-idle phase. Small requests, explicit
+overrides, and compatible backends retain their first-parsed-event semantics.
+Raw SSE comments are outside this layer.
"""
from __future__ import annotations
@@ -320,6 +321,53 @@ def test_idle_phase_policy_is_narrow_and_preserves_operator_overrides(
assert watchdogs.est_tokens == input_chars // 4
assert watchdogs.idle_enabled is idle_enabled
assert watchdogs.idle_requires_progress is requires_progress
+ assert (watchdogs.progress_timeout > 0) is requires_progress
+
+
+def test_lifecycle_event_does_not_restart_first_progress_deadline():
+ """The budget belongs to the physical attempt, not to the first lifecycle frame."""
+ from agent import chat_completion_wait_notice as wn
+
+ deadline = wn.codex_watchdog_deadline(
+ stale_timeout=900.0, ttfb_enabled=True, ttfb_timeout=300.0,
+ last_event_ts=280.0, last_progress_ts=None, retry_started_ts=None,
+ call_start=100.0, idle_enabled=True, idle_timeout=120.0,
+ idle_requires_progress=True, progress_timeout=300.0, elapsed=250.0,
+ )
+
+ assert deadline == ("first progress", 50.0)
+
+
+def test_large_codex_lifecycle_only_stream_hits_attempt_progress_budget(tmp_path, monkeypatch):
+ """Lifecycle events may change phase diagnostics, but cannot buy another full grace period."""
+ from agent import chat_completion_helpers as h
+
+ agent = _make_codex_agent(tmp_path, monkeypatch)
+ original = h._resolve_nonstream_watchdogs
+
+ def resolve(agent, kwargs):
+ wd = original(agent, kwargs)
+ wd.ttfb_timeout = 0.9
+ wd.progress_timeout = 0.9
+ return wd
+
+ monkeypatch.setattr(h, "_resolve_nonstream_watchdogs", resolve)
+ closes = []
+
+ def stream_attempt():
+ time.sleep(0.7)
+ yield SimpleNamespace(type="response.created")
+ while getattr(agent, "_active_codex_stream_request_token", None) is not None:
+ time.sleep(0.02)
+ raise ConnectionError("retired lifecycle-only stream")
+
+ _install_codex_event_stream(agent, monkeypatch, stream_attempt, closes)
+ started = time.monotonic()
+ with pytest.raises(TimeoutError, match="no substantive model progress"):
+ h.interruptible_api_call(agent, {"model": "gpt-5.6-sol", "input": "x" * 40_004})
+
+ assert time.monotonic() - started < 1.5
+ assert "codex_progress_kill" in closes
@pytest.mark.parametrize(