DSPy: The framework for programming—not prompting—language models
Python
fix cache thread unsafety (#8133)
Chen Qiane20c5e9b7c9d
diff --git a/dspy/clients/cache.py b/dspy/clients/cache.pyindex 6ac81240e..26086d3f0 100644--- a/dspy/clients/cache.py+++ b/dspy/clients/cache.py@@ -29,7 +29,6 @@ class Cache:disk_cache_dir: str,disk_size_limit_bytes: Optional[int] = 1024 * 1024 * 10,memory_max_entries: Optional[int] = 1000000,- ignored_args_for_cache_key: Optional[list[str]] = None,):"""Args:@@ -38,7 +37,6 @@ class Cache:disk_cache_dir: The directory where the disk cache is stored.disk_size_limit_bytes: The maximum size of the disk cache (in bytes).memory_max_entries: The maximum size of the in-memory cache (in number of items).- ignored_args_for_cache_key: A list of arguments to ignore when computing the cache key from the request."""self.enable_disk_cache = enable_disk_cache@@ -57,21 +55,21 @@ class Cache:else:self.disk_cache = {}- self.ignored_args_for_cache_key = ignored_args_for_cache_key or []-self._lock = threading.RLock()def __contains__(self, key: str) -> bool:"""Check if a key is in the cache."""return key in self.memory_cache or key in self.disk_cache- def cache_key(self, request: Dict[str, Any]) -> str:+ def cache_key(self, request: Dict[str, Any], ignored_args_for_cache_key: Optional[list[str]] = None) -> str:"""Obtain a unique cache key for the given request dictionary by hashing its JSONrepresentation. For request fields having types that are known to be JSON-incompatible,convert them to a JSON-serializable format before hashing."""+ ignored_args_for_cache_key = ignored_args_for_cache_key or []+def transform_value(value):if isinstance(value, type) and issubclass(value, pydantic.BaseModel):return value.model_json_schema()@@ -93,12 +91,12 @@ class Cache:else:return value- params = {k: transform_value(v) for k, v in request.items() if k not in self.ignored_args_for_cache_key}+ params = {k: transform_value(v) for k, v in request.items() if k not in ignored_args_for_cache_key}return sha256(ujson.dumps(params, sort_keys=True).encode()).hexdigest()- def get(self, request: Dict[str, Any]) -> Any:+ def get(self, request: Dict[str, Any], ignored_args_for_cache_key: Optional[list[str]] = None) -> Any:try:- key = self.cache_key(request)+ key = self.cache_key(request, ignored_args_for_cache_key)except Exception:logger.debug(f"Failed to generate cache key for request: {request}")return None@@ -121,9 +119,9 @@ class Cache:response.usage = {}return response- def put(self, request: Dict[str, Any], value: Any) -> None:+ def put(self, request: Dict[str, Any], value: Any, ignored_args_for_cache_key: Optional[list[str]] = None) -> None:try:- key = self.cache_key(request)+ key = self.cache_key(request, ignored_args_for_cache_key)except Exception:logger.debug(f"Failed to generate cache key for request: {request}")return@@ -166,7 +164,7 @@ class Cache:def request_cache(cache_arg_name: Optional[str] = None,ignored_args_for_cache_key: Optional[list[str]] = ["api_key", "api_base", "base_url"],- *, # everything after this is keyword-only+ *, # everything after this is keyword-onlymaxsize: Optional[int] = None, # legacy / no-op):"""@@ -178,14 +176,13 @@ def request_cache(ignored_args_for_cache_key: A list of arguments to ignore when computing the cache key from the request."""- # ---- Deprecation notice ----------------------------------------------+ # Deprecation noticeif maxsize is not None:logger.warning(- "`maxsize` is deprecated and no longer does anything; "+ "[DEPRECATION] `maxsize` is deprecated and no longer does anything; ""the cache is now handled internally by `dspy.cache`. ""This parameter will be removed in a future release.",)- # ----------------------------------------------------------------------def decorator(fn):@wraps(fn)@@ -193,11 +190,6 @@ def request_cache(import dspycache = dspy.cache- original_ignored_args_for_cache_key = cache.ignored_args_for_cache_key-- # FIXME: Why is this mutating the global cache instead of passing an argument?- cache.ignored_args_for_cache_key = list(ignored_args_for_cache_key) or []-# Use fully qualified function name for uniquenessfn_identifier = f"{fn.__module__}.{fn.__qualname__}"@@ -215,16 +207,15 @@ def request_cache(modified_request["_fn_identifier"] = fn_identifier# Retrieve from cache if available- cached_result = cache.get(modified_request)+ cached_result = cache.get(modified_request, ignored_args_for_cache_key)if cached_result is not None:return cached_result# Otherwise, compute and store the resultresult = fn(*args, **kwargs)- cache.put(modified_request, result)+ cache.put(modified_request, result, ignored_args_for_cache_key)- cache.ignored_args_for_cache_key = original_ignored_args_for_cache_keyreturn resultreturn wrapperdiff --git a/tests/clients/test_cache.py b/tests/clients/test_cache.pyindex 2ced975c9..bf93caa69 100644--- a/tests/clients/test_cache.py+++ b/tests/clients/test_cache.py@@ -200,7 +200,7 @@ def test_save_and_load_memory_cache(cache, tmp_path):assert result == f"Response {requests.index(req)}"-def test_lm_cache_decorator(cache):+def test_request_cache_decorator(cache):"""Test the lm_cache decorator."""from dspy.clients.cache import request_cache@@ -225,3 +225,32 @@ def test_lm_cache_decorator(cache):# Call with different arguments should compute againresult3 = test_function(prompt="Different", model="openai/gpt-4o-mini")assert result3 == "Response for Different with openai/gpt-4o-mini"+++def test_request_cache_decorator_with_ignored_args_for_cache_key(cache):+ """Test the request_cache decorator with ignored_args_for_cache_key."""+ from dspy.clients.cache import request_cache++ # Mock the dspy.cache attribute+ with patch("dspy.cache", cache):+ # Define a test function+ @request_cache(ignored_args_for_cache_key=["model"])+ def test_function1(prompt, model):+ return f"Response for {prompt} with {model}"++ @request_cache()+ def test_function2(prompt, model):+ return f"Response for {prompt} with {model}"++ # First call should compute the result+ result1 = test_function1(prompt="Hello", model="openai/gpt-4o-mini")+ result2 = test_function1(prompt="Hello", model="openai/gpt-4o")++ # Because model arg is ignored, the second call should return the same result as the first+ assert result1 == result2++ result3 = test_function2(prompt="Hello", model="openai/gpt-4o-mini")+ result4 = test_function2(prompt="Hello", model="openai/gpt-4o")++ # Because model arg is not ignored, the second call should return a different result+ assert result3 != result4