reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
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
#![cfg(test)]

use std::error;
use std::future::{Future, ready};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use std::time::Duration;

use crate::cancel::Token;
use tokio::sync::{Notify, RwLock};

use super::event::ToolEmitter;
use super::tool::{
    self, CallDisposition, Descriptor, ExecutionError, Executor, ExecutorError, ExposeAll,
    Invocation, MappingError, StepToolSnapshot,
};
use super::tool_batch::{ErrorOrigin, PreparedToolCall, SettledDisposition, execute_prepared};
use crate::opaque::Payload;
use crate::redact_tests::{SECRET, assert_redacted, assert_states};
use crate::transcript::item::{Item, ModelVisibility, System};
use crate::transcript::store::{Snapshot, Version};
use crate::value::tool_call::{self, Id, ToolCall, ToolResult};

fn assert_pending_once<F: Future + ?Sized>(future: Pin<&mut F>) {
    let mut context = Context::from_waker(Waker::noop());
    assert!(matches!(future.poll(&mut context), Poll::Pending));
}

// ---------------------------------------------------------------------------
// Shared fixtures. These mirror the minting rules in runtime/tool.rs:927 and
// runtime/tool.rs:438: only a resolved snapshot can mint an invocation, and only
// a statically paired executor/mapper can be registered.
// ---------------------------------------------------------------------------

fn step_transcript() -> Snapshot {
    Snapshot::new(
        Version::ZERO,
        vec![Item::System(System::new(
            "step".to_owned(),
            "step top".to_owned(),
            ModelVisibility::Visible,
        ))],
    )
}

fn local(name: &str) -> tool::Name {
    tool::Name::local(name.to_owned()).unwrap()
}

fn descriptor(name: &str) -> Descriptor {
    Descriptor::new(
        local(name),
        "description".to_owned(),
        Payload::copy_from_slice(b"{}"),
    )
}

fn call(name: &str) -> ToolCall {
    ToolCall::new(
        Id::new(format!("call-{name}")),
        tool_call::Name::new(name.to_owned()),
        Payload::copy_from_slice(b"{}"),
    )
}

fn snapshot_of(registrations: Vec<tool::Registration>) -> Arc<StepToolSnapshot> {
    let mut builder = tool::RegistryBuilder::new();
    for registration in registrations {
        builder.register(registration);
    }
    Arc::new(
        builder
            .build()
            .unwrap()
            .resolve_step_without_providers(step_transcript(), &Token::new(), &ExposeAll)
            .unwrap()
            .into_snapshot(),
    )
}

fn executable(snapshot: &Arc<StepToolSnapshot>, name: &str) -> PreparedToolCall {
    PreparedToolCall::executable(
        Arc::clone(snapshot),
        Some("session".to_owned()),
        call(name),
        ToolEmitter::closed(),
    )
}

/// An executor that only completes when its own release signal fires, so tests can
/// force real overlap and choose completion order independently of source order.
///
/// `started` and `release` are `Notify`, whose permit is *stored* rather than
/// dropped: `notify_one` before the peer ever awaits still releases it, so these
/// handshakes do not depend on which side reaches its await point first. The
/// permit count saturates at one, so each handle serves exactly one rendezvous.
struct DeferredExecutor {
    release: Arc<Notify>,
    started: Arc<Notify>,
    outcome: Mutex<Result<String, ExecutorError>>,
    running: Arc<AtomicUsize>,
    peak: Arc<AtomicUsize>,
}

impl Executor for DeferredExecutor {
    type Output = String;

    async fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> Result<Self::Output, ExecutorError> {
        let running = self.running.fetch_add(1, Ordering::SeqCst) + 1;
        self.peak.fetch_max(running, Ordering::SeqCst);
        self.started.notify_one();
        self.release.notified().await;
        self.running.fetch_sub(1, Ordering::SeqCst);
        self.outcome.lock().unwrap().clone()
    }
}

struct DeferredHandles {
    release: Arc<Notify>,
    started: Arc<Notify>,
}

struct Overlap {
    running: Arc<AtomicUsize>,
    peak: Arc<AtomicUsize>,
}

impl Overlap {
    fn new() -> Self {
        Self {
            running: Arc::new(AtomicUsize::new(0)),
            peak: Arc::new(AtomicUsize::new(0)),
        }
    }

    fn peak(&self) -> usize {
        self.peak.load(Ordering::SeqCst)
    }

    fn deferred(
        &self,
        name: &str,
        outcome: Result<String, ExecutorError>,
    ) -> (tool::Registration, DeferredHandles) {
        let release = Arc::new(Notify::new());
        let started = Arc::new(Notify::new());
        let registration = tool::Registration::client(
            descriptor(name),
            Arc::new(DeferredExecutor {
                release: Arc::clone(&release),
                started: Arc::clone(&started),
                outcome: Mutex::new(outcome),
                running: Arc::clone(&self.running),
                peak: Arc::clone(&self.peak),
            }),
            Arc::new(|output: String| Ok(ToolResult::success_text(output))),
        );
        (registration, DeferredHandles { release, started })
    }
}

