1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! State management for graph execution
//!
//! Provides typed state with reducers for controlling how updates are merged.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
/// Graph state - a map of channel names to values
pub type State = HashMap<String, Value>;
/// Reducer determines how state updates are merged
#[derive(Clone)]
pub enum Reducer {
/// Replace the value entirely (default)
Overwrite,
/// Append to a list
Append,
/// Sum numeric values
Sum,
/// Custom merge function
Custom(Arc<dyn Fn(Value, Value) -> Value + Send + Sync>),
}
// Cannot derive Default because of the Custom variant with Arc<dyn Fn>
#[allow(clippy::derivable_impls)]
impl Default for Reducer {
fn default() -> Self {
Self::Overwrite
}
}
impl std::fmt::Debug for Reducer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Overwrite => write!(f, "Overwrite"),
Self::Append => write!(f, "Append"),
Self::Sum => write!(f, "Sum"),
Self::Custom(_) => write!(f, "Custom"),
}
}
}
/// Channel definition for a state field
#[derive(Clone)]
pub struct Channel {
/// Channel name
pub name: String,
/// Reducer for merging updates
pub reducer: Reducer,
/// Default value
pub default: Option<Value>,
}
impl Channel {
/// Create a new channel with overwrite semantics
pub fn new(name: &str) -> Self {
Self { name: name.to_string(), reducer: Reducer::Overwrite, default: None }
}
/// Create a list channel with append semantics
pub fn list(name: &str) -> Self {
Self { name: name.to_string(), reducer: Reducer::Append, default: Some(json!([])) }
}
/// Create a counter channel with sum semantics
pub fn counter(name: &str) -> Self {
Self { name: name.to_string(), reducer: Reducer::Sum, default: Some(json!(0)) }
}
/// Set the reducer
pub fn with_reducer(mut self, reducer: Reducer) -> Self {
self.reducer = reducer;
self
}
/// Set the default value
pub fn with_default(mut self, default: Value) -> Self {
self.default = Some(default);
self
}
}
/// State schema defines channels and their reducers
#[derive(Clone, Default)]
pub struct StateSchema {
/// Channel definitions
pub channels: HashMap<String, Channel>,
}
impl StateSchema {
/// Create a new empty schema
pub fn new() -> Self {
Self::default()
}
/// Create a schema builder
pub fn builder() -> StateSchemaBuilder {
StateSchemaBuilder::default()
}
/// Create a simple schema with just channel names (all overwrite)
pub fn simple(channels: &[&str]) -> Self {
let mut schema = Self::new();
for name in channels {
schema.channels.insert((*name).to_string(), Channel::new(name));
}
schema
}
/// Get the reducer for a channel
pub fn get_reducer(&self, channel: &str) -> &Reducer {
self.channels.get(channel).map(|c| &c.reducer).unwrap_or(&Reducer::Overwrite)
}
/// Returns the first of `keys` that this schema does not declare.
///
/// Returns `None` when the schema declares no channels, because then there
/// is nothing to check against.
///
/// # Example
///
/// ```
/// use adk_graph::state::StateSchema;
///
/// let schema = StateSchema::simple(&["kept"]);
/// assert_eq!(schema.first_undeclared(["kept"]), None);
/// assert_eq!(schema.first_undeclared(["kept", "typo"]), Some("typo"));
/// ```
pub fn first_undeclared<'a>(&self, keys: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
if self.channels.is_empty() {
return None;
}
keys.into_iter().find(|key| !self.channels.contains_key(*key))
}
/// Get the default value for a channel
pub fn get_default(&self, channel: &str) -> Option<&Value> {
self.channels.get(channel).and_then(|c| c.default.as_ref())
}
/// Apply an update to state using the appropriate reducer
pub fn apply_update(&self, state: &mut State, key: &str, value: Value) {
let reducer = self.get_reducer(key);
let current = state.get(key).cloned().unwrap_or(Value::Null);
let new_value = match reducer {
Reducer::Overwrite => value,
Reducer::Append => {
let mut arr = match current {
Value::Array(a) => a,
Value::Null => vec![],
_ => vec![current],
};
match value {
Value::Array(items) => arr.extend(items),
_ => arr.push(value),
}
Value::Array(arr)
}
Reducer::Sum => {
let current_num = current.as_f64().unwrap_or(0.0);
let add_num = value.as_f64().unwrap_or(0.0);
json!(current_num + add_num)
}
Reducer::Custom(f) => f(current, value),
};
state.insert(key.to_string(), new_value);
}
/// Initialize state with default values
pub fn initialize_state(&self) -> State {
let mut state = State::new();
for (name, channel) in &self.channels {
if let Some(default) = &channel.default {
state.insert(name.clone(), default.clone());
}
}
state
}
}
/// Builder for StateSchema
#[derive(Default)]
pub struct StateSchemaBuilder {
channels: HashMap<String, Channel>,
}
impl StateSchemaBuilder {
/// Add a channel with overwrite semantics
pub fn channel(mut self, name: &str) -> Self {
self.channels.insert(name.to_string(), Channel::new(name));
self
}
/// Add a channel with append semantics (for lists)
pub fn list_channel(mut self, name: &str) -> Self {
self.channels.insert(name.to_string(), Channel::list(name));
self
}
/// Add a counter channel with sum semantics
pub fn counter_channel(mut self, name: &str) -> Self {
self.channels.insert(name.to_string(), Channel::counter(name));
self
}
/// Add a channel with custom reducer
pub fn channel_with_reducer(mut self, name: &str, reducer: Reducer) -> Self {
self.channels.insert(name.to_string(), Channel::new(name).with_reducer(reducer));
self
}
/// Add a channel with default value
pub fn channel_with_default(mut self, name: &str, default: Value) -> Self {
self.channels.insert(name.to_string(), Channel::new(name).with_default(default));
self
}
/// Build the schema
pub fn build(self) -> StateSchema {
StateSchema { channels: self.channels }
}
}
/// Checkpoint data structure for persistence
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Checkpoint {
/// Thread identifier
pub thread_id: String,
/// Unique checkpoint ID
pub checkpoint_id: String,
/// State at this checkpoint
pub state: State,
/// Step number
pub step: usize,
/// Nodes pending execution
pub pending_nodes: Vec<String>,
/// Additional metadata
pub metadata: HashMap<String, Value>,
/// Creation timestamp
pub created_at: chrono::DateTime<chrono::Utc>,
/// The node whose static interrupt produced this checkpoint.
///
/// A static interrupt is raised before the node runs, so the checkpoint holds
/// a frontier that still contains it. Without this marker the resumed run
/// reaches the same conclusion and raises the same interrupt, and the node
/// never executes. The executor clears the marker once that node has run, so
/// a cycle returning to the same gate asks again.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cleared_interrupt: Option<String>,
/// How many times each node has been attempted, for retry policies.
///
/// Held here so a retry budget survives a resume. adk-python does not persist
/// its attempt count, so a resumed node there starts its budget again.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub attempts: HashMap<String, u32>,
/// Outputs of children invoked imperatively from a node body, keyed by child
/// path.
///
/// A resumed parent re-runs from the top, so without this every child would
/// run again. Only successful outputs are recorded: a failed or interrupted
/// child must re-run.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub child_ledger: HashMap<String, Value>,
/// The checkpoint's revision within its thread.
///
/// A [`Checkpointer`](crate::checkpoint::Checkpointer) stores a checkpoint only
/// when its version is greater than every version already stored for the thread,
/// so two writers on one thread cannot interleave: the one that falls behind is
/// refused with [`GraphError::CheckpointConflict`](crate::error::GraphError::CheckpointConflict).
/// The newest checkpoint is the one with the highest version. Versions start at 1.
#[serde(default)]
pub version: u64,
/// Outputs of the nodes that finished in a super-step that did not complete,
/// keyed by node name.
///
/// When one node of a parallel super-step fails, the nodes that succeeded keep
/// their writes here, and a resumed run applies them instead of running those
/// nodes again. Cleared once the super-step completes.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub pending_writes: BTreeMap<String, PendingWrite>,
}
/// What one node of an unfinished super-step produced.
///
/// # Example
///
/// ```
/// use adk_graph::state::PendingWrite;
/// use serde_json::json;
///
/// let write = PendingWrite::new([("summary".to_string(), json!("done"))].into_iter().collect());
/// assert!(write.goto.is_none());
/// ```
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PendingWrite {
/// The channel updates the node returned.
#[serde(default)]
pub updates: HashMap<String, Value>,
/// Successors the node named in place of its edges.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub goto: Option<Vec<String>>,
/// Nodes of the parent graph the node asked to run next.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub goto_parent: Option<Vec<String>>,
}
impl PendingWrite {
/// Creates a pending write holding a node's channel updates.
pub fn new(updates: HashMap<String, Value>) -> Self {
Self { updates, goto: None, goto_parent: None }
}
}
impl Checkpoint {
/// Create a new checkpoint
pub fn new(thread_id: &str, state: State, step: usize, pending_nodes: Vec<String>) -> Self {
Self {
thread_id: thread_id.to_string(),
checkpoint_id: uuid::Uuid::new_v4().to_string(),
state,
step,
pending_nodes,
metadata: HashMap::new(),
// Whole microseconds, the finest precision every backend stores, so a
// loaded checkpoint equals the one saved.
created_at: chrono::SubsecRound::trunc_subsecs(chrono::Utc::now(), 6),
cleared_interrupt: None,
attempts: HashMap::new(),
child_ledger: HashMap::new(),
version: 1,
pending_writes: BTreeMap::new(),
}
}
/// Sets the checkpoint's revision within its thread.
///
/// A writer that continues a thread whose newest checkpoint has version `n`
/// saves version `n + 1`.
///
/// # Example
///
/// ```
/// use adk_graph::state::{Checkpoint, State};
///
/// let first = Checkpoint::new("thread", State::new(), 0, vec!["a".into()]);
/// let next = Checkpoint::new("thread", State::new(), 1, vec![]).with_version(first.version + 1);
/// assert_eq!(next.version, 2);
/// ```
pub fn with_version(mut self, version: u64) -> Self {
self.version = version;
self
}
/// Record the node whose static interrupt produced this checkpoint.
pub fn with_cleared_interrupt(mut self, node: impl Into<String>) -> Self {
self.cleared_interrupt = Some(node.into());
self
}
/// Add metadata to the checkpoint
pub fn with_metadata(mut self, key: &str, value: Value) -> Self {
self.metadata.insert(key.to_string(), value);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_overwrite_reducer() {
let schema = StateSchema::simple(&["value"]);
let mut state = State::new();
schema.apply_update(&mut state, "value", json!(1));
assert_eq!(state.get("value"), Some(&json!(1)));
schema.apply_update(&mut state, "value", json!(2));
assert_eq!(state.get("value"), Some(&json!(2)));
}
#[test]
fn test_append_reducer() {
let schema = StateSchema::builder().list_channel("messages").build();
let mut state = schema.initialize_state();
schema.apply_update(&mut state, "messages", json!({"role": "user", "content": "hi"}));
assert_eq!(state.get("messages"), Some(&json!([{"role": "user", "content": "hi"}])));
schema.apply_update(
&mut state,
"messages",
json!([{"role": "assistant", "content": "hello"}]),
);
assert_eq!(
state.get("messages"),
Some(&json!([
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "hello"}
]))
);
}
#[test]
fn test_sum_reducer() {
let schema = StateSchema::builder().counter_channel("count").build();
let mut state = schema.initialize_state();
assert_eq!(state.get("count"), Some(&json!(0)));
schema.apply_update(&mut state, "count", json!(5));
assert_eq!(state.get("count"), Some(&json!(5.0)));
schema.apply_update(&mut state, "count", json!(3));
assert_eq!(state.get("count"), Some(&json!(8.0)));
}
#[test]
fn test_custom_reducer() {
let schema = StateSchema::builder()
.channel_with_reducer(
"max",
Reducer::Custom(Arc::new(|a, b| {
let a_num = a.as_f64().unwrap_or(f64::MIN);
let b_num = b.as_f64().unwrap_or(f64::MIN);
json!(a_num.max(b_num))
})),
)
.build();
let mut state = State::new();
schema.apply_update(&mut state, "max", json!(5));
schema.apply_update(&mut state, "max", json!(3));
schema.apply_update(&mut state, "max", json!(8));
assert_eq!(state.get("max"), Some(&json!(8.0)));
}
}