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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
#[cfg(test)]
use crate::context::AccessKind;
use crate::context::{AccessSpec, AccessViolation, Context};
use crate::step::{Flow, Step, StepError};
use std::any::TypeId;
use std::collections::{HashMap, HashSet};

/// Why [`PipelineBuilder::build`] rejected a pipeline.
///
/// See [`PipelineBuilder::build`] for a runnable example of the
/// [`UnsatisfiedRead`](Self::UnsatisfiedRead) case.
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
    /// Two steps — including one placed by
    /// [`PipelineBuilder::insert_before`]/[`PipelineBuilder::insert_after`] —
    /// share the same [`Step::name`].
    #[error("duplicate step name: `{name}`")]
    DuplicateName {
        /// The name shared by more than one step.
        name: String,
    },
    /// An [`insert_before`](PipelineBuilder::insert_before)/
    /// [`insert_after`](PipelineBuilder::insert_after) call named an anchor
    /// that no step, whether added directly or by another pending insert,
    /// ever resolves to.
    #[error("anchor step not found: `{anchor}`")]
    AnchorNotFound {
        /// The anchor name that never matched a step.
        anchor: String,
    },
    /// A step declares [`AccessSpec::reads`] for a type that no earlier
    /// step (or the pipeline's input type) declares writing. Also used for
    /// an [`Arm`](crate::Arm) step that reads a type an earlier step in the
    /// same arm has already consumed (via [`AccessSpec::consumes`]) without
    /// a later step rewriting it — that type is gone for the rest of the
    /// arm regardless of what's available outside it, so this is caught
    /// when the arm itself is built rather than deferred to the enclosing
    /// pipeline.
    #[error(
        "step `{step}` reads `{entry}`, but no upstream step (nor the pipeline input) writes it"
    )]
    UnsatisfiedRead {
        /// The step with the unsatisfied read.
        step: String,
        /// The [`type_name`](std::any::type_name) of the unwritten entry.
        entry: &'static str,
    },
    /// A [`Branch`](crate::Branch) was built with no arms registered via
    /// [`BranchBuilder::arm`](crate::BranchBuilder::arm). Such a branch
    /// would fail every run with
    /// [`PipelineError::NoMatchingBranch`](crate::PipelineError::NoMatchingBranch)
    /// regardless of the key its condition function produces, so it's
    /// rejected at build time instead.
    #[error("branch `{step}` has no arms")]
    EmptyBranch {
        /// The name of the `Branch`.
        step: String,
    },
    /// A [`Loop`](crate::Loop)'s body [`Arm`](crate::Arm) consumes a type via
    /// [`AccessSpec::consumes`] without a later step in that same body
    /// rewriting it. A `Loop` body runs more than once, so a type it
    /// consumed and never rewrote would exist on the first iteration but be
    /// gone from the second one onward — a failure mode
    /// [`Arm::build`](crate::ArmBuilder::build)'s single-pass check can't
    /// see, since it only reasons about one execution of the body.
    #[error(
        "loop `{step}` body consumes `{entry}` without rewriting it, which would fail every iteration after the first"
    )]
    UnrepeatableConsume {
        /// The name of the `Loop`.
        step: String,
        /// The [`type_name`](std::any::type_name) of the consumed-but-never-rewritten entry.
        entry: &'static str,
    },
}

/// Why [`Pipeline::run`] failed.
///
/// See [`Pipeline::run`] for the full list of conditions that produce each
/// variant.
#[derive(Debug, thiserror::Error)]
pub enum PipelineError {
    /// A step's [`Step::run`] returned `Err`.
    #[error("step `{step}` failed: {source}")]
    Step {
        /// The name of the step that failed.
        step: String,
        /// The error the step returned.
        #[source]
        source: StepError,
    },
    /// A step read, wrote, or consumed a [`Context`] entry its
    /// [`AccessSpec`] didn't declare. See [`AccessViolation`] for which
    /// step, which entry, and which kind of access.
    #[error("step `{}` {} `{}` without declaring it", .0.step, .0.verb(), .0.entry)]
    AccessViolation(AccessViolation),
    /// Every step returned [`Flow::Continue`]; none produced a
    /// [`Flow::Done`] output.
    #[error("pipeline exhausted: no step produced an outcome")]
    Exhausted,
    /// A [`Branch`](crate::Branch) step's condition function produced a key
    /// that no arm was registered for.
    #[error("step `{step}` had no matching branch arm")]
    NoMatchingBranch {
        /// The name of the `Branch` step.
        step: String,
    },
    /// A [`Loop`](crate::Loop) step ran its body `max_iterations` times
    /// without its condition function ever returning `false`.
    #[error("step `{step}` exceeded its max_iterations limit of {max_iterations}")]
    MaxIterationsExceeded {
        /// The name of the `Loop` step.
        step: String,
        /// The configured iteration limit that was reached.
        max_iterations: u32,
    },
}

/// Wraps a [`PipelineError`] so it can cross a [`Step::run`] boundary intact
/// even though [`Step::run`] can only return a [`StepError`].
///
/// [`Branch`](crate::Branch) uses this both for its own "no arm matched"
/// case and to re-wrap whatever [`PipelineError`] one of its arms produced
/// (via [`run_steps`]), so that error surfaces from the outermost
/// [`Pipeline::run`] as itself — an [`AccessViolation`] or
/// [`NoMatchingBranch`](PipelineError::NoMatchingBranch) three arms deep
/// stays that variant, rather than getting flattened into
/// [`PipelineError::Step`] at every level it passes through.
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub(crate) struct NestedPipelineError(pub(crate) PipelineError);

