Skip to content

The agent that grows with you

fix(agent): release_clients() closes the Codex app-server session too

teknium173959315455f
diff --git a/run_agent.py b/run_agent.py
index 43ab361f075..73208e32274 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -942,6 +942,9 @@ class AIAgent(
# and a cross-thread close can release TLS FDs under a still-unwinding worker.
_quietly(self._drop_shared_client, lambda c: self._retire_shared_openai_client(c, reason="cache_evict"))
self._close_request_clients("cache_evict")
+ # The Codex app-server child is an LLM client, not session tool state: the evicted instance is popped
+ # from the cache and a rebuilt agent spawns its own child, so an unclosed one leaks for the gateway's life.
+ _quietly(self._close_codex_session)
def close(self) -> None:
"""Release every resource this agent holds (idempotent); each phase is guarded so one failure never
diff --git a/tests/agent/test_codex_app_server_lifecycle.py b/tests/agent/test_codex_app_server_lifecycle.py
index 3e784ccaafc..8f41ed633e8 100644
--- a/tests/agent/test_codex_app_server_lifecycle.py
+++ b/tests/agent/test_codex_app_server_lifecycle.py
@@ -80,3 +80,19 @@ def test_close_without_codex_session_is_a_noop(monkeypatch):
agent.close()
assert getattr(agent, "_codex_session", None) is None
+
+
+def test_release_clients_releases_codex_app_server_session():
+ """Gateway cache eviction (#72548, #66671) pops the agent and soft-releases it via release_clients();
+ a rebuilt agent spawns its own app-server child, so the evicted one must be closed here too — and
+ repeated release/close must not re-close it."""
+ agent = _bare_agent("test-codex-evict")
+ codex_session = _FakeCodexSession(raises=True)
+ agent._codex_session = codex_session
+ agent._session_messages = []
+
+ agent.release_clients()
+ agent.release_clients()
+
+ assert codex_session.close_calls == 1
+ assert agent._codex_session is None