streamweave 0.10.1

Composable, async, stream-first computation in pure Rust
Documentation
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! # Graph Test Suite - Stream-Based
//!
//! Comprehensive test suite for the [`Graph`] struct with stream-based architecture,
//! including node management, edge management, and stream-based execution.
//!
//! ## Test Coverage
//!
//! This test suite covers:
//!
//! - **Name Management**: Getting and setting graph names
//! - **Node Management**: Adding, removing, and querying nodes
//! - **Edge Management**: Adding, removing, and querying edges
//! - **Stream Execution**: Executing graphs with stream-based node connections

use crate::edge::Edge;
use crate::graph::{Graph, topological_sort};
use crate::node::{InputStreams, Node, NodeExecutionError, OutputStreams};
use async_trait::async_trait;
use std::any::Any;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use tokio_stream::{Stream, StreamExt};

// ============================================================================
// Mock Node Implementations for Testing
// ============================================================================

/// Mock producer node (0 inputs, 1 output)
struct MockProducerNode {
  name: String,
  output_port_names: Vec<String>,
  data: Vec<i32>,
}

impl MockProducerNode {
  fn new(name: String, data: Vec<i32>) -> Self {
    Self {
      name,
      output_port_names: vec!["out".to_string()],
      data,
    }
  }
}

#[async_trait]
impl Node for MockProducerNode {
  fn name(&self) -> &str {
    &self.name
  }

  fn set_name(&mut self, name: &str) {
    self.name = name.to_string();
  }

  fn input_port_names(&self) -> &[String] {
    &[]
  }

  fn output_port_names(&self) -> &[String] {
    &self.output_port_names
  }

  fn has_input_port(&self, _name: &str) -> bool {
    false
  }

  fn has_output_port(&self, name: &str) -> bool {
    self.output_port_names.contains(&name.to_string())
  }

  fn execute(
    &self,
    _inputs: InputStreams,
  ) -> Pin<
    Box<dyn std::future::Future<Output = Result<OutputStreams, NodeExecutionError>> + Send + '_>,
  > {
    let data = self.data.clone();
    Box::pin(async move {
      let (tx, rx) = mpsc::channel(10);

      tokio::spawn(async move {
        for item in data {
          let _ = tx.send(Arc::new(item) as Arc<dyn Any + Send + Sync>).await;
        }
      });

      let mut outputs = HashMap::new();
      outputs.insert(
        "out".to_string(),
        Box::pin(ReceiverStream::new(rx))
          as Pin<Box<dyn Stream<Item = Arc<dyn Any + Send + Sync>> + Send>>,
      );
      Ok(outputs)
    })
  }
}

/// Mock transform node (1 input, 1 output)
struct MockTransformNode {
  name: String,
  input_port_names: Vec<String>,
  output_port_names: Vec<String>,
}

impl MockTransformNode {
  fn new(name: String) -> Self {
    Self {
      name,
      input_port_names: vec!["in".to_string()],
      output_port_names: vec!["out".to_string()],
    }
  }
}

#[async_trait]
impl Node for MockTransformNode {
  fn name(&self) -> &str {
    &self.name
  }

  fn set_name(&mut self, name: &str) {
    self.name = name.to_string();
  }

  fn input_port_names(&self) -> &[String] {
    &self.input_port_names
  }

  fn output_port_names(&self) -> &[String] {
    &self.output_port_names
  }

  fn has_input_port(&self, name: &str) -> bool {
    self.input_port_names.contains(&name.to_string())
  }

  fn has_output_port(&self, name: &str) -> bool {
    self.output_port_names.contains(&name.to_string())
  }

  fn execute(
    &self,
    mut inputs: InputStreams,
  ) -> Pin<
    Box<dyn std::future::Future<Output = Result<OutputStreams, NodeExecutionError>> + Send + '_>,
  > {
    Box::pin(async move {
      let input_stream = inputs.remove("in").ok_or("Missing 'in' input")?;

      let output_stream: OutputStreams = {
        let mut map = HashMap::new();
        map.insert(
          "out".to_string(),
          Box::pin(async_stream::stream! {
            let mut input = input_stream;
            while let Some(item) = input.next().await {
              if let Ok(arc_i32) = item.clone().downcast::<i32>() {
                yield Arc::new(*arc_i32 * 2) as Arc<dyn Any + Send + Sync>;
              } else {
                yield item;
              }
            }
          }) as Pin<Box<dyn Stream<Item = Arc<dyn Any + Send + Sync>> + Send>>,
        );
        map
      };

      Ok(output_stream)
    })
  }
}