struct Pending<Out> {
    anchor: String,
    step: Box<dyn Step<Out>>,
    after: bool,
}

/// Incrementally assembles a [`Pipeline`], returned by [`Pipeline::builder`].
///
/// `In` is the type steps can read as the pipeline input; `Out` is the type
/// every [`Step`] in the pipeline shares as its own output type. Chain
/// [`Self::step`], [`Self::insert_before`], and [`Self::insert_after`]
/// calls, then finish with [`Self::build`].
pub struct PipelineBuilder<In, Out> {
    steps: Vec<Box<dyn Step<Out>>>,
    pending: Vec<Pending<Out>>,
    _in: std::marker::PhantomData<fn(In)>,
}

impl<In: Send + Sync + 'static, Out> PipelineBuilder<In, Out> {
    /// Appends `step` to the end of the pipeline, after every step added so
    /// far — though possibly before steps inserted later via
    /// [`Self::insert_before`]/[`Self::insert_after`] anchored on one of
    /// those earlier steps.
    ///
    /// # Examples
    ///
    /// ```
    /// use pipeline_toolkit::Pipeline;
    /// # use pipeline_toolkit::{AccessSpec, Context, Flow, Step, StepError};
    /// #
    /// # struct NoOp(&'static str);
    /// # #[async_trait::async_trait]
    /// # impl Step<()> for NoOp {
    /// #     fn name(&self) -> &str { self.0 }
    /// #     fn access(&self) -> AccessSpec { AccessSpec::new() }
    /// #     async fn run(&self, _ctx: &mut Context) -> Result<Flow<()>, StepError> {
    /// #         Ok(Flow::Continue)
    /// #     }
    /// # }
    /// let pipeline = Pipeline::<(), ()>::builder()
    ///     .step(NoOp("a"))
    ///     .step(NoOp("b"))
    ///     .build()?;
    /// assert_eq!(pipeline.step_names(), vec!["a", "b"]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn step(mut self, step: impl Step<Out> + 'static) -> Self {
        self.steps.push(Box::new(step));
        self
    }

    /// Registers `step` to be placed immediately before the step named
    /// `anchor`, once [`Self::build`] resolves anchors.
    ///
    /// `anchor` may itself be a step registered via [`Self::step`] or
    /// another pending insert — resolution order doesn't matter, only that
    /// some step eventually resolves to that name, or [`Self::build`]
    /// returns [`BuildError::AnchorNotFound`]. Repeated calls with the same
    /// anchor keep steps in registration order, immediately preceding the
    /// anchor.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pipeline_toolkit::{AccessSpec, Context, Flow, Pipeline, Step, StepError};
    /// #
    /// # struct NoOp(&'static str);
    /// # #[async_trait::async_trait]
    /// # impl Step<()> for NoOp {
    /// #     fn name(&self) -> &str { self.0 }
    /// #     fn access(&self) -> AccessSpec { AccessSpec::new() }
    /// #     async fn run(&self, _ctx: &mut Context) -> Result<Flow<()>, StepError> {
    /// #         Ok(Flow::Continue)
    /// #     }
    /// # }
    /// let pipeline = Pipeline::<(), ()>::builder()
    ///     .step(NoOp("a"))
    ///     .step(NoOp("b"))
    ///     .insert_before("b", NoOp("x"))
    ///     .build()?;
    /// assert_eq!(pipeline.step_names(), vec!["a", "x", "b"]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn insert_before(
        mut self,
        anchor: impl Into<String>,
        step: impl Step<Out> + 'static,
    ) -> Self {
        self.pending.push(Pending {
            anchor: anchor.into(),
            step: Box::new(step),
            after: false,
        });
        self
    }

    /// Registers `step` to be placed immediately after the step named
    /// `anchor`, once [`Self::build`] resolves anchors.
    ///
    /// Follows the same anchor-resolution and repeated-call ordering rules
    /// as [`Self::insert_before`], but places `step` after the anchor
    /// instead of before it.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pipeline_toolkit::{AccessSpec, Context, Flow, Pipeline, Step, StepError};
    /// #
    /// # struct NoOp(&'static str);
    /// # #[async_trait::async_trait]
    /// # impl Step<()> for NoOp {
    /// #     fn name(&self) -> &str { self.0 }
    /// #     fn access(&self) -> AccessSpec { AccessSpec::new() }
    /// #     async fn run(&self, _ctx: &mut Context) -> Result<Flow<()>, StepError> {
    /// #         Ok(Flow::Continue)
    /// #     }
    /// # }
    /// let pipeline = Pipeline::<(), ()>::builder()
    ///     .step(NoOp("a"))
    ///     .step(NoOp("b"))
    ///     .insert_after("a", NoOp("x"))
    ///     .build()?;
    /// assert_eq!(pipeline.step_names(), vec!["a", "x", "b"]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn insert_after(
        mut self,
        anchor: impl Into<String>,
        step: impl Step<Out> + 'static,
    ) -> Self {
        self.pending.push(Pending {
            anchor: anchor.into(),
            step: Box::new(step),
            after: true,
        });
        self
    }

    /// Validates that every declared read is satisfied by an earlier step's
    /// (or the pipeline input's) declared write, and that a step declaring
    /// [`AccessSpec::consumes`] is treated as removing the value for
    /// downstream steps unless it is written again afterward.
    ///
    /// This check is static: it reasons about declared access, not what a
    /// step's `run` actually does. A step that declares
    /// [`AccessSpec::writes`] but never calls [`Context::insert`] still
    /// passes validation; a downstream read of that type will simply
    /// observe `None` at runtime, since [`Context`] accessors return
    /// `Option` rather than assuming presence.
    ///
    /// # Errors
    ///
    /// - [`BuildError::AnchorNotFound`] if an
    ///   [`insert_before`](Self::insert_before)/[`insert_after`](Self::insert_after)
    ///   anchor never resolves to a step.
    /// - [`BuildError::DuplicateName`] if two steps share a [`Step::name`].
    /// - [`BuildError::UnsatisfiedRead`] if a step declares a read that no
    ///   earlier step (or the pipeline input) declares writing.
    ///
    /// # Examples
    ///
    /// ```
    /// use pipeline_toolkit::{AccessSpec, BuildError, Pipeline, Step};
    /// # use pipeline_toolkit::{Context, Flow, StepError};
    /// #
    /// struct Marker;
    ///
    /// # struct ReadsMarker;
    /// # #[async_trait::async_trait]
    /// # impl Step<()> for ReadsMarker {
    /// #     fn name(&self) -> &str { "reads_marker" }
    /// #     fn access(&self) -> AccessSpec { AccessSpec::new().reads::<Marker>() }
    /// #     async fn run(&self, _ctx: &mut Context) -> Result<Flow<()>, StepError> {
    /// #         Ok(Flow::Continue)
    /// #     }
    /// # }
    /// // `ReadsMarker` reads `Marker`, but nothing upstream writes it.
    /// let result = Pipeline::<(), ()>::builder().step(ReadsMarker).build();
    /// assert!(matches!(
    ///     result,
    ///     Err(BuildError::UnsatisfiedRead { step, .. }) if step == "reads_marker"
    /// ));
    /// ```
    pub fn build(mut self) -> Result<Pipeline<In, Out>, BuildError> {
        // Resolution is a fixed-point over multiple passes rather than a
        // single left-to-right scan: a pending insert may anchor onto
        // another pending insert that hasn't been placed into `self.steps`
        // yet, and which pending resolves first must not depend on which
        // `insert_before`/`insert_after` call happened to be registered
        // first.
        let mut pending = self.pending;
        // Tracks how many steps have already been placed after a given
        // anchor, so repeated insert_after("a", ...) calls queue up
        // following the anchor in registration order — the same order
        // repeated insert_before("a", ...) calls naturally produce
        // immediately preceding the anchor (each one is inserted at the
        // anchor's current position, pushing the anchor itself, and every
        // step already placed before it, further along).
        let mut after_offset: HashMap<String, usize> = HashMap::new();
        while !pending.is_empty() {
            let mut still_pending = Vec::with_capacity(pending.len());
            let mut progressed = false;
            for item in pending {
                match self.steps.iter().position(|s| s.name() == item.anchor) {
                    Some(index) => {
                        progressed = true;
                        if item.after {
                            let offset = after_offset.entry(item.anchor).or_insert(0);
                            *offset += 1;
                            self.steps.insert(index + *offset, item.step);
                        } else {
                            self.steps.insert(index, item.step);
                        }
                    }
                    None => still_pending.push(item),
                }
            }
            if !progressed {
                return Err(BuildError::AnchorNotFound {
                    anchor: still_pending[0].anchor.clone(),
                });
            }
            pending = still_pending;
        }

        // Call each step's name() and access() exactly once here and cache
        // the result in the compiled Pipeline. Steps are trait objects with
        // no purity contract on these methods; if run() called them again
        // instead of reusing what build() validated, a step that returned a
        // different name or AccessSpec on a later call could make run()
        // enforce something other than what build() actually checked.
        let mut names = HashSet::new();
        let mut compiled = 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();
            compiled.push(CompiledStep { name, access, step });
        }

        let mut written: HashSet<TypeId> = HashSet::from([TypeId::of::<In>()]);
        for compiled_step in &compiled {
            // AccessSpec stores reads in a HashMap, whose iteration order is
            // randomized per-process; if a step has multiple unsatisfied
            // reads, picking the first one seen here would make the
            // reported entry vary run to run for identical input. Collect
            // every unsatisfied read and report the one that sorts first by
            // type name, which is stable regardless of HashMap iteration
            // order.
            let mut unsatisfied: Vec<(TypeId, &'static str)> = compiled_step
                .access
                .read_entries()
                .filter(|(id, _)| !written.contains(id))
                .collect();
            unsatisfied.sort_unstable_by_key(|(_, entry)| *entry);
            if let Some((_, entry)) = unsatisfied.into_iter().next() {
                return Err(BuildError::UnsatisfiedRead {
                    step: compiled_step.name.clone(),
                    entry,
                });
            }
            written.extend(compiled_step.access.write_entries().map(|(id, _)| id));
            for (id, _) in compiled_step.access.consume_entries() {
                written.remove(&id);
            }
        }

        Ok(Pipeline {
            steps: compiled,
            _in: std::marker::PhantomData,
        })
    }
}

