camel-processor 0.21.0

Message processors for rust-camel
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
//! ## Stop semantics (ADR-0025)
//!
//! This segment implements `OutcomePipeline` and propagates `PipelineOutcome::Stopped(ex)` with the exchange state intact (including mutations made inside the segment body before Stop fired). See ADR-0025 §3 (stopped-exchange-state-preservation invariant).

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use tokio::task::JoinSet;

use camel_api::{
    AggregationStrategy, Body, CamelError, Exchange, OutcomeSegment, PipelineOutcome,
    SplitExpression, Value,
};

// ── aggregate_completed (SplitSegment helper) ─────────────────────────

/// Aggregate completed fragment outputs into a single Exchange.
///
/// Unlike `aggregate` (which works on `Vec<Result<Exchange, CamelError>>`),
/// this operates on `Vec<Exchange>` where all entries are `Completed` outcomes.
pub(crate) fn aggregate_completed(
    completed: Vec<Exchange>,
    original: Exchange,
    strategy: AggregationStrategy,
) -> Exchange {
    match strategy {
        AggregationStrategy::LastWins => completed.into_iter().last().unwrap_or(original),
        AggregationStrategy::CollectAll => {
            let mut bodies = Vec::new();
            for ex in &completed {
                let value = match &ex.input.body {
                    Body::Text(s) => Value::String(s.clone()),
                    Body::Json(v) => v.clone(),
                    Body::Xml(s) => Value::String(s.clone()),
                    Body::Bytes(b) => Value::String(String::from_utf8_lossy(b).into_owned()),
                    Body::Empty => Value::Null,
                    Body::Stream(s) => serde_json::json!({
                        "_stream": {
                            "origin": s.metadata.origin,
                            "placeholder": true,
                            "hint": "Materialize exchange body with .into_bytes() before aggregation if content needed"
                        }
                    }),
                };
                bodies.push(value);
            }
            let mut out = original;
            out.input.body = Body::Json(Value::Array(bodies));
            out
        }
        AggregationStrategy::Original => original,
        AggregationStrategy::Custom(fold_fn) => {
            let mut iter = completed.into_iter();
            let first = iter.next().unwrap_or(original);
            iter.fold(first, |acc, next| fold_fn(acc, next))
        }
    }
}

// ── SplitSegment (ADR-0025 OutcomePipeline) ────────────────────────────

/// Outcome-aware structural EIP segment for the Split pattern.
///
/// Splits an incoming exchange into fragments, processes each fragment through
/// `body`, and aggregates the results. Supports sequential and parallel modes.
///
/// In sequential mode, fragments are processed in order. A `Stopped` or `Failed`
/// outcome from any fragment halts processing immediately and propagates.
///
/// In parallel mode, all fragments are spawned as tokio tasks. The first
/// `Stopped` outcome (lowest fragment index wins via CAS) propagates as the
/// outer `Stopped`. In-flight tasks run to completion (spec §5.6: no abrupt
/// abort — child sub-pipelines may have HTTP/SQL side effects). Tasks that
/// have not started yet are short-circuited via a pre-start gate.
///
/// Unlike `SplitterService` (which operates at the Tower layer and cannot
/// preserve `Stopped(ex)` with mutations), `SplitSegment` operates at the
/// `PipelineOutcome` layer and preserves the exchange including all mutations
/// at the Stop point.
pub struct SplitSegment {
    /// Splits an exchange into fragment exchanges.
    pub splitter: SplitExpression,
    /// The sub-pipeline executed for each fragment.
    pub body: OutcomeSegment,
    /// Whether to process fragments in parallel.
    pub parallel: bool,
    /// Maximum number of concurrent fragments in parallel mode (None = unlimited).
    pub parallel_limit: Option<usize>,
    /// Whether to stop processing on the first exception.
    ///
    /// When `true`, a `Failed` outcome from any fragment halts processing
    /// immediately. When `false`, the error is collected and processing
    /// continues; the last-seen error is propagated (last-wins, matching legacy multicast.rs::process_parallel)
    /// is propagated after all fragments complete.
    ///
    /// `Stopped` outcomes always propagate immediately regardless of this
    /// flag (per ADR-0025 §7 — Stop is successful control flow).
    pub stop_on_exception: bool,
    /// Strategy for aggregating fragment results.
    pub aggregation: AggregationStrategy,
}