/// Mock sink node (1 input, 0 outputs)
struct MockSinkNode {
  name: String,
  input_port_names: Vec<String>,
  received: Arc<tokio::sync::Mutex<Vec<i32>>>,
}

impl MockSinkNode {
  fn new(name: String) -> Self {
    Self {
      name,
      input_port_names: vec!["in".to_string()],
      received: Arc::new(tokio::sync::Mutex::new(Vec::new())),
    }
  }

  #[allow(dead_code)]
  async fn get_received(&self) -> Vec<i32> {
    self.received.lock().await.clone()
  }
}

#[async_trait]
impl Node for MockSinkNode {
  fn name(&self) -> &str {
    &self.name
  }

  fn set_name(&mut self, name: &str) {
    self.name = name.to_string();
  }

  fn input_port_names(&self) -> &[String] {
    &self.input_port_names
  }

  fn output_port_names(&self) -> &[String] {
    &[]
  }

  fn has_input_port(&self, name: &str) -> bool {
    self.input_port_names.contains(&name.to_string())
  }

  fn has_output_port(&self, _name: &str) -> bool {
    false
  }

  fn execute(
    &self,
    mut inputs: InputStreams,
  ) -> Pin<
    Box<dyn std::future::Future<Output = Result<OutputStreams, NodeExecutionError>> + Send + '_>,
  > {
    let received = Arc::clone(&self.received);
    Box::pin(async move {
      let input_stream = inputs.remove("in").ok_or("Missing 'in' input")?;

      tokio::spawn(async move {
        let mut input = input_stream;
        while let Some(item) = input.next().await {
          if let Ok(arc_i32) = item.downcast::<i32>() {
            received.lock().await.push(*arc_i32);
          }
        }
      });

      Ok(HashMap::new())
    })
  }
}

// ============================================================================
// Name Management Tests
// ============================================================================

#[test]
fn test_graph_name_get() {
  let graph = Graph::new("test_graph".to_string());
  assert_eq!(graph.name(), "test_graph");
}

#[test]
fn test_graph_name_set() {
  let mut graph = Graph::new("old_name".to_string());
  graph.set_name("new_name");
  assert_eq!(graph.name(), "new_name");
}

// ============================================================================
// Node Management Tests
// ============================================================================

#[test]
fn test_add_node() {
  let mut graph = Graph::new("test".to_string());
  let node = Box::new(MockProducerNode::new("producer".to_string(), vec![1, 2, 3]));
  assert!(graph.add_node("producer".to_string(), node).is_ok());
  assert!(graph.find_node_by_name("producer").is_some());
}

#[test]
fn test_add_duplicate_node() {
  let mut graph = Graph::new("test".to_string());
  let node1 = Box::new(MockProducerNode::new("producer".to_string(), vec![1]));
  let node2 = Box::new(MockProducerNode::new("producer".to_string(), vec![2]));

  assert!(graph.add_node("producer".to_string(), node1).is_ok());
  assert!(graph.add_node("producer".to_string(), node2).is_err());
}

#[test]
fn test_remove_node() {
  let mut graph = Graph::new("test".to_string());
  let node = Box::new(MockProducerNode::new("producer".to_string(), vec![1]));
  graph.add_node("producer".to_string(), node).unwrap();
  assert!(graph.remove_node("producer").is_ok());
  assert!(graph.find_node_by_name("producer").is_none());
}

#[test]
fn test_remove_nonexistent_node() {
  let mut graph = Graph::new("test".to_string());
  assert!(graph.remove_node("nonexistent").is_err());
}

// ============================================================================
// Edge Management Tests
// ============================================================================

#[test]
fn test_add_edge() {
  let mut graph = Graph::new("test".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1]));
  let sink = Box::new(MockSinkNode::new("sink".to_string()));

  graph.add_node("producer".to_string(), producer).unwrap();
  graph.add_node("sink".to_string(), sink).unwrap();

  let edge = Edge {
    source_node: "producer".to_string(),
    source_port: "out".to_string(),
    target_node: "sink".to_string(),
    target_port: "in".to_string(),
  };

  assert!(graph.add_edge(edge).is_ok());
  assert_eq!(graph.get_edges().len(), 1);
}

#[test]
fn test_add_edge_invalid_source() {
  let mut graph = Graph::new("test".to_string());
  let edge = Edge {
    source_node: "nonexistent".to_string(),
    source_port: "out".to_string(),
    target_node: "sink".to_string(),
    target_port: "in".to_string(),
  };

  assert!(graph.add_edge(edge).is_err());
}

