Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions ccflow/evaluators/common.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from collections import OrderedDict
from collections.abc import Callable
from types import MappingProxyType
from typing import Any
Expand Down Expand Up @@ -365,8 +366,12 @@ def effective_cache_key(model: CallableModel, context: ContextBase) -> bytes:
class MemoryCacheEvaluator(EvaluatorBase):
"""Evaluator that caches results in memory."""

maxsize: int | None = Field(
None, gt=0, description="Maximum number of results to keep, evicting the least recently used first. None keeps every result."
)

# Note: We make the cache attributes private, so they don't affect tokenization of the MemoryCacheEvaluator itself
_cache: dict[bytes, ResultType] = PrivateAttr({})
_cache: OrderedDict[bytes, ResultType] = PrivateAttr(default_factory=OrderedDict)
_ids: dict[bytes, ModelEvaluationContext] = PrivateAttr({})

def is_transparent(self, context: ModelEvaluationContext) -> bool:
Expand Down Expand Up @@ -396,10 +401,17 @@ def __call__(self, context: ModelEvaluationContext) -> ResultType:
if context.options.get("volatile") or not context.options.get("cacheable"):
return context()
key = self.key(context)
if key not in self._cache:
self._ids[key] = context
self._cache[key] = context()
return self._cache[key]
if key in self._cache:
self._cache.move_to_end(key)
return self._cache[key]
result = context()
self._cache[key] = result
self._ids[key] = context
if self.maxsize is not None:
while len(self._cache) > self.maxsize:
evicted, _ = self._cache.popitem(last=False)
del self._ids[evicted]
return result

def __deepcopy__(self, memo):
# Without this, when the framework makes deep copies of the evaluator (when used in the ModelEvaluationContext),
Expand Down
50 changes: 50 additions & 0 deletions ccflow/tests/evaluators/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import pandas as pd
import pyarrow as pa
from pydantic import ValidationError

from ccflow import (
CallableModel,
Expand Down Expand Up @@ -569,6 +570,55 @@ def __call__(self, context: ModelEvaluationContext):
# FallbackEvaluator is not transparent, so cache key should differ
self.assertEqual(len(cache.cache), 2)

def test_maxsize_evicts_least_recently_used(self):
NodeModel._calls.clear()
model = NodeModel(meta={"name": "n"})
evaluator = MemoryCacheEvaluator(maxsize=2)
with FlowOptionsOverride(options={"evaluator": evaluator, "cacheable": True}):
for day in (1, 2, 1, 3, 1, 2):
model(DateContext(date=date(2022, 1, day)))
self.assertLessEqual(len(evaluator.cache), 2)
self.assertEqual([d.day for _, d in NodeModel._calls], [1, 2, 3, 2])

def test_maxsize_evicts_ids(self):
evaluator = MemoryCacheEvaluator(maxsize=2)
with FlowOptionsOverride(options={"evaluator": evaluator, "cacheable": True}):
for day in (1, 2, 3):
MyDateCallable(offset=1)(DateContext(date=date(2022, 1, day)))
with self.assertRaises(ValueError):
MyRaisingCallable(offset=1)(DateContext(date=date(2022, 1, 4)))
self.assertEqual(len(evaluator.cache), 2)
self.assertEqual(evaluator.ids.keys(), evaluator.cache.keys())

def test_maxsize_none_is_unbounded(self):
evaluator = MemoryCacheEvaluator()
self.assertIsNone(evaluator.maxsize)
with FlowOptionsOverride(options={"evaluator": evaluator, "cacheable": True}):
for day in range(1, 21):
MyDateCallable(offset=1)(DateContext(date=date(2022, 1, day)))
self.assertEqual(len(evaluator.cache), 20)
self.assertEqual(len(evaluator.ids), 20)

def test_maxsize_must_be_positive(self):
for maxsize in (0, -1):
with self.assertRaises(ValidationError):
MemoryCacheEvaluator(maxsize=maxsize)

def test_maxsize_shared_between_models(self):
NodeModel._calls.clear()
evaluator = MemoryCacheEvaluator(maxsize=2)
options = {"evaluator": evaluator, "cacheable": True}
a = NodeModel(meta={"name": "a", "options": options})
b = NodeModel(meta={"name": "b", "options": options})
context = DateContext(date=date(2022, 1, 1))
for model in (a, b, a, b):
model(context)
self.assertEqual(len(evaluator.cache), 2)
b2 = NodeModel(meta={"name": "b2", "options": options})
for model in (b2, b, a):
model(context)
self.assertEqual([name for name, _ in NodeModel._calls], ["a", "b", "b2", "a"])


class TestGraphDeps(TestCase):
def test_graph_deps_diamond(self):
Expand Down
8 changes: 8 additions & 0 deletions docs/wiki/how-to/Cache-Results.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ with FlowOptionsOverride(options={"cacheable": True, "evaluator": evaluator}):

To keep a model out of the cache even when caching is on globally, mark it `volatile=True` in its `@Flow.call`.

The cache keeps every result for the life of the evaluator. If results are large, such as dataframes read by a few downstream models, set `maxsize` to keep only that many results; once full, the least recently used result is evicted:

```python
bounded_evaluator = MemoryCacheEvaluator(maxsize=8)
```

Models that should share a bounded cache must use the same evaluator instance.

## Understand cache invalidation

A model's fields are part of its cache key, so changing them invalidates the cache automatically:
Expand Down
2 changes: 1 addition & 1 deletion docs/wiki/reference/Built-in-Models.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Evaluators control *how* a `CallableModel` runs. Set one through `FlowOptions` (
| :---------------------------------- | :------------------ | :--------------------------------------------------------------------------------------------------- |
| `LazyEvaluator` | `ccflow.evaluators` | Runs the callable only once an attribute of the result is queried. |
| `LoggingEvaluator` | `ccflow.evaluators` | Logs information about evaluating the callable (the default). |
| `MemoryCacheEvaluator` | `ccflow.evaluators` | Caches results in memory. |
| `MemoryCacheEvaluator` | `ccflow.evaluators` | Caches results in memory, optionally keeping only the `maxsize` most recently used. |
| `MultiEvaluator` | `ccflow.evaluators` | Combines multiple evaluators. |
| `GraphEvaluator` | `ccflow.evaluators` | Evaluates the dependency graph in topologically sorted order, running each node once per evaluation. |
| `RetryEvaluator` | `ccflow.evaluators` | Retries evaluation on failure with exponential backoff and jitter. |
Expand Down
Loading