/// Prefixes whatever step name is embedded in `err` with `qualifier`.
///
/// An error from deep inside a [`Branch`](crate::Branch) arm or a
/// [`Loop`](crate::Loop) body would otherwise carry only that step's own
/// bare name — meaningful on its own, but ambiguous once more than one arm,
/// loop body, or enclosing pipeline can contain a step of the same name.
/// Qualifying it with the branch/loop it came from keeps
/// [`PipelineError::Step`]/[`AccessViolation`]/[`PipelineError::NoMatchingBranch`]/
/// [`PipelineError::MaxIterationsExceeded`] messages locally identifiable at
/// every level they pass through, without requiring step names to be
/// globally unique across arms, loop bodies, and pipelines.
pub(crate) fn qualify_step_name(qualifier: &str, err: PipelineError) -> PipelineError {
    match err {
        PipelineError::Step { step, source } => PipelineError::Step {
            step: format!("{qualifier}/{step}"),
            source,
        },
        PipelineError::AccessViolation(violation) => {
            PipelineError::AccessViolation(AccessViolation {
                step: format!("{qualifier}/{}", violation.step),
                ..violation
            })
        }
        PipelineError::NoMatchingBranch { step } => PipelineError::NoMatchingBranch {
            step: format!("{qualifier}/{step}"),
        },
        PipelineError::MaxIterationsExceeded {
            step,
            max_iterations,
        } => PipelineError::MaxIterationsExceeded {
            step: format!("{qualifier}/{step}"),
            max_iterations,
        },
        // run_steps only ever returns this from Pipeline::run reaching the
        // end of a top-level pipeline with every step Continue-ing — never
        // from the arm/body dispatch this function's callers (Branch::run,
        // Loop::run) wrap, which report the equivalent "every step
        // continued" outcome as Ok(Flow::Continue) instead (see
        // run_steps's doc comment). Exhausted also carries no step name to
        // qualify in the first place, so silently passing it through here
        // would be misleading.
        PipelineError::Exhausted => unreachable!(
            "Branch's arm dispatch and Loop's body dispatch never produce PipelineError::Exhausted, only Pipeline::run does"
        ),
    }
}

