Skip to main content

manager: improve the caching of generators

ID
d519037
date
2026-11-14 09:35:08+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
0f346d2
message
manager: improve the caching of generators

*   Do not allow caching generators which send/receive values.
*   Allow callers to specify a soft cap for the amount of memory to use
    when buffering a generator output before skipping the cache and
    calling the function directly.
changed files
4 files, 254 additions, 21 deletions

Changed files

CHANGELOG.md (326 → 625)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index c8e8b34..a1a3e39 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
 # CHANGELOG
 
+## v1.0.3 - 2026-11-14
+
+Improve the handling of cached generators:
+
+*   Do not allow caching generators which send/receive values.
+*   Allow callers to specify a soft cap for the amount of memory to use when buffering a generator output before skipping the cache and calling the function directly.
+
 ## 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.

src/funkycache/manager.py (17871 → 21889)

diff --git a/src/funkycache/manager.py b/src/funkycache/manager.py
index 312f6e3..06b4f5b 100644
--- a/src/funkycache/manager.py
+++ b/src/funkycache/manager.py
@@ -5,15 +5,25 @@ Ensure each function has an independent cache.
 """
 
 import atexit
-from collections.abc import Callable, Sequence
+from collections.abc import Callable, Generator, Sequence
 from dataclasses import dataclass
 from functools import wraps
 import inspect
 import itertools
 import json
 from pathlib import Path
+import pickle
 import typing
-from typing import Any, cast, Literal, overload, ParamSpec, Protocol, TypeVar
+from typing import (
+    Any,
+    cast,
+    Literal,
+    NamedTuple,
+    overload,
+    ParamSpec,
+    Protocol,
+    TypeVar,
+)
 import warnings
 
 import xxhash
@@ -161,7 +171,11 @@ class FunkyCache:
 
     @overload
     def register[**P, R](
-        self, *, files: list[Path | str] | None = None, values: list[Any] | None = None
+        self,
+        *,
+        files: list[Path | str] | None = None,
+        values: list[Any] | None = None,
+        max_memory: int | None = None,
     ) -> Callable[[F], F]: ...
 
     def register[**P, R](
@@ -170,6 +184,7 @@ class FunkyCache:
         *,
         files: list[Path | str] | None = None,
         values: list[Any] | None = None,
+        max_memory: int | None = None,
     ) -> F:
         """
         Cache the input/output of func.
@@ -181,6 +196,10 @@ class FunkyCache:
 
         The function's own source file is always a dependency, so editing
         the code that produced a value also invalidates it on the next run.
