Skip to content

Commit a89bad7

Browse files
committed
commonwealth: decorators: add cache invalidation
1 parent 8b4a708 commit a89bad7

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

core/libs/commonwealth/src/commonwealth/utils/decorators.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
def temporary_cache(timeout_seconds: float = 10) -> Callable[[F], F]:
1010
"""Decorator that creates a cache for specific inputs with a configured timeout in seconds.
1111
12+
The wrapped function exposes an `invalidate()` attribute that drops every cached entry,
13+
forcing the next call to re-execute the function. Useful when the cached data is known
14+
to be stale (e.g. after a write that mutates the underlying state).
15+
1216
Args:
1317
timeout_seconds (float, optional): Timeout to be used for cache invalidation. Defaults to 10.
1418
@@ -35,6 +39,11 @@ def wrapper(*args: Any) -> Any:
3539
cache[args] = function_return
3640
return function_return
3741

42+
def invalidate() -> None:
43+
cache.clear()
44+
last_sample_time.clear()
45+
46+
wrapper.invalidate = invalidate # type: ignore[attr-defined]
3847
return wrapper # type: ignore
3948

4049
return inner_function

core/libs/commonwealth/src/commonwealth/utils/tests/test_decorators.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,16 @@ def test_nested_settings_save_load() -> None:
2424

2525
# Check if all cache values are invalid after waiting for a long time
2626
assert all(original_output[key] != cached_function(key) for key in inputs)
27+
28+
29+
def test_temporary_cache_invalidate() -> None:
30+
inputs = ["first", "second", "third"]
31+
original_output = {key: cached_function(key) for key in inputs}
32+
33+
# Cache is still warm: same call returns the same value
34+
assert all(original_output[key] == cached_function(key) for key in inputs)
35+
36+
# Force invalidation; subsequent calls must re-execute the function
37+
cached_function.invalidate() # type: ignore[attr-defined]
38+
39+
assert all(original_output[key] != cached_function(key) for key in inputs)

0 commit comments

Comments
 (0)