lythonic.compose.cached¶
Cache utilities for wrapping callables with SQLite-backed caching.
Cached: SQLite-backed caching layer for namespace callables.
Wraps sync or async methods that return dict or Pydantic BaseModel with
SQLite-backed caching. Each cached method gets its own table with typed
parameter columns (derived from the method signature) and a composite
primary key.
Usage¶
Declare cached callables in namespace config using NsCacheConfig, then
call ns.mount(storage) to activate caching:
from pathlib import Path
from lythonic.compose.namespace import Namespace, NsCacheConfig
from lythonic.compose.engine import StorageConfig
ns = Namespace()
cfg = NsCacheConfig(
nsref="market:fetch_prices",
gref="myapp.downloads:fetch_prices",
min_ttl=0.5, max_ttl=2.0,
)
ns.register("myapp.downloads:fetch_prices", nsref="market:fetch_prices", config=cfg)
ns.mount(StorageConfig(cache_db=Path("cache.db")))
result = ns.market.fetch_prices(ticker="AAPL")
TTL Behavior¶
- age <
min_ttl: return cached value (fresh) min_ttl<= age <max_ttl: probabilistic refresh — probability increases linearly from 0 to 1. On refresh failure, returns stale value.- age >=
max_ttlor cache miss: call original method. On failure, raises.
Validation¶
All method parameters must have types registered as simple_type in
KNOWN_TYPES (primitives, date, datetime, Path). Validated at mount time
via Method.validate_simple_type_args().
Pushback¶
When a cached method raises CacheRefreshPushback(days, namespace_prefix), all
probabilistic refreshes matching the scope are suppressed for the given duration.
If namespace_prefix is omitted, only the raising method is suppressed.
- During the probabilistic window with active pushback: returns stale data.
- Past
max_ttlwith active pushback: raisesCacheRefreshSuppressed. - Cache miss: always calls the method regardless of pushback.
CacheRefreshPushback
¶
Bases: Exception
Raise from a cached method to suppress probabilistic refreshes.
Defaults to suppressing only the raising method; set namespace_prefix
to suppress a group of methods.
Source code in src/lythonic/compose/cached.py
CacheRefreshSuppressed
¶
Bases: Exception
Raised when a cache entry is past max_ttl but refresh is suppressed by an active pushback.
Source code in src/lythonic/compose/cached.py
CacheProhibitDirectCall
¶
Bases: Exception
Raised when a cached method is called directly instead of through
the cache wrapper. Call CacheProhibitDirectCall.require() from
a method body to enforce this.
Source code in src/lythonic/compose/cached.py
require()
staticmethod
¶
mount_cached_node(node, db_path)
¶
Activate caching on a node that has NsCacheConfig. Builds the
sync/async wrapper, creates DDL, and sets node._decorated.
Called by Namespace.mount().
Source code in src/lythonic/compose/cached.py
generate_cache_table_ddl(table_name, method)
¶
Generate CREATE TABLE DDL for a cache table based on the method's parameter types.