+
+        If the function is a simple generator, you can set a max_memory.
+        The memory budget is an approximate, best-effort limit in bytes.
+        It's a soft cap, and may be slightly exceeded.
         """
 
         def decorator(func: F) -> F:
@@ -196,6 +215,13 @@ class FunkyCache:
                     "A function cannot depend on a file/folder inside the cache root"
                 )
 
+            # The max_memory argument is only used for generator function;
+            # passing it for non-generator functions is an error.
+            is_generator = inspect.isgeneratorfunction(func)
+
+            if not is_generator and max_memory is not None:
+                raise TypeError("Do not set max_memory for a non-generator function")
+
             # Check if we already have a cache for this function.
             #
             # We must do this before creating the storage, or we could have
@@ -218,8 +244,6 @@ class FunkyCache:
                 bound.apply_defaults()
                 key = bound.arguments
 
-                is_generator = inspect.isgeneratorfunction(func)
-
                 # We need to look up the CacheStorage in self._known_caches
                 # every time, in case it's changed since the last call.
                 storage = self._known_caches[func_name].storage
@@ -234,25 +258,29 @@ class FunkyCache:
                 except Exception as e:
                     warnings.warn(f"unexpected error looking up key in cache: {e}")
 
-                # If the function is a generator, capture up to 10,000 items
-                # in a list and store that. If it returns >10,000 values
+                # If the function is a generator, try to consume the entire
+                # generator and store that. If it returns too much data
                 # (for example, if it's infinite), bypass the cache to avoid
                 # storing an unbounded amount of info.
+                #
+                # TODO: decide how to handle generators that receive values.
                 new_value = func(*args, **kwargs)
                 if is_generator:
-                    list_value = []
-                    for item in itertools.islice(new_value, 10000):
-                        list_value.append(item)
-                    try:
-                        list_value.append(next(new_value))
-                    except StopIteration:
-                        new_value = list_value
+                    gen_result = _materialise_generator(
+                        new_value,
+                        # Default max_memory to 5MB is unspecified by caller
+                        max_memory=max_memory or 5 * 1024 * 1024,
+                    )
+                    if gen_result.is_exhausted:
+                        new_value = gen_result.list_value
                     else:
                         warnings.warn(
-                            "iterator returned more than 10,000 items; "
+                            "iterator returned too many items; "
                             "output will not be cached"
                         )
-                        return cast(R, itertools.chain(iter(list_value), new_value))
+                        return cast(
+                            R, itertools.chain(iter(gen_result.list_value), new_value)
+                        )
 
                 try:
                     storage.set(key, new_value)
@@ -390,8 +418,21 @@ def _data_type(func: F, storage: StorageType) -> Any:
     if inspect.isgeneratorfunction(func):
         origin = typing.get_origin(ret_annotation)
         args = typing.get_args(ret_annotation)
+
+        # Iterator, Iterable, etc.
         if origin is not None and len(args) == 1:
             return list[args[0]]  # type: ignore
+
+        # Generator[YieldType, SendType, ReceiveType]
+        elif origin is not None and len(args) == 3:
+            if args[1] is None and args[2] is None:
+                return list[args[0]]  # type: ignore
+            else:
+                raise TypeError(
+                    f"{func.__name__} is a generator that sends/receives values; "
+                    "it cannot be cached."
+                )
+
         else:
             match storage:
                 case "memory":
@@ -510,3 +551,79 @@ def _input_signature(dep_paths: set[Path], values: list[Any]) -> str:
 
     json_str = json.dumps(signature, sort_keys=True)
     return xxhash.xxh64_hexdigest(json_str.encode("utf8"))
+
+
+class _GeneratorResult[R](NamedTuple):
+    """
+    _GeneratorResult is the materialised result of a generator function.
+    """
+
+    list_value: list[R]
+    is_exhausted: bool
+
+
+def _materialise_generator[R](
+    gen: Generator[R, Any, Any], max_memory: int
+) -> _GeneratorResult:
+    """
+    Consume a generator, materialising items into a list until either
+    the generator is exhausted or the underlying buffer reaches the
+    memory budget.
+
+    The function returns the materialised list of items, and whether
+    the generator was exhausted.
+
+    The memory budget is an approximate, best-effort limit in bytes.
+    It's a soft cap, and may be slightly exceeded.
+    """
+    # As we go along, we want to measure the total memory used by the list,
+    # so we don't exceed our memory budget. Calculating memory usage is
+    # moderately expensive, so we do it in batches. We use pending_items
+    # to track items we haven't measured the size of yet.
+    items: list[R] = []
+    pending_items: list[R] = []
+    current_bytes = 0
+
+    # Start by measuring the size of every item, to get a sense of overall
+    # trends. We'll increase this later.
+    batch_size = 1
+    avg_item_size = 0.0
+
+    for item in gen:
+        items.append(item)
+        pending_items.append(item)
+
+        # When the pending batch reaches the threshold, measure all
+        # of them.
+        if len(pending_items) >= batch_size:
+            # Measure the current batch size
+            batch_bytes = len(pickle.dumps(pending_items))
+            current_bytes += batch_bytes
+
+            # Check if we've breached our soft cap.
+            #
+            # We exit slightly below the given cap, because we'll try
+            # to get one more item from the  generator to determine if
+            # it was exhausted. If the generator isn't exhausted, we
+            # don't want that item to push us further beyond the cap.
+            if current_bytes >= max_memory - avg_item_size:
+                break
+
+            # Count the first ten items 1-by-1, so we get some sense
+            # of how large individual items are.
+            if len(items) < 10:
+                continue
+
+            # Calculate the average item size of items seen so far,
+            # then aim to spend ~10% of our remaining memory budget
+            # on the next batch.
+            avg_item_size = current_bytes / len(items)
+            remaining_memory = max_memory - current_bytes
+            batch_size = max(1, min(50, remaining_memory * 0.1 / avg_item_size))
+
+    try:
+        items.append(next(gen))
+    except StopIteration:
+        return _GeneratorResult(items, is_exhausted=True)
+    else:
+        return _GeneratorResult(items, is_exhausted=False)

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

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

tests/test_manager.py (27827 → 31639)

diff --git a/tests/test_manager.py b/tests/test_manager.py
index 85a12b9..b809238 100644
--- a/tests/test_manager.py
+++ b/tests/test_manager.py
@@ -3,7 +3,7 @@ Tests for the FunkyCache cache manager.
 """
 
 from abc import ABC, abstractmethod
-from collections.abc import Callable, Iterator, Mapping, Sequence
+from collections.abc import Callable, Generator, Iterator, Mapping, Sequence
 from collections import Counter
 import contextlib
 import inspect
@@ -114,6 +114,42 @@ class FunkyCacheTestSuite(ABC):
         assert next(n1) == 2
         assert next(n2) == 1
 