fn text_of(result: &ToolResult) -> String {
    result.output().unwrap().user_view().unwrap().to_owned()
}

async fn with_timeout<F: Future>(future: F) -> F::Output {
    tokio::time::timeout(Duration::from_secs(5), future)
        .await
        .expect("the batch engine must join all owned work without hanging")
}

/// Concurrency must be real: two slots have to be inside their executors at the
/// same moment, which is impossible for a serial loop.
#[tokio::test(flavor = "current_thread")]
async fn executable_slots_genuinely_overlap_rather_than_running_serially() {
    let overlap = Overlap::new();
    let (first, first_handles) = overlap.deferred("first", Ok("first".to_owned()));
    let (second, second_handles) = overlap.deferred("second", Ok("second".to_owned()));
    let snapshot = snapshot_of(vec![first, second]);
    let entries = vec![
        executable(&snapshot, "first"),
        executable(&snapshot, "second"),
    ];

    let cancellation = Token::new();
    let mut batch = Box::pin(execute_prepared(entries, &cancellation));
    // Poll once so both slots start; neither can finish yet.
    assert_pending_once(batch.as_mut());
    with_timeout(first_handles.started.notified()).await;
    with_timeout(second_handles.started.notified()).await;
    assert_eq!(overlap.peak(), 2);

    first_handles.release.notify_one();
    second_handles.release.notify_one();
    let outcomes = with_timeout(batch).await.unwrap();
    assert_eq!(overlap.peak(), 2);
    assert_eq!(
        outcomes
            .iter()
            .map(|outcome| text_of(outcome.result()))
            .collect::<Vec<_>>(),
        vec!["first".to_owned(), "second".to_owned()]
    );
}

/// Completing in exactly reverse order must not change the returned order, and
/// caller-settled slots must keep their reserved source positions among them.
#[tokio::test(flavor = "current_thread")]
async fn reverse_completion_order_still_returns_source_order_with_settled_slots() {
    let overlap = Overlap::new();
    let (first, first_handles) = overlap.deferred("first", Ok("first".to_owned()));
    let (second, second_handles) = overlap.deferred("second", Ok("second".to_owned()));
    let snapshot = snapshot_of(vec![first, second]);
    let entries = vec![
        executable(&snapshot, "first"),
        PreparedToolCall::settled(
            ToolResult::success_text("short-circuit".to_owned()),
            SettledDisposition::ShortCircuited,
        ),
        executable(&snapshot, "second"),
        PreparedToolCall::settled(ToolResult::no_output(), SettledDisposition::Blocked),
    ];

    let cancellation = Token::new();
    let mut batch = Box::pin(execute_prepared(entries, &cancellation));
    assert_pending_once(batch.as_mut());
    // Release strictly last-to-first.
    second_handles.release.notify_one();
    with_timeout(second_handles.started.notified()).await;
    assert_pending_once(batch.as_mut());
    first_handles.release.notify_one();

    let outcomes = with_timeout(batch).await.unwrap();
    assert_eq!(outcomes.len(), 4);
    assert_eq!(text_of(outcomes[0].result()), "first");
    assert_eq!(outcomes[0].disposition(), CallDisposition::Executed);
    assert_eq!(text_of(outcomes[1].result()), "short-circuit");
    assert_eq!(outcomes[1].disposition(), CallDisposition::ShortCircuited);
    assert_eq!(text_of(outcomes[2].result()), "second");
    assert_eq!(outcomes[2].disposition(), CallDisposition::Executed);
    assert!(!outcomes[3].result().has_output());
    assert_eq!(outcomes[3].disposition(), CallDisposition::Blocked);

    // The closed pair transfers without re-derivation.
    let (result, disposition) = outcomes.into_iter().next().unwrap().into_parts();
    assert_eq!(text_of(&result), "first");
    assert_eq!(disposition, CallDisposition::Executed);
}

fn immediate(name: &str, outcome: Result<String, ExecutorError>) -> tool::Registration {
    tool::Registration::client(
        descriptor(name),
        Arc::new(ImmediateExecutor(Mutex::new(outcome))),
        Arc::new(|output: String| Ok(ToolResult::success_text(output))),
    )
}

struct ImmediateExecutor(Mutex<Result<String, ExecutorError>>);

impl Executor for ImmediateExecutor {
    type Output = String;

    fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> impl Future<Output = Result<Self::Output, ExecutorError>> + Send {
        ready(self.0.lock().unwrap().clone())
    }
}

