Commit Graph

37 Commits

Author SHA1 Message Date
Ishaan Jaff 2ea9e207bd Litellm ishaan march 20 (#24303)
* feat(redis): add circuit breaker to RedisCache to fast-fail when Redis is down (#24181)

* feat(redis): add circuit breaker env var constants

* feat(redis): add RedisCircuitBreaker and apply guard decorator to all async ops

* fix(dual_cache): fall back to L1 instead of re-raising on Redis increment failures

* test(caching): add circuit breaker unit tests

* fix(redis): fast-fail concurrent HALF_OPEN probes — only one probe at a time

* fix(dual_cache): return None fallback when in_memory_cache is absent and Redis fails

* test(caching): add regression tests for HALF_OPEN concurrency and None fallback

* Fix blocking sync next in __anext__ (#24177)

* Fix blocking sync next

* Update tests/test_litellm/litellm_core_utils/test_streaming_handler.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix PEP 479 regression in __anext__ sync iterator exhaustion

asyncio.to_thread re-raises thread exceptions inside a coroutine, where
PEP 479 converts StopIteration to RuntimeError before any except clause
can catch it. Add _next_sync_or_exhausted() module-level helper that
catches StopIteration in the thread and returns a sentinel instead, then
raise StopAsyncIteration in the coroutine.

Also rewrites the non-blocking test to use asyncio.gather() instead of
asyncio.create_task() (which returned None on Python 3.9 / pytest-asyncio
in CI), and adds an exhaustion regression test that drains the wrapper
fully and asserts no RuntimeError leaks out.

---------

Co-authored-by: Emerson Gomes <emerson.gomes@thalesgroup.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* feat: add git-subdir source type to claude-code/plugins API (#24223)

Support a third plugin source type `git-subdir` alongside the existing
`github` and `url` types, as documented in the official Claude Code
plugin marketplaces spec.

New format: {"source": "git-subdir", "url": "...", "path": "subdir/path"}

- Validates url and path fields are present and non-empty
- Rejects absolute paths, '..' segments, backslashes, and percent-encoded
  traversal sequences (including double-encoded variants via regex check)
- Extracts path validation into _validate_git_subdir_path() helper
- Updates Pydantic field description to document all three source types
- Adds isValidUrl() check for url/git-subdir source types in the UI form
- Adds "Git Subdir" option to the UI form with a required Path field
- Adds unit tests covering success, update, missing/empty fields,
  path traversal variants, and unknown source type

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

* [FEAT] add extract_header and extract_footer to Mistral OCR supported params (#24213)

* docs: add git-subdir source type to claude-code plugin marketplace docs (#24289)

* fix(ui): swap J/K keyboard navigation in log details drawer (#24279) (#24286)

J should navigate down (next) and K should navigate up (previous),
matching vim/standard conventions.

* fix: use async_set_cache in user_api_key_auth hot path (#24302)

* fix: use async_set_cache in auth hot path to avoid blocking event loop

* test: assert no blocking set_cache call in _user_api_key_auth_builder

* test: broaden blocking call check to all sync DualCache methods

* test: fix regression test to actually catch blocking cache calls

* fix: ruff lint unused variable + UI build MessageManager error

- litellm/caching/redis_cache.py: remove unused variable 'e' in circuit
  breaker exception handler (F841)
- add_plugin_form.tsx: use MessageManager.error() instead of undefined
  message.error() for git URL validation

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* docs: add REDIS_CIRCUIT_BREAKER env vars to config_settings reference

Add REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD and
REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT to the environment variables
reference table so test_env_keys.py passes.

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

---------

Co-authored-by: Emerson Gomes <emerson.gomes@thalesgroup.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Vincenzo Barrea <manamana88@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Robert Kirscht <rkirscht242@gmail.com>
Co-authored-by: Imgyu Kim <kimimgo@gmail.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>
2026-03-21 12:40:11 -07:00
Chesars feed274aa3 Reapply "feat: add model_cost aliases expansion support"
This reverts commit 3d2df7e8b5.
2026-03-12 13:36:57 -03:00
Chesars 1be6b31e2f merge: resolve conflicts between main and litellm_oss_staging_03_11_2026 2026-03-12 09:38:31 -03:00
Sameer Kankute 3f17a63b81 Merge branch 'main' into litellm_oss_staging_03_02_2026 2026-03-10 17:19:37 +05:30
michelligabriele 8dc0c97958 fix(caching): check REDIS_CLUSTER_NODES env var in Cache and Router class selection (#22790)
When Redis Cluster is configured via the REDIS_CLUSTER_NODES environment
variable, Cache.__init__() and Router._create_redis_cache() ignored the
env var and always created RedisCache instead of RedisClusterCache. This
caused the v3 rate limiter's cluster detection (_is_redis_cluster()) to
return False, skipping hash-slot key grouping. The resulting CROSSLOT
errors were silently caught, falling back to per-instance in-memory
counting — breaking RPM/TPM enforcement across multiple proxy instances.

Add REDIS_CLUSTER_NODES env var detection to both Cache.__init__() and
Router._create_redis_cache(), matching the existing pattern in
_redis.py:215-220. When the env var is set and no explicit startup_nodes
parameter is provided, parse it and create RedisClusterCache.

Fixes #22748
Related to #20836
2026-03-06 17:31:30 -08:00
Ishaan Jaff 503eb2fd4c fix: don't close HTTP/SDK clients on LLMClientCache eviction (#22925)
* fix: don't close HTTP/SDK clients on LLMClientCache eviction

Removing the _remove_key override that eagerly called aclose()/close()
on evicted clients. Evicted clients may still be held by in-flight
streaming requests; closing them causes:

  RuntimeError: Cannot send a request, as the client has been closed.

This is a regression from commit fb72979432. Clients that are no longer
referenced will be garbage-collected naturally. Explicit shutdown cleanup
happens via close_litellm_async_clients().

Fixes production crashes after the 1-hour cache TTL expires.

* test: update LLMClientCache unit tests for no-close-on-eviction behavior

Flip the assertions: evicted clients must NOT be closed. Replace
test_remove_key_closes_async_client → test_remove_key_does_not_close_async_client
and equivalents for sync/eviction paths.

Add test_remove_key_removes_plain_values for non-client cache entries.
Remove test_background_tasks_cleaned_up_after_completion (no more _background_tasks).
Remove test_remove_key_no_event_loop variant that depended on old behavior.

* test: add e2e tests for OpenAI SDK client surviving cache eviction

Add two new e2e tests using real AsyncOpenAI clients:
- test_evicted_openai_sdk_client_stays_usable: verifies size-based eviction
  doesn't close the client
- test_ttl_expired_openai_sdk_client_stays_usable: verifies TTL expiry
  eviction doesn't close the client

Both tests sleep after eviction so any create_task()-based close would
have time to run, making the regression detectable.

Also expand the module docstring to explain why the sleep is required.

* docs(AGENTS.md): add rule — never close HTTP/SDK clients on cache eviction

* docs(CLAUDE.md): add HTTP client cache safety guideline
2026-03-05 12:00:38 -08:00
pnookala-godaddy 239f044721 fix(caching): inject default_in_memory_ttl in DualCache async_set_cache and async_set_cache_pipeline (#22241)
DualCache.async_set_cache and async_set_cache_pipeline were missing the
default_in_memory_ttl injection that the sync set_cache method has. This
caused InMemoryCache to fall back to its own default_ttl (600s) instead
of using DualCache's configured default_in_memory_ttl (typically 60s).

This is particularly impactful for end-user budget enforcement in the
proxy, where cached spend values could remain stale for 10 minutes
instead of 1 minute, allowing users to exceed their budgets.
2026-03-02 21:52:32 -08:00
Shivaang fb72979432 fix(caching): store background task references in LLMClientCache._remove_key to prevent unawaited coroutine warnings
Fixes #22128
2026-02-27 21:23:56 -05:00
Ryan Crabbe dce597b806 Close httpx clients after assertions to prevent resource leaks 2026-02-27 12:58:33 -08:00
Ryan Crabbe 0b7e9a1971 Add e2e tests: httpx clients survive LLMClientCache eviction
Tests go through the real get_async_httpx_client() code path to verify
clients remain usable after both capacity eviction and TTL expiry.
Regression tests for PR #22247.
2026-02-27 12:43:08 -08:00
Ryan Crabbe 6490ad1d48 Revert "Add LLMClientCache regression tests for httpx client eviction safety"
This reverts commit ad9c70ec5d.
2026-02-27 12:43:03 -08:00
Ryan Crabbe ad9c70ec5d Add LLMClientCache regression tests for httpx client eviction safety
Regression tests for PR #22247 — ensures cache eviction (capacity and TTL)
does not close httpx clients that are still in use.
2026-02-27 11:14:13 -08:00
Ryan Crabbe df36845839 fix: remove cache eviction close that kills in-use httpx clients 2026-02-26 17:39:01 -08:00
Ryan Crabbe 68a30a39e6 fix(proxy): add LPOP pipeline error checking and fix org spend ServiceType
- Add per-command error check in _pipeline_lpop_helper to match _pipeline_rpush_helper, preventing silent data loss on WRONGTYPE errors
- Fix pre-existing bug: org spend queue metric was using REDIS_DAILY_SPEND_UPDATE_QUEUE instead of REDIS_DAILY_ORG_SPEND_UPDATE_QUEUE
- Add test for per-command LPOP pipeline error propagation
2026-02-24 14:22:57 -08:00
Ryan Crabbe 98b4964330 perf(proxy): pipeline Redis RPUSH/LPOP in spend update cycle
Replace 14 sequential Redis round-trips (7 RPUSH + 7 LPOP) per spend
update cycle with 2 pipelined calls (1 RPUSH pipeline + 1 LPOP pipeline).
This reduces connection pool contention at scale (50+ pods).

- Add RedisPipelineRpushOperation and RedisPipelineLpopOperation TypedDicts
- Add async_rpush_pipeline() and async_lpop_pipeline() to RedisCache
- Refactor store_in_memory_spend_updates_in_redis() to use pipeline
- Add get_all_transactions_from_redis_buffer_pipeline() for batched drain
- Update _commit_spend_updates_to_db_with_redis() to use pipeline drain
- Existing individual methods preserved for backward compatibility
2026-02-24 12:46:52 -08:00
Sameer Kankute c7aafdf794 Merge pull request #21926 from BerriAI/main
merge main in oss 21 02
2026-02-23 18:17:30 +05:30
Ishaan Jaff 59e5b7e8c6 fix(tests): use monkeypatch.setenv for Redis pool max_connections tests (#21834)
Replace patch('litellm._redis._get_redis_client_logic') with monkeypatch.setenv
in test_max_connections_url_config and test_max_connections_url_config_string_value.

The mock was unreliable in CI (REDIS_URL is set to the real Redis Cloud server),
causing the pool to silently use the real config instead of the test config.
Using monkeypatch.setenv tests the full env-var→pool chain more robustly and
matches the actual production code path.
2026-02-21 14:38:28 -08:00
Zhenting Huang e0aaedc9d1 feat(semantic-cache): support configurable vector dimensions for Qdrant (#21649)
Add vector_size parameter to QdrantSemanticCache and expose it through
the Cache facade as qdrant_semantic_cache_vector_size. This allows users
to use embedding models with dimensions other than the default 1536,
enabling cheaper/stronger models like Stella (1024d), bge-en-icl (4096d),
voyage, cohere, etc.

The parameter defaults to QDRANT_VECTOR_SIZE (env var or 1536) for
backward compatibility. When creating new collections, the configured
vector_size is used instead of the hardcoded constant.

Closes #9377
2026-02-21 00:51:15 -08:00
Ryan Crabbe d6c6d12549 rename test file to test_redis_connection_pool.py 2026-02-20 17:10:08 -08:00
Ryan Crabbe 6931fea929 fix: close leaked Redis connection pools on cache eviction and disconnect
- RC1: Override _remove_key() in LLMClientCache to schedule aclose() on
  evicted async clients instead of relying on GC
- RC2: Use passed connection_pool for URL configs instead of creating an
  orphaned pool via from_url()
- RC3: Pass max_connections through to BlockingConnectionPool.from_url()
  for URL configs, with input validation for invalid values
- RC5: Close sync redis_client in disconnect() with try/except guard
2026-02-20 17:09:32 -08:00
Emerson Gomes 8a650f0170 fix(cache): prevent DualCache async batch check-then-act race (#20986)
* fix(cache): prevent dual cache batch redis race under concurrency

* chore(cache): remove unused dual cache batch key helper

* chore(cache): align dual cache type hints and throttle comment
2026-02-13 18:32:41 +05:30
Alexsander Hamir 727fe504bb fix(redis): handle float redis_version from AWS ElastiCache Valkey (#16207)
* fix(redis): handle float redis_version from AWS ElastiCache Valkey

AWS ElastiCache Valkey returns redis_version as a float (7.0) instead
of a string ('7.0.0'), causing AttributeError: 'float' object has no
attribute 'split' in async_lpop when parsing version for LPOP count.

Changes:
- Extract version parsing into _parse_redis_major_version() helper
- Add DEFAULT_REDIS_MAJOR_VERSION constant (replaces magic number)
- Support multiple version formats: string, float, int, malformed
- Add comprehensive test coverage for all version format edge cases

Fixes: 'LiteLLM Redis Cache LPOP: - Got exception from REDIS' error
during db_spend_update_job cronjobs

* refactor: move DEFAULT_REDIS_MAJOR_VERSION to constants.py
2025-11-04 19:20:00 -08:00
malags 68189d1c04 [Performance] Reduce complexity of InMemoryCache.evict_cache from O(n*log(n)) to O(log(n)) (#15000)
* Improved performance by reducing complexity

* Improved logic to prevent memory from increasing too much, added test

* Restore indent

* Restore indent

* Added type annotation

* Updated test to correctly initialize the expiration_heap
2025-09-30 16:49:35 -07:00
Copilot 1816176f9d [Memory Leak Fix] Fix InMemoryCache unbounded growth when TTLs are set (#14869)
* Initial plan

* Fix InMemoryCache unbounded growth issue when TTLs are set

Co-authored-by: ishaan-jaff <29436595+ishaan-jaff@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ishaan-jaff <29436595+ishaan-jaff@users.noreply.github.com>
2025-09-24 11:54:06 -07:00
Michal Otmianowski c444263e7d verify expires field prior to serving cache entry 2025-08-25 10:42:12 +02:00
Michal Otmianowski a6f052882b fix test 2025-08-21 12:10:29 +02:00
Michal Otmianowski feae09da5d minor adjustments 2025-08-21 11:33:11 +02:00
Michal Otmianowski 5dd7e00127 formatting adjustments 2025-08-21 11:27:12 +02:00
Michal Otmianowski 08c942c306 refactor tests 2025-08-21 10:38:43 +02:00
Michal Otmianowski 744dca1dc3 init asyc implementation 2025-08-21 10:22:54 +02:00
Michal Otmianowski 405e74ec16 use namespace as prefix in s3 2025-08-18 13:43:51 +02:00
Pascal Bro a17d483c89 Add GCS bucket caching support (#13122) 2025-08-04 16:09:33 -07:00
Ishaan Jaff 311d356520 test_qdrant_semantic_cache_async_set_cache 2025-07-19 15:59:56 -07:00
Brian Caswell 45605f8362 add azure blob cache support (#12587)
* add support for Azure Blob caching

* add integration tests

* address feedback
2025-07-15 11:47:38 -07:00
Krish Dholakia db23016536 fix(redis_cache.py): support pipeline redis lpop for older redis vers… (#11425)
* fix(redis_cache.py): support pipeline redis lpop for older redis versions

Fixes https://github.com/BerriAI/litellm/issues/10379

* test: add mock host
2025-06-05 00:05:54 -07:00
Krish Dholakia ba39f9e360 Helicone base url support + fix for embedding cache hits on str input (#11211)
* fix(helicone.py): add helicone api base support

Fixes https://github.com/BerriAI/litellm/issues/10825

* test: add unit test for cache hit response on embedding calls

* fix(caching_handler.py): fix handling cache hit on embedding when input is string

Fixes LIT-197

* docs(helicone_integration.md): document new helicone api base param
2025-05-28 22:02:55 -07:00
Krish Dholakia ef42461c1e Litellm fix GitHub action testing (#11163)
* test: add __init__.py files

* refactor: rename test folder to avoid naming conflict

* test: update workflows

* test: update tests

* test: update imports

* test: update tests

* test: remove unused import

* ci(test-litellm.yml): add pytest retry to github workflow

* test: fix test
2025-05-26 14:41:42 -07:00