Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(providers): preserve shared HTTP clients

huanghua016ec7b510ed3f
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.py
index 822a1142f..4f3759634 100644
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@ -5,7 +5,9 @@ ChatLLM is designed specifically for the AgentLoop ReAct cycle.
from __future__ import annotations
+import asyncio
import html
+import inspect
import logging
import os
import re
@@ -298,25 +300,87 @@ class ChatLLM:
)
def close(self) -> None:
- """Best-effort release of the underlying provider HTTP client.
-
- The LangChain adapter (ChatOpenAI and its OpenAI-compatible
- subclasses) owns a pooled ``httpx.Client`` that is not guaranteed to
- be refcount-collected promptly — cyclic references can defer it to a
- GC pass. Long-running callers (swarm workers build one ChatLLM per
- task) must call this when the instance is done with, or sockets
- accumulate in CLOSE-WAIT. Safe to call multiple times; providers
- without a closeable client are a no-op.
+ """Best-effort release of HTTP clients owned by this adapter.
+
+ LangChain may lend multiple adapters the same cached HTTPX clients.
+ Those process-scoped clients must remain open when one ``ChatLLM`` is
+ discarded. Only explicitly marked, Vibe-created clients are closed;
+ adapters without the ownership marker keep the legacy best-effort
+ behavior for compatibility.
"""
+ for label, client in self._close_candidates():
+ close_fn = getattr(client, "aclose", None)
+ if not callable(close_fn):
+ close_fn = getattr(client, "close", None)
+ if not callable(close_fn):
+ continue
+ try:
+ result = close_fn()
+ if inspect.isawaitable(result):
+ self._run_or_schedule_close(result, label)
+ except Exception:
+ logger.debug("ChatLLM.close: failed to close %s", label, exc_info=True)
+
+ async def aclose(self) -> None:
+ """Asynchronously release HTTP clients owned by this adapter."""
+ for label, client in self._close_candidates():
+ close_fn = getattr(client, "aclose", None)
+ if not callable(close_fn):
+ close_fn = getattr(client, "close", None)
+ if not callable(close_fn):
+ continue
+ try:
+ result = close_fn()
+ if inspect.isawaitable(result):
+ await result
+ except Exception:
+ logger.debug("ChatLLM.aclose: failed to close %s", label, exc_info=True)
+
+ def _close_candidates(self) -> list[tuple[str, Any]]:
+ """Return unique clients this wrapper is responsible for closing."""
llm = self._llm
- for attr in ("root_client", "root_async_client", "client"):
- client = getattr(llm, attr, None)
- close_fn = getattr(client, "close", None)
- if callable(close_fn):
- try:
- close_fn()
- except Exception:
- logger.debug("ChatLLM.close: failed to close %s", attr, exc_info=True)
+ if hasattr(llm, "_vibe_owned_http_clients"):
+ candidates = [
+ ("owned_http_client", client)
+ for client in llm._vibe_owned_http_clients
+ ]
+ else:
+ candidates = [
+ (attr, getattr(llm, attr, None))
+ for attr in ("root_client", "root_async_client", "client")
+ ]
+
+ unique: list[tuple[str, Any]] = []
+ seen: set[int] = set()
+ for label, client in candidates:
+ if client is None or id(client) in seen:
+ continue
+ seen.add(id(client))
+ unique.append((label, client))
+ return unique
+
+ @staticmethod
+ def _run_or_schedule_close(awaitable: Any, label: str) -> None:
+ """Consume an async close from either synchronous or async code."""
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ asyncio.run(awaitable)
+ return
+
+ task = loop.create_task(awaitable)
+
+ def _log_failure(done: asyncio.Task[Any]) -> None:
+ try:
+ done.result()
+ except asyncio.CancelledError:
+ return
+ except Exception:
+ logger.debug(
+ "ChatLLM.close: async close failed for %s", label, exc_info=True
+ )
+
+ task.add_done_callback(_log_failure)
def chat(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None, timeout: Optional[int] = None) -> LLMResponse:
"""Call the LLM synchronously.
diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.py
index d132a4025..1fb5f2e1c 100644
--- a/agent/src/providers/llm.py
+++ b/agent/src/providers/llm.py
@@ -265,12 +265,14 @@ if ChatOpenAI is not None:
_vibe_api_key: str = PrivateAttr(default="")
_vibe_ambient_header_names: tuple[str, ...] = PrivateAttr(default=())
_vibe_has_explicit_authorization: bool = PrivateAttr(default=False)
+ _vibe_owned_http_clients: tuple[Any, ...] = PrivateAttr(default=())
def __init__(
self,
*args: Any,
vibe_provider: str | None = None,
vibe_api_key: str | None = None,
+ vibe_owned_http_clients: Sequence[Any] | None = None,
**kwargs: Any,
) -> None:
"""Initialize while retaining the resolved provider name."""
@@ -287,6 +289,7 @@ if ChatOpenAI is not None:
super().__init__(*args, **kwargs)
self._vibe_provider = vibe_provider
self._vibe_api_key = vibe_api_key or ""
+ self._vibe_owned_http_clients = tuple(vibe_owned_http_clients or ())
self._vibe_ambient_header_names = tuple(
name for name in ambient_names if name not in explicit_names
)
@@ -1455,4 +1458,5 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Any
sync_client, async_client = _build_proxy_free_http_clients()
kwargs["http_client"] = sync_client
kwargs["http_async_client"] = async_client
+ kwargs["vibe_owned_http_clients"] = (sync_client, async_client)
return ChatOpenAIWithReasoning(**kwargs)
diff --git a/agent/tests/test_chat_llm_lifecycle.py b/agent/tests/test_chat_llm_lifecycle.py
new file mode 100644
index 000000000..888f30384
--- /dev/null
+++ b/agent/tests/test_chat_llm_lifecycle.py
@@ -0,0 +1,106 @@
+"""Regression tests for provider HTTP-client ownership."""
+
+from __future__ import annotations
+
+import asyncio
+
+from src.providers.chat import ChatLLM
+
+
+class _SyncClient:
+ def __init__(self) -> None:
+ self.close_calls = 0
+
+ def close(self) -> None:
+ self.close_calls += 1
+
+
+class _AsyncClient:
+ def __init__(self) -> None:
+ self.close_calls = 0
+
+ async def aclose(self) -> None:
+ self.close_calls += 1
+
+
+def _wrapper(adapter: object) -> ChatLLM:
+ llm = ChatLLM.__new__(ChatLLM)
+ llm._llm = adapter
+ return llm
+
+
+def test_close_leaves_borrowed_langchain_clients_open() -> None:
+ """A short-lived wrapper must not close LangChain's shared clients."""
+ sync_client = _SyncClient()
+ async_client = _AsyncClient()
+
+ class _Adapter:
+ _vibe_owned_http_clients: tuple[object, ...] = ()
+ root_client = sync_client
+ root_async_client = async_client
+ client = sync_client
+
+ _wrapper(_Adapter()).close()
+
+ assert sync_client.close_calls == 0
+ assert async_client.close_calls == 0
+
+
+def test_close_releases_only_explicitly_owned_clients() -> None:
+ """Proxy-free clients created by Vibe remain instance-owned."""
+ sync_client = _SyncClient()
+ async_client = _AsyncClient()
+
+ class _Adapter:
+ _vibe_owned_http_clients = (sync_client, async_client, sync_client)
+ root_client = object()
+
+ _wrapper(_Adapter()).close()
+
+ assert sync_client.close_calls == 1
+ assert async_client.close_calls == 1
+
+
+def test_close_schedules_owned_async_client_inside_running_loop() -> None:
+ """The synchronous compatibility API must consume async close methods."""
+ async_client = _AsyncClient()
+
+ class _Adapter:
+ _vibe_owned_http_clients = (async_client,)
+
+ async def scenario() -> None:
+ _wrapper(_Adapter()).close()
+ await asyncio.sleep(0)
+
+ asyncio.run(scenario())
+
+ assert async_client.close_calls == 1
+
+
+def test_aclose_awaits_owned_clients() -> None:
+ sync_client = _SyncClient()
+ async_client = _AsyncClient()
+
+ class _Adapter:
+ _vibe_owned_http_clients = (sync_client, async_client)
+
+ asyncio.run(_wrapper(_Adapter()).aclose())
+
+ assert sync_client.close_calls == 1
+ assert async_client.close_calls == 1
+
+
+def test_native_adapter_without_marker_keeps_legacy_cleanup() -> None:
+ """Non-LangChain adapters retain the previous best-effort contract."""
+ client = _SyncClient()
+
+ class _Adapter:
+ pass
+
+ adapter = _Adapter()
+ adapter.root_client = client
+ adapter.client = client
+
+ _wrapper(adapter).close()
+
+ assert client.close_calls == 1
diff --git a/agent/tests/test_llm.py b/agent/tests/test_llm.py
index 4640d16ec..6839c2b8e 100644
--- a/agent/tests/test_llm.py
+++ b/agent/tests/test_llm.py
@@ -553,6 +553,7 @@ class TestDisableHttpProxy:
build_clients.assert_called_once_with()
assert captured["http_client"] is sync_client
assert captured["http_async_client"] is async_client
+ assert captured["vibe_owned_http_clients"] == (sync_client, async_client)
assert "http_socket_options" not in captured
def test_build_llm_leaves_default_transport_when_disabled(self) -> None:
@@ -577,6 +578,7 @@ class TestDisableHttpProxy:
assert "http_client" not in captured
assert "http_async_client" not in captured
+ assert "vibe_owned_http_clients" not in captured
def test_direct_clients_do_not_install_environment_proxy_mounts(self) -> None:
import asyncio