#[test]
fn test_remove_edge() {
  let mut graph = Graph::new("test".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1]));
  let sink = Box::new(MockSinkNode::new("sink".to_string()));

  graph.add_node("producer".to_string(), producer).unwrap();
  graph.add_node("sink".to_string(), sink).unwrap();

  let edge = Edge {
    source_node: "producer".to_string(),
    source_port: "out".to_string(),
    target_node: "sink".to_string(),
    target_port: "in".to_string(),
  };

  graph.add_edge(edge).unwrap();
  assert!(graph.remove_edge("producer", "out", "sink", "in").is_ok());
  assert_eq!(graph.get_edges().len(), 0);
}

// ============================================================================
// Topological Sort Tests
// ============================================================================

#[test]
fn test_topological_sort_linear() {
  let node_a: Box<dyn Node> = Box::new(MockProducerNode::new("a".to_string(), vec![1]));
  let node_b: Box<dyn Node> = Box::new(MockTransformNode::new("b".to_string()));
  let node_c: Box<dyn Node> = Box::new(MockSinkNode::new("c".to_string()));
  let nodes: Vec<&dyn Node> = vec![node_a.as_ref(), node_b.as_ref(), node_c.as_ref()];

  let edge1 = Edge {
    source_node: "a".to_string(),
    source_port: "out".to_string(),
    target_node: "b".to_string(),
    target_port: "in".to_string(),
  };
  let edge2 = Edge {
    source_node: "b".to_string(),
    source_port: "out".to_string(),
    target_node: "c".to_string(),
    target_port: "in".to_string(),
  };
  let edges = vec![&edge1, &edge2];

  let result = topological_sort(&nodes, &edges).unwrap();
  assert_eq!(result, vec!["a", "b", "c"]);
}

#[test]
fn test_topological_sort_diamond() {
  let node_a: Box<dyn Node> = Box::new(MockProducerNode::new("a".to_string(), vec![1]));
  let node_b: Box<dyn Node> = Box::new(MockTransformNode::new("b".to_string()));
  let node_c: Box<dyn Node> = Box::new(MockTransformNode::new("c".to_string()));
  let node_d: Box<dyn Node> = Box::new(MockSinkNode::new("d".to_string()));
  let nodes: Vec<&dyn Node> = vec![
    node_a.as_ref(),
    node_b.as_ref(),
    node_c.as_ref(),
    node_d.as_ref(),
  ];

  let edge1 = Edge {
    source_node: "a".to_string(),
    source_port: "out".to_string(),
    target_node: "b".to_string(),
    target_port: "in".to_string(),
  };
  let edge2 = Edge {
    source_node: "a".to_string(),
    source_port: "out".to_string(),
    target_node: "c".to_string(),
    target_port: "in".to_string(),
  };
  let edge3 = Edge {
    source_node: "b".to_string(),
    source_port: "out".to_string(),
    target_node: "d".to_string(),
    target_port: "in".to_string(),
  };
  let edge4 = Edge {
    source_node: "c".to_string(),
    source_port: "out".to_string(),
    target_node: "d".to_string(),
    target_port: "in".to_string(),
  };
  let edges = vec![&edge1, &edge2, &edge3, &edge4];

  let result = topological_sort(&nodes, &edges).unwrap();
  assert_eq!(result[0], "a");
  assert!(result.contains(&"b".to_string()));
  assert!(result.contains(&"c".to_string()));
  assert_eq!(result[result.len() - 1], "d");
}

// ============================================================================
// Execution Tests
// ============================================================================

#[tokio::test]
async fn test_execute_simple_graph() {
  let mut graph = Graph::new("test".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1, 2, 3]));
  let sink = Box::new(MockSinkNode::new("sink".to_string()));

  graph.add_node("producer".to_string(), producer).unwrap();
  graph.add_node("sink".to_string(), sink).unwrap();

  let edge = Edge {
    source_node: "producer".to_string(),
    source_port: "out".to_string(),
    target_node: "sink".to_string(),
    target_port: "in".to_string(),
  };

  graph.add_edge(edge).unwrap();

  // Execute the graph (use Graph::execute to disambiguate from Node::execute)
  assert!(Graph::execute(&mut graph).await.is_ok());

  // Wait for completion
  assert!(graph.wait_for_completion().await.is_ok());
}

