causa-runtime 0.0.6

Causa runtime — optional components: material execution, bound tool processing, streaming
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
//! Direct execution properties extracted from the former driver/session consumers.
mod common;
use async_trait::async_trait;
use causa_kernel::*;
use causa_runtime::*;
use common::*;
use serde_json::json;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;

fn cause(out: &TurnOutcome) -> &TurnInterruption {
    match &out.result {
        TurnResult::Interrupted { cause } => cause,
        _ => panic!("expected interruption"),
    }
}

#[tokio::test]
async fn complete_output_and_actual_options_are_preserved() {
    let mut output = endturn_output(" done ");
    output.usage = Some(ModelUsage::new(12, 3));
    output.reasoning = Some(ReasoningPayload::new("reason"));
    let gateway = RecordingGateway::scripted(vec![Ok(output)]);
    let runner = runner_with(gateway.clone(), vec![]);
    let mut opts = options();
    opts.generation.max_tokens = Some(123);
    opts.cache = CacheDirective::StablePrefix;
    let out = runner
        .run(TurnId::new("explicit"), input("hello"), opts, ctrl())
        .await;
    assert_eq!(out.turn_id, TurnId::new("explicit"));
    let TurnResult::Completed { final_output } = out.result else {
        panic!("must complete")
    };
    assert_eq!(final_output.response.text(), " done ");
    assert_eq!(final_output.usage.unwrap().input_tokens, 12);
    assert_eq!(final_output.reasoning.unwrap().text, "reason");
    assert_eq!(out.context.blocks().len(), 2);
    assert!(out.uncommitted_tool_batch.is_none());
    let requests = gateway.recorded.lock().unwrap();
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].invocation_id.round_id, RoundId(0));
    assert_eq!(requests[0].model.0, "fixture-model");
    assert_eq!(requests[0].generation.max_tokens, Some(123));
    assert_eq!(requests[0].cache, CacheDirective::StablePrefix);
}

