inky-engine 2.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
//! A generation session: owns the context (tokens + KV/conv state on the GPU), prefill and decode loops.

use crate::engine::{Engine, Lane, Run};
use crate::metal::{wait_all, wait_or_drain};
use crate::sampler::Sampler;
use crate::tokenizer::Tokenizer;
use crate::stream_text::stream_text;
use objc2_metal::MTLCommandBuffer;
use std::collections::VecDeque;
use std::time::{Duration, Instant};

pub struct Session<'a> {
    pub eng: &'a Engine,
    /// this session's stream state (cache, convolution rows, tokens)
    pub lane: Lane,
    pub tk: &'a Tokenizer,
    /// tokens whose K/V and conv state are in the cache
    pub n_past: usize,
    /// a sampled token not yet fed through the model (it becomes the first input of the next step)
    pending: Option<u32>,
    pub stats: Stats,
    /// Monotone block index up to which expired `BlockKind::Window` blocks have been retired on a blocked lane.
    win_retired_to: usize,
    /// Monotone post-pin cursor while `ckpt_pin_end` is active so post-pin retirement stays O(1) amortized.
    win_retired_after_pin: usize,
    /// Committed `n_past` pinned by an active `run_chat_turn` checkpoint so its `Window` blocks survive rollback.
    ckpt_pin_end: Option<usize>,
}

#[derive(Default, Clone, Copy)]
pub struct Stats { pub prompt_tokens: usize, pub prompt_time: Duration, pub gen_tokens: usize, pub gen_time: Duration,
                   /// largest activation buffer (decode arena + prefill arena) any prefill needed, bytes
                   pub peak_scratch: usize }

/// Snapshot of a [`Session`] before an interactive CLI turn (`t-audit-engine-cli-step-status`),
/// allowing a failed prefill chunk or decode step to roll back K/V, convolution state, `n_past`,
/// `pending`, and `stats` cleanly for the next turn.
pub struct TurnCheckpoint {
    n_past: usize,
    pending: Option<u32>,
    stats: Stats,
    cs: Vec<u8>,
    window_kv: Vec<crate::engine::KvUndo>,
    win_retired_to: usize,
}

