From 8a5b49d86a6fad96e47f07973d9e680f22491e71 Mon Sep 17 00:00:00 2001 From: dsad Date: Mon, 27 Jul 2026 00:56:07 +0300 Subject: [PATCH] fix(auxiliary): never release Codex client FDs from the timeout Timer _CodexCompletionsAdapter.create arms a daemon threading.Timer that calls client.close() when the aux Responses stream exceeds its timeout. On a stalled stream -- the failure the timeout exists for -- the Timer is the only thing that fires, so the close runs on a thread that does not own the in-flight httpx connection. That is the FD-ownership violation the repo already fixed twice on the main transport (#29507, #67142, #70773): close() releases the raw TLS fd while the owner's OpenSSL BIO still caches that integer, the kernel recycles it into the next open() in the process -- a SessionDB or kanban.db handle -- and the owner's unwinding TLS flush writes an application-data record into that database file. agent/auxiliary_client.py had no thread-ownership machinery at all: the guarded twins (_retire_shared_openai_client, _abort_request_openai_client) live in run_agent.py and are unreachable from this adapter, which holds no AIAgent reference. Dispatch on ownership the way chat_completion_helpers already does: from a stranger thread only force_close_tcp_sockets() (shutdown(SHUT_RDWR), which is FD-safe from any thread), and let the owning thread release the FDs when it unwinds. The owner-thread caller (_check_cancelled) keeps closing directly. Cache eviction (#23432) is unchanged. --- agent/auxiliary_client.py | 58 ++++++- .../test_codex_aux_timeout_fd_ownership.py | 160 ++++++++++++++++++ 2 files changed, 214 insertions(+), 4 deletions(-) create mode 100644 tests/agent/test_codex_aux_timeout_fd_ownership.py diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index 8901747332..bd72099382 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -1815,6 +1815,10 @@ class _CodexCompletionsAdapter: progress_deadline = [_start_monotonic + no_progress_timeout] saw_content = threading.Event() timed_out = threading.Event() + # Set only when the timeout WON the attempt (not when the owner + # hard-cancelled first): tells the owning thread's ``finally`` that + # the shared client's FDs still need a real close (#29507). + timeout_release_pending = threading.Event() stream_finished = threading.Event() timeout_timer: List[Optional[threading.Timer]] = [None] # A protected provider call may outlive its owning compression attempt: @@ -1827,6 +1831,9 @@ class _CodexCompletionsAdapter: ) attempt_stream_lock = threading.Lock() attempt_stream: List[Any] = [] + # The thread driving this request owns its transport's file + # descriptors — see the FD-ownership note in _close_client_on_timeout. + owner_tid = threading.get_ident() def _effective_deadline() -> float: with deadline_lock: @@ -1890,12 +1897,39 @@ class _CodexCompletionsAdapter: exc_info=True, ) return - close = getattr(self._client, "close", None) - if callable(close): + # FD-ownership contract (#29507 / #67142 / #70773): only the + # thread driving the request may RELEASE this client's file + # descriptors. This callback has two callers — ``_check_cancelled`` + # on the owning thread, and the daemon watchdog ``threading.Timer``, + # which is a stranger thread. From a stranger thread we may only + # ``shutdown()`` the pooled sockets: ``close()`` releases the raw + # TLS fd while the owner's OpenSSL BIO still caches that integer, + # the kernel recycles it into the next ``open()`` in this process + # (a SessionDB / kanban.db handle), and the owner's unwinding TLS + # flush writes an application-data record into that database file. + # ``shutdown()`` from any thread is FD-safe; ``close()`` is not. + # The owning thread performs the real close in the ``finally`` + # below, which is where the FD release belongs. + timeout_release_pending.set() + if threading.get_ident() == owner_tid: + close = getattr(self._client, "close", None) + if callable(close): + try: + close() + except Exception: + logger.debug("Codex auxiliary: client close during timeout failed", exc_info=True) + else: try: - close() + from agent.agent_runtime_helpers import force_close_tcp_sockets + + shutdown_count = force_close_tcp_sockets(self._client) + logger.info( + "Codex auxiliary client aborted (timeout, tcp_force_closed=%d, " + "deferred_close=stranger_thread)", + shutdown_count, + ) except Exception: - logger.debug("Codex auxiliary: client close during timeout failed", exc_info=True) + logger.debug("Codex auxiliary: client abort during timeout failed", exc_info=True) # The cached auxiliary client wraps this same ``self._client`` # (or *is* a ``CodexAuxiliaryClient`` whose ``_real_client`` is # this instance). After we close the httpx transport above, the @@ -2090,6 +2124,22 @@ class _CodexCompletionsAdapter: _t = timeout_timer[0] if _t is not None: _t.cancel() + # A stranger-thread timeout only shut the sockets down; the FDs + # are still open and this — the owning thread, now unwound — is + # the one context that may release them (#29507). Gated on + # timeout_release_pending, NOT timed_out: in the hard-cancel + # branch (timeout_won=False) the shared client must stay usable + # for other sessions. + if timeout_release_pending.is_set(): + close = getattr(self._client, "close", None) + if callable(close): + try: + close() + except Exception: + logger.debug( + "Codex auxiliary: owner-thread close after timeout failed", + exc_info=True, + ) content = "".join(text_parts).strip() or None diff --git a/tests/agent/test_codex_aux_timeout_fd_ownership.py b/tests/agent/test_codex_aux_timeout_fd_ownership.py new file mode 100644 index 0000000000..1758e13e14 --- /dev/null +++ b/tests/agent/test_codex_aux_timeout_fd_ownership.py @@ -0,0 +1,160 @@ +"""Regression: the timeout watchdog must not release the client's FDs. + +Salvaged from PR #72260 (@necoweb3 / dsad), adapted to the re-armable +no-progress watchdog introduced in PR #99660. + +``close()`` from a thread that does not own the in-flight httpx connection +releases the raw TLS fd while the owner's OpenSSL BIO still caches that +integer. The kernel can hand the same integer to the next ``open()`` in the +process — a SessionDB or kanban.db handle — and the owner's unwinding TLS +flush then writes an application-data record into that database file +(#29507 / #67142 / #70773). ``shutdown()`` is FD-safe from any thread; +``close()`` is not, so it belongs to the owning thread. +""" + +import threading +import time +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +from agent.auxiliary_client import _CodexCompletionsAdapter + + +def _adapter_with_recording_client(stream): + """Build an adapter whose client records (action, thread) events. + + The nested ``_client._transport._pool._connections`` shape is what + ``force_close_tcp_sockets`` traverses. + """ + events = [] + + class _Sock: + def shutdown(self, how): + events.append(("shutdown", threading.get_ident())) + + def close(self): + events.append(("sock.close", threading.get_ident())) + + sock = _Sock() + + class _Conn: + def __init__(self): + self._connection = self + self._network_stream = self + + def get_extra_info(self, name): + return sock if name == "socket" else None + + class _Client: + def __init__(self): + self._transport = SimpleNamespace( + _pool=SimpleNamespace(_connections=[_Conn()]) + ) + + class _LeafClient: + def __init__(self): + self._client = _Client() + self.base_url = "https://chatgpt.com/backend-api/codex" + self.responses = SimpleNamespace(create=lambda **kw: stream) + + def close(self): + events.append(("client.close", threading.get_ident())) + + return _CodexCompletionsAdapter(_LeafClient(), "gpt-5.5"), events + + +class TestCodexAuxiliaryTimeoutFdOwnership: + def test_stalled_stream_timeout_shuts_down_from_timer_and_closes_from_owner(self): + """The watchdog Timer fires on a stalled stream: it may only + shutdown(); the real close() must land on the owning thread in the + adapter's ``finally``.""" + + def _stalled(): + deadline = time.monotonic() + 30.0 + while time.monotonic() < deadline: + time.sleep(0.02) + yield SimpleNamespace(type="response.in_progress") + + adapter, events = _adapter_with_recording_client(_stalled()) + 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, + ) + + # Give the daemon Timer thread a beat to finish its callback. + time.sleep(0.2) + actions = [a for a, _ in events] + # Stranger thread (Timer) only shut the sockets down. + shutdown_tids = {tid for a, tid in events if a == "shutdown"} + assert "shutdown" in actions, events + assert owner_tid not in shutdown_tids, "shutdown ran on owner thread" + # close() from a stranger thread is the corruption vector — banned. + stranger_closes = [ + (a, tid) for a, tid in events + if a in {"client.close", "sock.close"} and tid != owner_tid + ] + assert not stranger_closes, f"stranger-thread FD release: {stranger_closes}" + # The owning thread released the FDs on unwind. + assert ("client.close", owner_tid) in events, 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.""" + + def _one_keepalive_then_block(): + yield SimpleNamespace(type="response.in_progress") + time.sleep(1.0) # past the patched window; owner detects on next event + yield SimpleNamespace(type="response.in_progress") + + adapter, events = _adapter_with_recording_client(_one_keepalive_then_block()) + 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) + + # Cancel the watchdog race by making the Timer window huge relative + # to the owner's per-event check: patch the timer to never fire. + class _NeverTimer: + def __init__(self, *_a, **_k): + self.daemon = True + + def start(self): + pass + + def cancel(self): + pass + + with ( + patch("agent.auxiliary_client._AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS", 0.3), + patch("agent.auxiliary_client._evict_cached_client_instance"), + patch("agent.auxiliary_client.threading.Timer", _NeverTimer), + patch("agent.codex_runtime._consume_codex_event_stream", _consume), + pytest.raises(TimeoutError), + ): + adapter.create( + messages=[{"role": "user", "content": "summarize"}], + timeout=300, + ) + + stranger = [(a, t) for a, t in events if t != owner_tid] + assert not stranger, f"non-owner activity: {stranger}" + assert ("client.close", owner_tid) in events, events