Skip to main content

adk_graph/functional/
reducers.rs

1//! Typed state reducers for the Functional API.
2//!
3//! This module provides state containers with different persistence semantics:
4//!
5//! - [`ReducedValue<T>`]: Append-only state container persisted across checkpoints.
6//! - [`UntrackedValue<T>`]: Transient runtime value excluded from checkpoint serialization.
7//!   Resets to `T::default()` on workflow resume.
8
9use std::ops::Deref;
10
11use serde::de::DeserializeOwned;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13
14// ---------------------------------------------------------------------------
15// ReducedValue<T>
16// ---------------------------------------------------------------------------
17
18/// Append-only state container. Accumulates values across tasks.
19/// Persisted to checkpoints on each task completion.
20///
21/// # Example
22///
23/// ```rust,ignore
24/// use adk_graph::functional::ReducedValue;
25///
26/// let mut rv = ReducedValue::new();
27/// rv.push(1);
28/// rv.push(2);
29/// assert_eq!(rv.len(), 2);
30/// assert_eq!(&*rv, &[1, 2]);
31/// ```
32#[derive(Debug, Clone, Serialize, Deserialize)]
33#[serde(bound = "T: Serialize + DeserializeOwned")]
34pub struct ReducedValue<T>
35where
36    T: Serialize + DeserializeOwned + Clone + Send + Sync,
37{
38    items: Vec<T>,
39}
40
41impl<T> ReducedValue<T>
42where
43    T: Serialize + DeserializeOwned + Clone + Send + Sync,
44{
45    /// Create an empty `ReducedValue`.
46    pub fn new() -> Self {
47        Self { items: Vec::new() }
48    }
49
50    /// Append a value to the collection.
51    pub fn push(&mut self, value: T) {
52        self.items.push(value);
53    }
54
55    /// Extend with multiple values.
56    pub fn extend(&mut self, values: impl IntoIterator<Item = T>) {
57        self.items.extend(values);
58    }
59
60    /// Get the number of accumulated items.
61    pub fn len(&self) -> usize {
62        self.items.len()
63    }
64
65    /// Check if empty.
66    pub fn is_empty(&self) -> bool {
67        self.items.is_empty()
68    }
69}
70
71impl<T> Deref for ReducedValue<T>
72where
73    T: Serialize + DeserializeOwned + Clone + Send + Sync,
74{
75    type Target = [T];
76    fn deref(&self) -> &[T] {
77        &self.items
78    }
79}
80
81impl<T> Default for ReducedValue<T>
82where
83    T: Serialize + DeserializeOwned + Clone + Send + Sync,
84{
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90// ---------------------------------------------------------------------------
91// UntrackedValue<T>
92// ---------------------------------------------------------------------------
93
94/// Transient runtime value excluded from checkpoints.
95///
96/// `UntrackedValue<T>` stores a value that is intentionally omitted from checkpoint
97/// persistence. When a workflow resumes from a checkpoint, any `UntrackedValue` field
98/// will be initialized to `T::default()` regardless of what value it held before
99/// the checkpoint was created.
100///
101/// This is useful for caching intermediate computation results, holding open file
102/// handles or connections, or any runtime-only state that should not inflate
103/// checkpoint size.
104///
105/// # Custom Serialization
106///
107/// `UntrackedValue` implements `Serialize` by always serializing as `null`, and
108/// `Deserialize` by always producing `T::default()`. This ensures checkpoint
109/// round-trips correctly reset the value.
110///
111/// # Example
112///
113/// ```rust,ignore
114/// use adk_graph::functional::UntrackedValue;
115///
116/// let mut cache: UntrackedValue<Vec<String>> = UntrackedValue::new();
117/// cache.set(vec!["cached_result".to_string()]);
118/// assert_eq!(cache.get().len(), 1);
119///
120/// // After checkpoint round-trip, value resets to default
121/// let serialized = serde_json::to_string(&cache).unwrap();
122/// let restored: UntrackedValue<Vec<String>> = serde_json::from_str(&serialized).unwrap();
123/// assert!(restored.get().is_empty());
124/// ```
125#[derive(Debug, Clone)]
126pub struct UntrackedValue<T: Default + Send + Sync> {
127    value: T,
128}
129
130impl<T: Default + Send + Sync> UntrackedValue<T> {
131    /// Create a new `UntrackedValue` initialized to `T::default()`.
132    pub fn new() -> Self {
133        Self { value: T::default() }
134    }
135
136    /// Create a new `UntrackedValue` with an initial value.
137    pub fn with_value(value: T) -> Self {
138        Self { value }
139    }
140
141    /// Get a reference to the contained value.
142    pub fn get(&self) -> &T {
143        &self.value
144    }
145
146    /// Set the contained value.
147    pub fn set(&mut self, value: T) {
148        self.value = value;
149    }
150
151    /// Take the value, replacing it with `T::default()`.
152    pub fn take(&mut self) -> T {
153        std::mem::take(&mut self.value)
154    }
155}
156
157impl<T: Default + Send + Sync> Default for UntrackedValue<T> {
158    fn default() -> Self {
159        Self::new()
160    }
161}
162
163/// Custom serialization: always serializes as `null` to exclude from checkpoints.
164impl<T: Default + Send + Sync> Serialize for UntrackedValue<T> {
165    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
166    where
167        S: Serializer,
168    {
169        serializer.serialize_none()
170    }
171}
172
173/// Custom deserialization: always produces `T::default()` regardless of input.
174impl<'de, T: Default + Send + Sync> Deserialize<'de> for UntrackedValue<T> {
175    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
176    where
177        D: Deserializer<'de>,
178    {
179        // Consume and discard whatever value is in the serialized data
180        let _ = serde::de::IgnoredAny::deserialize(deserializer)?;
181        Ok(Self::new())
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    // -----------------------------------------------------------------------
190    // ReducedValue tests
191    // -----------------------------------------------------------------------
192
193    #[test]
194    fn test_reduced_value_new_is_empty() {
195        let rv: ReducedValue<i32> = ReducedValue::new();
196        assert!(rv.is_empty());
197        assert_eq!(rv.len(), 0);
198    }
199
200    #[test]
201    fn test_reduced_value_push_and_deref() {
202        let mut rv = ReducedValue::new();
203        rv.push(1);
204        rv.push(2);
205        rv.push(3);
206        assert_eq!(rv.len(), 3);
207        assert_eq!(&*rv, &[1, 2, 3]);
208    }
209
210    #[test]
211    fn test_reduced_value_extend() {
212        let mut rv = ReducedValue::new();
213        rv.extend(vec![10, 20, 30]);
214        assert_eq!(rv.len(), 3);
215        assert_eq!(&*rv, &[10, 20, 30]);
216    }
217
218    #[test]
219    fn test_reduced_value_serde_round_trip() {
220        let mut rv = ReducedValue::new();
221        rv.push("hello".to_string());
222        rv.push("world".to_string());
223        let json = serde_json::to_string(&rv).unwrap();
224        let restored: ReducedValue<String> = serde_json::from_str(&json).unwrap();
225        assert_eq!(&*restored, &*rv);
226    }
227
228    // -----------------------------------------------------------------------
229    // UntrackedValue tests
230    // -----------------------------------------------------------------------
231
232    #[test]
233    fn test_new_creates_default_value() {
234        let uv: UntrackedValue<i32> = UntrackedValue::new();
235        assert_eq!(*uv.get(), 0);
236    }
237
238    #[test]
239    fn test_with_value_stores_value() {
240        let uv = UntrackedValue::with_value(42);
241        assert_eq!(*uv.get(), 42);
242    }
243
244    #[test]
245    fn test_set_and_get() {
246        let mut uv: UntrackedValue<String> = UntrackedValue::new();
247        assert_eq!(uv.get(), "");
248        uv.set("hello".to_string());
249        assert_eq!(uv.get(), "hello");
250    }
251
252    #[test]
253    fn test_take_returns_value_and_resets() {
254        let mut uv = UntrackedValue::with_value(vec![1, 2, 3]);
255        let taken = uv.take();
256        assert_eq!(taken, vec![1, 2, 3]);
257        assert!(uv.get().is_empty());
258    }
259
260    #[test]
261    fn test_default_trait() {
262        let uv: UntrackedValue<bool> = UntrackedValue::default();
263        assert!(!*uv.get());
264    }
265
266    #[test]
267    fn test_serialize_produces_null() {
268        let uv = UntrackedValue::with_value(999);
269        let serialized = serde_json::to_string(&uv).unwrap();
270        assert_eq!(serialized, "null");
271    }
272
273    #[test]
274    fn test_deserialize_always_produces_default() {
275        // Deserializing from null
276        let restored: UntrackedValue<i32> = serde_json::from_str("null").unwrap();
277        assert_eq!(*restored.get(), 0);
278
279        // Deserializing from an arbitrary value
280        let restored: UntrackedValue<i32> = serde_json::from_str("42").unwrap();
281        assert_eq!(*restored.get(), 0);
282
283        // Deserializing from an array
284        let restored: UntrackedValue<Vec<i32>> = serde_json::from_str("[1,2,3]").unwrap();
285        assert!(restored.get().is_empty());
286    }
287
288    #[test]
289    fn test_round_trip_resets_value() {
290        let uv = UntrackedValue::with_value("important data".to_string());
291        let serialized = serde_json::to_string(&uv).unwrap();
292        let restored: UntrackedValue<String> = serde_json::from_str(&serialized).unwrap();
293        assert_eq!(restored.get(), "");
294    }
295}