pipeline-toolkit 0.2.0

A small toolkit for building linear, async processing pipelines out of independently testable steps that communicate through a shared, type-keyed Context.
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
776
777
778
779
780
781
782
783
784
785
786
787
use std::any::TypeId;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;

use crate::Context;
use crate::context::AccessSpec;
use crate::pipeline::{
    BuildError, CompiledStep, NestedPipelineError, PipelineError, qualify_step_name, run_steps,
};
use crate::step::{Flow, Step, StepError};

/// A named sequence of [`Step`]s that runs as one option of a [`Branch`].
///
/// Build one via [`Self::builder`], the same way a top-level
/// [`Pipeline`](crate::Pipeline) is built, then hand it to
/// [`BranchBuilder::arm`]. An arm may itself contain a `Branch` step,
/// which is how nested branching is expressed — no separate API is needed
/// for it.
///
/// # Examples
///
/// ```
/// use pipeline_toolkit::{AccessSpec, Arm, Context, Flow, Step, StepError};
///
/// struct Double;
///
/// #[async_trait::async_trait]
/// impl Step<i32> for Double {
///     fn name(&self) -> &str {
///         "double"
///     }
///
///     fn access(&self) -> AccessSpec {
///         AccessSpec::new().reads::<i32>()
///     }
///
///     async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
///         let value = *ctx.get::<i32>().expect("declared as read");
///         Ok(Flow::Done(value * 2))
///     }
/// }
///
/// let arm: Arm<i32> = Arm::builder().step(Double).build().unwrap();
/// ```
pub struct Arm<Out> {
    steps: Vec<CompiledStep<Out>>,
    effective: EffectiveAccess,
}

impl<Out> Arm<Out> {
    /// Starts building an arm, the same way [`Pipeline::builder`](crate::Pipeline::builder)
    /// starts building a top-level pipeline.
    pub fn builder() -> ArmBuilder<Out> {
        ArmBuilder { steps: Vec::new() }
    }

    /// This arm's effective access from the outside: which reads it needs
    /// satisfied before it runs (never written or consumed by an earlier
    /// step in the same arm), which writes it guarantees are present by the
    /// time it finishes (accounting for later steps rewriting a consumed
    /// type), and the union of every type any of its steps ever consumes.
    pub(crate) fn effective_access(&self) -> &EffectiveAccess {
        &self.effective
    }

    /// This arm's compiled steps, for a caller (namely
    /// [`Loop`](crate::Loop)) that runs them itself via [`run_steps`] rather
    /// than going through [`Step::run`].
    pub(crate) fn steps(&self) -> &[CompiledStep<Out>] {
        &self.steps
    }
}

pub(crate) struct EffectiveAccess {
    pub(crate) reads: HashMap<TypeId, &'static str>,
    pub(crate) writes: HashMap<TypeId, &'static str>,
    pub(crate) consumes: HashMap<TypeId, &'static str>,
}