impl Clone for SplitSegment {
    fn clone(&self) -> Self {
        Self {
            splitter: Arc::clone(&self.splitter),
            body: self.body.clone(),
            parallel: self.parallel,
            parallel_limit: self.parallel_limit,
            stop_on_exception: self.stop_on_exception,
            aggregation: self.aggregation.clone(),
        }
    }
}

impl camel_api::OutcomePipeline for SplitSegment {
    fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
        Box::new(self.clone())
    }

    fn run<'a>(
        &'a mut self,
        exchange: camel_api::Exchange,
    ) -> Pin<Box<dyn Future<Output = camel_api::PipelineOutcome> + Send + 'a>> {
        let splitter = Arc::clone(&self.splitter);
        let aggregation = self.aggregation.clone();
        let parallel = self.parallel;
        let parallel_limit = self.parallel_limit;
        let stop_on_exception = self.stop_on_exception;
        let body = &mut self.body;

        Box::pin(async move {
            let original = exchange;
            let fragments = splitter(&original);

            if fragments.is_empty() {
                return PipelineOutcome::Completed(original);
            }

            if parallel {
                parallel_split(
                    fragments,
                    original,
                    body,
                    &aggregation,
                    parallel_limit,
                    stop_on_exception,
                )
                .await
            } else {
                sequential_split(fragments, original, body, &aggregation, stop_on_exception).await
            }
        })
    }
}

// ── Sequential split ────────────────────────────────────────────────────

async fn sequential_split(
    fragments: Vec<Exchange>,
    original: Exchange,
    body: &mut OutcomeSegment,
    aggregation: &AggregationStrategy,
    stop_on_exception: bool,
) -> PipelineOutcome {
    let mut outputs = Vec::new();
    let mut last_error: Option<CamelError> = None;
    for frag in fragments {
        match body.run(frag).await {
            PipelineOutcome::Completed(ex) => outputs.push(ex),
            PipelineOutcome::Stopped(ex) => return PipelineOutcome::Stopped(ex),
            PipelineOutcome::Failed(err) => {
                if stop_on_exception {
                    return PipelineOutcome::Failed(err);
                }
                // stop_on_exception=false: collect the error and continue.
                last_error = Some(err);
            }
        }
    }
    if let Some(err) = last_error {
        return PipelineOutcome::Failed(err);
    }
    PipelineOutcome::Completed(aggregate_completed(outputs, original, aggregation.clone()))
}

// ── Parallel split ──────────────────────────────────────────────────────

