Skip to content

The agent that grows with you

fix(codex): make the post-terminal drain budget a config key (agent.stream_drain_timeout)

teknium1a8c317d483c2
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py
index 44a35410f55..f6100b542f5 100644
--- a/agent/codex_runtime.py
+++ b/agent/codex_runtime.py
@@ -24,7 +24,26 @@ _codex_watchdog_state_var: contextvars.ContextVar[Any | None] = contextvars.Cont
"codex_watchdog_state", default=None
)
-_CODEX_POST_TERMINAL_DRAIN_TIMEOUT_SECONDS = 2.0
+_DEFAULT_STREAM_DRAIN_TIMEOUT = 2.0
+
+
+def _stream_drain_timeout() -> float:
+ """``agent.stream_drain_timeout`` (seconds) — how long the post-terminal SSE drain may block.
+
+ The drain is a courtesy to Relay's finalizer, never a correctness requirement: ``final`` is fully
+ assembled before it starts. A relay that never closes the socket after ``response.completed`` would
+ otherwise wedge the turn until the idle watchdog discards the already-billed response (#103864).
+ ``0`` skips the drain entirely.
+ """
+ try:
+ from hermes_cli.config import load_config_readonly
+ agent_cfg = load_config_readonly().get("agent")
+ value = agent_cfg.get("stream_drain_timeout") if isinstance(agent_cfg, dict) else None
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return max(0.0, float(value))
+ except Exception:
+ pass
+ return _DEFAULT_STREAM_DRAIN_TIMEOUT
def _call_guarded(fn: Callable | None, fail_msg: str, *fail_args: Any, args: tuple = (), kwargs: dict | None = None):
@@ -984,6 +1003,9 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta
def _drain_for_finalizer(event_stream: Any) -> None:
# ``final`` is already assembled; draining only lets Relay run its finalizer. A transport error
# here must NOT discard the completed, already-billed response.
+ budget = _stream_drain_timeout()
+ if budget <= 0:
+ return # the ``finally`` below closes the stream
drained = threading.Event()
def _drain() -> None:
@@ -1002,12 +1024,12 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta
drained.set()
threading.Thread(target=_drain, name="codex-post-terminal-drain", daemon=True).start()
- if drained.wait(_CODEX_POST_TERMINAL_DRAIN_TIMEOUT_SECONDS):
+ if drained.wait(budget):
return
logger.warning(
- "Codex Responses stream remained open %.1fs after a terminal response; closing it and returning the "
- "completed response instead of retrying. %s",
- _CODEX_POST_TERMINAL_DRAIN_TIMEOUT_SECONDS, agent._client_log_context(),
+ "Codex Responses stream remained open %.1fs after a terminal response (agent.stream_drain_timeout); "
+ "closing it and returning the completed response instead of retrying. %s",
+ budget, agent._client_log_context(),
)
_close_event_stream(event_stream)
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 1a1fb6c1719..77ba613e94c 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -107,6 +107,11 @@ DEFAULT_CONFIG = {
# whole call; the OpenAI SDK also retries transient errors (max_retries=2). Set 1 for fast
# failover to fallback providers; raise to tolerate longer provider hiccups.
"api_max_retries": 3,
+ # Seconds the Codex/Responses stream may keep reading after its terminal frame so the relay
+ # finalizer can run. Relays that never close the SSE socket after response.completed would
+ # otherwise wedge the turn until the idle watchdog discards the already-billed response
+ # (#103864). 0 skips the drain. Well-behaved endpoints close immediately and never wait this long.
+ "stream_drain_timeout": 2.0,
# Empty-response retry guard. Empty retries re-send the full input at full price; this stops
# re-billing deterministic empties (unsignaled refusals, zero output tokens) while failing
# open on ambiguous evidence (missing usage, any tokens, model/provider change).
diff --git a/tests/agent/test_run_agent_codex_responses.py b/tests/agent/test_run_agent_codex_responses.py
index 9ad27176624..08254634323 100644
--- a/tests/agent/test_run_agent_codex_responses.py
+++ b/tests/agent/test_run_agent_codex_responses.py
@@ -1128,7 +1128,7 @@ def test_run_codex_stream_bounds_post_terminal_drain(monkeypatch):
return _HeldOpenAfterTerminalStream()
agent.client = SimpleNamespace(responses=SimpleNamespace(create=_fake_create))
- monkeypatch.setattr(codex_runtime, "_CODEX_POST_TERMINAL_DRAIN_TIMEOUT_SECONDS", 0.01)
+ monkeypatch.setattr(codex_runtime, "_stream_drain_timeout", lambda: 0.01)
started = time.monotonic()
response = agent._run_codex_stream(_codex_request_kwargs())
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index e4dd3a48a4c..626dc013c9f 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -1267,6 +1267,7 @@ Hermes has separate timeout layers for streaming, plus a stale detector for non-
| Stale stream detection | 180s | Raised to a 900s ceiling (`agent.local_stream_stale_timeout`) | `HERMES_STREAM_STALE_TIMEOUT` |
| Stale non-stream detection | 90s | Auto-disabled when left implicit | `providers.<id>.stale_timeout_seconds` or `HERMES_API_CALL_STALE_TIMEOUT` |
| API call (non-streaming) | 1800s | Unchanged | `providers.<id>.request_timeout_seconds` / `timeout_seconds` or `HERMES_API_TIMEOUT` |
+| Post-terminal stream drain (Codex/Responses) | 2s | Unchanged | `agent.stream_drain_timeout` |
The **socket read timeout** controls how long httpx waits for the next chunk of data from the provider. Local LLMs can take minutes for prefill on large contexts before producing the first token, so Hermes raises this to 30 minutes when it detects a local endpoint. If you explicitly set `HERMES_STREAM_READ_TIMEOUT`, that value is always used regardless of endpoint detection.
@@ -1274,6 +1275,8 @@ The **stale stream detection** kills connections that receive SSE keep-alive pin
The **stale non-stream detection** kills non-streaming calls that produce no response for too long. By default Hermes disables this on local endpoints to avoid false positives during long prefills. If you explicitly set `providers.<id>.stale_timeout_seconds`, `providers.<id>.models.<model>.stale_timeout_seconds`, or `HERMES_API_CALL_STALE_TIMEOUT`, that explicit value is honored even on local endpoints.
+The **post-terminal stream drain** bounds how long a Codex/Responses stream keeps reading after its terminal `response.completed` frame (a courtesy so the relay finalizer can run). Some relays never close the SSE socket after the terminal frame; without a bound the turn wedged until the stale-stream watchdog fired and discarded the already-billed response, then retried. After `agent.stream_drain_timeout` seconds the stream is closed and the completed response is returned. Endpoints that close the connection normally finish the drain immediately and never wait this long; set `0` to skip the drain entirely.
+
This budget bounds every non-streaming call. A provider that accepts a request and then goes silent — connection held open, no bytes, no error — is aborted at the stale timeout and retried, rather than hanging until the much longer socket read timeout (or, for an unattended cron run, until something external kills the process).
The periodic provider-wait notice appears only after at least **60 seconds of silence**. The Codex Responses **waiting status** describes silence, not total generation time: active stream events (including reasoning) keep it quiet. If events stop, it reports time without stream events instead of claiming no response has arrived; the notice clears when events resume. When a reconnect starts a fresh first-event watchdog phase, the waiting status follows that phase. This display behavior does not extend the separate wall-clock stale-call budget or change watchdog timeouts. The status is shown once per silence (after 60s), in neutral wording that names the wait phase (`waiting for the first provider event` vs `provider stream active; Ns without stream events`) and the watchdog that would reconnect (`TTFB`, `stream idle`, or `wall-clock stale`) with the seconds left before it fires; it is rewritten only when the phase changes or that deadline is near, not on every 30s liveness heartbeat. Chat-completion streams follow the same rule (`waiting for the first stream chunk` / `stream open; Ns without stream output`, `stream stale` watchdog) and likewise clear their silence notice promptly when chunks resume, without replacing a local model-loading status.