async-nodes 0.1.0

An asynchronous, type-safe node engine implementing the Bulk Synchronous Parallel (BSP) model: control-flow loops, recovery, suspension, and serializable graphs, with dataflow-once pipelines as a profile.
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
//! Core scheduler integration tests: chains, joins, step limits, bounded concurrency,
//! the event stream, and the sequential (!Clone) API.

use std::sync::{
    Arc, Mutex,
    atomic::{AtomicUsize, Ordering},
};

use async_nodes::{
    Activation, BspContext, BspEngine, BspError, BspGraph, BspInterceptor, BspNode, EngineResult,
    NodeOutcome, RunContext, async_trait::async_trait,
};
#[cfg(feature = "tokio")]
use async_nodes::{BspEvent, ChannelInterceptor};
use indexmap::IndexMap;

// =========================================================================
// TEST NODES
// =========================================================================

/// Adds a constant to a `u64` state whenever it fires.
struct AddNode {
    name: &'static str,
    amount: u64,
}

#[async_trait]
impl BspNode<u64> for AddNode {
    fn name(&self) -> &str {
        self.name
    }

    async fn execute(&self, run: &mut RunContext<'_, u64>) -> Result<NodeOutcome, BspError> {
        *run.state += self.amount;
        Ok(NodeOutcome::Success(IndexMap::new()))
    }
}

/// Does nothing; carries a configurable activation policy.
struct NoopNode {
    name: &'static str,
    activation: Activation,
}

#[async_trait]
impl<S: Send> BspNode<S> for NoopNode {
    fn name(&self) -> &str {
        self.name
    }

    fn activation(&self) -> Activation {
        self.activation
    }

    async fn execute(&self, _run: &mut RunContext<'_, S>) -> Result<NodeOutcome, BspError> {
        Ok(NodeOutcome::Success(IndexMap::new()))
    }
}

/// Records its `execution_no` into a Vec state each time it fires.
struct TraceNode {
    name: &'static str,
}

#[async_trait]
impl BspNode<Vec<u64>> for TraceNode {
    fn name(&self) -> &str {
        self.name
    }

    async fn execute(&self, run: &mut RunContext<'_, Vec<u64>>) -> Result<NodeOutcome, BspError> {
        run.state.push(run.execution_no);
        Ok(NodeOutcome::Success(IndexMap::new()))
    }
}

// =========================================================================
// LINEAR CHAINS & JOIN SEMANTICS
// =========================================================================

#[tokio::test]
async fn test_linear_chain_runs_in_declaration_order() {
    let mut graph = BspGraph::new();
    let a = graph.add_node(AddNode {
        name: "a",
        amount: 1,
    });
    let b = graph.add_node(AddNode {
        name: "b",
        amount: 10,
    });
    let c = graph.add_node(AddNode {
        name: "c",
        amount: 100,
    });
    graph.add_edge(a.id, b.id);
    graph.add_edge(b.id, c.id);

    let engine = BspEngine::new(graph);
    let outcome = engine.run(0_u64).await.unwrap();

    let EngineResult::Complete(state) = outcome else {
        panic!("expected completion, got {outcome:?}");
    };
    assert_eq!(state.user, 111);
    assert_eq!(state.step, 3);
    assert_eq!(state.execution_count(a.id), 1);
    assert_eq!(state.execution_count(b.id), 1);
    assert_eq!(state.execution_count(c.id), 1);
}

#[tokio::test]
async fn test_diamond_join_all_fires_once() {
    let mut graph = BspGraph::new();
    let src = graph.add_node(NoopNode {
        name: "src",
        activation: Activation::Any,
    });
    let a = graph.add_node(NoopNode {
        name: "a",
        activation: Activation::Any,
    });
    let b = graph.add_node(NoopNode {
        name: "b",
        activation: Activation::Any,
    });
    let join = graph.add_node(NoopNode {
        name: "join",
        activation: Activation::All,
    });
    graph.add_edge(src.id, a.id);
    graph.add_edge(src.id, b.id);
    graph.add_edge(a.id, join.id);
    graph.add_edge(b.id, join.id);

    let engine = BspEngine::new(graph);
    let EngineResult::Complete(state) = engine.run(()).await.unwrap() else {
        panic!("expected completion");
    };
    // The join waits for both branch tokens, then fires exactly once.
    assert_eq!(state.execution_count(join.id), 1);
    assert_eq!(state.execution_count(a.id), 1);
    assert_eq!(state.execution_count(b.id), 1);
}