/// Parallel split with lowest-index-wins CAS semantics.
///
/// See spec §5.2.2 line 497 for the CAS guarantee and §5.6 line 544 for the
/// "no abrupt abort" in-flight task policy (pre-start gate + run-to-completion).
async fn parallel_split(
    fragments: Vec<Exchange>,
    original: Exchange,
    body: &mut OutcomeSegment,
    aggregation: &AggregationStrategy,
    parallel_limit: Option<usize>,
    stop_on_exception: bool,
) -> PipelineOutcome {
    use tokio::sync::Semaphore;

    let stopped_seen = Arc::new(AtomicBool::new(false));
    let stopped_idx = Arc::new(AtomicUsize::new(usize::MAX));
    let aggregation = aggregation.clone();
    let semaphore = parallel_limit
        .filter(|&limit| limit > 0)
        .map(|limit| Arc::new(Semaphore::new(limit)));

    let mut set: JoinSet<(usize, Option<PipelineOutcome>)> = JoinSet::new();

    for (idx, frag) in fragments.into_iter().enumerate() {
        let mut body = body.clone();
        let stopped_seen = Arc::clone(&stopped_seen);
        let stopped_idx = Arc::clone(&stopped_idx);
        let sem = semaphore.clone();
        set.spawn(async move {
            // Pre-start gate: a lower-index branch already stopped.
            // This is the ONLY cancellation check — once a body starts
            // running, it runs to completion (spec §5.6: "in-flight futures
            // MUST NOT be abruptly aborted").
            if stopped_seen.load(Ordering::SeqCst) {
                return (idx, None);
            }
            // Acquire semaphore permit if parallel_limit is set.
            let _permit: Option<tokio::sync::OwnedSemaphorePermit> = match &sem {
                Some(s) => match std::sync::Arc::clone(s).acquire_owned().await {
                    Ok(p) => Some(p),
                    Err(_) => {
                        return (
                            idx,
                            Some(PipelineOutcome::Failed(CamelError::ProcessorError(
                                "semaphore closed".into(),
                            ))),
                        );
                    }
                },
                None => None,
            };
            // Re-check pre-start gate after permit acquisition
            // (another branch may have stopped while we were waiting).
            if stopped_seen.load(Ordering::SeqCst) {
                return (idx, None);
            }
            let outcome = body.run(frag).await;
            if let PipelineOutcome::Stopped(_) = &outcome {
                // Lower-the-value CAS: ensures lowest-branch-index wins
                // even under simultaneous Stop (spec §5.2.2 line 497).
                // Loop until our idx is recorded or a lower idx has already
                // claimed it.
                loop {
                    let cur = stopped_idx.load(Ordering::SeqCst);
                    if idx >= cur {
                        break; // a lower index already won
                    }
                    match stopped_idx.compare_exchange_weak(
                        cur,
                        idx,
                        Ordering::SeqCst,
                        Ordering::SeqCst,
                    ) {
                        Ok(_) => break,
                        Err(actual) => {
                            // CAS failed — `actual` is the new cur; loop and
                            // retry with updated value.
                            if actual <= idx {
                                break;
                            }
                        }
                    }
                }
                stopped_seen.store(true, Ordering::SeqCst);
            }
            (idx, Some(outcome))
        });
    }

    // Wait for ALL in-flight branches to finish (spec §5.6: no abrupt
    // abort). Post-stop outputs are discarded at aggregation, but the
    // branches DO complete.
    let mut results: Vec<(usize, PipelineOutcome)> = Vec::new();
    while let Some(res) = set.join_next().await {
        if let Ok((idx, Some(o))) = res {
            results.push((idx, o));
        }
    }

    // Deterministic lowest-branch-index wins (spec §5.2.2 line 497).
    if stopped_seen.load(Ordering::SeqCst) {
        let winning_idx = stopped_idx.load(Ordering::SeqCst);
        if winning_idx == usize::MAX {
            tracing::warn!(
                target: "camel.phase4.split",
                "stopped_seen=true but stopped_idx=usize::MAX — race condition; falling back to pre-split exchange"
            );
            return PipelineOutcome::Stopped(original);
        }
        let stopped_ex = results
            .iter()
            .find(|(idx, _)| *idx == winning_idx)
            .and_then(|(_, o)| match o {
                PipelineOutcome::Stopped(ex) => Some(ex.clone()),
                _ => None,
            });
        if let Some(ex) = stopped_ex {
            return PipelineOutcome::Stopped(ex);
        }
        tracing::warn!(
            target: "camel.phase4.split",
            winning_idx = winning_idx,
            "winning_idx not found in results — falling back to pre-split exchange"
        );
        return PipelineOutcome::Stopped(original);
    }

    // No Stop — check for Failed.
    // stop_on_exception=true: propagate first Failed (lowest branch index).
    // stop_on_exception=false: collect last error (last-wins) and propagate at end.
    results.sort_by_key(|(idx, _)| *idx);
    if stop_on_exception {
        let mut first_failed: Option<(usize, CamelError)> = None;
        for (idx, o) in &results {
            if let PipelineOutcome::Failed(err) = o
                && first_failed
                    .as_ref()
                    .map(|(i, _)| *i > *idx)
                    .unwrap_or(true)
            {
                first_failed = Some((*idx, err.clone()));
            }
        }
        if let Some((_, err)) = first_failed {
            return PipelineOutcome::Failed(err);
        }
    } else {
        // Collect last error (last-wins, matching MulticastSegment semantics).
        let mut last_error: Option<CamelError> = None;
        for (_, o) in &results {
            if let PipelineOutcome::Failed(err) = o {
                last_error = Some(err.clone());
            }
        }
        if let Some(err) = last_error {
            return PipelineOutcome::Failed(err);
        }
    }

    // All Completed — aggregate.
    let completed: Vec<Exchange> = results
        .into_iter()
        .filter_map(|(_, o)| match o {
            PipelineOutcome::Completed(ex) => Some(ex),
            _ => None,
        })
        .collect();
    PipelineOutcome::Completed(aggregate_completed(completed, original, aggregation))
}