pub(crate) struct CompiledStep<Out> {
    pub(crate) name: String,
    pub(crate) access: AccessSpec,
    pub(crate) step: Box<dyn Step<Out>>,
}

/// Runs `steps` against `ctx` in order, starting from whatever step is
/// first, until one returns [`Flow::Done`], returns `Err`, or every step has
/// run and returned [`Flow::Continue`].
///
/// This is the shared execution loop behind both [`Pipeline::run`] and
/// [`Branch`](crate::Branch)'s arm dispatch. The two differ only in how they
/// treat exhausting `steps` without a [`Flow::Done`]: [`Pipeline::run`]
/// treats that as [`PipelineError::Exhausted`], while an arm treats it as a
/// normal [`Flow::Continue`] back to the branch (see
/// [`Branch`](crate::Branch) for why) — so this function reports that case
/// as `Ok(Flow::Continue)` and lets each caller decide.
///
/// A step's `Err` is normally wrapped as [`PipelineError::Step`], but a
/// [`StepError`] wrapping a [`NestedPipelineError`] (as
/// [`Branch`](crate::Branch) produces) is unwrapped and returned as-is
/// instead, so a nested arm's own [`PipelineError`] variant propagates
/// unchanged through every enclosing branch/pipeline.
pub(crate) async fn run_steps<Out>(
    steps: &[CompiledStep<Out>],
    ctx: &mut Context,
) -> Result<Flow<Out>, PipelineError> {
    for compiled_step in steps {
        ctx.set_active(compiled_step.name.clone(), compiled_step.access.clone());
        let result = compiled_step.step.run(ctx).await;
        ctx.clear_active();
        if let Some(v) = ctx.take_violation() {
            return Err(PipelineError::AccessViolation(v));
        }
        match result {
            Ok(Flow::Continue) => continue,
            Ok(Flow::Done(out)) => return Ok(Flow::Done(out)),
            Err(source) => {
                return match source.downcast::<NestedPipelineError>() {
                    Ok(NestedPipelineError(err)) => Err(err),
                    Err(source) => Err(PipelineError::Step {
                        step: compiled_step.name.clone(),
                        source,
                    }),
                };
            }
        }
    }
    Ok(Flow::Continue)
}

/// A validated, immutable sequence of [`Step`]s, built via [`Self::builder`].
///
/// Every step's [`name`](Step::name) and [`access`](Step::access) were
/// already read once during [`PipelineBuilder::build`] and are reused for
/// the pipeline's lifetime, so [`Self::run`] never calls them again.
///
/// See the [crate-level example](crate) for building and running one.
pub struct Pipeline<In, Out> {
    steps: Vec<CompiledStep<Out>>,
    _in: std::marker::PhantomData<fn(In)>,
}

