camel-processor 0.69.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
//! ## Stop semantics (ADR-0025)
//!
//! This segment implements `OutcomePipeline` and propagates `PipelineOutcome::Stopped(ex)`
//! with the exchange state intact. See ADR-0025 §3.

use crate::do_try::CatchMatcher;
use crate::do_try::chain_predicate_error;
use crate::error_handler::record_span_error;
use camel_api::error_handler::ExceptionDisposition;
use camel_api::exchange::PROPERTY_EXCEPTION_HANDLED;
use camel_api::outcome_pipeline::OutcomePipeline;
use camel_api::pipeline_outcome::PipelineOutcome;
use camel_api::{CamelError, Exchange, PredicateSource};
use std::future::Future;
use std::pin::Pin;

/// Emit the catch-handled business log (business-error-model 1.6).
///
/// Only `code`/`kind` are structured; `message` and `data` are never
/// serialized into the record.
fn log_catch_business(error: &CamelError) {
    if let CamelError::Business { code, kind, .. } = error {
        tracing::info!(code = %code, kind = %kind, "business error handled by doTry catch");
    }
}

/// - `Handled`: the exchange continues through finally and downstream.
/// - `Propagate`: the catch body runs for side effects, finally runs with the
///   catch body's exchange, and the original try-error re-throws as `Failed`.
#[derive(Clone)]
pub struct CatchClauseSegment {
    pub matcher: CatchMatcher,
    pub on_when: Option<PredicateSource>,
    pub body: camel_api::OutcomeSegment,
    pub disposition: ExceptionDisposition,
}

/// Compilable segment for a `doFinally` clause within a `DoTrySegment`.
#[derive(Clone)]
pub struct FinallyClauseSegment {
    pub on_when: Option<PredicateSource>,
    pub body: camel_api::OutcomeSegment,
}

/// Outcome-aware structural EIP segment for the doTry/doCatch/doFinally pattern.
///
/// Operates at the `PipelineOutcome` layer so that `Stopped(ex)` from a
/// sub-step (e.g. Stop EIP) is preserved with the exchange including all
/// mutations. See ADR-0025 §5.1 for full semantics.
pub struct DoTrySegment {
    pub try_body: camel_api::OutcomeSegment,
    pub catches: Vec<CatchClauseSegment>,
    pub finally: Option<FinallyClauseSegment>,
}

impl Clone for DoTrySegment {
    fn clone(&self) -> Self {
        Self {
            try_body: self.try_body.clone(),
            catches: self.catches.clone(),
            finally: self.finally.clone(),
        }
    }
}

/// Narrow outcome type for `run_finally_body` so the compiler enforces
/// exhaustiveness at the two call sites instead of `unreachable!()`.
/// This is a private, transient type; the `Stopped` exchange is boxed to keep
/// the `Err` variant of `run_finally_body` small (clippy::result_large_err).
enum FinallyOutcome {
    Stopped(Box<Exchange>),
    Failed(CamelError),
    /// The finally `on_when` predicate itself failed; the typed error fails
    /// the segment.
    PredicateFailed(CamelError),
}

/// Run the finally body if present and on_when permits.
/// Free function (not a method) to avoid borrow conflict with
/// `self.catches.iter_mut()` inside the catch loop.
/// The `FinallyOutcome` variants move the `Exchange` (the catch loop needs
/// its state); boxing would rewrite the segment call chain for a lint
/// threshold.
#[allow(clippy::result_large_err)]
async fn run_finally_body(
    finally: &mut Option<FinallyClauseSegment>,
    ex: Exchange,
) -> Result<Exchange, FinallyOutcome> {
    let Some(f) = finally.as_mut() else {
        return Ok(ex);
    };
    if let Some(on_when) = &f.on_when {
        match on_when.matches(&ex).await {
            Ok(true) => {}
            Ok(false) => return Ok(ex),
            Err(err) => return Err(FinallyOutcome::PredicateFailed(err)),
        }
    }
    match f.body.run(ex).await {
        PipelineOutcome::Completed(e) => Ok(e),
        PipelineOutcome::Stopped(e) => Err(FinallyOutcome::Stopped(Box::new(e))),
        PipelineOutcome::Failed(e) => Err(FinallyOutcome::Failed(e)),
    }
}