+    def test_cache_simple_generator(self, cache: FunkyCache) -> None:
+        """
+        You can cache a function which returns a simple generator
+        (doesn't receive values).
+        """
+        # Count how many times the underlying function was called
+        calls = Counter[str]()
+
+        @cache.register
+        def numbers(max: int) -> Generator[int, None, None]:
+            """
+            Numbers yields all the numbers between 1 and max.
+            """
+            calls[f"max={max}"] += 1
+            for i in itertools.count(start=1):
+                if i > max:
+                    break
+                yield i
+            else:  # pragma: no cover
+                pass
+
+        # The first call is a cache miss; goes to the real function
+        assert list(numbers(max=3)) == [1, 2, 3]
+        assert calls == {"max=3": 1}
+
+        # The second call is a cache hit; skips the real function
+        assert list(numbers(max=3)) == [1, 2, 3]
+        assert calls == {"max=3": 1}
+
+        # Check that every instance of the generator is independent
+        n1 = numbers(max=3)
+        n2 = numbers(max=3)
+        assert next(n1) == 1
+        assert next(n1) == 2
+        assert next(n2) == 1
+
     def test_infinite_iterator_isnt_cached(self, cache: FunkyCache) -> None:
         """
         You can register a cache on a function which returns an infinite
@@ -130,22 +166,95 @@ class FunkyCacheTestSuite(ABC):
                 pass
 
         # The first call is a cache miss
-        with pytest.warns(match="iterator returned more than 10,000 items"):
+        with pytest.warns(match="iterator returned too many items"):
             assert next(greet_forever("Alex")) == "Hello Alex! (0)"
             assert calls == {"Alex": 1}
 
         # The second call is also a cache miss, because the function was
         # never cached
-        with pytest.warns(match="iterator returned more than 10,000 items"):
+        with pytest.warns(match="iterator returned too many items"):
             assert next(greet_forever("Alex")) == "Hello Alex! (0)"
             assert calls == {"Alex": 2}
 
         # The cached items are combined with the rest of the iterator
-        with pytest.warns(match="iterator returned more than 10,000 items"):
+        with pytest.warns(match="iterator returned too many items"):
             assert list(itertools.islice(greet_forever("Alex"), 11000)) == [
                 f"Hello Alex! ({i})" for i in range(11000)
             ]
 
+    def test_iterator_looks_at_max_memory(self, cache: FunkyCache) -> None:
+        """
+        If you register the cache on a function that returns more items
+        than the max_memory, you get a warning.
+        """
+        calls = Counter[str]()
+
+        @cache.register(max_memory=1)
+        def greet_forever(name: str) -> Iterator[str]:
+            calls[name] += 1
+            for i in range(10):
+                yield f"Hello {name}! ({i})"
+
+        # The first call is a cache miss
+        with pytest.warns(match="iterator returned too many items"):
+            assert next(greet_forever("Alex")) == "Hello Alex! (0)"
+            assert calls == {"Alex": 1}
+
+        # The second call is also a cache miss, because the function was
+        # never cached
+        with pytest.warns(match="iterator returned too many items"):
+            assert next(greet_forever("Alex")) == "Hello Alex! (0)"
+            assert calls == {"Alex": 2}
+
+        # The cached items are combined with the rest of the iterator
+        with pytest.warns(match="iterator returned too many items"):
+            assert list(greet_forever("Alex")) == [
+                f"Hello Alex! ({i})" for i in range(10)
+            ]
+
+    def test_cannot_cache_non_simple_generator(self, cache: FunkyCache) -> None:
+        """
+        You can't cache a function which returns a non-simple generator
+        (sends and receives values).
+        """
+        G = Generator[float | None, float, None]
+
+        def running_average() -> G:  # pragma: no cover
+            """
+            Receive numbers via send and yield the current running average.
+            """
+            total = 0.0
+            count = 0
+            average = None
+
+            while True:
+                value = yield average
+
+                if value is None:
+                    break
+
+                total += value
+                count += 1
+                average = total / count
+
+        with pytest.raises(
+            TypeError, match="running_average is a generator that sends/receives values"
+        ):
+            cache.register(running_average)
+
+    def test_cannot_use_max_memory_with_non_generator(self, cache: FunkyCache) -> None:
+        """
+        You can't pass the max_memory argument when caching a non-generator.
+        """
+        with pytest.raises(
+            TypeError, match="Do not set max_memory for a non-generator function"
+        ):
+
+            @cache.register(max_memory=128)
+            def greet(name: str) -> str:  # pragma: no cover
+                """Return a friendly greeting."""
+                return f"Hello {name}!"
+
     def test_per_function_caches_are_independent(self, cache: FunkyCache) -> None:
         """
         Different functions have different caches.