impl<In, Out> std::fmt::Debug for Pipeline<In, Out> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Pipeline")
            .field(
                "steps",
                &self
                    .steps
                    .iter()
                    .map(|s| s.name.as_str())
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

impl<In: Send + Sync + 'static, Out> Pipeline<In, Out> {
    /// Starts building a pipeline whose steps take `In` as input and share
    /// `Out` as their output type.
    ///
    /// # Examples
    ///
    /// ```
    /// use pipeline_toolkit::Pipeline;
    ///
    /// let pipeline = Pipeline::<(), i32>::builder().build()?;
    /// assert!(pipeline.step_names().is_empty());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn builder() -> PipelineBuilder<In, Out> {
        PipelineBuilder {
            steps: Vec::new(),
            pending: Vec::new(),
            _in: std::marker::PhantomData,
        }
    }

    /// Runs the pipeline against `input`, executing steps in order until one
    /// returns [`Flow::Done`].
    ///
    /// `input` is inserted into a fresh [`Context`] as the pipeline's `In`
    /// value before the first step runs.
    ///
    /// # Errors
    ///
    /// - [`PipelineError::Step`] if a step's [`run`](Step::run) returns
    ///   `Err`.
    /// - [`PipelineError::AccessViolation`] if a step reads, writes, or
    ///   takes a [`Context`] entry its [`AccessSpec`] didn't declare.
    /// - [`PipelineError::Exhausted`] if every step returns
    ///   [`Flow::Continue`] and none produces an output.
    ///
    /// See the [crate-level example](crate) for a full pipeline that builds
    /// and runs successfully.
    pub async fn run(&self, input: In) -> Result<Out, PipelineError> {
        let mut ctx = Context::new();
        ctx.insert(input);
        match run_steps(&self.steps, &mut ctx).await? {
            Flow::Done(out) => Ok(out),
            Flow::Continue => Err(PipelineError::Exhausted),
        }
    }

    /// Lists the resolved step names in execution order, mainly for
    /// diagnostics and tests.
    ///
    /// # Examples
    ///
    /// ```
    /// use pipeline_toolkit::Pipeline;
    ///
    /// let pipeline = Pipeline::<(), ()>::builder().build()?;
    /// assert!(pipeline.step_names().is_empty());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn step_names(&self) -> Vec<&str> {
        self.steps.iter().map(|s| s.name.as_str()).collect()
    }
}

#[cfg(test)]
mod test {
    use std::error::Error;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;
    use crate::test_support::block_on;

    #[test]
    fn display_formats_duplicate_name() {
        let err = BuildError::DuplicateName {
            name: "load".to_string(),
        };
        assert_eq!(err.to_string(), "duplicate step name: `load`");
    }

    #[test]
    fn display_formats_anchor_not_found() {
        let err = BuildError::AnchorNotFound {
            anchor: "load".to_string(),
        };
        assert_eq!(err.to_string(), "anchor step not found: `load`");
    }

    #[test]
    fn display_formats_unsatisfied_read() {
        let err = BuildError::UnsatisfiedRead {
            step: "load".to_string(),
            entry: "Marker",
        };
        assert_eq!(
            err.to_string(),
            "step `load` reads `Marker`, but no upstream step (nor the pipeline input) writes it"
        );
    }

    #[test]
    fn display_formats_empty_branch() {
        let err = BuildError::EmptyBranch {
            step: "route".to_string(),
        };
        assert_eq!(err.to_string(), "branch `route` has no arms");
    }

    #[test]
    fn implements_std_error_trait_with_none_source() {
        let err = BuildError::DuplicateName {
            name: "load".to_string(),
        };
        let as_dyn: &dyn Error = &err;
        assert!(as_dyn.source().is_none());
    }

    #[test]
    fn display_formats_step_variant() {
        let err = PipelineError::Step {
            step: "load".to_string(),
            source: StepError::new("boom"),
        };
        assert_eq!(err.to_string(), "step `load` failed: boom");
    }

    #[test]
    fn display_formats_access_violation_variant_for_read() {
        let err = PipelineError::AccessViolation(AccessViolation {
            step: "load".to_string(),
            entry: "Marker",
            kind: AccessKind::Read,
        });
        assert_eq!(
            err.to_string(),
            "step `load` read `Marker` without declaring it"
        );
    }

    #[test]
    fn display_formats_access_violation_variant_for_write() {
        let err = PipelineError::AccessViolation(AccessViolation {
            step: "load".to_string(),
            entry: "Marker",
            kind: AccessKind::Write,
        });
        assert_eq!(
            err.to_string(),
            "step `load` wrote `Marker` without declaring it"
        );
    }

    #[test]
    fn display_formats_exhausted_variant() {
        let err = PipelineError::Exhausted;
        assert_eq!(
            err.to_string(),
            "pipeline exhausted: no step produced an outcome"
        );
    }

    #[test]
    fn display_formats_no_matching_branch_variant() {
        let err = PipelineError::NoMatchingBranch {
            step: "route".to_string(),
        };
        assert_eq!(err.to_string(), "step `route` had no matching branch arm");
    }

    #[test]
    fn source_returns_some_for_step_variant() {
        let err = PipelineError::Step {
            step: "load".to_string(),
            source: StepError::new("boom"),
        };
        let source = err.source().expect("source should be present");
        assert_eq!(source.to_string(), "boom");
    }

    #[test]
    fn source_returns_none_for_access_violation_variant() {
        let err = PipelineError::AccessViolation(AccessViolation {
            step: "load".to_string(),
            entry: "Marker",
            kind: AccessKind::Read,
        });
        assert!(err.source().is_none());
    }

    #[test]
    fn source_returns_none_for_exhausted_variant() {
        let err = PipelineError::Exhausted;
        assert!(err.source().is_none());
    }

