Skip to content

The agent that grows with you

fix(auxiliary): the watchdog Timer shuts the attempt stream's socket down instead of closing the stream

Justas Cesnauskasb1aa0a9be0f4
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 8384858b7e6..7e7dc201ba3 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -1160,6 +1160,18 @@ def _parse_codex_final_response(final: Any) -> Tuple[List[str], List[Any], Any]:
return text_parts, tool_calls_raw, usage
+def _attempt_stream_socket(stream: Any) -> Any:
+ """The raw socket under an SDK event stream (``stream.response`` is the ``httpx.Response``;
+ httpcore publishes its connection as the ``network_stream`` extension), or None."""
+ try:
+ extensions = getattr(getattr(stream, "response", None), "extensions", None)
+ network_stream = extensions.get("network_stream") if isinstance(extensions, dict) else None
+ get_extra_info = getattr(network_stream, "get_extra_info", None)
+ return get_extra_info("socket") if callable(get_extra_info) else None
+ except Exception:
+ return None
+
+
def _close_quietly(target: Any, failure_note: Optional[str]) -> None:
"""Call ``target.close()`` if present; a failure is debug-logged under ``failure_note`` (silent when None)."""
close = getattr(target, "close", None)
@@ -1257,9 +1269,32 @@ class _CodexStreamGuard:
self._attempt_stream = None
def close_attempt_stream(self, failure_note: str) -> None:
- """Closes only this attempt's stream — never the process-shared client."""
+ """Wakes only this attempt's stream — never the process-shared client.
+
+ On the owning thread this is a real ``close()``. From any other thread (the watchdog
+ Timer) it only shuts the stream's own socket down: ``Stream.close()`` on an unfinished
+ response ends in ``sock.close()`` (httpx ``Response.close`` → httpcore
+ ``HTTP11Connection.close`` → ``SyncStream.close``), i.e. exactly the stranger-thread FD
+ release ``_close_client_on_timeout`` forbids — the owner is still inside ``SSL_read`` on
+ that descriptor, the kernel hands the number to the next ``open()``, and OpenSSL writes
+ a TLS alert into that file (#70773, #130115). ``shutdown()`` wakes the reader and keeps
+ the FD; the owner does the real close in its ``finally`` (``release_stream``). A stream
+ with no reachable socket (a test double, a non-httpx transport) has no FD this thread
+ could strand, so it is closed as before.
+ """
with self._attempt_stream_lock:
stream = self._attempt_stream
+ if stream is None:
+ return
+ if threading.get_ident() != self._owner_tid:
+ sock = _attempt_stream_socket(stream)
+ if sock is not None:
+ try:
+ from agent.agent_runtime_helpers import _shutdown_socket
+ _shutdown_socket(sock)
+ except Exception:
+ logger.debug("Codex auxiliary: %s", failure_note, exc_info=True)
+ return
_close_quietly(stream, failure_note)
def record_progress(self) -> None:
@@ -1315,8 +1350,9 @@ class _CodexStreamGuard:
except Exception:
logger.debug("Codex auxiliary: client abort during timeout failed", exc_info=True)
# Socket shutdown only wakes a reader on a REAL transport; the owner may be blocked
- # inside the SDK's event stream (or a socketless test double). Closing the
- # attempt-owned stream releases it without touching shared FDs.
+ # inside the SDK's event stream (or a socketless test double). Wake the
+ # attempt-owned stream too — from this thread that is a shutdown of its socket,
+ # never a close (see close_attempt_stream).
self.close_attempt_stream("attempt stream close during stranger-thread timeout failed")
# The aux client cache wraps this same client; drop the entry so the next aux call
# doesn't reuse the dead transport and fail fast.
diff --git a/tests/agent/test_codex_aux_timeout_fd_ownership.py b/tests/agent/test_codex_aux_timeout_fd_ownership.py
index 64922eae2ad..a9febd9eab4 100644
--- a/tests/agent/test_codex_aux_timeout_fd_ownership.py
+++ b/tests/agent/test_codex_aux_timeout_fd_ownership.py
@@ -118,6 +118,73 @@ class TestCodexAuxiliaryTimeoutFdOwnership:
# The owning thread released the FDs on unwind.
assert ("client.close", owner_tid) in events, events
+ def test_timer_thread_never_closes_a_real_sdk_stream(self):
+ """An SDK stream's ``close()`` on an unfinished response ends in ``sock.close()``.
+ From the watchdog Timer that strands the FD under the owner's ``SSL_read``: the next
+ ``open()`` reuses the number and OpenSSL writes a TLS alert into that file (two SQLite
+ headers were clobbered this way on 2026-09-30, #130115). The Timer may only shut the
+ stream's socket down; the stream is closed by the owner."""
+
+ events = []
+ woken = threading.Event()
+
+ class _StreamSock:
+ def settimeout(self, value):
+ pass
+
+ def shutdown(self, how):
+ events.append(("stream.sock.shutdown", threading.get_ident()))
+ woken.set()
+
+ def close(self):
+ events.append(("stream.sock.close", threading.get_ident()))
+
+ stream_sock = _StreamSock()
+
+ class _SdkStream:
+ """Shaped like ``openai.Stream``: ``.response.extensions['network_stream']``."""
+
+ def __init__(self):
+ network_stream = SimpleNamespace(
+ get_extra_info=lambda name: stream_sock if name == "socket" else None)
+ self.response = SimpleNamespace(extensions={"network_stream": network_stream})
+
+ def __iter__(self):
+ assert woken.wait(10), "watchdog did not wake the stalled stream"
+ yield SimpleNamespace(type="response.in_progress")
+
+ def close(self):
+ events.append(("stream.close", threading.get_ident()))
+ stream_sock.close()
+
+ adapter, client_events = _adapter_with_recording_client(_SdkStream())
+ owner_tid = threading.get_ident()
+
+ def _consume(stream, *, model, on_event):
+ del model
+ for event in stream:
+ on_event(event)
+ return SimpleNamespace(output=[], usage=None)
+
+ with (
+ patch("agent.auxiliary_client._AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS", 0.3),
+ patch("agent.auxiliary_client._evict_cached_client_instance"),
+ patch("agent.codex_runtime._consume_codex_event_stream", _consume),
+ pytest.raises(TimeoutError),
+ ):
+ adapter.create(
+ messages=[{"role": "user", "content": "summarize"}],
+ timeout=300,
+ )
+
+ time.sleep(0.2)
+ stranger = [(a, tid) for a, tid in events if tid != owner_tid]
+ assert ("stream.sock.shutdown", stranger[0][1]) in events, events
+ assert all(a == "stream.sock.shutdown" for a, _ in stranger), f"stranger-thread FD release: {stranger}"
+ # The owner released the stream (and with it the socket) on unwind.
+ assert ("stream.close", owner_tid) in events, events
+ assert ("client.close", owner_tid) in client_events, client_events
+
def test_owner_thread_deadline_hit_closes_directly(self):
"""When the OWNING thread detects the deadline in _check_cancelled,
it may close() directly — no shutdown-only detour required."""