Cache
Hypergraph provides cache backends for storing and reusing node execution results.Cache Backends
CacheBackend
Protocol for cache backend implementations. All cache backends must implement:InMemoryCache
Dict-based in-memory cache with optional LRU eviction.Maximum number of entries. None means unlimited
Methods
Return (hit, value). Moves key to end for LRU tracking. Returns (False, None) on cache miss
Store a value. Evicts least-recently-used entry if at capacity
Example
DiskCache
Persistent disk-based cache using diskcache library.Requires
pip install hypergraph[cache] (installs diskcache).Path to the cache directory
Additional arguments passed to
diskcache.CacheSecurity
Values are serialized to bytes with pickle at write time. The raw bytes and an HMAC-SHA256 signature are stored together. On read, the HMAC is verified before deserialization, so tampered payloads are never unpickled. A per-directory secret key is generated on first use and stored in the cache directory.Methods
Return (hit, value) from disk cache. Verifies HMAC integrity before deserializing. Tampered or unsigned entries are evicted and treated as cache misses
Store a value to disk cache with HMAC signature. Serializes to bytes first, computes HMAC over the raw bytes, then stores both. Skips silently if value is not picklable
Example
Cache Key Computation
compute_cache_key
Compute a cache key from node identity and input values.The node’s definition hash (from
node.definition_hash)Resolved input values for the node
str
SHA256 hex digest string, or empty string if inputs are not picklable
- Sort input items by key for determinism
- Serialize sorted inputs with pickle
- Combine definition hash + serialized inputs
- Return SHA256 hash of combined bytes
Using Cache with Nodes
Nodes opt in to caching with thecache=True parameter:
Cache Behavior
What Gets Cached
Only nodes withcache=True participate in caching:
- FunctionNode:
@node(output_name="x", cache=True) - RouteNode:
@route(targets=[...], cache=True) - IfElseNode:
@ifelse(when_true="a", when_false="b", cache=True) - InterruptNode:
@interrupt(output_name="x", cache=True)
Cache Key Components
The cache key includes:- Node definition hash (function source code, parameters, configuration)
- Resolved input values (sorted for determinism)
- Modify function body → new definition hash → cache miss
- Different input values → different cache key → cache miss
- Same inputs, same code → cache hit
Picklability
Both inputs and outputs must be picklable:- Inputs: If not picklable, cache key computation fails → no caching
- Outputs: If not picklable, cache write is skipped → logged warning
Best Practices
When to Use Caching
Cache Invalidation
Caches are automatically invalidated when:- Node code changes (new definition hash)
- Input values change
- InMemoryCache: Create new instance or manually clear dict
- DiskCache: Delete cache directory or specific keys via
diskcache.CacheAPI