/// Every non-fatal branch reachable through the routing seam stays an in-order
/// business outcome: an unexposed name or an ordinary executor error. Neither
/// may fail the batch.
#[tokio::test]
async fn unknown_and_ordinary_error_are_ordered_business_outcomes() {
    let snapshot = snapshot_of(vec![
        immediate("allowed", Ok("ok".to_owned())),
        immediate(
            "failing",
            Err(ExecutorError::new("ordinary failure".to_owned())),
        ),
    ]);
    let entries = vec![
        // Unknown names are never exposed, so this is a business rejection.
        executable(&snapshot, "absent"),
        executable(&snapshot, "failing"),
        executable(&snapshot, "allowed"),
    ];

    let outcomes = with_timeout(execute_prepared(entries, &Token::new()))
        .await
        .unwrap();
    assert_eq!(
        outcomes
            .iter()
            .map(|outcome| (outcome.disposition(), outcome.result().is_business_error()))
            .collect::<Vec<_>>(),
        vec![
            (CallDisposition::Rejected, true),
            (CallDisposition::Executed, true),
            (CallDisposition::Executed, false),
        ]
    );
    assert_eq!(text_of(outcomes[0].result()), "unknown tool: absent");
    assert_eq!(text_of(outcomes[1].result()), "ordinary failure");
}

struct FailingMapExecutor;

impl Executor for FailingMapExecutor {
    type Output = String;

    fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> impl Future<Output = Result<Self::Output, ExecutorError>> + Send {
        ready(Ok("unmappable".to_owned()))
    }
}

/// Each typed control-path failure of the routing seam must fail the whole batch
/// and materialize nothing at all.
#[tokio::test]
async fn every_typed_control_path_failure_fails_the_batch_with_no_outcomes() {
    let mapping_error = MappingError::Protocol("bad output".to_owned());
    let registration = tool::Registration::client(
        descriptor("mapping"),
        Arc::new(FailingMapExecutor),
        Arc::new({
            let error = mapping_error.clone();
            move |_output: String| Err(error.clone())
        }),
    );
    let snapshot = snapshot_of(vec![registration]);
    let entries = vec![
        PreparedToolCall::settled(
            ToolResult::success_text("settled".to_owned()),
            SettledDisposition::ShortCircuited,
        ),
        executable(&snapshot, "mapping"),
    ];
    let failure = with_timeout(execute_prepared(entries, &Token::new()))
        .await
        .err()
        .unwrap();
    let expected = ExecutionError::Mapping(mapping_error);
    assert_eq!(failure.origin(), ErrorOrigin::Slot(1));
    assert_eq!(failure.execution(), &expected);
    assert_eq!(
        failure.to_string(),
        format!("prepared tool batch failed at source index 1: {expected}")
    );
    let _: &dyn std::error::Error = &failure;
    assert_eq!(failure.clone().into_execution(), expected);
    assert_deprecated_execution_accessors(&failure);
    assert!(format!("{failure:?}").contains("Error"));
}

#[expect(
    deprecated,
    reason = "the compatibility test intentionally exercises the deprecated aliases"
)]
fn assert_deprecated_execution_accessors(failure: &super::tool_batch::Error) {
    assert_eq!(failure.error(), failure.execution());
    assert_eq!(
        failure.clone().into_error(),
        failure.clone().into_execution()
    );
}

/// An executor whose future records, at drop time, whether its own cancellation
/// token had already been cancelled. Per the cancellation-safety contract in
/// runtime/tool.rs:293-304 a cancelled route drops the executor future instead of
/// awaiting it, so drop-time token state - not executor completion - is the
/// observable proof that a sibling saw the cancellation.
struct ObservingExecutor(Arc<Observations>);

#[derive(Default)]
struct Observations {
    /// A stored-permit rendezvous, not an edge trigger: `notify_one` from an
    /// executor that ran before the test awaited still releases the waiter, so no
    /// wakeup is lost. The permit count saturates at one, so a test that awaits it
    /// once learns only that *some* run started, and must use the counters below
    /// to reason about how many.
    started: Notify,
    dropped_with_cancelled_token: AtomicUsize,
    dropped: AtomicUsize,
    completed: AtomicUsize,
}

struct DropProbe {
    observations: Arc<Observations>,
    cancellation: Token,
}

impl Drop for DropProbe {
    fn drop(&mut self) {
        self.observations.dropped.fetch_add(1, Ordering::SeqCst);
        if self.cancellation.is_cancelled() {
            self.observations
                .dropped_with_cancelled_token
                .fetch_add(1, Ordering::SeqCst);
        }
    }
}

impl Executor for ObservingExecutor {
    type Output = String;

