The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(langfuse): stop a collected httpx handler from closing a shared client (#35981)
Yassin Kortam9d589230651a
diff --git a/litellm/integrations/langfuse/langfuse.py b/litellm/integrations/langfuse/langfuse.pyindex 38162d99688..05e7fe99e16 100644--- a/litellm/integrations/langfuse/langfuse.py+++ b/litellm/integrations/langfuse/langfuse.py@@ -128,8 +128,8 @@ class LangFuseLogger:self.langfuse_client = create_mock_langfuse_client()self.is_mock_mode = Trueelse:- http_client: Final = _get_httpx_client()- self.langfuse_client = http_client.client+ self._http_handler: Final = _get_httpx_client()+ self.langfuse_client = self._http_handler.clientself.is_mock_mode = Falseparameters: Final = {diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.pyindex c1421d0f969..d586156b625 100644--- a/litellm/llms/custom_httpx/http_handler.py+++ b/litellm/llms/custom_httpx/http_handler.py@@ -129,6 +129,21 @@ def _default_cached_client_timeout() -> httpx.Timeout:return httpx.Timeout(timeout=configured, connect=HTTP_HANDLER_CONNECT_TIMEOUT_SECONDS)+_CLIENT_REFCOUNT_WHEN_HANDLER_IS_SOLE_REFERRER: Final = 2+++def _handler_may_close_client(client_refcount: int, owns_client: bool) -> bool:+ """+ Whether a handler being finalized may close its client.++ Only when the handler built the client and is still its sole referrer. Finalization+ proves that nothing references the *handler*; it proves nothing about the client, which+ a cached handler may have handed to consumers that outlive it. Callers must read the+ refcount at the call site, since binding the client to a parameter would inflate it.+ """+ return owns_client and client_refcount <= _CLIENT_REFCOUNT_WHEN_HANDLER_IS_SOLE_REFERRER++_STREAMING_ERROR_BODY_READ_TIMEOUT_SECONDS: Final = 5.0_STREAMING_ERROR_BODY_READ_EXECUTOR: Final = concurrent.futures.ThreadPoolExecutor(max_workers=50,@@ -577,14 +592,15 @@ class AsyncHTTPHandler:async def close(self):# Close the client when you're done with it- await self._client.aclose()+ if self._owns_client:+ await self._client.aclose()async def __aenter__(self):return self.clientasync def __aexit__(self):# close the client when exiting- await self._client.aclose()+ await self.close()async def get(self,@@ -893,7 +909,9 @@ class AsyncHTTPHandler:def __del__(self) -> None:try:- asyncio.get_running_loop().create_task(self.close())+ if not _handler_may_close_client(sys.getrefcount(self._client), self._owns_client):+ return+ asyncio.get_running_loop().create_task(self._client.aclose())except Exception:pass@@ -1132,7 +1150,8 @@ class HTTPHandler:def close(self):# Close the client when you're done with it- self._client.close()+ if self._owns_client:+ self._client.close()def get(self,@@ -1375,7 +1394,8 @@ class HTTPHandler:def __del__(self) -> None:try:- self.close()+ if _handler_may_close_client(sys.getrefcount(self._client), self._owns_client):+ self._client.close()except Exception:passdiff --git a/tests/test_litellm/integrations/test_langfuse.py b/tests/test_litellm/integrations/test_langfuse.pyindex 98e5d1f6dd4..63d1aceb2e7 100644--- a/tests/test_litellm/integrations/test_langfuse.py+++ b/tests/test_litellm/integrations/test_langfuse.py@@ -930,3 +930,67 @@ def test_max_langfuse_clients_limit():assert litellm.initialized_langfuse_clients == 2litellm.initialized_langfuse_clients = original_initialized_langfuse_clients+++class _RecordingLangfuse:+ last_parameters: Optional[dict] = None++ def __init__(self, **parameters):+ type(self).last_parameters = parameters+ self.client = MagicMock()+++def _build_langfuse_logger(monkeypatch) -> LangFuseLogger:+ monkeypatch.setenv("LANGFUSE_MOCK", "false")+ monkeypatch.setattr(litellm, "initialized_langfuse_clients", 0)+ with patch("langfuse.Langfuse", _RecordingLangfuse):+ return LangFuseLogger(+ langfuse_public_key="pk-lit5228",+ langfuse_secret="sk-lit5228",+ langfuse_host="https://test.langfuse.com",+ )+++def test_langfuse_sdk_client_survives_httpx_cache_eviction(monkeypatch):+ import gc+ import weakref++ from litellm.caching.llm_caching_handler import LLMClientCache++ from litellm.llms.custom_httpx.http_handler import _get_httpx_client++ monkeypatch.setattr(litellm, "in_memory_llm_clients_cache", LLMClientCache())+ logger = _build_langfuse_logger(monkeypatch)+ sdk_client = _RecordingLangfuse.last_parameters["httpx_client"]++ cached_handler = _get_httpx_client()+ handler_ref = weakref.ref(cached_handler)++ assert sdk_client is logger.langfuse_client+ assert sdk_client is cached_handler.client++ litellm.in_memory_llm_clients_cache = LLMClientCache()+ del cached_handler+ gc.collect()++ assert litellm.in_memory_llm_clients_cache.get_cache("httpx_client") is None+ assert handler_ref() is not None, "logger must keep the handler that owns the client it handed the SDK"+ assert not sdk_client.is_closed+++def test_langfuse_logger_reuses_the_shared_cached_client(monkeypatch):+ import gc++ from litellm.caching.llm_caching_handler import LLMClientCache++ monkeypatch.setattr(litellm, "in_memory_llm_clients_cache", LLMClientCache())++ first = _build_langfuse_logger(monkeypatch)+ second = _build_langfuse_logger(monkeypatch)++ assert first.langfuse_client is second.langfuse_client++ del second+ gc.collect()++ assert not first.langfuse_client.is_closeddiff --git a/tests/test_litellm/llms/custom_httpx/test_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_http_handler.pyindex b4921558ded..86d097c6123 100644--- a/tests/test_litellm/llms/custom_httpx/test_http_handler.py+++ b/tests/test_litellm/llms/custom_httpx/test_http_handler.py@@ -1,10 +1,12 @@import asyncio+import gcimport ioimport osimport pathlibimport sslimport sysimport threading+import weakreffrom unittest.mock import MagicMock, patchimport certifi@@ -18,6 +20,7 @@ sys.path.insert(import litellmfrom litellm.llms.custom_httpx.aiohttp_transport import LiteLLMAiohttpTransportfrom litellm.llms.custom_httpx.http_handler import (+ _CLIENT_REFCOUNT_WHEN_HANDLER_IS_SOLE_REFERRER,AsyncHTTPHandler,HTTPHandler,MaskedHTTPStatusError,@@ -958,3 +961,213 @@ def test_concurrent_sync_heal_creates_exactly_one_replacement():assert seen[0] is seen[1]assert not seen[0].is_closedhandler.close()+++def fresh_llm_client_cache():+ from litellm.caching.llm_caching_handler import LLMClientCache++ previous = getattr(litellm, "in_memory_llm_clients_cache", None)+ litellm.in_memory_llm_clients_cache = LLMClientCache()+ try:+ yield+ finally:+ litellm.in_memory_llm_clients_cache = previous+++def test_sole_referrer_handler_may_close_but_a_sharing_one_may_not():+ from litellm.llms.custom_httpx.http_handler import _handler_may_close_client++ assert _handler_may_close_client(_CLIENT_REFCOUNT_WHEN_HANDLER_IS_SOLE_REFERRER, owns_client=True)+ assert not _handler_may_close_client(_CLIENT_REFCOUNT_WHEN_HANDLER_IS_SOLE_REFERRER + 1, owns_client=True)+ assert not _handler_may_close_client(_CLIENT_REFCOUNT_WHEN_HANDLER_IS_SOLE_REFERRER, owns_client=False)+++def keepalive_server():+ from http.server import BaseHTTPRequestHandler, HTTPServer+ from socketserver import ThreadingMixIn++ class OkRequestHandler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def do_GET(self):+ self.send_response(200)+ self.send_header("Content-Length", "2")+ self.end_headers()+ self.wfile.write(b"ok")++ def log_message(self, format, *args):+ pass++ class ThreadedServer(ThreadingMixIn, HTTPServer):+ daemon_threads = True++ server = ThreadedServer(("127.0.0.1", 0), OkRequestHandler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}/"+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++def test_exclusively_owned_sync_client_pool_is_closed_when_handler_is_collected(keepalive_server):+ handler = HTTPHandler()+ pool = handler._client._transport._pool+ client_ref = weakref.ref(handler._client)+ handler.get(keepalive_server)++ assert pool._connections, "setup failed: no pooled connection to release"++ del handler+ gc.collect()++ assert client_ref() is None+ assert pool._connections == []+++async def test_exclusively_owned_async_client_pool_is_closed_when_handler_is_collected(keepalive_server, monkeypatch):+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "force_ipv4", False)++ handler = AsyncHTTPHandler()+ pool = handler.client._transport._pool+ await handler.get(keepalive_server)++ assert pool._connections, "setup failed: no pooled connection to release"++ del handler+ gc.collect()+ await asyncio.sleep(0.25)++ assert pool._connections == []+++async def test_handed_out_async_client_pool_survives_handler_collection(keepalive_server, monkeypatch):+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "force_ipv4", False)++ handler = AsyncHTTPHandler()+ consumer_client = handler.client+ pool = consumer_client._transport._pool+ await handler.get(keepalive_server)++ assert pool._connections, "setup failed: no pooled connection to observe"++ del handler+ gc.collect()+ await asyncio.sleep(0.25)++ assert pool._connections != []+ assert not consumer_client.is_closed+ await consumer_client.aclose()+++def test_handed_out_sync_client_pool_survives_handler_collection(keepalive_server):+ handler = HTTPHandler()+ consumer_client = handler.client+ pool = consumer_client._transport._pool+ handler.get(keepalive_server)++ assert pool._connections, "setup failed: no pooled connection to observe"++ del handler+ gc.collect()++ assert pool._connections != []+ assert not consumer_client.is_closed+ consumer_client.close()+++def test_sync_close_leaves_caller_supplied_client_open():+ supplied = httpx.Client()+ handler = HTTPHandler(client=supplied)++ handler.close()++ assert not supplied.is_closed+ supplied.close()+++async def test_async_aexit_closes_an_owned_client_but_not_an_assigned_one():+ owning = AsyncHTTPHandler()+ owned = owning.client++ await owning.__aexit__()++ assert owned.is_closed++ borrowing = AsyncHTTPHandler()+ original = borrowing.client+ assigned = httpx.AsyncClient()+ borrowing.client = assigned++ await borrowing.__aexit__()++ assert not assigned.is_closed+ await assigned.aclose()+ await original.aclose()+++async def test_async_close_leaves_assigned_client_open():+ handler = AsyncHTTPHandler()+ owned = handler.client+ assigned = httpx.AsyncClient()+ handler.client = assigned++ await handler.close()++ assert not assigned.is_closed+ await assigned.aclose()+ await owned.aclose()+++def test_client_handed_out_by_sync_cache_survives_eviction_and_collection(fresh_llm_client_cache):+ from litellm.caching.llm_caching_handler import LLMClientCache++ handler = _get_httpx_client()+ consumer_client = handler.client+ handler_ref = weakref.ref(handler)++ assert not consumer_client.is_closed+ assert litellm.in_memory_llm_clients_cache.get_cache("httpx_client") is handler++ litellm.in_memory_llm_clients_cache = LLMClientCache()+ del handler+ gc.collect()++ assert litellm.in_memory_llm_clients_cache.get_cache("httpx_client") is None+ assert handler_ref() is None+ assert not consumer_client.is_closed++ consumer_client.close()+++async def test_client_handed_out_by_async_cache_survives_eviction_and_collection(fresh_llm_client_cache):+ from litellm.caching.llm_caching_handler import LLMClientCache+ from litellm.llms.custom_httpx.http_handler import get_async_httpx_client+ from litellm.types.utils import LlmProviders++ handler = get_async_httpx_client(llm_provider=LlmProviders.OPENAI)+ consumer_client = handler.client+ handler_ref = weakref.ref(handler)++ assert not consumer_client.is_closed++ litellm.in_memory_llm_clients_cache = LLMClientCache()+ del handler+ gc.collect()+ await asyncio.sleep(0.1)++ assert handler_ref() is None+ assert not consumer_client.is_closed++ await consumer_client.aclose()