#[tokio::test]
async fn test_execute_transform_graph() {
  let mut graph = Graph::new("test".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1, 2, 3]));
  let transform = Box::new(MockTransformNode::new("transform".to_string()));
  let sink = Box::new(MockSinkNode::new("sink".to_string()));

  graph.add_node("producer".to_string(), producer).unwrap();
  graph.add_node("transform".to_string(), transform).unwrap();
  graph.add_node("sink".to_string(), sink).unwrap();

  graph
    .add_edge(Edge {
      source_node: "producer".to_string(),
      source_port: "out".to_string(),
      target_node: "transform".to_string(),
      target_port: "in".to_string(),
    })
    .unwrap();

  graph
    .add_edge(Edge {
      source_node: "transform".to_string(),
      source_port: "out".to_string(),
      target_node: "sink".to_string(),
      target_port: "in".to_string(),
    })
    .unwrap();

  // Execute the graph (use Graph::execute to disambiguate from Node::execute)
  assert!(Graph::execute(&mut graph).await.is_ok());

  // Wait for completion
  assert!(graph.wait_for_completion().await.is_ok());
}

#[tokio::test]
async fn test_stop_execution() {
  let mut graph = Graph::new("test".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1, 2, 3]));
  let sink = Box::new(MockSinkNode::new("sink".to_string()));

  graph.add_node("producer".to_string(), producer).unwrap();
  graph.add_node("sink".to_string(), sink).unwrap();

  graph
    .add_edge(Edge {
      source_node: "producer".to_string(),
      source_port: "out".to_string(),
      target_node: "sink".to_string(),
      target_port: "in".to_string(),
    })
    .unwrap();

  Graph::execute(&mut graph).await.unwrap();

  // Stop execution
  assert!(graph.stop().await.is_ok());

  // Wait for completion (should complete quickly after stop)
  assert!(graph.wait_for_completion().await.is_ok());
}

// ============================================================================
// Graph as Node Tests
// ============================================================================

#[test]
fn test_graph_has_input_ports() {
  let mut graph = Graph::new("test".to_string());
  // New graphs have no ports by default
  assert!(!graph.has_input_port("configuration"));
  assert!(!graph.has_input_port("input"));
  assert!(!graph.has_input_port("nonexistent"));

  // Add a node and expose a port
  let transform = Box::new(MockTransformNode::new("transform".to_string()));
  graph.add_node("transform".to_string(), transform).unwrap();
  graph.expose_input_port("transform", "in", "input").unwrap();
  assert!(graph.has_input_port("input"));
  assert!(!graph.has_input_port("configuration"));
}

#[test]
fn test_graph_has_output_ports() {
  let mut graph = Graph::new("test".to_string());
  // New graphs have no ports by default
  assert!(!graph.has_output_port("output"));
  assert!(!graph.has_output_port("error"));
  assert!(!graph.has_output_port("nonexistent"));

  // Add a node and expose a port
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1]));
  graph.add_node("producer".to_string(), producer).unwrap();
  graph
    .expose_output_port("producer", "out", "output")
    .unwrap();
  assert!(graph.has_output_port("output"));
  assert!(!graph.has_output_port("error"));
}

#[test]
fn test_graph_input_port_names() {
  let mut graph = Graph::new("test".to_string());
  // New graphs have no ports by default
  let ports = graph.input_port_names();
  assert_eq!(ports.len(), 0);

  // Add a node and expose a port
  let transform = Box::new(MockTransformNode::new("transform".to_string()));
  graph.add_node("transform".to_string(), transform).unwrap();
  graph.expose_input_port("transform", "in", "input").unwrap();
  let ports = graph.input_port_names();
  assert_eq!(ports.len(), 1);
  assert!(ports.contains(&"input".to_string()));

  // Expose another port with a different name
  let transform2 = Box::new(MockTransformNode::new("transform2".to_string()));
  graph
    .add_node("transform2".to_string(), transform2)
    .unwrap();
  graph
    .expose_input_port("transform2", "in", "configuration")
    .unwrap();
  let ports = graph.input_port_names();
  assert_eq!(ports.len(), 2);
  assert!(ports.contains(&"configuration".to_string()));
  assert!(ports.contains(&"input".to_string()));
}

#[test]
fn test_graph_output_port_names() {
  let mut graph = Graph::new("test".to_string());
  // New graphs have no ports by default
  let ports = graph.output_port_names();
  assert_eq!(ports.len(), 0);

  // Add a node and expose a port
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1]));
  graph.add_node("producer".to_string(), producer).unwrap();
  graph
    .expose_output_port("producer", "out", "output")
    .unwrap();
  let ports = graph.output_port_names();
  assert_eq!(ports.len(), 1);
  assert!(ports.contains(&"output".to_string()));

  // Expose another port with a different name (using same node's port twice)
  graph
    .expose_output_port("producer", "out", "error")
    .unwrap();
  let ports = graph.output_port_names();
  assert_eq!(ports.len(), 2);
  assert!(ports.contains(&"output".to_string()));
  assert!(ports.contains(&"error".to_string()));
}