/// Surface `failure` after running finally.
///
/// Used for a failed catch predicate (the predicate error surfaced as the
/// main failure), the no-catch-matched path, the Propagate / fail-closed
/// path (the original try error), and the catch-body-failure path (the catch
/// error is the surfaced failure).
/// `failure` becomes the main failure (Camel parity: a throwing finally body
/// restores it; Stop in finally still stops the outer route; a failed finally
/// `on_when` predicate supersedes it).
async fn fail_after_finally(
    finally: &mut Option<FinallyClauseSegment>,
    ex: Exchange,
    failure: CamelError,
) -> PipelineOutcome {
    match run_finally_body(finally, ex).await {
        Ok(_) => PipelineOutcome::Failed(failure),
        Err(FinallyOutcome::Stopped(e)) => PipelineOutcome::Stopped(*e),
        Err(FinallyOutcome::Failed(_finally_err)) => {
            tracing::warn!(
                error = %failure,
                "doFinally threw; restoring previous error (Camel parity)"
            );
            PipelineOutcome::Failed(failure)
        }
        Err(FinallyOutcome::PredicateFailed(pred_err)) => PipelineOutcome::Failed(pred_err),
    }
}

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

    fn run<'a>(
        &'a mut self,
        mut exchange: Exchange,
    ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
        Box::pin(async move {
            // Stale handled-marker protocol inherited from the deleted
            // `DoTryService` (clear-on-entry; `Exchange::clear_error` does not
            // touch HANDLED).
            exchange.properties.remove(PROPERTY_EXCEPTION_HANDLED);
            // Pre-clone for the "no catch matched" path; `exchange` itself is
            // consumed by `try_body.run(...)` below.
            let exchange_for_unmatched = exchange.branch_clone();

            // 1. Run try_body. If Stopped, return immediately (skip catch AND finally).
            let try_outcome = self.try_body.run(exchange).await;
            let returned_ex = match try_outcome {
                PipelineOutcome::Stopped(ex) => return PipelineOutcome::Stopped(ex),
                PipelineOutcome::Completed(ex) => ex,
                PipelineOutcome::Failed(err) => {
                    // 2. try failed — try each catch in order. Walk the catch
                    // chain starting from the failed try-exchange. On the first
                    // matching catch whose `on_when` is true (or unset), run it.
                    // A failed catch `when`/`on_when` predicate replaces the
                    // original error (preserved as `cause`) and fails the scope.
                    let mut current_ex = exchange_for_unmatched;
                    current_ex.set_error(err.clone());
                    // Distinguishes "a catch handled the error" (loop breaks
                    // with `current_ex` = catch output) from "the loop
                    // exhausted with no match" (must propagate the original).
                    let mut catch_matched = false;
                    for catch in self.catches.iter_mut() {
                        let matched = match catch.matcher.matches(&err, &current_ex).await {
                            Ok(m) => m,
                            Err(pred_err) => {
                                let chained = chain_predicate_error(pred_err, err);
                                return fail_after_finally(&mut self.finally, current_ex, chained)
                                    .await;
                            }
                        };
                        if !matched {
                            continue;
                        }
                        if let Some(on_when) = &catch.on_when {
                            match on_when.matches(&current_ex).await {
                                Ok(true) => {}
                                Ok(false) => continue,
                                Err(pred_err) => {
                                    let chained = chain_predicate_error(pred_err, err);
                                    return fail_after_finally(
                                        &mut self.finally,
                                        current_ex,
                                        chained,
                                    )
                                    .await;
                                }
                            }
                        }
                        // Pre-clone for the catch-body-failure path:
                        // `PipelineOutcome::Failed` drops the exchange, so the
                        // finally body still needs a pre-catch snapshot (same
                        // pattern as `exchange_for_unmatched` above).
                        let catch_input_ex = current_ex.branch_clone();
                        match catch.body.run(current_ex).await {
                            // Stop in catch: skip finally AND outer route halts.
                            PipelineOutcome::Stopped(stopped_ex) => {
                                return PipelineOutcome::Stopped(stopped_ex);
                            }
                            // Catch handled — exit catch chain with this exchange.
                            PipelineOutcome::Completed(mut next) => {
                                match catch.disposition {
                                    ExceptionDisposition::Handled => {
                                        log_catch_business(&err);
                                        next.handle_error();
                                        current_ex = next;
                                        catch_matched = true;
                                        break;
                                    }
                                    ExceptionDisposition::Continued => {
                                        log_catch_business(&err);
                                        next.clear_error();
                                        current_ex = next;
                                        catch_matched = true;
                                        break;
                                    }
                                    // Propagate and any future variant run finally then
                                    // surface the original error (fail-closed).
                                    _ => {
                                        return fail_after_finally(&mut self.finally, next, err)
                                            .await;
                                    }
                                }
                            }
                            // Catch-body Failed: Java try/catch/finally
                            // parity (JLS §14.20.2) — the finally body runs
                            // exactly once even when the catch body fails,
                            // and the catch error remains the surfaced
                            // failure. No catch-of-catch: the doTry island
                            // invariant (ADR-0025 #4) is unchanged, so the
                            // catch chain is NOT re-entered.
                            PipelineOutcome::Failed(catch_err) => {
                                // Sealed failure envelope: the catch error
                                // stays the main error (returned below);
                                // the original try error is surfaced
                                // through the unconditional warn record
                                // and, when a span is active, the span
                                // error record. No new span is created.
                                tracing::warn!(
                                    original_error = %err,
                                    catch_error = %catch_err,
                                    "do_try catch block failed; catch error supersedes original"
                                );
                                record_span_error(&catch_err);
                                return fail_after_finally(
                                    &mut self.finally,
                                    catch_input_ex,
                                    catch_err,
                                )
                                .await;
                            }
                        }
                    }
                    if catch_matched {
                        // A catch handled the error: continue to the shared
                        // finally path and return its exchange as Completed.
                        current_ex
                    } else {
                        // No catch matched: run finally, then propagate the
                        // original try error as `Failed`. Falling through to the
                        // shared finally path would return `Completed` and
                        // swallow the error, letting the route continue past
                        // the scope (the segment is the only doTry runtime).
                        return fail_after_finally(&mut self.finally, current_ex, err).await;
                    }
                }
            };
            // 3. Run finally if present (skip if try/catch returned Stopped —
            // already returned above; catch-body failures flow through
            // `fail_after_finally` and return there).
            match run_finally_body(&mut self.finally, returned_ex).await {
                Ok(ex) => PipelineOutcome::Completed(ex),
                Err(FinallyOutcome::Stopped(e)) => PipelineOutcome::Stopped(*e),
                Err(FinallyOutcome::Failed(finally_err)) => {
                    tracing::warn!(
                        error = %finally_err,
                        "doFinally threw during/after catch; surfacing finally error"
                    );
                    PipelineOutcome::Failed(finally_err)
                }
                // Failed finally `on_when` predicate: the typed error fails
                // the segment.
                Err(FinallyOutcome::PredicateFailed(pred_err)) => PipelineOutcome::Failed(pred_err),
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::do_try::CatchMatcher;
    use crate::test_log_capture::{capture_debugs_with_span_records, captured_field, record_field};
    use camel_api::Value;
    use camel_api::exchange::{PROPERTY_EXCEPTION_CAUGHT, PROPERTY_EXCEPTION_MESSAGE};
    use camel_api::pipeline_outcome::PipelineOutcome;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};

    // ── Helpers for DoTrySegment tests ──

    struct CompleteSegment;

    impl OutcomePipeline for CompleteSegment {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(CompleteSegment)
        }
        fn run<'a>(
            &'a mut self,
            exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            Box::pin(async move { PipelineOutcome::Completed(exchange) })
        }
    }

    fn seg_complete() -> camel_api::OutcomeSegment {
        camel_api::OutcomeSegment::new(Box::new(CompleteSegment))
    }

    struct FailSegment(CamelError);

    impl OutcomePipeline for FailSegment {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(FailSegment(self.0.clone()))
        }
        fn run<'a>(
            &'a mut self,
            _exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            let e = self.0.clone();
            Box::pin(async move { PipelineOutcome::Failed(e) })
        }
    }

    fn seg_fail(err: CamelError) -> camel_api::OutcomeSegment {
        camel_api::OutcomeSegment::new(Box::new(FailSegment(err)))
    }

    struct MutateThenStop {
        mutator: Arc<dyn Fn(&mut Exchange) + Send + Sync>,
    }

    impl OutcomePipeline for MutateThenStop {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(MutateThenStop {
                mutator: Arc::clone(&self.mutator),
            })
        }
        fn run<'a>(
            &'a mut self,
            mut exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            let m = Arc::clone(&self.mutator);
            Box::pin(async move {
                m(&mut exchange);
                PipelineOutcome::Stopped(exchange)
            })
        }
    }

    fn seg_stop_with(
        mutator: impl Fn(&mut Exchange) + Send + Sync + 'static,
    ) -> camel_api::OutcomeSegment {
        camel_api::OutcomeSegment::new(Box::new(MutateThenStop {
            mutator: Arc::new(mutator),
        }))
    }

    struct CheckThenComplete {
        check: Arc<dyn Fn(&Exchange) + Send + Sync>,
    }

    impl OutcomePipeline for CheckThenComplete {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(CheckThenComplete {
                check: Arc::clone(&self.check),
            })
        }
        fn run<'a>(
            &'a mut self,
            exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            let check = Arc::clone(&self.check);
            Box::pin(async move {
                check(&exchange);
                PipelineOutcome::Completed(exchange)
            })
        }
    }

    fn seg_check_then_complete(
        check: impl Fn(&Exchange) + Send + Sync + 'static,
    ) -> camel_api::OutcomeSegment {
        camel_api::OutcomeSegment::new(Box::new(CheckThenComplete {
            check: Arc::new(check),
        }))
    }

    struct RecordCall {
        counter: Arc<AtomicU32>,
    }

    impl OutcomePipeline for RecordCall {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(RecordCall {
                counter: Arc::clone(&self.counter),
            })
        }
        fn run<'a>(
            &'a mut self,
            exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            let c = Arc::clone(&self.counter);
            Box::pin(async move {
                c.fetch_add(1, Ordering::SeqCst);
                PipelineOutcome::Completed(exchange)
            })
        }
    }

    fn seg_record(counter: Arc<AtomicU32>) -> camel_api::OutcomeSegment {
        camel_api::OutcomeSegment::new(Box::new(RecordCall { counter }))
    }

    struct CountThenFail {
        counter: Arc<AtomicU32>,
        err: CamelError,
    }

    impl OutcomePipeline for CountThenFail {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(CountThenFail {
                counter: Arc::clone(&self.counter),
                err: self.err.clone(),
            })
        }
        fn run<'a>(
            &'a mut self,
            _exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            let c = Arc::clone(&self.counter);
            let e = self.err.clone();
            Box::pin(async move {
                c.fetch_add(1, Ordering::SeqCst);
                PipelineOutcome::Failed(e)
            })
        }
    }

    fn seg_count_then_fail(counter: Arc<AtomicU32>, err: CamelError) -> camel_api::OutcomeSegment {
        camel_api::OutcomeSegment::new(Box::new(CountThenFail { counter, err }))
    }

    struct CountThenStop {
        counter: Arc<AtomicU32>,
        mutator: Arc<dyn Fn(&mut Exchange) + Send + Sync>,
    }

    impl OutcomePipeline for CountThenStop {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(CountThenStop {
                counter: Arc::clone(&self.counter),
                mutator: Arc::clone(&self.mutator),
            })
        }
        fn run<'a>(
            &'a mut self,
            mut exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            let c = Arc::clone(&self.counter);
            let m = Arc::clone(&self.mutator);
            Box::pin(async move {
                c.fetch_add(1, Ordering::SeqCst);
                m(&mut exchange);
                PipelineOutcome::Stopped(exchange)
            })
        }
    }

    fn seg_count_then_stop(
        counter: Arc<AtomicU32>,
        mutator: impl Fn(&mut Exchange) + Send + Sync + 'static,
    ) -> camel_api::OutcomeSegment {
        camel_api::OutcomeSegment::new(Box::new(CountThenStop {
            counter,
            mutator: Arc::new(mutator),
        }))
    }

    // ── 5 New tests for DoTrySegment (ADR-0025) ──

    #[tokio::test]
    async fn stop_inside_try_skips_catch_and_finally() {
        let catch_call = Arc::new(AtomicU32::new(0));
        let finally_call = Arc::new(AtomicU32::new(0));

        let mut seg = DoTrySegment {
            try_body: seg_stop_with(|ex| {
                ex.set_property("mutated", camel_api::Value::Bool(true));
            }),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::ByVariant(vec!["*".into()]),
                on_when: None,
                body: seg_record(catch_call.clone()),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: Some(FinallyClauseSegment {
                on_when: None,
                body: seg_record(finally_call.clone()),
            }),
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Stopped(ex) => {
                assert_eq!(
                    ex.properties.get("mutated"),
                    Some(&camel_api::Value::Bool(true)),
                    "try body mutation must be preserved in Stopped exchange"
                );
            }
            other => panic!("expected Stopped, got {:?}", other),
        }
        assert_eq!(
            catch_call.load(Ordering::SeqCst),
            0,
            "catch must NOT run when try stops"
        );
        assert_eq!(
            finally_call.load(Ordering::SeqCst),
            0,
            "finally must NOT run when try stops"
        );
    }

    #[tokio::test]
    async fn stop_inside_catch_skips_finally() {
        let finally_call = Arc::new(AtomicU32::new(0));

        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
                on_when: None,
                body: seg_stop_with(|ex| {
                    ex.set_property("catch_mutated", camel_api::Value::Bool(true));
                }),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: Some(FinallyClauseSegment {
                on_when: None,
                body: seg_record(finally_call.clone()),
            }),
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Stopped(ex) => {
                assert_eq!(
                    ex.properties.get("catch_mutated"),
                    Some(&camel_api::Value::Bool(true)),
                    "catch body mutation must be preserved in Stopped exchange"
                );
            }
            other => panic!("expected Stopped, got {:?}", other),
        }
        assert_eq!(
            finally_call.load(Ordering::SeqCst),
            0,
            "finally must NOT run when catch stops"
        );
    }

    #[tokio::test]
    async fn stop_inside_finally_stops_outer_route() {
        let mut seg = DoTrySegment {
            try_body: seg_complete(),
            catches: vec![],
            finally: Some(FinallyClauseSegment {
                on_when: None,
                body: seg_stop_with(|ex| {
                    ex.set_property("finally_mutated", camel_api::Value::Bool(true));
                }),
            }),
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Stopped(ex) => {
                assert_eq!(
                    ex.properties.get("finally_mutated"),
                    Some(&camel_api::Value::Bool(true)),
                    "finally body mutation must be preserved in Stopped exchange"
                );
            }
            other => panic!("expected Stopped, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn catch_on_when_false_falls_through_to_next_catch() {
        let first_call = Arc::new(AtomicU32::new(0));
        let second_call = Arc::new(AtomicU32::new(0));

        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::Io("disk err".into())),
            catches: vec![
                CatchClauseSegment {
                    matcher: CatchMatcher::ByVariant(vec!["Io".into()]),
                    on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
                    body: seg_record(first_call.clone()),
                    disposition: ExceptionDisposition::Handled,
                },
                CatchClauseSegment {
                    matcher: CatchMatcher::ByVariant(vec!["*".into()]),
                    on_when: None,
                    body: seg_record(second_call.clone()),
                    disposition: ExceptionDisposition::Handled,
                },
            ],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(result, PipelineOutcome::Completed(_)),
            "expected Completed after second catch"
        );
        assert_eq!(
            first_call.load(Ordering::SeqCst),
            0,
            "first catch must NOT fire (on_when=false)"
        );
        assert_eq!(
            second_call.load(Ordering::SeqCst),
            1,
            "second catch must fire"
        );
    }

    #[tokio::test]
    async fn finally_on_when_false_skips_finally_entirely() {
        let finally_call = Arc::new(AtomicU32::new(0));
        let mut ex = Exchange::default();
        ex.set_property("try_set", camel_api::Value::Bool(true));

        let mut seg = DoTrySegment {
            try_body: seg_complete(),
            catches: vec![],
            finally: Some(FinallyClauseSegment {
                on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
                body: seg_record(finally_call.clone()),
            }),
        };

        let result = seg.run(ex).await;
        match result {
            PipelineOutcome::Completed(ex) => {
                assert_eq!(
                    ex.properties.get("try_set"),
                    Some(&camel_api::Value::Bool(true)),
                    "exchange state from try must be preserved"
                );
            }
            other => panic!("expected Completed, got {:?}", other),
        }
        assert_eq!(
            finally_call.load(Ordering::SeqCst),
            0,
            "finally must NOT run when on_when=false"
        );
    }

    // ── Catch disposition clears error (mission 479) ──

    #[tokio::test]
    async fn handled_catch_clears_error_and_marks_handled() {
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
                on_when: None,
                body: seg_check_then_complete(|ex| {
                    assert!(ex.has_error(), "catch body must see the try error");
                    assert!(
                        matches!(ex.properties.get(PROPERTY_EXCEPTION_MESSAGE), Some(Value::String(s)) if s.contains("boom")),
                        "catch body must see the derived exception message, got {:?}",
                        ex.properties.get(PROPERTY_EXCEPTION_MESSAGE)
                    );
                }),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Completed(ex) => {
                assert!(
                    !ex.has_error(),
                    "handled catch must clear the exchange error"
                );
                assert_eq!(
                    ex.properties.get(PROPERTY_EXCEPTION_HANDLED),
                    Some(&Value::Bool(true)),
                    "handled catch must set CamelExceptionHandled"
                );
                assert!(
                    !ex.properties.contains_key(PROPERTY_EXCEPTION_MESSAGE),
                    "handled catch must clear the derived exception message"
                );
            }
            other => panic!("expected Completed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn continued_catch_clears_error_without_handled_marker() {
        let mut ex = Exchange::default();
        ex.set_property(PROPERTY_EXCEPTION_HANDLED, Value::Bool(true));

        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
                on_when: None,
                body: seg_check_then_complete(|ex| {
                    assert!(ex.has_error(), "catch body must see the try error");
                    assert!(
                        matches!(ex.properties.get(PROPERTY_EXCEPTION_MESSAGE), Some(Value::String(s)) if s.contains("boom")),
                        "catch body must see the derived exception message, got {:?}",
                        ex.properties.get(PROPERTY_EXCEPTION_MESSAGE)
                    );
                }),
                disposition: ExceptionDisposition::Continued,
            }],
            finally: None,
        };

        let result = seg.run(ex).await;
        match result {
            PipelineOutcome::Completed(ex) => {
                assert!(
                    !ex.has_error(),
                    "continued catch must clear the exchange error"
                );
                assert!(
                    !ex.properties.contains_key(PROPERTY_EXCEPTION_HANDLED),
                    "Continued must not leave the handled marker"
                );
                assert!(
                    !ex.properties.contains_key(PROPERTY_EXCEPTION_MESSAGE),
                    "continued catch must clear the derived exception message"
                );
            }
            other => panic!("expected Completed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn finally_after_handled_catch_sees_no_error() {
        let finally_calls = Arc::new(AtomicU32::new(0));
        let calls = Arc::clone(&finally_calls);
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
                on_when: None,
                body: seg_complete(),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: Some(FinallyClauseSegment {
                on_when: None,
                body: seg_check_then_complete(move |ex| {
                    calls.fetch_add(1, Ordering::SeqCst);
                    assert!(
                        !ex.has_error(),
                        "finally must observe a clean exchange after a handled catch"
                    );
                    assert!(
                        !ex.properties.contains_key(PROPERTY_EXCEPTION_MESSAGE),
                        "derived exception properties must be cleared"
                    );
                }),
            }),
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Completed(ex) => {
                assert!(!ex.has_error(), "handled catch must leave a clean exchange");
            }
            other => panic!("expected Completed, got {other:?}"),
        }
        assert_eq!(
            finally_calls.load(Ordering::SeqCst),
            1,
            "finally must run exactly once"
        );
    }

    // ── Catch-body failure envelope (compiled-segment path) ──

    fn catch_fails_segment() -> DoTrySegment {
        DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
                on_when: None,
                body: seg_fail(CamelError::Io("catch-fail".into())),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: None,
        }
    }

    #[test]
    fn catch_body_failure_returns_catch_err_and_marks_span() {
        let mut seg = catch_fails_segment();
        let (result, captured, span_records) = capture_debugs_with_span_records(|| {
            // Declared `error` field so record_span_error's record lands.
            let span = tracing::info_span!("dotry_seg_test", error = tracing::field::Empty);
            let _guard = span.enter();
            tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("current-thread runtime")
                .block_on(async { seg.run(Exchange::default()).await })
        });

        assert!(
            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
            "catch failure must surface the catch error as Failed(Io), got: {result:?}"
        );
        // The span recorded the `error` field with the CATCH error.
        // Structured field lookup: substring `error=` would also match
        // `original_error=` suffixes.
        assert!(
            span_records.iter().any(|line| {
                captured_field(line, "error").is_some_and(|v| v.contains("catch-fail"))
            }),
            "expected span error record carrying the catch error, span records: {span_records:?}"
        );
        let original = record_field(&captured, "do_try catch block failed", "original_error")
            .unwrap_or_else(|| {
                panic!(
                    "envelope record missing original_error field under active span, captured: {captured:?}"
                )
            });
        assert!(
            original.contains("orig"),
            "original_error must carry the original error under an active span, got: {original}"
        );
    }

    #[test]
    fn catch_body_failure_emits_envelope_log() {
        let mut seg = catch_fails_segment();
        let (result, captured, _span_records) = capture_debugs_with_span_records(|| {
            tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("current-thread runtime")
                .block_on(async { seg.run(Exchange::default()).await })
        });

        assert!(
            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
            "catch failure must surface the catch error as Failed(Io), got: {result:?}"
        );
        // Structured field lookup on the envelope record, not message
        // formatting.
        let original = record_field(&captured, "do_try catch block failed", "original_error")
            .unwrap_or_else(|| {
                panic!("envelope record missing original_error field, captured: {captured:?}")
            });
        let catch = record_field(&captured, "do_try catch block failed", "catch_error")
            .unwrap_or_else(|| {
                panic!("envelope record missing catch_error field, captured: {captured:?}")
            });
        assert!(
            original.contains("orig"),
            "original_error must carry the original error, got: {original}"
        );
        assert!(
            catch.contains("catch-fail"),
            "catch_error must carry the catch error, got: {catch}"
        );
    }

    // ── Fallible predicate path (language-value-boundary task 1.4) ──

    use camel_api::{ExpressionErrorClass, FilterPredicate, PredicateSource};

    fn expression_failed() -> CamelError {
        CamelError::ExpressionFailed {
            language: "rhai".to_string(),
            route_id: "r1".to_string(),
            step_id: "step#0".to_string(),
            verb: "on_when".to_string(),
            class: ExpressionErrorClass::Runtime,
            position: None,
            conversion: None,
            cause: None,
        }
    }

    fn async_err_predicate(err: CamelError) -> PredicateSource {
        PredicateSource::Async(Arc::new(move |_: &Exchange| {
            let err = err.clone();
            Box::pin(async move { Err(err) }) as camel_api::BoxBoolFuture
        }))
    }

    #[tokio::test]
    async fn finally_on_when_predicate_error_fails_segment() {
        let finally_call = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_complete(),
            catches: vec![],
            finally: Some(FinallyClauseSegment {
                on_when: Some(async_err_predicate(expression_failed())),
                body: seg_record(finally_call.clone()),
            }),
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Failed(CamelError::ExpressionFailed { .. }) => {}
            other => panic!("expected Failed(ExpressionFailed), got {other:?}"),
        }
        assert_eq!(
            finally_call.load(Ordering::SeqCst),
            0,
            "finally body must not run when its on_when predicate errors"
        );
    }

    // ── No-catch-matched path (mission 353) ──

    /// doTry with no matching catch must run finally and propagate the
    /// original try error as `Failed` (the segment is the only doTry runtime).
    /// Guards against regressing back to `Completed(bugged_swallow)`.
    #[tokio::test]
    async fn no_clause_matches_runs_finally_and_propagates_original() {
        let catch_call = Arc::new(AtomicU32::new(0));
        let finally_call = Arc::new(AtomicU32::new(0));

        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::EndpointCreationFailed(
                "direct endpoint 'direct:does-not-exist' not registered".into(),
            )),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::ByVariant(vec!["Io".into()]),
                on_when: None,
                body: seg_record(catch_call.clone()),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: Some(FinallyClauseSegment {
                on_when: None,
                body: seg_record(finally_call.clone()),
            }),
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Failed(CamelError::EndpointCreationFailed(msg)) => {
                assert!(
                    msg.contains("does-not-exist"),
                    "propagated error must be the original try error, got: {msg}"
                );
            }
            other => {
                panic!("no catch matched: expected Failed(EndpointCreationFailed), got {other:?}")
            }
        }
        assert_eq!(
            finally_call.load(Ordering::SeqCst),
            1,
            "finally must run exactly once when no catch matches"
        );
        assert_eq!(
            catch_call.load(Ordering::SeqCst),
            0,
            "the unmatched catch body must not run"
        );
    }
    // ── Ported from the deleted Tower doTry service (no coverage loss) ──

    use camel_language_api::{EvalMeta, LanguageError, to_expression_failed};

    fn catch_variant(names: &[&str], body: camel_api::OutcomeSegment) -> CatchClauseSegment {
        catch_variant_with(names, body, ExceptionDisposition::Handled)
    }

    fn catch_variant_with(
        names: &[&str],
        body: camel_api::OutcomeSegment,
        disposition: ExceptionDisposition,
    ) -> CatchClauseSegment {
        CatchClauseSegment {
            matcher: CatchMatcher::ByVariant(names.iter().map(|n| (*n).to_string()).collect()),
            on_when: None,
            body,
            disposition,
        }
    }

    fn finally_seg(body: camel_api::OutcomeSegment) -> FinallyClauseSegment {
        FinallyClauseSegment {
            on_when: None,
            body,
        }
    }

    #[tokio::test]
    async fn happy_path_try_succeeds_finally_runs() {
        let finally_flag = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_complete(),
            catches: vec![],
            finally: Some(finally_seg(seg_record(finally_flag.clone()))),
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(result, PipelineOutcome::Completed(_)),
            "try success must complete, got {result:?}"
        );
        assert_eq!(finally_flag.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn catch_by_variant_handled_returns_ok() {
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
            catches: vec![catch_variant(&["ProcessorError"], seg_complete())],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Completed(ex) => {
                assert!(!ex.has_error(), "Handled must clear the exchange error");
                assert_eq!(
                    ex.properties.get(PROPERTY_EXCEPTION_HANDLED),
                    Some(&Value::Bool(true)),
                    "Handled must set CamelExceptionHandled"
                );
            }
            other => panic!("Handled must return Completed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn catch_by_variant_propagate_runs_side_effects_and_rethrows() {
        let side_effect = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
            catches: vec![catch_variant_with(
                &["ProcessorError"],
                seg_record(side_effect.clone()),
                ExceptionDisposition::Propagate,
            )],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(
                result,
                PipelineOutcome::Failed(CamelError::ProcessorError(_))
            ),
            "Propagate must rethrow the original error, got {result:?}"
        );
        assert_eq!(
            side_effect.load(Ordering::SeqCst),
            1,
            "catch branch must have run for side-effects"
        );
    }

    #[tokio::test]
    async fn catch_by_predicate_matches_via_exception_kind() {
        let predicate = FilterPredicate::new(|ex: &Exchange| {
            ex.properties
                .get(camel_api::exchange::PROPERTY_EXCEPTION_KIND)
                .map(|v| matches!(v, camel_api::Value::String(s) if s == "io"))
                .unwrap_or(false)
        });
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::Io("disk full".into())),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::Predicate(PredicateSource::Sync(predicate)),
                on_when: None,
                body: seg_complete(),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(result, PipelineOutcome::Completed(_)),
            "Predicate matcher must catch the error and Handled must return Completed, got {result:?}"
        );
    }

    #[tokio::test]
    async fn first_match_wins_subsequent_clauses_not_evaluated() {
        let first_call = Arc::new(AtomicU32::new(0));
        let second_call = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::Io("err".into())),
            catches: vec![
                catch_variant(&["Io"], seg_record(first_call.clone())),
                catch_variant(&["*"], seg_record(second_call.clone())),
            ],
            finally: None,
        };

        let _ = seg.run(Exchange::default()).await;
        assert_eq!(first_call.load(Ordering::SeqCst), 1);
        assert_eq!(second_call.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn catch_branch_throws_new_error_wins() {
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
            catches: vec![catch_variant(
                &["ProcessorError"],
                seg_fail(CamelError::Io("catch-fail".into())),
            )],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
            "catch error must win over the try error, got {result:?}"
        );
    }

    #[tokio::test]
    async fn finally_throws_with_no_previous_error_propagates_finally_error() {
        let mut seg = DoTrySegment {
            try_body: seg_complete(),
            catches: vec![],
            finally: Some(finally_seg(seg_fail(CamelError::Config("fin".into())))),
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(result, PipelineOutcome::Failed(CamelError::Config(_))),
            "finally error must propagate when no previous error exists, got {result:?}"
        );
    }

    #[tokio::test]
    async fn finally_throws_with_previous_error_restores_previous() {
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
            catches: vec![],
            finally: Some(finally_seg(seg_fail(CamelError::Config("fin".into())))),
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(
                result,
                PipelineOutcome::Failed(CamelError::ProcessorError(_))
            ),
            "previous error must be restored when finally throws (Camel parity), got {result:?}"
        );
    }

    #[tokio::test]
    async fn stale_handled_marker_cleared_on_entry() {
        let mut ex = Exchange::default();
        ex.set_property(
            camel_api::exchange::PROPERTY_EXCEPTION_HANDLED,
            camel_api::Value::Bool(true),
        );
        ex.set_error(CamelError::ProcessorError("stale".into()));
        let mut seg = DoTrySegment {
            try_body: seg_complete(),
            catches: vec![],
            finally: None,
        };

        let result = seg.run(ex).await;
        match result {
            PipelineOutcome::Completed(ex) => assert!(
                !ex.properties
                    .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_HANDLED),
                "stale CamelExceptionHandled must be cleared on entry"
            ),
            other => panic!("expected Completed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn nested_do_try_inner_catch_does_not_leak_to_outer() {
        let inner = DoTrySegment {
            try_body: seg_fail(CamelError::Io("inner".into())),
            catches: vec![catch_variant(&["Io"], seg_complete())],
            finally: None,
        };
        let mut outer = DoTrySegment {
            try_body: camel_api::OutcomeSegment::new(Box::new(inner)),
            catches: vec![catch_variant(&["Io"], seg_complete())],
            finally: None,
        };

        let result = outer.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Completed(ex) => {
                assert!(
                    !ex.has_error(),
                    "inner handled error must not leak to the outer exchange"
                );
            }
            other => panic!(
                "outer must see Completed because inner handled its own error, got {other:?}"
            ),
        }
    }

    #[tokio::test]
    async fn catch_all_only_fires_when_no_specific_clause_matches() {
        let processor_call = Arc::new(AtomicU32::new(0));
        let catch_all_call = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::Io("err".into())),
            catches: vec![
                catch_variant(&["ProcessorError"], seg_record(processor_call.clone())),
                catch_variant(&["*"], seg_record(catch_all_call.clone())),
            ],
            finally: None,
        };

        let _ = seg.run(Exchange::default()).await;
        assert_eq!(
            processor_call.load(Ordering::SeqCst),
            0,
            "specific ProcessorError clause must not fire on Io error"
        );
        assert_eq!(
            catch_all_call.load(Ordering::SeqCst),
            1,
            "catch-all clause must fire when no specific clause matches"
        );
    }

    /// Java try/catch/finally parity (JLS §14.20.2): a failing catch body
    /// does not skip finally, and the catch error remains the surfaced
    /// failure. This rebuilds the catch-and-finally coverage lost with the
    /// deleted builder-only `DoTryService`.
    #[tokio::test]
    async fn catch_body_failure_runs_finally_once_then_returns_catch_err() {
        let finally_flag = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
            catches: vec![catch_variant(
                &["ProcessorError"],
                seg_fail(CamelError::Io("catch-fail".into())),
            )],
            finally: Some(finally_seg(seg_record(finally_flag.clone()))),
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
            "catch_err must propagate (not original ProcessorError), got {result:?}"
        );
        assert_eq!(
            finally_flag.load(Ordering::SeqCst),
            1,
            "finally must run exactly once even when the catch body fails (Java try/catch/finally parity)"
        );
    }

    /// Real exercise of the finally/catch parity rule: the finally body runs
    /// (and throws) even when the catch body fails, and the catch error still
    /// wins over the finally error (Camel parity: a throwing finally restores
    /// the previous error). Before the catch-body-failure path ran finally,
    /// this test passed vacuously.
    #[tokio::test]
    async fn catch_throws_and_throwing_finally_still_returns_catch_err() {
        let finally_flag = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
            catches: vec![catch_variant(
                &["ProcessorError"],
                seg_fail(CamelError::Io("catch-fail".into())),
            )],
            finally: Some(finally_seg(seg_count_then_fail(
                finally_flag.clone(),
                CamelError::Config("fin-fail".into()),
            ))),
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
            "catch_err (Io) must be returned over finally_err (Config), got {result:?}"
        );
        assert_eq!(
            finally_flag.load(Ordering::SeqCst),
            1,
            "finally must run exactly once even when its own body fails"
        );
    }

    /// Stop in finally takes precedence over the pending catch failure: the
    /// outer route stops with the finally exchange (mutation preserved), and
    /// the finally body still ran exactly once. Pins the `Stopped` arm of
    /// `fail_after_finally` on the catch-body-failure path.
    #[tokio::test]
    async fn catch_body_failure_then_finally_stops_stops_outer_route() {
        let finally_flag = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
            catches: vec![catch_variant(
                &["ProcessorError"],
                seg_fail(CamelError::Io("catch-fail".into())),
            )],
            finally: Some(finally_seg(seg_count_then_stop(
                finally_flag.clone(),
                |ex| {
                    ex.set_property("finally_stopped_marker", camel_api::Value::Bool(true));
                },
            ))),
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Stopped(ex) => {
                assert_eq!(
                    ex.properties.get("finally_stopped_marker"),
                    Some(&camel_api::Value::Bool(true)),
                    "finally exchange mutation must be preserved in Stopped"
                );
            }
            other => panic!("expected Stopped, got {other:?}"),
        }
        assert_eq!(
            finally_flag.load(Ordering::SeqCst),
            1,
            "finally must run exactly once before the outer route stops"
        );
    }

    #[tokio::test]
    async fn finally_on_when_false_with_previous_error_still_propagates_original() {
        let finally_flag = Arc::new(AtomicU32::new(0));
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
            catches: vec![],
            finally: Some(FinallyClauseSegment {
                on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
                body: seg_record(finally_flag.clone()),
            }),
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(
                result,
                PipelineOutcome::Failed(CamelError::ProcessorError(_))
            ),
            "original error must propagate even when finally_on_when skips finally, got {result:?}"
        );
        assert_eq!(
            finally_flag.load(Ordering::SeqCst),
            0,
            "doFinally must NOT run when on_when returns false"
        );
    }

    #[tokio::test]
    async fn catch_throws_under_propagate_disposition_returns_catch_err() {
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
            catches: vec![catch_variant_with(
                &["ProcessorError"],
                seg_fail(CamelError::Io("catch-fail".into())),
                ExceptionDisposition::Propagate,
            )],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        assert!(
            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
            "Propagate-disposition catch failure must surface the catch error, got {result:?}"
        );
    }

    #[tokio::test]
    async fn catch_when_predicate_error_chains_original() {
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::Predicate(async_err_predicate(expression_failed())),
                on_when: None,
                body: seg_complete(),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Failed(CamelError::ExpressionFailed {
                cause: Some(cause), ..
            }) => {
                assert!(
                    cause.to_string().contains("boom"),
                    "cause must carry the original error, got: {cause}"
                );
            }
            other => panic!("expected Failed(ExpressionFailed) with chained cause, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn catch_on_when_predicate_error_chains_original() {
        let mut seg = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
            catches: vec![CatchClauseSegment {
                matcher: CatchMatcher::ByVariant(vec!["*".into()]),
                on_when: Some(async_err_predicate(expression_failed())),
                body: seg_complete(),
                disposition: ExceptionDisposition::Handled,
            }],
            finally: None,
        };

        let result = seg.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Failed(CamelError::ExpressionFailed {
                cause: Some(cause), ..
            }) => {
                assert!(
                    cause.to_string().contains("boom"),
                    "cause must carry the original error, got: {cause}"
                );
            }
            other => panic!("expected Failed(ExpressionFailed) with chained cause, got {other:?}"),
        }
    }

    // ── Mapper-generated cause replacement (ported from do_try.rs) ──

    fn caller_diagnostic_failed(cause: CamelError) -> CamelError {
        CamelError::ExpressionFailed {
            language: "rhai".to_string(),
            route_id: "r1".to_string(),
            step_id: "s1".to_string(),
            verb: "when".to_string(),
            class: ExpressionErrorClass::Runtime,
            position: None,
            conversion: None,
            cause: Some(Box::new(cause)),
        }
    }

    #[test]
    fn chain_replaces_mapper_generated_cause() {
        let meta = EvalMeta {
            language: "xpath".into(),
            route_id: "r1".into(),
            step_id: "s1".into(),
            verb: "when".into(),
            target: None,
        };
        let mapper_err = to_expression_failed(
            LanguageError::EvalFailure {
                class: ExpressionErrorClass::Parse,
                position: None,
                detail: Some("body is not valid XML".into()),
            },
            &meta,
        );

        let result = chain_predicate_error(mapper_err, CamelError::ProcessorError("boom".into()));

        match result {
            CamelError::ExpressionFailed {
                cause: Some(cause), ..
            } => {
                assert!(
                    cause.to_string().contains("boom"),
                    "mapper diagnostic cause must be replaced by the original, got: {cause}"
                );
            }
            other => panic!("expected ExpressionFailed with chained cause, got {other:?}"),
        }
    }

    #[test]
    fn chain_preserves_caller_cause() {
        let predicate_err =
            caller_diagnostic_failed(CamelError::ProcessorError("caller diagnostic".into()));

        let result =
            chain_predicate_error(predicate_err, CamelError::ProcessorError("boom".into()));

        match result {
            CamelError::ExpressionFailed {
                cause: Some(cause), ..
            } => {
                let rendered = cause.to_string();
                assert!(
                    rendered.contains("caller diagnostic"),
                    "caller cause must pass through untouched, got: {rendered}"
                );
                assert!(
                    !rendered.contains("boom"),
                    "caller cause must not be replaced, got: {rendered}"
                );
            }
            other => panic!("expected ExpressionFailed with caller cause, got {other:?}"),
        }
    }

    #[test]
    fn chain_preserves_caller_source_bearing_cause() {
        let predicate_err = caller_diagnostic_failed(CamelError::ProcessorErrorWithSource(
            "caller diagnostic".into(),
            Arc::new(std::io::Error::other("caller source")),
        ));

        let result =
            chain_predicate_error(predicate_err, CamelError::ProcessorError("boom".into()));

        match result {
            CamelError::ExpressionFailed {
                cause: Some(cause), ..
            } => {
                let rendered = cause.to_string();
                assert!(
                    rendered.contains("caller diagnostic"),
                    "caller cause must pass through untouched, got: {rendered}"
                );
                let source = std::error::Error::source(cause.as_ref())
                    .unwrap_or_else(|| panic!("caller source must survive, cause: {cause:?}"));
                assert!(
                    source.to_string().contains("caller source"),
                    "caller source must survive untouched, got: {source}"
                );
            }
            other => panic!("expected ExpressionFailed with caller cause, got {other:?}"),
        }
    }

    // ── Handled-marker / caught-property lifetime tests ──

    struct MarkThenFail;

    impl OutcomePipeline for MarkThenFail {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(MarkThenFail)
        }
        fn run<'a>(
            &'a mut self,
            mut exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            Box::pin(async move {
                exchange.set_property(PROPERTY_EXCEPTION_HANDLED, Value::Bool(true));
                PipelineOutcome::Failed(CamelError::ProcessorError("try".into()))
            })
        }
    }

    #[tokio::test]
    async fn nested_handled_marker_survives_outer_continued() {
        let inner = DoTrySegment {
            try_body: seg_fail(CamelError::Io("inner".into())),
            catches: vec![catch_variant(&["Io"], seg_complete())],
            finally: None,
        };
        let mut outer = DoTrySegment {
            try_body: seg_fail(CamelError::ProcessorError("outer".into())),
            catches: vec![catch_variant_with(
                &["ProcessorError"],
                camel_api::OutcomeSegment::new(Box::new(inner)),
                ExceptionDisposition::Continued,
            )],
            finally: None,
        };

        let result = outer.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Completed(ex) => {
                assert!(
                    !ex.has_error(),
                    "continued catch must leave a clean exchange"
                );
                assert_eq!(
                    ex.properties.get(PROPERTY_EXCEPTION_HANDLED),
                    Some(&Value::Bool(true)),
                    "inner Handled marker must survive the outer Continued exit"
                );
                assert!(
                    !ex.properties.contains_key(PROPERTY_EXCEPTION_CAUGHT),
                    "continued exit must clear CamelExceptionCaught"
                );
            }
            other => panic!("expected Completed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn failing_try_body_marker_does_not_reach_catch_chain() {
        let mut outer = DoTrySegment {
            try_body: camel_api::OutcomeSegment::new(Box::new(MarkThenFail)),
            catches: vec![catch_variant_with(
                &["ProcessorError"],
                seg_complete(),
                ExceptionDisposition::Continued,
            )],
            finally: None,
        };

        let result = outer.run(Exchange::default()).await;
        match result {
            PipelineOutcome::Completed(ex) => {
                assert!(
                    !ex.has_error(),
                    "continued catch must leave a clean exchange"
                );
                assert!(
                    !ex.properties.contains_key(PROPERTY_EXCEPTION_HANDLED),
                    "a marker set by a failing try body must not reach the catch chain"
                );
            }
            other => panic!("expected Completed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn caught_property_absent_after_handled_and_continued_exit() {
        for disposition in [
            ExceptionDisposition::Handled,
            ExceptionDisposition::Continued,
        ] {
            let mut seg = DoTrySegment {
                try_body: seg_fail(CamelError::ProcessorError("boom".into())),
                catches: vec![catch_variant_with(
                    &["ProcessorError"],
                    seg_check_then_complete(|ex| {
                        assert!(
                            ex.properties.contains_key(PROPERTY_EXCEPTION_CAUGHT),
                            "catch body must see CamelExceptionCaught"
                        );
                    }),
                    disposition,
                )],
                finally: None,
            };

            let result = seg.run(Exchange::default()).await;
            match result {
                PipelineOutcome::Completed(ex) => {
                    assert!(
                        !ex.has_error(),
                        "{disposition:?} must clear the exchange error"
                    );
                    assert!(
                        !ex.properties.contains_key(PROPERTY_EXCEPTION_CAUGHT),
                        "{disposition:?} exit must clear CamelExceptionCaught"
                    );
                    if disposition == ExceptionDisposition::Handled {
                        assert_eq!(
                            ex.properties.get(PROPERTY_EXCEPTION_HANDLED),
                            Some(&Value::Bool(true)),
                            "Handled exit must keep the handled marker"
                        );
                    } else {
                        assert!(
                            !ex.properties.contains_key(PROPERTY_EXCEPTION_HANDLED),
                            "Continued exit must not leave the handled marker"
                        );
                    }
                }
                other => panic!("expected Completed, got {other:?}"),
            }
        }
    }
}