impl<'a> Session<'a> {
    pub fn new(eng: &'a Engine, tk: &'a Tokenizer) -> Session<'a> {
        let force_pooled = std::env::var("INK_POOLED_SESSION")
            .is_ok_and(|v| !v.is_empty() && v != "0");
        let use_pooled = (eng.max_ctx > crate::engine::MAX_CONTIGUOUS_CONTEXT || force_pooled)
            && !crate::engine::KV_DISK.load(std::sync::atomic::Ordering::Relaxed);
        let lane = if use_pooled {
            Lane::new_blocked(eng, eng.max_ctx)
        } else {
            Lane::new(eng)
        };
        Self::with_lane(eng, tk, lane)
    }
    /// a new session on an existing lane: its buffers are kept (no regrowth), its contents forgotten
    pub fn with_lane(eng: &'a Engine, tk: &'a Tokenizer, lane: Lane) -> Session<'a> {
        if lane.is_blocked() {
            eng.discard_pending_sketch_updates();
            lane.block_table()
                .borrow_mut()
                .clear_entries(&mut eng.block_pool().borrow_mut())
                .expect("clear pooled session block table");
        }
        eng.on(&lane).reset();
        Session {
            eng,
            tk,
            lane,
            n_past: 0,
            pending: None,
            stats: Stats::default(),
            win_retired_to: 0,
            win_retired_after_pin: 0,
            ckpt_pin_end: None,
        }
    }
    /// give the lane back, to start another session on it
    pub fn into_lane(self) -> Lane { self.lane }
    /// the engine working on this session's lane
    pub fn run(&self) -> Run<'_> { self.eng.on(&self.lane) }

    pub fn ctx_left(&self) -> usize { self.eng.max_ctx.saturating_sub(self.n_past + 1) }

    fn pregrow_pooled_for(&self, target_end: usize) -> Result<(), String> {
        grow_pooled_session_pools(
            &mut self.eng.block_pool().borrow_mut(),
            self.eng.max_ctx,
            self.eng.chunk,
            target_end,
        )
    }

    fn ensure_pooled_span(&mut self, p0: usize, t: usize) -> Result<(), String> {
        map_pooled_session_span(
            &mut self.eng.block_pool().borrow_mut(),
            &mut self.lane.block_table().borrow_mut(),
            self.eng.max_ctx,
            p0,
            t,
        )
    }

    fn commit_pooled_span(&mut self, p0: usize, t: usize) {
        use crate::blocks::{BlockIndex, BlockKind, BLOCK};
        let end = p0 + t;
        let lo_blk = p0 / BLOCK;
        let hi_blk = (end - 1) / BLOCK;
        {
            let tbl = self.lane.block_table().borrow();
            let mut pools = self.eng.block_pool().borrow_mut();
            for b in lo_blk..=hi_blk {
                let bi = BlockIndex::new(b as u32);
                let block_len = (end - b * BLOCK).min(BLOCK) as u32;
                for kind in [BlockKind::Full, BlockKind::Window] {
                    if let Some(e) = tbl.get(kind, bi).unwrap() {
                        pools
                            .of_mut(kind)
                            .record_mut(e.slot())
                            .unwrap()
                            .set_length(block_len)
                            .expect("set pooled session block length");
                    }
                }
            }
        }
        self.retire_pooled_window(end);
    }

    fn retire_pooled_window(&mut self, end_pos: usize) {
        use crate::blocks::{BlockIndex, BlockKind, BLOCK, WINDOW};
        if end_pos == 0 {
            return;
        }
        let min_win_blk = end_pos.saturating_sub(WINDOW) / BLOCK;
        let pin_range = self
            .ckpt_pin_end
            .filter(|&p| p > 0)
            .map(|p| (p.saturating_sub(WINDOW) / BLOCK, (p - 1) / BLOCK));
        let stop_blk = match pin_range {
            Some((pin_lo, _)) => min_win_blk.min(pin_lo),
            None => min_win_blk,
        };
        let mut pools = self.eng.block_pool().borrow_mut();
        let mut tbl = self.lane.block_table().borrow_mut();
        for b in self.win_retired_to..stop_blk {
            let bi = BlockIndex::new(b as u32);
            if tbl.get(BlockKind::Window, bi).unwrap().is_some() {
                tbl.clear_kind_entry(&mut pools.window, bi).unwrap();
            }
        }
        if stop_blk > self.win_retired_to {
            self.win_retired_to = stop_blk;
        }
        if let Some((_, pin_hi)) = pin_range {
            let start = self.win_retired_after_pin.max(pin_hi + 1);
            if min_win_blk > start {
                for b in start..min_win_blk {
                    let bi = BlockIndex::new(b as u32);
                    if tbl.get(BlockKind::Window, bi).unwrap().is_some() {
                        tbl.clear_kind_entry(&mut pools.window, bi).unwrap();
                    }
                }
                self.win_retired_after_pin = min_win_blk;
            }
        }
    }

    /// Snapshot valid session context (`0..n_past`) before a chat turn so a failed Metal command
    /// buffer leaves the session state intact for the next turn.
    pub fn checkpoint(&self) -> TurnCheckpoint {
        let base_lo = self.n_past.saturating_sub(crate::blocks::WINDOW);
        let win_lo = if self.lane.is_blocked() {
            base_lo
                .max(self.win_retired_to.saturating_mul(crate::blocks::BLOCK))
                .min(self.n_past)
        } else {
            base_lo
        };
        let win_cnt = self.n_past - win_lo;
        if win_cnt > 0 && self.run().tier_on() {
            self.run().tier_leave(self.n_past);
        }
        let window_kv = if win_cnt > 0 {
            self.eng.snapshot_kv_positions(&self.lane, win_lo, win_cnt)
        } else {
            Vec::new()
        };
        TurnCheckpoint {
            n_past: self.n_past,
            pending: self.pending,
            stats: self.stats,
            cs: self.run().get_cs(),
            window_kv,
            win_retired_to: self.win_retired_to,
        }
    }

    /// Restore `self` to `ckpt` after a failed turn. When `ckpt.n_past == 0`, resets the lane
    /// cleanly; otherwise leaves any active `--kv-disk` hot ring and truncates cold-file metadata
    /// past `ckpt.n_past` before restoring `cs`, live sliding-window K/V rows, and zeroing the
    /// uncommitted tail.
    pub fn rollback(&mut self, ckpt: TurnCheckpoint) {
        self.ckpt_pin_end = None;
        self.win_retired_after_pin = 0;
        if ckpt.n_past == 0 {
            if self.lane.is_blocked() {
                self.eng.discard_pending_sketch_updates();
                self.lane
                    .block_table()
                    .borrow_mut()
                    .clear_entries(&mut self.eng.block_pool().borrow_mut())
                    .expect("clear pooled session block table on rollback");
            }
            self.run().reset();
            self.win_retired_to = 0;
        } else {
            self.run().set_cs(&ckpt.cs);
            self.run().tier_rollback(ckpt.n_past);
            for undo in &ckpt.window_kv {
                self.eng.restore_kv_pos(&self.lane, undo);
            }
            self.eng.clear_kv_tail(&self.lane, ckpt.n_past);
            self.win_retired_to = ckpt.win_retired_to;
        }
        self.n_past = ckpt.n_past;
        self.pending = ckpt.pending;
        self.stats = ckpt.stats;
    }

    /// Execute one complete chat turn (`prefill` + `generate` + `Renderer::end`), rolling back
    /// session state and closing any open ANSI styling if any Metal step or sample fails.
    pub fn run_chat_turn(
        &mut self,
        toks: &[u32],
        max_gen: usize,
        show_thinking: bool,
        raw: bool,
        sampler: &mut Sampler,
        out: &mut impl std::io::Write,
    ) -> Result<usize, String> {
        let ckpt = self.checkpoint();
        if self.lane.is_blocked() {
            self.ckpt_pin_end = Some(ckpt.n_past);
            self.win_retired_after_pin = 0;
        }
        let first = match self.prefill(toks) {
            Ok(tok) => tok,
            Err(err) => {
                self.rollback(ckpt);
                return Err(err);
            }
        };
        let mut r = Renderer::new(show_thinking, raw);
        let max = max_gen.min(self.ctx_left().saturating_sub(4));
        let tk = self.tk;
        let res = self.generate(first, max, sampler, |t| {
            r.push(tk, t, out);
            true
        });
        r.end(out);
        if let Err(err) = res {
            self.rollback(ckpt);
            return Err(err);
        }
        if self.lane.is_blocked() {
            self.ckpt_pin_end = None;
            self.win_retired_after_pin = 0;
            self.retire_pooled_window(self.n_past);
        }
        res
    }

    /// Feed `toks` (preceded by any pending sampled token) through the model in prefill chunks.
    /// Returns the greedy next token (argmax of the last position); logits stay available in the engine.
    /// After an error, discard or reset the lane before using it for another inference.
    pub fn prefill(&mut self, toks: &[u32]) -> Result<u32, String> {
        let mut all: Vec<u32> = self.pending.take().into_iter().collect();
        all.extend_from_slice(toks);
        if all.is_empty() {
            return Err("cannot prefill an empty token sequence".into());
        }
        if self.n_past.saturating_add(all.len()) >= self.eng.max_ctx {
            return Err(format!("context full ({} tokens)", self.eng.max_ctx));
        }
        let t0 = Instant::now();
        if self.lane.is_blocked() {
            self.run().set_tokens(self.n_past, &all);
            let end = self.n_past + all.len();
            self.pregrow_pooled_for((end + 128).min(self.eng.max_ctx))?;
            self.eng.ensure_batch(all.len().min(self.eng.chunk).max(2));
            self.eng.ensure_dbatch(1);
            self.stats.peak_scratch = self.stats.peak_scratch.max(self.run().mem().1);
            let mut p0 = self.n_past;
            while p0 < end {
                let t = (end - p0).min(self.eng.chunk);
                self.ensure_pooled_span(p0, t)?;
                let cb = self.eng.gpu.cmd();
                self.run().encode_prefill(&cb, p0, t, p0 + t == end, true);
                cb.commit();
                self.eng.wait_step(&cb, "prefill", p0)?;
                self.commit_pooled_span(p0, t);
                p0 += t;
            }
            self.n_past = end;
            self.stats.prompt_tokens += all.len();
            self.stats.prompt_time += t0.elapsed();
            return Ok(self.run().token_at(end));
        }
        self.run().tier_leave(self.n_past);       // (--kv-disk) a prefill attends through the whole cache in memory
        self.run().set_tokens(self.n_past, &all);
        let end = self.n_past + all.len();
        self.run().reserve(end + 1, true);
        self.eng.ensure_batch(all.len().min(self.eng.chunk));
        self.stats.peak_scratch = self.stats.peak_scratch.max(self.run().mem().1);
        let mut p0 = self.n_past;
        let mut last = None;
        while p0 < end {
            let t = (end - p0).min(self.eng.chunk);
            let cb = self.eng.gpu.cmd();
            self.run().encode_prefill(&cb, p0, t, p0 + t == end, true);
            cb.commit();
            // Let Metal run the next chunk while the CPU checks the previous one.
            if let Some((pos, prev)) = last.replace((p0, cb)) {
                wait_or_drain((pos, &prev), last.as_ref().map(|(pos, cb)| (*pos, cb)),
                              |(pos, cb)| self.eng.wait_step(cb, "prefill", pos))?;
            }
            p0 += t;
        }
        if let Some((pos, cb)) = last {
            self.eng.wait_step(&cb, "prefill", pos)?;
        }
        self.n_past = end;
        self.stats.prompt_tokens += all.len();
        self.stats.prompt_time += t0.elapsed();
        Ok(self.run().token_at(end))
    }

    /// Generate up to `max` tokens after a prefill. `on_token` returns false to stop early.
    /// Greedy decoding is fully pipelined on the GPU: the argmax of step p is the embedding input of step p+1, so the CPU
    /// never sits between steps. Exactly two steps are kept in flight, so the in-flight step always processes the token
    /// just emitted: when generation stops, the context (KV + conv state) is exactly "everything emitted so far".
    /// Sampling reads the logits back each step.
    /// After an error, discard or reset the lane before using it for another inference.
    pub fn generate(&mut self, first: u32, max: usize, sampler: &mut Sampler, mut on_token: impl FnMut(u32) -> bool) -> Result<usize, String> {
        let t0 = Instant::now();
        if self.lane.is_blocked() {
            let eos = self.tk.eos;
            if max == 0 {
                self.eng.release_batch();
                return Ok(0);
            }
            let mut tok = if sampler.greedy() {
                first
            } else {
                let softcap = self.eng.effective_sampler_softcap(0);
                let res = if self.eng.loopcd_omega() > 0.0 {
                    sampler.sample_next_with_ban_and_softcap(&self.eng.span_logits(0), None, softcap)
                } else {
                    sampler.sample_next_with_ban_and_softcap(&self.run().logits(), None, softcap)
                };
                res.map_err(|err| format!("model sampling failed: {err:?}"))?
            };
            self.eng.release_batch();
            self.eng.ensure_batch(2);
            self.eng.ensure_dbatch(1);
            let mut n = 1usize;
            let mut stop = tok == eos || !on_token(tok) || n >= max || self.ctx_left() < 2;
            while !stop {
                let pos = self.n_past;
                self.run().set_tokens(pos, &[tok]);
                self.ensure_pooled_span(pos, 1)?;
                let cb = self.eng.gpu.cmd();
                self.eng.encode_decode(
                    &cb,
                    &[crate::engine::Span { lane: &self.lane, p0: pos, t: 1 }],
                    true,
                    sampler.greedy(),
                );
                cb.commit();
                self.eng.wait_step(&cb, "decode", pos)?;
                self.commit_pooled_span(pos, 1);
                self.n_past = pos + 1;
                tok = if sampler.greedy() {
                    self.run().token_at(pos + 1)
                } else {
                    sampler
                        .sample_next_with_ban_and_softcap(
                            &self.eng.span_logits(0),
                            None,
                            self.eng.effective_sampler_softcap(0),
                        )
                        .map_err(|err| format!("model sampling failed: {err:?}"))?
                };
                n += 1;
                stop = tok == eos || !on_token(tok) || n >= max || self.ctx_left() < 2;
            }
            self.pending = Some(tok);
            self.stats.gen_tokens += n;
            self.stats.gen_time += t0.elapsed();
            return Ok(n);
        }
        let eng = self.eng.on(&self.lane);
        let eos = self.tk.eos;
        eng.release_batch();      // the prefill arena is not needed while generating
        if max == 0 { return Ok(0); }
        let mut tok = if sampler.greedy() {
            first
        } else {
            sampler
                .sample_next_with_ban_and_softcap(&eng.logits(), None, self.eng.effective_sampler_softcap(0))
                .map_err(|err| format!("model sampling failed: {err:?}"))?
        };
        let mut n = 1usize;
        let mut stop = tok == eos || !on_token(tok) || n >= max || self.ctx_left() < 2;
        if sampler.greedy() {
            if stop { self.pending = Some(tok); }
            else {
                eng.set_tokens(self.n_past, &[tok]);
                let mut inflight = VecDeque::with_capacity(2);
                let step = |pos: usize| (pos, eng.step(pos, true, true));
                eng.gen_reserve(self.n_past);
                inflight.push_back(step(self.n_past));
                loop {
                    if inflight.len() < 2 {
                        if let Some(&(last_pos, _)) = inflight.back() {
                            let pos = last_pos + 1;
                            if pos >= eng.gen_capacity() {
                                // the K/V buffers must grow (or, with --kv-disk, be re-sized): nothing may be in flight meanwhile
                                wait_all(&inflight, |(pos, cmd)| cmd.wait(*pos))?;
                                eng.gen_reserve(pos);
                            }
                            inflight.push_back(step(pos));
                        }
                    }
                    let Some((pos, cmd)) = inflight.pop_front() else { break };
                    wait_or_drain(&(pos, cmd), &inflight, |(pos, cmd)| cmd.wait(*pos))?;
                    self.n_past = pos + 1;
                    tok = eng.token_at(pos + 1);
                    n += 1;
                    stop = tok == eos || !on_token(tok) || n >= max || self.ctx_left() < 3;
                    if stop {
                        // the remaining in-flight step consumes `tok` (a real token): keep it in the context
                        match inflight.pop_front() {
                            Some((p2, cmd)) => {
                                cmd.wait(p2)?;
                                self.n_past = p2 + 1;
                                self.pending = None;
                            }
                            None => self.pending = Some(tok),
                        }
                        break;
                    }
                }
            }
        } else {
            while !stop {
                eng.set_tokens(self.n_past, &[tok]);
                eng.gen_reserve(self.n_past);
                eng.step(self.n_past, true, false).wait(self.n_past)?;
                self.n_past += 1;
                tok = sampler
                    .sample_next_with_ban_and_softcap(&eng.logits(), None, self.eng.effective_sampler_softcap(0))
                    .map_err(|err| format!("model sampling failed: {err:?}"))?;
                n += 1;
                stop = tok == eos || !on_token(tok) || n >= max || self.ctx_left() < 2;
            }
            self.pending = Some(tok);
        }
        self.stats.gen_tokens += n;
        self.stats.gen_time += t0.elapsed();
        Ok(n)
    }
}