    async fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        cancellation: Token,
    ) -> Result<Self::Output, ExecutorError> {
        let _probe = DropProbe {
            observations: Arc::clone(&self.0),
            cancellation: cancellation.clone(),
        };
        self.0.started.notify_one();
        cancellation.cancelled().await;
        self.0.completed.fetch_add(1, Ordering::SeqCst);
        Ok("never materialized".to_owned())
    }
}

fn observing(name: &str, observations: &Arc<Observations>) -> tool::Registration {
    tool::Registration::client(
        descriptor(name),
        Arc::new(ObservingExecutor(Arc::clone(observations))),
        Arc::new(|output: String| Ok(ToolResult::success_text(output))),
    )
}

/// The first typed fatal must cancel its siblings through a *child* token, and
/// the batch must still join every run it started. The caller's own token stays
/// untouched, the sibling observes the cancellation, and its future is dropped
/// rather than awaited to completion.
#[tokio::test(flavor = "current_thread")]
async fn first_fatal_cancels_siblings_that_observe_it_and_all_runs_are_joined() {
    let observations = Arc::new(Observations::default());
    let snapshot = snapshot_of(vec![
        tool::Registration::client(
            descriptor("fatal"),
            Arc::new(FailingMapExecutor),
            Arc::new(|_output: String| Err(MappingError::Protocol("unmappable".to_owned()))),
        ),
        observing("sibling", &observations),
    ]);
    let entries = vec![
        executable(&snapshot, "fatal"),
        executable(&snapshot, "sibling"),
    ];

    let cancellation = Token::new();
    let failure = with_timeout(execute_prepared(entries, &cancellation))
        .await
        .err()
        .unwrap();
    assert_eq!(
        *failure.execution(),
        ExecutionError::Mapping(MappingError::Protocol("unmappable".to_owned()))
    );
    assert_eq!(failure.origin(), ErrorOrigin::Slot(0));
    assert_eq!(observations.dropped.load(Ordering::SeqCst), 1);
    assert_eq!(
        observations
            .dropped_with_cancelled_token
            .load(Ordering::SeqCst),
        1
    );
    assert_eq!(observations.completed.load(Ordering::SeqCst), 0);
    // A sibling cancellation must never escape into the caller's own scope.
    assert!(!cancellation.is_cancelled());
}

struct TriggeredExecutor(Token);

impl Executor for TriggeredExecutor {
    type Output = String;

    async fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> Result<Self::Output, ExecutorError> {
        self.0.cancelled().await;
        Ok("ready to map".to_owned())
    }
}

fn triggered_mapping_failure(
    name: &'static str,
    trigger: &Token,
    mappings: &Arc<AtomicUsize>,
) -> tool::Registration {
    let mappings = Arc::clone(mappings);
    tool::Registration::client(
        descriptor(name),
        Arc::new(TriggeredExecutor(trigger.clone())),
        Arc::new(move |_output: String| {
            mappings.fetch_add(1, Ordering::SeqCst);
            Err(MappingError::Protocol(name.to_owned()))
        }),
    )
}

/// `execute_prepared` polls ready workers in source order before cancelling any
/// sibling (runtime/tool_batch.rs:417-439). Releasing both executors together
/// therefore exposes both real fatals to one poll pass, and the lower source
/// index must be the stable result rather than whichever mapper ran last.
#[tokio::test(flavor = "current_thread")]
async fn same_poll_pass_fatals_choose_the_lower_source_index() {
    let trigger = Token::new();
    let mappings = Arc::new(AtomicUsize::new(0));
    let snapshot = snapshot_of(vec![
        triggered_mapping_failure("earlier", &trigger, &mappings),
        triggered_mapping_failure("later", &trigger, &mappings),
    ]);
    let entries = vec![
        PreparedToolCall::settled(
            ToolResult::success_text("settled".to_owned()),
            SettledDisposition::ShortCircuited,
        ),
        executable(&snapshot, "earlier"),
        executable(&snapshot, "later"),
    ];

    let cancellation = Token::new();
    let mut batch = Box::pin(execute_prepared(entries, &cancellation));
    assert_pending_once(batch.as_mut());
    trigger.cancel();

    let failure = with_timeout(batch).await.err().unwrap();
    assert_eq!(mappings.load(Ordering::SeqCst), 2);
    assert_eq!(failure.origin(), ErrorOrigin::Slot(1));
    assert_eq!(
        failure.execution(),
        &ExecutionError::Mapping(MappingError::Protocol("earlier".to_owned()))
    );
}

struct CancellingExecutor(Token);

impl Executor for CancellingExecutor {
    type Output = String;

    fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> impl Future<Output = Result<Self::Output, ExecutorError>> + Send {
        self.0.cancel();
        ready(Ok("ready to map".to_owned()))
    }
}

struct CountingExecutor(Arc<AtomicUsize>);

impl Executor for CountingExecutor {
    type Output = String;

    fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> impl Future<Output = Result<Self::Output, ExecutorError>> + Send {
        self.0.fetch_add(1, Ordering::SeqCst);
        ready(Ok("unexpected execution".to_owned()))
    }
}

/// The first worker makes its mapping fatal and the caller's cancellation ready
/// during the same outer poll. The next source slot observes that cancellation,
/// exercising `execute_prepared`'s real latch path rather than calling `latch`
/// directly; the real fatal must outrank the same-pass cancellation.
#[tokio::test(flavor = "current_thread")]
async fn same_poll_pass_fatal_outranks_cancellation() {
    let cancellation = Token::new();
    let later_calls = Arc::new(AtomicUsize::new(0));
    let snapshot = snapshot_of(vec![
        tool::Registration::client(
            descriptor("fatal"),
            Arc::new(CancellingExecutor(cancellation.clone())),
            Arc::new(|_output: String| Err(MappingError::Protocol("fatal wins".to_owned()))),
        ),
        tool::Registration::client(
            descriptor("cancelled"),
            Arc::new(CountingExecutor(Arc::clone(&later_calls))),
            Arc::new(|output: String| Ok(ToolResult::success_text(output))),
        ),
    ]);
    let entries = vec![
        PreparedToolCall::settled(
            ToolResult::success_text("settled".to_owned()),
            SettledDisposition::ShortCircuited,
        ),
        executable(&snapshot, "fatal"),
        executable(&snapshot, "cancelled"),
    ];

    let failure = with_timeout(execute_prepared(entries, &cancellation))
        .await
        .err()
        .unwrap();
    assert!(cancellation.is_cancelled());
    assert_eq!(later_calls.load(Ordering::SeqCst), 0);
    assert_eq!(failure.origin(), ErrorOrigin::Slot(1));
    assert_eq!(
        failure.execution(),
        &ExecutionError::Mapping(MappingError::Protocol("fatal wins".to_owned()))
    );
}

#[test]
fn latch_prefers_a_real_failure_over_cancellation_and_keeps_the_first_equal_rank() {
    let mut latched = None;
    super::tool_batch::latch(&mut latched, 3, ExecutionError::Cancelled);
    super::tool_batch::latch(
        &mut latched,
        2,
        ExecutionError::Mapping(MappingError::Protocol("first".to_owned())),
    );
    super::tool_batch::latch(&mut latched, 1, ExecutionError::Hosted("later".to_owned()));

    let failure = latched.expect("a failure was latched");
    assert_eq!(failure.origin(), ErrorOrigin::Slot(2));
    assert_eq!(
        failure.execution(),
        &ExecutionError::Mapping(MappingError::Protocol("first".to_owned()))
    );
}

/// An executor that never completes and never consults its token at all.
struct PermanentlyPendingExecutor(Arc<Observations>);

impl Executor for PermanentlyPendingExecutor {
    type Output = String;

    async fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> Result<Self::Output, ExecutorError> {
        let _probe = DropProbe {
            observations: Arc::clone(&self.0),
            cancellation: Token::new(),
        };
        self.0.started.notify_one();
        std::future::pending::<()>().await;
        unreachable!("a permanently pending executor never completes")
    }
}

/// External cancellation fails the batch, keeps the earliest cancelled source
/// index, and must not hang even when a slot's future would never complete: the
/// engine relies on the cancellation-safety contract that lets the routing seam
/// drop such a future instead of awaiting it.
#[tokio::test(flavor = "current_thread")]
async fn external_cancellation_drops_permanently_pending_runs_without_hanging() {
    let observations = Arc::new(Observations::default());
    let snapshot = snapshot_of(vec![
        tool::Registration::client(
            descriptor("pending-a"),
            Arc::new(PermanentlyPendingExecutor(Arc::clone(&observations))),
            Arc::new(|output: String| Ok(ToolResult::success_text(output))),
        ),
        tool::Registration::client(
            descriptor("pending-b"),
            Arc::new(PermanentlyPendingExecutor(Arc::clone(&observations))),
            Arc::new(|output: String| Ok(ToolResult::success_text(output))),
        ),
    ]);
    let entries = vec![
        PreparedToolCall::settled(
            ToolResult::success_text("settled".to_owned()),
            SettledDisposition::ShortCircuited,
        ),
        executable(&snapshot, "pending-a"),
        executable(&snapshot, "pending-b"),
    ];

    let cancellation = Token::new();
    let mut batch = Box::pin(execute_prepared(entries, &cancellation));
    assert_pending_once(batch.as_mut());
    with_timeout(observations.started.notified()).await;
    cancellation.cancel();

    let failure = with_timeout(batch).await.err().unwrap();
    assert_eq!(*failure.execution(), ExecutionError::Cancelled);
    // Both slots were cancelled; the earliest source index is the stable report.
    assert_eq!(failure.origin(), ErrorOrigin::Slot(1));
    assert_eq!(observations.dropped.load(Ordering::SeqCst), 2);
    assert_eq!(observations.completed.load(Ordering::SeqCst), 0);
}