#[tokio::test]
async fn test_diamond_join_any_fires_per_arriving_token() {
    let mut graph = BspGraph::new();
    let src = graph.add_node(NoopNode {
        name: "src",
        activation: Activation::Any,
    });
    let a = graph.add_node(NoopNode {
        name: "a",
        activation: Activation::Any,
    });
    let b = graph.add_node(NoopNode {
        name: "b",
        activation: Activation::Any,
    });
    let join = graph.add_node(NoopNode {
        name: "join",
        activation: Activation::Any,
    });
    graph.add_edge(src.id, a.id);
    graph.add_edge(src.id, b.id);
    graph.add_edge(a.id, join.id);
    graph.add_edge(b.id, join.id);

    let engine = BspEngine::new(graph);
    let EngineResult::Complete(state) = engine.run(()).await.unwrap() else {
        panic!("expected completion");
    };
    // `Any` fires once per pending token: both branch arrivals trigger it.
    assert_eq!(state.execution_count(join.id), 2);
}

// =========================================================================
// STEP LIMITS
// =========================================================================

#[tokio::test]
async fn test_step_limit_is_a_distinct_result() {
    // Unbounded self-loop: only the global budget can stop it.
    let mut graph = BspGraph::new();
    let looper = graph.add_node(NoopNode {
        name: "looper",
        activation: Activation::Any,
    });
    graph.add_edge(looper.id, looper.id);
    graph.add_entry(looper.id);

    let engine = BspEngine::new(graph).with_max_steps(7);
    let outcome = engine.run(()).await.unwrap();

    let EngineResult::StepLimitReached(state) = outcome else {
        panic!("expected StepLimitReached, got {outcome:?}");
    };
    assert_eq!(state.step, 7);
    assert_eq!(state.execution_count(looper.id), 7);

    // The unbounded cycle is a validation warning, not an error.
    let report = engine.validate_with_report();
    assert!(report.is_ok());
    assert!(
        report
            .warnings
            .iter()
            .any(|w| w.contains("no max_iterations budget"))
    );
}

// =========================================================================
// BOUNDED CONCURRENCY
// =========================================================================

async fn run_probe(max_concurrency: Option<usize>) -> usize {
    /// Shared in-flight instrumentation, injected through the DI context.
    struct Counters {
        in_flight: AtomicUsize,
        max_seen: AtomicUsize,
    }

    struct SharedCounters(Arc<Counters>);

    impl async_nodes::typemap_rev::TypeMapKey for SharedCounters {
        type Value = Self;
    }

    struct CounterProbeNode {
        name: &'static str,
    }

    #[async_trait]
    impl BspNode<()> for CounterProbeNode {
        fn name(&self) -> &str {
            self.name
        }

        async fn execute(&self, run: &mut RunContext<'_, ()>) -> Result<NodeOutcome, BspError> {
            let counters = run
                .ctx
                .get::<SharedCounters>()
                .expect("probe injected")
                .0
                .clone();
            let current = counters.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
            counters.max_seen.fetch_max(current, Ordering::SeqCst);
            // Two yield points so co-scheduled tasks overlap measurably.
            tokio::task::yield_now().await;
            tokio::task::yield_now().await;
            counters.in_flight.fetch_sub(1, Ordering::SeqCst);
            Ok(NodeOutcome::Success(IndexMap::new()))
        }
    }

    let probe = Arc::new(Counters {
        in_flight: AtomicUsize::new(0),
        max_seen: AtomicUsize::new(0),
    });
    let ctx = BspContext::new();
    ctx.insert::<SharedCounters>(SharedCounters(probe.clone()));

    let mut graph = BspGraph::new();
    for name in ["p1", "p2", "p3", "p4"] {
        graph.add_node(CounterProbeNode { name });
    }
    let mut engine = BspEngine::new(graph).with_context(ctx);
    if let Some(limit) = max_concurrency {
        engine = engine.with_max_concurrency(limit);
    }
    let EngineResult::Complete(_) = engine.run(()).await.unwrap() else {
        panic!("expected completion");
    };
    probe.max_seen.load(Ordering::SeqCst)
}

