The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(codex): keep post-terminal stream close on reader thread
JoaoMarcos44a1cb9794d858
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.pyindex 64a4e5be145..e7d6f76627e 100644--- a/agent/codex_runtime.py+++ b/agent/codex_runtime.py@@ -1215,55 +1215,119 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltalogger.debug("Codex stream opened (attempt=%s/%s, model=%s)",attempt + 1, max_stream_retries + 1, model)+ def _post_terminal_socket(*streams: Any):+ """Return the raw socket for the current Responses stream, if it can be interrupted safely."""+ from agent.agent_runtime_helpers import _connection_candidates, _socket_from_candidate++ try:+ for stream in streams:+ response = getattr(stream, "response", None)+ if response is None:+ continue+ extensions = getattr(response, "extensions", None) or {}+ network_stream = extensions.get("network_stream") if isinstance(extensions, dict) else None+ for root in (network_stream, getattr(response, "stream", None)):+ if root is None:+ continue+ for candidate in _connection_candidates(root):+ sock = _socket_from_candidate(candidate)+ if sock is not None:+ return sock+ except Exception:+ return None+ return None+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.+ # The final response is already assembled. Keep the finalizer drain on THIS owner thread:+ # moving the reader to a daemon thread and later closing from here releases the FD under that+ # thread's SSL BIO (#127390, same class as #29507). A tiny watchdog may only shutdown() the+ # socket; shutdown wakes this owner-thread read without releasing the descriptor.budget = _stream_drain_timeout()if budget <= 0:- return # the ``finally`` below closes the stream- drained = threading.Event()+ return+ raw_stream = writer_token.get("raw_stream")+ sock = _post_terminal_socket(raw_stream, event_stream)+ if sock is None:+ # Without a shutdown-capable socket a synchronous drain could become unbounded. The drain+ # is only for Relay's finalizer, so skip it and let the owner-thread finally close below.+ with suppress(Exception):+ logger.debug("Codex post-terminal drain skipped: no interruptible stream socket found. %s",+ agent._client_log_context())+ return- def _drain() -> None:- try:- for _ignored in event_stream:- pass- except (*transport_errors, _APIConnectionError) as exc:- if not isinstance(exc, transport_errors):- _log_failure(exc)- logger.warning("Codex Responses stream transport finalization failed after a terminal response was already "- "received; returning the completed response instead of retrying. %s error=%s",- agent._client_log_context(), exc)- except Exception:- logger.debug("Codex Responses stream finalization failed after a terminal response", exc_info=True)- finally:- drained.set()+ timed_out = threading.Event()- threading.Thread(target=_drain, name="codex-post-terminal-drain", daemon=True).start()- if drained.wait(budget):+ def _wake_owner() -> None:+ timed_out.set()+ # FD-safe from a stranger thread: never close here. The owner continues the iteration,+ # observes EOF/error, and performs the real close from the same thread that was reading.+ from agent.agent_runtime_helpers import _shutdown_socket+ _shutdown_socket(sock)++ watchdog = threading.Timer(budget, _wake_owner)+ watchdog.name = "codex-post-terminal-watchdog"+ watchdog.daemon = True+ try:+ watchdog.start()+ except BaseException as exc:+ # If an interrupt lands inside start(), cancel first; if the timer thread already exists,+ # join it before the owner can close the stream.+ watchdog.cancel()+ if watchdog.ident is not None:+ with suppress(Exception):+ watchdog.join()+ if not isinstance(exc, Exception):+ raise+ with suppress(Exception):+ logger.debug("Codex post-terminal watchdog failed to start; skipping finalizer drain", exc_info=True)return- logger.warning(- "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(),- )- # Under a live Relay loop the managed wrapper's close() cannot reach the provider response- # (the loop is still running the drain); close the raw stream captured at stream creation too.- raw_stream = writer_token.get("raw_stream")- if raw_stream is not None and raw_stream is not event_stream:- _close_event_stream(raw_stream)- _close_event_stream(event_stream)- def _close_event_stream(event_stream: Any) -> None:+ try:+ for _ignored in event_stream:+ pass+ except (*transport_errors, _APIConnectionError) as exc:+ # A timeout-triggered shutdown is the expected wakeup, not another provider failure. Other+ # transport failures still get the old diagnostic, but none may discard the completed response.+ if not timed_out.is_set():+ with suppress(Exception):+ if not isinstance(exc, transport_errors):+ _log_failure(exc)+ logger.warning(+ "Codex Responses stream transport finalization failed after a terminal response was already "+ "received; returning the completed response instead of retrying. %s error=%s",+ agent._client_log_context(), exc,+ )+ except Exception:+ with suppress(Exception):+ logger.debug("Codex Responses stream finalization failed after a terminal response", exc_info=True)+ finally:+ # cancel() wins if the budget has not fired; join() also waits for an already-running shutdown+ # callback, preserving shutdown-before-close ordering at the exact timeout boundary.+ watchdog.cancel()+ watchdog.join()++ if timed_out.is_set():+ with suppress(Exception):+ logger.warning(+ "Codex Responses stream remained open %.1fs after a terminal response "+ "(agent.stream_drain_timeout); shut down its socket and completed cleanup on the owner thread. %s",+ budget, agent._client_log_context(),+ )++ def _close_event_stream(event_stream: Any) -> bool:close_fn = getattr(event_stream, "close", None) # None while connect never succeeded+ if not callable(close_fn):+ return Falsetry:- if callable(close_fn):- close_fn()+ close_fn()+ return Trueexcept Exception:# A failed close can leave this connection checked out of the httpx pool while the caller- # reuse-caches the client; poison the slot so close really closes the pool. ``client is None``+ # reuse-caches the client; poison the slot so close really closes the pool. client is None# is the shared primary client — never force-shut.if client is not None:agent._abort_request_openai_client(active_client, reason="codex_stream_close_failed")+ return Falseshow_commentary = getattr(agent, "show_commentary", True)wants_commentary = getattr(agent, "interim_assistant_callback", None) is not None and show_commentaryon_commentary_message = _live(agent._fire_streamed_codex_commentary) if wants_commentary else None@@ -1346,7 +1410,10 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltasum(len(p) for p in agent._codex_streamed_text_parts), agent._client_log_context())return finalfinally:- _close_event_stream(event_stream)+ closed_managed = _close_event_stream(event_stream)+ raw_stream = writer_token.get("raw_stream")+ if not closed_managed and raw_stream is not None and raw_stream is not event_stream:+ _close_event_stream(raw_stream)__all__ = [diff --git a/tests/agent/test_run_agent_codex_responses.py b/tests/agent/test_run_agent_codex_responses.pyindex 2de706e2e2b..a18410b0c6b 100644--- a/tests/agent/test_run_agent_codex_responses.py+++ b/tests/agent/test_run_agent_codex_responses.py@@ -977,8 +977,8 @@ def test_run_codex_stream_bounds_post_terminal_drain(monkeypatch):assert closed.wait(1.0)-def test_run_codex_stream_drain_timeout_closes_raw_stream_when_managed_close_raises(monkeypatch):- """A Relay-managed wrapper whose close() raises (running loop) must not leak the provider stream."""+def test_run_codex_stream_owner_close_falls_back_to_raw_when_managed_close_raises(monkeypatch):+ """If managed close fails, the owner thread must still close the captured raw stream."""import threadingimport agent.codex_runtime as codex_runtime@@ -1039,6 +1039,128 @@ def test_run_codex_stream_drain_timeout_closes_raw_stream_when_managed_close_raiassert raw_closed.wait(1.0)+def test_run_codex_stream_post_terminal_timeout_keeps_close_on_reader_thread(monkeypatch):+ """The timeout thread may shutdown the socket, but only the reader thread may release its FD."""+ import threading++ import agent.codex_runtime as codex_runtime++ agent = _build_agent(monkeypatch)+ owner = threading.current_thread().name+ woken = threading.Event()+ blocked = threading.Event()+ timeline = []++ class _Socket:+ def settimeout(self, value):+ timeline.append(("settimeout", threading.current_thread().name, value))++ def shutdown(self, how):+ timeline.append(("shutdown", threading.current_thread().name, how))+ woken.set()++ sock = _Socket()+ network_stream = SimpleNamespace(get_extra_info=lambda key: sock if key == "socket" else None)+ message_item = SimpleNamespace(+ type="message", status="completed", content=[SimpleNamespace(type="output_text", text="All done.")],+ )+ usage = SimpleNamespace(input_tokens=10, output_tokens=6, total_tokens=16)++ class _HeldOpenAfterTerminalStream:+ def __init__(self):+ self.response = SimpleNamespace(extensions={"network_stream": network_stream})+ self._events = iter([+ SimpleNamespace(type="response.output_item.done", item=message_item),+ SimpleNamespace(+ type="response.completed",+ response=SimpleNamespace(status="completed", usage=usage, id="resp_owner_close"),+ ),+ ])++ def __iter__(self):+ return self++ def __next__(self):+ try:+ return next(self._events)+ except StopIteration:+ blocked.set()+ assert woken.wait(2.0)+ raise++ def close(self):+ timeline.append(("close", threading.current_thread().name, None))++ agent.client = SimpleNamespace(+ responses=SimpleNamespace(create=lambda **_kwargs: _HeldOpenAfterTerminalStream())+ )+ monkeypatch.setattr(codex_runtime, "_stream_drain_timeout", lambda: 0.01)++ response = agent._run_codex_stream(_codex_request_kwargs())++ assert response.id == "resp_owner_close"+ assert blocked.is_set()+ shutdowns = [entry for entry in timeline if entry[0] == "shutdown"]+ closes = [entry for entry in timeline if entry[0] == "close"]+ assert shutdowns and {entry[1] for entry in shutdowns} == {"codex-post-terminal-watchdog"}+ assert closes and {entry[1] for entry in closes} == {owner}+ assert timeline.index(shutdowns[0]) < timeline.index(closes[0])+++def test_run_codex_stream_post_terminal_clean_drain_never_shutdowns(monkeypatch):+ """A provider that closes inside the budget must stay on the ordinary owner-thread path."""+ import threading++ import agent.codex_runtime as codex_runtime++ agent = _build_agent(monkeypatch)+ socket_calls = []+ close_threads = []++ class _Socket:+ def settimeout(self, value):+ socket_calls.append(("settimeout", value))++ def shutdown(self, how):+ socket_calls.append(("shutdown", how))++ sock = _Socket()+ network_stream = SimpleNamespace(get_extra_info=lambda key: sock if key == "socket" else None)+ message_item = SimpleNamespace(+ type="message", status="completed", content=[SimpleNamespace(type="output_text", text="Done.")],+ )+ usage = SimpleNamespace(input_tokens=8, output_tokens=4, total_tokens=12)++ class _ClosingStream:+ def __init__(self):+ self.response = SimpleNamespace(extensions={"network_stream": network_stream})+ self._events = iter([+ SimpleNamespace(type="response.output_item.done", item=message_item),+ SimpleNamespace(+ type="response.completed",+ response=SimpleNamespace(status="completed", usage=usage, id="resp_clean_drain"),+ ),+ ])++ def __iter__(self):+ return self++ def __next__(self):+ return next(self._events)++ def close(self):+ close_threads.append(threading.current_thread().name)++ agent.client = SimpleNamespace(responses=SimpleNamespace(create=lambda **_kwargs: _ClosingStream()))+ monkeypatch.setattr(codex_runtime, "_stream_drain_timeout", lambda: 1.0)++ response = agent._run_codex_stream(_codex_request_kwargs())++ assert response.id == "resp_clean_drain"+ assert socket_calls == []+ assert close_threads+ assert set(close_threads) == {threading.current_thread().name}+def test_codex_preflight_defangs_harmony_tokens_before_and_after_middleware(monkeypatch):"""Both mutable request boundaries must reject literal Harmony wire tokens."""agent = _build_agent(monkeypatch)