camel-processor 0.62.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
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
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
//! ## 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, SplitSource,
    Value,
};

use crate::splitter::{CAMEL_SPLIT_COMPLETE, CAMEL_SPLIT_INDEX, CAMEL_SPLIT_SIZE};

// ── 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::Stream(s) => serde_json::json!({
                        "_stream": {
                            "origin": s.metadata.origin,
                            "placeholder": true,
                            "hint": "Materialize exchange body with .into_bytes() before aggregation if content needed"
                        }
                    }),
                    // Empty and future variants contribute no extractable value.
                    _ => Value::Null,
                };
                bodies.push(value);
            }
            let mut out = original;
            out.input.body = Body::Json(Value::Array(bodies));
            out
        }
        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))
        }
        // Original and any future variant return the original exchange.
        _ => original,
    }
}

// ── 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 the removed Tower split wrapper (which could not 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: SplitSource,
    /// 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,
    /// Maximum number of fragments the eager split may materialize.
    ///
    /// Defaults to `camel_api::splitter::DEFAULT_MAX_FRAGMENTS`. A split whose
    /// materialized `len` exceeds this cap is rejected before metadata stamping
    /// and before any fragment is processed; `0` fails closed for any
    /// non-empty split.
    pub max_fragments: usize,
    /// Strategy for aggregating fragment results.
    pub aggregation: AggregationStrategy,
}