/// Grow the shared pools ahead of a pooled `Session` prefill that ends at `target_end`: `Window` slots for one
/// prefill chunk plus the sliding window, `Full` slots for every block up to `target_end` (growing geometrically,
/// never past `max_ctx`). A pool that cannot grow is an error, not a panic.
fn grow_pooled_session_pools(
    pools: &mut crate::blocks::BlockPools,
    max_ctx: usize,
    chunk: usize,
    target_end: usize,
) -> Result<(), String> {
    use crate::blocks::{span_bound, BLOCK, WINDOW};
    let want_full = target_end.min(max_ctx).div_ceil(BLOCK).max(1);
    let want_win = span_bound(chunk.max(BLOCK)).max((WINDOW / BLOCK) + 20).max(48);
    if pools.window.len() < want_win {
        let add = want_win - pools.window.len();
        pools
            .window
            .grow_by(add)
            .map_err(|e| format!("cannot grow the Window block pool to {want_win} blocks: {e}"))?;
    }
    if pools.full.len() < want_full {
        let max_full = max_ctx.div_ceil(BLOCK).max(want_full);
        let cur = pools.full.len();
        let geom = cur.saturating_add((cur / 2).max(64)).min(max_full);
        let target = want_full.max(geom);
        pools
            .full
            .grow_by(target - cur)
            .map_err(|e| format!("cannot grow the Full block pool to {target} blocks: {e}"))?;
    }
    Ok(())
}