#[tokio::test]
async fn test_max_concurrency_bounds_in_flight_tasks() {
    assert_eq!(run_probe(Some(1)).await, 1);
    assert_eq!(run_probe(Some(2)).await, 2);
}

#[tokio::test]
async fn test_unbounded_frontier_runs_fully_concurrent() {
    assert_eq!(run_probe(None).await, 4);
}

// =========================================================================
// EVENT STREAM
// =========================================================================

struct RecordingInterceptor {
    events: Mutex<Vec<String>>,
}

impl RecordingInterceptor {
    fn record(&self, event: String) {
        self.events.lock().unwrap().push(event);
    }
}

impl BspInterceptor for RecordingInterceptor {
    fn on_superstep_start(&self, step: u64, frontier: &[async_nodes::NodeId]) {
        self.record(format!("superstep:{step}:{frontier:?}"));
    }

    fn on_node_start(&self, _node_id: async_nodes::NodeId, name: &str) {
        self.record(format!("start:{name}"));
    }

    fn on_node_complete(
        &self,
        _node_id: async_nodes::NodeId,
        name: &str,
        _duration: std::time::Duration,
    ) {
        self.record(format!("done:{name}"));
    }

    fn on_edge_taken(&self, source: async_nodes::NodeId, target: async_nodes::NodeId, label: &str) {
        self.record(format!("edge:{source}->{target}:{label}"));
    }

    fn on_complete(&self, steps: u64) {
        self.record(format!("complete:{steps}"));
    }
}

#[tokio::test]
async fn test_event_stream_sequence() {
    let mut graph = BspGraph::new();
    let a = graph.add_node(AddNode {
        name: "a",
        amount: 1,
    });
    let b = graph.add_node(AddNode {
        name: "b",
        amount: 2,
    });
    graph.add_edge(a.id, b.id);

    let interceptor = Arc::new(RecordingInterceptor {
        events: Mutex::new(Vec::new()),
    });
    let engine = BspEngine::new(graph).with_interceptor(interceptor.clone());
    let outcome = engine.run(0_u64).await.unwrap();
    assert!(matches!(outcome, EngineResult::Complete(_)));

    let events = interceptor.events.lock().unwrap().clone();
    assert_eq!(
        events,
        vec![
            format!("superstep:0:[{}]", a.id),
            "start:a".to_string(),
            "done:a".to_string(),
            format!("edge:{}->{}:always", a.id, b.id),
            format!("superstep:1:[{}]", b.id),
            "start:b".to_string(),
            "done:b".to_string(),
            "complete:2".to_string(),
        ]
    );
}

#[cfg(feature = "tokio")]
#[tokio::test]
async fn test_channel_interceptor_broadcasts_run_events() {
    let channel = ChannelInterceptor::new(64);
    let mut rx = channel.subscribe();

    let mut graph = BspGraph::new();
    let a = graph.add_node(AddNode {
        name: "a",
        amount: 1,
    });
    let b = graph.add_node(AddNode {
        name: "b",
        amount: 2,
    });
    graph.add_edge(a.id, b.id);

    let engine = BspEngine::new(graph).with_interceptor(Arc::new(channel));
    let outcome = engine.run(0_u64).await.unwrap();
    assert!(matches!(outcome, EngineResult::Complete(_)));

    let mut events = Vec::new();
    while let Ok(event) = rx.try_recv() {
        events.push(event);
    }
    assert!(
        events
            .iter()
            .any(|e| matches!(e, BspEvent::SuperstepStart { step: 0, .. }))
    );
    assert!(events.iter().any(|e| matches!(
        e,
        BspEvent::EdgeTaken { source, target, .. } if *source == a.id && *target == b.id
    )));
    assert!(
        events
            .iter()
            .any(|e| matches!(e, BspEvent::Complete { steps: 2 }))
    );
}