#[tokio::test]
async fn context_reuse_and_import_never_reexecute_old_declarations() {
    let calls = Arc::new(AtomicUsize::new(0));
    let gateway = RecordingGateway::scripted(vec![
        Ok(tooluse_output("", "echo", json!({"x":1}))),
        Ok(endturn_output("first")),
        Ok(endturn_output("second")),
    ]);
    let runner = runner_with(gateway.clone(), vec![Arc::new(CountingTool(calls.clone()))]);
    let first = runner
        .run(TurnId::new("first"), input("hi"), options(), ctrl())
        .await;
    let first_saved = first.context.clone();
    let encoded = serde_json::to_vec(&first.context).unwrap();
    let mut restored: Context = serde_json::from_slice(&encoded).unwrap();
    restored
        .edit()
        .append([text_block("more")])
        .commit()
        .unwrap();
    let second = runner
        .run(TurnId::new("second"), restored, options(), ctrl())
        .await;
    assert!(matches!(second.result, TurnResult::Completed { .. }));
    assert_eq!(calls.load(Ordering::SeqCst), 1);
    assert_eq!(
        &second.context.blocks()[..first_saved.blocks().len()],
        first_saved.blocks()
    );
    {
        let requests = gateway.recorded.lock().unwrap();
        assert_eq!(requests[2].invocation_id.turn_id, TurnId::new("second"));
        assert_eq!(
            requests[2].frame.blocks.len(),
            first_saved.blocks().len() + 1
        );
    }
    // Context can also carry an unmatched old declaration; it is never a queue.
    let old = ModelResponse {
        items: vec![ModelItem::tool_call(draft("echo", json!({})))],
    }
    .to_blocks(ModelStopReason::ToolUse, &[new_block_id()])
    .unwrap();
    let imported = Context::from_blocks(old).unwrap();
    let runner = runner_with(
        RecordingGateway::scripted(vec![Ok(endturn_output("done"))]),
        vec![Arc::new(CountingTool(calls.clone()))],
    );
    let out = runner
        .run(TurnId::new("import"), imported, options(), ctrl())
        .await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    assert_eq!(calls.load(Ordering::SeqCst), 1);
}
struct CountingTool(Arc<AtomicUsize>);
#[async_trait]
impl Tool for CountingTool {
    fn definition(&self) -> ToolDefinition {
        EchoTool.definition()
    }
    async fn execute(
        &self,
        c: &ToolCallContext,
        k: &CallControl,
        _store: Option<&dyn causa_kernel::ArtifactStore>,
    ) -> ToolResultPayload {
        self.0.fetch_add(1, Ordering::SeqCst);
        EchoTool.execute(c, k, None).await
    }
}
#[test]
fn saved_context_is_independent_and_duplicate_ids_are_rejected() {
    let mut original = input("saved");
    let bytes = serde_json::to_vec(&original).unwrap();
    let saved: Context = serde_json::from_slice(&bytes).unwrap();
    original
        .apply(
            vec![Replacement {
                range: 0..1,
                with: vec![text_block("summary")],
            }],
            vec![],
        )
        .unwrap();
    assert_ne!(saved.blocks(), original.blocks());
    let block = saved.blocks()[0].clone();
    let wire = json!({"blocks":[block.clone(),block]});
    assert!(serde_json::from_value::<Context>(wire).is_err());
}
#[tokio::test]
async fn logical_gateway_errors_are_not_retried_or_reclassified_as_parent_control() {
    for kind in [
        ModelInvokeErrorKind::Transient,
        ModelInvokeErrorKind::Permanent,
        ModelInvokeErrorKind::TimedOut,
        ModelInvokeErrorKind::Cancelled,
        ModelInvokeErrorKind::UnknownOutcome,
        ModelInvokeErrorKind::InvalidRequest,
    ] {
        let gateway = RecordingGateway::scripted(vec![
            Err(kind.clone()),
            Ok(endturn_output("should not run")),
        ]);
        let out = runner_with(gateway.clone(), vec![])
            .run(TurnId::new("error"), input("retained"), options(), ctrl())
            .await;
        let TurnInterruption::ModelCallFailed { error, .. } = cause(&out) else {
            panic!("wrong cause: {:?}", out.result)
        };
        assert_eq!(error.kind, kind);
        assert_eq!(error.message, "scripted error");
        assert_eq!(gateway.recorded.lock().unwrap().len(), 1);
        assert_eq!(out.context.blocks().len(), 1);
    }
}
#[tokio::test]
async fn limits_count_declarations_and_return_new_batch() {
    let gateway = RecordingGateway::scripted(vec![Ok(tooluse_calls_output(
        "",
        vec![draft("echo", json!({})), draft("absent", json!({}))],
    ))]);
    let calls = Arc::new(AtomicUsize::new(0));
    let runner = runner_with(gateway.clone(), vec![Arc::new(CountingTool(calls.clone()))]);
    let mut opts = options();
    opts.limits.max_model_rounds = 0;
    let out = runner
        .run(TurnId::new("zero"), Context::new(), opts, ctrl())
        .await;
    assert!(matches!(
        cause(&out),
        TurnInterruption::MaxModelRounds { limit: 0, .. }
    ));
    assert!(gateway.recorded.lock().unwrap().is_empty());
    let mut opts = options();
    opts.limits.max_tool_calls = 1;
    let out = runner
        .run(TurnId::new("limit"), Context::new(), opts, ctrl())
        .await;
    assert!(matches!(
        cause(&out),
        TurnInterruption::MaxToolCalls {
            declared_before: 0,
            declared_this_round: 2,
            limit: 1,
            ..
        }
    ));
    // The tool declaration and the two calls.
    assert_eq!(out.context.blocks().len(), 3);
    assert_eq!(out.uncommitted_tool_batch.unwrap().calls().len(), 2);
    assert_eq!(calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn model_round_limit_stops_before_another_binding_or_request() {
    let gateway = RecordingGateway::scripted(vec![
        Ok(tooluse_output("", "echo", json!({}))),
        Ok(endturn_output("extra")),
    ]);
    let mut opts = options();
    opts.limits.max_model_rounds = 1;
    let out = runner_with(gateway.clone(), vec![Arc::new(EchoTool)])
        .run(TurnId::new("round-limit"), Context::new(), opts, ctrl())
        .await;
    assert!(matches!(
        cause(&out),
        TurnInterruption::MaxModelRounds { limit: 1, .. }
    ));
    assert_eq!(gateway.recorded.lock().unwrap().len(), 1);
    assert_eq!(out.context.blocks().len(), 3);
    assert!(out.uncommitted_tool_batch.is_none());
}
#[tokio::test]
async fn malformed_model_output_retains_output_ids_and_provider_metadata() {
    let mut output = tooluse_output("text", " ", json!({}));
    let ModelItemContent::ToolCall(call) = &mut output.response.items[1].content else {
        panic!("second item is the tool call");
    };
    call.provider_call_id = Some("provider-id".into());
    let gateway = RecordingGateway::scripted(vec![Ok(output)]);
    let out = runner_with(gateway, vec![])
        .run(TurnId::new("invalid"), Context::new(), options(), ctrl())
        .await;
    let TurnInterruption::ModelConversionFailed {
        error,
        output,
        block_ids,
        ..
    } = cause(&out)
    else {
        panic!("typed conversion failure expected")
    };
    assert!(matches!(
        error,
        ModelBlockError::EmptyToolName { tool_index: 0, .. }
    ));
    assert_eq!(
        output
            .response
            .tool_calls()
            .next()
            .unwrap()
            .provider_call_id
            .as_deref(),
        Some("provider-id")
    );
    assert_eq!(block_ids.len(), 2);
    assert!(out.context.blocks().is_empty());
    assert!(out.uncommitted_tool_batch.is_none());
}

struct ParkedGateway;
#[async_trait]
impl ModelGateway for ParkedGateway {
    async fn invoke(
        &self,
        _: &ModelRequest,
        _: &CallControl,
    ) -> Result<ModelOutput, ModelInvokeError> {
        std::future::pending().await
    }
}
#[tokio::test]
async fn cancellation_and_deadline_return_existing_materials_without_cancelling_parent_on_timeout()
{
    for deadline in [false, true] {
        let token = CancellationToken::new();
        let control = CallControl::new(
            token.clone(),
            deadline.then(|| Instant::now() + Duration::from_millis(5)),
        );
        let runner = runner_with(Arc::new(ParkedGateway), vec![]);
        let future = runner.run(TurnId::new("parked"), input("kept"), options(), control);
        let out = if deadline {
            future.await
        } else {
            tokio::join!(future, async {
                tokio::task::yield_now().await;
                token.cancel();
            })
            .0
        };
        assert_eq!(out.context.blocks().len(), 1);
        assert!(out.uncommitted_tool_batch.is_none());
        if deadline {
            assert!(matches!(
                cause(&out),
                TurnInterruption::DeadlineExceeded {
                    invocation_id: Some(_),
                    ..
                }
            ));
            assert!(!token.is_cancelled());
        } else {
            assert!(matches!(
                cause(&out),
                TurnInterruption::Cancelled {
                    invocation_id: Some(_),
                    ..
                }
            ));
        }
    }
}

struct ResolveWithId(BlockId);
#[async_trait]
impl ToolBatchProcessor for ResolveWithId {
    async fn process(
        &self,
        b: &mut ToolBatch,
        _: &ProcessorContext<'_>,
    ) -> Result<(), ProcessorError> {
        let call = b.calls()[0].call().clone();
        b.resolve_at(
            0,
            self.0,
            ToolResultPayload::new(
                call.call_block_id,
                ToolResultStatus::Rejected,
                ToolOutput::new(json!({"kept":true})),
            )
            .with_media(vec![MediaRef::new("image/png", "asset")])
            .with_notes(vec![TextPayload::new("kept note")]),
        )
        .unwrap();
        Ok(())
    }
}
#[tokio::test]
async fn tool_commit_failure_returns_complete_batch_and_actual_edit_input() {
    let context = input("existing");
    let collision = context.blocks()[0].id();
    let executor = ToolExecutor::new(
        vec![Arc::new(EchoTool)],
        ToolExecutorOptions::default().with_before(vec![Arc::new(ResolveWithId(collision))]),
    )
    .unwrap();
    let runner = TurnRunner::new(
        RecordingGateway::scripted(vec![Ok(tooluse_output(
            "",
            "echo",
            json!({"original":true}),
        ))]),
        Arc::new(executor),
    );
    let observed = Arc::new(Mutex::new(vec![]));
    let events = observed.clone();
    let token = CancellationToken::new();
    let callback_token = token.clone();
    let mut opts = options();
    opts.observer = Some(Arc::new(move |event| {
        if let RunEvent::BlocksCommitted { blocks, .. } = event {
            events
                .lock()
                .unwrap()
                .extend(blocks.iter().map(ContextBlock::id));
        }
        if let RunEvent::ToolBatchReturned { result, .. } = event {
            assert!(result.is_ok());
        }
        let _ = &callback_token;
    }));
    let out = runner
        .run(
            TurnId::new("collision"),
            context,
            opts,
            CallControl::new(token.clone(), None),
        )
        .await;
    let TurnInterruption::ToolCommitFailed { error, .. } = cause(&out) else {
        panic!("{:?}", out.result)
    };
    assert_eq!(error.appended.len(), 1);
    assert_eq!(error.appended[0].id(), collision);
    assert!(error.replacements.is_empty());
    let batch = out.uncommitted_tool_batch.as_ref().unwrap();
    assert_eq!(batch.completed_len(), 1);
    let (_, result) = batch.results()[0].result().unwrap();
    assert_eq!(result.notes[0].0, "kept note");
    assert_eq!(result.media[0].reference, "asset");
    assert_eq!(
        batch.results()[0].call().input.arguments,
        json!({"original":true})
    );
    // The tool declaration and the call; the colliding result is not added.
    assert_eq!(out.context.blocks().len(), 3);
    assert_eq!(observed.lock().unwrap().len(), 2);
    assert!(!token.is_cancelled());
}

struct FailedProcessor;
#[async_trait]
impl ToolBatchProcessor for FailedProcessor {
    async fn process(
        &self,
        b: &mut ToolBatch,
        _: &ProcessorContext<'_>,
    ) -> Result<(), ProcessorError> {
        b.calls_mut()[0].push_note(TextPayload::new("before failure"));
        Err(ProcessorError::Failed("precise failure".into()))
    }
}
#[tokio::test]
async fn processor_error_is_selected_before_returned_callback_cancels() {
    let executor = ToolExecutor::new(
        vec![Arc::new(EchoTool)],
        ToolExecutorOptions::default().with_before(vec![Arc::new(FailedProcessor)]),
    )
    .unwrap();
    let runner = TurnRunner::new(
        RecordingGateway::scripted(vec![Ok(tooluse_output("", "echo", json!({})))]),
        Arc::new(executor),
    );
    let token = CancellationToken::new();
    let cancel = token.clone();
    let mut opts = options();
    opts.observer = Some(Arc::new(move |e| {
        if let RunEvent::ToolBatchReturned { result, .. } = e {
            assert!(result.is_err());
            cancel.cancel();
        }
    }));
    let out = runner
        .run(
            TurnId::new("processor"),
            Context::new(),
            opts,
            CallControl::new(token, None),
        )
        .await;
    assert!(matches!(
        cause(&out),
        TurnInterruption::ToolProcessingFailed {
            error: ToolProcessingError::Processor {
                phase: ToolProcessorPhase::Before,
                index: 0,
                ..
            },
            ..
        }
    ));
    assert_eq!(out.uncommitted_tool_batch.unwrap().calls().len(), 1);
    assert_eq!(out.context.blocks().len(), 2);
}

struct UnknownTool;
#[async_trait]
impl Tool for UnknownTool {
    fn definition(&self) -> ToolDefinition {
        EchoTool.definition()
    }
    async fn execute(
        &self,
        c: &ToolCallContext,
        k: &CallControl,
        _store: Option<&dyn causa_kernel::ArtifactStore>,
    ) -> ToolResultPayload {
        let mut r = EchoTool.execute(c, k, None).await;
        r.status = ToolResultStatus::UnknownOutcome;
        r
    }
}
#[tokio::test]
async fn observer_cancellation_respects_each_commit_boundary() {
    for stage in [
        "request",
        "output",
        "declaration",
        "ready",
        "returned",
        "result",
    ] {
        let gateway = RecordingGateway::scripted(vec![
            Ok(tooluse_output("", "echo", json!({}))),
            Ok(endturn_output("next")),
        ]);
        let calls = Arc::new(AtomicUsize::new(0));
        let runner = runner_with(gateway.clone(), vec![Arc::new(CountingTool(calls.clone()))]);
        let token = CancellationToken::new();
        let cancel = token.clone();
        let notices = Arc::new(Mutex::new(vec![]));
        let seen = notices.clone();
        let mut opts = options();
        opts.observer = Some(Arc::new(move |e| {
            let name = match e {
                RunEvent::ModelRequestReady { .. } => "request",
                RunEvent::ModelOutput { .. } => "output",
                RunEvent::BlocksCommitted { blocks, .. } => {
                    if blocks
                        .iter()
                        .any(|b| matches!(b.content(), BlockContent::ToolResult(_)))
                    {
                        "result"
                    } else if is_tool_change(blocks) {
                        "tools"
                    } else {
                        "declaration"
                    }
                }
                RunEvent::ToolBatchReady { .. } => "ready",
                RunEvent::ToolBatchReturned { result, .. } => {
                    assert!(result.is_ok());
                    "returned"
                }
                RunEvent::ModelDelta { .. } => "delta",
                other => panic!("unexpected event: {other:?}"),
            };
            seen.lock().unwrap().push(name);
            if name == stage {
                cancel.cancel();
            }
        }));
        let out = runner
            .run(
                TurnId::new(stage),
                Context::new(),
                opts,
                CallControl::new(token, None),
            )
            .await;
        assert!(matches!(cause(&out), TurnInterruption::Cancelled { .. }));
        assert_eq!(
            gateway.recorded.lock().unwrap().len(),
            usize::from(stage != "request")
        );
        assert_eq!(
            calls.load(Ordering::SeqCst),
            usize::from(matches!(stage, "returned" | "result"))
        );
        assert_eq!(
            out.context.blocks().len(),
            // The tool declaration comes first in every case.
            match stage {
                "request" | "output" => 1,
                // A batch that came back fully processed is committed before
                // the stop is honored.
                "returned" | "result" => 3,
                _ => 2,
            }
        );
        assert_eq!(
            out.uncommitted_tool_batch.is_some(),
            matches!(stage, "declaration" | "ready")
        );
        if stage == "returned" {
            assert!(notices.lock().unwrap().contains(&"result"));
        }
        if matches!(stage, "declaration" | "ready") {
            assert!(!notices.lock().unwrap().contains(&"returned"));
        }
    }
}
#[tokio::test]
async fn terminal_results_survive_observer_cancellation_and_unknown_is_not_returned_twice() {
    for stop in [
        ModelStopReason::EndTurn,
        ModelStopReason::MaxTokens,
        ModelStopReason::Refusal,
        ModelStopReason::ContextWindowExceeded,
        ModelStopReason::Unrecognized,
        ModelStopReason::ToolUse,
    ] {
        let mut output = if stop == ModelStopReason::ToolUse {
            tooluse_output("", "echo", json!({}))
        } else {
            endturn_output("retained body")
        };
        output.stop_reason = stop;
        let gateway = RecordingGateway::scripted(vec![Ok(output)]);
        let token = CancellationToken::new();
        let cancel = token.clone();
        let mut opts = options();
        opts.observer = Some(Arc::new(move |e| match e {
            // Every non-committing reason selects its interruption before the
            // observer runs; the callback is where this test cancels.
            RunEvent::ModelOutput { .. }
                if !matches!(stop, ModelStopReason::EndTurn | ModelStopReason::ToolUse) =>
            {
                cancel.cancel()
            }
            RunEvent::BlocksCommitted { blocks, .. }
                if (stop == ModelStopReason::EndTurn && !is_tool_change(blocks))
                    || blocks
                        .iter()
                        .any(|b| matches!(b.content(), BlockContent::ToolResult(_))) =>
            {
                cancel.cancel()
            }
            _ => (),
        }));
        let out = runner_with(gateway, vec![Arc::new(UnknownTool)])
            .run(
                TurnId::new("terminal"),
                Context::new(),
                opts,
                CallControl::new(token, None),
            )
            .await;
        match stop {
            ModelStopReason::EndTurn => assert!(matches!(out.result, TurnResult::Completed { .. })),
            ModelStopReason::MaxTokens => assert!(
                matches!(cause(&out),TurnInterruption::ModelMaxTokens {output,..} if output.response.text()=="retained body")
            ),
            ModelStopReason::Refusal => {
                assert!(matches!(cause(&out), TurnInterruption::ModelRefusal { .. }))
            }
            ModelStopReason::ContextWindowExceeded => assert!(matches!(
                cause(&out),
                TurnInterruption::ModelContextWindowExceeded { output, .. }
                    if output.response.text() == "retained body"
            )),
            ModelStopReason::Unrecognized => assert!(matches!(
                cause(&out),
                TurnInterruption::ModelStopUnrecognized { output, .. }
                    if output.response.text() == "retained body"
            )),
            ModelStopReason::ToolUse => {
                assert!(matches!(
                    cause(&out),
                    TurnInterruption::UnknownToolOutcome { .. }
                ));
                assert_eq!(out.context.blocks().len(), 3);
            }
        }
        assert!(out.uncommitted_tool_batch.is_none());
    }
    // Observer absence does not change unknown outcome policy.
    let out = runner_with(
        RecordingGateway::scripted(vec![Ok(tooluse_output("", "echo", json!({})))]),
        vec![Arc::new(UnknownTool)],
    )
    .run(TurnId::new("silent"), Context::new(), options(), ctrl())
    .await;
    assert!(matches!(
        cause(&out),
        TurnInterruption::UnknownToolOutcome { .. }
    ));
    assert_eq!(out.context.blocks().len(), 3);
}

#[tokio::test]
async fn tool_limit_is_selected_before_declaration_commit_callback_cancels() {
    let gateway = RecordingGateway::scripted(vec![Ok(tooluse_output("", "echo", json!({})))]);
    let token = CancellationToken::new();
    let cancel = token.clone();
    let mut opts = options();
    opts.limits.max_tool_calls = 0;
    opts.observer = Some(Arc::new(move |e| match e {
        RunEvent::BlocksCommitted { blocks, .. } if !is_tool_change(blocks) => cancel.cancel(),
        RunEvent::ToolBatchReady { .. } | RunEvent::ToolBatchReturned { .. } => {
            panic!("over-limit declarations cannot enter processing")
        }
        _ => (),
    }));
    let out = runner_with(gateway, vec![Arc::new(EchoTool)])
        .run(
            TurnId::new("limit-cancel"),
            Context::new(),
            opts,
            CallControl::new(token, None),
        )
        .await;
    assert!(matches!(
        cause(&out),
        TurnInterruption::MaxToolCalls {
            limit: 0,
            declared_before: 0,
            declared_this_round: 1,
            ..
        }
    ));
    assert_eq!(out.context.blocks().len(), 2);
    assert_eq!(out.uncommitted_tool_batch.unwrap().calls().len(), 1);
}

/// Cancels the caller's token and reports success.
struct CancelsThenReturns;
#[async_trait]
impl ToolBatchProcessor for CancelsThenReturns {
    async fn process(
        &self,
        _: &mut ToolBatch,
        ctx: &ProcessorContext<'_>,
    ) -> Result<(), ProcessorError> {
        ctx.control.cancellation_token().cancel();
        Ok(())
    }
}
struct CountsRuns(Arc<AtomicUsize>);
#[async_trait]
impl ToolBatchProcessor for CountsRuns {
    async fn process(
        &self,
        _: &mut ToolBatch,
        _: &ProcessorContext<'_>,
    ) -> Result<(), ProcessorError> {
        self.0.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
}

fn result_blocks(out: &TurnOutcome) -> usize {
    out.context
        .blocks()
        .iter()
        .filter(|block| matches!(block.content(), BlockContent::ToolResult(_)))
        .count()
}

#[tokio::test]
async fn a_stop_from_the_last_after_processor_commits_the_finished_batch() {
    let gateway = RecordingGateway::scripted(vec![
        Ok(tooluse_output("", "echo", json!({}))),
        Ok(endturn_output("never requested")),
    ]);
    let executor = ToolExecutor::new(
        vec![Arc::new(EchoTool)],
        ToolExecutorOptions::default().with_after(vec![Arc::new(CancelsThenReturns)]),
    )
    .unwrap();
    let runner = TurnRunner::new(gateway.clone(), Arc::new(executor));
    let committed = Arc::new(AtomicUsize::new(0));
    let seen = committed.clone();
    let opts = options().with_observer(Arc::new(move |event| {
        if let RunEvent::BlocksCommitted { blocks, .. } = event
            && blocks
                .iter()
                .any(|block| matches!(block.content(), BlockContent::ToolResult(_)))
        {
            seen.fetch_add(1, Ordering::SeqCst);
        }
    }));
    let out = runner
        .run(TurnId::new("late"), Context::new(), opts, ctrl())
        .await;
    assert!(matches!(
        cause(&out),
        TurnInterruption::Cancelled {
            invocation_id: Some(_),
            ..
        }
    ));
    assert!(out.uncommitted_tool_batch.is_none());
    assert_eq!(result_blocks(&out), 1);
    assert_eq!(committed.load(Ordering::SeqCst), 1);
    // The stop still holds: no second model round was requested.
    assert_eq!(gateway.recorded.lock().unwrap().len(), 1);
}

#[tokio::test]
async fn a_stop_during_the_after_phase_still_returns_the_batch() {
    let later = Arc::new(AtomicUsize::new(0));
    let executor = ToolExecutor::new(
        vec![Arc::new(EchoTool)],
        ToolExecutorOptions::default().with_after(vec![
            Arc::new(CancelsThenReturns),
            Arc::new(CountsRuns(later.clone())),
        ]),
    )
    .unwrap();
    let runner = TurnRunner::new(
        RecordingGateway::scripted(vec![Ok(tooluse_output("", "echo", json!({})))]),
        Arc::new(executor),
    );
    let out = runner
        .run(TurnId::new("mid"), Context::new(), options(), ctrl())
        .await;
    assert!(matches!(cause(&out), TurnInterruption::Cancelled { .. }));
    // The second after-processor never ran, so host policy was not applied
    // and nothing is committed on the host's behalf.
    assert_eq!(later.load(Ordering::SeqCst), 0);
    assert_eq!(result_blocks(&out), 0);
    let batch = out.uncommitted_tool_batch.as_ref().unwrap();
    assert_eq!(batch.completed_len(), 1);
}

#[tokio::test]
async fn a_deadline_passing_after_processing_commits_the_finished_batch() {
    let runner = runner_with(
        RecordingGateway::scripted(vec![
            Ok(tooluse_output("", "echo", json!({}))),
            Ok(endturn_output("never requested")),
        ]),
        vec![Arc::new(EchoTool)],
    );
    let deadline = Instant::now() + Duration::from_secs(2);
    // The observer is synchronous: holding the batch-returned notification
    // until the deadline has passed puts the stop after processing and
    // before the commit.
    let opts = options().with_observer(Arc::new(move |event| {
        if let RunEvent::ToolBatchReturned { result, .. } = event {
            assert!(result.is_ok());
            while Instant::now() <= deadline {
                std::thread::sleep(Duration::from_millis(10));
            }
        }
    }));
    let out = runner
        .run(
            TurnId::new("deadline"),
            Context::new(),
            opts,
            CallControl::new(CancellationToken::new(), Some(deadline)),
        )
        .await;
    assert!(matches!(
        cause(&out),
        TurnInterruption::DeadlineExceeded {
            invocation_id: Some(_),
            ..
        }
    ));
    assert!(out.uncommitted_tool_batch.is_none());
    assert_eq!(result_blocks(&out), 1);
}

/// Cancels the caller's token, then returns an ordinary result.
struct CancelsThenSucceeds;
#[async_trait]
impl Tool for CancelsThenSucceeds {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition::new("echo", "cancels, then answers", json!({"type": "object"}))
    }
    async fn execute(
        &self,
        call: &ToolCallContext,
        control: &CallControl,
        _store: Option<&dyn ArtifactStore>,
    ) -> ToolResultPayload {
        control.cancellation_token().cancel();
        ToolResultPayload::new(
            call.call_block_id,
            ToolResultStatus::Succeeded,
            ToolOutput::new(json!("done")),
        )
    }
}

#[tokio::test]
async fn with_no_after_processors_a_batch_whose_tools_returned_is_committed() {
    let gateway = RecordingGateway::scripted(vec![
        Ok(tooluse_output("", "echo", json!({}))),
        Ok(endturn_output("never requested")),
    ]);
    let runner = runner_with(gateway.clone(), vec![Arc::new(CancelsThenSucceeds)]);
    let out = runner
        .run(TurnId::new("no-after"), Context::new(), options(), ctrl())
        .await;
    assert!(matches!(cause(&out), TurnInterruption::Cancelled { .. }));
    assert!(out.uncommitted_tool_batch.is_none());
    assert_eq!(result_blocks(&out), 1);
    assert_eq!(gateway.recorded.lock().unwrap().len(), 1);
}

/// Whether a commit is the runner's record of a tool change.
fn is_tool_change(blocks: &[ContextBlock]) -> bool {
    blocks
        .iter()
        .all(|block| matches!(block.content(), BlockContent::ToolChange(_)))
}