Skip to main content

storage: don't mutate keys in _encode_key_as_json

ID
0f346d2
date
2026-11-12 20:40:14+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
80aad94
message
storage: don't mutate keys in _encode_key_as_json

If the key gets mutated, a get/set can use different keys, which leads
to cache misses and confusing errors.
changed files
5 files, 83 additions, 9 deletions

Changed files

CHANGELOG.md (171 → 326)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7b6f050..c8e8b34 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
 # CHANGELOG
 
+## v1.0.2 - 2026-11-12
+
+Fix a bug in 1.0.1 where the manager could fail to find already cached values, if the function arguments contained large strings.
+
 ## v1.0.1 - 2026-11-11
 
 Tweak how function arguments are encoded as strings to improve performance in common cases.

src/funkycache/storage.py (11057 → 11554)

diff --git a/src/funkycache/storage.py b/src/funkycache/storage.py
index 5bc224d..bea2de7 100644
--- a/src/funkycache/storage.py
+++ b/src/funkycache/storage.py
@@ -322,6 +322,14 @@ def _get_type_adapter(target_type: Any) -> TypeAdapter:
     return TypeAdapter(target_type)
 
 
+def _should_hash(v: Any) -> bool:
+    """
+    Return whether the value is a long string that should be hashed
+    before JSON-encoding the key.
+    """
+    return isinstance(v, str) and len(v) > 512
+
+
 def _encode_key_as_json(key: dict[str, Any]) -> str:
     """
     Encode a set of arguments to a Python function as a JSON string.
@@ -329,24 +337,34 @@ def _encode_key_as_json(key: dict[str, Any]) -> str:
     This is a lossy transformation that is designed to get a reasonable
     serialisation as JSON. It is possible for values of different types
     to collide.
+
+    This function must not mutate its input.
     """
+    overrides: dict[str, Any] = {}
+
     for name, val in key.items():
-        if isinstance(val, str) and len(val) > 2048:
-            key[name] = _hash(val)
+        if _should_hash(val):
+            overrides[name] = _hash(val)
 
         elif isinstance(val, dict):
-            for k, v in val.items():
-                if isinstance(v, str) and len(v) > 2048:
-                    val[k] = _hash(v)
+            if any(_should_hash(v) for v in val.values()):
+                overrides[name] = {
+                    k: _hash(v) if _should_hash(v) else v for k, v in val.items()
+                }
 
         elif isinstance(val, BaseModel) or dataclasses.is_dataclass(val):
             adapter = _get_type_adapter(type(val))
-            key[name] = adapter.dump_python(val, mode="json")
+            overrides[name] = {
+                k: _hash(v) if _should_hash(v) else v
+                for k, v in adapter.dump_python(val, mode="json").items()
+            }
+
+    reduced_key = {**key, **overrides}
 
     try:
-        return json.dumps(key, sort_keys=True, default=str)
+        return json.dumps(reduced_key, sort_keys=True, default=str)
     except TypeError:
-        clean_key = _make_json_compatible(key)
+        clean_key = _make_json_compatible(reduced_key)
         return json.dumps(clean_key, sort_keys=True, default=str)
 
 

src/funkycache/version.py (55 → 55)

diff --git a/src/funkycache/version.py b/src/funkycache/version.py
index 76c0cbc..dc6f677 100644
--- a/src/funkycache/version.py
+++ b/src/funkycache/version.py
@@ -2,4 +2,4 @@
 The FunkyCache version.
 """
 
-__version__ = "1.0.1"
+__version__ = "1.0.2"

tests/test_integration.py (0 → 788)

diff --git a/tests/test_integration.py b/tests/test_integration.py
new file mode 100644
index 0000000..f1187ef
--- /dev/null
+++ b/tests/test_integration.py
@@ -0,0 +1,36 @@
+"""
+Integration tests for the library.
+"""
+
+from datetime import datetime
+import time
+
+from pydantic import BaseModel
+
+from funkycache import FunkyCache
+
+
+def test_long_mutable_key() -> None:
+    """
+    We can cache a function argument which includes a long key that
+    gets reduced during key encoding.
+
+    This is a regression test for a bug in 1.0.1, where the key would be
+    mutated when we checked if a value was already cached, which led to
+    cache misses and errors about overwriting values.
+    """
+
+    class MyType(BaseModel):
+        content: str = ""
+
+    cache = FunkyCache(storage="memory")
+
+    @cache.register
+    def upcase(tp: MyType) -> str:
+        return str(datetime.now())
+
+    t = MyType(content="a" * 2500)
+
+    upcase(t)
+    time.sleep(0.1)
+    upcase(t)

tests/test_storage.py (9069 → 9624)

diff --git a/tests/test_storage.py b/tests/test_storage.py
index 931c237..2fe102d 100644
--- a/tests/test_storage.py
+++ b/tests/test_storage.py
@@ -5,6 +5,7 @@ Tests for backend storage implementations.
 from abc import ABC, abstractmethod
 from collections.abc import Generator
 from contextlib import closing, contextmanager
+import copy
 from dataclasses import dataclass
 from pathlib import Path
 import sqlite3
@@ -58,12 +59,19 @@ class CacheStorageTestSuite(ABC):
                 {"args": [{Path("n"): "numbers"}]}, id="path_key_nested_in_list"
             ),
             pytest.param({"1": {Path("n"): "numbers"}}, id="path_key_nested_in_obj"),
+            #
+            # A long string which gets truncated during hashing
+            pytest.param({"a": {"n": "n" * 5000}}, id="long_key"),
         ],
     )
     def test_cache(self, key: dict[str, Any], tmp_path: Path) -> None:
         """
         Test the basic properties of a cache.
         """
+        # Take a copy of the original key, to check that get/set
+        # doesn't mutate the key.
+        orig_key = copy.deepcopy(key)
+
         with self.create_storage(tmp_path, data_type=int) as storage:
             fib10 = 55
             fib20 = 6765
@@ -72,10 +80,18 @@ class CacheStorageTestSuite(ABC):
             with pytest.raises(KeyError):
                 storage.get(key)
 
+            assert key == orig_key, (
+                f"key changed after get: key={key!r}, orig_key={orig_key!r}"
+            )
+
             # Store and retrieve a value
             storage.set(key, value=fib10)
             assert storage.get(key) == fib10
 
+            assert key == orig_key, (
+                f"key changed after set: key={key!r}, orig_key={orig_key!r}"
+            )
+
             # Overwriting an existing value is an error.
             with pytest.raises(CannotOverwriteValueException) as exc:
                 storage.set(key, value=fib20)