/// Map a `Full` and a `Window` block for every 64-token block that positions `[p0, p0 + t)` of a pooled `Session`
/// lane touch, growing a pool that has no free slot. A pool that cannot grow is an error, not a panic.
fn map_pooled_session_span(
    pools: &mut crate::blocks::BlockPools,
    tbl: &mut crate::blocks::BlockTable,
    max_ctx: usize,
    p0: usize,
    t: usize,
) -> Result<(), String> {
    use crate::blocks::{BlockIndex, BlockKind, BLOCK};
    let lo_blk = p0 / BLOCK;
    let hi_blk = (p0 + t - 1) / BLOCK;
    let max_full = max_ctx.div_ceil(BLOCK).max(hi_blk + 1);
    for b in lo_blk..=hi_blk {
        let bi = BlockIndex::new(b as u32);
        for kind in [BlockKind::Full, BlockKind::Window] {
            if tbl.get(kind, bi).map_err(|e| format!("block {b} of a pooled session: {e}"))?.is_some() {
                continue;
            }
            let pool = pools.of_mut(kind);
            if pool.lowest_free().is_none() {
                let cur = pool.len();
                let add = if kind == BlockKind::Full {
                    (cur / 2).max(64).min(max_full.saturating_sub(cur)).max(1)
                } else {
                    16
                };
                pool.grow_by(add)
                    .map_err(|e| format!("cannot grow the {kind:?} block pool past {cur} blocks: {e}"))?;
            }
            let slot = pool.lowest_free().ok_or_else(|| format!("no free {kind:?} block after growth"))?;
            pool.take_unzeroed(slot).map_err(|e| format!("take {kind:?} block for position {p0}: {e}"))?;
            let gen = pool.record(slot).map_err(|e| format!("{kind:?} block record: {e}"))?.generation();
            tbl.fill(pool, bi, slot, gen).map_err(|e| format!("map {kind:?} block {b}: {e}"))?;
        }
    }
    Ok(())
}

/// Streams model output: hides protocol tokens, dims the reasoning, emits valid UTF-8 only.
pub struct Renderer { buf: Vec<u8>, pub thinking: bool, pub show_thinking: bool, pub raw: bool, think_note: bool }

impl Renderer {
    pub fn new(show_thinking: bool, raw: bool) -> Renderer { Renderer { buf: Vec::new(), thinking: false, show_thinking, raw, think_note: false } }

    pub fn push(&mut self, tk: &Tokenizer, t: u32, out: &mut impl std::io::Write) {
        if self.raw { self.emit(&tk.decode_bytes(t), out); return; }
        if tk.is_special(t) {
            self.flush_text(true, out);
            let s = String::from_utf8_lossy(&tk.decode_bytes(t)).to_string();
            match s.as_str() {
                "<|content_thinking|>" => {
                    self.thinking = true;
                    if self.show_thinking { let _ = write!(out, "\x1b[2m"); } else if !self.think_note { let _ = write!(out, "\x1b[2m(thinking…)\x1b[0m "); self.think_note = true; }
                }
                "<|content_text|>" => { self.thinking = false; }
                "<|end_message|>" => { if self.thinking && self.show_thinking { let _ = write!(out, "\x1b[0m\n\n"); } self.thinking = false; }
                "<|message_model|>" | "<|content_model_end_sampling|>" => {}
                _ => { let _ = write!(out, "{s}"); }
            }
            let _ = out.flush();
            return;
        }
        if self.thinking && !self.show_thinking { return; }
        self.emit(&tk.decode_bytes(t), out);
    }

    fn emit(&mut self, bytes: &[u8], out: &mut impl std::io::Write) {
        self.buf.extend_from_slice(bytes);
        self.flush_text(false, out);
    }

    fn flush_text(&mut self, end: bool, out: &mut impl std::io::Write) {
        stream_text(&mut self.buf, end, |text| {
            let _ = out.write_all(text.as_bytes());
            let _ = out.flush();
        });
    }