/// A batch with nothing to execute still returns its reserved positions in
/// source order, and an empty batch is trivially ordered.
#[tokio::test]
async fn batches_without_executable_slots_return_reserved_positions_in_order() {
    let cancellation = Token::new();
    assert!(
        with_timeout(execute_prepared(Vec::new(), &cancellation))
            .await
            .unwrap()
            .is_empty()
    );

    let outcomes = with_timeout(execute_prepared(
        vec![
            PreparedToolCall::settled(
                ToolResult::success_text("first".to_owned()),
                SettledDisposition::Truncated,
            ),
            PreparedToolCall::settled(
                ToolResult::error_text("second".to_owned()),
                SettledDisposition::NotExecuted,
            ),
        ],
        &cancellation,
    ))
    .await
    .unwrap();
    let cloned = outcomes[0].clone();
    assert_eq!(text_of(cloned.result()), "first");
    assert_eq!(cloned.disposition(), CallDisposition::Truncated);
    assert_eq!(text_of(outcomes[1].result()), "second");
    assert!(outcomes[1].result().is_business_error());
    assert_eq!(outcomes[1].disposition(), CallDisposition::NotExecuted);
}

/// A batch whose cancellation is already observable is cancelled, not succeeded,
/// even when it has nothing at all to execute. Both shapes that could otherwise
/// slip through - the empty batch and the fully settled batch - are covered, and
/// the failure carries no source index because no slot reported it.
#[tokio::test]
async fn pre_cancelled_empty_and_fully_settled_batches_are_cancelled() {
    let cancellation = Token::new();
    cancellation.cancel();

    let empty = execute_prepared(Vec::new(), &cancellation).await.err();
    let empty = empty.unwrap();
    assert_eq!(*empty.execution(), ExecutionError::Cancelled);
    assert_eq!(empty.origin(), ErrorOrigin::Batch);
    assert_eq!(
        empty.to_string(),
        "prepared tool batch failed with no source position: tool run cancelled"
    );

    let settled = execute_prepared(
        vec![
            PreparedToolCall::settled(
                ToolResult::success_text("first".to_owned()),
                SettledDisposition::ShortCircuited,
            ),
            PreparedToolCall::settled(ToolResult::no_output(), SettledDisposition::NotExecuted),
        ],
        &cancellation,
    )
    .await
    .err()
    .unwrap();
    assert_eq!(*settled.execution(), ExecutionError::Cancelled);
    assert_eq!(settled.origin(), ErrorOrigin::Batch);
}

/// An executor that cancels the caller's own batch token and then succeeds, so
/// the batch is cancelled while no slot ever reports a failure.
struct SelfCancellingExecutor(Token);

impl Executor for SelfCancellingExecutor {
    type Output = String;

    fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> impl Future<Output = Result<Self::Output, ExecutorError>> + Send {
        self.0.cancel();
        ready(Ok("outran cancellation".to_owned()))
    }
}

/// A cancellation that arrives while the batch runs must fail the batch even when
/// every slot outran it, so the caller can never publish a batch that was
/// cancelled. This is the closing re-check, and it too has no source position.
#[tokio::test]
async fn cancellation_that_every_slot_outran_still_cancels_the_batch() {
    let cancellation = Token::new();
    let snapshot = snapshot_of(vec![tool::Registration::client(
        descriptor("outrunner"),
        Arc::new(SelfCancellingExecutor(cancellation.clone())),
        Arc::new(|output: String| Ok(ToolResult::success_text(output))),
    )]);
    let entries = vec![
        PreparedToolCall::settled(
            ToolResult::success_text("settled".to_owned()),
            SettledDisposition::Truncated,
        ),
        executable(&snapshot, "outrunner"),
    ];

    let failure = with_timeout(execute_prepared(entries, &cancellation))
        .await
        .err()
        .unwrap();
    assert_eq!(*failure.execution(), ExecutionError::Cancelled);
    assert_eq!(failure.origin(), ErrorOrigin::Batch);
}

