mirror of
https://github.com/BerriAI/litellm.git
synced 2026-10-08 03:08:45 +00:00
* ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: move tests/test_litellm integrations and secret_managers into tests/unit Rename-only. Mirrors the old paths, including the directory conftests and the prompt and JSON fixtures. Follow-up commits prune and wire them. * test: prune and repoint the moved integrations tests Deletes the 7 audited tests a stronger test in the same tree already covers, imports the TLS sink helpers from their new conftest path, and restores os.environ after each integrations test. Some presets write OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the legacy tree's test ordering that header leaked into the AgentOps tests. * ci: run the moved integrations tests under their legacy flag The integrations GHA shard and a new CircleCI job run the integrations unit selection. secret_managers joins the misc selection. * docs: point integrations and secret_managers references at tests/unit * test: make the moved integrations directories packages * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: move tests/test_litellm core utils, routing, responses, caching and rust_bridge into tests/unit Rename-only. Mirrors the old paths, including fixtures, the stubtest config and the native-route wheel script. Two files that collide with existing unit files are merged in a follow-up commit. * test: merge, prune and repoint the moved core, routing, responses, caching and rust_bridge tests Merges the two files that collided with existing unit files, folding the legacy extra case into test_is_chat_completion_cached_dict, and deletes the 9 audited tests a stronger test in the same file already covers. Keeps what needs the network in tests/test_litellm: test_tokenizers pulls a tokenizer from the Hugging Face hub, and the gpt2 and r50k_base tokenizer cases download their BPE files. The unit core_utils conftest points TIKTOKEN_CACHE_DIR at litellm's bundled encodings so the rest never depend on import order to stay offline, and FakeSecretVault moves to a shared module so both trees can build it. * ci: run the moved core, routing, responses, caching and rust_bridge tests under their flags core_utils gets a core-utils flag and CircleCI job, and its GHA shard keeps the legacy path for the retained network tests. router_utils and router_strategy join enterprise-routing, responses joins responses-caching-types (minus responses/mcp, which mcp-integration owns), caching joins caching-local and rust_bridge joins misc. The redis-compat, test-rust, stubtest and merge-smoke paths follow the move. * docs: point the Rust crate references at tests/unit * test: make the moved core, routing and rust_bridge directories packages * test: keep the no-loop DualCache batch_get_cache regression test It runs the sync path outside any event loop, which the inside-loop test cannot, so a change that picks the Redis client by loop state would only show up there. * test: keep the job's UNIT_FLAG out of the shard-script tests * fix(url_utils): block 192.0.0.0/24 on every Python patch release * test: move the new budget limiter tests into tests/unit/router_strategy * test: move the new sentry scrubbing tests into tests/unit/litellm_core_utils * test: move the new zerobus tests into tests/unit/integrations * test: make tests/unit/integrations/zerobus a package * test: load litellm's own tiktoken cache setup once instead of resetting it per test --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
210 lines
8.6 KiB
Python
210 lines
8.6 KiB
Python
import logging
|
|
from typing import Final
|
|
|
|
import pytest
|
|
|
|
from litellm.caching.caching import DualCache
|
|
from litellm.caching.in_memory_cache import InMemoryCache
|
|
from litellm.caching.redis_cache import RedisCircuitBreakerOpenError
|
|
from litellm.router_strategy.least_busy import IN_FLIGHT_COUNT_TTL_SECONDS, LeastBusyLoggingHandler
|
|
|
|
GROUP: Final = "least-busy-group"
|
|
DEPLOYMENT_A: Final[dict[str, object]] = {"model_info": {"id": "dep-a"}}
|
|
DEPLOYMENT_B: Final[dict[str, object]] = {"model_info": {"id": "dep-b"}}
|
|
HEALTHY: Final = [DEPLOYMENT_A, DEPLOYMENT_B]
|
|
|
|
|
|
def _call_kwargs(deployment_id: str) -> dict[str, object]:
|
|
return {"litellm_params": {"metadata": {"model_group": GROUP}, "model_info": {"id": deployment_id}}}
|
|
|
|
|
|
class SharedRedisCounters:
|
|
"""Mirrors what Redis gives the handler: increments clamped at zero, a TTL set once when
|
|
the key is created, and ordered reads that raise rather than invent a value."""
|
|
|
|
def __init__(self) -> None:
|
|
self.counts: dict[str, int] = {}
|
|
self.ttls: dict[str, int] = {}
|
|
|
|
def count(self, key: str) -> int | None:
|
|
return self.counts.get(key)
|
|
|
|
def expire(self, key: str) -> None:
|
|
self.counts.pop(key, None)
|
|
self.ttls.pop(key, None)
|
|
|
|
def increment_with_floor(self, key: str, value: int, ttl: int) -> int:
|
|
incremented: Final = max(0, self.counts.get(key, 0) + value)
|
|
self.counts[key] = incremented
|
|
self.ttls.setdefault(key, ttl)
|
|
return incremented
|
|
|
|
async def async_increment_with_floor(self, key: str, value: int, ttl: int) -> int:
|
|
return self.increment_with_floor(key, value, ttl)
|
|
|
|
def batch_get_counts(self, key_list: list[str]) -> tuple[int | None, ...]:
|
|
return tuple(self.counts.get(key) for key in key_list)
|
|
|
|
async def async_batch_get_counts(self, key_list: list[str]) -> tuple[int | None, ...]:
|
|
return self.batch_get_counts(key_list)
|
|
|
|
|
|
def _worker(shared: SharedRedisCounters | None) -> LeastBusyLoggingHandler:
|
|
cache: Final = DualCache(in_memory_cache=InMemoryCache(), redis_cache=shared) # pyright: ignore[reportArgumentType] # duck-typed Redis double
|
|
return LeastBusyLoggingHandler(router_cache=cache)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_worker_routes_around_a_request_another_worker_started() -> None:
|
|
shared: Final = SharedRedisCounters()
|
|
streaming_worker: Final = _worker(shared)
|
|
picking_worker: Final = _worker(shared)
|
|
|
|
picking_worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
await picking_worker.async_log_success_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
streaming_worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
|
|
assert await picking_worker.async_get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_B
|
|
|
|
await streaming_worker.async_log_success_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
assert await picking_worker.async_get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_A
|
|
|
|
|
|
def test_sync_pick_reads_the_shared_counts() -> None:
|
|
shared: Final = SharedRedisCounters()
|
|
streaming_worker: Final = _worker(shared)
|
|
picking_worker: Final = _worker(shared)
|
|
|
|
picking_worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
picking_worker.log_success_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
streaming_worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
|
|
assert picking_worker.get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_B
|
|
|
|
streaming_worker.log_failure_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
assert picking_worker.get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_A
|
|
|
|
|
|
def test_the_handler_never_pushes_a_counters_ttl_forward() -> None:
|
|
"""A worker that dies mid-request leaves a +1 nobody will ever decrement. Redis expires that
|
|
stuck count an hour after the key was created, which only works while nothing writes the TTL
|
|
again: a handler that refreshed it on every touch would keep the count alive for as long as
|
|
the group takes traffic, and the deployment would read busier than it is forever."""
|
|
shared: Final = SharedRedisCounters()
|
|
worker: Final = _worker(shared)
|
|
key: Final = f"{GROUP}_request_count:dep-a"
|
|
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
|
|
assert shared.ttls == {key: IN_FLIGHT_COUNT_TTL_SECONDS}
|
|
|
|
shared.ttls[key] = 5
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
worker.log_success_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
assert shared.count(key) == 1
|
|
assert shared.ttls == {key: 5}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_counts_stay_in_memory_without_redis() -> None:
|
|
worker: Final = _worker(None)
|
|
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
|
|
assert await worker.async_get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_B
|
|
assert worker.get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_B
|
|
|
|
await worker.async_log_success_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
assert await worker.async_get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_A
|
|
assert worker.router_cache.get_cache(f"{GROUP}_request_count:dep-a") == 0
|
|
|
|
|
|
class UnavailableRedis(SharedRedisCounters):
|
|
def increment_with_floor(self, key: str, value: int, ttl: int) -> int:
|
|
raise ConnectionError("redis is down")
|
|
|
|
def batch_get_counts(self, key_list: list[str]) -> tuple[int | None, ...]:
|
|
raise ConnectionError("redis is down")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_redis_outage_falls_back_to_this_workers_own_counts() -> None:
|
|
worker: Final = _worker(UnavailableRedis())
|
|
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
|
|
assert worker.get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_B
|
|
assert await worker.async_get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_B
|
|
|
|
await worker.async_log_success_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
assert worker.get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_A
|
|
|
|
|
|
def test_a_shared_counter_that_expired_mid_request_cannot_go_negative() -> None:
|
|
shared: Final = SharedRedisCounters()
|
|
worker: Final = _worker(shared)
|
|
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
shared.expire(f"{GROUP}_request_count:dep-a")
|
|
worker.log_success_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
assert shared.count(f"{GROUP}_request_count:dep-a") == 0
|
|
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
|
|
assert shared.count(f"{GROUP}_request_count:dep-a") == 1
|
|
assert worker.get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_B
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_local_counter_that_expired_mid_request_cannot_go_negative() -> None:
|
|
worker: Final = _worker(None)
|
|
in_memory: Final = worker.router_cache.in_memory_cache
|
|
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
in_memory.delete_cache(f"{GROUP}_request_count:dep-a")
|
|
await worker.async_log_success_event(_call_kwargs("dep-a"), None, None, None)
|
|
|
|
assert worker.router_cache.get_cache(f"{GROUP}_request_count:dep-a") == 0
|
|
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
|
|
assert await worker.async_get_available_deployments(GROUP, HEALTHY) is DEPLOYMENT_B
|
|
|
|
|
|
def test_calls_without_a_deployment_are_ignored() -> None:
|
|
shared: Final = SharedRedisCounters()
|
|
worker: Final = _worker(shared)
|
|
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs={"litellm_params": {"metadata": None}})
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs={})
|
|
|
|
assert shared.counts == {}
|
|
|
|
|
|
class OpenBreakerRedis(SharedRedisCounters):
|
|
def increment_with_floor(self, key: str, value: int, ttl: int) -> int:
|
|
raise RedisCircuitBreakerOpenError("Redis circuit breaker is open")
|
|
|
|
def batch_get_counts(self, key_list: list[str]) -> tuple[int | None, ...]:
|
|
raise RedisCircuitBreakerOpenError("Redis circuit breaker is open")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_an_open_circuit_breaker_falls_back_without_a_warning_per_request(caplog: pytest.LogCaptureFixture) -> None:
|
|
worker: Final = _worker(OpenBreakerRedis())
|
|
|
|
with caplog.at_level(logging.DEBUG, logger="LiteLLM Router"):
|
|
worker.log_pre_api_call(model="m", messages=[], kwargs=_call_kwargs("dep-a"))
|
|
picked: Final = worker.get_available_deployments(GROUP, HEALTHY)
|
|
|
|
assert picked is DEPLOYMENT_B
|
|
assert [record.getMessage() for record in caplog.records if record.levelno >= logging.WARNING] == []
|
|
assert sum("circuit breaker is open" in record.getMessage() for record in caplog.records) == 2
|