mirror of
https://github.com/BerriAI/litellm.git
synced 2026-10-14 04:09:09 +00:00
* feat(model-catalog): add Rust registry validation (#43136) * doc * feat(model-catalog): add Rust registry validation * test(model-catalog): ignore integration tests * docs(model-catalog): fix validation note grammar --------- Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commitc289d5d6fb) * test(rust): reorganize core crate tests and split cache and OCR suites (#43177) * test(rust): group cache tests under cache/ and fold test_ocr.py into ocr/ The two failure cases in test_ocr.py duplicated the upstream-500 and timeout rows of PUBLIC_FAILURES, so only the file-input encoding case moves to ocr/test_requests.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(rust): split the response cache suite into one file per backend test_response_cache.py grew to 2400 lines. Each backend now has its own file, shared fixtures live in cache/conftest.py and shared helpers in support/cache.py. The helpers alias the private native test handles once, dropping the per-call reportPrivateUsage hits Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * split tokenizer test * test(core): consolidate route integration tests under tests/ with rstest and wiremock Moves the public-API OCR route tests out of src/ocr/route.rs and document.rs into tests/ocr/, split per provider plus lifecycle, machine, and document tests, merging the duplicated pairs. Messages, audio transcription, and chat completions share one wiremock-based upstream and recording secret source in tests/support, and gain table-driven cases for auth, routing, upstream errors, streaming, and declines. Tests of litellm-llms items move to that crate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(messages): keep the stream relay test independent of the stream head contents The stream head carries no headers on main, so the relay test asserts the open-then-deliver order and the relayed body instead of header hand-off. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit10413796c6) * feat(rust): hand upstream response headers to the native Messages stream (#43178) * ci: drop the ocr_testing job now that tests/ocr_tests is gone Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(ocr): restore the live OCR matrix and the ocr_testing job The public litellm.ocr / aocr / Router interface is unchanged by the Rust migration, so the live provider matrix still applies. Drops the stale VCR skip list for the deleted test_rust_bridge.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(messages): show streamed upstream headers never reach the native stream The Python handler puts the upstream response headers on the stream's _hidden_params before the first chunk so the proxy can forward them as llm_provider-* headers. The native route drops them, and this test fails on the Rust path while passing on Python. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(messages): hand upstream response headers to the native stream before its first chunk The Messages route fills MessagesStreamHead from the upstream response and yields it on Open. The Python driver converts it through the protocol host and hands it to Stream and SyncStream as their _hidden_params, so a streamed native call carries additional_headers the same way the Python handler does and the proxy can forward them as llm_provider-* headers. The relay contract lives in the core crate test, the hand-off in the host-python driver test, and the header projection in the route host test, so the recording-server test that showed the gap is dropped. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * wip --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit081f73f021) * feat(testkit): agent clients for Claude Code, Codex and opencode (#43181) * feat(testkit): install and configure Claude Code, Codex and opencode against a gateway Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * refactor(testkit): derive targets from target-lexicon and split agents behind a trait Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * refactor(testkit): group sources into agent and install folders Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(testkit): split agents into install, configure and drive with semver-aware launch Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * style(testkit): drop a needless borrow Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> (cherry picked from commit9c10e0f985) * ci: run migrated unit selections on every event in legacy GHA shards (#43182) * 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 --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit694783ebbe) * test: move tests/test_litellm root and small trees into tests/unit (#43186) * 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: 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. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitf6882246d4) * refactor(framer): replace Framer trait with tokio-util codecs (#43193) * refactor(framer): replace Framer trait with tokio-util codecs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(framer): port SSE and AWS event stream framing to codecs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): drop clone on Copy capabilities in messages request test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): use field init shorthand in messages request test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit3c93ea1697) * test: move tests/test_litellm/llms into tests/unit/llms (#43191) * 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: 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: keep the job's UNIT_FLAG out of the shard-script tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit5e6dc89ba1) * test: move tests/test_litellm integrations and secret_managers into tests/unit (#43194) * 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: keep the job's UNIT_FLAG out of the shard-script tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitcf491d1df9) * fix(tests): drop the repeated UNIT_FLAG key in test_unit_shard_missing_paths (#43212) Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com> (cherry picked from commit25de1ab2b0) * fix(jwt): let x-litellm-team-id select DB membership teams when the token also carries a team claim (#43206) * fix(jwt): let x-litellm-team-id select DB membership teams when the token also carries a team claim Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs(jwt): describe header team selection under fallback_to_db_teams Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit7b4fd47c6e) * test: move tests/test_litellm core utils, routing, responses, caching and rust_bridge into tests/unit (#43199) * 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> (cherry picked from commita11a93f44a) * refactor(rust): move credential inheritance and the SDK limits out of the legacy callback crate into a driver preflight (#43259) The legacy callback crate carried two rewrites that have nothing to do with the Logging contract: litellm_credential_name inheritance and the max_budget and num_retries_per_request checks. Any later callback host would need them unchanged, which is the smell the crate's AGENTS.md now names. They are now a Preflight the driver in litellm-host-python runs on the keyword view begin returned, before the host projects from it, supplied by python-bridge and passed through run_legacy_call. The call order is unchanged (setup, deployment hook, credentials, limits) and a rejection still fails the call as a host failure, so the failure callbacks run as before. The preflight rewrites the adapter's own copy in place, so no extra dict copy and no new lifecycle method Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commite9491d31b5) * refactor(http): hand out an owned Client and route all providers through the pool (#43245) * refactor(messages): take the provider client from the injected HTTP pool The messages route kept its own process-wide reqwest client, so it ignored ssl_verify, CA bundles, client certs, proxies and every other setting that litellm-http resolves. The machine now takes the HttpClientPool and the call's HttpClientConfig, as OCR does, and the bridge passes its shared pool. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(http): hand out an owned Client and move chat, audio and OIDC onto the pool HttpClientPool now returns litellm_http::Client, a newtype only crates/http can build, so every provider client carries the resolved TLS, proxy and timeout settings. Chat completions and audio transcription drop their process-wide reqwest clients and take the pool and call config like messages; their 600s ceiling moves to the request. OidcResolver takes its client instead of building one, and the bridge hands it the pooled one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(secrets): build Google, Azure and CyberArk manager clients from the pool The native secret managers built bare reqwest clients, so they ignored the host's TLS and proxy settings. load_native_manager now takes the pool and the host config and hands each manager a pooled client. CyberArk's CYBERARK_SSL_VERIFY and CYBERARK_CLIENT_CERT/KEY become an override on the host config instead of a hand-built client. To express a certificate and key in separate files, HttpClientConfig::client_certificate is now a ClientIdentity that is either one PEM or a split pair. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(clippy): only crates/http may build a reqwest client Fence reqwest::Client, ClientBuilder and the TLS builder methods with disallowed-types and disallowed-methods so new code takes a litellm_http::Client from the pool. crates/http is exempt as the one place clients are built, and testkit as a dev-only installer. Tests move to litellm_http::Client::plain_for_test or a pooled client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(secrets-cyberark): keep verifying certificates when the host disables it Python hands CyberArk its own ssl_verify, which wins over the global setting, so CYBERARK_SSL_VERIFY unset or true still verifies even when the host sets ssl_verify false. The pooled client copied the host's Disabled and would send the API key unverified; fall back to the built-in roots instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(python-bridge): treat a missing litellm package as no host HTTP settings Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit1a58162630) * refactor(rust): promote anthropic messages out of experimental_pass_through (#43269) Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commit2ef3250ec3) * test: stop CI tests from downloading tokenizer files and images (#43257) * test: load the embedding base image from a committed 100x100 PNG instead of downloading it * test: move the volcengine embedding test into tests/unit * test: check gpt2 and r50k_base tokenizer parity against committed tiktoken reference files * test: check hub tokenizer selection against an in-memory Hugging Face hub * test: serve image URLs from respx in the gemini tool-result and format-param tests * ci: drop the emptied legacy core-utils test path * test: cover the cohere and anthropic tokenizer paths in the hub tokenizer test * test: fetch every format-param image through respx and check its bytes reach the request * test: drop the gpt2 and r50k_base parity tests, which no litellm path uses * test: drop comments that restate assertions in the format-param test (cherry picked from commit2530255624) * fix(rust): preserve nested optional import failures (#43265) * fix(rust): preserve nested optional import failures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(rust): restore Python modules after settings tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commite1a9378093) * fix(callbacks-legacy-python): traverse and release the retained headers dict (#43274) * fix(callbacks-legacy-python): traverse and release the retained headers dict LegacyLogging keeps the headers dict it hands to pre_call and post_call, but its traverse never reported that edge to the collector and close never dropped it. A cycle a callback builds through that dict could not be collected, and a closed call kept the dict alive until the driver dropped the whole adapter. Visit and clear headers like body, with regression tests for both * refactor(callbacks-legacy-python): move the test support module into its own file --------- Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commit4eb340abe0) * test(integration): port langfuse callbacks-in-db coverage to the local harness (#43282) * test(integration): port langfuse callbacks-in-db coverage to the local harness Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): assert the langfuse db rows after the exported span Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commite11c3f5815) * test: finish the non-proxy half of tests/test_litellm (#43281) * test: move key-gated tests/test_litellm SDK tests into tests/llm_translation and drop empty folders * test: make token counter and health check unit tests run offline * ci: point unit shards, rust path filter, Makefile and docs at tests/unit * docs: fix stale test_litellm run paths in moved llm_translation tests * fix: correct databricks e2e sys.path depth and contributing example path --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit99655b6f86) * refactor(rust): prepare inference and auth foundations for the gateway (#43287) * refactor(rust): prepare inference and auth foundations * fix(rust): keep textract operations parsing from kebab-case model names Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit7ae721bf79) * feat(rust): add config router and gateway crates (#43289) Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commitaffb547525) * test(integration): run the Langfuse DB-callback test on its own scratch database (#43288) * test(integration): run the Langfuse DB-callback test on its own scratch database The test from #43282 wrote success_callback=langfuse and the LANGFUSE_* env into the shared integration LiteLLM_Config. The suite's long-running gateway reloads that table and only ever adds callbacks, so it kept exporting to the test's closed Langfuse fake for the rest of the shard even after the rows were restored. The owned proxy now gets a scratch database, which also removes the snapshot/restore code. scratch_database moves into _support/database.py so test_cache_and_quota and this test share one copy, and the stock-config guard now checks the callback settings instead of the raw YAML text. * test(integration): include failure_callback in the stock-config Langfuse guard (cherry picked from commitdd63637322) * refactor(rust): expand logging and test coverage across gateway and Anthropic messages (#43295) * refactor(rust): prepare inference and auth foundations * fix(rust): keep textract operations parsing from kebab-case model names Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * done * refactor(types): derive Anthropic beta string conversions with Strum * fix(anthropic): report missing max_tokens as a missing field * refactor(rust): type Anthropic messages headers and auth after the Python layout Delete anthropic/messages/headers.rs. Its OAuth handling, credential ladder and beta merging move to anthropic/common_utils.rs where Python keeps them (optionally_handle_anthropic_oauth, get_auth_header, _merge_beta_headers), and the feature beta injection becomes update_headers_with_anthropic_beta on the messages config, as in Python. The BaseAnthropicMessagesConfig impl is unchanged apart from the bodies of validate_environment and request_headers Beta values are now the AnthropicBeta enum and BetaSet, which sort, dedupe and comma-join by construction. Request params gain typed speed, tools and context_management through Recognized, so the beta logic matches on enums instead of string-comparing JSON. OauthToken parses the sk-ant-oat token once and the chat config shares that detection instead of its own copy Case-insensitive header helpers move next to has_header in litellm-http. One deliberate divergence: a Bearer-prefixed OAuth key configured through api_key or ANTHROPIC_API_KEY is sent with a single Bearer scheme, where Python would emit "Bearer Bearer" Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * done * fix(rust): repair test compilation and clippy failures resolve auth before building the outbound request in prepare tests, give the host hook tests their own error type, and drop the disallowed reqwest client and err().expect() from core tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commit90873c46de) * test(proxy_behavior): scope the management proxy fixture to its package so its spend monitor cannot race the spend tests (#43302) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit115668f43e) * fix(ci): stop stale CI reds, keep unit tests off the host env, retry CyberArk policy conflicts (#43294) * fix(ci): stop five stale or flaky CI reds and retry CyberArk policy-load conflicts The Langfuse redaction unit test exports to a local OTLP capture instead of polling Langfuse Cloud through a recorded lookup. The passthrough worker-kill test only requires spend rows for requests the surviving worker served. The spend-routes sweep treats the intentional /spend/capture_rate 503 as expected. CyberArk retries a 409 policy load in Python, Rust and the e2e Conjur helper instead of reading it as "variable exists". The integration egress guard now matches the script's own cgroup, so it no longer blocks the CircleCI agent, which runs as the same user. * fix(ci): keep the policy-load backoff typed as float * fix(ci): retry CyberArk policy loads without blocking the event loop and tighten the worker-kill and Langfuse tests * fix(secrets): load CyberArk policy one request at a time per manager * test(secrets): pin that non-conflict CyberArk policy failures are not retried * test(unit): run tests/unit with only an allowlisted host environment CircleCI's unit job inherits every project env var, so real provider keys, REDIS_HOST, DATABASE_URL and AWS or Azure credentials reached tests that assume none are set. Locally, litellm's import-time load_dotenv did the same from any .env up the tree. The unit conftest now drops every variable outside a small allowlist and disables dotenv before litellm is imported. * test(e2e): name a failed search and the stuck batch status instead of misattributing them The websearch session test read an empty web_search_tool_result_error block as a successful search, so a failing search tool surfaced as a session billing bug. The batch cancellation timeout now reports the last status the proxy returned. * fix(ci): scrub the host environment per unit test instead of for the whole pytest process GHA shards run tests/unit next to other suites in one process, so the import-time scrub deleted MCP_TEST_PEER_PYTHON before tests/mcp_tests read it and the MCP upstream fell back to the SDK2 interpreter. The two websearch tests that called OpenAI and Perplexity live are removed: tests/unit no longer sees their keys. * fix(ci): scrub only the host variables present before litellm is imported The per-test scrub also deleted TIKTOKEN_CACHE_DIR, which litellm sets at import to its bundled encodings, so tokenizer paths tried to download them and hit the socket guard. The prisma setup test now passes its own database URL instead of reading one another test leaked into the process environment. * fix(ci): stop the order-dependent unit reds and settle logging tasks on their own queue LoggingWorker marked a task done on whichever queue was current when the callback finished, so a callback that outlived an event-loop change raised "task_done() called too many times" or undercounted the new loop's queue. It now settles the queue the task came from. The rest are test isolation fixes for failures that only appeared when another file ran first on the same xdist worker: a replaced user_api_key_cache, breaker metrics unregistered by prometheus tests, semantic_router's health-check filter on uvicorn.access, logging tasks carried over from bedrock tests, a Router-written model_cost entry, and a stray post captured by the langflow test. The token counter check now asserts bounded chunking instead of wall-clock time. * test(e2e/ui): wait for the logout redirect before visiting a protected page Logout revokes the session server-side before clearing cookies and navigating, so an immediate page.goto either ran with the cookie still set or was aborted by the logout redirect (net::ERR_ABORTED). * test(unit): restore the prometheus metrics config per test and settle logs carried from earlier tests in the a2a cost tests * test(router): pin the router clock in the usage counter tests so a minute rollover cannot empty the read * test(e2e/ui): wait for logout to clear the token cookie instead of for a login redirect * test(integration/mcp): answer the model-info probe another test's proxy sends to the model double (cherry picked from commit14f4c34c61) * test(e2e): assert only litellm-owned batch behavior and move the blank S3 env pin to an integration test (#43321) (cherry picked from commite53e67ede5) * ci: drop main and litellm_* branch filters from the CircleCI litellm-main workflows (#43272) Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitc822c7fffa) * test(e2e): accept the otel cost write as a linked root trace (#42931) * test(e2e): accept the otel cost write as a linked root trace Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(e2e): window and fail-closed the linked otel trace read-back Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(e2e): poll the otel read-back without recursion Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit3ebf6a1fd8) * refactor(rust): exclude gateway and config crates from rc backport * refactor(rust): exclude router crate from rc backport --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: yassin <yassin@berri.ai>
793 lines
30 KiB
Python
793 lines
30 KiB
Python
import asyncio
|
|
import logging
|
|
import time
|
|
import uuid
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
from litellm.constants import DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE
|
|
from litellm.caching.dual_cache import DualCache
|
|
from litellm.caching.in_memory_cache import InMemoryCache
|
|
from litellm.caching.redis_cache import RedisCache, _redis_circuit_breaker_guard, _redis_circuit_breaker_guard_sync
|
|
from litellm.types.caching import RedisPipelineIncrementOperation
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_async_batch_get_cache_coalesces_concurrent_redis_reads():
|
|
dual_cache = DualCache(
|
|
redis_cache=MagicMock(spec=RedisCache), default_redis_batch_cache_expiry=10
|
|
)
|
|
keys = ["shared_a", "shared_b"]
|
|
start_gate = asyncio.Event()
|
|
|
|
async def _mock_async_batch_get_cache(key_list, parent_otel_span=None):
|
|
await asyncio.sleep(0.05)
|
|
return {k: None for k in key_list}
|
|
|
|
with patch.object(
|
|
dual_cache.redis_cache,
|
|
"async_batch_get_cache",
|
|
new=AsyncMock(side_effect=_mock_async_batch_get_cache),
|
|
) as mock_async_batch_get_cache:
|
|
|
|
async def worker():
|
|
await start_gate.wait()
|
|
return await dual_cache.async_batch_get_cache(keys=keys)
|
|
|
|
tasks = [asyncio.create_task(worker()) for _ in range(50)]
|
|
start_gate.set()
|
|
await asyncio.gather(*tasks)
|
|
|
|
assert mock_async_batch_get_cache.call_count == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_async_batch_get_cache_rolls_back_redis_reservation_on_error():
|
|
dual_cache = DualCache(
|
|
redis_cache=MagicMock(spec=RedisCache), default_redis_batch_cache_expiry=10
|
|
)
|
|
keys = ["shared_a", "shared_b"]
|
|
|
|
with patch.object(
|
|
dual_cache.redis_cache,
|
|
"async_batch_get_cache",
|
|
new=AsyncMock(side_effect=RuntimeError("redis unavailable")),
|
|
) as mock_async_batch_get_cache:
|
|
first_result = await dual_cache.async_batch_get_cache(keys=keys)
|
|
second_result = await dual_cache.async_batch_get_cache(keys=keys)
|
|
|
|
assert first_result is None
|
|
assert second_result is None
|
|
assert mock_async_batch_get_cache.call_count == 2
|
|
assert "shared_a" not in dual_cache.last_redis_batch_access_time
|
|
assert "shared_b" not in dual_cache.last_redis_batch_access_time
|
|
|
|
|
|
def _redis_mock_for_sync_batch(redis_result: dict) -> MagicMock:
|
|
mock_redis = MagicMock(spec=RedisCache)
|
|
mock_redis.batch_get_cache.return_value = redis_result
|
|
return mock_redis
|
|
|
|
|
|
def _assert_sync_batch_used_blocking_client(dual_cache: DualCache, mock_redis: MagicMock) -> None:
|
|
with patch("asyncio.new_event_loop", side_effect=AssertionError("sync path must not create an event loop")):
|
|
result = dual_cache.batch_get_cache(keys=["lit6729_key"])
|
|
|
|
assert result == ["redis_value"]
|
|
mock_redis.batch_get_cache.assert_called_once_with(key_list=["lit6729_key"], parent_otel_span=None)
|
|
mock_redis.async_batch_get_cache.assert_not_called()
|
|
mock_redis.init_async_client.assert_not_called()
|
|
assert dual_cache.in_memory_cache.get_cache("lit6729_key") == "redis_value"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_batch_get_cache_uses_sync_redis_client_inside_running_loop():
|
|
"""
|
|
Regression test for LIT-6729: sync batch_get_cache ran async_batch_get_cache on a
|
|
throwaway event loop, reusing an async Redis client created on another loop and
|
|
corrupting its connection pool. The sync path must use the blocking client, never
|
|
the async one, and never create an event loop, even when called from a coroutine
|
|
(e.g. async_raise_no_deployment_exception -> get_min_cooldown).
|
|
"""
|
|
mock_redis = _redis_mock_for_sync_batch({"lit6729_key": "redis_value"})
|
|
dual_cache = DualCache(in_memory_cache=InMemoryCache(), redis_cache=mock_redis)
|
|
|
|
_assert_sync_batch_used_blocking_client(dual_cache, mock_redis)
|
|
|
|
|
|
def test_dual_cache_batch_get_cache_uses_sync_redis_client_without_running_loop():
|
|
mock_redis = _redis_mock_for_sync_batch({"lit6729_key": "redis_value"})
|
|
dual_cache = DualCache(in_memory_cache=InMemoryCache(), redis_cache=mock_redis)
|
|
|
|
_assert_sync_batch_used_blocking_client(dual_cache, mock_redis)
|
|
|
|
|
|
def test_dual_cache_batch_get_cache_only_reads_missing_keys_from_redis():
|
|
mock_redis = _redis_mock_for_sync_batch({"miss_key": "from_redis"})
|
|
dual_cache = DualCache(in_memory_cache=InMemoryCache(), redis_cache=mock_redis)
|
|
dual_cache.in_memory_cache.set_cache("hit_key", "from_memory")
|
|
|
|
result = dual_cache.batch_get_cache(keys=["hit_key", "miss_key"])
|
|
|
|
assert result == ["from_memory", "from_redis"]
|
|
mock_redis.batch_get_cache.assert_called_once_with(key_list=["miss_key"], parent_otel_span=None)
|
|
|
|
|
|
def test_dual_cache_batch_get_cache_throttles_repeat_redis_reads():
|
|
mock_redis = _redis_mock_for_sync_batch({"absent_key": None})
|
|
dual_cache = DualCache(
|
|
in_memory_cache=InMemoryCache(), redis_cache=mock_redis, default_redis_batch_cache_expiry=10
|
|
)
|
|
|
|
first = dual_cache.batch_get_cache(keys=["absent_key"])
|
|
second = dual_cache.batch_get_cache(keys=["absent_key"])
|
|
|
|
assert first == [None]
|
|
assert second == [None]
|
|
mock_redis.batch_get_cache.assert_called_once()
|
|
|
|
|
|
def test_dual_cache_batch_get_cache_rolls_back_redis_reservation_on_error():
|
|
mock_redis = MagicMock(spec=RedisCache)
|
|
mock_redis.batch_get_cache.side_effect = RuntimeError("redis unavailable")
|
|
dual_cache = DualCache(
|
|
in_memory_cache=InMemoryCache(), redis_cache=mock_redis, default_redis_batch_cache_expiry=10
|
|
)
|
|
|
|
first_result = dual_cache.batch_get_cache(keys=["shared_a"])
|
|
second_result = dual_cache.batch_get_cache(keys=["shared_a"])
|
|
|
|
assert first_result is None
|
|
assert second_result is None
|
|
assert mock_redis.batch_get_cache.call_count == 2
|
|
assert "shared_a" not in dual_cache.last_redis_batch_access_time
|
|
|
|
|
|
def test_dual_cache_batch_get_cache_returns_memory_only_when_redis_read_is_throttled():
|
|
mock_redis = _redis_mock_for_sync_batch({"throttled_key": "redis_value"})
|
|
dual_cache = DualCache(
|
|
in_memory_cache=InMemoryCache(), redis_cache=mock_redis, default_redis_batch_cache_expiry=10
|
|
)
|
|
dual_cache.last_redis_batch_access_time["throttled_key"] = time.time()
|
|
|
|
result = dual_cache.batch_get_cache(keys=["throttled_key"])
|
|
|
|
assert result == [None]
|
|
mock_redis.batch_get_cache.assert_not_called()
|
|
|
|
|
|
def test_dual_cache_sync_batch_redis_backfill_injects_default_in_memory_ttl():
|
|
"""Sync batch_get_cache's Redis-to-memory backfill must honor
|
|
default_in_memory_ttl, same as the async path."""
|
|
in_memory_cache = InMemoryCache(default_ttl=600)
|
|
mock_redis = _redis_mock_for_sync_batch({"batch_backfill_key": "redis_value"})
|
|
dual_cache = DualCache(
|
|
in_memory_cache=in_memory_cache,
|
|
redis_cache=mock_redis,
|
|
default_in_memory_ttl=60,
|
|
)
|
|
|
|
before = time.time()
|
|
result = dual_cache.batch_get_cache(keys=["batch_backfill_key"])
|
|
after = time.time()
|
|
|
|
assert result == ["redis_value"]
|
|
expiry = in_memory_cache.ttl_dict["batch_backfill_key"]
|
|
assert expiry >= before + 60
|
|
assert expiry <= after + 60
|
|
|
|
|
|
def test_dual_cache_batch_get_cache_forwards_explicit_ttl_to_backfill():
|
|
"""An explicit ttl kwarg must reach the in-memory backfill flat, not nested
|
|
under a 'kwargs' key the way the old locals()-forwarding path sent it."""
|
|
in_memory_cache = InMemoryCache(default_ttl=600)
|
|
mock_redis = _redis_mock_for_sync_batch({"explicit_ttl_key": "redis_value"})
|
|
dual_cache = DualCache(in_memory_cache=in_memory_cache, redis_cache=mock_redis)
|
|
|
|
before = time.time()
|
|
result = dual_cache.batch_get_cache(keys=["explicit_ttl_key"], ttl=5)
|
|
after = time.time()
|
|
|
|
assert result == ["redis_value"]
|
|
expiry = in_memory_cache.ttl_dict["explicit_ttl_key"]
|
|
assert expiry >= before + 5
|
|
assert expiry <= after + 5
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_async_set_cache_injects_default_in_memory_ttl():
|
|
"""
|
|
Test that async_set_cache injects default_in_memory_ttl into kwargs
|
|
when no explicit ttl is provided, matching the sync set_cache behavior.
|
|
|
|
Regression test for: async_set_cache was missing the TTL injection that
|
|
sync set_cache has, causing InMemoryCache to use its own default_ttl (600s)
|
|
instead of DualCache's default_in_memory_ttl.
|
|
"""
|
|
in_memory_cache = InMemoryCache(default_ttl=600)
|
|
dual_cache = DualCache(
|
|
in_memory_cache=in_memory_cache,
|
|
default_in_memory_ttl=60,
|
|
)
|
|
|
|
before = time.time()
|
|
await dual_cache.async_set_cache(key="test_key", value="test_value")
|
|
after = time.time()
|
|
|
|
# The TTL stored should reflect default_in_memory_ttl (60s), not
|
|
# InMemoryCache's default_ttl (600s)
|
|
expiry = in_memory_cache.ttl_dict["test_key"]
|
|
assert expiry >= before + 60
|
|
assert expiry <= after + 60
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_redis_backfill_injects_default_in_memory_ttl():
|
|
"""
|
|
A Redis-hit backfill into the in-memory tier must honor
|
|
default_in_memory_ttl the same way the write paths do. Without it, the
|
|
backfilled entry falls to InMemoryCache's own default_ttl (600s), so a
|
|
replica that primed a management object (e.g. a virtual key's auth blob)
|
|
from Redis keeps serving it for 10 minutes after the object was updated
|
|
and invalidated, instead of re-reading within the configured TTL.
|
|
"""
|
|
in_memory_cache = InMemoryCache(default_ttl=600)
|
|
redis_cache = MagicMock()
|
|
redis_cache.async_get_cache = AsyncMock(return_value="redis_value")
|
|
dual_cache = DualCache(
|
|
in_memory_cache=in_memory_cache,
|
|
redis_cache=redis_cache,
|
|
default_in_memory_ttl=60,
|
|
)
|
|
|
|
before = time.time()
|
|
result = await dual_cache.async_get_cache(key="backfill_key")
|
|
after = time.time()
|
|
|
|
assert result == "redis_value"
|
|
expiry = in_memory_cache.ttl_dict["backfill_key"]
|
|
assert expiry >= before + 60
|
|
assert expiry <= after + 60
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_batch_redis_backfill_injects_default_in_memory_ttl():
|
|
"""async_batch_get_cache's Redis-to-memory backfill must honor
|
|
default_in_memory_ttl, same as the single-key path."""
|
|
in_memory_cache = InMemoryCache(default_ttl=600)
|
|
mock_redis = MagicMock(spec=RedisCache)
|
|
mock_redis.async_batch_get_cache = AsyncMock(
|
|
return_value={"batch_backfill_key": "redis_value"}
|
|
)
|
|
dual_cache = DualCache(
|
|
in_memory_cache=in_memory_cache,
|
|
redis_cache=mock_redis,
|
|
default_in_memory_ttl=60,
|
|
)
|
|
|
|
before = time.time()
|
|
result = await dual_cache.async_batch_get_cache(keys=["batch_backfill_key"])
|
|
after = time.time()
|
|
|
|
assert result == ["redis_value"]
|
|
expiry = in_memory_cache.ttl_dict["batch_backfill_key"]
|
|
assert expiry >= before + 60
|
|
assert expiry <= after + 60
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_async_set_cache_respects_explicit_ttl():
|
|
"""
|
|
Test that async_set_cache does NOT override an explicitly provided ttl.
|
|
"""
|
|
in_memory_cache = InMemoryCache(default_ttl=600)
|
|
dual_cache = DualCache(
|
|
in_memory_cache=in_memory_cache,
|
|
default_in_memory_ttl=60,
|
|
)
|
|
|
|
before = time.time()
|
|
await dual_cache.async_set_cache(key="test_key", value="test_value", ttl=30)
|
|
after = time.time()
|
|
|
|
# The explicit ttl=30 should be used, not default_in_memory_ttl (60)
|
|
expiry = in_memory_cache.ttl_dict["test_key"]
|
|
assert expiry >= before + 30
|
|
assert expiry <= after + 30
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_async_set_cache_pipeline_injects_default_in_memory_ttl():
|
|
"""
|
|
Test that async_set_cache_pipeline injects default_in_memory_ttl into kwargs
|
|
when no explicit ttl is provided.
|
|
"""
|
|
in_memory_cache = InMemoryCache(default_ttl=600)
|
|
dual_cache = DualCache(
|
|
in_memory_cache=in_memory_cache,
|
|
default_in_memory_ttl=60,
|
|
)
|
|
|
|
cache_list = [("key_a", "value_a"), ("key_b", "value_b")]
|
|
|
|
before = time.time()
|
|
await dual_cache.async_set_cache_pipeline(cache_list=cache_list)
|
|
after = time.time()
|
|
|
|
for key in ["key_a", "key_b"]:
|
|
expiry = in_memory_cache.ttl_dict[key]
|
|
assert expiry >= before + 60
|
|
assert expiry <= after + 60
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_sync_and_async_set_cache_use_same_ttl():
|
|
"""
|
|
Test that sync set_cache and async async_set_cache produce the same TTL
|
|
when no explicit ttl is provided, ensuring parity between the two paths.
|
|
"""
|
|
in_memory_sync = InMemoryCache(default_ttl=600)
|
|
dual_cache_sync = DualCache(
|
|
in_memory_cache=in_memory_sync,
|
|
default_in_memory_ttl=60,
|
|
)
|
|
|
|
in_memory_async = InMemoryCache(default_ttl=600)
|
|
dual_cache_async = DualCache(
|
|
in_memory_cache=in_memory_async,
|
|
default_in_memory_ttl=60,
|
|
)
|
|
|
|
dual_cache_sync.set_cache(key="test_key", value="test_value")
|
|
await dual_cache_async.async_set_cache(key="test_key", value="test_value")
|
|
|
|
sync_expiry = in_memory_sync.ttl_dict["test_key"]
|
|
async_expiry = in_memory_async.ttl_dict["test_key"]
|
|
|
|
# Both should use default_in_memory_ttl=60, so their expiry times
|
|
# should be within a small tolerance of each other
|
|
assert abs(sync_expiry - async_expiry) < 1.0
|
|
|
|
|
|
def test_circuit_breaker_opens_after_threshold():
|
|
"""Circuit opens after N consecutive Redis failures."""
|
|
from litellm.caching.redis_cache import RedisCircuitBreaker
|
|
|
|
cb = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)
|
|
for _ in range(3):
|
|
cb.record_failure()
|
|
|
|
assert cb._state == "open"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_circuit_breaker_open_skips_redis():
|
|
"""When circuit is open, the guard decorator raises immediately without calling the method."""
|
|
from litellm.caching.redis_cache import (
|
|
RedisCircuitBreaker,
|
|
_redis_circuit_breaker_guard,
|
|
)
|
|
|
|
class FakeRedis:
|
|
def __init__(self):
|
|
self._circuit_breaker = RedisCircuitBreaker(
|
|
failure_threshold=3, recovery_timeout=60
|
|
)
|
|
self._circuit_breaker._state = "open"
|
|
self._circuit_breaker._opened_at = time.time()
|
|
self.call_count = 0
|
|
|
|
@_redis_circuit_breaker_guard
|
|
async def do_thing(self):
|
|
self.call_count += 1
|
|
return "result"
|
|
|
|
fr = FakeRedis()
|
|
with pytest.raises(Exception, match="circuit breaker is open"):
|
|
await fr.do_thing()
|
|
|
|
assert fr.call_count == 0 # method body never executed
|
|
|
|
|
|
def test_circuit_breaker_closes_on_recovery():
|
|
"""After recovery_timeout expires, probe is allowed and success closes the circuit."""
|
|
from litellm.caching.redis_cache import RedisCircuitBreaker
|
|
|
|
cb = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)
|
|
cb._state = "open"
|
|
cb._opened_at = time.time() - 9999 # recovery timeout long expired
|
|
|
|
# is_open() should return False to allow a probe through, and transition to HALF_OPEN
|
|
assert cb.is_open() is False
|
|
assert cb._state == "half_open"
|
|
|
|
# Successful probe closes the circuit
|
|
cb.record_success()
|
|
assert cb._state == "closed"
|
|
|
|
|
|
def test_circuit_breaker_half_open_concurrent_calls_are_fast_failed():
|
|
"""
|
|
Regression test: only ONE probe gets through when the circuit transitions
|
|
OPEN → HALF_OPEN. All concurrent callers that check is_open() while the
|
|
state is already HALF_OPEN must be fast-failed (return True), not allowed
|
|
through as additional probes.
|
|
"""
|
|
from litellm.caching.redis_cache import RedisCircuitBreaker
|
|
|
|
cb = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)
|
|
cb._state = "open"
|
|
cb._opened_at = time.time() - 9999 # recovery timeout long expired
|
|
|
|
# First caller: OPEN + expired → transitions to HALF_OPEN, returns False (probe)
|
|
assert cb.is_open() is False
|
|
assert cb._state == "half_open"
|
|
|
|
# All subsequent concurrent callers: HALF_OPEN → fast-fail (return True)
|
|
for _ in range(10):
|
|
assert (
|
|
cb.is_open() is True
|
|
), "concurrent callers should be fast-failed in HALF_OPEN"
|
|
|
|
|
|
def test_circuit_breaker_disabled_never_opens():
|
|
"""When disabled, failures never open the circuit and is_open() stays False."""
|
|
from litellm.caching.redis_cache import RedisCircuitBreaker
|
|
|
|
cb = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60, enabled=False)
|
|
|
|
for _ in range(100):
|
|
cb.record_failure()
|
|
|
|
assert cb._state == "closed"
|
|
assert cb.is_open() is False
|
|
|
|
|
|
def test_circuit_breaker_disabled_record_success_leaves_state_untouched():
|
|
"""
|
|
A disabled breaker must not mutate state in any state-machine method. Force
|
|
a non-default (OPEN) state and assert record_success() returns without
|
|
resetting it — the same enabled-guard contract as is_open/record_failure.
|
|
"""
|
|
from litellm.caching.redis_cache import RedisCircuitBreaker
|
|
|
|
cb = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60, enabled=False)
|
|
cb._state = "open"
|
|
cb._failure_count = 3
|
|
|
|
cb.record_success()
|
|
|
|
assert cb._state == "open"
|
|
assert cb._failure_count == 3
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_circuit_breaker_disabled_guard_always_calls_method():
|
|
"""A disabled breaker lets every guarded call through, even after failures."""
|
|
from litellm.caching.redis_cache import (
|
|
RedisCircuitBreaker,
|
|
_redis_circuit_breaker_guard,
|
|
)
|
|
|
|
class FakeRedis:
|
|
def __init__(self):
|
|
self._circuit_breaker = RedisCircuitBreaker(
|
|
failure_threshold=1, recovery_timeout=60, enabled=False
|
|
)
|
|
self.call_count = 0
|
|
|
|
@_redis_circuit_breaker_guard
|
|
async def boom(self):
|
|
self.call_count += 1
|
|
raise RuntimeError("redis down")
|
|
|
|
fr = FakeRedis()
|
|
for _ in range(5):
|
|
with pytest.raises(RuntimeError, match="redis down"):
|
|
await fr.boom()
|
|
|
|
# Every call reached the method body; the breaker never short-circuited.
|
|
assert fr.call_count == 5
|
|
assert fr._circuit_breaker.is_open() is False
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_increment_cache_returns_none_when_no_in_memory_cache_and_redis_fails():
|
|
"""
|
|
Regression test: when in_memory_cache is None and Redis fails, async_increment_cache
|
|
must return None — not the raw increment delta — to avoid silently miscalculating
|
|
rate-limit counters.
|
|
"""
|
|
dc = DualCache()
|
|
dc.in_memory_cache = None # type: ignore[assignment] # constructor always creates InMemoryCache, so null it manually
|
|
dc.redis_cache = MagicMock()
|
|
dc.redis_cache.async_increment = AsyncMock(side_effect=Exception("redis down"))
|
|
|
|
result = await dc.async_increment_cache("rpm:model:14-05", 1.0, ttl=60)
|
|
|
|
assert result is None, (
|
|
f"Expected None when in_memory_cache is absent and Redis fails, got {result!r}. "
|
|
"Returning the delta (1.0) would silently miscalculate rate-limit counters."
|
|
)
|
|
|
|
|
|
def test_dual_cache_late_attach_redis_wires_writes_and_ttl_sync():
|
|
"""
|
|
Typical lazy startup (sync): DualCache runs with in-memory only, then Redis
|
|
becomes available and is attached. New writes must reach Redis; keys written
|
|
before attach are not backfilled. Optional default_redis_ttl is applied on attach.
|
|
"""
|
|
in_memory = InMemoryCache()
|
|
dual_cache = DualCache(in_memory_cache=in_memory, redis_cache=None)
|
|
|
|
mock_redis = MagicMock()
|
|
mock_redis.set_cache = MagicMock()
|
|
mock_redis.async_set_cache = AsyncMock()
|
|
|
|
key_before = f"before_attach_{uuid.uuid4()}"
|
|
val_before = {"phase": "memory_only"}
|
|
dual_cache.set_cache(key_before, val_before)
|
|
|
|
assert in_memory.get_cache(key_before) == val_before
|
|
|
|
dual_cache.attach_redis_cache(mock_redis, default_redis_ttl=99.0)
|
|
assert dual_cache.redis_cache is mock_redis
|
|
assert dual_cache.default_redis_ttl == 99.0
|
|
|
|
mock_redis.set_cache.assert_not_called()
|
|
|
|
key_after = f"after_attach_{uuid.uuid4()}"
|
|
val_after = {"phase": "memory_and_redis"}
|
|
dual_cache.set_cache(key_after, val_after)
|
|
mock_redis.set_cache.assert_called_once()
|
|
assert mock_redis.set_cache.call_args[0][:2] == (key_after, val_after)
|
|
|
|
assert in_memory.get_cache(key_after) == val_after
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dual_cache_late_attach_redis_wires_writes_and_ttl_async():
|
|
"""
|
|
Typical lazy startup (async): DualCache runs with in-memory only, then Redis
|
|
becomes available and is attached. New writes must reach Redis; keys written
|
|
before attach are not backfilled. Optional default_redis_ttl is applied on attach.
|
|
"""
|
|
in_memory = InMemoryCache()
|
|
dual_cache = DualCache(in_memory_cache=in_memory, redis_cache=None)
|
|
|
|
mock_redis = MagicMock()
|
|
mock_redis.set_cache = MagicMock()
|
|
mock_redis.async_set_cache = AsyncMock()
|
|
|
|
key_before = f"before_attach_{uuid.uuid4()}"
|
|
val_before = {"phase": "memory_only"}
|
|
await dual_cache.async_set_cache(key_before, val_before)
|
|
|
|
assert in_memory.get_cache(key_before) == val_before
|
|
|
|
dual_cache.attach_redis_cache(mock_redis, default_redis_ttl=99.0)
|
|
assert dual_cache.redis_cache is mock_redis
|
|
assert dual_cache.default_redis_ttl == 99.0
|
|
|
|
mock_redis.async_set_cache.assert_not_called()
|
|
|
|
key_after = f"after_attach_{uuid.uuid4()}"
|
|
val_after = {"phase": "memory_and_redis"}
|
|
await dual_cache.async_set_cache(key_after, val_after)
|
|
mock_redis.async_set_cache.assert_called_once()
|
|
assert mock_redis.async_set_cache.call_args[0][:2] == (key_after, val_after)
|
|
|
|
assert in_memory.get_cache(key_after) == val_after
|
|
|
|
|
|
class _OpenBreakerRedis:
|
|
def __init__(self) -> None:
|
|
from litellm.caching.redis_cache import RedisCircuitBreaker
|
|
|
|
self._circuit_breaker = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)
|
|
for _ in range(3):
|
|
self._circuit_breaker.record_failure()
|
|
|
|
@_redis_circuit_breaker_guard
|
|
async def async_get_cache(self, key, **kwargs):
|
|
raise AssertionError("never reached")
|
|
|
|
@_redis_circuit_breaker_guard
|
|
async def async_batch_get_cache(self, key_list, **kwargs):
|
|
raise AssertionError("never reached")
|
|
|
|
@_redis_circuit_breaker_guard
|
|
async def async_set_cache(self, key, value, **kwargs):
|
|
raise AssertionError("never reached")
|
|
|
|
@_redis_circuit_breaker_guard
|
|
async def async_set_cache_pipeline(self, cache_list, **kwargs):
|
|
raise AssertionError("never reached")
|
|
|
|
@_redis_circuit_breaker_guard
|
|
async def async_increment_pipeline(self, increment_list, **kwargs):
|
|
raise AssertionError("never reached")
|
|
|
|
@_redis_circuit_breaker_guard
|
|
async def async_increment(self, key, value, **kwargs):
|
|
raise AssertionError("never reached")
|
|
|
|
@_redis_circuit_breaker_guard_sync
|
|
def get_cache(self, key, **kwargs):
|
|
raise AssertionError("never reached")
|
|
|
|
@_redis_circuit_breaker_guard_sync
|
|
def batch_get_cache(self, key_list, **kwargs):
|
|
raise AssertionError("never reached")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"call",
|
|
[
|
|
lambda cache: cache.async_get_cache("k"),
|
|
lambda cache: cache.async_batch_get_cache(["k1", "k2"]),
|
|
lambda cache: cache.async_set_cache("k", "v"),
|
|
lambda cache: cache.async_set_cache_pipeline([("k", "v")]),
|
|
lambda cache: cache.async_increment_cache_pipeline(
|
|
increment_list=[RedisPipelineIncrementOperation(key="k", increment_value=1.0, ttl=60)]
|
|
),
|
|
lambda cache: cache.async_increment_cache("k", 1.0),
|
|
],
|
|
ids=["get", "batch_get", "set", "set_pipeline", "increment_pipeline", "increment"],
|
|
)
|
|
async def test_an_open_circuit_breaker_is_not_an_error_per_request(caplog, call):
|
|
cache = DualCache(in_memory_cache=InMemoryCache(), redis_cache=_OpenBreakerRedis()) # pyright: ignore[reportArgumentType] # duck-typed Redis double
|
|
caplog.clear()
|
|
|
|
with caplog.at_level(logging.DEBUG, logger="LiteLLM"):
|
|
await call(cache)
|
|
|
|
assert [record.levelno for record in caplog.records if record.levelno >= logging.WARNING] == []
|
|
assert any("circuit breaker is open" in record.getMessage() for record in caplog.records)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"call",
|
|
[lambda cache: cache.get_cache("k"), lambda cache: cache.batch_get_cache(["k1", "k2"])],
|
|
ids=["get", "batch_get"],
|
|
)
|
|
def test_an_open_circuit_breaker_is_not_an_error_per_sync_request(caplog, call):
|
|
cache = DualCache(in_memory_cache=InMemoryCache(), redis_cache=_OpenBreakerRedis()) # pyright: ignore[reportArgumentType] # duck-typed Redis double
|
|
caplog.clear()
|
|
|
|
with caplog.at_level(logging.DEBUG, logger="LiteLLM"):
|
|
call(cache)
|
|
|
|
assert [record.levelno for record in caplog.records if record.levelno >= logging.WARNING] == []
|
|
assert any("circuit breaker is open" in record.getMessage() for record in caplog.records)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_real_redis_failure_still_logs_an_error(caplog):
|
|
class _BrokenRedis:
|
|
async def async_get_cache(self, key, **kwargs):
|
|
raise ConnectionError("redis is down")
|
|
|
|
cache = DualCache(in_memory_cache=InMemoryCache(), redis_cache=_BrokenRedis()) # pyright: ignore[reportArgumentType] # duck-typed Redis double
|
|
|
|
with caplog.at_level(logging.DEBUG, logger="LiteLLM"):
|
|
assert await cache.async_get_cache("k") is None
|
|
|
|
errors = [record for record in caplog.records if record.levelno == logging.ERROR]
|
|
assert [record.getMessage() for record in errors] == ["LiteLLM Cache: exception in async_get_cache: redis is down"]
|
|
assert errors[0].exc_info is not None
|
|
|
|
|
|
def _dual_cache_with_open_breaker_and_a_memory_hit() -> DualCache:
|
|
in_memory = InMemoryCache()
|
|
in_memory.set_cache("k1", "v1")
|
|
return DualCache(in_memory_cache=in_memory, redis_cache=_OpenBreakerRedis(), default_redis_batch_cache_expiry=10) # pyright: ignore[reportArgumentType] # duck-typed Redis double
|
|
|
|
|
|
def test_open_breaker_keeps_sync_batch_read_memory_hits_and_releases_reservations():
|
|
"""A refused Redis batch read must still answer with the in-memory hits and hold no reservation.
|
|
|
|
The refusal was logged and turned into a bare None, so a caller lost its in-memory hits
|
|
for as long as the breaker stayed open, and the reserved keys stayed throttled until
|
|
the batch expiry passed even though nothing was ever read for them.
|
|
"""
|
|
cache = _dual_cache_with_open_breaker_and_a_memory_hit()
|
|
|
|
assert list(cache.batch_get_cache(["k1", "k2"])) == ["v1", None]
|
|
assert "k2" not in cache.last_redis_batch_access_time
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_open_breaker_keeps_async_batch_read_memory_hits_and_releases_reservations():
|
|
cache = _dual_cache_with_open_breaker_and_a_memory_hit()
|
|
|
|
assert list(await cache.async_batch_get_cache(["k1", "k2"])) == ["v1", None]
|
|
assert "k2" not in cache.last_redis_batch_access_time
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_redis_timeouts_falling_back_to_memory_log_once_per_interval(caplog, monkeypatch):
|
|
"""The first fallback WARNING of a timeout streak logs, the rest stay at DEBUG until the summary."""
|
|
from redis.exceptions import TimeoutError as RedisTimeoutError
|
|
|
|
from litellm.caching import redis_cache as redis_cache_module
|
|
from litellm.caching.redis_cache import _RedisTimeoutLogThrottle
|
|
|
|
clock = MagicMock(return_value=1_000.0)
|
|
monkeypatch.setattr(
|
|
redis_cache_module, "_redis_timeout_log_throttle", _RedisTimeoutLogThrottle(interval=5.0, clock=clock)
|
|
)
|
|
|
|
class _TimingOutRedis:
|
|
async def async_increment_pipeline(self, increment_list, **kwargs):
|
|
raise RedisTimeoutError("Timeout reading from 127.0.0.1:6379")
|
|
|
|
async def async_increment(self, key, value, **kwargs):
|
|
raise RedisTimeoutError("Timeout reading from 127.0.0.1:6379")
|
|
|
|
cache = DualCache(
|
|
in_memory_cache=InMemoryCache(),
|
|
redis_cache=_TimingOutRedis(), # pyright: ignore[reportArgumentType] # duck-typed Redis double
|
|
)
|
|
increments = [RedisPipelineIncrementOperation(key="k", increment_value=1.0, ttl=60)]
|
|
|
|
with caplog.at_level(logging.DEBUG, logger="LiteLLM"):
|
|
for _ in range(100):
|
|
await cache.async_increment_cache_pipeline(increment_list=increments)
|
|
await cache.async_increment_cache("k", 1.0)
|
|
|
|
visible = [r for r in caplog.records if r.levelno >= logging.WARNING]
|
|
assert [(r.levelno, r.getMessage()) for r in visible] == [
|
|
(
|
|
logging.WARNING,
|
|
"Redis async_increment_cache_pipeline failed, falling back to in-memory result:"
|
|
" Timeout reading from 127.0.0.1:6379",
|
|
)
|
|
]
|
|
assert visible[0].filename == "dual_cache.py"
|
|
assert sum("Timeout reading from" in r.getMessage() for r in caplog.records) == 200
|
|
|
|
caplog.clear()
|
|
clock.return_value += 5.0
|
|
with caplog.at_level(logging.DEBUG, logger="LiteLLM"):
|
|
await cache.async_increment_cache("k", 1.0)
|
|
assert [(r.levelno, r.getMessage()) for r in caplog.records] == [
|
|
(
|
|
logging.WARNING,
|
|
"Redis async_increment_cache failed, falling back to in-memory result: Timeout reading from 127.0.0.1:6379"
|
|
" (199 more Redis timeouts since the previous Redis timeout line were logged at DEBUG)",
|
|
)
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_delete_cache_keys_drops_memory_and_chunks_redis():
|
|
"""Batch delete clears both layers, and chunks Redis so one caller's large
|
|
key list cannot become a single oversized DELETE command."""
|
|
redis_cache = MagicMock(spec=RedisCache)
|
|
redis_cache.delete_cache_keys = AsyncMock()
|
|
dual_cache = DualCache(in_memory_cache=InMemoryCache(), redis_cache=redis_cache)
|
|
keys = [f"key-{i}" for i in range(DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE + 7)]
|
|
for key in keys:
|
|
dual_cache.in_memory_cache.set_cache(key=key, value=1)
|
|
|
|
await dual_cache.async_delete_cache_keys(keys)
|
|
|
|
assert all(dual_cache.in_memory_cache.get_cache(key=key) is None for key in keys)
|
|
sent = [call.args[0] for call in redis_cache.delete_cache_keys.await_args_list]
|
|
assert [len(chunk) for chunk in sent] == [DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE, 7]
|
|
assert [key for chunk in sent for key in chunk] == keys
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_delete_cache_keys_on_empty_list_touches_no_backend():
|
|
"""An empty page must not reach Redis: DELETE with no arguments is an error."""
|
|
redis_cache = MagicMock(spec=RedisCache)
|
|
redis_cache.delete_cache_keys = AsyncMock()
|
|
dual_cache = DualCache(in_memory_cache=InMemoryCache(), redis_cache=redis_cache)
|
|
|
|
await dual_cache.async_delete_cache_keys([])
|
|
|
|
redis_cache.delete_cache_keys.assert_not_awaited()
|