/// Computes an arm's [`EffectiveAccess`], mirroring the same reasoning
/// [`PipelineBuilder::build`](crate::PipelineBuilder::build) applies to a
/// whole pipeline: a read is checked against what earlier steps in `steps`
/// have written so far.
///
/// Unlike [`PipelineBuilder::build`](crate::PipelineBuilder::build), a read
/// that nothing earlier in `steps` has ever produced isn't an error here —
/// it's deferred as a "needed" read, to be checked one level up against
/// whatever the enclosing pipeline has already written by the time it
/// reaches the `Branch` step. But a read of a type that *was* produced
/// earlier in `steps` and has since been consumed (and not rewritten) *is*
/// an error here: that type is gone for the rest of this arm regardless of
/// what's available outside it, so no outer pipeline could ever satisfy it
/// either.
fn compute_effective_access<Out>(
    steps: &[CompiledStep<Out>],
) -> Result<EffectiveAccess, BuildError> {
    let mut written: HashMap<TypeId, &'static str> = HashMap::new();
    // Every type this arm has written or consumed at least once so far,
    // regardless of whether it's currently in `written`. Distinguishes "not
    // in `written` because nothing in this arm has touched it yet" (fine,
    // might come from outside) from "not in `written` because this arm
    // itself consumed it and never rewrote it" (an error).
    let mut ever_produced: HashSet<TypeId> = HashSet::new();
    let mut needed_reads: HashMap<TypeId, &'static str> = HashMap::new();
    let mut all_consumed: HashMap<TypeId, &'static str> = HashMap::new();

    for step in steps {
        let mut lost: Vec<(TypeId, &'static str)> = Vec::new();
        let mut first_time: Vec<(TypeId, &'static str)> = Vec::new();
        for (id, name) in step.access.read_entries() {
            if written.contains_key(&id) {
                continue;
            }
            if ever_produced.contains(&id) {
                lost.push((id, name));
            } else {
                first_time.push((id, name));
            }
        }
        if !lost.is_empty() {
            // Deterministic regardless of the read set's HashMap iteration
            // order, matching PipelineBuilder::build's same concern.
            lost.sort_unstable_by_key(|(_, name)| *name);
            let (_, entry) = lost[0];
            return Err(BuildError::UnsatisfiedRead {
                step: step.name.clone(),
                entry,
            });
        }
        for (id, name) in first_time {
            needed_reads.insert(id, name);
        }
        for (id, name) in step.access.write_entries() {
            written.insert(id, name);
            ever_produced.insert(id);
        }
        for (id, name) in step.access.consume_entries() {
            all_consumed.insert(id, name);
            written.remove(&id);
        }
    }

    Ok(EffectiveAccess {
        reads: needed_reads,
        writes: written,
        consumes: all_consumed,
    })
}

/// Incrementally assembles an [`Arm`], returned by [`Arm::builder`].
pub struct ArmBuilder<Out> {
    steps: Vec<Box<dyn Step<Out>>>,
}

impl<Out> ArmBuilder<Out> {
    /// Appends `step` to the end of this arm.
    pub fn step(mut self, step: impl Step<Out> + 'static) -> Self {
        self.steps.push(Box::new(step));
        self
    }

    /// Finishes this arm, caching each step's [`Step::name`] and
    /// [`Step::access`] for the arm's lifetime, the same way
    /// [`PipelineBuilder::build`](crate::PipelineBuilder::build) does for a
    /// top-level pipeline.
    ///
    /// # Errors
    ///
    /// - [`BuildError::DuplicateName`] if two steps in this arm share a
    ///   [`Step::name`].
    /// - [`BuildError::UnsatisfiedRead`] if a step reads a type that an
    ///   earlier step in this same arm has already consumed (via
    ///   [`AccessSpec::consumes`]) without a later step rewriting it —
    ///   nothing outside the arm could ever supply that type once this
    ///   arm has thrown it away itself.
    pub fn build(self) -> Result<Arm<Out>, BuildError> {
        let mut names = HashSet::new();
        let mut steps = Vec::with_capacity(self.steps.len());
        for step in self.steps {
            let name = step.name().to_string();
            if !names.insert(name.clone()) {
                return Err(BuildError::DuplicateName { name });
            }
            let access = step.access();
            steps.push(CompiledStep { name, access, step });
        }

        let effective = compute_effective_access(&steps)?;

        Ok(Arm { steps, effective })
    }
}

/// A framework-provided [`Step`] that runs one of several named arms,
/// chosen at run time by a key-selecting condition function.
///
/// Build one via [`Self::builder`]. `K` is the key type the condition
/// function produces; each arm is registered under one value of `K` via
/// [`BranchBuilder::arm`], and the arm whose key matches the condition's
/// output at run time is the one that runs.
///
/// # Access declaration
///
/// A `Branch`'s [`Step::access`] is computed automatically from its arms,
/// following an asymmetric rule (see the
/// [design doc](https://github.com/ryoshrimp/pipeline-toolkit/blob/main/docs/design/branching.md)
/// for the full rationale):
///
/// - **reads**: the union of every arm's reads (plus the condition
///   function's own declared reads, via [`BranchBuilder::reads`]) — whichever
///   arm runs, everything it might read must already be available.
/// - **writes**: the intersection of every arm's writes — only a type every
///   arm guarantees writing is safe for a downstream step to read.
/// - **consumes**: the union of every arm's consumes — a downstream step
///   must not assume a type survives the branch if any arm might remove it.
///
/// # No matching arm
///
/// If the condition function produces a key with no registered arm,
/// [`Pipeline::run`](crate::Pipeline::run) fails with
/// [`PipelineError::NoMatchingBranch`](crate::PipelineError::NoMatchingBranch)
/// rather than requiring a catch-all default arm.
///
/// # Examples
///
/// ```
/// use pipeline_toolkit::{AccessSpec, Arm, Branch, Context, Flow, Pipeline, Step, StepError};
///
/// #[derive(Clone, Copy, PartialEq, Eq, Hash)]
/// enum Route {
///     Small,
///     Large,
/// }
///
/// struct MarkSmall;
///
/// #[async_trait::async_trait]
/// impl Step<i32> for MarkSmall {
///     fn name(&self) -> &str {
///         "mark_small"
///     }
///     fn access(&self) -> AccessSpec {
///         AccessSpec::new().reads::<i32>()
///     }
///     async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
///         Ok(Flow::Done(*ctx.get::<i32>().expect("declared as read")))
///     }
/// }
///
/// struct MarkLarge;
///
/// #[async_trait::async_trait]
/// impl Step<i32> for MarkLarge {
///     fn name(&self) -> &str {
///         "mark_large"
///     }
///     fn access(&self) -> AccessSpec {
///         AccessSpec::new().reads::<i32>()
///     }
///     async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
///         Ok(Flow::Done(*ctx.get::<i32>().expect("declared as read") * 100))
///     }
/// }
///
/// let branch = Branch::builder("route", |ctx: &Context| {
///     if *ctx.get::<i32>().expect("declared as read") < 10 {
///         Route::Small
///     } else {
///         Route::Large
///     }
/// })
/// .reads::<i32>()
/// .arm(Route::Small, Arm::builder().step(MarkSmall).build()?)
/// .arm(Route::Large, Arm::builder().step(MarkLarge).build()?)
/// .build()?;
///
/// let pipeline = Pipeline::<i32, i32>::builder().step(branch).build()?;
///
/// # fn block_on<F: std::future::Future>(fut: F) -> F::Output {
/// #     use std::task::{Context as TaskContext, Poll, Waker};
/// #     let mut fut = std::pin::pin!(fut);
/// #     let mut cx = TaskContext::from_waker(Waker::noop());
/// #     loop {
/// #         if let Poll::Ready(val) = fut.as_mut().poll(&mut cx) {
/// #             return val;
/// #         }
/// #     }
/// # }
/// #
/// assert_eq!(block_on(pipeline.run(3))?, 3);
/// assert_eq!(block_on(pipeline.run(30))?, 3000);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct Branch<K, Out> {
    name: String,
    condition: Box<dyn Fn(&Context) -> K + Send + Sync>,
    arms: HashMap<K, Arm<Out>>,
    access: AccessSpec,
}

impl<K, Out> Branch<K, Out> {
    /// Starts building a `Branch` named `name`, whose arm is selected by
    /// calling `condition` against the shared [`Context`] each time this
    /// step runs.
    ///
    /// If `condition` itself reads from the [`Context`], declare that via
    /// [`BranchBuilder::reads`] — it is not inferred automatically, since a
    /// closure's body can't be introspected.
    pub fn builder(
        name: impl Into<String>,
        condition: impl Fn(&Context) -> K + Send + Sync + 'static,
    ) -> BranchBuilder<K, Out> {
        BranchBuilder {
            name: name.into(),
            condition: Box::new(condition),
            condition_access: AccessSpec::new(),
            arms: HashMap::new(),
        }
    }
}

#[async_trait::async_trait]
impl<K, Out> Step<Out> for Branch<K, Out>
where
    K: Eq + Hash + Send + Sync + 'static,
    Out: Send + Sync + 'static,
{
    fn name(&self) -> &str {
        &self.name
    }

    fn access(&self) -> AccessSpec {
        self.access.clone()
    }

    async fn run(&self, ctx: &mut Context) -> Result<Flow<Out>, StepError> {
        let key = (self.condition)(ctx);
        let Some(arm) = self.arms.get(&key) else {
            return Err(StepError::new(NestedPipelineError(
                PipelineError::NoMatchingBranch {
                    step: self.name.clone(),
                },
            )));
        };
        run_steps(&arm.steps, ctx)
            .await
            .map_err(|err| StepError::new(NestedPipelineError(qualify_step_name(&self.name, err))))
    }
}

/// Incrementally assembles a [`Branch`], returned by [`Branch::builder`].
pub struct BranchBuilder<K, Out> {
    name: String,
    condition: Box<dyn Fn(&Context) -> K + Send + Sync>,
    condition_access: AccessSpec,
    arms: HashMap<K, Arm<Out>>,
}

impl<K: Eq + Hash, Out> BranchBuilder<K, Out> {
    /// Declares that the condition function reads `T` from the [`Context`]
    /// when it runs, folding it into the union computed for
    /// [`Step::access`]. Chainable across multiple types, like
    /// [`AccessSpec::reads`].
    pub fn reads<T: 'static>(mut self) -> Self {
        self.condition_access = self.condition_access.reads::<T>();
        self
    }

    /// Registers `arm` to run when the condition function produces `key`.
    /// Registering the same `key` again replaces the previous arm.
    pub fn arm(mut self, key: K, arm: Arm<Out>) -> Self {
        self.arms.insert(key, arm);
        self
    }

    /// Finishes this `Branch`, computing its [`Step::access`] from every
    /// registered arm's effective access plus the condition's own declared
    /// reads. See [`Branch`]'s docs for the union/intersection/union rule
    /// this applies.
    ///
    /// # Errors
    ///
    /// [`BuildError::EmptyBranch`] if no arm was ever registered via
    /// [`Self::arm`] — such a branch would fail every run with
    /// [`PipelineError::NoMatchingBranch`](crate::PipelineError::NoMatchingBranch)
    /// no matter what key the condition function produces.
    pub fn build(self) -> Result<Branch<K, Out>, BuildError> {
        if self.arms.is_empty() {
            return Err(BuildError::EmptyBranch { step: self.name });
        }

        let mut reads_union: HashMap<TypeId, &'static str> = HashMap::new();
        let mut consumes_union: HashMap<TypeId, &'static str> = HashMap::new();
        let mut writes_intersection: Option<HashMap<TypeId, &'static str>> = None;

        for arm in self.arms.values() {
            let effective = arm.effective_access();
            reads_union.extend(effective.reads.iter().map(|(id, name)| (*id, *name)));
            consumes_union.extend(effective.consumes.iter().map(|(id, name)| (*id, *name)));
            writes_intersection = Some(match writes_intersection {
                None => effective.writes.clone(),
                Some(acc) => acc
                    .into_iter()
                    .filter(|(id, _)| effective.writes.contains_key(id))
                    .collect(),
            });
        }

        let writes_intersection = writes_intersection.unwrap_or_default();

        let mut access = self.condition_access;
        access.extend_reads(reads_union);
        // A type in `writes_intersection` is guaranteed present by every
        // arm once it finishes, so it must not also be declared as
        // consumed here: PipelineBuilder::build applies a step's declared
        // writes before its declared consumes, so a type present in both
        // would have its guaranteed write immediately undone by this same
        // step's own consume, making the outer pipeline wrongly see it as
        // unavailable to a step downstream of this Branch. This only
        // arises when every arm both consumes and rewrites the same type
        // (an edge case for Branch, but the normal case for Loop, whose
        // single body always does this when it rewrites a consumed type).
        access.extend_consumes(
            consumes_union
                .into_iter()
                .filter(|(id, _)| !writes_intersection.contains_key(id)),
        );
        access.extend_writes(writes_intersection);

        Ok(Branch {
            name: self.name,
            condition: self.condition,
            arms: self.arms,
            access,
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::step::Flow;
    use crate::test_support::block_on;

    struct Alpha;
    struct Beta;

    struct FixedAccessStep {
        access: AccessSpec,
    }

    #[async_trait::async_trait]
    impl Step<i32> for FixedAccessStep {
        fn name(&self) -> &str {
            "fixed"
        }

        fn access(&self) -> AccessSpec {
            self.access.clone()
        }

        async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
            Ok(Flow::Continue)
        }
    }

    fn arm_with(access: AccessSpec) -> Arm<i32> {
        Arm::builder()
            .step(FixedAccessStep { access })
            .build()
            .unwrap()
    }

    #[test]
    fn build_computes_reads_as_union_of_arms_needed_reads() {
        let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
            .arm(0, arm_with(AccessSpec::new().reads::<Alpha>()))
            .arm(1, arm_with(AccessSpec::new().reads::<Beta>()))
            .build()
            .unwrap();
        let access = branch.access();
        assert!(access.can_read(TypeId::of::<Alpha>()));
        assert!(access.can_read(TypeId::of::<Beta>()));
    }

    #[test]
    fn build_folds_the_condition_functions_own_declared_reads_into_the_union() {
        let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
            .reads::<Alpha>()
            .arm(0, arm_with(AccessSpec::new()))
            .build()
            .unwrap();
        assert!(branch.access().can_read(TypeId::of::<Alpha>()));
    }

    #[test]
    fn build_computes_writes_as_intersection_of_arms_writes() {
        let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
            .arm(
                0,
                arm_with(AccessSpec::new().writes::<Alpha>().writes::<Beta>()),
            )
            .arm(1, arm_with(AccessSpec::new().writes::<Alpha>()))
            .build()
            .unwrap();
        let access = branch.access();
        assert!(access.can_write(TypeId::of::<Alpha>()));
        assert!(!access.can_write(TypeId::of::<Beta>()));
    }

    #[test]
    fn build_computes_consumes_as_union_of_arms_consumes() {
        let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
            .arm(0, arm_with(AccessSpec::new().consumes::<Alpha>()))
            .arm(1, arm_with(AccessSpec::new().consumes::<Beta>()))
            .build()
            .unwrap();
        let access = branch.access();
        assert!(access.can_consume(TypeId::of::<Alpha>()));
        assert!(access.can_consume(TypeId::of::<Beta>()));
    }

    #[test]
    fn arm_build_fails_when_a_later_step_reads_a_type_this_arm_already_consumed() {
        struct ConsumeAlpha;
        #[async_trait::async_trait]
        impl Step<i32> for ConsumeAlpha {
            fn name(&self) -> &str {
                "consume_alpha"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().consumes::<Alpha>()
            }
            async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                ctx.take::<Alpha>();
                Ok(Flow::Continue)
            }
        }

        struct ReadAlphaAgain;
        #[async_trait::async_trait]
        impl Step<i32> for ReadAlphaAgain {
            fn name(&self) -> &str {
                "read_alpha_again"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().reads::<Alpha>()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Ok(Flow::Continue)
            }
        }

        let result = Arm::<i32>::builder()
            .step(ConsumeAlpha)
            .step(ReadAlphaAgain)
            .build();
        assert!(matches!(
            result,
            Err(BuildError::UnsatisfiedRead { step, .. }) if step == "read_alpha_again"
        ));
    }

    #[test]
    fn arm_build_succeeds_when_a_read_after_consume_is_needed_from_outside_the_arm() {
        // The very first (and only) access of Alpha in this arm is a read;
        // nothing inside the arm has produced-then-lost it, so this is a
        // legitimate "needed from outside" read, not the consumed-then-read
        // bug.
        let result = Arm::<i32>::builder()
            .step(FixedAccessStep {
                access: AccessSpec::new().reads::<Alpha>(),
            })
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn arm_build_treats_a_read_as_satisfied_by_an_earlier_write_in_the_same_arm() {
        struct WriteThenReadAlpha;
        #[async_trait::async_trait]
        impl Step<i32> for WriteThenReadAlpha {
            fn name(&self) -> &str {
                "write_alpha"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().writes::<Alpha>()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Ok(Flow::Continue)
            }
        }
        struct ReadAlpha;
        #[async_trait::async_trait]
        impl Step<i32> for ReadAlpha {
            fn name(&self) -> &str {
                "read_alpha"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().reads::<Alpha>()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Ok(Flow::Continue)
            }
        }

        let arm = Arm::<i32>::builder()
            .step(WriteThenReadAlpha)
            .step(ReadAlpha)
            .build()
            .unwrap();
        let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
            .arm(0, arm)
            .build()
            .unwrap();
        // Alpha was written by the first step in this same arm before the
        // second step reads it, so it's satisfied internally and must not
        // show up as something the branch needs from outside.
        assert!(!branch.access().can_read(TypeId::of::<Alpha>()));
    }

    #[test]
    fn arm_build_fails_on_duplicate_step_names() {
        let result = Arm::<i32>::builder()
            .step(FixedAccessStep {
                access: AccessSpec::new(),
            })
            .step(FixedAccessStep {
                access: AccessSpec::new(),
            })
            .build();
        assert!(matches!(result, Err(BuildError::DuplicateName { name }) if name == "fixed"));
    }

    #[test]
    fn branch_build_fails_when_no_arms_registered() {
        let result = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8).build();
        assert!(matches!(result, Err(BuildError::EmptyBranch { step }) if step == "route"));
    }

    struct DoneStep(i32);

    #[async_trait::async_trait]
    impl Step<i32> for DoneStep {
        fn name(&self) -> &str {
            "done"
        }

        fn access(&self) -> AccessSpec {
            AccessSpec::new()
        }

        async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
            Ok(Flow::Done(self.0))
        }
    }

    #[test]
    fn run_dispatches_to_the_arm_matching_the_condition_key() {
        let branch: Branch<u8, i32> = Branch::builder("route", |_ctx: &Context| 1u8)
            .arm(0, Arm::builder().step(DoneStep(100)).build().unwrap())
            .arm(1, Arm::builder().step(DoneStep(200)).build().unwrap())
            .build()
            .unwrap();
        let mut ctx = Context::new();
        match block_on(branch.run(&mut ctx)) {
            Ok(Flow::Done(v)) => assert_eq!(v, 200),
            Ok(Flow::Continue) => panic!("expected Done(200), got Continue"),
            Err(err) => panic!("expected Done(200), got Err({err})"),
        }
    }

    #[test]
    fn run_returns_err_wrapping_no_matching_branch_when_key_has_no_arm() {
        let branch: Branch<u8, i32> = Branch::builder("route", |_ctx: &Context| 9u8)
            .arm(0, Arm::builder().step(DoneStep(1)).build().unwrap())
            .build()
            .unwrap();
        let mut ctx = Context::new();
        let err = match block_on(branch.run(&mut ctx)) {
            Err(err) => err,
            Ok(_) => panic!("expected Err: no arm matches key 9"),
        };
        let nested = err
            .downcast::<NestedPipelineError>()
            .unwrap_or_else(|_| panic!("expected a NestedPipelineError"));
        match nested.0 {
            PipelineError::NoMatchingBranch { step } => assert_eq!(step, "route"),
            other => panic!("expected NoMatchingBranch, got {other}"),
        }
    }

    #[test]
    fn run_qualifies_a_step_error_from_within_an_arm_with_the_branch_name() {
        struct Fail;
        #[async_trait::async_trait]
        impl Step<i32> for Fail {
            fn name(&self) -> &str {
                "fail"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Err(StepError::new("boom"))
            }
        }

        let branch: Branch<u8, i32> = Branch::builder("route", |_ctx: &Context| 0u8)
            .arm(0, Arm::builder().step(Fail).build().unwrap())
            .build()
            .unwrap();
        let mut ctx = Context::new();
        let err = match block_on(branch.run(&mut ctx)) {
            Err(err) => err,
            Ok(_) => panic!("expected Err"),
        };
        let nested = err
            .downcast::<NestedPipelineError>()
            .unwrap_or_else(|_| panic!("expected a NestedPipelineError"));
        match nested.0 {
            PipelineError::Step { step, .. } => assert_eq!(step, "route/fail"),
            other => panic!("expected Step, got {other}"),
        }
    }

    #[test]
    fn run_qualifies_an_access_violation_from_within_an_arm_with_the_branch_name() {
        struct RogueRead;
        #[async_trait::async_trait]
        impl Step<i32> for RogueRead {
            fn name(&self) -> &str {
                "rogue_read"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new()
            }
            async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                let _ = ctx.get::<Alpha>();
                Ok(Flow::Continue)
            }
        }

        let branch: Branch<u8, i32> = Branch::builder("route", |_ctx: &Context| 0u8)
            .arm(0, Arm::builder().step(RogueRead).build().unwrap())
            .build()
            .unwrap();
        let mut ctx = Context::new();
        let err = match block_on(branch.run(&mut ctx)) {
            Err(err) => err,
            Ok(_) => panic!("expected Err"),
        };
        let nested = err
            .downcast::<NestedPipelineError>()
            .unwrap_or_else(|_| panic!("expected a NestedPipelineError"));
        match nested.0 {
            PipelineError::AccessViolation(v) => assert_eq!(v.step, "route/rogue_read"),
            other => panic!("expected AccessViolation, got {other}"),
        }
    }

    #[test]
    fn run_qualifies_a_nested_no_matching_branch_error_with_both_branch_names() {
        let inner: Branch<u8, i32> = Branch::builder("inner", |_ctx: &Context| 9u8)
            .arm(0, Arm::builder().step(DoneStep(1)).build().unwrap())
            .build()
            .unwrap();

        let outer: Branch<u8, i32> = Branch::builder("outer", |_ctx: &Context| 0u8)
            .arm(0, Arm::builder().step(inner).build().unwrap())
            .build()
            .unwrap();

        let mut ctx = Context::new();
        let err = match block_on(outer.run(&mut ctx)) {
            Err(err) => err,
            Ok(_) => panic!("expected Err"),
        };
        let nested = err
            .downcast::<NestedPipelineError>()
            .unwrap_or_else(|_| panic!("expected a NestedPipelineError"));
        match nested.0 {
            PipelineError::NoMatchingBranch { step } => assert_eq!(step, "outer/inner"),
            other => panic!("expected NoMatchingBranch, got {other}"),
        }
    }
}