adk_graph/deferred.rs
1//! Deferred node (fan-in barrier) support for graph workflows.
2//!
3//! Provides fan-in barrier semantics for nodes that wait on multiple upstream
4//! parallel paths before executing. This enables scatter-gather patterns where
5//! work is distributed across parallel branches and then collected at a single
6//! synchronization point.
7//!
8//! # Overview
9//!
10//! A deferred node is declared with a [`DeferredNodeConfig`] that specifies:
11//! - [`MergeStrategy`]: How upstream outputs are combined (collect, merge maps, first, or custom).
12//! - `fan_in_timeout`: Optional maximum wait duration for all upstream paths.
13//!
14//! The [`FanInTracker`] tracks which upstream paths have completed and merges
15//! their outputs according to the configured strategy.
16//!
17//! # Example
18//!
19//! ```rust
20//! use std::time::Duration;
21//! use adk_graph::deferred::{DeferredNodeConfig, FanInTracker, MergeStrategy};
22//! use serde_json::json;
23//!
24//! // Configure a deferred node that collects all upstream outputs
25//! let config = DeferredNodeConfig {
26//! merge_strategy: MergeStrategy::Collect,
27//! fan_in_timeout: Some(Duration::from_secs(30)),
28//! ..Default::default()
29//! };
30//!
31//! // Track upstream completions
32//! let mut tracker = FanInTracker::new(vec!["branch_a", "branch_b", "branch_c"]);
33//!
34//! tracker.record("branch_a", json!({"result": 1}));
35//! tracker.record("branch_b", json!({"result": 2}));
36//! assert!(!tracker.is_ready());
37//!
38//! tracker.record("branch_c", json!({"result": 3}));
39//! assert!(tracker.is_ready());
40//!
41//! // Merge outputs using the configured strategy
42//! let merged = tracker.merge(&config.merge_strategy);
43//! assert_eq!(merged, json!([{"result": 1}, {"result": 2}, {"result": 3}]));
44//! ```
45
46use std::collections::{BTreeMap, HashMap, HashSet};
47use std::fmt;
48use std::sync::Arc;
49use std::time::{Duration, Instant};
50
51use serde::{Deserialize, Serialize};
52use serde_json::Value;
53
54use crate::error::{GraphError, Result};
55
56/// How to combine outputs from multiple upstream parallel paths.
57///
58/// The merge strategy determines how the collected outputs from all upstream
59/// branches are combined into a single value for the deferred node's input.
60///
61/// # Example
62///
63/// ```rust
64/// use adk_graph::deferred::MergeStrategy;
65///
66/// // Default strategy collects all outputs into a Vec
67/// let strategy = MergeStrategy::default();
68/// assert!(matches!(strategy, MergeStrategy::Collect));
69///
70/// // MergeMap combines all output maps with last-write-wins
71/// let strategy = MergeStrategy::MergeMap;
72/// ```
73#[derive(Clone, Default)]
74pub enum MergeStrategy {
75 /// Collect all outputs into a `Vec<Value>`.
76 ///
77 /// Outputs are ordered by the insertion order of source nodes
78 /// (the order in which they were recorded).
79 #[default]
80 Collect,
81
82 /// Merge all output maps into a single map (last-write-wins on key conflict).
83 ///
84 /// Each upstream output is expected to be a JSON object. Non-object outputs
85 /// are skipped. When multiple outputs contain the same key, the value from
86 /// the later-recorded source wins.
87 MergeMap,
88
89 /// Use only the first completed output.
90 ///
91 /// Returns the output from whichever upstream path completed first
92 /// (i.e., was recorded first).
93 First,
94
95 /// Custom merge function.
96 ///
97 /// Accepts a closure that takes all collected outputs and produces a
98 /// single merged value.
99 ///
100 /// # Example
101 ///
102 /// ```rust
103 /// use std::sync::Arc;
104 /// use adk_graph::deferred::MergeStrategy;
105 /// use serde_json::{json, Value};
106 ///
107 /// let strategy = MergeStrategy::Custom(Arc::new(|outputs: Vec<Value>| {
108 /// json!({ "count": outputs.len() })
109 /// }));
110 /// ```
111 Custom(Arc<dyn Fn(Vec<Value>) -> Value + Send + Sync>),
112}
113
114impl fmt::Debug for MergeStrategy {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 match self {
117 Self::Collect => write!(f, "Collect"),
118 Self::MergeMap => write!(f, "MergeMap"),
119 Self::First => write!(f, "First"),
120 Self::Custom(_) => write!(f, "Custom(<fn>)"),
121 }
122 }
123}
124
125/// Configuration for a deferred (fan-in) node.
126///
127/// A deferred node waits for all upstream parallel paths to complete before
128/// executing. The configuration controls how outputs are merged and how long
129/// the node waits.
130///
131/// # Example
132///
133/// ```rust
134/// use std::time::Duration;
135/// use adk_graph::deferred::{DeferredNodeConfig, MergeStrategy};
136///
137/// let config = DeferredNodeConfig {
138/// merge_strategy: MergeStrategy::MergeMap,
139/// fan_in_timeout: Some(Duration::from_secs(60)),
140/// ..Default::default()
141/// };
142/// ```
143#[derive(Debug, Clone, Default)]
144pub struct DeferredNodeConfig {
145 /// Strategy for combining upstream outputs.
146 pub merge_strategy: MergeStrategy,
147
148 /// Maximum time to wait for the predecessors that can still run.
149 ///
150 /// - `None`: Wait until every predecessor that can still run in this pass has
151 /// arrived.
152 /// - `Some(duration)`: If the timeout expires and at least `min_predecessors`
153 /// have arrived, proceed with partial results and ignore the late arrival of
154 /// the others. Otherwise, return `GraphError::FanInTimedOut`.
155 pub fan_in_timeout: Option<Duration>,
156 /// How many predecessors must have arrived for the node to be released with
157 /// partial results.
158 ///
159 /// `None` means one, which is the behaviour this field replaced. Set it to
160 /// the full predecessor count to require all of them even after a timeout, or
161 /// to any value between for an n-of-m join: release once that many branches
162 /// have answered and abandon the rest. A node whose remaining predecessors can
163 /// no longer run, and that has fewer than this, fails with
164 /// `GraphError::FanInIncomplete`.
165 pub min_predecessors: Option<usize>,
166}
167
168/// Tracks which upstream paths have completed for a deferred node.
169///
170/// The tracker maintains a set of expected source nodes and records their
171/// outputs as they arrive. Once all expected sources have reported, the
172/// tracker is ready and outputs can be merged.
173///
174/// # Example
175///
176/// ```rust
177/// use adk_graph::deferred::{FanInTracker, MergeStrategy};
178/// use serde_json::json;
179///
180/// let mut tracker = FanInTracker::new(vec!["node_a", "node_b"]);
181///
182/// assert!(!tracker.is_ready());
183/// assert_eq!(tracker.received_count(), 0);
184/// assert_eq!(tracker.expected_count(), 2);
185///
186/// tracker.record("node_a", json!("output_a"));
187/// assert!(!tracker.is_ready());
188///
189/// tracker.record("node_b", json!("output_b"));
190/// assert!(tracker.is_ready());
191///
192/// let merged = tracker.merge(&MergeStrategy::Collect);
193/// assert_eq!(merged, json!(["output_a", "output_b"]));
194/// ```
195pub struct FanInTracker {
196 /// The set of source node names we expect to receive output from.
197 expected: HashSet<String>,
198 /// Outputs received so far, keyed by source node name.
199 received: HashMap<String, Value>,
200 /// Insertion order of received outputs (for deterministic merge ordering).
201 insertion_order: Vec<String>,
202}
203
204impl FanInTracker {
205 /// Create a new tracker expecting outputs from the given source nodes.
206 ///
207 /// # Arguments
208 ///
209 /// * `expected_sources` - Names of upstream nodes that must complete
210 /// before this deferred node can execute.
211 ///
212 /// # Example
213 ///
214 /// ```rust
215 /// use adk_graph::deferred::FanInTracker;
216 ///
217 /// let tracker = FanInTracker::new(vec!["branch_1", "branch_2", "branch_3"]);
218 /// assert_eq!(tracker.expected_count(), 3);
219 /// assert!(!tracker.is_ready());
220 /// ```
221 pub fn new(expected_sources: Vec<&str>) -> Self {
222 Self {
223 expected: expected_sources.iter().map(|s| (*s).to_string()).collect(),
224 received: HashMap::new(),
225 insertion_order: Vec::new(),
226 }
227 }
228
229 /// Returns `true` when all expected sources have reported their output.
230 ///
231 /// # Example
232 ///
233 /// ```rust
234 /// use adk_graph::deferred::FanInTracker;
235 /// use serde_json::json;
236 ///
237 /// let mut tracker = FanInTracker::new(vec!["a"]);
238 /// assert!(!tracker.is_ready());
239 ///
240 /// tracker.record("a", json!(42));
241 /// assert!(tracker.is_ready());
242 /// ```
243 pub fn is_ready(&self) -> bool {
244 self.expected.iter().all(|s| self.received.contains_key(s))
245 }
246
247 /// Record the output from a source node.
248 ///
249 /// If the source has already been recorded, the previous value is
250 /// overwritten (last-write-wins). Recording a source that is not in
251 /// the expected set is a no-op for readiness but the value is still stored.
252 ///
253 /// # Arguments
254 ///
255 /// * `source_node` - The name of the upstream node that produced the output.
256 /// * `output` - The output value from the source node.
257 ///
258 /// # Example
259 ///
260 /// ```rust
261 /// use adk_graph::deferred::FanInTracker;
262 /// use serde_json::json;
263 ///
264 /// let mut tracker = FanInTracker::new(vec!["worker_1", "worker_2"]);
265 /// tracker.record("worker_1", json!({"status": "done"}));
266 /// assert_eq!(tracker.received_count(), 1);
267 /// ```
268 pub fn record(&mut self, source_node: &str, output: Value) {
269 let key = source_node.to_string();
270 if !self.received.contains_key(&key) {
271 self.insertion_order.push(key.clone());
272 }
273 self.received.insert(key, output);
274 }
275
276 /// Merge all received outputs according to the given strategy.
277 ///
278 /// The merge operation combines all recorded outputs into a single
279 /// [`Value`] based on the [`MergeStrategy`]:
280 ///
281 /// - [`MergeStrategy::Collect`]: Returns a JSON array of all outputs in
282 /// insertion order.
283 /// - [`MergeStrategy::MergeMap`]: Merges all JSON object outputs into a
284 /// single object (last-write-wins). Non-object outputs are skipped.
285 /// - [`MergeStrategy::First`]: Returns the first recorded output.
286 /// - [`MergeStrategy::Custom`]: Invokes the custom function with all outputs.
287 ///
288 /// # Arguments
289 ///
290 /// * `strategy` - The merge strategy to apply.
291 ///
292 /// # Example
293 ///
294 /// ```rust
295 /// use adk_graph::deferred::{FanInTracker, MergeStrategy};
296 /// use serde_json::json;
297 ///
298 /// let mut tracker = FanInTracker::new(vec!["a", "b"]);
299 /// tracker.record("a", json!({"x": 1}));
300 /// tracker.record("b", json!({"y": 2}));
301 ///
302 /// // Collect strategy
303 /// let result = tracker.merge(&MergeStrategy::Collect);
304 /// assert_eq!(result, json!([{"x": 1}, {"y": 2}]));
305 ///
306 /// // MergeMap strategy
307 /// let result = tracker.merge(&MergeStrategy::MergeMap);
308 /// assert_eq!(result, json!({"x": 1, "y": 2}));
309 /// ```
310 pub fn merge(&self, strategy: &MergeStrategy) -> Value {
311 match strategy {
312 MergeStrategy::Collect => {
313 let outputs: Vec<Value> = self
314 .insertion_order
315 .iter()
316 .filter_map(|key| self.received.get(key).cloned())
317 .collect();
318 Value::Array(outputs)
319 }
320 MergeStrategy::MergeMap => {
321 let mut merged = serde_json::Map::new();
322 for key in &self.insertion_order {
323 if let Some(Value::Object(map)) = self.received.get(key) {
324 for (k, v) in map {
325 merged.insert(k.clone(), v.clone());
326 }
327 }
328 }
329 Value::Object(merged)
330 }
331 MergeStrategy::First => self
332 .insertion_order
333 .first()
334 .and_then(|key| self.received.get(key).cloned())
335 .unwrap_or(Value::Null),
336 MergeStrategy::Custom(f) => {
337 let outputs: Vec<Value> = self
338 .insertion_order
339 .iter()
340 .filter_map(|key| self.received.get(key).cloned())
341 .collect();
342 f(outputs)
343 }
344 }
345 }
346
347 /// Returns the number of outputs received so far.
348 pub fn received_count(&self) -> usize {
349 self.received.len()
350 }
351
352 /// Returns the number of expected source nodes.
353 pub fn expected_count(&self) -> usize {
354 self.expected.len()
355 }
356
357 /// Returns the names of sources that have not yet reported.
358 pub fn pending_sources(&self) -> Vec<&str> {
359 self.expected
360 .iter()
361 .filter(|s| !self.received.contains_key(*s))
362 .map(|s| s.as_str())
363 .collect()
364 }
365
366 /// Returns the names of sources that have reported.
367 pub fn completed_sources(&self) -> Vec<&str> {
368 self.insertion_order.iter().map(|s| s.as_str()).collect()
369 }
370}
371
372/// Checkpoint metadata key holding the arrivals of fan-in nodes still waiting.
373pub(crate) const FAN_IN_METADATA_KEY: &str = "adk.graph.fanIn";
374
375/// Layout version of [`FAN_IN_METADATA_KEY`].
376///
377/// A checkpoint without the key predates it and restores with no arrivals.
378const FAN_IN_SNAPSHOT_VERSION: u32 = 1;
379
380/// The fan-in arrivals a checkpoint carries, so a resumed run still releases a
381/// join whose earlier predecessors finished before the pause or crash.
382#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
383#[serde(rename_all = "camelCase")]
384pub(crate) struct FanInSnapshot {
385 version: u32,
386 nodes: BTreeMap<String, PendingFanIn>,
387 /// Predecessors whose next arrival a node ignores, because a `fan_in_timeout`
388 /// released it without them. Absent from checkpoints that predate it.
389 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
390 abandoned: BTreeMap<String, Vec<String>>,
391}
392
393/// What a checkpoint restores of the fan-in nodes still waiting.
394pub(crate) struct RestoredFanIn {
395 /// The waiting nodes' trackers.
396 pub(crate) trackers: HashMap<String, FanInTracker>,
397 /// When each waiting node started waiting.
398 pub(crate) started: HashMap<String, Instant>,
399 /// The predecessors each node ignores the next arrival of.
400 pub(crate) abandoned: HashMap<String, HashSet<String>>,
401}
402
403/// One deferred node's recorded arrivals.
404#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
405#[serde(rename_all = "camelCase")]
406struct PendingFanIn {
407 /// Arrivals in recording order, which is the merge order.
408 arrivals: Vec<FanInArrival>,
409 /// When the node started waiting, so `fan_in_timeout` spans the pause.
410 waiting_since: chrono::DateTime<chrono::Utc>,
411}
412
413#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
414#[serde(rename_all = "camelCase")]
415struct FanInArrival {
416 source: String,
417 output: Value,
418}
419
420impl FanInSnapshot {
421 /// Captures every waiting tracker and abandoned predecessor, or `None` when
422 /// there is neither.
423 pub(crate) fn capture(
424 trackers: &HashMap<String, FanInTracker>,
425 started: &HashMap<String, Instant>,
426 abandoned: &HashMap<String, HashSet<String>>,
427 ) -> Option<Self> {
428 if trackers.is_empty() && abandoned.values().all(HashSet::is_empty) {
429 return None;
430 }
431 let now = chrono::Utc::now();
432 let nodes = trackers
433 .iter()
434 .map(|(node, tracker)| {
435 let waited = started
436 .get(node)
437 .and_then(|start| chrono::Duration::from_std(start.elapsed()).ok())
438 .unwrap_or_default();
439 let arrivals = tracker
440 .insertion_order
441 .iter()
442 .filter_map(|source| {
443 tracker.received.get(source).map(|output| FanInArrival {
444 source: source.clone(),
445 output: output.clone(),
446 })
447 })
448 .collect();
449 (node.clone(), PendingFanIn { arrivals, waiting_since: now - waited })
450 })
451 .collect();
452 let abandoned = abandoned
453 .iter()
454 .filter(|(_, sources)| !sources.is_empty())
455 .map(|(node, sources)| {
456 let mut sources: Vec<String> = sources.iter().cloned().collect();
457 sources.sort();
458 (node.clone(), sources)
459 })
460 .collect();
461 Some(Self { version: FAN_IN_SNAPSHOT_VERSION, nodes, abandoned })
462 }
463
464 /// Reads the snapshot from checkpoint metadata; `None` when the key is absent.
465 ///
466 /// # Errors
467 ///
468 /// Returns [`GraphError::CheckpointError`] when the value is malformed or was
469 /// written in a newer layout than this release reads.
470 pub(crate) fn from_metadata(metadata: &HashMap<String, Value>) -> Result<Option<Self>> {
471 let Some(value) = metadata.get(FAN_IN_METADATA_KEY) else { return Ok(None) };
472 let snapshot: Self = serde_json::from_value(value.clone()).map_err(|e| {
473 GraphError::CheckpointError(format!(
474 "checkpoint metadata '{FAN_IN_METADATA_KEY}' is malformed: {e}"
475 ))
476 })?;
477 if snapshot.version != FAN_IN_SNAPSHOT_VERSION {
478 return Err(GraphError::CheckpointError(format!(
479 "checkpoint metadata '{FAN_IN_METADATA_KEY}' has layout version {}, but this \
480 adk-graph release reads version {FAN_IN_SNAPSHOT_VERSION}; resume the thread \
481 with the release that wrote it",
482 snapshot.version
483 )));
484 }
485 Ok(Some(snapshot))
486 }
487
488 /// Rebuilds the trackers, their wait start times, and the abandoned predecessors.
489 ///
490 /// `upstream` names each node's predecessors from the graph being resumed, so
491 /// the expected set is never read from the checkpoint.
492 pub(crate) fn restore(self, upstream: impl Fn(&str) -> Vec<String>) -> RestoredFanIn {
493 let now = chrono::Utc::now();
494 let mut trackers = HashMap::new();
495 let mut started = HashMap::new();
496 for (node, pending) in self.nodes {
497 let sources = upstream(&node);
498 let mut tracker = FanInTracker::new(sources.iter().map(String::as_str).collect());
499 for arrival in pending.arrivals {
500 tracker.record(&arrival.source, arrival.output);
501 }
502 let waited = (now - pending.waiting_since).to_std().unwrap_or_default();
503 started.insert(
504 node.clone(),
505 Instant::now().checked_sub(waited).unwrap_or_else(Instant::now),
506 );
507 trackers.insert(node, tracker);
508 }
509 let abandoned = self
510 .abandoned
511 .into_iter()
512 .map(|(node, sources)| (node, sources.into_iter().collect()))
513 .collect();
514 RestoredFanIn { trackers, started, abandoned }
515 }
516
517 /// Serializes the snapshot for checkpoint metadata.
518 pub(crate) fn to_value(&self) -> Value {
519 serde_json::to_value(self).unwrap_or(Value::Null)
520 }
521}
522
523impl fmt::Debug for FanInTracker {
524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525 f.debug_struct("FanInTracker")
526 .field("expected", &self.expected)
527 .field("received_keys", &self.insertion_order)
528 .field("is_ready", &self.is_ready())
529 .finish()
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536 use serde_json::json;
537
538 #[test]
539 fn test_tracker_new_empty_not_ready() {
540 let tracker = FanInTracker::new(vec!["a", "b", "c"]);
541 assert!(!tracker.is_ready());
542 assert_eq!(tracker.expected_count(), 3);
543 assert_eq!(tracker.received_count(), 0);
544 }
545
546 #[test]
547 fn test_tracker_ready_when_all_received() {
548 let mut tracker = FanInTracker::new(vec!["a", "b"]);
549 tracker.record("a", json!(1));
550 assert!(!tracker.is_ready());
551 tracker.record("b", json!(2));
552 assert!(tracker.is_ready());
553 }
554
555 #[test]
556 fn test_merge_collect() {
557 let mut tracker = FanInTracker::new(vec!["x", "y", "z"]);
558 tracker.record("x", json!("first"));
559 tracker.record("y", json!("second"));
560 tracker.record("z", json!("third"));
561
562 let result = tracker.merge(&MergeStrategy::Collect);
563 assert_eq!(result, json!(["first", "second", "third"]));
564 }
565
566 #[test]
567 fn test_merge_map_combines_objects() {
568 let mut tracker = FanInTracker::new(vec!["a", "b"]);
569 tracker.record("a", json!({"key1": "val1", "shared": "from_a"}));
570 tracker.record("b", json!({"key2": "val2", "shared": "from_b"}));
571
572 let result = tracker.merge(&MergeStrategy::MergeMap);
573 assert_eq!(result, json!({"key1": "val1", "key2": "val2", "shared": "from_b"}));
574 }
575
576 #[test]
577 fn test_merge_map_skips_non_objects() {
578 let mut tracker = FanInTracker::new(vec!["a", "b"]);
579 tracker.record("a", json!(42)); // Not an object, skipped
580 tracker.record("b", json!({"key": "value"}));
581
582 let result = tracker.merge(&MergeStrategy::MergeMap);
583 assert_eq!(result, json!({"key": "value"}));
584 }
585
586 #[test]
587 fn test_merge_first() {
588 let mut tracker = FanInTracker::new(vec!["a", "b", "c"]);
589 tracker.record("b", json!("first_to_arrive"));
590 tracker.record("a", json!("second_to_arrive"));
591 tracker.record("c", json!("third_to_arrive"));
592
593 let result = tracker.merge(&MergeStrategy::First);
594 assert_eq!(result, json!("first_to_arrive"));
595 }
596
597 #[test]
598 fn test_merge_first_empty() {
599 let tracker = FanInTracker::new(vec!["a"]);
600 let result = tracker.merge(&MergeStrategy::First);
601 assert_eq!(result, Value::Null);
602 }
603
604 #[test]
605 fn test_merge_custom() {
606 let mut tracker = FanInTracker::new(vec!["a", "b"]);
607 tracker.record("a", json!(10));
608 tracker.record("b", json!(20));
609
610 let strategy = MergeStrategy::Custom(Arc::new(|outputs| {
611 let sum: i64 = outputs.iter().filter_map(|v| v.as_i64()).sum();
612 json!(sum)
613 }));
614
615 let result = tracker.merge(&strategy);
616 assert_eq!(result, json!(30));
617 }
618
619 #[test]
620 fn test_record_overwrites_previous() {
621 let mut tracker = FanInTracker::new(vec!["a"]);
622 tracker.record("a", json!("first"));
623 tracker.record("a", json!("second"));
624
625 assert!(tracker.is_ready());
626 assert_eq!(tracker.received_count(), 1);
627
628 let result = tracker.merge(&MergeStrategy::First);
629 assert_eq!(result, json!("second"));
630 }
631
632 #[test]
633 fn test_pending_and_completed_sources() {
634 let mut tracker = FanInTracker::new(vec!["a", "b", "c"]);
635 tracker.record("b", json!(1));
636
637 let mut pending = tracker.pending_sources();
638 pending.sort();
639 assert_eq!(pending, vec!["a", "c"]);
640 assert_eq!(tracker.completed_sources(), vec!["b"]);
641 }
642
643 #[test]
644 fn test_default_config() {
645 let config = DeferredNodeConfig::default();
646 assert!(matches!(config.merge_strategy, MergeStrategy::Collect));
647 assert!(config.fan_in_timeout.is_none());
648 }
649
650 #[test]
651 fn fan_in_snapshot_round_trips_arrivals_in_order() {
652 let mut tracker = FanInTracker::new(vec!["a", "b", "c"]);
653 tracker.record("b", json!("from b"));
654 tracker.record("a", json!({"x": 1}));
655 let trackers = HashMap::from([("join".to_string(), tracker)]);
656 let started = HashMap::from([("join".to_string(), Instant::now())]);
657
658 let abandoned =
659 HashMap::from([("quorum".to_string(), HashSet::from(["slow".to_string()]))]);
660
661 let snapshot =
662 FanInSnapshot::capture(&trackers, &started, &abandoned).expect("a join is waiting");
663 let metadata = HashMap::from([(FAN_IN_METADATA_KEY.to_string(), snapshot.to_value())]);
664 let restored = FanInSnapshot::from_metadata(&metadata).unwrap().expect("key present");
665 let restored =
666 restored.restore(|_| vec!["a".to_string(), "b".to_string(), "c".to_string()]);
667
668 let tracker = &restored.trackers["join"];
669 assert_eq!(tracker.completed_sources(), vec!["b", "a"]);
670 assert_eq!(tracker.merge(&MergeStrategy::Collect), json!(["from b", {"x": 1}]));
671 assert!(!tracker.is_ready());
672 assert!(restored.started.contains_key("join"));
673 assert_eq!(restored.abandoned, abandoned);
674 }
675
676 #[test]
677 fn a_snapshot_without_abandoned_predecessors_reads_as_before() {
678 let metadata =
679 HashMap::from([(FAN_IN_METADATA_KEY.to_string(), json!({"version": 1, "nodes": {}}))]);
680 let restored = FanInSnapshot::from_metadata(&metadata).unwrap().expect("key present");
681 assert!(restored.restore(|_| Vec::new()).abandoned.is_empty());
682 }
683
684 #[test]
685 fn a_checkpoint_without_fan_in_metadata_restores_nothing() {
686 assert_eq!(FanInSnapshot::from_metadata(&HashMap::new()).unwrap(), None);
687 assert_eq!(FanInSnapshot::capture(&HashMap::new(), &HashMap::new(), &HashMap::new()), None);
688 }
689
690 #[test]
691 fn a_newer_fan_in_layout_is_rejected() {
692 let metadata =
693 HashMap::from([(FAN_IN_METADATA_KEY.to_string(), json!({"version": 99, "nodes": {}}))]);
694 assert!(matches!(
695 FanInSnapshot::from_metadata(&metadata),
696 Err(GraphError::CheckpointError(_))
697 ));
698 }
699
700 #[test]
701 fn test_merge_strategy_debug() {
702 assert_eq!(format!("{:?}", MergeStrategy::Collect), "Collect");
703 assert_eq!(format!("{:?}", MergeStrategy::MergeMap), "MergeMap");
704 assert_eq!(format!("{:?}", MergeStrategy::First), "First");
705 let custom = MergeStrategy::Custom(Arc::new(Value::Array));
706 assert_eq!(format!("{:?}", custom), "Custom(<fn>)");
707 }
708}