Skip to content

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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_python_version_ci

Yujong Leefae3d224eb10
diff --cc basedpyright-code-budget.json
index 56f05d462d4,cb3756575f7..dc51a44b5fc
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@@ -42,10 -42,10 +42,10 @@@
"limit": 12
},
"reportIndexIssue": {
- "limit": 25
+ "limit": 24
},
"reportInvalidTypeForm": {
- "limit": 34
+ "limit": 32
},
"reportInvalidTypeVarUse": {
"limit": 2
diff --cc tests/rust-python-harness/shared/tracing/profiler.py
index 44697e7b9f6,55d9818f507..ead856ee58f
--- a/tests/rust-python-harness/shared/tracing/profiler.py
+++ b/tests/rust-python-harness/shared/tracing/profiler.py
@@@ -2,12 -2,11 +2,12 @@@ from __future__ import annotation
import sys
import threading
- from collections.abc import Generator, Iterator, Mapping, Sequence
-from collections.abc import Generator
++from collections.abc import Generator, Iterator, Mapping
from contextlib import contextmanager
from dataclasses import dataclass
+from functools import lru_cache
from pathlib import Path
-from types import CodeType, FrameType
+from types import CodeType, FrameType, FunctionType, MappingProxyType
from typing import Final
@@@ -28,74 -36,43 +37,87 @@@ class PythonProfiler
def __call__(self, frame: FrameType, event: str, _arg: object) -> None:
if event != "call" or frame in self._seen_frames:
return
- function_name: Final = self.function_name(frame.f_code)
+ function_name: Final = self.function_name(frame)
if function_name is None:
return
- ancestors: Final = tuple(
- name for ancestor in _frame_ancestors(frame) if (name := self.function_name(ancestor)) is not None
+ event_id: Final = len(self.events)
+ parent_id: Final = next(
+ (self._event_ids[ancestor] for ancestor in _frame_ancestors(frame) if ancestor in self._event_ids),
+ None,
)
self._seen_frames.add(frame)
- self.events.append(
- FunctionTraceEvent(
- function=function_name,
- depth=len(ancestors),
- ancestors=ancestors if self._source_root is not None else None,
- )
- )
+ self._event_ids[frame] = event_id
+ self.events.append(FunctionTraceEvent(id=event_id, parent_id=parent_id, function=function_name))
- def function_name(self, code: CodeType) -> str | None:
+ def function_name(self, frame: FrameType) -> str | None:
+ code: Final = frame.f_code
- if self._source_root is None:
- return self._names_by_code.get(code)
if not code.co_filename.startswith(self._source_root):
return None
relative: Final = code.co_filename.removeprefix(self._source_root)
- return f"{relative}:{code.co_firstlineno} {getattr(code, 'co_qualname', code.co_name)}"
+ return f"{relative}:{code.co_firstlineno} {_qualified_name(frame)}"
+ class PythonFunctionUsageProfiler:
+ def __init__(self, source_root: Path, functions: frozenset[str]) -> None:
+ self._source_root: Final = str(source_root.resolve()) + "/"
+ self._functions: Final = functions
+ self.called: Final[set[str]] = set()
+
+ def __call__(self, frame: FrameType, event: str, _arg: object) -> None:
+ if event != "call":
+ return
+ code: Final = frame.f_code
+ if not code.co_filename.startswith(self._source_root):
+ return
+ relative: Final = code.co_filename.removeprefix(self._source_root)
- function: Final = f"{relative}:{code.co_firstlineno} {getattr(code, 'co_qualname', code.co_name)}"
++ function: Final = f"{relative}:{code.co_firstlineno} {_qualified_name(frame)}"
+ if function in self._functions:
+ self.called.add(function)
+
+
+def _qualified_name(frame: FrameType) -> str:
+ code: Final = frame.f_code
+ native: Final = getattr(code, "co_qualname", None)
+ if isinstance(native, str):
+ return native
+ module_name: Final = frame.f_globals.get("__name__")
+ if not isinstance(module_name, str):
+ return code.co_name
+ return _module_qualnames(module_name).get(code, code.co_name)
+
+
+@lru_cache(maxsize=None)
+def _module_qualnames(module_name: str) -> Mapping[CodeType, str]:
+ module: Final = sys.modules.get(module_name)
+ if module is None:
+ return MappingProxyType({})
+ return MappingProxyType(dict(_declared_functions(vars(module), frozenset())))
+
+
+def _declared_functions(namespace: Mapping[str, object], visited: frozenset[int]) -> Iterator[tuple[CodeType, str]]:
+ for attribute in tuple(namespace.values()):
+ for value in _accessors(attribute):
+ if isinstance(value, FunctionType):
+ yield from ((wrapped.__code__, wrapped.__qualname__) for wrapped in _unwrapped(value))
+ elif isinstance(value, type) and id(value) not in visited:
+ yield from _declared_functions(dict(vars(value)), visited | {id(value)})
+
+
+def _unwrapped(function: FunctionType) -> Iterator[FunctionType]:
+ yield function
+ inner: Final = getattr(function, "__wrapped__", None)
+ if isinstance(inner, FunctionType):
+ yield from _unwrapped(inner)
+
+
+def _accessors(value: object) -> tuple[object, ...]:
+ if isinstance(value, (staticmethod, classmethod)):
+ return (value.__func__,)
+ if isinstance(value, property):
+ return tuple(accessor for accessor in (value.fget, value.fset, value.fdel) if accessor is not None)
+ return (value,)
+
+
def _frame_ancestors(frame: FrameType) -> Generator[FrameType]:
ancestor: Final = frame.f_back
if ancestor is not None:
diff --cc tests/rust-python-harness/shared/tracing/test_profiler.py
index 00000000000,ba85ffe63cd..616e9c23e75
mode 000000,100644..100644
--- a/tests/rust-python-harness/shared/tracing/test_profiler.py
+++ b/tests/rust-python-harness/shared/tracing/test_profiler.py
@@@ -1,0 -1,108 +1,141 @@@
+ from __future__ import annotations
+
+ import asyncio
+ import sys
+ import threading
++from collections.abc import Callable
++from functools import wraps
+ from pathlib import Path
-from typing import Final
++from types import FunctionType
++from typing import Final, ParamSpec, TypeVar, cast
+
+ import pytest
+
-from .profiler import FunctionTraceEvent, PythonProfiler, profile_python, profile_python_function_usage
++from .profiler import (
++ FunctionTraceEvent,
++ PythonProfiler,
++ _module_qualnames,
++ profile_python,
++ profile_python_function_usage,
++)
++
++_P = ParamSpec("_P")
++_T = TypeVar("_T")
++
++
++def _passthrough(function: Callable[_P, _T]) -> Callable[_P, _T]:
++ @wraps(function)
++ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
++ return function(*args, **kwargs)
++
++ return wrapper
++
++
++class Decorated:
++ @_passthrough
++ def call(self) -> None:
++ return None
+
+
+ def _events_named(profiler: PythonProfiler, name: str) -> tuple[FunctionTraceEvent, ...]:
+ return tuple(event for event in profiler.events if event.function.endswith(name))
+
+
+ def test_profiler_keeps_repeated_calls() -> None:
+ def called() -> None:
+ return None
+
+ with profile_python(Path(__file__).parent) as profiler:
+ called()
+ called()
+
+ assert len(_events_named(profiler, "called")) == 2
+
+
++def test_profiler_qualifies_decorated_methods_by_class() -> None:
++ with profile_python(Path(__file__).parent) as profiler:
++ Decorated().call()
++
++ assert any(event.function.endswith(" Decorated.call") for event in profiler.events)
++ assert _module_qualnames(__name__)[cast(FunctionType, Decorated.call.__wrapped__).__code__] == "Decorated.call"
++
++
+ def test_profiler_records_real_frame_ancestry() -> None:
+ def called() -> None:
+ return None
+
+ def outer() -> None:
+ called()
+
+ with profile_python(Path(__file__).parent) as profiler:
+ outer()
+
+ outer_event, called_event = (event for event in profiler.events if event.function.endswith(("outer", "called")))
+ assert called_event.parent_id == outer_event.id
+
+
+ def test_profiler_restores_previous_profiler_after_failure() -> None:
+ previous: Final = sys.getprofile()
+
+ with pytest.raises(RuntimeError, match="stop"):
+ with profile_python(Path(__file__).parent):
+ raise RuntimeError("stop")
+
+ assert sys.getprofile() is previous
+
+
+ def test_profiler_does_not_count_coroutine_resumption_as_another_call() -> None:
+ async def suspended() -> None:
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ with profile_python(Path(__file__).parent) as profiler:
+ asyncio.run(suspended())
+
+ assert len(_events_named(profiler, "suspended")) == 1
+
+
+ def test_profiler_preserves_parent_across_coroutine_suspension() -> None:
+ def called() -> None:
+ return None
+
+ async def suspended() -> None:
+ await asyncio.sleep(0)
+ called()
+
+ with profile_python(Path(__file__).parent) as profiler:
+ asyncio.run(suspended())
+
+ suspended_event: Final = _events_named(profiler, "suspended")[0]
+ called_event: Final = _events_named(profiler, "called")[0]
+ assert called_event.parent_id == suspended_event.id
+
+
+ def test_profiler_captures_worker_threads_when_enabled() -> None:
+ def called() -> None:
+ return None
+
+ with profile_python(Path(__file__).parent, threads=True) as profiler:
+ thread: Final = threading.Thread(target=called)
+ thread.start()
+ thread.join()
+
+ called_event: Final = _events_named(profiler, "called")[0]
+ assert called_event.parent_id is None
+
+
+ def test_function_usage_profiler_records_only_selected_functions() -> None:
+ def selected() -> None:
+ return None
+
+ def ignored() -> None:
+ return None
+
+ source_root: Final = Path(__file__).parent
- function: Final = PythonProfiler(source_root).function_name(selected.__code__)
- assert function is not None
++ function: Final = f"{Path(__file__).name}:{selected.__code__.co_firstlineno} {selected.__qualname__}"
+
+ with profile_python_function_usage(source_root, frozenset((function,))) as profiler:
+ selected()
+ ignored()
+
+ assert profiler.called == {function}
diff --cc tests/test_litellm/caching/test_redis_cache.py
index 0743824f85b,e4724ff8705..2a0119bcfb8
--- a/tests/test_litellm/caching/test_redis_cache.py
+++ b/tests/test_litellm/caching/test_redis_cache.py
@@@ -504,8 -515,175 +515,175 @@@ async def test_circuit_breaker_opens_wh
await call_method(cache)
+ def test_circuit_breaker_open_keeps_sync_batch_get_cache_as_a_miss(sync_batch_redis_cache):
+ """An open breaker must preserve the sync batch read's dictionary fallback."""
+ from litellm.constants import REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD
+
+ for _ in range(REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD):
+ assert sync_batch_redis_cache.batch_get_cache(key_list=["lit6729"]) == {}
+
+ assert sync_batch_redis_cache.batch_get_cache(key_list=["lit6729"]) == {}
+
+
+ @pytest.fixture
+ def sync_batch_cache_with_service_logger(redis_no_ping: None) -> Iterator[tuple[RedisCache, ServiceLogging]]:
+ service_logger = ServiceLogging(mock_testing=True)
+ failing_client = MagicMock()
+ failing_client.mget.side_effect = OSError("redis unavailable")
+ with patch( # test-quality-ok: RedisCache.__init__ builds its client eagerly, with no injection point
+ "litellm._redis.get_redis_client", return_value=failing_client
+ ):
+ cache = RedisCache(host="127.0.0.1", port=6379, service_logger_obj=service_logger)
+ yield cache, service_logger
+
+
+ @pytest.mark.asyncio
+ async def test_sync_batch_get_cache_reports_a_failed_read_from_a_running_loop(
+ sync_batch_cache_with_service_logger: tuple[RedisCache, ServiceLogging],
+ ):
+ """A swallowed Redis failure must still be reported as a service failure event.
+
+ The routing strategies call this blocking read from inside the request's event loop,
+ and the read hides the Redis error by returning an empty dict. Without an emitted
+ failure event, litellm_redis_failed_requests_total stops moving during a Redis
+ outage while the success path keeps reporting, so the dashboards read healthy.
+ """
+ cache, service_logger = sync_batch_cache_with_service_logger
+
+ assert cache.batch_get_cache(key_list=["lit6729"]) == {}
+ await asyncio.sleep(0.05)
+
+ assert service_logger.mock_testing_sync_failure_hook == 1
+ assert service_logger.mock_testing_async_failure_hook == 1
+
+
+ def test_sync_batch_get_cache_reports_a_failed_read_from_a_worker_thread(
+ sync_batch_cache_with_service_logger: tuple[RedisCache, ServiceLogging],
+ ):
+ """The same report must reach the async hook when the caller has no event loop at all."""
+ from concurrent.futures import ThreadPoolExecutor
+
+ cache, service_logger = sync_batch_cache_with_service_logger
+
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ assert pool.submit(cache.batch_get_cache, key_list=["lit6729"]).result() == {}
+
+ assert service_logger.mock_testing_async_failure_hook == 1
+
+
+ def test_sync_batch_get_cache_reports_a_failed_read_on_an_idle_event_loop(
+ sync_batch_cache_with_service_logger: tuple[RedisCache, ServiceLogging],
+ ):
+ """The report must also go out when the caller holds an open loop that is not running."""
+ cache, service_logger = sync_batch_cache_with_service_logger
+ loop = asyncio.new_event_loop()
+ try:
+ asyncio.set_event_loop(loop)
+ assert cache.batch_get_cache(key_list=["lit6729"]) == {}
+ finally:
+ asyncio.set_event_loop(None)
+ loop.close()
+
+ assert service_logger.mock_testing_async_failure_hook == 1
+
+
+ def test_sync_batch_get_cache_survives_a_service_callback_that_raises(
+ sync_batch_cache_with_service_logger: tuple[RedisCache, ServiceLogging],
+ monkeypatch: pytest.MonkeyPatch,
+ ):
+ """A failing service callback must not replace the swallowed Redis failure.
+
+ A misconfigured callback raises while emitting (a datadog callback with no
+ DD_API_KEY raises at construction), and the failure event is emitted from inside
+ the except block that swallows the Redis error. If that exception escapes, a Redis
+ outage surfaces to routing as a callback error and the circuit breaker never
+ records the failed read.
+ """
+ from concurrent.futures import ThreadPoolExecutor
+
+ import litellm
+
+ from litellm.constants import REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD
+
+ cache, service_logger = sync_batch_cache_with_service_logger
+ monkeypatch.setattr(litellm, "service_callback", ["prometheus_system"])
+ monkeypatch.setattr(
+ service_logger,
+ "init_prometheus_services_logger_if_none",
+ AsyncMock(side_effect=Exception("callback is misconfigured")),
+ )
+
+ for _ in range(REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD):
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ assert pool.submit(cache.batch_get_cache, key_list=["lit6729"]).result() == {}
+
+ assert cache.batch_get_cache(key_list=["lit6729"]) == {}
+
+
+ def test_call_stack_info_skips_breaker_guard_frames():
+ """Guarded methods must still report their real callers in service-log call_type.
+
+ The breaker guards put their own frames between a method body and its caller, so
+ without skipping them every guarded method logged the guard machinery instead of
+ who actually issued the Redis call.
+ """
+ from litellm.caching.redis_cache import (
+ RedisCircuitBreaker,
+ _get_call_stack_info,
+ _redis_circuit_breaker_guard_sync,
+ )
+
+ class Guarded:
+ _circuit_breaker = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)
+
+ @_redis_circuit_breaker_guard_sync
+ def probe(self):
+ return _get_call_stack_info()
+
+ def caller_one():
+ return Guarded().probe()
+
+ def caller_two():
+ return caller_one()
+
+ assert caller_two() == "caller_one <- caller_two"
+
+
+ def test_call_stack_info_skips_guard_frames_when_deployed_without_sources(monkeypatch):
+ """Guard-frame skipping must survive a bytecode-only deployment.
+
+ Shipping `.pyc` files without their `.py` sources leaves the module's `__file__` pointing
+ at the compiled file while every frame still carries the compile-time source path, so a
+ check comparing those two paths stops skipping and the service log then names the guard
+ machinery instead of the real caller.
+ """
+ from litellm.caching import redis_cache as redis_cache_module
+ from litellm.caching.redis_cache import (
+ RedisCircuitBreaker,
+ _get_call_stack_info,
+ _redis_circuit_breaker_guard_sync,
+ )
+
+ monkeypatch.setattr(redis_cache_module, "__file__", redis_cache_module.__file__ + "c")
+
+ class Guarded:
+ _circuit_breaker = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)
+
+ @_redis_circuit_breaker_guard_sync
+ def probe(self):
+ return _get_call_stack_info()
+
+ def caller_one():
+ return Guarded().probe()
+
+ def caller_two():
+ return caller_one()
+
+ assert caller_two() == "caller_one <- caller_two"
+
+
@pytest.mark.asyncio
-async def test_circuit_breaker_success_still_resets_the_failure_streak(redis_no_ping):
+async def test_circuit_breaker_success_still_resets_the_failure_streak():
"""A reachable Redis must keep the breaker closed, however many earlier calls failed.
The guard now records success only when nothing failed while the method ran, so this
diff --cc type-discipline-budget.json
index 6c316d2eca1,ab1a793e09d..ba871b5f69b
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@@ -27,12 -27,12 +27,12 @@@
"limit": 0
},
"LIT010": {
- "limit": 16477
+ "limit": 16468
},
"LIT011": {
- "limit": 5519
+ "limit": 5514
},
"LIT012": {
- "limit": 4489
+ "limit": 4488
}
}