storage: tweak the encoding of function args as strings again
- ID
19f9783- date
2026-11-15 14:50:04+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
d519037- message
storage: tweak the encoding of function args as strings again * Recursively handle Pydantic models in dicts/lists * Extract the keys once in lists of dicts * Omit empty dict values- changed files
4 files, 113 additions, 62 deletions
Changed files
CHANGELOG.md (625 → 734)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a1a3e39..5074da0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# CHANGELOG
+## v1.0.4 - 2026-11-15
+
+Tweak how function arguments are encoded as strings to further improve performance.
+
## v1.0.3 - 2026-11-14
Improve the handling of cached generators:
src/funkycache/storage.py (11554 → 12827)
diff --git a/src/funkycache/storage.py b/src/funkycache/storage.py
index bea2de7..bfb1fc3 100644
--- a/src/funkycache/storage.py
+++ b/src/funkycache/storage.py
@@ -8,7 +8,7 @@ a collection of arguments to the return value.
from abc import ABC, abstractmethod
import dataclasses
from datetime import datetime, timezone
-from functools import cache
+import functools
import json
from pathlib import Path
import sqlite3
@@ -299,19 +299,83 @@ class SQLiteCacheStorage[V](TypedCacheStorage[V]):
raise KeyError(key)
-def _make_json_compatible(value: Any) -> Any:
+def _encode_key_as_json(key: dict[str, Any]) -> str:
"""
- Recursively walk an arbitrary structure and prepare it for JSON encoding.
+ Encode a set of arguments to a Python function as a JSON string.
+
+ 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.
+
+ JSON encoding is a significant bottleneck, so we are trying to reduce
+ the JSON object to be as small as possible before encoding it.
+
+ This function must not mutate its input.
"""
- if isinstance(value, dict):
- return {str(k): _make_json_compatible(v) for k, v in value.items()}
- elif isinstance(value, (list, tuple, set)):
- return [_make_json_compatible(item) for item in value]
+ reduced_key = {k: _process_value(v) for k, v in key.items()}
+
+ try:
+ return json.dumps(
+ reduced_key, sort_keys=True, default=str, separators=(",", ":")
+ )
+ except TypeError:
+ clean_key = _make_json_compatible(reduced_key)
+ return json.dumps(clean_key, sort_keys=True, default=str, separators=(",", ":"))
+
+
+def _process_value(val: Any) -> Any:
+ """
+ Prepare a single value for JSON encoding.
+ """
+ # Primitive types: return directly and skip the isinstance() checks.
+ # Large strings should be hashed.
+ if val is None or type(val) in (str, int, float, bool):
+ if isinstance(val, str) and len(val) > 256:
+ return _hash(val)
+ return val
+
+ # Dictionaries: walk recursively, and omit keys for empty values.
+ elif isinstance(val, dict):
+ return {k: _process_value(v) for k, v in val.items() if v}
+
+ # Lists and tuples: walk recursively. If a list/tuple contains a list
+ # of dictionaries, extract the keys/values into separate lists to
+ # avoid repeating the keys in the JSON.
+ elif isinstance(val, (list, tuple)):
+ processed_items = [_process_value(v) for v in val]
+
+ if len(processed_items) <= 1:
+ return processed_items
+
+ if all(isinstance(item, dict) for item in processed_items):
+ all_keys = set().union(*(item.keys() for item in processed_items))
+ sorted_keys = sorted(all_keys)
+
+ values_matrix = [
+ [item.get(k) for k in sorted_keys] for item in processed_items
+ ]
+
+ return {"_keys": sorted_keys, "_values": values_matrix}
+
+ return processed_items
+
+ # Pydantic models and dataclasses: convert to dicts.
+ #
+ # This comes after the isinstance(…, dict) check because every Pydantic
+ # value will hit this branch and the dict() branch, but some values can
+ # go directly into the dict() branch. This reduces isinstance and
+ # is_dataclass calls.
+ elif isinstance(val, BaseModel) or dataclasses.is_dataclass(val):
+ # print(type(val))
+ adapter = _get_type_adapter(type(val))
+ dumped = adapter.dump_python(val, mode="json")
+ return _process_value(dumped)
+
else:
- return value
+ return val
-@cache
+@functools.cache
def _get_type_adapter(target_type: Any) -> TypeAdapter:
"""
Return a TypeAdapter for the given Pydantic type.
@@ -322,53 +386,19 @@ 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:
+def _make_json_compatible(value: Any) -> Any:
"""
- Encode a set of arguments to a Python function as a JSON string.
-
- 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.
+ Recursively walk an arbitrary structure and prepare it for JSON encoding.
"""
- overrides: dict[str, Any] = {}
-
- for name, val in key.items():
- if _should_hash(val):
- overrides[name] = _hash(val)
-
- elif isinstance(val, dict):
- 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))
- 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(reduced_key, sort_keys=True, default=str)
- except TypeError:
- clean_key = _make_json_compatible(reduced_key)
- return json.dumps(clean_key, sort_keys=True, default=str)
+ if isinstance(value, dict):
+ return {str(k): _make_json_compatible(v) for k, v in value.items()}
+ elif isinstance(value, (list, tuple, set)):
+ return [_make_json_compatible(item) for item in value]
+ else:
+ return value
-@cache
+@functools.cache
def _hash(s: str) -> str:
"""
Hash a string to reduce it to a fixed size.
src/funkycache/version.py (55 → 55)
diff --git a/src/funkycache/version.py b/src/funkycache/version.py
index 34d85ed..dbbda4d 100644
--- a/src/funkycache/version.py
+++ b/src/funkycache/version.py
@@ -2,4 +2,4 @@
The FunkyCache version.
"""
-__version__ = "1.0.3"
+__version__ = "1.0.4"
tests/test_storage.py (9624 → 10271)
diff --git a/tests/test_storage.py b/tests/test_storage.py
index 2fe102d..3f10c9e 100644
--- a/tests/test_storage.py
+++ b/tests/test_storage.py
@@ -264,31 +264,48 @@ class Greeting:
KEY_ENCODING_TEST_CASES: list[ParameterSet] = [
- pytest.param({"n": "one"}, '{"n": "one"}', id="str"),
- pytest.param({"n": 1}, '{"n": 1}', id="int"),
+ pytest.param({"n": "one"}, '{"n":"one"}', id="str"),
+ pytest.param({"n": 1}, '{"n":1}', id="int"),
+ pytest.param(
+ {"n": ["one", "uno", "eins"]}, '{"n":["one","uno","eins"]}', id="list"
+ ),
+ pytest.param(
+ {"n": ("one", "uno", "eins")}, '{"n":["one","uno","eins"]}', id="tuple"
+ ),
+ pytest.param({"n": []}, '{"n":[]}', id="empty_list"),
+ pytest.param({"n": [{"en": "one"}]}, '{"n":[{"en":"one"}]}', id="list_1"),
+ pytest.param(
+ {
+ "n": [
+ {"lang": "en", "val": "one"},
+ {"lang": "fr", "val": "un"},
+ {"lang": "de", "val": "eins"},
+ ]
+ },
+ '{"n":{"_keys":["lang","val"],"_values":[["en","one"],["fr","un"],["de","eins"]]}}',
+ id="list_many",
+ ),
pytest.param(
{"n": Shape(sides=4, colour="red")},
- '{"n": {"colour": "red", "sides": 4}}',
+ '{"n":{"colour":"red","sides":4}}',
id="pydantic",
),
pytest.param(
{"n": Greeting(name="alex", message="hello")},
- '{"n": {"message": "hello", "name": "alex"}}',
+ '{"n":{"message":"hello","name":"alex"}}',
id="dataclass",
),
pytest.param(
{"long": "a" * 5000, "short": "a"},
- '{"long": "xxh64:b2b67943d4803cd6", "short": "a"}',
+ '{"long":"xxh64:b2b67943d4803cd6","short":"a"}',
id="long_str",
),
pytest.param(
{"n": {"long": "a" * 5000, "short": "a"}},
- '{"n": {"long": "xxh64:b2b67943d4803cd6", "short": "a"}}',
+ '{"n":{"long":"xxh64:b2b67943d4803cd6","short":"a"}}',
id="long_str",
),
- pytest.param(
- {"n": {Path("1"): "one"}}, '{"n": {"1": "one"}}', id="nested_path_key"
- ),
+ pytest.param({"n": {Path("1"): "one"}}, '{"n":{"1":"one"}}', id="nested_path_key"),
]