impl Clone for SplitSegment {
    fn clone(&self) -> Self {
        Self {
            splitter: self.splitter.clone(),
            body: self.body.clone(),
            parallel: self.parallel,
            parallel_limit: self.parallel_limit,
            stop_on_exception: self.stop_on_exception,
            max_fragments: self.max_fragments,
            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 = self.splitter.clone();
        let aggregation = self.aggregation.clone();
        let parallel = self.parallel;
        let parallel_limit = self.parallel_limit;
        let stop_on_exception = self.stop_on_exception;
        let max_fragments = self.max_fragments;
        let body = &mut self.body;

        Box::pin(async move {
            let original = exchange;
            // A typed error from the split expression fails loud as
            // `Failed`, carrying the original error untouched.
            let mut fragments = match splitter.split(&original).await {
                Ok(fragments) => fragments,
                Err(err) => return PipelineOutcome::Failed(err),
            };

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

            if fragments.len() > max_fragments {
                return PipelineOutcome::Failed(CamelError::ProcessorError(format!(
                    "Splitter produced {} fragments, exceeding max_fragments {}",
                    fragments.len(),
                    max_fragments
                )));
            }

            // Stamp split metadata on each fragment — exact parity with the
            // previous eager split path (removed with `SplitterService`), so
            // downstream consumers observe the same `CamelSplit*` properties
            // on either split path.
            let total = fragments.len();
            for (i, frag) in fragments.iter_mut().enumerate() {
                frag.set_property(CAMEL_SPLIT_INDEX, Value::from(i as u64));
                frag.set_property(CAMEL_SPLIT_SIZE, Value::from(total as u64));
                frag.set_property(CAMEL_SPLIT_COMPLETE, Value::Bool(i == total - 1));
            }

            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.branch_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)]
    #[allow(dead_code)]
    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)]
    #[allow(dead_code)]
    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::SplitSource::Sync(camel_api::split_body_lines()),
            body: OutcomeSegment::new(Box::new(body)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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::SplitSource::Sync(camel_api::split_body_lines()),
            body: OutcomeSegment::new(Box::new(MutateAndStopBody)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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 = SplitSource::Sync(Arc::new(|ex: &Exchange| {
            Ok((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,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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 = SplitSource::Sync(Arc::new(|ex: &Exchange| {
            Ok((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,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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 = SplitSource::Sync(Arc::new(|ex: &Exchange| {
            Ok((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,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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::SplitSource::Sync(camel_api::split_body_lines()),
            body: OutcomeSegment::new(Box::new(body)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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::SplitSource::Sync(camel_api::split_body_lines()),
            body: OutcomeSegment::new(Box::new(body)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: false,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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 = SplitSource::Sync(Arc::new(|ex: &Exchange| {
            Ok((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,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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 = SplitSource::Sync(Arc::new(|ex: &Exchange| {
            Ok((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,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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"
        );
    }

    // ── Test 10: Split expression error → Failed, body never runs ──────

    #[tokio::test]
    async fn test_split_segment_expression_error_is_failed() {
        /// Recording body: counts invocations, always completes.
        #[derive(Clone)]
        struct RecordingBody {
            counter: Arc<AtomicUsize>,
        }
        impl camel_api::OutcomePipeline for RecordingBody {
            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>> {
                self.counter.fetch_add(1, Ordering::SeqCst);
                Box::pin(async move { PipelineOutcome::Completed(exchange) })
            }
        }

        let invocations = Arc::new(AtomicUsize::new(0));
        let splitter = SplitSource::Sync(Arc::new(|_| {
            Err(CamelError::TypeConversionFailed(
                "declarative split requires a text or array value, got number; add an unmarshal step before split"
                    .to_string(),
            ))
        }));

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

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

        match result {
            PipelineOutcome::Failed(err) => {
                let msg = err.to_string();
                assert!(
                    msg.contains("declarative split"),
                    "carried error should mention 'declarative split': {msg}"
                );
            }
            other => panic!("Expected Failed, got {other:?}"),
        }
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "body segment must record zero invocations when the split expression errors"
        );
    }

    #[tokio::test]
    async fn split_segment_wrong_type_body_fails_loud() {
        // Splitting a Text body with body_json_array must fail with the typed
        // message, not silently pass the original body through.
        let invocations = Arc::new(AtomicUsize::new(0));

        #[derive(Clone)]
        struct RecordingBody {
            counter: Arc<AtomicUsize>,
        }
        impl camel_api::OutcomePipeline for RecordingBody {
            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>> {
                self.counter.fetch_add(1, Ordering::SeqCst);
                Box::pin(async move { PipelineOutcome::Completed(exchange) })
            }
        }

        let mut seg = SplitSegment {
            splitter: SplitSource::Sync(camel_api::split_body_json_array()),
            body: OutcomeSegment::new(Box::new(RecordingBody {
                counter: Arc::clone(&invocations),
            })),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            aggregation: AggregationStrategy::LastWins,
        };

        let ex = Exchange::new(Message::new(Body::Text("a,b".to_string())));
        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;

        match result {
            PipelineOutcome::Failed(err) => {
                let msg = err.to_string();
                for needle in [
                    "body_json_array",
                    "text",
                    "json (array)",
                    "add an unmarshal step before split",
                ] {
                    assert!(msg.contains(needle), "message '{msg}' missing '{needle}'");
                }
            }
            other => panic!("wrong body type must fail loud, got {other:?}"),
        }
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "body segment must record zero invocations when the split expression errors"
        );
    }

    #[tokio::test]
    async fn split_segment_async_error_propagates_before_fragments() {
        use camel_api::BoxValueFuture;

        let invocations = Arc::new(AtomicUsize::new(0));

        #[derive(Clone)]
        struct RecordingBody {
            counter: Arc<AtomicUsize>,
        }
        impl camel_api::OutcomePipeline for RecordingBody {
            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>> {
                self.counter.fetch_add(1, Ordering::SeqCst);
                Box::pin(async move { PipelineOutcome::Completed(exchange) })
            }
        }

        let splitter = SplitSource::Async(Arc::new(|_: &Exchange| {
            Box::pin(async { Err(CamelError::ProcessorError("split boom".into())) })
                as BoxValueFuture
        }));

        let mut seg = SplitSegment {
            splitter,
            body: OutcomeSegment::new(Box::new(RecordingBody {
                counter: Arc::clone(&invocations),
            })),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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::Failed(CamelError::ProcessorError(ref e)) if e.contains("split boom")),
            "an async split-expression failure must propagate; got {result:?}"
        );
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "no fragment may reach the sub-pipeline when the split expression fails"
        );
    }
    // ── Tests 11-13: fragment metadata stamping ────────────────────────

    /// Helper: OutcomePipeline body that captures the split metadata
    /// properties (index, size, complete) from each fragment exchange
    /// into a shared buffer.
    #[derive(Clone)]
    struct MetadataCaptureBody {
        triples: Arc<std::sync::Mutex<Vec<(u64, u64, bool)>>>,
    }
    impl camel_api::OutcomePipeline for MetadataCaptureBody {
        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 triples = Arc::clone(&self.triples);
            Box::pin(async move {
                let index = exchange
                    .property(crate::splitter::CAMEL_SPLIT_INDEX)
                    .and_then(|v| v.as_u64())
                    .unwrap_or(u64::MAX);
                let size = exchange
                    .property(crate::splitter::CAMEL_SPLIT_SIZE)
                    .and_then(|v| v.as_u64())
                    .unwrap_or(u64::MAX);
                let complete = exchange
                    .property(crate::splitter::CAMEL_SPLIT_COMPLETE)
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                triples.lock().unwrap().push((index, size, complete));
                PipelineOutcome::Completed(exchange)
            })
        }
    }

    /// Custom splitter producing `n` fragments with distinguishable bodies.
    fn n_fragment_splitter(n: u64) -> SplitSource {
        SplitSource::Sync(Arc::new(move |ex: &Exchange| {
            Ok((0..n)
                .map(|i| {
                    let mut frag = ex.clone();
                    frag.input.body = Body::Text(format!("frag-{i}"));
                    frag
                })
                .collect())
        }))
    }

    #[tokio::test]
    async fn sequential_split_stamps_fragment_metadata() {
        let triples = Arc::new(std::sync::Mutex::new(Vec::new()));

        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(3),
            body: OutcomeSegment::new(Box::new(MetadataCaptureBody {
                triples: Arc::clone(&triples),
            })),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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:?}"
        );

        assert_eq!(
            *triples.lock().unwrap(),
            vec![(0, 3, false), (1, 3, false), (2, 3, true)]
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn parallel_split_stamps_fragment_metadata() {
        let triples = Arc::new(std::sync::Mutex::new(Vec::new()));

        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(3),
            body: OutcomeSegment::new(Box::new(MetadataCaptureBody {
                triples: Arc::clone(&triples),
            })),
            parallel: true,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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 mut got = triples.lock().unwrap().clone();
        got.sort_by_key(|(idx, _, _)| *idx);
        assert_eq!(got, vec![(0, 3, false), (1, 3, false), (2, 3, true)]);
    }

    #[tokio::test]
    async fn single_fragment_is_complete() {
        let triples = Arc::new(std::sync::Mutex::new(Vec::new()));

        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(1),
            body: OutcomeSegment::new(Box::new(MetadataCaptureBody {
                triples: Arc::clone(&triples),
            })),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            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:?}"
        );

        assert_eq!(*triples.lock().unwrap(), vec![(0, 1, true)]);
    }

    // ── Ported from the removed Tower split tests ──────────────────────

    #[tokio::test]
    async fn split_segment_empty_fragments_returns_original_unchanged() {
        // Body::Empty → zero fragments → return original unchanged, properties intact.
        let mut seg = SplitSegment {
            splitter: SplitSource::Sync(camel_api::split_body_lines()),
            body: OutcomeSegment::new(Box::new(CompletedBody)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            aggregation: AggregationStrategy::LastWins,
        };

        let mut ex = Exchange::new(Message::default()); // Body::Empty
        ex.set_property("marker", Value::Bool(true));

        let result = camel_api::OutcomePipeline::run(&mut seg, ex).await;
        match result {
            PipelineOutcome::Completed(out) => {
                assert!(out.input.body.is_empty());
                assert_eq!(out.property("marker"), Some(&Value::Bool(true)));
            }
            other => panic!("Expected Completed(original), got {other:?}"),
        }
    }

    /// Body that records the split metadata into the body as JSON.
    #[derive(Clone)]
    struct MetadataJsonBody;
    impl camel_api::OutcomePipeline for MetadataJsonBody {
        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
            Box::new(MetadataJsonBody)
        }
        fn run<'a>(
            &'a mut self,
            exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            Box::pin(async move {
                let index = exchange
                    .property(crate::splitter::CAMEL_SPLIT_INDEX)
                    .cloned();
                let size = exchange
                    .property(crate::splitter::CAMEL_SPLIT_SIZE)
                    .cloned();
                let complete = exchange
                    .property(crate::splitter::CAMEL_SPLIT_COMPLETE)
                    .cloned();
                let mut out = exchange;
                out.input.body = Body::Json(serde_json::json!({
                    "index": index,
                    "size": size,
                    "complete": complete,
                }));
                PipelineOutcome::Completed(out)
            })
        }
    }

    #[tokio::test]
    async fn split_segment_metadata_properties() {
        // Uses split_body_lines + CollectAll so the metadata stamped on each
        // fragment is observable in the aggregated JSON body.
        let mut seg = SplitSegment {
            splitter: SplitSource::Sync(camel_api::split_body_lines()),
            body: OutcomeSegment::new(Box::new(MetadataJsonBody)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            aggregation: AggregationStrategy::CollectAll,
        };

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

        let expected = serde_json::json!([
            {"index": 0, "size": 3, "complete": false},
            {"index": 1, "size": 3, "complete": false},
            {"index": 2, "size": 3, "complete": true},
        ]);
        match result {
            PipelineOutcome::Completed(out) => match &out.input.body {
                Body::Json(v) => assert_eq!(*v, expected),
                other => panic!("expected JSON body, got {other:?}"),
            },
            other => panic!("Expected Completed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn split_segment_json_array_body() {
        // split(body_json_array) iterates array elements without tokenizing.
        let mut seg = SplitSegment {
            splitter: SplitSource::Sync(camel_api::split_body_json_array()),
            body: OutcomeSegment::new(Box::new(CompletedBody)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            aggregation: AggregationStrategy::CollectAll,
        };

        let msg = Message::new(Body::Json(serde_json::json!([1, 2, 3])));
        let parent = Exchange::new(msg);

        let result = camel_api::OutcomePipeline::run(&mut seg, parent).await;
        match result {
            PipelineOutcome::Completed(out) => match &out.input.body {
                Body::Json(serde_json::Value::Array(arr)) => {
                    assert_eq!(
                        arr,
                        &vec![
                            serde_json::json!(1),
                            serde_json::json!(2),
                            serde_json::json!(3)
                        ]
                    );
                }
                other => panic!("expected JSON array body, got {other:?}"),
            },
            other => panic!("Expected Completed, got {other:?}"),
        }
    }

    /// Body that replaces the body with the fragment correlation id.
    #[derive(Clone)]
    struct CorrelationIdBody;
    impl camel_api::OutcomePipeline for CorrelationIdBody {
        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
            Box::new(CorrelationIdBody)
        }
        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(exchange.correlation_id().to_string());
                PipelineOutcome::Completed(exchange)
            })
        }
    }

    #[tokio::test]
    async fn split_segment_each_fragment_has_unique_correlation_id() {
        let mut seg = SplitSegment {
            splitter: SplitSource::Sync(camel_api::split_body_lines()),
            body: OutcomeSegment::new(Box::new(CorrelationIdBody)),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            aggregation: AggregationStrategy::CollectAll,
        };

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

        let ids: Vec<String> = match result {
            PipelineOutcome::Completed(out) => match &out.input.body {
                Body::Json(serde_json::Value::Array(arr)) => arr
                    .iter()
                    .map(|v| v.as_str().unwrap_or("").to_string())
                    .collect(),
                other => panic!("expected JSON array of ids, got {other:?}"),
            },
            other => panic!("Expected Completed, got {other:?}"),
        };
        assert_eq!(ids.len(), 4, "should have 4 fragments");
        let unique: std::collections::HashSet<&String> = ids.iter().collect();
        assert_eq!(unique.len(), 4, "fragment correlation_ids must be unique");
    }

    // ── Fragment cap ───────────────────────────────────────────────────

    /// Helper: OutcomePipeline body that counts invocations and completes.
    #[derive(Clone)]
    struct CountingBody {
        counter: Arc<AtomicUsize>,
    }
    impl camel_api::OutcomePipeline for CountingBody {
        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>> {
            self.counter.fetch_add(1, Ordering::SeqCst);
            Box::pin(async move { PipelineOutcome::Completed(exchange) })
        }
    }

    fn counting_body(counter: &Arc<AtomicUsize>) -> OutcomeSegment {
        OutcomeSegment::new(Box::new(CountingBody {
            counter: Arc::clone(counter),
        }))
    }

    #[tokio::test]
    async fn split_rejects_above_custom_cap() {
        let invocations = Arc::new(AtomicUsize::new(0));
        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(5),
            body: counting_body(&invocations),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: 4,
            aggregation: AggregationStrategy::LastWins,
        };

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

        match result {
            PipelineOutcome::Failed(err) => assert!(
                err.to_string()
                    .contains("Splitter produced 5 fragments, exceeding max_fragments 4"),
                "error should name the produced count and cap, got {err}"
            ),
            other => panic!("expected Failed, got {other:?}"),
        }
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "no fragment may run when the cap is exceeded"
        );
    }

    #[tokio::test]
    async fn split_accepts_at_and_below_custom_cap() {
        let below = Arc::new(AtomicUsize::new(0));
        let mut below_seg = SplitSegment {
            splitter: n_fragment_splitter(3),
            body: counting_body(&below),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: 4,
            aggregation: AggregationStrategy::LastWins,
        };
        let below_result =
            camel_api::OutcomePipeline::run(&mut below_seg, Exchange::new(Message::new("test")))
                .await;
        assert!(
            matches!(below_result, PipelineOutcome::Completed(_)),
            "cap-1 must complete, got {below_result:?}"
        );
        assert_eq!(below.load(Ordering::SeqCst), 3, "cap-1 should run 3 bodies");

        let at = Arc::new(AtomicUsize::new(0));
        let mut at_seg = SplitSegment {
            splitter: n_fragment_splitter(4),
            body: counting_body(&at),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: 4,
            aggregation: AggregationStrategy::LastWins,
        };
        let at_result =
            camel_api::OutcomePipeline::run(&mut at_seg, Exchange::new(Message::new("test"))).await;
        assert!(
            matches!(at_result, PipelineOutcome::Completed(_)),
            "exactly-at-cap must complete, got {at_result:?}"
        );
        assert_eq!(at.load(Ordering::SeqCst), 4, "cap should run 4 bodies");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn split_rejects_before_spawning_parallel() {
        let invocations = Arc::new(AtomicUsize::new(0));
        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(3),
            body: counting_body(&invocations),
            parallel: true,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: 2,
            aggregation: AggregationStrategy::LastWins,
        };

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

        match result {
            PipelineOutcome::Failed(err) => assert!(
                err.to_string()
                    .contains("Splitter produced 3 fragments, exceeding max_fragments 2"),
                "error should name the produced count and cap, got {err}"
            ),
            other => panic!("expected Failed, got {other:?}"),
        }
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "no parallel task may spawn when the cap is exceeded"
        );
    }

    #[tokio::test]
    async fn split_rejects_before_processing_sequential() {
        let invocations = Arc::new(AtomicUsize::new(0));
        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(3),
            body: counting_body(&invocations),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: 2,
            aggregation: AggregationStrategy::LastWins,
        };

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

        match result {
            PipelineOutcome::Failed(err) => assert!(
                err.to_string()
                    .contains("Splitter produced 3 fragments, exceeding max_fragments 2"),
                "error should name the produced count and cap, got {err}"
            ),
            other => panic!("expected Failed, got {other:?}"),
        }
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "no fragment may run when the cap is exceeded"
        );
    }

    #[tokio::test]
    async fn split_empty_fragments_pass_through_with_cap() {
        let invocations = Arc::new(AtomicUsize::new(0));
        let splitter = SplitSource::Sync(
            Arc::new(|_: &Exchange| Ok(Vec::new())) as camel_api::SplitExpression
        );
        let mut seg = SplitSegment {
            splitter,
            body: counting_body(&invocations),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: 4,
            aggregation: AggregationStrategy::LastWins,
        };

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

        match result {
            PipelineOutcome::Completed(out) => {
                assert_eq!(
                    out.input.body.as_text(),
                    Some("original"),
                    "empty split must pass the original exchange through"
                );
            }
            other => panic!("expected Completed, got {other:?}"),
        }
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "an empty split must not invoke the body"
        );
    }

    #[tokio::test]
    async fn split_default_cap_respected() {
        assert_eq!(camel_api::splitter::DEFAULT_MAX_FRAGMENTS, 100_000);

        let invocations = Arc::new(AtomicUsize::new(0));
        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(3),
            body: counting_body(&invocations),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            aggregation: AggregationStrategy::LastWins,
        };

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

        assert!(
            matches!(result, PipelineOutcome::Completed(_)),
            "3 fragments are well below the default cap, got {result:?}"
        );
        assert_eq!(invocations.load(Ordering::SeqCst), 3, "all 3 bodies run");
    }

    #[tokio::test]
    async fn split_default_cap_plus_one_rejected() {
        let invocations = Arc::new(AtomicUsize::new(0));
        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(100_001),
            body: counting_body(&invocations),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: camel_api::splitter::DEFAULT_MAX_FRAGMENTS,
            aggregation: AggregationStrategy::LastWins,
        };

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

        match result {
            PipelineOutcome::Failed(err) => assert!(
                err.to_string().contains("exceeding max_fragments 100000"),
                "default cap error should name 100000, got {err}"
            ),
            other => panic!("expected Failed, got {other:?}"),
        }
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "no fragment may run when the default cap is exceeded"
        );
    }

    #[tokio::test]
    async fn split_zero_cap_fails_closed_non_empty() {
        let invocations = Arc::new(AtomicUsize::new(0));
        let mut seg = SplitSegment {
            splitter: n_fragment_splitter(2),
            body: counting_body(&invocations),
            parallel: false,
            parallel_limit: None,
            stop_on_exception: true,
            max_fragments: 0,
            aggregation: AggregationStrategy::LastWins,
        };

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

        match result {
            PipelineOutcome::Failed(err) => assert!(
                err.to_string().contains("exceeding max_fragments 0"),
                "zero cap must fail closed for non-empty splits, got {err}"
            ),
            other => panic!("expected Failed, got {other:?}"),
        }
        assert_eq!(
            invocations.load(Ordering::SeqCst),
            0,
            "zero cap must reject before processing"
        );
    }
}