    pub fn end(&mut self, out: &mut impl std::io::Write) {
        self.flush_text(true, out);
        if self.thinking && self.show_thinking { let _ = write!(out, "\x1b[0m"); }
        let _ = out.flush();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn push_bytes(renderer: &mut Renderer, tk: &Tokenizer, bytes: &[u8], out: &mut Vec<u8>) {
        for &byte in bytes {
            renderer.push(tk, tk.eos + 1 + u32::from(byte), out);
        }
    }

    #[test]
    fn renderer_recovers_valid_text_and_flushes_at_end() {
        let tk = Tokenizer::for_byte_test();
        for raw in [false, true] {
            let mut renderer = Renderer::new(false, raw);
            let mut out = Vec::new();
            push_bytes(&mut renderer, &tk, b"\xffvalid text\xe2", &mut out);
            assert_eq!(out, "�valid text".as_bytes());
            push_bytes(&mut renderer, &tk, b"\x82\xac\xf0\x9f", &mut out);
            assert_eq!(out, "�valid text€".as_bytes());
            renderer.end(&mut out);
            assert_eq!(out, "�valid text€�".as_bytes());
        }
    }

    #[test]
    fn renderer_does_not_join_utf8_across_content_boundaries() {
        let tk = Tokenizer::for_byte_test();
        let mut renderer = Renderer::new(false, false);
        let mut out = Vec::new();
        push_bytes(&mut renderer, &tk, b"\xe2", &mut out);
        for token in tk.encode("<|content_thinking|>hidden<|end_message|><|content_text|>", true) {
            renderer.push(&tk, token, &mut out);
        }
        push_bytes(&mut renderer, &tk, b"\x82\xactext", &mut out);
        renderer.end(&mut out);
        assert_eq!(out, "�\x1b[2m(thinking…)\x1b[0m ��text".as_bytes());
    }

    #[test]
    fn failed_command_drains_later_work_without_consuming_results() {
        let mut waited = Vec::new();
        let mut consumed = false;
        let result = wait_or_drain(0, [1, 2], |command| {
            waited.push(command);
            if command == 0 { Err("first command failed".into()) } else { Ok(()) }
        }).map(|_| consumed = true);
        assert_eq!(result, Err("first command failed".into()));
        assert_eq!(waited, [0, 1, 2]);
        assert!(!consumed);

        waited.clear();
        wait_or_drain(0, [1], |command| { waited.push(command); Ok(()) }).unwrap();
        assert_eq!(waited, [0]);
    }

    #[test]
    fn wait_all_preserves_first_error_and_checks_final_command() {
        for (failures, expected) in [
            ([true, true, false], Err("command 0".into())),
            ([false, false, true], Err("command 2".into())),
            ([false, false, false], Ok(())),
        ] {
            let mut waited = Vec::new();
            let result = wait_all(failures.into_iter().enumerate(), |(command, failed)| {
                waited.push(command);
                if failed { Err(format!("command {command}")) } else { Ok(()) }
            });
            assert_eq!(result, expected);
            assert_eq!(waited, [0, 1, 2]);
        }
    }

    #[test]
    fn renderer_replaces_bad_utf8_with_replacement_char_and_keeps_following_text() {
        // Standalone invalid byte followed by >8 bytes of valid ASCII in one chunk and subsequent chunks.
        let mut r = Renderer::new(true, true);
        let mut out = Vec::new();
        r.emit(b"\xffhello, world!", &mut out);
        r.emit(b" more text", &mut out);
        r.end(&mut out);
        assert_eq!(String::from_utf8(out).unwrap(), "\u{FFFD}hello, world! more text");

        // Split valid 4-byte emoji across four 1-byte chunks, then an incomplete 3-byte prefix followed by valid ASCII,
        // then a trailing incomplete 2-byte prefix flushed at end().
        let mut r2 = Renderer::new(true, true);
        let mut out2 = Vec::new();
        for &b in "🦀".as_bytes() {
            r2.emit(&[b], &mut out2);
        }
        r2.emit(&[0xE2, 0x82], &mut out2);
        assert_eq!(String::from_utf8(out2.clone()).unwrap(), "🦀");
        r2.emit(b"kept after truncated sequence", &mut out2);
        r2.emit(&[0xC3], &mut out2);
        r2.end(&mut out2);
        assert_eq!(String::from_utf8(out2).unwrap(), "🦀\u{FFFD}kept after truncated sequence\u{FFFD}");
    }

    fn capped_pools(full_per_slab: usize, window_per_slab: usize) -> crate::blocks::BlockPools {
        use crate::blocks::{BlockKind, BlockPool, BlockPools, KvMode};
        BlockPools {
            window: BlockPool::host_capped(BlockKind::Window, KvMode::Kv4, window_per_slab),
            full: BlockPool::host_capped(BlockKind::Full, KvMode::Kv4, full_per_slab),
        }
    }

    #[test]
    fn pooled_session_pregrow_sizes_the_pools_and_reports_a_capped_pool() {
        use crate::blocks::{BLOCK, MAX_SLABS};
        let max_ctx = 2_097_152;
        // Room for every request below: 4 slabs of 64 Full slots and of 16 Window slots.
        let mut pools = capped_pools(64, 16);
        grow_pooled_session_pools(&mut pools, max_ctx, 64, 3 * BLOCK + 1).unwrap();
        assert_eq!(pools.window.len(), 48);
        assert_eq!(pools.full.len(), 64, "the first growth is geometric: at least 64 blocks");
        grow_pooled_session_pools(&mut pools, max_ctx, 64, 64 * BLOCK).unwrap();
        assert_eq!((pools.window.len(), pools.full.len()), (48, 64), "a request that fits grows nothing");
        grow_pooled_session_pools(&mut pools, max_ctx, 64, 200 * BLOCK).unwrap();
        assert_eq!(pools.full.len(), 200);
        // The engine context bounds the geometric step.
        let mut pools = capped_pools(64, 16);
        grow_pooled_session_pools(&mut pools, 10 * BLOCK, 64, 3 * BLOCK).unwrap();
        assert_eq!(pools.full.len(), 10);
        grow_pooled_session_pools(&mut pools, 10 * BLOCK, 64, 4096 * BLOCK).unwrap();
        assert_eq!(pools.full.len(), 10, "a target past the context is clamped to it");

        // A Full pool that cannot hold the request is an error and stays as it was.
        let mut pools = capped_pools(2, 16);
        assert_eq!(MAX_SLABS * 2, 8);
        let err = grow_pooled_session_pools(&mut pools, max_ctx, 64, 9 * BLOCK).unwrap_err();
        assert!(err.contains("Full block pool") && err.contains("slab cap"), "{err}");
        assert_eq!(pools.full.len(), 0);
        // So is a Window pool too small for one prefill chunk plus the sliding window.
        let mut pools = capped_pools(64, 8);
        let err = grow_pooled_session_pools(&mut pools, max_ctx, 64, BLOCK).unwrap_err();
        assert!(err.contains("Window block pool to 48 blocks"), "{err}");
        assert_eq!((pools.window.len(), pools.full.len()), (0, 0));
    }

    #[test]
    fn pooled_session_span_maps_each_block_once_and_reports_a_full_pool() {
        use crate::blocks::{BlockIndex, BlockKind, BlockTable, BLOCK};
        // 8 Full slots and 32 Window slots in all; the lane's context is 8 blocks.
        let mut pools = capped_pools(2, 8);
        let max_ctx = 8 * BLOCK;
        let mut tbl = BlockTable::new(16).unwrap();
        let mapped = |tbl: &BlockTable, kind: BlockKind| -> Vec<u32> {
            (0..16).filter(|&b| tbl.get(kind, BlockIndex::new(b)).unwrap().is_some()).collect()
        };

        // A span inside one block, then one that straddles three.
        map_pooled_session_span(&mut pools, &mut tbl, max_ctx, 5, 1).unwrap();
        assert_eq!(mapped(&tbl, BlockKind::Full), [0]);
        assert_eq!(mapped(&tbl, BlockKind::Window), [0]);
        assert_eq!((pools.full.len(), pools.window.len()), (8, 16));
        map_pooled_session_span(&mut pools, &mut tbl, max_ctx, BLOCK - 1, BLOCK + 2).unwrap();
        assert_eq!(mapped(&tbl, BlockKind::Full), [0, 1, 2]);
        assert_eq!(mapped(&tbl, BlockKind::Window), [0, 1, 2]);
        // Mapping a span again takes no further slot and keeps every entry.
        let before: Vec<_> = tbl.entries().collect();
        map_pooled_session_span(&mut pools, &mut tbl, max_ctx, 0, 3 * BLOCK).unwrap();
        assert_eq!(tbl.entries().collect::<Vec<_>>(), before);
        for (_, entry) in tbl.entries() {
            assert_eq!(pools.of(entry.kind()).record(entry.slot()).unwrap().refs(), 1);
        }

        // The rest of the context fits exactly.
        map_pooled_session_span(&mut pools, &mut tbl, max_ctx, 3 * BLOCK, 5 * BLOCK).unwrap();
        assert_eq!(mapped(&tbl, BlockKind::Full), (0..8).collect::<Vec<_>>());
        assert!(pools.full.lowest_free().is_none());
        // One block more than the Full pool can hold is an error; the mapped blocks stay mapped.
        let before: Vec<_> = tbl.entries().collect();
        let err = map_pooled_session_span(&mut pools, &mut tbl, max_ctx, 8 * BLOCK, 1).unwrap_err();
        assert!(err.contains("Full block pool past 8 blocks") && err.contains("slab cap"), "{err}");
        assert_eq!(tbl.entries().collect::<Vec<_>>(), before);
        assert_eq!(pools.full.len(), 8);

        // A Window pool with no free slot and no room to grow is reported the same way.
        let mut pools = capped_pools(64, 4);
        let mut tbl = BlockTable::new(64).unwrap();
        map_pooled_session_span(&mut pools, &mut tbl, 64 * BLOCK, 0, 16 * BLOCK).unwrap();
        assert_eq!(pools.window.len(), 16);
        let err = map_pooled_session_span(&mut pools, &mut tbl, 64 * BLOCK, 16 * BLOCK, 1).unwrap_err();
        assert!(err.contains("Window block pool past 16 blocks"), "{err}");
        // A block outside the lane's table is an error too.
        let mut tbl = BlockTable::new(2).unwrap();
        let err = map_pooled_session_span(&mut pools, &mut tbl, 64 * BLOCK, 2 * BLOCK, 1).unwrap_err();
        assert!(err.contains("block 2 of a pooled session"), "{err}");
    }

    #[test]
    #[ignore = "requires local Inkling-2-Mini GGUF on M5"]
    fn cli_session_recovers_from_injected_prefill_and_decode_failures() {
        use crate::metal::{clear_wait_failure, inject_wait_failure};

        let model = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
        let mut eng = Engine::load(&model, 256);
        eng.chunk = 32;
        let tk = Tokenizer::load(&eng.g);

        let turn1 = tk.encode("<|message_user|><|content_text|>Count to three.<|end_message|><|message_model|>", true);
        // Make a 48-token turn-2 prompt so prefill splits into an early chunk (32) + final chunk (16 + 1 pending).
        let mut turn2 = tk.encode("<|message_user|><|content_text|>", true);
        while turn2.len() < 46 {
            turn2.extend(tk.encode(" apple banana cherry", false));
        }
        turn2.extend(tk.encode("<|end_message|><|message_model|>", true));
        assert!(turn2.len() > eng.chunk, "turn2 ({}) must span at least 2 prefill chunks ({})", turn2.len(), eng.chunk);

        // Reference clean 2-turn greedy run AND clean 2-turn sampled run.
        let run_clean = |temp: f32| -> (usize, u64, Vec<u8>) {
            let mut sess = Session::new(&eng, &tk);
            let mut s1 = Sampler::new(temp, 64, 0.95, eng.softcap, 12345);
            let mut out1 = Vec::new();
            sess.run_chat_turn(&turn1, 4, true, true, &mut s1, &mut out1).unwrap();
            let mut s2 = Sampler::new(temp, 64, 0.95, eng.softcap, 67890);
            let mut out2 = Vec::new();
            sess.run_chat_turn(&turn2, 4, true, true, &mut s2, &mut out2).unwrap();
            (sess.n_past, eng.lane_hash(&sess.lane), out2)
        };
        let (clean_greedy_npast, clean_greedy_hash, clean_greedy_out2) = run_clean(0.0);
        let (clean_samp_npast, clean_samp_hash, clean_samp_out2) = run_clean(0.8);

        // Exercise all 4 required failure points on turn 2 after turn 1 has already populated context:
        //  (1) early prefill chunk (`prefill`, call 0)
        //  (2) final prefill chunk (`prefill`, call 1)
        //  (3) greedy decode step (`decode`, call 0 — drains pipelined step 1 without consuming!)
        //  (4) sampled decode step (`decode`, call 0)
        for (label, temp, stage, call_idx, want_npast, want_hash, want_out2) in [
            ("early prefill chunk", 0.0f32, "prefill", 0usize, clean_greedy_npast, clean_greedy_hash, &clean_greedy_out2),
            ("final prefill chunk", 0.0f32, "prefill", 1usize, clean_greedy_npast, clean_greedy_hash, &clean_greedy_out2),
            ("greedy decode step", 0.0f32, "decode", 0usize, clean_greedy_npast, clean_greedy_hash, &clean_greedy_out2),
            ("sampled decode step", 0.8f32, "decode", 0usize, clean_samp_npast, clean_samp_hash, &clean_samp_out2),
        ] {
            let mut sess = Session::new(&eng, &tk);
            let mut s1 = Sampler::new(temp, 64, 0.95, eng.softcap, 12345);
            let mut out1 = Vec::new();
            sess.run_chat_turn(&turn1, 4, true, true, &mut s1, &mut out1).unwrap();
            let turn1_npast = sess.n_past;
            let turn1_cs = sess.run().get_cs();
            let turn1_kv: Vec<Vec<u8>> = eng
                .snapshot_kv_positions(&sess.lane, 0, turn1_npast)
                .into_iter()
                .map(|u| u.rows)
                .collect();

            // Inject device/command-buffer failure on turn 2: must return Err and leave session at turn 1 state!
            inject_wait_failure(stage, call_idx);
            let mut s_fail = Sampler::new(temp, 64, 0.95, eng.softcap, 67890);
            let mut fail_out = Vec::new();
            let err = sess.run_chat_turn(&turn2, 4, true, true, &mut s_fail, &mut fail_out);
            clear_wait_failure();
            assert!(err.is_err(), "{label}: injected {stage}[{call_idx}] failure was not reported");
            assert!(std::str::from_utf8(&fail_out).is_ok(), "{label}: output left invalid UTF-8");
            assert_eq!(sess.n_past, turn1_npast, "{label}: n_past mutated after failed turn");
            assert_eq!(sess.run().get_cs(), turn1_cs, "{label}: CS corrupted after failed turn");
            let after_kv: Vec<Vec<u8>> = eng
                .snapshot_kv_positions(&sess.lane, 0, turn1_npast)
                .into_iter()
                .map(|u| u.rows)
                .collect();
            assert_eq!(after_kv, turn1_kv, "{label}: committed KV[0..turn1_npast) corrupted after failed turn");

            // Retry turn 2 on the same session: must match the clean 2-turn session bit-for-bit!
            let mut s2 = Sampler::new(temp, 64, 0.95, eng.softcap, 67890);
            let mut retry_out = Vec::new();
            sess.run_chat_turn(&turn2, 4, true, true, &mut s2, &mut retry_out).unwrap();
            assert_eq!(sess.n_past, want_npast, "{label}: retry n_past mismatch");
            assert_eq!(eng.lane_hash(&sess.lane), want_hash, "{label}: retry lane_hash mismatch");
            assert_eq!(&retry_out, want_out2, "{label}: retry output mismatch");
        }
    }

    #[test]
    #[ignore = "requires local Inkling-2-Mini GGUF"]
    fn cli_session_kv_disk_recovers_across_tier_entry_and_active_tier_rollback() {
        use crate::engine::KV_DISK;
        use crate::metal::{clear_wait_failure, inject_wait_failure};
        use std::sync::atomic::Ordering;

        struct KvDiskGuard;
        impl Drop for KvDiskGuard {
            fn drop(&mut self) {
                KV_DISK.store(false, Ordering::Relaxed);
                clear_wait_failure();
            }
        }
        let _guard = KvDiskGuard;

        let model = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
        let mut eng = Engine::load(&model, 2048);
        eng.chunk = 128;
        let tk = Tokenizer::load(&eng.g);

        let make_turn = |target_tokens: usize, phrase: &str| -> Vec<u32> {
            let mut toks = tk.encode("<|message_user|><|content_text|>", true);
            let piece = tk.encode(phrase, false);
            while toks.len() + 2 < target_tokens {
                toks.extend_from_slice(&piece);
            }
            toks.extend(tk.encode("<|end_message|><|message_model|>", true));
            toks
        };

        let make_disk_session = || -> Session<'_> {
            KV_DISK.store(true, Ordering::Relaxed);
            let sess = Session::new(&eng, &tk);
            KV_DISK.store(false, Ordering::Relaxed);
            sess
        };

        let snapshot_all_kv = |sess: &Session<'_>| -> Vec<Vec<u8>> {
            if sess.run().tier_on() {
                sess.run().tier_leave(sess.n_past);
            }
            eng.snapshot_kv_positions(&sess.lane, 0, sess.n_past)
                .into_iter()
                .map(|u| u.rows)
                .collect()
        };

