The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: prune expired in-memory cache heap entries (#25664)
Emerson Gomes924418aeeaad
diff --git a/litellm/caching/in_memory_cache.py b/litellm/caching/in_memory_cache.pyindex 5239fa1f4b0..ba446dd4f60 100644--- a/litellm/caching/in_memory_cache.py+++ b/litellm/caching/in_memory_cache.py@@ -161,9 +161,10 @@ class InMemoryCache(BaseCache):if self.max_size_in_memory == 0:return # Don't cache anything if max size is 0- if len(self.cache_dict) >= self.max_size_in_memory:- # only evict when cache is full- self.evict_cache()+ # Always prune expired/outdated heap roots before inserting.+ # This keeps expiration_heap bounded even when the live cache stays+ # below max_size_in_memory and keys are reinserted after TTL expiry.+ self.evict_cache()if not self.check_value_size(value):returndiff --git a/tests/test_litellm/caching/test_in_memory_cache.py b/tests/test_litellm/caching/test_in_memory_cache.pyindex e7cc7f80ab3..8828ebf207e 100644--- a/tests/test_litellm/caching/test_in_memory_cache.py+++ b/tests/test_litellm/caching/test_in_memory_cache.py@@ -97,26 +97,26 @@ def test_in_memory_cache_max_size_with_ttl():"""in_memory_cache = InMemoryCache(max_size_in_memory=3)long_ttl = 86400 # 1 day-+# Fill the cache to max capacityfor i in range(3):in_memory_cache.set_cache(key=f"key_{i}", value=f"value_{i}", ttl=long_ttl)time.sleep(0.01) # Small delay to ensure different timestamps-+assert len(in_memory_cache.cache_dict) == 3assert len(in_memory_cache.ttl_dict) == 3-+# Add another item - should evict the earliest itemin_memory_cache.set_cache(key="key_3", value="value_3", ttl=long_ttl)-+# Cache should still be at max size, not largerassert len(in_memory_cache.cache_dict) == 3assert len(in_memory_cache.ttl_dict) == 3-+# key_0 should have been evicted (it was added first)assert "key_0" not in in_memory_cache.cache_dictassert "key_0" not in in_memory_cache.ttl_dict-+# Other keys should still be presentassert "key_1" in in_memory_cache.cache_dictassert "key_2" in in_memory_cache.cache_dict@@ -128,26 +128,26 @@ def test_in_memory_cache_expired_items_evicted_first():Test that expired items are evicted before non-expired items when cache is full."""in_memory_cache = InMemoryCache(max_size_in_memory=3)-+# Add items with short TTL that will expirein_memory_cache.set_cache(key="expired_1", value="value_1", ttl=1)in_memory_cache.set_cache(key="expired_2", value="value_2", ttl=1)-+# Add item with long TTLin_memory_cache.set_cache(key="long_lived", value="value_long", ttl=86400)-+assert len(in_memory_cache.cache_dict) == 3-+# Wait for short TTL items to expiretime.sleep(2)-+# Add new item - should evict expired items first, not the long-lived onein_memory_cache.set_cache(key="new_item", value="new_value", ttl=86400)-+# Long-lived item should still be presentassert "long_lived" in in_memory_cache.cache_dictassert "new_item" in in_memory_cache.cache_dict-+# Expired items should be goneassert "expired_1" not in in_memory_cache.cache_dictassert "expired_2" not in in_memory_cache.cache_dict@@ -160,29 +160,33 @@ def test_in_memory_cache_eviction_order():Test that when non-expired items need to be evicted, those with earliest expiration times are evicted first."""in_memory_cache = InMemoryCache(max_size_in_memory=2)-+# Add items with different TTLsnow = time.time()- in_memory_cache.set_cache(key="early_expire", value="value_1", ttl=100) # expires in 100 seconds+ in_memory_cache.set_cache(+ key="early_expire", value="value_1", ttl=100+ ) # expires in 100 secondstime.sleep(0.01)- in_memory_cache.set_cache(key="late_expire", value="value_2", ttl=200) # expires in 200 seconds-+ in_memory_cache.set_cache(+ key="late_expire", value="value_2", ttl=200+ ) # expires in 200 seconds+# Verify TTL orderearly_ttl = in_memory_cache.ttl_dict["early_expire"]late_ttl = in_memory_cache.ttl_dict["late_expire"]assert early_ttl < late_ttl, "early_expire should have earlier expiration time"-+assert len(in_memory_cache.cache_dict) == 2-+# Add third item - should evict the one with earliest expiration timein_memory_cache.set_cache(key="new_item", value="value_3", ttl=300)-+assert len(in_memory_cache.cache_dict) == 2-+# Item with earliest expiration should be evictedassert "early_expire" not in in_memory_cache.cache_dictassert "early_expire" not in in_memory_cache.ttl_dict-+# Items with later expiration should remainassert "late_expire" in in_memory_cache.cache_dictassert "new_item" in in_memory_cache.cache_dict@@ -199,3 +203,23 @@ def test_in_memory_cache_heap_size_staus_bounded():# Expiration heap should only have 1 entryassert len(in_memory_cache.expiration_heap) == 1+++def test_in_memory_cache_prunes_expired_heap_entries_below_capacity():+ """+ Re-inserting expired keys below capacity should not grow expiration_heap+ without bound.+ """+ in_memory_cache = InMemoryCache(max_size_in_memory=200, default_ttl=1)++ for cycle in range(3):+ for i in range(5):+ in_memory_cache.set_cache(key=f"key_{i}", value=f"value_{cycle}_{i}", ttl=1)+ time.sleep(1.1)++ for i in range(5):+ in_memory_cache.set_cache(key=f"key_{i}", value=f"value_final_{i}", ttl=1)++ assert len(in_memory_cache.cache_dict) == 5+ assert len(in_memory_cache.ttl_dict) == 5+ assert len(in_memory_cache.expiration_heap) == 5