    struct Input(i32);
    struct Marker(i32);

    enum Action {
        Continue,
        Done(i32),
        Fail(&'static str),
        WriteMarker(i32),
        WriteMarkerThenFail(i32, &'static str),
        ReadMarkerAsDone,
        ReadInputAsDone,
    }

    struct ScriptedStep {
        name: &'static str,
        access: AccessSpec,
        action: Action,
    }

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

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

        async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
            match &self.action {
                Action::Continue => Ok(Flow::Continue),
                Action::Done(v) => Ok(Flow::Done(*v)),
                Action::Fail(msg) => Err(StepError::new(*msg)),
                Action::WriteMarker(v) => {
                    ctx.insert(Marker(*v));
                    Ok(Flow::Continue)
                }
                Action::WriteMarkerThenFail(v, msg) => {
                    ctx.insert(Marker(*v));
                    Err(StepError::new(*msg))
                }
                Action::ReadMarkerAsDone => {
                    let doubled = ctx.get::<Marker>().map(|m| m.0 * 2).unwrap_or(-1);
                    Ok(Flow::Done(doubled))
                }
                Action::ReadInputAsDone => {
                    let v = ctx.get::<Input>().map(|i| i.0).unwrap_or(-1);
                    Ok(Flow::Done(v))
                }
            }
        }
    }

    struct CountingStep {
        access_calls: Arc<AtomicUsize>,
        name_calls: Arc<AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl Step<i32> for CountingStep {
        fn name(&self) -> &str {
            self.name_calls.fetch_add(1, Ordering::SeqCst);
            "counting"
        }

        fn access(&self) -> AccessSpec {
            self.access_calls.fetch_add(1, Ordering::SeqCst);
            AccessSpec::new()
        }

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

    fn step(name: &'static str, access: AccessSpec) -> ScriptedStep {
        ScriptedStep {
            name,
            access,
            action: Action::Continue,
        }
    }

    fn scripted(name: &'static str, access: AccessSpec, action: Action) -> ScriptedStep {
        ScriptedStep {
            name,
            access,
            action,
        }
    }

    #[test]
    fn build_preserves_step_call_order_when_no_pending_insertions() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .step(step("b", AccessSpec::new()))
            .step(step("c", AccessSpec::new()))
            .build()
            .unwrap();
        assert_eq!(pipeline.step_names(), vec!["a", "b", "c"]);
    }

    #[test]
    fn insert_before_places_step_immediately_before_anchor() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .step(step("b", AccessSpec::new()))
            .insert_before("b", step("x", AccessSpec::new()))
            .build()
            .unwrap();
        assert_eq!(pipeline.step_names(), vec!["a", "x", "b"]);
    }