/// Dropping the batch future mid-flight must cancel every started run *before*
/// dropping it, so a run that releases resources on observed cancellation still
/// sees a cancelled token in its own `Drop`. The caller's token stays untouched.
#[tokio::test(flavor = "current_thread")]
async fn dropping_the_batch_mid_flight_cancels_then_drops_every_started_run() {
    let observations = Arc::new(Observations::default());
    let snapshot = snapshot_of(vec![
        observing("mid-a", &observations),
        observing("mid-b", &observations),
    ]);
    let entries = vec![
        executable(&snapshot, "mid-a"),
        PreparedToolCall::settled(ToolResult::no_output(), SettledDisposition::Blocked),
        executable(&snapshot, "mid-b"),
    ];

    let cancellation = Token::new();
    let mut batch = Box::pin(execute_prepared(entries, &cancellation));
    // One poll starts both runs; neither can finish while the token is live.
    assert_pending_once(batch.as_mut());
    with_timeout(observations.started.notified()).await;
    assert_eq!(observations.dropped.load(Ordering::SeqCst), 0);

    drop(batch);

    assert_eq!(observations.dropped.load(Ordering::SeqCst), 2);
    assert_eq!(
        observations
            .dropped_with_cancelled_token
            .load(Ordering::SeqCst),
        2
    );
    assert_eq!(observations.completed.load(Ordering::SeqCst), 0);
    assert!(!cancellation.is_cancelled());
}

#[test]
fn error_has_exactly_one_reachable_source_and_it_is_the_trait_method() {
    // `Error` used to carry an inherent `source()` returning `ErrorOrigin`
    // alongside its `std::error::Error` implementation, so `err.source()`
    // resolved to a different method depending on how the receiver was typed.
    // The inherent accessor is now `origin()`, which leaves exactly one
    // `source()` reachable. This pins which one.
    let failure = super::tool_batch::Error::cancelled_batch();

    // The inherent accessor answers "where was this observed".
    assert_eq!(failure.origin(), ErrorOrigin::Batch);

    // `source()` now resolves to the trait method on every receiver spelling,
    // and only when the trait is in scope. Before the rename the inherent method
    // answered this call with no import at all. The one reachable `source()`
    // hands back the latched typed failure rather than nothing: a batch failure
    // always retains one, so returning `None` would delete it.
    use std::error::Error as _;

    let retained = |cause: Option<&(dyn error::Error + 'static)>| {
        cause
            .expect("a batch failure retains its typed run failure")
            .to_string()
    };
    let expected = ExecutionError::Cancelled.to_string();
    assert_eq!(retained(error::Error::source(&failure)), expected);
    assert_eq!(retained(failure.source()), expected);
    let dynamic: &dyn error::Error = &failure;
    assert_eq!(retained(dynamic.source()), expected);
    assert!(
        failure
            .source()
            .and_then(|cause| cause.downcast_ref::<ExecutionError>())
            .is_some_and(|cause| *cause == ExecutionError::Cancelled)
    );
}

// ---------------------------------------------------------------------------
// Composition-owned exclusion (ADR-022 item 4).
//
// The declaration and scheduling of exclusivity are not separable: a field core
// never reads would have no production consumer, and a field core *does* read
// would make core own a policy the reference products spell in different ways.
// Both halves therefore stay outside, and this is what "outside" looks like — one
// reader/writer lane captured by the composition layer's own executors at
// registration, built from nothing core does not already expose.
// ---------------------------------------------------------------------------

struct Occupancy {
    running: AtomicUsize,
    peak: AtomicUsize,
    peak_beside_exclusive: AtomicUsize,
}

impl Occupancy {
    fn new() -> Arc<Self> {
        Arc::new(Self {
            running: AtomicUsize::new(0),
            peak: AtomicUsize::new(0),
            peak_beside_exclusive: AtomicUsize::new(0),
        })
    }

    fn enter(&self, exclusive: bool) {
        let running = self.running.fetch_add(1, Ordering::SeqCst) + 1;
        self.peak.fetch_max(running, Ordering::SeqCst);
        if exclusive {
            self.peak_beside_exclusive
                .fetch_max(running, Ordering::SeqCst);
        }
    }

    fn leave(&self, exclusive: bool) {
        if exclusive {
            self.peak_beside_exclusive
                .fetch_max(self.running.load(Ordering::SeqCst), Ordering::SeqCst);
        }
        self.running.fetch_sub(1, Ordering::SeqCst);
    }
}

struct ExclusionExecutor {
    lane: Arc<RwLock<()>>,
    exclusive: bool,
    label: &'static str,
    occupancy: Arc<Occupancy>,
    started: Arc<Notify>,
    release: Arc<Notify>,
}

impl ExclusionExecutor {
    async fn body(&self) -> Result<String, ExecutorError> {
        self.occupancy.enter(self.exclusive);
        self.started.notify_one();
        self.release.notified().await;
        self.occupancy.leave(self.exclusive);
        Ok(self.label.to_owned())
    }
}

impl Executor for ExclusionExecutor {
    type Output = String;

    async fn execute(
        &self,
        _invocation: &Invocation,
        _call: &ToolCall,
        _cancellation: Token,
    ) -> Result<Self::Output, ExecutorError> {
        // The composition layer owns the wait, so it also owns racing it
        // against the token core supplied; both acquire futures are
        // cancellation-safe and deregister when the engine drops the slot.
        if self.exclusive {
            let _lane = self.lane.write().await;
            self.body().await
        } else {
            let _lane = self.lane.read().await;
            self.body().await
        }
    }
}