// =========================================================================
// EXECUTION COUNTERS & THE SEQUENTIAL API
// =========================================================================

#[tokio::test]
async fn test_execution_no_counts_loop_iterations() {
    let mut graph = BspGraph::new();
    let entry = graph.add_node(NoopNode {
        name: "entry",
        activation: Activation::Any,
    });
    let tracer = graph.add_node(TraceNode { name: "tracer" });
    graph.add_edge(entry.id, tracer.id);
    graph.register_condition("again", |seen: &Vec<u64>, _| seen.len() < 3);
    graph.add_edge_with(
        tracer.id,
        tracer.id,
        async_nodes::Condition::Named("again".into()),
    );

    let engine = BspEngine::new(graph);
    let EngineResult::Complete(state) = engine.run(Vec::new()).await.unwrap() else {
        panic!("expected completion");
    };
    // Fired exactly three times, seeing 0-based execution numbers.
    assert_eq!(state.user, vec![0, 1, 2]);
    assert_eq!(state.execution_count(tracer.id), 3);
}

#[tokio::test]
async fn test_sequential_api_matches_concurrent_for_linear_chains() {
    let build = || {
        let mut graph = BspGraph::new();
        let a = graph.add_node(AddNode {
            name: "a",
            amount: 5,
        });
        let b = graph.add_node(AddNode {
            name: "b",
            amount: 7,
        });
        graph.add_edge(a.id, b.id);
        graph
    };

    let concurrent = BspEngine::new(build()).run(1_u64).await.unwrap();
    let sequential = BspEngine::new(build()).run_sequential(1_u64).await.unwrap();

    let EngineResult::Complete(a) = concurrent else {
        panic!("expected completion")
    };
    let EngineResult::Complete(b) = sequential else {
        panic!("expected completion")
    };
    assert_eq!(a.user, 13);
    assert_eq!(b.user, 13);
}

/// A state type that is deliberately not `Clone` (and still `Send`).
struct NoClone {
    count: u64,
    _marker: Box<dyn Fn() + Send + Sync>,
}

struct CountNode {
    name: &'static str,
}

#[async_trait]
impl BspNode<NoClone> for CountNode {
    fn name(&self) -> &str {
        self.name
    }

    async fn execute(&self, run: &mut RunContext<'_, NoClone>) -> Result<NodeOutcome, BspError> {
        run.state.count += 1;
        Ok(NodeOutcome::Success(IndexMap::new()))
    }
}

#[tokio::test]
async fn test_sequential_api_supports_non_clone_states() {
    let mut graph = BspGraph::new();
    let a = graph.add_node(CountNode { name: "a" });
    let b = graph.add_node(CountNode { name: "b" });
    graph.add_edge(a.id, b.id);

    let engine = BspEngine::new(graph);
    let EngineResult::Complete(state) = engine
        .run_sequential(NoClone {
            count: 0,
            _marker: Box::new(|| {}),
        })
        .await
        .unwrap()
    else {
        panic!("expected completion");
    };
    assert_eq!(state.user.count, 2);
}

// =========================================================================
// FORCED ENTRIES
// =========================================================================

#[tokio::test]
async fn test_run_with_entries_starts_at_the_forced_node() {
    // a -> b -> c; forcing b as the entry must skip a entirely.
    let mut graph = BspGraph::new();
    let a = graph.add_node(AddNode {
        name: "a",
        amount: 1,
    });
    let b = graph.add_node(AddNode {
        name: "b",
        amount: 10,
    });
    let c = graph.add_node(AddNode {
        name: "c",
        amount: 100,
    });
    graph.add_edge(a.id, b.id);
    graph.add_edge(b.id, c.id);

    let engine = BspEngine::new(graph);
    let EngineResult::Complete(state) = engine.run_with_entries(0, [b.id]).await.unwrap() else {
        panic!("expected completion");
    };
    assert_eq!(state.user, 110, "forced entry skips upstream nodes");
    assert_eq!(state.execution_count(a.id), 0);
    assert_eq!(state.execution_count(b.id), 1);
    assert_eq!(state.execution_count(c.id), 1);
}