#[test]
fn test_expose_input_port() {
  let mut graph = Graph::new("test".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1]));

  graph.add_node("producer".to_string(), producer).unwrap();

  // Expose producer's output as graph's input
  assert!(graph.expose_input_port("producer", "out", "input").is_err()); // producer has no input port

  // Create a node with input port
  let transform = Box::new(MockTransformNode::new("transform".to_string()));
  graph.add_node("transform".to_string(), transform).unwrap();

  // Expose transform's input as graph's input
  assert!(graph.expose_input_port("transform", "in", "input").is_ok());

  // Try non-existent internal node
  assert!(
    graph
      .expose_input_port("nonexistent", "in", "input")
      .is_err()
  );

  // Try non-existent internal port
  assert!(
    graph
      .expose_input_port("transform", "nonexistent", "input")
      .is_err()
  );
}

#[test]
fn test_expose_output_port() {
  let mut graph = Graph::new("test".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1]));

  graph.add_node("producer".to_string(), producer).unwrap();

  // Expose producer's output as graph's output
  assert!(
    graph
      .expose_output_port("producer", "out", "output")
      .is_ok()
  );

  // Try non-existent internal node
  assert!(
    graph
      .expose_output_port("nonexistent", "out", "output")
      .is_err()
  );

  // Try non-existent internal port
  assert!(
    graph
      .expose_output_port("producer", "nonexistent", "output")
      .is_err()
  );
}

#[tokio::test]
async fn test_graph_as_node_execute() {
  // Create a subgraph
  let mut subgraph = Graph::new("subgraph".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1, 2, 3]));
  let transform = Box::new(MockTransformNode::new("transform".to_string()));

  subgraph.add_node("producer".to_string(), producer).unwrap();
  subgraph
    .add_node("transform".to_string(), transform)
    .unwrap();

  subgraph
    .add_edge(Edge {
      source_node: "producer".to_string(),
      source_port: "out".to_string(),
      target_node: "transform".to_string(),
      target_port: "in".to_string(),
    })
    .unwrap();

  // Expose ports
  let _ = subgraph
    .expose_input_port("producer", "out", "input")
    .is_err(); // producer has no input
  // Instead, we'll expose transform's output as graph's output
  subgraph
    .expose_output_port("transform", "out", "output")
    .unwrap();

  // Create a parent graph with the subgraph as a node
  let mut parent_graph = Graph::new("parent".to_string());
  let subgraph_node: Box<dyn Node> = Box::new(subgraph);
  parent_graph
    .add_node("subgraph".to_string(), subgraph_node)
    .unwrap();

  // The subgraph needs input, but we can't easily test this without a proper source
  // For now, just verify the structure is correct
  assert!(parent_graph.find_node_by_name("subgraph").is_some());
}

// ============================================================================
// Lifecycle Control Tests
// ============================================================================

#[test]
fn test_start_pause_resume_stop() {
  let graph = Graph::new("test".to_string());

  // Initially stopped
  // (We can't easily check state without exposing it, but we can test the methods)

  // Start execution
  graph.start();

  // Pause execution
  graph.pause();

  // Resume execution
  graph.resume();

  // All methods should complete without error
  // (Actual state verification would require exposing execution_state or testing behavior)
}

#[tokio::test]
async fn test_stop_clears_state() {
  let mut graph = Graph::new("test".to_string());
  let producer = Box::new(MockProducerNode::new("producer".to_string(), vec![1, 2, 3]));
  let sink = Box::new(MockSinkNode::new("sink".to_string()));

  graph.add_node("producer".to_string(), producer).unwrap();
  graph.add_node("sink".to_string(), sink).unwrap();

  graph
    .add_edge(Edge {
      source_node: "producer".to_string(),
      source_port: "out".to_string(),
      target_node: "sink".to_string(),
      target_port: "in".to_string(),
    })
    .unwrap();

  // Start execution
  Graph::execute(&mut graph).await.unwrap();

  // Stop should clear state
  assert!(graph.stop().await.is_ok());

  // After stop, execution handles should be cleared
  // (We verify this by checking wait_for_completion completes quickly)
  assert!(graph.wait_for_completion().await.is_ok());
}