Skip to main content

camel_processor/
do_try_segment.rs

1//! ## Stop semantics (ADR-0025)
2//!
3//! This segment implements `OutcomePipeline` and propagates `PipelineOutcome::Stopped(ex)`
4//! with the exchange state intact. See ADR-0025 §3.
5
6use crate::do_try::CatchMatcher;
7use crate::do_try::chain_predicate_error;
8use crate::error_handler::record_span_error;
9use camel_api::error_handler::ExceptionDisposition;
10use camel_api::exchange::PROPERTY_EXCEPTION_HANDLED;
11use camel_api::outcome_pipeline::OutcomePipeline;
12use camel_api::pipeline_outcome::PipelineOutcome;
13use camel_api::{CamelError, Exchange, PredicateSource};
14use std::future::Future;
15use std::pin::Pin;
16
17/// - `Handled`: the exchange continues through finally and downstream.
18/// - `Propagate`: the catch body runs for side effects, finally runs with the
19///   catch body's exchange, and the original try-error re-throws as `Failed`.
20#[derive(Clone)]
21pub struct CatchClauseSegment {
22    pub matcher: CatchMatcher,
23    pub on_when: Option<PredicateSource>,
24    pub body: camel_api::OutcomeSegment,
25    pub disposition: ExceptionDisposition,
26}
27
28/// Compilable segment for a `doFinally` clause within a `DoTrySegment`.
29#[derive(Clone)]
30pub struct FinallyClauseSegment {
31    pub on_when: Option<PredicateSource>,
32    pub body: camel_api::OutcomeSegment,
33}
34
35/// Outcome-aware structural EIP segment for the doTry/doCatch/doFinally pattern.
36///
37/// Operates at the `PipelineOutcome` layer so that `Stopped(ex)` from a
38/// sub-step (e.g. Stop EIP) is preserved with the exchange including all
39/// mutations. See ADR-0025 §5.1 for full semantics.
40pub struct DoTrySegment {
41    pub try_body: camel_api::OutcomeSegment,
42    pub catches: Vec<CatchClauseSegment>,
43    pub finally: Option<FinallyClauseSegment>,
44}
45
46impl Clone for DoTrySegment {
47    fn clone(&self) -> Self {
48        Self {
49            try_body: self.try_body.clone(),
50            catches: self.catches.clone(),
51            finally: self.finally.clone(),
52        }
53    }
54}
55
56/// Narrow outcome type for `run_finally_body` so the compiler enforces
57/// exhaustiveness at the two call sites instead of `unreachable!()`.
58/// This is a private, transient type; the `Stopped` exchange is boxed to keep
59/// the `Err` variant of `run_finally_body` small (clippy::result_large_err).
60enum FinallyOutcome {
61    Stopped(Box<Exchange>),
62    Failed(CamelError),
63    /// The finally `on_when` predicate itself failed; the typed error fails
64    /// the segment.
65    PredicateFailed(CamelError),
66}
67
68/// Run the finally body if present and on_when permits.
69/// Free function (not a method) to avoid borrow conflict with
70/// `self.catches.iter_mut()` inside the catch loop.
71/// The `FinallyOutcome` variants move the `Exchange` (the catch loop needs
72/// its state); boxing would rewrite the segment call chain for a lint
73/// threshold.
74#[allow(clippy::result_large_err)]
75async fn run_finally_body(
76    finally: &mut Option<FinallyClauseSegment>,
77    ex: Exchange,
78) -> Result<Exchange, FinallyOutcome> {
79    let Some(f) = finally.as_mut() else {
80        return Ok(ex);
81    };
82    if let Some(on_when) = &f.on_when {
83        match on_when.matches(&ex).await {
84            Ok(true) => {}
85            Ok(false) => return Ok(ex),
86            Err(err) => return Err(FinallyOutcome::PredicateFailed(err)),
87        }
88    }
89    match f.body.run(ex).await {
90        PipelineOutcome::Completed(e) => Ok(e),
91        PipelineOutcome::Stopped(e) => Err(FinallyOutcome::Stopped(Box::new(e))),
92        PipelineOutcome::Failed(e) => Err(FinallyOutcome::Failed(e)),
93    }
94}
95
96/// Surface `failure` after running finally.
97///
98/// Used for a failed catch predicate (the predicate error surfaced as the
99/// main failure), the no-catch-matched path, the Propagate / fail-closed
100/// path (the original try error), and the catch-body-failure path (the catch
101/// error is the surfaced failure).
102/// `failure` becomes the main failure (Camel parity: a throwing finally body
103/// restores it; Stop in finally still stops the outer route; a failed finally
104/// `on_when` predicate supersedes it).
105async fn fail_after_finally(
106    finally: &mut Option<FinallyClauseSegment>,
107    ex: Exchange,
108    failure: CamelError,
109) -> PipelineOutcome {
110    match run_finally_body(finally, ex).await {
111        Ok(_) => PipelineOutcome::Failed(failure),
112        Err(FinallyOutcome::Stopped(e)) => PipelineOutcome::Stopped(*e),
113        Err(FinallyOutcome::Failed(_finally_err)) => {
114            tracing::warn!(
115                error = %failure,
116                "doFinally threw; restoring previous error (Camel parity)"
117            );
118            PipelineOutcome::Failed(failure)
119        }
120        Err(FinallyOutcome::PredicateFailed(pred_err)) => PipelineOutcome::Failed(pred_err),
121    }
122}
123
124impl OutcomePipeline for DoTrySegment {
125    fn clone_box(&self) -> Box<dyn OutcomePipeline> {
126        Box::new(self.clone())
127    }
128
129    fn run<'a>(
130        &'a mut self,
131        mut exchange: Exchange,
132    ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
133        Box::pin(async move {
134            // Stale handled-marker protocol inherited from the deleted
135            // `DoTryService` (clear-on-entry; `Exchange::clear_error` does not
136            // touch HANDLED).
137            exchange.properties.remove(PROPERTY_EXCEPTION_HANDLED);
138            // Pre-clone for the "no catch matched" path; `exchange` itself is
139            // consumed by `try_body.run(...)` below.
140            let exchange_for_unmatched = exchange.branch_clone();
141
142            // 1. Run try_body. If Stopped, return immediately (skip catch AND finally).
143            let try_outcome = self.try_body.run(exchange).await;
144            let returned_ex = match try_outcome {
145                PipelineOutcome::Stopped(ex) => return PipelineOutcome::Stopped(ex),
146                PipelineOutcome::Completed(ex) => ex,
147                PipelineOutcome::Failed(err) => {
148                    // 2. try failed — try each catch in order. Walk the catch
149                    // chain starting from the failed try-exchange. On the first
150                    // matching catch whose `on_when` is true (or unset), run it.
151                    // A failed catch `when`/`on_when` predicate replaces the
152                    // original error (preserved as `cause`) and fails the scope.
153                    let mut current_ex = exchange_for_unmatched;
154                    current_ex.set_error(err.clone());
155                    // Distinguishes "a catch handled the error" (loop breaks
156                    // with `current_ex` = catch output) from "the loop
157                    // exhausted with no match" (must propagate the original).
158                    let mut catch_matched = false;
159                    for catch in self.catches.iter_mut() {
160                        let matched = match catch.matcher.matches(&err, &current_ex).await {
161                            Ok(m) => m,
162                            Err(pred_err) => {
163                                let chained = chain_predicate_error(pred_err, err);
164                                return fail_after_finally(&mut self.finally, current_ex, chained)
165                                    .await;
166                            }
167                        };
168                        if !matched {
169                            continue;
170                        }
171                        if let Some(on_when) = &catch.on_when {
172                            match on_when.matches(&current_ex).await {
173                                Ok(true) => {}
174                                Ok(false) => continue,
175                                Err(pred_err) => {
176                                    let chained = chain_predicate_error(pred_err, err);
177                                    return fail_after_finally(
178                                        &mut self.finally,
179                                        current_ex,
180                                        chained,
181                                    )
182                                    .await;
183                                }
184                            }
185                        }
186                        // Pre-clone for the catch-body-failure path:
187                        // `PipelineOutcome::Failed` drops the exchange, so the
188                        // finally body still needs a pre-catch snapshot (same
189                        // pattern as `exchange_for_unmatched` above).
190                        let catch_input_ex = current_ex.branch_clone();
191                        match catch.body.run(current_ex).await {
192                            // Stop in catch: skip finally AND outer route halts.
193                            PipelineOutcome::Stopped(stopped_ex) => {
194                                return PipelineOutcome::Stopped(stopped_ex);
195                            }
196                            // Catch handled — exit catch chain with this exchange.
197                            PipelineOutcome::Completed(next) => {
198                                match catch.disposition {
199                                    ExceptionDisposition::Handled => {
200                                        current_ex = next;
201                                        catch_matched = true;
202                                        break;
203                                    }
204                                    ExceptionDisposition::Continued => {
205                                        current_ex = next;
206                                        catch_matched = true;
207                                        break;
208                                    }
209                                    // Propagate and any future variant run finally then
210                                    // surface the original error (fail-closed).
211                                    _ => {
212                                        return fail_after_finally(&mut self.finally, next, err)
213                                            .await;
214                                    }
215                                }
216                            }
217                            // Catch-body Failed: Java try/catch/finally
218                            // parity (JLS §14.20.2) — the finally body runs
219                            // exactly once even when the catch body fails,
220                            // and the catch error remains the surfaced
221                            // failure. No catch-of-catch: the doTry island
222                            // invariant (ADR-0025 #4) is unchanged, so the
223                            // catch chain is NOT re-entered.
224                            PipelineOutcome::Failed(catch_err) => {
225                                // Sealed failure envelope: the catch error
226                                // stays the main error (returned below);
227                                // the original try error is surfaced
228                                // through the unconditional warn record
229                                // and, when a span is active, the span
230                                // error record. No new span is created.
231                                tracing::warn!(
232                                    original_error = %err,
233                                    catch_error = %catch_err,
234                                    "do_try catch block failed; catch error supersedes original"
235                                );
236                                record_span_error(&catch_err);
237                                return fail_after_finally(
238                                    &mut self.finally,
239                                    catch_input_ex,
240                                    catch_err,
241                                )
242                                .await;
243                            }
244                        }
245                    }
246                    if catch_matched {
247                        // A catch handled the error: continue to the shared
248                        // finally path and return its exchange as Completed.
249                        current_ex
250                    } else {
251                        // No catch matched: run finally, then propagate the
252                        // original try error as `Failed`. Falling through to the
253                        // shared finally path would return `Completed` and
254                        // swallow the error, letting the route continue past
255                        // the scope (the segment is the only doTry runtime).
256                        return fail_after_finally(&mut self.finally, current_ex, err).await;
257                    }
258                }
259            };
260            // 3. Run finally if present (skip if try/catch returned Stopped —
261            // already returned above; catch-body failures flow through
262            // `fail_after_finally` and return there).
263            match run_finally_body(&mut self.finally, returned_ex).await {
264                Ok(ex) => PipelineOutcome::Completed(ex),
265                Err(FinallyOutcome::Stopped(e)) => PipelineOutcome::Stopped(*e),
266                Err(FinallyOutcome::Failed(finally_err)) => {
267                    tracing::warn!(
268                        error = %finally_err,
269                        "doFinally threw during/after catch; surfacing finally error"
270                    );
271                    PipelineOutcome::Failed(finally_err)
272                }
273                // Failed finally `on_when` predicate: the typed error fails
274                // the segment.
275                Err(FinallyOutcome::PredicateFailed(pred_err)) => PipelineOutcome::Failed(pred_err),
276            }
277        })
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use crate::do_try::CatchMatcher;
285    use crate::test_log_capture::{capture_debugs_with_span_records, captured_field, record_field};
286    use camel_api::pipeline_outcome::PipelineOutcome;
287    use std::sync::Arc;
288    use std::sync::atomic::{AtomicU32, Ordering};
289
290    // ── Helpers for DoTrySegment tests ──
291
292    struct CompleteSegment;
293
294    impl OutcomePipeline for CompleteSegment {
295        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
296            Box::new(CompleteSegment)
297        }
298        fn run<'a>(
299            &'a mut self,
300            exchange: Exchange,
301        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
302            Box::pin(async move { PipelineOutcome::Completed(exchange) })
303        }
304    }
305
306    fn seg_complete() -> camel_api::OutcomeSegment {
307        camel_api::OutcomeSegment::new(Box::new(CompleteSegment))
308    }
309
310    struct FailSegment(CamelError);
311
312    impl OutcomePipeline for FailSegment {
313        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
314            Box::new(FailSegment(self.0.clone()))
315        }
316        fn run<'a>(
317            &'a mut self,
318            _exchange: Exchange,
319        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
320            let e = self.0.clone();
321            Box::pin(async move { PipelineOutcome::Failed(e) })
322        }
323    }
324
325    fn seg_fail(err: CamelError) -> camel_api::OutcomeSegment {
326        camel_api::OutcomeSegment::new(Box::new(FailSegment(err)))
327    }
328
329    struct MutateThenStop {
330        mutator: Arc<dyn Fn(&mut Exchange) + Send + Sync>,
331    }
332
333    impl OutcomePipeline for MutateThenStop {
334        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
335            Box::new(MutateThenStop {
336                mutator: Arc::clone(&self.mutator),
337            })
338        }
339        fn run<'a>(
340            &'a mut self,
341            mut exchange: Exchange,
342        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
343            let m = Arc::clone(&self.mutator);
344            Box::pin(async move {
345                m(&mut exchange);
346                PipelineOutcome::Stopped(exchange)
347            })
348        }
349    }
350
351    fn seg_stop_with(
352        mutator: impl Fn(&mut Exchange) + Send + Sync + 'static,
353    ) -> camel_api::OutcomeSegment {
354        camel_api::OutcomeSegment::new(Box::new(MutateThenStop {
355            mutator: Arc::new(mutator),
356        }))
357    }
358
359    struct RecordCall {
360        counter: Arc<AtomicU32>,
361    }
362
363    impl OutcomePipeline for RecordCall {
364        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
365            Box::new(RecordCall {
366                counter: Arc::clone(&self.counter),
367            })
368        }
369        fn run<'a>(
370            &'a mut self,
371            exchange: Exchange,
372        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
373            let c = Arc::clone(&self.counter);
374            Box::pin(async move {
375                c.fetch_add(1, Ordering::SeqCst);
376                PipelineOutcome::Completed(exchange)
377            })
378        }
379    }
380
381    fn seg_record(counter: Arc<AtomicU32>) -> camel_api::OutcomeSegment {
382        camel_api::OutcomeSegment::new(Box::new(RecordCall { counter }))
383    }
384
385    struct CountThenFail {
386        counter: Arc<AtomicU32>,
387        err: CamelError,
388    }
389
390    impl OutcomePipeline for CountThenFail {
391        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
392            Box::new(CountThenFail {
393                counter: Arc::clone(&self.counter),
394                err: self.err.clone(),
395            })
396        }
397        fn run<'a>(
398            &'a mut self,
399            _exchange: Exchange,
400        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
401            let c = Arc::clone(&self.counter);
402            let e = self.err.clone();
403            Box::pin(async move {
404                c.fetch_add(1, Ordering::SeqCst);
405                PipelineOutcome::Failed(e)
406            })
407        }
408    }
409
410    fn seg_count_then_fail(counter: Arc<AtomicU32>, err: CamelError) -> camel_api::OutcomeSegment {
411        camel_api::OutcomeSegment::new(Box::new(CountThenFail { counter, err }))
412    }
413
414    struct CountThenStop {
415        counter: Arc<AtomicU32>,
416        mutator: Arc<dyn Fn(&mut Exchange) + Send + Sync>,
417    }
418
419    impl OutcomePipeline for CountThenStop {
420        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
421            Box::new(CountThenStop {
422                counter: Arc::clone(&self.counter),
423                mutator: Arc::clone(&self.mutator),
424            })
425        }
426        fn run<'a>(
427            &'a mut self,
428            mut exchange: Exchange,
429        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
430            let c = Arc::clone(&self.counter);
431            let m = Arc::clone(&self.mutator);
432            Box::pin(async move {
433                c.fetch_add(1, Ordering::SeqCst);
434                m(&mut exchange);
435                PipelineOutcome::Stopped(exchange)
436            })
437        }
438    }
439
440    fn seg_count_then_stop(
441        counter: Arc<AtomicU32>,
442        mutator: impl Fn(&mut Exchange) + Send + Sync + 'static,
443    ) -> camel_api::OutcomeSegment {
444        camel_api::OutcomeSegment::new(Box::new(CountThenStop {
445            counter,
446            mutator: Arc::new(mutator),
447        }))
448    }
449
450    // ── 5 New tests for DoTrySegment (ADR-0025) ──
451
452    #[tokio::test]
453    async fn stop_inside_try_skips_catch_and_finally() {
454        let catch_call = Arc::new(AtomicU32::new(0));
455        let finally_call = Arc::new(AtomicU32::new(0));
456
457        let mut seg = DoTrySegment {
458            try_body: seg_stop_with(|ex| {
459                ex.set_property("mutated", camel_api::Value::Bool(true));
460            }),
461            catches: vec![CatchClauseSegment {
462                matcher: CatchMatcher::ByVariant(vec!["*".into()]),
463                on_when: None,
464                body: seg_record(catch_call.clone()),
465                disposition: ExceptionDisposition::Handled,
466            }],
467            finally: Some(FinallyClauseSegment {
468                on_when: None,
469                body: seg_record(finally_call.clone()),
470            }),
471        };
472
473        let result = seg.run(Exchange::default()).await;
474        match result {
475            PipelineOutcome::Stopped(ex) => {
476                assert_eq!(
477                    ex.properties.get("mutated"),
478                    Some(&camel_api::Value::Bool(true)),
479                    "try body mutation must be preserved in Stopped exchange"
480                );
481            }
482            other => panic!("expected Stopped, got {:?}", other),
483        }
484        assert_eq!(
485            catch_call.load(Ordering::SeqCst),
486            0,
487            "catch must NOT run when try stops"
488        );
489        assert_eq!(
490            finally_call.load(Ordering::SeqCst),
491            0,
492            "finally must NOT run when try stops"
493        );
494    }
495
496    #[tokio::test]
497    async fn stop_inside_catch_skips_finally() {
498        let finally_call = Arc::new(AtomicU32::new(0));
499
500        let mut seg = DoTrySegment {
501            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
502            catches: vec![CatchClauseSegment {
503                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
504                on_when: None,
505                body: seg_stop_with(|ex| {
506                    ex.set_property("catch_mutated", camel_api::Value::Bool(true));
507                }),
508                disposition: ExceptionDisposition::Handled,
509            }],
510            finally: Some(FinallyClauseSegment {
511                on_when: None,
512                body: seg_record(finally_call.clone()),
513            }),
514        };
515
516        let result = seg.run(Exchange::default()).await;
517        match result {
518            PipelineOutcome::Stopped(ex) => {
519                assert_eq!(
520                    ex.properties.get("catch_mutated"),
521                    Some(&camel_api::Value::Bool(true)),
522                    "catch body mutation must be preserved in Stopped exchange"
523                );
524            }
525            other => panic!("expected Stopped, got {:?}", other),
526        }
527        assert_eq!(
528            finally_call.load(Ordering::SeqCst),
529            0,
530            "finally must NOT run when catch stops"
531        );
532    }
533
534    #[tokio::test]
535    async fn stop_inside_finally_stops_outer_route() {
536        let mut seg = DoTrySegment {
537            try_body: seg_complete(),
538            catches: vec![],
539            finally: Some(FinallyClauseSegment {
540                on_when: None,
541                body: seg_stop_with(|ex| {
542                    ex.set_property("finally_mutated", camel_api::Value::Bool(true));
543                }),
544            }),
545        };
546
547        let result = seg.run(Exchange::default()).await;
548        match result {
549            PipelineOutcome::Stopped(ex) => {
550                assert_eq!(
551                    ex.properties.get("finally_mutated"),
552                    Some(&camel_api::Value::Bool(true)),
553                    "finally body mutation must be preserved in Stopped exchange"
554                );
555            }
556            other => panic!("expected Stopped, got {:?}", other),
557        }
558    }
559
560    #[tokio::test]
561    async fn catch_on_when_false_falls_through_to_next_catch() {
562        let first_call = Arc::new(AtomicU32::new(0));
563        let second_call = Arc::new(AtomicU32::new(0));
564
565        let mut seg = DoTrySegment {
566            try_body: seg_fail(CamelError::Io("disk err".into())),
567            catches: vec![
568                CatchClauseSegment {
569                    matcher: CatchMatcher::ByVariant(vec!["Io".into()]),
570                    on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
571                    body: seg_record(first_call.clone()),
572                    disposition: ExceptionDisposition::Handled,
573                },
574                CatchClauseSegment {
575                    matcher: CatchMatcher::ByVariant(vec!["*".into()]),
576                    on_when: None,
577                    body: seg_record(second_call.clone()),
578                    disposition: ExceptionDisposition::Handled,
579                },
580            ],
581            finally: None,
582        };
583
584        let result = seg.run(Exchange::default()).await;
585        assert!(
586            matches!(result, PipelineOutcome::Completed(_)),
587            "expected Completed after second catch"
588        );
589        assert_eq!(
590            first_call.load(Ordering::SeqCst),
591            0,
592            "first catch must NOT fire (on_when=false)"
593        );
594        assert_eq!(
595            second_call.load(Ordering::SeqCst),
596            1,
597            "second catch must fire"
598        );
599    }
600
601    #[tokio::test]
602    async fn finally_on_when_false_skips_finally_entirely() {
603        let finally_call = Arc::new(AtomicU32::new(0));
604        let mut ex = Exchange::default();
605        ex.set_property("try_set", camel_api::Value::Bool(true));
606
607        let mut seg = DoTrySegment {
608            try_body: seg_complete(),
609            catches: vec![],
610            finally: Some(FinallyClauseSegment {
611                on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
612                body: seg_record(finally_call.clone()),
613            }),
614        };
615
616        let result = seg.run(ex).await;
617        match result {
618            PipelineOutcome::Completed(ex) => {
619                assert_eq!(
620                    ex.properties.get("try_set"),
621                    Some(&camel_api::Value::Bool(true)),
622                    "exchange state from try must be preserved"
623                );
624            }
625            other => panic!("expected Completed, got {:?}", other),
626        }
627        assert_eq!(
628            finally_call.load(Ordering::SeqCst),
629            0,
630            "finally must NOT run when on_when=false"
631        );
632    }
633
634    // ── Catch-body failure envelope (compiled-segment path) ──
635
636    fn catch_fails_segment() -> DoTrySegment {
637        DoTrySegment {
638            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
639            catches: vec![CatchClauseSegment {
640                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
641                on_when: None,
642                body: seg_fail(CamelError::Io("catch-fail".into())),
643                disposition: ExceptionDisposition::Handled,
644            }],
645            finally: None,
646        }
647    }
648
649    #[test]
650    fn catch_body_failure_returns_catch_err_and_marks_span() {
651        let mut seg = catch_fails_segment();
652        let (result, captured, span_records) = capture_debugs_with_span_records(|| {
653            // Declared `error` field so record_span_error's record lands.
654            let span = tracing::info_span!("dotry_seg_test", error = tracing::field::Empty);
655            let _guard = span.enter();
656            tokio::runtime::Builder::new_current_thread()
657                .enable_all()
658                .build()
659                .expect("current-thread runtime")
660                .block_on(async { seg.run(Exchange::default()).await })
661        });
662
663        assert!(
664            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
665            "catch failure must surface the catch error as Failed(Io), got: {result:?}"
666        );
667        // The span recorded the `error` field with the CATCH error.
668        // Structured field lookup: substring `error=` would also match
669        // `original_error=` suffixes.
670        assert!(
671            span_records.iter().any(|line| {
672                captured_field(line, "error").is_some_and(|v| v.contains("catch-fail"))
673            }),
674            "expected span error record carrying the catch error, span records: {span_records:?}"
675        );
676        let original = record_field(&captured, "do_try catch block failed", "original_error")
677            .unwrap_or_else(|| {
678                panic!(
679                    "envelope record missing original_error field under active span, captured: {captured:?}"
680                )
681            });
682        assert!(
683            original.contains("orig"),
684            "original_error must carry the original error under an active span, got: {original}"
685        );
686    }
687
688    #[test]
689    fn catch_body_failure_emits_envelope_log() {
690        let mut seg = catch_fails_segment();
691        let (result, captured, _span_records) = capture_debugs_with_span_records(|| {
692            tokio::runtime::Builder::new_current_thread()
693                .enable_all()
694                .build()
695                .expect("current-thread runtime")
696                .block_on(async { seg.run(Exchange::default()).await })
697        });
698
699        assert!(
700            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
701            "catch failure must surface the catch error as Failed(Io), got: {result:?}"
702        );
703        // Structured field lookup on the envelope record, not message
704        // formatting.
705        let original = record_field(&captured, "do_try catch block failed", "original_error")
706            .unwrap_or_else(|| {
707                panic!("envelope record missing original_error field, captured: {captured:?}")
708            });
709        let catch = record_field(&captured, "do_try catch block failed", "catch_error")
710            .unwrap_or_else(|| {
711                panic!("envelope record missing catch_error field, captured: {captured:?}")
712            });
713        assert!(
714            original.contains("orig"),
715            "original_error must carry the original error, got: {original}"
716        );
717        assert!(
718            catch.contains("catch-fail"),
719            "catch_error must carry the catch error, got: {catch}"
720        );
721    }
722
723    // ── Fallible predicate path (language-value-boundary task 1.4) ──
724
725    use camel_api::{ExpressionErrorClass, FilterPredicate, PredicateSource};
726
727    fn expression_failed() -> CamelError {
728        CamelError::ExpressionFailed {
729            language: "rhai".to_string(),
730            route_id: "r1".to_string(),
731            step_id: "step#0".to_string(),
732            verb: "on_when".to_string(),
733            class: ExpressionErrorClass::Runtime,
734            position: None,
735            conversion: None,
736            cause: None,
737        }
738    }
739
740    fn async_err_predicate(err: CamelError) -> PredicateSource {
741        PredicateSource::Async(Arc::new(move |_: &Exchange| {
742            let err = err.clone();
743            Box::pin(async move { Err(err) }) as camel_api::BoxBoolFuture
744        }))
745    }
746
747    #[tokio::test]
748    async fn finally_on_when_predicate_error_fails_segment() {
749        let finally_call = Arc::new(AtomicU32::new(0));
750        let mut seg = DoTrySegment {
751            try_body: seg_complete(),
752            catches: vec![],
753            finally: Some(FinallyClauseSegment {
754                on_when: Some(async_err_predicate(expression_failed())),
755                body: seg_record(finally_call.clone()),
756            }),
757        };
758
759        let result = seg.run(Exchange::default()).await;
760        match result {
761            PipelineOutcome::Failed(CamelError::ExpressionFailed { .. }) => {}
762            other => panic!("expected Failed(ExpressionFailed), got {other:?}"),
763        }
764        assert_eq!(
765            finally_call.load(Ordering::SeqCst),
766            0,
767            "finally body must not run when its on_when predicate errors"
768        );
769    }
770
771    // ── No-catch-matched path (mission 353) ──
772
773    /// doTry with no matching catch must run finally and propagate the
774    /// original try error as `Failed` (the segment is the only doTry runtime).
775    /// Guards against regressing back to `Completed(bugged_swallow)`.
776    #[tokio::test]
777    async fn no_clause_matches_runs_finally_and_propagates_original() {
778        let catch_call = Arc::new(AtomicU32::new(0));
779        let finally_call = Arc::new(AtomicU32::new(0));
780
781        let mut seg = DoTrySegment {
782            try_body: seg_fail(CamelError::EndpointCreationFailed(
783                "direct endpoint 'direct:does-not-exist' not registered".into(),
784            )),
785            catches: vec![CatchClauseSegment {
786                matcher: CatchMatcher::ByVariant(vec!["Io".into()]),
787                on_when: None,
788                body: seg_record(catch_call.clone()),
789                disposition: ExceptionDisposition::Handled,
790            }],
791            finally: Some(FinallyClauseSegment {
792                on_when: None,
793                body: seg_record(finally_call.clone()),
794            }),
795        };
796
797        let result = seg.run(Exchange::default()).await;
798        match result {
799            PipelineOutcome::Failed(CamelError::EndpointCreationFailed(msg)) => {
800                assert!(
801                    msg.contains("does-not-exist"),
802                    "propagated error must be the original try error, got: {msg}"
803                );
804            }
805            other => {
806                panic!("no catch matched: expected Failed(EndpointCreationFailed), got {other:?}")
807            }
808        }
809        assert_eq!(
810            finally_call.load(Ordering::SeqCst),
811            1,
812            "finally must run exactly once when no catch matches"
813        );
814        assert_eq!(
815            catch_call.load(Ordering::SeqCst),
816            0,
817            "the unmatched catch body must not run"
818        );
819    }
820    // ── Ported from the deleted Tower doTry service (no coverage loss) ──
821
822    use camel_language_api::{EvalMeta, LanguageError, to_expression_failed};
823
824    fn catch_variant(names: &[&str], body: camel_api::OutcomeSegment) -> CatchClauseSegment {
825        catch_variant_with(names, body, ExceptionDisposition::Handled)
826    }
827
828    fn catch_variant_with(
829        names: &[&str],
830        body: camel_api::OutcomeSegment,
831        disposition: ExceptionDisposition,
832    ) -> CatchClauseSegment {
833        CatchClauseSegment {
834            matcher: CatchMatcher::ByVariant(names.iter().map(|n| (*n).to_string()).collect()),
835            on_when: None,
836            body,
837            disposition,
838        }
839    }
840
841    fn finally_seg(body: camel_api::OutcomeSegment) -> FinallyClauseSegment {
842        FinallyClauseSegment {
843            on_when: None,
844            body,
845        }
846    }
847
848    #[tokio::test]
849    async fn happy_path_try_succeeds_finally_runs() {
850        let finally_flag = Arc::new(AtomicU32::new(0));
851        let mut seg = DoTrySegment {
852            try_body: seg_complete(),
853            catches: vec![],
854            finally: Some(finally_seg(seg_record(finally_flag.clone()))),
855        };
856
857        let result = seg.run(Exchange::default()).await;
858        assert!(
859            matches!(result, PipelineOutcome::Completed(_)),
860            "try success must complete, got {result:?}"
861        );
862        assert_eq!(finally_flag.load(Ordering::SeqCst), 1);
863    }
864
865    #[tokio::test]
866    async fn catch_by_variant_handled_returns_ok() {
867        let mut seg = DoTrySegment {
868            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
869            catches: vec![catch_variant(&["ProcessorError"], seg_complete())],
870            finally: None,
871        };
872
873        let result = seg.run(Exchange::default()).await;
874        assert!(
875            matches!(result, PipelineOutcome::Completed(_)),
876            "Handled must return Completed, got {result:?}"
877        );
878    }
879
880    #[tokio::test]
881    async fn catch_by_variant_propagate_runs_side_effects_and_rethrows() {
882        let side_effect = Arc::new(AtomicU32::new(0));
883        let mut seg = DoTrySegment {
884            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
885            catches: vec![catch_variant_with(
886                &["ProcessorError"],
887                seg_record(side_effect.clone()),
888                ExceptionDisposition::Propagate,
889            )],
890            finally: None,
891        };
892
893        let result = seg.run(Exchange::default()).await;
894        assert!(
895            matches!(
896                result,
897                PipelineOutcome::Failed(CamelError::ProcessorError(_))
898            ),
899            "Propagate must rethrow the original error, got {result:?}"
900        );
901        assert_eq!(
902            side_effect.load(Ordering::SeqCst),
903            1,
904            "catch branch must have run for side-effects"
905        );
906    }
907
908    #[tokio::test]
909    async fn catch_by_predicate_matches_via_exception_kind() {
910        let predicate = FilterPredicate::new(|ex: &Exchange| {
911            ex.properties
912                .get(camel_api::exchange::PROPERTY_EXCEPTION_KIND)
913                .map(|v| matches!(v, camel_api::Value::String(s) if s == "io"))
914                .unwrap_or(false)
915        });
916        let mut seg = DoTrySegment {
917            try_body: seg_fail(CamelError::Io("disk full".into())),
918            catches: vec![CatchClauseSegment {
919                matcher: CatchMatcher::Predicate(PredicateSource::Sync(predicate)),
920                on_when: None,
921                body: seg_complete(),
922                disposition: ExceptionDisposition::Handled,
923            }],
924            finally: None,
925        };
926
927        let result = seg.run(Exchange::default()).await;
928        assert!(
929            matches!(result, PipelineOutcome::Completed(_)),
930            "Predicate matcher must catch the error and Handled must return Completed, got {result:?}"
931        );
932    }
933
934    #[tokio::test]
935    async fn first_match_wins_subsequent_clauses_not_evaluated() {
936        let first_call = Arc::new(AtomicU32::new(0));
937        let second_call = Arc::new(AtomicU32::new(0));
938        let mut seg = DoTrySegment {
939            try_body: seg_fail(CamelError::Io("err".into())),
940            catches: vec![
941                catch_variant(&["Io"], seg_record(first_call.clone())),
942                catch_variant(&["*"], seg_record(second_call.clone())),
943            ],
944            finally: None,
945        };
946
947        let _ = seg.run(Exchange::default()).await;
948        assert_eq!(first_call.load(Ordering::SeqCst), 1);
949        assert_eq!(second_call.load(Ordering::SeqCst), 0);
950    }
951
952    #[tokio::test]
953    async fn catch_branch_throws_new_error_wins() {
954        let mut seg = DoTrySegment {
955            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
956            catches: vec![catch_variant(
957                &["ProcessorError"],
958                seg_fail(CamelError::Io("catch-fail".into())),
959            )],
960            finally: None,
961        };
962
963        let result = seg.run(Exchange::default()).await;
964        assert!(
965            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
966            "catch error must win over the try error, got {result:?}"
967        );
968    }
969
970    #[tokio::test]
971    async fn finally_throws_with_no_previous_error_propagates_finally_error() {
972        let mut seg = DoTrySegment {
973            try_body: seg_complete(),
974            catches: vec![],
975            finally: Some(finally_seg(seg_fail(CamelError::Config("fin".into())))),
976        };
977
978        let result = seg.run(Exchange::default()).await;
979        assert!(
980            matches!(result, PipelineOutcome::Failed(CamelError::Config(_))),
981            "finally error must propagate when no previous error exists, got {result:?}"
982        );
983    }
984
985    #[tokio::test]
986    async fn finally_throws_with_previous_error_restores_previous() {
987        let mut seg = DoTrySegment {
988            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
989            catches: vec![],
990            finally: Some(finally_seg(seg_fail(CamelError::Config("fin".into())))),
991        };
992
993        let result = seg.run(Exchange::default()).await;
994        assert!(
995            matches!(
996                result,
997                PipelineOutcome::Failed(CamelError::ProcessorError(_))
998            ),
999            "previous error must be restored when finally throws (Camel parity), got {result:?}"
1000        );
1001    }
1002
1003    #[tokio::test]
1004    async fn stale_handled_marker_cleared_on_entry() {
1005        let mut ex = Exchange::default();
1006        ex.set_property(
1007            camel_api::exchange::PROPERTY_EXCEPTION_HANDLED,
1008            camel_api::Value::Bool(true),
1009        );
1010        ex.set_error(CamelError::ProcessorError("stale".into()));
1011        let mut seg = DoTrySegment {
1012            try_body: seg_complete(),
1013            catches: vec![],
1014            finally: None,
1015        };
1016
1017        let result = seg.run(ex).await;
1018        match result {
1019            PipelineOutcome::Completed(ex) => assert!(
1020                !ex.properties
1021                    .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_HANDLED),
1022                "stale CamelExceptionHandled must be cleared on entry"
1023            ),
1024            other => panic!("expected Completed, got {other:?}"),
1025        }
1026    }
1027
1028    #[tokio::test]
1029    async fn nested_do_try_inner_catch_does_not_leak_to_outer() {
1030        let inner = DoTrySegment {
1031            try_body: seg_fail(CamelError::Io("inner".into())),
1032            catches: vec![catch_variant(&["Io"], seg_complete())],
1033            finally: None,
1034        };
1035        let mut outer = DoTrySegment {
1036            try_body: camel_api::OutcomeSegment::new(Box::new(inner)),
1037            catches: vec![catch_variant(&["Io"], seg_complete())],
1038            finally: None,
1039        };
1040
1041        let result = outer.run(Exchange::default()).await;
1042        assert!(
1043            matches!(result, PipelineOutcome::Completed(_)),
1044            "outer must see Completed because inner handled its own error, got {result:?}"
1045        );
1046    }
1047
1048    #[tokio::test]
1049    async fn catch_all_only_fires_when_no_specific_clause_matches() {
1050        let processor_call = Arc::new(AtomicU32::new(0));
1051        let catch_all_call = Arc::new(AtomicU32::new(0));
1052        let mut seg = DoTrySegment {
1053            try_body: seg_fail(CamelError::Io("err".into())),
1054            catches: vec![
1055                catch_variant(&["ProcessorError"], seg_record(processor_call.clone())),
1056                catch_variant(&["*"], seg_record(catch_all_call.clone())),
1057            ],
1058            finally: None,
1059        };
1060
1061        let _ = seg.run(Exchange::default()).await;
1062        assert_eq!(
1063            processor_call.load(Ordering::SeqCst),
1064            0,
1065            "specific ProcessorError clause must not fire on Io error"
1066        );
1067        assert_eq!(
1068            catch_all_call.load(Ordering::SeqCst),
1069            1,
1070            "catch-all clause must fire when no specific clause matches"
1071        );
1072    }
1073
1074    /// Java try/catch/finally parity (JLS §14.20.2): a failing catch body
1075    /// does not skip finally, and the catch error remains the surfaced
1076    /// failure. This rebuilds the catch-and-finally coverage lost with the
1077    /// deleted builder-only `DoTryService`.
1078    #[tokio::test]
1079    async fn catch_body_failure_runs_finally_once_then_returns_catch_err() {
1080        let finally_flag = Arc::new(AtomicU32::new(0));
1081        let mut seg = DoTrySegment {
1082            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1083            catches: vec![catch_variant(
1084                &["ProcessorError"],
1085                seg_fail(CamelError::Io("catch-fail".into())),
1086            )],
1087            finally: Some(finally_seg(seg_record(finally_flag.clone()))),
1088        };
1089
1090        let result = seg.run(Exchange::default()).await;
1091        assert!(
1092            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
1093            "catch_err must propagate (not original ProcessorError), got {result:?}"
1094        );
1095        assert_eq!(
1096            finally_flag.load(Ordering::SeqCst),
1097            1,
1098            "finally must run exactly once even when the catch body fails (Java try/catch/finally parity)"
1099        );
1100    }
1101
1102    /// Real exercise of the finally/catch parity rule: the finally body runs
1103    /// (and throws) even when the catch body fails, and the catch error still
1104    /// wins over the finally error (Camel parity: a throwing finally restores
1105    /// the previous error). Before the catch-body-failure path ran finally,
1106    /// this test passed vacuously.
1107    #[tokio::test]
1108    async fn catch_throws_and_throwing_finally_still_returns_catch_err() {
1109        let finally_flag = Arc::new(AtomicU32::new(0));
1110        let mut seg = DoTrySegment {
1111            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1112            catches: vec![catch_variant(
1113                &["ProcessorError"],
1114                seg_fail(CamelError::Io("catch-fail".into())),
1115            )],
1116            finally: Some(finally_seg(seg_count_then_fail(
1117                finally_flag.clone(),
1118                CamelError::Config("fin-fail".into()),
1119            ))),
1120        };
1121
1122        let result = seg.run(Exchange::default()).await;
1123        assert!(
1124            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
1125            "catch_err (Io) must be returned over finally_err (Config), got {result:?}"
1126        );
1127        assert_eq!(
1128            finally_flag.load(Ordering::SeqCst),
1129            1,
1130            "finally must run exactly once even when its own body fails"
1131        );
1132    }
1133
1134    /// Stop in finally takes precedence over the pending catch failure: the
1135    /// outer route stops with the finally exchange (mutation preserved), and
1136    /// the finally body still ran exactly once. Pins the `Stopped` arm of
1137    /// `fail_after_finally` on the catch-body-failure path.
1138    #[tokio::test]
1139    async fn catch_body_failure_then_finally_stops_stops_outer_route() {
1140        let finally_flag = Arc::new(AtomicU32::new(0));
1141        let mut seg = DoTrySegment {
1142            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1143            catches: vec![catch_variant(
1144                &["ProcessorError"],
1145                seg_fail(CamelError::Io("catch-fail".into())),
1146            )],
1147            finally: Some(finally_seg(seg_count_then_stop(
1148                finally_flag.clone(),
1149                |ex| {
1150                    ex.set_property("finally_stopped_marker", camel_api::Value::Bool(true));
1151                },
1152            ))),
1153        };
1154
1155        let result = seg.run(Exchange::default()).await;
1156        match result {
1157            PipelineOutcome::Stopped(ex) => {
1158                assert_eq!(
1159                    ex.properties.get("finally_stopped_marker"),
1160                    Some(&camel_api::Value::Bool(true)),
1161                    "finally exchange mutation must be preserved in Stopped"
1162                );
1163            }
1164            other => panic!("expected Stopped, got {other:?}"),
1165        }
1166        assert_eq!(
1167            finally_flag.load(Ordering::SeqCst),
1168            1,
1169            "finally must run exactly once before the outer route stops"
1170        );
1171    }
1172
1173    #[tokio::test]
1174    async fn finally_on_when_false_with_previous_error_still_propagates_original() {
1175        let finally_flag = Arc::new(AtomicU32::new(0));
1176        let mut seg = DoTrySegment {
1177            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1178            catches: vec![],
1179            finally: Some(FinallyClauseSegment {
1180                on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
1181                body: seg_record(finally_flag.clone()),
1182            }),
1183        };
1184
1185        let result = seg.run(Exchange::default()).await;
1186        assert!(
1187            matches!(
1188                result,
1189                PipelineOutcome::Failed(CamelError::ProcessorError(_))
1190            ),
1191            "original error must propagate even when finally_on_when skips finally, got {result:?}"
1192        );
1193        assert_eq!(
1194            finally_flag.load(Ordering::SeqCst),
1195            0,
1196            "doFinally must NOT run when on_when returns false"
1197        );
1198    }
1199
1200    #[tokio::test]
1201    async fn catch_throws_under_propagate_disposition_returns_catch_err() {
1202        let mut seg = DoTrySegment {
1203            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1204            catches: vec![catch_variant_with(
1205                &["ProcessorError"],
1206                seg_fail(CamelError::Io("catch-fail".into())),
1207                ExceptionDisposition::Propagate,
1208            )],
1209            finally: None,
1210        };
1211
1212        let result = seg.run(Exchange::default()).await;
1213        assert!(
1214            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
1215            "Propagate-disposition catch failure must surface the catch error, got {result:?}"
1216        );
1217    }
1218
1219    #[tokio::test]
1220    async fn catch_when_predicate_error_chains_original() {
1221        let mut seg = DoTrySegment {
1222            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
1223            catches: vec![CatchClauseSegment {
1224                matcher: CatchMatcher::Predicate(async_err_predicate(expression_failed())),
1225                on_when: None,
1226                body: seg_complete(),
1227                disposition: ExceptionDisposition::Handled,
1228            }],
1229            finally: None,
1230        };
1231
1232        let result = seg.run(Exchange::default()).await;
1233        match result {
1234            PipelineOutcome::Failed(CamelError::ExpressionFailed {
1235                cause: Some(cause), ..
1236            }) => {
1237                assert!(
1238                    cause.to_string().contains("boom"),
1239                    "cause must carry the original error, got: {cause}"
1240                );
1241            }
1242            other => panic!("expected Failed(ExpressionFailed) with chained cause, got {other:?}"),
1243        }
1244    }
1245
1246    #[tokio::test]
1247    async fn catch_on_when_predicate_error_chains_original() {
1248        let mut seg = DoTrySegment {
1249            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
1250            catches: vec![CatchClauseSegment {
1251                matcher: CatchMatcher::ByVariant(vec!["*".into()]),
1252                on_when: Some(async_err_predicate(expression_failed())),
1253                body: seg_complete(),
1254                disposition: ExceptionDisposition::Handled,
1255            }],
1256            finally: None,
1257        };
1258
1259        let result = seg.run(Exchange::default()).await;
1260        match result {
1261            PipelineOutcome::Failed(CamelError::ExpressionFailed {
1262                cause: Some(cause), ..
1263            }) => {
1264                assert!(
1265                    cause.to_string().contains("boom"),
1266                    "cause must carry the original error, got: {cause}"
1267                );
1268            }
1269            other => panic!("expected Failed(ExpressionFailed) with chained cause, got {other:?}"),
1270        }
1271    }
1272
1273    // ── Mapper-generated cause replacement (ported from do_try.rs) ──
1274
1275    fn caller_diagnostic_failed(cause: CamelError) -> CamelError {
1276        CamelError::ExpressionFailed {
1277            language: "rhai".to_string(),
1278            route_id: "r1".to_string(),
1279            step_id: "s1".to_string(),
1280            verb: "when".to_string(),
1281            class: ExpressionErrorClass::Runtime,
1282            position: None,
1283            conversion: None,
1284            cause: Some(Box::new(cause)),
1285        }
1286    }
1287
1288    #[test]
1289    fn chain_replaces_mapper_generated_cause() {
1290        let meta = EvalMeta {
1291            language: "xpath".into(),
1292            route_id: "r1".into(),
1293            step_id: "s1".into(),
1294            verb: "when".into(),
1295            target: None,
1296        };
1297        let mapper_err = to_expression_failed(
1298            LanguageError::EvalFailure {
1299                class: ExpressionErrorClass::Parse,
1300                position: None,
1301                detail: Some("body is not valid XML".into()),
1302            },
1303            &meta,
1304        );
1305
1306        let result = chain_predicate_error(mapper_err, CamelError::ProcessorError("boom".into()));
1307
1308        match result {
1309            CamelError::ExpressionFailed {
1310                cause: Some(cause), ..
1311            } => {
1312                assert!(
1313                    cause.to_string().contains("boom"),
1314                    "mapper diagnostic cause must be replaced by the original, got: {cause}"
1315                );
1316            }
1317            other => panic!("expected ExpressionFailed with chained cause, got {other:?}"),
1318        }
1319    }
1320
1321    #[test]
1322    fn chain_preserves_caller_cause() {
1323        let predicate_err =
1324            caller_diagnostic_failed(CamelError::ProcessorError("caller diagnostic".into()));
1325
1326        let result =
1327            chain_predicate_error(predicate_err, CamelError::ProcessorError("boom".into()));
1328
1329        match result {
1330            CamelError::ExpressionFailed {
1331                cause: Some(cause), ..
1332            } => {
1333                let rendered = cause.to_string();
1334                assert!(
1335                    rendered.contains("caller diagnostic"),
1336                    "caller cause must pass through untouched, got: {rendered}"
1337                );
1338                assert!(
1339                    !rendered.contains("boom"),
1340                    "caller cause must not be replaced, got: {rendered}"
1341                );
1342            }
1343            other => panic!("expected ExpressionFailed with caller cause, got {other:?}"),
1344        }
1345    }
1346
1347    #[test]
1348    fn chain_preserves_caller_source_bearing_cause() {
1349        let predicate_err = caller_diagnostic_failed(CamelError::ProcessorErrorWithSource(
1350            "caller diagnostic".into(),
1351            Arc::new(std::io::Error::other("caller source")),
1352        ));
1353
1354        let result =
1355            chain_predicate_error(predicate_err, CamelError::ProcessorError("boom".into()));
1356
1357        match result {
1358            CamelError::ExpressionFailed {
1359                cause: Some(cause), ..
1360            } => {
1361                let rendered = cause.to_string();
1362                assert!(
1363                    rendered.contains("caller diagnostic"),
1364                    "caller cause must pass through untouched, got: {rendered}"
1365                );
1366                let source = std::error::Error::source(cause.as_ref())
1367                    .unwrap_or_else(|| panic!("caller source must survive, cause: {cause:?}"));
1368                assert!(
1369                    source.to_string().contains("caller source"),
1370                    "caller source must survive untouched, got: {source}"
1371                );
1372            }
1373            other => panic!("expected ExpressionFailed with caller cause, got {other:?}"),
1374        }
1375    }
1376}