    #[test]
    fn insert_after_places_step_immediately_after_anchor() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .step(step("b", AccessSpec::new()))
            .insert_after("a", step("x", AccessSpec::new()))
            .build()
            .unwrap();
        assert_eq!(pipeline.step_names(), vec!["a", "x", "b"]);
    }

    #[test]
    fn repeated_insert_before_on_the_same_anchor_preserves_registration_order() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .insert_before("a", step("x", AccessSpec::new()))
            .insert_before("a", step("y", AccessSpec::new()))
            .build()
            .unwrap();
        assert_eq!(pipeline.step_names(), vec!["x", "y", "a"]);
    }

    #[test]
    fn repeated_insert_after_on_the_same_anchor_preserves_registration_order() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .insert_after("a", step("x", AccessSpec::new()))
            .insert_after("a", step("y", AccessSpec::new()))
            .build()
            .unwrap();
        assert_eq!(pipeline.step_names(), vec!["a", "x", "y"]);
    }

    #[test]
    fn pending_insert_can_anchor_onto_a_previously_resolved_pending_step() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .insert_after("a", step("b", AccessSpec::new()))
            .insert_before("b", step("c", AccessSpec::new()))
            .build()
            .unwrap();
        assert_eq!(pipeline.step_names(), vec!["a", "c", "b"]);
    }

    #[test]
    fn pending_insert_resolution_does_not_depend_on_registration_order() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .insert_before("b", step("c", AccessSpec::new()))
            .insert_after("a", step("b", AccessSpec::new()))
            .build()
            .unwrap();
        assert_eq!(pipeline.step_names(), vec!["a", "c", "b"]);
    }

    #[test]
    fn builder_creates_pipeline_with_zero_steps_when_none_added() {
        let pipeline = Pipeline::<Input, i32>::builder().build().unwrap();
        assert!(pipeline.step_names().is_empty());
    }

    #[test]
    fn build_returns_anchor_not_found_when_insert_before_anchor_missing() {
        let result = Pipeline::<Input, i32>::builder()
            .insert_before("missing", step("x", AccessSpec::new()))
            .build();
        assert!(
            matches!(result, Err(BuildError::AnchorNotFound { anchor }) if anchor == "missing")
        );
    }

    #[test]
    fn build_returns_anchor_not_found_when_insert_after_anchor_missing() {
        let result = Pipeline::<Input, i32>::builder()
            .insert_after("missing", step("x", AccessSpec::new()))
            .build();
        assert!(
            matches!(result, Err(BuildError::AnchorNotFound { anchor }) if anchor == "missing")
        );
    }

    #[test]
    fn build_returns_duplicate_name_when_two_added_steps_share_a_name() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .step(step("a", AccessSpec::new()))
            .build();
        assert!(matches!(result, Err(BuildError::DuplicateName { name }) if name == "a"));
    }

    #[test]
    fn build_returns_duplicate_name_when_a_pending_insert_introduces_a_duplicate() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .step(step("b", AccessSpec::new()))
            .insert_after("a", step("b", AccessSpec::new()))
            .build();
        assert!(matches!(result, Err(BuildError::DuplicateName { name }) if name == "b"));
    }

    #[test]
    fn build_succeeds_when_step_reads_the_pipeline_input_type() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new().reads::<Input>()))
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn build_succeeds_when_a_read_is_satisfied_by_an_earlier_steps_write() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new().writes::<Marker>()))
            .step(step("b", AccessSpec::new().reads::<Marker>()))
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn build_succeeds_when_step_declares_no_access_requirements() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new()))
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn build_returns_unsatisfied_read_when_nothing_writes_the_entry() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new().reads::<Marker>()))
            .build();
        assert!(matches!(
            result,
            Err(BuildError::UnsatisfiedRead { step, .. }) if step == "a"
        ));
    }

    #[test]
    fn build_returns_unsatisfied_read_when_a_step_consumes_the_entry_before_a_later_reader() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new().writes::<Marker>()))
            .step(step("b", AccessSpec::new().consumes::<Marker>()))
            .step(step("c", AccessSpec::new().reads::<Marker>()))
            .build();
        assert!(matches!(
            result,
            Err(BuildError::UnsatisfiedRead { step, .. }) if step == "c"
        ));
    }

    #[test]
    fn build_succeeds_when_a_later_step_rewrites_a_consumed_entry() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new().writes::<Marker>()))
            .step(step("b", AccessSpec::new().consumes::<Marker>()))
            .step(step("c", AccessSpec::new().writes::<Marker>()))
            .step(step("d", AccessSpec::new().reads::<Marker>()))
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn build_succeeds_when_reads_writes_is_used_for_in_place_mutation() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new().writes::<Marker>()))
            .step(step("b", AccessSpec::new().reads_writes::<Marker>()))
            .step(step("c", AccessSpec::new().reads::<Marker>()))
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn build_reports_deterministic_entry_when_step_has_multiple_unsatisfied_reads() {
        // Marker and a second unwritten type both go unsatisfied; the
        // reported entry must consistently be the one that sorts first by
        // type name, regardless of HashMap iteration order.
        struct OtherMarker;
        let access = AccessSpec::new().reads::<Marker>().reads::<OtherMarker>();
        let expected = [
            std::any::type_name::<Marker>(),
            std::any::type_name::<OtherMarker>(),
        ]
        .into_iter()
        .min()
        .unwrap();
        for _ in 0..20 {
            let result = Pipeline::<Input, i32>::builder()
                .step(step("a", access.clone()))
                .build();
            assert!(matches!(
                result,
                Err(BuildError::UnsatisfiedRead { entry, .. }) if entry == expected
            ));
        }
    }

    #[test]
    fn build_returns_unsatisfied_read_when_only_a_later_step_writes_the_entry() {
        let result = Pipeline::<Input, i32>::builder()
            .step(step("a", AccessSpec::new().reads::<Marker>()))
            .step(step("b", AccessSpec::new().writes::<Marker>()))
            .build();
        assert!(matches!(
            result,
            Err(BuildError::UnsatisfiedRead { step, .. }) if step == "a"
        ));
    }

    #[test]
    fn run_returns_done_value_from_a_single_step() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted("a", AccessSpec::new(), Action::Done(42)))
            .build()
            .unwrap();
        let result = block_on(pipeline.run(Input(0)));
        assert!(matches!(result, Ok(42)));
    }

    #[test]
    fn run_continues_to_next_step_when_flow_is_continue() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted("a", AccessSpec::new(), Action::Continue))
            .step(scripted("b", AccessSpec::new(), Action::Done(7)))
            .build()
            .unwrap();
        let result = block_on(pipeline.run(Input(0)));
        assert!(matches!(result, Ok(7)));
    }

    #[test]
    fn run_provides_pipeline_input_via_context() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted(
                "a",
                AccessSpec::new().reads::<Input>(),
                Action::ReadInputAsDone,
            ))
            .build()
            .unwrap();
        let result = block_on(pipeline.run(Input(9)));
        assert!(matches!(result, Ok(9)));
    }

    #[test]
    fn run_threads_a_value_written_by_an_earlier_step_to_a_later_step() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted(
                "a",
                AccessSpec::new().writes::<Marker>(),
                Action::WriteMarker(5),
            ))
            .step(scripted(
                "b",
                AccessSpec::new().reads::<Marker>(),
                Action::ReadMarkerAsDone,
            ))
            .build()
            .unwrap();
        let result = block_on(pipeline.run(Input(0)));
        assert!(matches!(result, Ok(10)));
    }

    #[test]
    fn run_returns_exhausted_for_pipeline_with_zero_steps() {
        let pipeline = Pipeline::<Input, i32>::builder().build().unwrap();
        let result = block_on(pipeline.run(Input(0)));
        assert!(matches!(result, Err(PipelineError::Exhausted)));
    }

    #[test]
    fn run_returns_step_error_when_a_step_returns_err() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted("a", AccessSpec::new(), Action::Fail("boom")))
            .build()
            .unwrap();
        match block_on(pipeline.run(Input(0))) {
            Err(PipelineError::Step { step, source }) => {
                assert_eq!(step, "a");
                assert_eq!(source.to_string(), "boom");
            }
            other => panic!("expected Step error, got {other:?}"),
        }
    }

    #[test]
    fn run_returns_access_violation_when_step_reads_undeclared_entry() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted("a", AccessSpec::new(), Action::ReadMarkerAsDone))
            .build()
            .unwrap();
        match block_on(pipeline.run(Input(0))) {
            Err(PipelineError::AccessViolation(AccessViolation { step, kind, .. })) => {
                assert_eq!(step, "a");
                assert_eq!(kind, AccessKind::Read);
            }
            other => panic!("expected AccessViolation, got {other:?}"),
        }
    }

    #[test]
    fn run_returns_access_violation_when_step_writes_undeclared_entry() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted("a", AccessSpec::new(), Action::WriteMarker(1)))
            .build()
            .unwrap();
        match block_on(pipeline.run(Input(0))) {
            Err(PipelineError::AccessViolation(AccessViolation { step, kind, .. })) => {
                assert_eq!(step, "a");
                assert_eq!(kind, AccessKind::Write);
            }
            other => panic!("expected AccessViolation, got {other:?}"),
        }
    }

    #[test]
    fn run_returns_access_violation_instead_of_step_error_when_both_occur() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted(
                "a",
                AccessSpec::new(),
                Action::WriteMarkerThenFail(1, "boom"),
            ))
            .build()
            .unwrap();
        match block_on(pipeline.run(Input(0))) {
            Err(PipelineError::AccessViolation(AccessViolation { step, kind, .. })) => {
                assert_eq!(step, "a");
                assert_eq!(kind, AccessKind::Write);
            }
            other => panic!("expected AccessViolation, got {other:?}"),
        }
    }

    #[test]
    fn run_never_calls_access_or_name_again_after_build_cached_them() {
        let access_calls = Arc::new(AtomicUsize::new(0));
        let name_calls = Arc::new(AtomicUsize::new(0));
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(CountingStep {
                access_calls: access_calls.clone(),
                name_calls: name_calls.clone(),
            })
            .build()
            .unwrap();
        let access_calls_after_build = access_calls.load(Ordering::SeqCst);
        let name_calls_after_build = name_calls.load(Ordering::SeqCst);
        assert!(access_calls_after_build >= 1);
        assert!(name_calls_after_build >= 1);

        block_on(pipeline.run(Input(0))).unwrap();
        block_on(pipeline.run(Input(0))).unwrap();

        assert_eq!(
            access_calls.load(Ordering::SeqCst),
            access_calls_after_build
        );
        assert_eq!(name_calls.load(Ordering::SeqCst), name_calls_after_build);
    }

    #[test]
    fn run_returns_exhausted_when_every_step_returns_continue() {
        let pipeline = Pipeline::<Input, i32>::builder()
            .step(scripted("a", AccessSpec::new(), Action::Continue))
            .step(scripted("b", AccessSpec::new(), Action::Continue))
            .build()
            .unwrap();
        let result = block_on(pipeline.run(Input(0)));
        assert!(matches!(result, Err(PipelineError::Exhausted)));
    }

    // ---- run_steps: the shared loop behind Pipeline::run and Branch's arm
    // dispatch. Unlike Pipeline::run, exhausting every step as Continue is
    // not an error here — see run_steps's doc comment for why.

    fn compiled(steps: Vec<ScriptedStep>) -> Vec<CompiledStep<i32>> {
        steps
            .into_iter()
            .map(|s| {
                let name = s.name().to_string();
                let access = s.access();
                CompiledStep {
                    name,
                    access,
                    step: Box::new(s),
                }
            })
            .collect()
    }

    #[test]
    fn run_steps_returns_continue_when_every_step_continues() {
        let steps = compiled(vec![
            scripted("a", AccessSpec::new(), Action::Continue),
            scripted("b", AccessSpec::new(), Action::Continue),
        ]);
        let mut ctx = Context::new();
        let result = block_on(run_steps(&steps, &mut ctx));
        assert!(matches!(result, Ok(Flow::Continue)));
    }

    #[test]
    fn run_steps_propagates_done_and_stops_running_further_steps() {
        let steps = compiled(vec![
            scripted("a", AccessSpec::new(), Action::Continue),
            scripted("b", AccessSpec::new(), Action::Done(9)),
            scripted("c", AccessSpec::new(), Action::Done(-1)),
        ]);
        let mut ctx = Context::new();
        let result = block_on(run_steps(&steps, &mut ctx));
        assert!(matches!(result, Ok(Flow::Done(9))));
    }

    #[test]
    fn run_steps_propagates_err() {
        let steps = compiled(vec![scripted("a", AccessSpec::new(), Action::Fail("boom"))]);
        let mut ctx = Context::new();
        match block_on(run_steps(&steps, &mut ctx)) {
            Err(PipelineError::Step { step, source }) => {
                assert_eq!(step, "a");
                assert_eq!(source.to_string(), "boom");
            }
            Ok(_) => panic!("expected Step error, got Ok"),
            Err(other) => panic!("expected Step error, got {other}"),
        }
    }
}