        // 0. Guard check: restore_kv_pos must panic cleanly rather than write OOB when pos >= full_cap.
        {
            let mut sess = make_disk_session();
            let short = make_turn(16, " hello");
            let mut s = Sampler::new(0.0, 64, 0.95, eng.softcap, 1);
            let mut out = Vec::new();
            sess.run_chat_turn(&short, 2, true, true, &mut s, &mut out).unwrap();
            let mut oob = eng.snapshot_kv_positions(&sess.lane, 0, 1).pop().unwrap();
            oob.pos = eng.max_ctx + 1;
            let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                eng.restore_kv_pos(&sess.lane, &oob);
            }))
            .is_err();
            assert!(panicked, "restore_kv_pos must assert on out-of-range full-attention pos");
        }

        // 1. Trigger A: Turn 1 ends below tier.min_n (512, tier_on == false), Turn 2 crosses min_n
        //    and calls tier_enter() (shrinking kv_full hot ring below turn1_npast), then fails
        //    in decode and rolls back without OOB Metal writes.
        let turn1_a = make_turn(360, " alpha beta gamma");
        let turn2_a = make_turn(240, " delta epsilon zeta");
        let (want_a_npast, want_a_hash, want_a_out2) = {
            let mut sess = make_disk_session();
            let mut s1 = Sampler::new(0.0, 64, 0.95, eng.softcap, 101);
            let mut out1 = Vec::new();
            sess.run_chat_turn(&turn1_a, 4, true, true, &mut s1, &mut out1).unwrap();
            assert!(!sess.run().tier_on(), "Trigger A Turn 1 must stay below tier.min_n");
            let mut s2 = Sampler::new(0.0, 64, 0.95, eng.softcap, 202);
            let mut out2 = Vec::new();
            sess.run_chat_turn(&turn2_a, 4, true, true, &mut s2, &mut out2).unwrap();
            assert!(sess.run().tier_on(), "Trigger A Turn 2 must enter disk tier");
            sess.run().tier_leave(sess.n_past);
            (sess.n_past, eng.lane_hash(&sess.lane), out2)
        };
        {
            let mut sess = make_disk_session();
            let mut s1 = Sampler::new(0.0, 64, 0.95, eng.softcap, 101);
            let mut out1 = Vec::new();
            sess.run_chat_turn(&turn1_a, 4, true, true, &mut s1, &mut out1).unwrap();
            assert!(!sess.run().tier_on());
            let t1_npast = sess.n_past;
            let t1_cs = sess.run().get_cs();
            let t1_kv = snapshot_all_kv(&sess);

            inject_wait_failure("decode", 0);
            let mut s_fail = Sampler::new(0.0, 64, 0.95, eng.softcap, 202);
            let mut fail_out = Vec::new();
            let res = sess.run_chat_turn(&turn2_a, 4, true, true, &mut s_fail, &mut fail_out);
            clear_wait_failure();
            assert!(res.is_err(), "Trigger A injected decode failure must return Err");
            assert!(!sess.run().tier_on(), "Trigger A rollback must leave disk tier cleanly");
            assert_eq!(sess.n_past, t1_npast);
            assert_eq!(sess.run().get_cs(), t1_cs);
            assert_eq!(snapshot_all_kv(&sess), t1_kv, "Trigger A rollback must preserve Turn 1 KV");

            let mut s2 = Sampler::new(0.0, 64, 0.95, eng.softcap, 202);
            let mut retry_out2 = Vec::new();
            sess.run_chat_turn(&turn2_a, 4, true, true, &mut s2, &mut retry_out2).unwrap();
            assert!(sess.run().tier_on(), "Trigger A retry must re-enter disk tier cleanly");
            sess.run().tier_leave(sess.n_past);
            assert_eq!(sess.n_past, want_a_npast);
            assert_eq!(eng.lane_hash(&sess.lane), want_a_hash);
            assert_eq!(retry_out2, want_a_out2);
        }

        // 2. Trigger B: Turn 1 ends >= tier.min_n with tier_on() == true; Turn 2 fails either in
        //    prefill (after overwriting SWA ring slots) or in decode (after re-entering tier and
        //    writing Turn 2 cold data), rolls back, and Turn 2 retry + Turn 3 match baseline bit-for-bit.
        let turn1_b = make_turn(560, " mercury venus earth");
        let turn2_b = make_turn(220, " mars jupiter saturn");
        let turn3_b = make_turn(160, " uranus neptune pluto");
        let (want_b_npast, want_b_hash, want_b_out2, want_b_out3) = {
            let mut sess = make_disk_session();
            let mut s1 = Sampler::new(0.0, 64, 0.95, eng.softcap, 303);
            let mut out1 = Vec::new();
            sess.run_chat_turn(&turn1_b, 4, true, true, &mut s1, &mut out1).unwrap();
            assert!(sess.run().tier_on(), "Trigger B Turn 1 must finish with tier_on()");
            let mut s2 = Sampler::new(0.0, 64, 0.95, eng.softcap, 404);
            let mut out2 = Vec::new();
            sess.run_chat_turn(&turn2_b, 4, true, true, &mut s2, &mut out2).unwrap();
            assert!(sess.run().tier_on(), "Trigger B Turn 2 must finish with tier_on()");
            let mut s3 = Sampler::new(0.0, 64, 0.95, eng.softcap, 505);
            let mut out3 = Vec::new();
            sess.run_chat_turn(&turn3_b, 4, true, true, &mut s3, &mut out3).unwrap();
            assert!(sess.run().tier_on(), "Trigger B Turn 3 must finish with tier_on()");
            sess.run().tier_leave(sess.n_past);
            (sess.n_past, eng.lane_hash(&sess.lane), out2, out3)
        };

        for (label, stage, call_idx) in [
            ("Trigger B prefill failure", "prefill", 1usize),
            ("Trigger B decode failure", "decode", 0usize),
        ] {
            let mut sess = make_disk_session();
            let mut s1 = Sampler::new(0.0, 64, 0.95, eng.softcap, 303);
            let mut out1 = Vec::new();
            sess.run_chat_turn(&turn1_b, 4, true, true, &mut s1, &mut out1).unwrap();
            assert!(sess.run().tier_on(), "{label}: Turn 1 must finish with tier_on()");
            let t1_npast = sess.n_past;
            let t1_cs = sess.run().get_cs();

            inject_wait_failure(stage, call_idx);
            let mut s_fail = Sampler::new(0.0, 64, 0.95, eng.softcap, 404);
            let mut fail_out = Vec::new();
            let res = sess.run_chat_turn(&turn2_b, 4, true, true, &mut s_fail, &mut fail_out);
            clear_wait_failure();
            assert!(res.is_err(), "{label}: injected {stage}[{call_idx}] failure must return Err");
            assert!(!sess.run().tier_on(), "{label}: rollback must leave disk tier cleanly");
            assert_eq!(sess.n_past, t1_npast, "{label}: n_past mismatch after rollback");
            assert_eq!(sess.run().get_cs(), t1_cs, "{label}: cs mismatch after rollback");

            // Continue cleanly with Turn 2 retry + Turn 3 (re-entering disk tier on both).
            let mut s2 = Sampler::new(0.0, 64, 0.95, eng.softcap, 404);
            let mut retry_out2 = Vec::new();
            sess.run_chat_turn(&turn2_b, 4, true, true, &mut s2, &mut retry_out2).unwrap();
            assert!(sess.run().tier_on(), "{label}: Turn 2 retry must re-enter disk tier");
            let mut s3 = Sampler::new(0.0, 64, 0.95, eng.softcap, 505);
            let mut retry_out3 = Vec::new();
            sess.run_chat_turn(&turn3_b, 4, true, true, &mut s3, &mut retry_out3).unwrap();
            assert!(sess.run().tier_on(), "{label}: Turn 3 must re-enter disk tier");
            sess.run().tier_leave(sess.n_past);

            assert_eq!(sess.n_past, want_b_npast, "{label}: final n_past mismatch");
            assert_eq!(eng.lane_hash(&sess.lane), want_b_hash, "{label}: final lane_hash mismatch");
            assert_eq!(retry_out2, want_b_out2, "{label}: Turn 2 retry output mismatch");
            assert_eq!(retry_out3, want_b_out3, "{label}: Turn 3 output mismatch");
        }
    }
}