// ── Tests ──────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use camel_api::Message;

    // ── Test helpers ───────────────────────────────────────────────────

    /// Helper: OutcomePipeline body that always returns `Completed(exchange)`.
    #[derive(Clone)]
    struct CompletedBody;
    impl camel_api::OutcomePipeline for CompletedBody {
        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
            Box::new(CompletedBody)
        }
        fn run<'a>(
            &'a mut self,
            exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            Box::pin(async move { PipelineOutcome::Completed(exchange) })
        }
    }

    /// Helper: OutcomePipeline body that always returns `Stopped(exchange)`.
    #[derive(Clone)]
    struct StopBody;
    impl camel_api::OutcomePipeline for StopBody {
        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
            Box::new(StopBody)
        }
        fn run<'a>(
            &'a mut self,
            exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            Box::pin(async move { PipelineOutcome::Stopped(exchange) })
        }
    }

    /// Helper: OutcomePipeline body that stops on the nth invocation (0-indexed).
    #[derive(Clone)]
    struct StopOnNthBody {
        counter: Arc<AtomicUsize>,
        stop_at: usize,
    }
    impl camel_api::OutcomePipeline for StopOnNthBody {
        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
            Box::new(self.clone())
        }
        fn run<'a>(
            &'a mut self,
            exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            let count = self.counter.fetch_add(1, Ordering::SeqCst);
            let stop_at = self.stop_at;
            Box::pin(async move {
                if count >= stop_at {
                    PipelineOutcome::Stopped(exchange)
                } else {
                    PipelineOutcome::Completed(exchange)
                }
            })
        }
    }

    /// Helper: OutcomePipeline body that mutates the exchange body then stops.
    #[derive(Clone)]
    struct MutateAndStopBody;
    impl camel_api::OutcomePipeline for MutateAndStopBody {
        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
            Box::new(MutateAndStopBody)
        }
        fn run<'a>(
            &'a mut self,
            mut exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            Box::pin(async move {
                exchange.input.body = Body::Text("mutated-by-body".to_string());
                PipelineOutcome::Stopped(exchange)
            })
        }
    }

    // ── Test 1: Sequential split — Stop halts remaining fragments ──

    #[tokio::test]
    async fn stop_inside_split_sequential_halts_remaining_fragments() {
        let invocations = Arc::new(AtomicUsize::new(0));
        let body = StopOnNthBody {
            counter: Arc::clone(&invocations),
            stop_at: 1, // stop on the 2nd fragment (index 1)
        };

        let mut seg = SplitSegment {
            splitter: camel_api::split_body_lines(),
            body: OutcomeSegment::new(Box::new(body)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("a\nb\nc"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        assert!(matches!(result, PipelineOutcome::Stopped(_)));
        // Fragments 0 (pass) + 1 (stop) = 2 invocations; fragment 2 never runs.
        assert_eq!(invocations.load(Ordering::SeqCst), 2);
    }

    // ── Test 2: Sequential split — Stop preserves exchange mutations ──

    #[tokio::test]
    async fn stop_inside_split_sequential_preserves_exchange_mutations() {
        let mut seg = SplitSegment {
            splitter: camel_api::split_body_lines(),
            body: OutcomeSegment::new(Box::new(MutateAndStopBody)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("hello"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        match result {
            PipelineOutcome::Stopped(ex) => {
                assert_eq!(
                    ex.input.body.as_text(),
                    Some("mutated-by-body"),
                    "Stopped exchange should carry body mutation"
                );
            }
            other => panic!("Expected Stopped, got {other:?}"),
        }
    }

    // ── Test 3: Parallel split — Stop cancels pending, waits in-flight ──
    //
    // NOTE: With JoinSet::spawn, all tasks are eagerly created. The
    // pre-start gate only stops fragments whose spawned closure hasn't
    // been polled yet. This test uses a tokio::sync::Barrier inside the
    // body to ensure ALL fragments pass the pre-start gate, then verifies
    // that in-flight (frag-1) completes even though Stop fires. The
    // "cancels pending" invariant (frag-2 not started) is best-effort;
    // the true invariant is: fragments that DO start MUST run to completion.

    #[tokio::test(flavor = "multi_thread")]
    async fn stop_inside_split_parallel_cancels_pending_and_waits_inflight() {
        use tokio::sync::Barrier;

        let barrier = Arc::new(Barrier::new(3));
        let fragment1_completed = Arc::new(AtomicBool::new(false));
        let fragment2_completed = Arc::new(AtomicBool::new(false));
        let frag1_ok = Arc::clone(&fragment1_completed);
        let frag2_ok = Arc::clone(&fragment2_completed);
        let bar = Arc::clone(&barrier);

        // Custom splitter producing 3 fragments.
        let splitter: SplitExpression = Arc::new(|ex: &Exchange| {
            (0..3)
                .map(|i| {
                    let mut frag = ex.clone();
                    frag.input.body = Body::Text(format!("frag-{i}"));
                    frag
                })
                .collect()
        });

        /// Body that uses a barrier to synchronize all fragments past the
        /// pre-start gate, then dispatches:
        ///   - frag-0: Stop
        ///   - frag-1: slow (100ms) Completed
        ///   - frag-2: fast Completed (asserts it started, proving no abort)
        struct BarrierDispatchBody {
            barrier: Arc<Barrier>,
            f1_completed: Arc<AtomicBool>,
            f2_completed: Arc<AtomicBool>,
        }
        impl Clone for BarrierDispatchBody {
            fn clone(&self) -> Self {
                Self {
                    barrier: Arc::clone(&self.barrier),
                    f1_completed: Arc::clone(&self.f1_completed),
                    f2_completed: Arc::clone(&self.f2_completed),
                }
            }
        }
        impl camel_api::OutcomePipeline for BarrierDispatchBody {
            fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
                Box::new(self.clone())
            }
            fn run<'a>(
                &'a mut self,
                exchange: Exchange,
            ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
                let bar = Arc::clone(&self.barrier);
                let f1c = Arc::clone(&self.f1_completed);
                let f2c = Arc::clone(&self.f2_completed);
                Box::pin(async move {
                    let body_text = exchange.input.body.as_text().unwrap_or("").to_string();

                    // All fragments synchronize AFTER passing the pre-start gate
                    // (the gate is checked before body.run()). This ensures all
                    // three fragments are in-flight when Stop fires.
                    bar.wait().await;

                    match body_text.as_str() {
                        "frag-0" => PipelineOutcome::Stopped(exchange),
                        "frag-1" => {
                            // Slow in-flight — fragment 0's Stop is recorded and
                            // propagates, but we still complete (spec §5.6).
                            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                            f1c.store(true, Ordering::SeqCst);
                            PipelineOutcome::Completed(exchange)
                        }
                        "frag-2" => {
                            f2c.store(true, Ordering::SeqCst);
                            PipelineOutcome::Completed(exchange)
                        }
                        _ => PipelineOutcome::Completed(exchange),
                    }
                })
            }
        }

        let body = BarrierDispatchBody {
            barrier: bar,
            f1_completed: frag1_ok,
            f2_completed: frag2_ok,
        };

        let mut seg = SplitSegment {
            splitter,
            body: OutcomeSegment::new(Box::new(body)),
            parallel: true,
            parallel_limit: None,
            stop_on_exception: true,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("test"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        assert!(
            matches!(result, PipelineOutcome::Stopped(_)),
            "Expected Stopped, got {result:?}"
        );
        // Fragment 1 was in-flight and completed (no abrupt abort per §5.6).
        assert!(
            fragment1_completed.load(Ordering::SeqCst),
            "fragment 1 should have completed despite Stop"
        );
        // Fragment 2 was also in-flight (barrier ensures all start) and completed.
        assert!(
            fragment2_completed.load(Ordering::SeqCst),
            "fragment 2 should have completed despite Stop"
        );
    }

    // ── Test 4: Parallel split — lowest stopped index wins ──

    #[tokio::test(flavor = "multi_thread")]
    async fn stop_inside_split_parallel_lowest_stopped_index_wins() {
        // Custom splitter producing 3 fragments with index-identifiable body.
        let splitter: SplitExpression = Arc::new(|ex: &Exchange| {
            (0..3)
                .map(|i| {
                    let mut frag = ex.clone();
                    frag.input.body = Body::Text(format!("from-fragment-{i}"));
                    frag
                })
                .collect()
        });

        // Body that stops for fragments 0 and 2; fragment 1 completes.
        struct DualStopBody;
        impl Clone for DualStopBody {
            fn clone(&self) -> Self {
                DualStopBody
            }
        }
        impl camel_api::OutcomePipeline for DualStopBody {
            fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
                Box::new(DualStopBody)
            }
            fn run<'a>(
                &'a mut self,
                exchange: Exchange,
            ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
                let is_frag0 = exchange
                    .input
                    .body
                    .as_text()
                    .map(|s| s == "from-fragment-0")
                    .unwrap_or(false);
                let is_frag2 = exchange
                    .input
                    .body
                    .as_text()
                    .map(|s| s == "from-fragment-2")
                    .unwrap_or(false);
                Box::pin(async move {
                    if is_frag0 {
                        return PipelineOutcome::Stopped(exchange);
                    }
                    if is_frag2 {
                        // Delay slightly to ensure fragment 0's Stop is recorded first
                        // in the CAS, then verify that lowest index wins.
                        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                        return PipelineOutcome::Stopped(exchange);
                    }
                    // frag-1: completed
                    PipelineOutcome::Completed(exchange)
                })
            }
        }

        let mut seg = SplitSegment {
            splitter,
            body: OutcomeSegment::new(Box::new(DualStopBody)),
            parallel: true,
            parallel_limit: None,
            stop_on_exception: true,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("test"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        match result {
            PipelineOutcome::Stopped(ex) => {
                assert_eq!(
                    ex.input.body.as_text(),
                    Some("from-fragment-0"),
                    "Lowest stopped index (0) should win, got body {:?}",
                    ex.input.body.as_text()
                );
            }
            other => panic!("Expected Stopped with fragment-0 body, got {other:?}"),
        }
    }

    // ── Test 5: parallel_limit enforcement ─────────────────────────────

    #[tokio::test(flavor = "multi_thread")]
    async fn split_parallel_limit_enforces_concurrency_cap() {
        let concurrent = Arc::new(AtomicUsize::new(0));
        let max_concurrent = Arc::new(AtomicUsize::new(0));

        // Split into 6 fragments. parallel_limit=2.
        let splitter: SplitExpression = Arc::new(|ex: &Exchange| {
            (0..6)
                .map(|i| {
                    let mut frag = ex.clone();
                    frag.input.body = Body::Text(format!("frag-{i}"));
                    frag
                })
                .collect()
        });

        let c = Arc::clone(&concurrent);
        let mc = Arc::clone(&max_concurrent);
        struct LimitedBody {
            concurrent: Arc<AtomicUsize>,
            max_concurrent: Arc<AtomicUsize>,
        }
        impl Clone for LimitedBody {
            fn clone(&self) -> Self {
                Self {
                    concurrent: Arc::clone(&self.concurrent),
                    max_concurrent: Arc::clone(&self.max_concurrent),
                }
            }
        }
        impl camel_api::OutcomePipeline for LimitedBody {
            fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
                Box::new(self.clone())
            }
            fn run<'a>(
                &'a mut self,
                exchange: Exchange,
            ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
                let c = Arc::clone(&self.concurrent);
                let mc = Arc::clone(&self.max_concurrent);
                Box::pin(async move {
                    let current = c.fetch_add(1, Ordering::SeqCst) + 1;
                    mc.fetch_max(current, Ordering::SeqCst);
                    tokio::task::yield_now().await;
                    c.fetch_sub(1, Ordering::SeqCst);
                    PipelineOutcome::Completed(exchange)
                })
            }
        }

        let mut seg = SplitSegment {
            splitter,
            body: OutcomeSegment::new(Box::new(LimitedBody {
                concurrent: c,
                max_concurrent: mc,
            })),
            parallel: true,
            parallel_limit: Some(2),
            stop_on_exception: true,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("test"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;
        assert!(
            matches!(result, PipelineOutcome::Completed(_)),
            "Expected Completed, got {result:?}"
        );

        let observed_max = max_concurrent.load(Ordering::SeqCst);
        assert!(
            observed_max <= 2,
            "parallel_limit=2 but max concurrency was {observed_max}"
        );
    }

    // ── Test 6: stop_on_exception=true (sequential) ────────────────────

    #[tokio::test]
    async fn split_sequential_stop_on_exception_true() {
        // 5 fragments, fail on 2nd (index 1). stop_on_exception=true → stops.
        fn make_fail_body(
            fail_at: usize,
            counter: Arc<AtomicUsize>,
        ) -> impl camel_api::OutcomePipeline + Clone {
            #[derive(Clone)]
            struct FailAtBody {
                fail_at: usize,
                counter: Arc<AtomicUsize>,
            }
            impl camel_api::OutcomePipeline for FailAtBody {
                fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
                    Box::new(self.clone())
                }
                fn run<'a>(
                    &'a mut self,
                    exchange: Exchange,
                ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
                    let count = self.counter.fetch_add(1, Ordering::SeqCst);
                    let fail_at = self.fail_at;
                    Box::pin(async move {
                        if count == fail_at {
                            PipelineOutcome::Failed(CamelError::ProcessorError(format!(
                                "fail at {count}"
                            )))
                        } else {
                            PipelineOutcome::Completed(exchange)
                        }
                    })
                }
            }
            FailAtBody { fail_at, counter }
        }

        let invocations = Arc::new(AtomicUsize::new(0));
        let body = make_fail_body(1, Arc::clone(&invocations));
        let mut seg = SplitSegment {
            splitter: camel_api::split_body_lines(),
            body: OutcomeSegment::new(Box::new(body)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("a\nb\nc\nd\ne"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        assert!(
            matches!(result, PipelineOutcome::Failed(_)),
            "stop_on_exception=true should propagate first failure"
        );
        // Only 2 fragments processed (index 0 passed, index 1 failed);
        // fragments 2-4 never run.
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            2,
            "should stop after 2 fragments (0 pass, 1 fail)"
        );
    }

    // ── Test 7: stop_on_exception=false (sequential) ───────────────────

    #[tokio::test]
    async fn split_sequential_stop_on_exception_false() {
        // 5 fragments, fail on 2nd (index 1). stop_on_exception=false → continues.
        fn make_fail_body(
            fail_at: usize,
            counter: Arc<AtomicUsize>,
        ) -> impl camel_api::OutcomePipeline + Clone {
            #[derive(Clone)]
            struct FailAtBody {
                fail_at: usize,
                counter: Arc<AtomicUsize>,
            }
            impl camel_api::OutcomePipeline for FailAtBody {
                fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
                    Box::new(self.clone())
                }
                fn run<'a>(
                    &'a mut self,
                    exchange: Exchange,
                ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
                    let count = self.counter.fetch_add(1, Ordering::SeqCst);
                    let fail_at = self.fail_at;
                    Box::pin(async move {
                        if count == fail_at {
                            PipelineOutcome::Failed(CamelError::ProcessorError(format!(
                                "fail at {count}"
                            )))
                        } else {
                            PipelineOutcome::Completed(exchange)
                        }
                    })
                }
            }
            FailAtBody { fail_at, counter }
        }

        let invocations = Arc::new(AtomicUsize::new(0));
        let body = make_fail_body(1, Arc::clone(&invocations));
        let mut seg = SplitSegment {
            splitter: camel_api::split_body_lines(),
            body: OutcomeSegment::new(Box::new(body)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: false,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("a\nb\nc\nd\ne"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        // With stop_on_exception=false, processing continues after failure;
        // last error is propagated.
        assert!(
            matches!(result, PipelineOutcome::Failed(_)),
            "stop_on_exception=false should still propagate error at end"
        );
        // All 5 fragments processed.
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            5,
            "all fragments should be processed when stop_on_exception=false"
        );
    }

    // ── Test 8: stop_on_exception=true (parallel) ──────────────────────

    #[tokio::test(flavor = "multi_thread")]
    async fn split_parallel_stop_on_exception_true() {
        let splitter: SplitExpression = Arc::new(|ex: &Exchange| {
            (0..5)
                .map(|i| {
                    let mut frag = ex.clone();
                    frag.input.body = Body::Text(format!("frag-{i}"));
                    frag
                })
                .collect()
        });

        // All fragments fail. stop_on_exception=true → first Failed propagated.
        let invocations = Arc::new(AtomicUsize::new(0));
        struct FailBody {
            counter: Arc<AtomicUsize>,
        }
        impl Clone for FailBody {
            fn clone(&self) -> Self {
                Self {
                    counter: Arc::clone(&self.counter),
                }
            }
        }
        impl camel_api::OutcomePipeline for FailBody {
            fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
                Box::new(self.clone())
            }
            fn run<'a>(
                &'a mut self,
                exchange: Exchange,
            ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
                let count = self.counter.fetch_add(1, Ordering::SeqCst);
                Box::pin(async move {
                    PipelineOutcome::Failed(CamelError::ProcessorError(format!("fail {count}")))
                })
            }
        }

        let mut seg = SplitSegment {
            splitter,
            body: OutcomeSegment::new(Box::new(FailBody {
                counter: Arc::clone(&invocations),
            })),
            parallel: true,
            parallel_limit: None,
            stop_on_exception: true,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("test"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        assert!(
            matches!(result, PipelineOutcome::Failed(_)),
            "stop_on_exception=true should propagate first failure"
        );
        // All 5 spawned (JoinSet), all completed.
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            5,
            "all fragments should be spawned"
        );
    }

    // ── Test 9: stop_on_exception=false (parallel) ─────────────────────

    #[tokio::test(flavor = "multi_thread")]
    async fn split_parallel_stop_on_exception_false() {
        let splitter: SplitExpression = Arc::new(|ex: &Exchange| {
            (0..5)
                .map(|i| {
                    let mut frag = ex.clone();
                    frag.input.body = Body::Text(format!("frag-{i}"));
                    frag
                })
                .collect()
        });

        // Fragment 0 passes, 1 fails, 2-4 pass.
        let invocations = Arc::new(AtomicUsize::new(0));
        struct MixedBody {
            counter: Arc<AtomicUsize>,
        }
        impl Clone for MixedBody {
            fn clone(&self) -> Self {
                Self {
                    counter: Arc::clone(&self.counter),
                }
            }
        }
        impl camel_api::OutcomePipeline for MixedBody {
            fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
                Box::new(self.clone())
            }
            fn run<'a>(
                &'a mut self,
                exchange: Exchange,
            ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
                let count = self.counter.fetch_add(1, Ordering::SeqCst);
                Box::pin(async move {
                    if count == 1 {
                        PipelineOutcome::Failed(CamelError::ProcessorError("fail 1".into()))
                    } else {
                        PipelineOutcome::Completed(exchange)
                    }
                })
            }
        }

        let mut seg = SplitSegment {
            splitter,
            body: OutcomeSegment::new(Box::new(MixedBody {
                counter: Arc::clone(&invocations),
            })),
            parallel: true,
            parallel_limit: None,
            stop_on_exception: false,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new("test"));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        // stop_on_exception=false → last error propagated at end.
        assert!(
            matches!(result, PipelineOutcome::Failed(_)),
            "stop_on_exception=false should propagate failure at end; got {result:?}"
        );
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            5,
            "all fragments should be spawned"
        );
    }
}