struct ExclusionHandles {
    started: Arc<Notify>,
    release: Arc<Notify>,
}

fn exclusion_tool(
    lane: &Arc<RwLock<()>>,
    occupancy: &Arc<Occupancy>,
    label: &'static str,
    exclusive: bool,
) -> (tool::Registration, ExclusionHandles) {
    let started = Arc::new(Notify::new());
    let release = Arc::new(Notify::new());
    let registration = tool::Registration::client(
        descriptor(label),
        Arc::new(ExclusionExecutor {
            lane: Arc::clone(lane),
            exclusive,
            label,
            occupancy: Arc::clone(occupancy),
            started: Arc::clone(&started),
            release: Arc::clone(&release),
        }),
        Arc::new(|output: String| Ok(ToolResult::success_text(output))),
    );
    (registration, ExclusionHandles { started, release })
}

/// A composition layer can make one tool exclusive without any core change, and
/// without giving up either of the two properties the batch engine provides:
/// concurrency-safe peers still genuinely overlap, and outcomes still come back
/// in source order however the executors interleaved.
#[tokio::test(flavor = "current_thread")]
async fn a_composition_owned_lane_makes_one_tool_exclusive_without_reordering_the_batch() {
    let lane = Arc::new(RwLock::new(()));
    let occupancy = Occupancy::new();
    let (reader_a, a) = exclusion_tool(&lane, &occupancy, "reader-a", false);
    let (reader_b, b) = exclusion_tool(&lane, &occupancy, "reader-b", false);
    let (writer, x) = exclusion_tool(&lane, &occupancy, "exclusive", true);
    let (reader_c, c) = exclusion_tool(&lane, &occupancy, "reader-c", false);
    let snapshot = snapshot_of(vec![reader_a, reader_b, writer, reader_c]);
    let entries = vec![
        executable(&snapshot, "reader-a"),
        executable(&snapshot, "reader-b"),
        executable(&snapshot, "exclusive"),
        executable(&snapshot, "reader-c"),
    ];

    let cancellation = Token::new();
    let mut batch = Box::pin(execute_prepared(entries, &cancellation));
    assert_pending_once(batch.as_mut());
    with_timeout(a.started.notified()).await;
    with_timeout(b.started.notified()).await;
    assert!(
        occupancy.peak.load(Ordering::SeqCst) >= 2,
        "the engine still overlaps the concurrency-safe peers"
    );

    // Every permit is stored, so releasing all of them now cannot depend on the
    // order the lane hands the guards out in.
    for handles in [&a, &b, &x, &c] {
        handles.release.notify_one();
    }
    let outcomes = with_timeout(batch).await.unwrap();

    assert_eq!(
        occupancy.peak_beside_exclusive.load(Ordering::SeqCst),
        1,
        "nothing else was inside its executor while the exclusive tool was"
    );
    assert_eq!(
        outcomes
            .iter()
            .map(|outcome| text_of(outcome.result()))
            .collect::<Vec<_>>(),
        ["reader-a", "reader-b", "exclusive", "reader-c"],
        "serialising execution does not perturb the source order C14 commits"
    );
}

#[test]
fn prepared_call_debug_says_whether_the_position_still_has_to_run() {
    let settled = PreparedToolCall::settled(
        ToolResult::success_text(SECRET.to_owned()),
        SettledDisposition::ShortCircuited,
    );
    assert_redacted(&settled);
    assert_eq!(
        format!("{settled:?}"),
        "PreparedToolCall { settled: true, disposition: ShortCircuited }"
    );

    let snapshot = snapshot_of(vec![immediate("search", Ok(SECRET.to_owned()))]);
    let executable = executable(&snapshot, "search");
    assert_redacted(&executable);
    assert_states(
        &executable,
        &[
            "settled: false",
            r#"Id("call-search")"#,
            "arguments: <2 bytes>",
        ],
    );
}

#[tokio::test]
async fn batch_outcome_debug_keeps_the_disposition_and_redacts_the_result() {
    let snapshot = snapshot_of(vec![immediate("search", Ok(SECRET.to_owned()))]);
    let outcomes = execute_prepared(
        vec![
            executable(&snapshot, "search"),
            PreparedToolCall::settled(
                ToolResult::error_text(SECRET.to_owned()),
                SettledDisposition::Truncated,
            ),
        ],
        &Token::new(),
    )
    .await
    .expect("a successful batch materializes in source order");

    for outcome in &outcomes {
        assert_redacted(outcome);
    }
    assert_states(&outcomes[0], &["disposition: Executed", "Success("]);
    assert_states(
        &outcomes[1],
        &["disposition: Truncated", "user_view: Some(<21 bytes>)"],
    );
}