adk_graph/cache.rs
1//! Node-level caching for graph execution.
2//!
3//! This module provides a caching layer that stores node execution results keyed
4//! by a blake3 hash of the node name and its input state. Cached results are
5//! returned on subsequent executions with identical inputs, avoiding redundant
6//! computation.
7//!
8//! # Backends
9//!
10//! Two cache backends are supported:
11//!
12//! - **InMemory** (default) — an LRU cache with configurable maximum entries.
13//! - **Redis** (behind the `redis-cache` feature) — a Redis-backed cache using
14//! the `fred` client.
15//!
16//! # Example
17//!
18//! ```rust,ignore
19//! use adk_graph::cache::{CacheBackend, NodeCachePolicy, NodeCache, compute_cache_key};
20//! use std::time::Duration;
21//! use serde_json::json;
22//! use std::collections::HashMap;
23//!
24//! // Define a cache policy with in-memory backend
25//! let policy = NodeCachePolicy {
26//! backend: CacheBackend::InMemory { max_entries: 128 },
27//! ttl: Some(Duration::from_secs(300)),
28//! };
29//!
30//! // Create a cache from the policy
31//! let cache = NodeCache::from_policy(&policy);
32//!
33//! // Compute a cache key from node name and input state
34//! let mut state = HashMap::new();
35//! state.insert("input".to_string(), json!("hello"));
36//! let key = compute_cache_key("my_node", &state);
37//!
38//! // Use the cache
39//! # tokio_test::block_on(async {
40//! assert!(cache.get(&key).await.is_none());
41//! cache.set(&key, json!({"result": 42}), policy.ttl).await;
42//! assert_eq!(cache.get(&key).await, Some(json!({"result": 42})));
43//! # });
44//! ```
45
46use std::collections::HashMap;
47use std::collections::VecDeque;
48use std::sync::Arc;
49use std::time::{Duration, Instant};
50
51use serde_json::Value;
52use tokio::sync::Mutex;
53
54use crate::state::State;
55
56/// Internal type alias for the in-memory LRU cache storage.
57type MemoryStore = Arc<Mutex<(LruCache, Option<Duration>)>>;
58
59/// Cache backend selection.
60///
61/// Determines where cached node results are stored.
62///
63/// # Example
64///
65/// ```rust,ignore
66/// use adk_graph::cache::CacheBackend;
67///
68/// // In-memory LRU cache with 256 max entries
69/// let backend = CacheBackend::InMemory { max_entries: 256 };
70///
71/// // Redis backend (requires `redis-cache` feature)
72/// #[cfg(feature = "redis-cache")]
73/// let backend = CacheBackend::Redis { url: "redis://localhost:6379".to_string() };
74/// ```
75#[derive(Debug, Clone)]
76pub enum CacheBackend {
77 /// In-memory LRU cache with a configurable maximum number of entries.
78 ///
79 /// When the cache is full, the least recently used entry is evicted.
80 InMemory {
81 /// Maximum number of entries to store. When exceeded, the least
82 /// recently used entry is evicted.
83 max_entries: usize,
84 },
85 /// Redis-backed cache (requires the `redis-cache` feature).
86 #[cfg(feature = "redis-cache")]
87 Redis {
88 /// Redis connection URL (e.g. `redis://localhost:6379`).
89 url: String,
90 },
91}
92
93impl Default for CacheBackend {
94 fn default() -> Self {
95 Self::InMemory { max_entries: 128 }
96 }
97}
98
99/// Cache policy for a graph node.
100///
101/// Configures which backend to use and an optional time-to-live for cached entries.
102///
103/// # Example
104///
105/// ```rust,ignore
106/// use adk_graph::cache::{CacheBackend, NodeCachePolicy};
107/// use std::time::Duration;
108///
109/// let policy = NodeCachePolicy {
110/// backend: CacheBackend::InMemory { max_entries: 64 },
111/// ttl: Some(Duration::from_secs(60)),
112/// };
113/// ```
114#[derive(Debug, Clone)]
115pub struct NodeCachePolicy {
116 /// The storage backend for cached results.
117 pub backend: CacheBackend,
118 /// Optional time-to-live for cached entries. Entries older than this
119 /// duration are treated as cache misses. `None` means entries never expire.
120 pub ttl: Option<Duration>,
121}
122
123/// Computes a deterministic cache key from a node name and its input state.
124///
125/// The key is the hex-encoded blake3 hash of the node name concatenated with
126/// the canonical (sorted-key) JSON serialization of the input state.
127///
128/// # Arguments
129///
130/// * `node_name` — the name of the graph node
131/// * `input_state` — the state map provided as input to the node
132///
133/// # Example
134///
135/// ```rust,ignore
136/// use adk_graph::cache::compute_cache_key;
137/// use serde_json::json;
138/// use std::collections::HashMap;
139///
140/// let mut state = HashMap::new();
141/// state.insert("x".to_string(), json!(1));
142/// state.insert("y".to_string(), json!(2));
143///
144/// let key = compute_cache_key("add", &state);
145/// // key is a 64-character hex string (blake3 digest)
146/// assert_eq!(key.len(), 64);
147///
148/// // Same inputs always produce the same key
149/// let key2 = compute_cache_key("add", &state);
150/// assert_eq!(key, key2);
151/// ```
152pub fn compute_cache_key(node_name: &str, input_state: &State) -> String {
153 // Sort keys for deterministic serialization
154 let mut sorted_keys: Vec<&String> = input_state.keys().collect();
155 sorted_keys.sort();
156
157 let mut canonical = serde_json::Map::new();
158 for key in sorted_keys {
159 if let Some(value) = input_state.get(key) {
160 canonical.insert(key.clone(), value.clone());
161 }
162 }
163
164 let state_json = serde_json::to_string(&canonical).unwrap_or_default();
165 let input = format!("{node_name}{state_json}");
166 let hash = blake3::hash(input.as_bytes());
167 hash.to_hex().to_string()
168}
169
170/// A simple LRU (Least Recently Used) cache.
171///
172/// Uses a `HashMap` for O(1) lookups and a `VecDeque` to track access order.
173/// When the cache exceeds `max_entries`, the least recently used entry is evicted.
174#[derive(Debug)]
175struct LruCache {
176 map: HashMap<String, (Value, Instant)>,
177 order: VecDeque<String>,
178 max_entries: usize,
179}
180
181impl LruCache {
182 fn new(max_entries: usize) -> Self {
183 Self {
184 map: HashMap::with_capacity(max_entries),
185 order: VecDeque::with_capacity(max_entries),
186 max_entries,
187 }
188 }
189
190 fn get(&mut self, key: &str, ttl: Option<Duration>) -> Option<Value> {
191 if let Some((value, inserted_at)) = self.map.get(key) {
192 // Check TTL expiration
193 if let Some(ttl) = ttl
194 && inserted_at.elapsed() > ttl
195 {
196 // Entry expired — remove it
197 self.map.remove(key);
198 self.order.retain(|k| k != key);
199 return None;
200 }
201
202 let value = value.clone();
203
204 // Move to back (most recently used)
205 self.order.retain(|k| k != key);
206 self.order.push_back(key.to_string());
207
208 Some(value)
209 } else {
210 None
211 }
212 }
213
214 fn insert(&mut self, key: String, value: Value) {
215 if self.map.contains_key(&key) {
216 // Update existing entry
217 self.map.insert(key.clone(), (value, Instant::now()));
218 self.order.retain(|k| k != &key);
219 self.order.push_back(key);
220 } else {
221 // Evict if at capacity
222 if self.map.len() >= self.max_entries
223 && let Some(evicted) = self.order.pop_front()
224 {
225 self.map.remove(&evicted);
226 }
227 self.order.push_back(key.clone());
228 self.map.insert(key, (value, Instant::now()));
229 }
230 }
231}
232
233/// Node cache that stores and retrieves execution results.
234///
235/// Supports in-memory LRU caching and optionally Redis-backed caching
236/// (behind the `redis-cache` feature flag).
237///
238/// # Example
239///
240/// ```rust,ignore
241/// use adk_graph::cache::{CacheBackend, NodeCache, NodeCachePolicy};
242/// use serde_json::json;
243/// use std::time::Duration;
244///
245/// let policy = NodeCachePolicy {
246/// backend: CacheBackend::InMemory { max_entries: 100 },
247/// ttl: Some(Duration::from_secs(60)),
248/// };
249///
250/// let cache = NodeCache::from_policy(&policy);
251///
252/// # tokio_test::block_on(async {
253/// // Cache miss
254/// assert!(cache.get("key1").await.is_none());
255///
256/// // Store a value
257/// cache.set("key1", json!({"answer": 42}), Some(Duration::from_secs(60))).await;
258///
259/// // Cache hit
260/// assert_eq!(cache.get("key1").await, Some(json!({"answer": 42})));
261/// # });
262/// ```
263pub struct NodeCache {
264 memory: Option<MemoryStore>,
265 #[cfg(feature = "redis-cache")]
266 redis: Option<fred::clients::Client>,
267}
268
269impl NodeCache {
270 /// Creates a new `NodeCache` from a [`NodeCachePolicy`].
271 ///
272 /// For the `InMemory` backend, this initializes an LRU cache with the
273 /// configured maximum entries. For the `Redis` backend, this creates a
274 /// Redis client (connection is established lazily on first use).
275 ///
276 /// # Arguments
277 ///
278 /// * `policy` — the cache policy specifying backend and TTL
279 ///
280 /// # Example
281 ///
282 /// ```rust,ignore
283 /// use adk_graph::cache::{CacheBackend, NodeCache, NodeCachePolicy};
284 /// use std::time::Duration;
285 ///
286 /// let policy = NodeCachePolicy {
287 /// backend: CacheBackend::InMemory { max_entries: 256 },
288 /// ttl: Some(Duration::from_secs(120)),
289 /// };
290 /// let cache = NodeCache::from_policy(&policy);
291 /// ```
292 pub fn from_policy(policy: &NodeCachePolicy) -> Self {
293 match &policy.backend {
294 CacheBackend::InMemory { max_entries } => Self {
295 memory: Some(Arc::new(Mutex::new((LruCache::new(*max_entries), policy.ttl)))),
296 #[cfg(feature = "redis-cache")]
297 redis: None,
298 },
299 #[cfg(feature = "redis-cache")]
300 CacheBackend::Redis { url: _url } => Self {
301 memory: None,
302 redis: {
303 // Create a Redis client config from the URL.
304 // Connection is established on first command.
305 let config = fred::prelude::Config::from_url(_url).unwrap_or_default();
306 Some(fred::clients::Client::new(config, None, None, None))
307 },
308 },
309 }
310 }
311
312 /// Retrieves a cached value by key.
313 ///
314 /// Returns `Some(value)` on a cache hit, or `None` on a miss (including
315 /// expired entries).
316 ///
317 /// # Arguments
318 ///
319 /// * `key` — the cache key (typically produced by [`compute_cache_key`])
320 ///
321 /// # Example
322 ///
323 /// ```rust,ignore
324 /// # tokio_test::block_on(async {
325 /// let value = cache.get("some_key").await;
326 /// if let Some(cached) = value {
327 /// println!("Cache hit: {cached}");
328 /// }
329 /// # });
330 /// ```
331 pub async fn get(&self, key: &str) -> Option<Value> {
332 if let Some(memory) = &self.memory {
333 let mut guard = memory.lock().await;
334 let (lru, ttl) = &mut *guard;
335 return lru.get(key, *ttl);
336 }
337
338 #[cfg(feature = "redis-cache")]
339 if let Some(redis) = &self.redis {
340 use fred::interfaces::KeysInterface;
341 let result: Option<String> = redis.get(key).await.ok()?;
342 return result.and_then(|s| serde_json::from_str(&s).ok());
343 }
344
345 None
346 }
347
348 /// Stores a value in the cache.
349 ///
350 /// For the in-memory backend, the value is stored with the current
351 /// timestamp for TTL tracking. For the Redis backend, the TTL is applied
352 /// as a Redis key expiration.
353 ///
354 /// # Arguments
355 ///
356 /// * `key` — the cache key
357 /// * `value` — the JSON value to cache
358 /// * `ttl` — optional time-to-live for this entry
359 ///
360 /// # Example
361 ///
362 /// ```rust,ignore
363 /// use serde_json::json;
364 /// use std::time::Duration;
365 ///
366 /// # tokio_test::block_on(async {
367 /// cache.set("key", json!({"result": "ok"}), Some(Duration::from_secs(300))).await;
368 /// # });
369 /// ```
370 pub async fn set(&self, key: &str, value: Value, _ttl: Option<Duration>) {
371 if let Some(memory) = &self.memory {
372 let mut guard = memory.lock().await;
373 let (lru, _) = &mut *guard;
374 lru.insert(key.to_string(), value);
375 } else {
376 #[cfg(feature = "redis-cache")]
377 if let Some(redis) = &self.redis {
378 use fred::interfaces::KeysInterface;
379 let serialized = serde_json::to_string(&value).unwrap_or_default();
380 let expiration = _ttl.map(|d| fred::types::Expiration::EX(d.as_secs() as i64));
381 let _: std::result::Result<(), _> =
382 redis.set(key, serialized, expiration, None, false).await;
383 }
384 }
385 }
386}
387
388impl std::fmt::Debug for NodeCache {
389 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390 f.debug_struct("NodeCache").field("has_memory", &self.memory.is_some()).finish()
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397 use serde_json::json;
398
399 #[test]
400 fn test_compute_cache_key_deterministic() {
401 let mut state = State::new();
402 state.insert("a".to_string(), json!(1));
403 state.insert("b".to_string(), json!("hello"));
404
405 let key1 = compute_cache_key("node1", &state);
406 let key2 = compute_cache_key("node1", &state);
407 assert_eq!(key1, key2);
408 assert_eq!(key1.len(), 64); // blake3 hex digest
409 }
410
411 #[test]
412 fn test_compute_cache_key_different_nodes() {
413 let state = State::new();
414 let key1 = compute_cache_key("node_a", &state);
415 let key2 = compute_cache_key("node_b", &state);
416 assert_ne!(key1, key2);
417 }
418
419 #[test]
420 fn test_compute_cache_key_different_state() {
421 let mut state1 = State::new();
422 state1.insert("x".to_string(), json!(1));
423
424 let mut state2 = State::new();
425 state2.insert("x".to_string(), json!(2));
426
427 let key1 = compute_cache_key("node", &state1);
428 let key2 = compute_cache_key("node", &state2);
429 assert_ne!(key1, key2);
430 }
431
432 #[test]
433 fn test_compute_cache_key_order_independent() {
434 let mut state1 = State::new();
435 state1.insert("a".to_string(), json!(1));
436 state1.insert("b".to_string(), json!(2));
437
438 let mut state2 = State::new();
439 state2.insert("b".to_string(), json!(2));
440 state2.insert("a".to_string(), json!(1));
441
442 let key1 = compute_cache_key("node", &state1);
443 let key2 = compute_cache_key("node", &state2);
444 assert_eq!(key1, key2);
445 }
446
447 #[tokio::test]
448 async fn test_node_cache_in_memory_basic() {
449 let policy =
450 NodeCachePolicy { backend: CacheBackend::InMemory { max_entries: 10 }, ttl: None };
451 let cache = NodeCache::from_policy(&policy);
452
453 // Miss
454 assert!(cache.get("key1").await.is_none());
455
456 // Set and hit
457 cache.set("key1", json!({"result": 42}), None).await;
458 assert_eq!(cache.get("key1").await, Some(json!({"result": 42})));
459 }
460
461 #[tokio::test]
462 async fn test_node_cache_lru_eviction() {
463 let policy =
464 NodeCachePolicy { backend: CacheBackend::InMemory { max_entries: 3 }, ttl: None };
465 let cache = NodeCache::from_policy(&policy);
466
467 cache.set("a", json!(1), None).await;
468 cache.set("b", json!(2), None).await;
469 cache.set("c", json!(3), None).await;
470
471 // Access "b" and "c" to make "a" the LRU
472 assert_eq!(cache.get("b").await, Some(json!(2)));
473 assert_eq!(cache.get("c").await, Some(json!(3)));
474
475 // Order is now: a, b, c (a is LRU)
476 // Adding "d" should evict "a"
477 cache.set("d", json!(4), None).await;
478
479 // "a" should be evicted (it was LRU)
480 assert!(cache.get("a").await.is_none());
481 assert_eq!(cache.get("b").await, Some(json!(2)));
482 assert_eq!(cache.get("c").await, Some(json!(3)));
483 assert_eq!(cache.get("d").await, Some(json!(4)));
484 }
485
486 #[tokio::test]
487 async fn test_node_cache_ttl_expiration() {
488 let policy = NodeCachePolicy {
489 backend: CacheBackend::InMemory { max_entries: 10 },
490 ttl: Some(Duration::from_millis(50)),
491 };
492 let cache = NodeCache::from_policy(&policy);
493
494 cache.set("key", json!("value"), Some(Duration::from_millis(50))).await;
495 assert_eq!(cache.get("key").await, Some(json!("value")));
496
497 // Wait for TTL to expire
498 tokio::time::sleep(Duration::from_millis(60)).await;
499 assert!(cache.get("key").await.is_none());
500 }
501}