From bbdf3824f35adf2b6128a824a77e16a695ccb629 Mon Sep 17 00:00:00 2001 From: Abdulmalik Alquwayfili Date: Thu, 8 Oct 2026 20:11:09 +0300 Subject: [PATCH] fix(cache): preserve falsy values in disk cache reads --- litellm/caching/disk_cache.py | 2 +- tests/unit/caching/test_disk_cache.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/litellm/caching/disk_cache.py b/litellm/caching/disk_cache.py index 50939ad51ca..472a7f52f85 100644 --- a/litellm/caching/disk_cache.py +++ b/litellm/caching/disk_cache.py @@ -42,7 +42,7 @@ class DiskCache(BaseCache): def get_cache(self, key, **kwargs): original_cached_response: Final = self.disk_cache.get(key) - if original_cached_response: + if original_cached_response is not None: try: cached_response = json.loads(original_cached_response) except Exception: diff --git a/tests/unit/caching/test_disk_cache.py b/tests/unit/caching/test_disk_cache.py index 084370726b1..d99076181ea 100644 --- a/tests/unit/caching/test_disk_cache.py +++ b/tests/unit/caching/test_disk_cache.py @@ -1,8 +1,10 @@ import threading import time from concurrent.futures import ThreadPoolExecutor +from typing import Final import pytest +from pydantic import JsonValue pytest.importorskip("diskcache") @@ -20,6 +22,18 @@ def cache(tmp_path): return DiskCache(disk_cache_dir=str(tmp_path)) +@pytest.mark.parametrize("value", (0, False, "", [], {}, 1, {"answer": "cached"})) +async def test_cache_preserves_falsy_values(cache: DiskCache, value: JsonValue) -> None: + await cache.async_set_cache("result", value) + + result: Final = cache.get_cache("result") + assert result == value + assert type(result) is type(value) + assert await cache.async_get_cache("result") == value + assert cache.batch_get_cache(["result", "missing"]) == [value, None] + assert await cache.async_batch_get_cache(["result", "missing"]) == [value, None] + + def test_increment_cache_starts_from_zero_when_key_missing(cache): assert cache.increment_cache("counter", 3) == 3 assert cache.get_cache("counter") == 3 @@ -31,6 +45,12 @@ def test_increment_cache_adds_to_existing_int(cache): assert cache.get_cache("counter") == 12 +def test_increment_cache_preserves_zero_result(cache: DiskCache) -> None: + assert cache.increment_cache("counter", 1) == 1 + assert cache.increment_cache("counter", -1) == 0 + assert cache.get_cache("counter") == 0 + + def test_increment_cache_treats_non_int_cached_value_as_zero(cache): cache.set_cache("counter", "not-a-number") assert cache.increment_cache("counter", 4) == 4