inky-engine 3.0.1

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
//! The turn-end start. A lane keeps the `cs` of its last decode block boundary, and `release_lane` saves a
//! start there, so the card's next turn binds past this turn's reply and prefills only what is new.
//!
//! The start at `end = 64k` binds Window blocks `k-16 .. k-1`. The lane's own table needs block `k-16` only
//! until it has written position `end + 62`: `first_live_window_block_at(end + 63) = k - 15`. So the table
//! drops that block one token before the next boundary, and a reply whose last written position is
//! `end + 62` used to lose its turn-end start (one turn in 64 with single-token steps, and most turns once a
//! step can cross a boundary without landing on it).
//!
//! Every test here drives a lane the way `serve.rs` does, ends the reply at each of the 64 offsets past a block
//! boundary, and then runs the card's next turn: it must bind the start at the reply's last boundary and
//! prefill from there with every Window block its first step reads in place.
use super::*;
use crate::blocks::{validate_span_blocks_at, CLEARED_GPU_TABLE_ENTRY};

const TABLE_BLOCKS: u32 = 96;

fn card() -> u64 {
    approx_twin("test-salt", 0, Some("card-turn-end"))
}

/// The conversation is one fixed token stream: a turn's prompt is a prefix of it, and so is its reply.
fn conv(len: usize) -> Vec<u32> {
    (0..len as u32).map(|i| 1_000 + i).collect()
}

/// A `cs` that names the position it was read at.
fn cs_at(pos: usize) -> Vec<u8> {
    (pos as u64).to_le_bytes().to_vec()
}

fn fresh() -> (ServeBlockCache, BlockPools) {
    let mut cache = ServeBlockCache::new();
    cache.set_approx_retain(true);
    (cache, BlockPools::records_only_with_capacities(256, 256, 2).unwrap())
}

/// One lane in one turn.
struct Turn {
    tbl: BlockTable,
    st: LaneBlockState,
    /// The prompt, then every token sampled so far: `history[p]` is the token whose K/V position `p` holds.
    history: Vec<u32>,
    full_gpu: Vec<u64>,
    win_gpu: Vec<u64>,
    /// Where the turn bound, and the `cs` the start carried.
    bound: Option<(usize, Vec<u8>)>,
    /// The last block boundary a step ended on exactly (the prompt start until a decode step lands on one).
    landed: usize,
}

impl Turn {
    /// Admit the card's turn with a prompt of `prompt_len` tokens: bind, then prefill to the end of the prompt
    /// in the spans `serve.rs` uses. Every span must find the Window blocks it reads.
    fn begin(cache: &mut ServeBlockCache, pools: &mut BlockPools, prompt_len: usize) -> Turn {
        Turn::begin_in(cache, pools, prompt_len, TABLE_BLOCKS)
    }

    /// As `begin`, on a lane whose context is `table_blocks` blocks.
    fn begin_in(cache: &mut ServeBlockCache, pools: &mut BlockPools, prompt_len: usize, table_blocks: u32) -> Turn {
        let prompt = conv(prompt_len);
        let mut tbl = BlockTable::new(table_blocks).unwrap();
        let mut st = LaneBlockState { owner: card(), ..Default::default() };
        let bound = cache.match_and_bind(pools, &mut tbl, &mut st, &prompt);
        let mut p = bound.as_ref().map_or(0, |b| b.0);
        while p < prompt_len {
            let next = effective_pf_target(p, prompt_len);
            cache.ensure_span_blocks(pools, &mut tbl, p, next - p).unwrap();
            validate_span_blocks_at(&tbl, pools, p, next - p, WINDOW, BLOCK).expect("a prefill span reads live blocks");
            cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt, p, next - p, || cs_at(next));
            p = next;
        }
        let landed = if prompt_len.is_multiple_of(BLOCK) { prompt_len } else { (prompt_len - 1) / BLOCK * BLOCK };
        let mut history = prompt;
        history.push(1_000 + prompt_len as u32); // sampled at the end of prefill
        Turn {
            tbl,
            st,
            history,
            full_gpu: vec![CLEARED_GPU_TABLE_ENTRY; table_blocks as usize],
            win_gpu: vec![CLEARED_GPU_TABLE_ENTRY; table_blocks as usize],
            bound,
            landed,
        }
    }

    fn written(&self) -> usize {
        self.st.written
    }

    fn sample(&mut self) {
        self.history.push(1_000 + self.history.len() as u32);
    }

    /// One single-token decode step, as the scheduler's decode branch books it.
    fn decode(&mut self, cache: &mut ServeBlockCache, pools: &mut BlockPools) {
        let pos = self.st.written;
        cache.ensure_span_blocks(pools, &mut self.tbl, pos, 1).unwrap();
        validate_span_blocks_at(&self.tbl, pools, pos, 1, WINDOW, BLOCK).expect("a decode step reads live blocks");
        cache.finish_decode_span(pools, &mut self.tbl, &mut self.st, pos);
        cache.seal_decode_block(pools, &self.tbl, &mut self.st, &self.history, pos, || cs_at(pos + 1));
        if (pos + 1).is_multiple_of(BLOCK) {
            self.landed = pos + 1;
        }
        self.sample();
    }

    /// One DSpark verify step of `1 + k` positions that keeps `n_keep` of them (`0` is a cancelled step), as the
    /// scheduler's verify branch books it.
    fn verify(&mut self, cache: &mut ServeBlockCache, pools: &mut BlockPools, k: usize, n_keep: usize) {
        assert!(n_keep <= 1 + k);
        let p0 = self.st.written;
        let alloc = cache.ensure_span_blocks_tracking(pools, &mut self.tbl, p0, 1 + k).unwrap();
        validate_span_blocks_at(&self.tbl, pools, p0, 1 + k, WINDOW, BLOCK).expect("a verify step reads live blocks");
        cache
            .finish_verify_span_to_slices(
                pools,
                &mut self.tbl,
                &mut self.st,
                &alloc,
                p0,
                n_keep,
                &mut self.full_gpu,
                &mut self.win_gpu,
            )
            .expect("finalize the verify step");
        if n_keep == 0 {
            return;
        }
        while self.history.len() < p0 + n_keep {
            self.sample();
        }
        cache.seal_decode_block(pools, &self.tbl, &mut self.st, &self.history, p0 + n_keep - 1, || cs_at(p0 + n_keep));
        if (p0 + n_keep).is_multiple_of(BLOCK) {
            self.landed = p0 + n_keep;
        }
        self.sample();
    }

    /// End the turn: release the lane with its committed tokens. Returns how many tokens the lane had written.
    fn end(mut self, cache: &mut ServeBlockCache, pools: &mut BlockPools, cancelled: bool) -> usize {
        let written = self.st.written;
        let committed = self.history[..written].to_vec();
        cache.release_lane_with_toks(pools, &mut self.tbl, &mut self.st, Some(&committed), cancelled);
        written
    }
}

/// The card's next turn, whose prompt is the first `prompt_len` tokens of the conversation: where it binds and
/// the `cs` it resumes with. Its prefill runs to the end of the prompt, so the bound Window blocks are read.
fn next_turn_binds(cache: &mut ServeBlockCache, pools: &mut BlockPools, prompt_len: usize) -> (usize, Vec<u8>) {
    let turn = Turn::begin(cache, pools, prompt_len);
    let bound = turn.bound.clone().unwrap_or((0, Vec::new()));
    turn.end(cache, pools, false);
    bound
}

fn drain(mut cache: ServeBlockCache, mut pools: BlockPools) {
    cache.shutdown(&mut pools);
    assert_zero_pool_leaks(&pools);
}

/// Prompts that end before, on and after a block boundary. All are past 1,087 tokens, so the lane's Window
/// has slid and its table is pruning as it decodes.
const PROMPTS: [usize; 4] = [1_500, 1_536, 1_599, 2_113];

#[test]
fn single_token_reply_ending_at_every_offset_leaves_a_start_at_its_last_block_boundary() {
    // Red before the fix at offset 63 for every prompt: the next turn binds the prompt start instead.
    let mut dropped = Vec::new();
    for prompt_len in PROMPTS {
        for offset in 0..BLOCK {
            let (mut cache, mut pools) = fresh();
            let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
            // Decode past two block boundaries and stop `offset` tokens after the third.
            let end = (prompt_len / BLOCK + 3) * BLOCK + offset;
            while turn.written() < end {
                turn.decode(&mut cache, &mut pools);
            }
            let written = turn.end(&mut cache, &mut pools, false);
            assert_eq!(written, end);
            let last_boundary = end / BLOCK * BLOCK;
            let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
            if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
                dropped.push((prompt_len, offset, at));
            }
            drain(cache, pools);
        }
    }
    assert!(dropped.is_empty(), "turn-end start not saved: (prompt, offset past the boundary, next turn bound at) {dropped:?}");
}

#[test]
fn a_reply_shorter_than_a_block_resumes_from_the_prompt_start() {
    // No decode boundary, so no turn-end start is due: the prompt start is the reply's last block boundary.
    for prompt_len in PROMPTS {
        let (mut cache, mut pools) = fresh();
        let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
        let prompt_start = turn.landed;
        let end = prompt_start + BLOCK - 1;
        while turn.written() < end {
            turn.decode(&mut cache, &mut pools);
        }
        turn.end(&mut cache, &mut pools, false);
        let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
        assert_eq!((at, cs), (prompt_start, cs_at(prompt_start)), "prompt {prompt_len}");
        drain(cache, pools);
    }
}

#[test]
fn second_turn_reply_ending_at_every_offset_leaves_a_start_at_its_last_block_boundary() {
    // The lane of a card's later turn starts on its approximate path, bound to the turn before's start.
    // Red before the fix at offset 63.
    let mut dropped = Vec::new();
    for offset in 0..BLOCK {
        let (mut cache, mut pools) = fresh();
        let mut one = Turn::begin(&mut cache, &mut pools, 1_500);
        while one.written() < 1_700 {
            one.decode(&mut cache, &mut pools);
        }
        one.end(&mut cache, &mut pools, false);
        // Turn 2: turn 1's 1,700 tokens and a 300-token tool result.
        let mut two = Turn::begin(&mut cache, &mut pools, 2_000);
        assert_eq!(two.bound.as_ref().map(|b| b.0), Some(1_664), "turn 2 resumes past turn 1's reply");
        assert!(two.st.approx_path);
        let end = 2_176 + offset;
        while two.written() < end {
            two.decode(&mut cache, &mut pools);
        }
        two.end(&mut cache, &mut pools, false);
        let last_boundary = end / BLOCK * BLOCK;
        let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
        if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
            dropped.push((offset, at));
        }
        drain(cache, pools);
    }
    assert!(dropped.is_empty(), "turn-end start not saved: (offset past the boundary, next turn bound at) {dropped:?}");
}

/// The kept lengths of successive verify steps of `1 + K` positions.
const K: usize = 4;
const SHAPES: [(&str, &[usize]); 5] = [
    ("every step keeps 2", &[2]),
    ("every step keeps 3", &[3]),
    ("every step keeps 5", &[5]),
    ("mixed 1,3,5,2,4", &[1, 3, 5, 2, 4]),
    ("mixed 5,5,1", &[5, 5, 1]),
];

#[test]
fn verify_step_reply_keeps_the_start_of_the_last_boundary_a_step_landed_on() {
    // A verify step reads `cs` only where it ends, so a checkpoint exists only where a step lands exactly on a
    // block boundary, and it then waits for the release however far the lane decodes past it. Red before the fix
    // whenever the reply ends 63 or more tokens past that boundary: the lane has pruned a Window block the start
    // binds, and the next turn falls back to the prompt start.
    let mut dropped = Vec::new();
    let mut ran = 0usize;
    for (name, shape) in SHAPES {
        for prompt_len in PROMPTS {
            for offset in 0..BLOCK {
                let (mut cache, mut pools) = fresh();
                let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
                let end = (prompt_len / BLOCK + 3) * BLOCK + offset;
                let mut step = 0usize;
                while turn.written() < end {
                    let n_keep = shape[step % shape.len()].min(end - turn.written());
                    turn.verify(&mut cache, &mut pools, K, n_keep);
                    step += 1;
                }
                let landed = turn.landed;
                turn.end(&mut cache, &mut pools, false);
                let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
                if (at, &cs) != (landed, &cs_at(landed)) {
                    dropped.push((name, prompt_len, offset, landed, at));
                }
                ran += 1;
                drain(cache, pools);
            }
        }
    }
    assert!(
        dropped.is_empty(),
        "{} of {ran} replies lost their checkpoint: (shape, prompt, offset, last landed boundary, next turn bound at) {:?}",
        dropped.len(),
        &dropped[..dropped.len().min(24)]
    );
}

#[test]
fn forced_close_between_verify_steps_ending_at_every_offset_keeps_its_last_checkpoint() {
    // A thinking-cap forced close decides its tokens, so DSpark does not draft them: the reply is verify steps,
    // then single-token steps for the close, then verify steps again. Single-token steps land on every boundary.
    let mut dropped = Vec::new();
    for offset in 0..BLOCK {
        let (mut cache, mut pools) = fresh();
        let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
        let end = 1_728 + offset;
        let close_at = 1_590;
        while turn.written() < close_at {
            let n_keep = 3.min(close_at - turn.written());
            turn.verify(&mut cache, &mut pools, K, n_keep);
        }
        for _ in 0..12 {
            turn.decode(&mut cache, &mut pools); // the close crosses 1,600 one token at a time
        }
        while turn.written() < end {
            let n_keep = 5.min(end - turn.written());
            turn.verify(&mut cache, &mut pools, K, n_keep);
        }
        let landed = turn.landed;
        assert!(landed >= 1_600);
        turn.end(&mut cache, &mut pools, false);
        let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
        if (at, &cs) != (landed, &cs_at(landed)) {
            dropped.push((offset, landed, at));
        }
        drain(cache, pools);
    }
    assert!(dropped.is_empty(), "checkpoint lost: (offset, last landed boundary, next turn bound at) {dropped:?}");
}

#[test]
fn cancelled_turn_at_every_offset_keeps_its_last_checkpoint_and_its_prompt_start() {
    // A client that goes away mid-reply: the lane is released as cancelled. What it decoded is still the
    // conversation's, so a continuation binds the last boundary; a retry of the same prompt binds the prompt start.
    let mut dropped = Vec::new();
    for offset in 0..BLOCK {
        for cancelled_in_verify in [false, true] {
            let (mut cache, mut pools) = fresh();
            let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
            let prompt_start = turn.landed;
            let end = 1_664 + offset;
            while turn.written() < end {
                turn.decode(&mut cache, &mut pools);
            }
            if cancelled_in_verify {
                turn.verify(&mut cache, &mut pools, K, 0); // the step is rolled back whole
            }
            assert_eq!(turn.written(), end);
            turn.end(&mut cache, &mut pools, true);
            let retry = next_turn_binds(&mut cache, &mut pools, 1_500);
            assert_eq!(retry, (prompt_start, cs_at(prompt_start)), "a retry resumes from the prompt start");
            let last_boundary = end / BLOCK * BLOCK;
            let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
            if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
                dropped.push((offset, cancelled_in_verify, at));
            }
            drain(cache, pools);
        }
    }
    assert!(dropped.is_empty(), "turn-end start not saved: (offset, cancelled in a verify step, bound at) {dropped:?}");
}

#[test]
fn reply_at_the_length_limit_at_every_offset_leaves_a_start_at_its_last_block_boundary() {
    // The lane's last position is two short of its context (`n_past + 2 >= max_ctx` ends the turn as "length"):
    // nothing is left to allocate, and the start must still be saved. Red before the fix at offset 63.
    let mut dropped = Vec::new();
    for offset in 0..BLOCK {
        let (mut cache, mut pools) = fresh();
        let max_ctx = 2_240 + offset + 2;
        let blocks = u32::try_from(max_ctx.div_ceil(BLOCK)).unwrap();
        let mut turn = Turn::begin_in(&mut cache, &mut pools, 2_113, blocks);
        while turn.written() + 2 < max_ctx {
            turn.decode(&mut cache, &mut pools);
        }
        let end = turn.end(&mut cache, &mut pools, false);
        assert_eq!(end, 2_240 + offset);
        let last_boundary = end / BLOCK * BLOCK;
        let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 1);
        if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
            dropped.push((offset, at));
        }
        drain(cache, pools);
    }
    assert!(dropped.is_empty(), "turn-end start not saved: (offset past the boundary, next turn bound at) {dropped:?}");
}

#[test]
fn window_ring_wrap_and_pre_wrap_replies_keep_last_boundary_and_partial_tail() {
    // Pre-wrap (`prompt = 80`, reply across `192 + offset`, still `< WINDOW = 1,024`) and first Window ring wrap
    // (`prompt = 896`, reply across `1,024 + offset`, where `offset = 63` at `1,087` prunes Window block `0` for
    // the very first time). Also checks partial-block tail capture (`observe_prior`) for every `offset in 0..64`.
    let mut dropped = Vec::new();
    for (prompt_len, boundary) in [(80usize, 192usize), (896usize, WINDOW)] {
        for offset in 0..BLOCK {
            let (mut cache, mut pools) = fresh();
            let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
            let end = boundary + offset;
            while turn.written() < end {
                turn.decode(&mut cache, &mut pools);
            }
            let written = turn.end(&mut cache, &mut pools, false);
            assert_eq!(written, end);
            let next_prompt = conv(end + 100);
            let obs = cache.observe_prior(card(), &next_prompt);
            assert!(obs.has_prior);
            assert_eq!(obs.total_len, end);
            assert_eq!(obs.proven_common_len, end, "partial-block tail must capture all {offset} trailing tokens");
            assert_eq!(obs.first_divergent_pos, None);
            let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
            if (at, &cs) != (boundary, &cs_at(boundary)) {
                dropped.push((prompt_len, boundary, offset, at));
            }
            drain(cache, pools);
        }
    }
    assert!(
        dropped.is_empty(),
        "window wrap/pre-wrap turn-end start lost: (prompt, boundary, offset, next turn bound at) {dropped:?}"
    );
}

#[test]
fn stitched_lane_ending_at_every_offset_keeps_turn_end_start_and_never_spills_or_donates_approx() {
    // A lane that stitched Full blocks (`--kv-stitch`), healed its Window ramp, and decoded past a reply boundary:
    // red before the fix at `offset = 63`. Also checks that evicting an approximate turn-end start with a
    // `SpillStore` attached never spills it to disk and never indexes it as a stitch donor for other cards.
    let kvb = 1u32;
    let mut pools = BlockPools::with_capacities(160, 96, kvb).unwrap();
    let file_span: Vec<u32> = (0..3_200u32).map(|i| 50_000 + i).collect();
    let mut donor_prompt: Vec<u32> = (0..128u32).map(|i| 2_000 + i).collect();
    donor_prompt.extend_from_slice(&file_span); // [128 .. 3,328) block-aligned zero-copy donor
    donor_prompt.extend((0..257u32).map(|i| 4_000 + i)); // 3,585 tokens -> exact EVERY/PROMPT start at 3,584

    let mut card_prompt: Vec<u32> = (0..128u32).map(|i| 6_000 + i).collect();
    card_prompt.extend_from_slice(&file_span); // [128 .. 3,328)
    card_prompt.extend((0..1_680u32).map(|i| 60_000 + i)); // 5,008 tokens (>= MIN_HEAL_TOKENS past stitch)
    let prompt_len = card_prompt.len();
    let reply_boundary = (prompt_len / BLOCK + 2) * BLOCK; // 5,120

    let mut dropped = Vec::new();
    for offset in 0..BLOCK {
        let dir = (offset == BLOCK - 1).then(|| ScratchDir::new("turn-end-stitch-approx"));
        let mut cache = match &dir {
            Some(d) => ServeBlockCache::with_spill(SpillStore::open_with_kvb(&d.0, 64 * 1024 * 1024, kvb).unwrap()),
            None => ServeBlockCache::new(),
        };
        cache.set_kv_stitch(true);
        cache.set_approx_retain(true);

        // Seed the exact donor start at 3,584.
        {
            let mut dtbl = BlockTable::new(96).unwrap();
            let mut dst = LaneBlockState::default();
            assert!(cache.match_and_bind(&mut pools, &mut dtbl, &mut dst, &donor_prompt).is_none());
            let mut p = 0usize;
            while p < donor_prompt.len() {
                let next = effective_pf_target(p, donor_prompt.len());
                cache.ensure_span_blocks(&mut pools, &mut dtbl, p, next - p).unwrap();
                cache.finish_prefill_span(&mut pools, &mut dtbl, &mut dst, &donor_prompt, p, next - p, || cs_at(next));
                p = next;
            }
            cache.release_lane(&mut pools, &mut dtbl, &mut dst);
        }

        // Card turn 1: stitch from donor, heal to `prompt_len`, then decode to `reply_boundary + offset`.
        let mut tbl = BlockTable::new(112).unwrap();
        let mut st = LaneBlockState { owner: card(), prompt_len, ..Default::default() };
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &card_prompt).is_none());
        let plans = cache.plan_stitches(&pools, 0, &card_prompt, 0);
        assert_eq!(plans.len(), 1);
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, 0, plans[0].stitch_start, || {
            cs_at(plans[0].stitch_start)
        });
        let out = cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &card_prompt, &plans[0]);
        assert!(matches!(out, StitchApplyOutcome::Applied { .. }));
        assert!(st.stitched_approx && st.approx_path);
        let mut p = st.written;
        while p < prompt_len {
            let next = effective_pf_target(p, prompt_len);
            cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
            validate_span_blocks_at(&tbl, &pools, p, next - p, WINDOW, BLOCK).expect("stitched heal reads live blocks");
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, p, next - p, || cs_at(next));
            p = next;
        }

        let end = reply_boundary + offset;
        let mut history = card_prompt.clone();
        history.push(70_000);
        while st.written < end {
            let pos = st.written;
            cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
            validate_span_blocks_at(&tbl, &pools, pos, 1, WINDOW, BLOCK).expect("stitched decode reads live blocks");
            cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
            cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || cs_at(pos + 1));
            history.push(70_000 + (history.len() - prompt_len) as u32);
        }
        cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&history[..end]), false);

        // Next turn of the same card must resume at `reply_boundary`.
        let mut next_prompt = history[..end].to_vec();
        next_prompt.extend((0..100u32).map(|i| 80_000 + i));
        let mut tbl2 = BlockTable::new(112).unwrap();
        let mut st2 = LaneBlockState { owner: card(), ..Default::default() };
        let bound = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &next_prompt);
        let (at, cs) = bound.clone().unwrap_or((0, Vec::new()));
        if (at, &cs) != (reply_boundary, &cs_at(reply_boundary)) {
            dropped.push((offset, at));
        } else {
            let mut p2 = at;
            while p2 < next_prompt.len() {
                let next = effective_pf_target(p2, next_prompt.len());
                cache.ensure_span_blocks(&mut pools, &mut tbl2, p2, next - p2).unwrap();
                validate_span_blocks_at(&tbl2, &pools, p2, next - p2, WINDOW, BLOCK)
                    .expect("next turn after stitched reply reads live blocks");
                cache.finish_prefill_span(&mut pools, &mut tbl2, &mut st2, &next_prompt, p2, next - p2, || cs_at(next));
                p2 = next;
            }
        }
        cache.release_lane(&mut pools, &mut tbl2, &mut st2);

        if dir.is_some() {
            // Stranger card sharing the stitched post-donor tail (`[3,328 .. end)`) must never stitch from `approx`.
            let mut stranger: Vec<u32> = (0..1_100u32).map(|i| 90_000 + i).collect();
            stranger.extend_from_slice(&history[3_328..end]);
            stranger.extend((0..1_600u32).map(|i| 95_000 + i));
            assert!(cache.plan_stitches(&pools, 0, &stranger, 0).is_empty(), "approx starts are never stitch donors");

            // Evicting approximate starts with a SpillStore attached must never spill them to disk.
            let approx_ids: Vec<SealedId> =
                cache.starts.iter().filter(|(_, s)| s.approx).map(|(&id, _)| id).collect();
            assert!(!approx_ids.is_empty(), "stitched turn must hold approximate starts before eviction");
            for sid in approx_ids {
                assert!(cache.evict_start(&mut pools, sid));
            }
            assert_eq!(cache.stats().starts_spilled, 0, "approximate starts are never spilled to disk");
            assert!(cache.spilled_starts.is_empty());
        }

        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }
    assert!(dropped.is_empty(), "stitched turn-end start not saved: (offset, next turn bound at) {dropped:?}");
}

#[test]
fn verify_step_with_crossed_boundary_cs_saves_the_reply_last_boundary_at_every_offset() {
    // When `serve.rs` supplies `Engine::verify_cs_after` for a crossed block boundary (`seal_verify_step`),
    // every single one of the 1,280 replies across all shapes, prompts and offsets binds the reply's true last
    // block boundary (`end / BLOCK * BLOCK`), not merely an earlier landed boundary, and reports `Saved`.
    let mut dropped = Vec::new();
    for (name, shape) in SHAPES {
        for prompt_len in PROMPTS {
            for offset in 0..BLOCK {
                let (mut cache, mut pools) = fresh();
                let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
                let end = (prompt_len / BLOCK + 3) * BLOCK + offset;
                let mut step = 0usize;
                while turn.written() < end {
                    let p0 = turn.written();
                    let n_keep = shape[step % shape.len()].min(end - p0);
                    let step_end = p0 + n_keep;
                    let boundary = step_end / BLOCK * BLOCK;
                    let crossed = (cache.keeps_turn_end_start(&turn.st)
                        && !step_end.is_multiple_of(BLOCK)
                        && boundary > p0)
                        .then(|| (boundary, cs_at(boundary)));
                    let alloc = cache.ensure_span_blocks_tracking(&mut pools, &mut turn.tbl, p0, 1 + K).unwrap();
                    validate_span_blocks_at(&turn.tbl, &pools, p0, 1 + K, WINDOW, BLOCK).unwrap();
                    cache
                        .finish_verify_span_to_slices(
                            &mut pools,
                            &mut turn.tbl,
                            &mut turn.st,
                            &alloc,
                            p0,
                            n_keep,
                            &mut turn.full_gpu,
                            &mut turn.win_gpu,
                        )
                        .unwrap();
                    while turn.history.len() < step_end {
                        turn.sample();
                    }
                    cache.seal_verify_step(
                        &mut pools,
                        &turn.tbl,
                        &mut turn.st,
                        &turn.history,
                        step_end - 1,
                        crossed,
                        || cs_at(step_end),
                    );
                    turn.sample();
                    step += 1;
                }
                let committed = turn.history[..end].to_vec();
                let outcome = cache.release_lane_with_toks(&mut pools, &mut turn.tbl, &mut turn.st, Some(&committed), false);
                assert_eq!(outcome, TurnEndStart::Saved);
                assert_eq!(outcome.record_tag(), "saved");
                assert_eq!(cache.stats().turn_end_starts_saved, 1);
                assert_eq!(cache.stats().turn_end_starts_not_saved, [0; TurnEndMiss::ALL.len()]);
                let last_boundary = end / BLOCK * BLOCK;
                let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
                if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
                    dropped.push((name, prompt_len, offset, last_boundary, at));
                }
                drain(cache, pools);
            }
        }
    }
    assert!(dropped.is_empty(), "crossed-boundary verify lost its last boundary: {dropped:?}");
}

#[test]
fn checkpoint_guards_ignore_zero_crossed_preserve_earlier_hold_on_miss_and_drop_on_rebind() {
    let (mut cache, mut pools) = fresh();
    for (miss, tag) in [
        (TurnEndMiss::NoCheckpoint, "not_saved:no_checkpoint"),
        (TurnEndMiss::Behind, "not_saved:behind"),
        (TurnEndMiss::OffPath, "not_saved:off_path"),
        (TurnEndMiss::BlockMissing, "not_saved:block_missing"),
        (TurnEndMiss::BlockNotLive, "not_saved:block_not_live"),
    ] {
        assert!(!miss.name().is_empty());
        assert_eq!(TurnEndStart::NotSaved(miss).record_tag(), tag);
    }
    assert_eq!(TurnEndStart::NotDue.record_tag(), "not_due");

    // 1. A bogus `crossed = Some((0, ...))` on a short prefix must never underflow `0 / BLOCK - 1` or set a checkpoint.
    {
        let mut tbl = BlockTable::new(TABLE_BLOCKS).unwrap();
        let mut st = LaneBlockState { owner: card(), prompt_len: 4, ..Default::default() };
        let toks = conv(16);
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 5).unwrap();
        cache.finish_decode_span(&mut pools, &mut tbl, &mut st, 4);
        cache.seal_verify_step(&mut pools, &tbl, &mut st, &toks, 4, Some((0, cs_at(0))), || cs_at(5));
        assert!(st.turn_ckpt.is_none());
        assert_eq!(cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&toks[..5]), false), TurnEndStart::NotDue);
    }

    // 2. If a later boundary is missing a Window block, an earlier valid TurnCheckpoint is preserved and saved (`Behind`).
    {
        let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
        while turn.written() < 1_600 {
            turn.decode(&mut cache, &mut pools);
        }
        assert!(turn.st.turn_ckpt.is_some());
        while turn.written() < 1_663 {
            turn.decode(&mut cache, &mut pools);
        }
        // Advance into position 1,663 (`end = 1,664`), then artificially clear Window block 10 before sealing 1,664.
        cache.ensure_span_blocks(&mut pools, &mut turn.tbl, 1_663, 1).unwrap();
        cache.finish_decode_span(&mut pools, &mut turn.tbl, &mut turn.st, 1_663);
        turn.tbl.clear_kind_entry(&mut pools.window, BlockIndex::new(10)).unwrap();
        cache.seal_decode_block(&mut pools, &turn.tbl, &mut turn.st, &turn.history, 1_663, || cs_at(1_664));
        let committed = turn.history[..1_664].to_vec();
        let outcome = cache.release_lane_with_toks(&mut pools, &mut turn.tbl, &mut turn.st, Some(&committed), false);
        assert_eq!(outcome, TurnEndStart::NotSaved(TurnEndMiss::Behind));
        let (at, cs) = next_turn_binds(&mut cache, &mut pools, 1_764);
        assert_eq!((at, cs), (1_600, cs_at(1_600)), "earlier valid checkpoint at 1,600 must still be saved");
    }

    // 3. Defensive `match_and_bind` on an unreleased state holding `turn_ckpt` must drop its Window holds cleanly.
    {
        let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
        while turn.written() < 1_663 {
            turn.decode(&mut cache, &mut pools);
        }
        assert!(turn.st.turn_ckpt.is_some());
        turn.tbl.clear_entries(&mut pools).unwrap();
        for id in turn.st.sealed.drain(..) {
            cache.tree.unpin(id);
        }
        let _ = cache.match_and_bind(&mut pools, &mut turn.tbl, &mut turn.st, &conv(1_500));
        assert!(turn.st.turn_ckpt.is_none());
        cache.release_lane(&mut pools, &mut turn.tbl, &mut turn.st);
    }

    // 4. `release_lane_invalid` at offset 63 drops `turn_ckpt` Window holds and evicts starts sharing pruned blocks.
    {
        let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
        while turn.written() < 1_664 + 63 {
            turn.decode(&mut cache, &mut pools);
        }
        assert!(turn.st.turn_ckpt.is_some());
        let evicted = cache.release_lane_invalid(&mut pools, &mut turn.tbl, &mut turn.st);
        assert!(evicted >= 1);
    }

    drain(cache, pools);
}

#[test]
fn stitched_lane_trailing_guard_never_enters_turn_checkpoint_or_tree_handles() {
    // While a stitched lane's trailing `WINDOW` still contains its zero `Window` guard slot (`is_stitch_guard`),
    // `seal_verify_step` / `take_turn_checkpoint` / `save_turn_end_start` must never publish that guard as a
    // `Window` handle in `EntryTree` and never pin or retain it in `TurnCheckpoint` or `starts`. Once the lane
    // has computed a full `WINDOW` (`1,024` tokens) of real `Window` K/V past `heal_start`, `TurnCheckpoint` holds
    // only computed `Window` blocks and saves the turn-end start cleanly even at `offset = 63`.
    let kvb = 1u32;
    let mut pools = BlockPools::with_capacities(160, 96, kvb).unwrap();
    let mut cache = ServeBlockCache::new();
    cache.set_kv_stitch(true);
    cache.set_approx_retain(true);

    let file_span: Vec<u32> = (0..3_200u32).map(|i| 50_000 + i).collect();
    let mut donor_prompt: Vec<u32> = (0..128u32).map(|i| 2_000 + i).collect();
    donor_prompt.extend_from_slice(&file_span); // [128 .. 3,328)
    donor_prompt.extend((0..257u32).map(|i| 4_000 + i)); // 3,585 tokens -> exact donor start at 3,584
    {
        let mut dtbl = BlockTable::new(96).unwrap();
        let mut dst = LaneBlockState::default();
        assert!(cache.match_and_bind(&mut pools, &mut dtbl, &mut dst, &donor_prompt).is_none());
        let mut p = 0usize;
        while p < donor_prompt.len() {
            let next = effective_pf_target(p, donor_prompt.len());
            cache.ensure_span_blocks(&mut pools, &mut dtbl, p, next - p).unwrap();
            cache.finish_prefill_span(&mut pools, &mut dtbl, &mut dst, &donor_prompt, p, next - p, || cs_at(next));
            p = next;
        }
        cache.release_lane(&mut pools, &mut dtbl, &mut dst);
    }

    let mut card_prompt: Vec<u32> = (0..128u32).map(|i| 6_000 + i).collect();
    card_prompt.extend_from_slice(&file_span); // [128 .. 3,328)
    card_prompt.extend((0..1_680u32).map(|i| 60_000 + i)); // 5,008 tokens

    // Phase 1: Immediately after `apply_stitch_plan` (`heal_start == 3,328`, blocks `36..52` hold `guard_w`),
    // run verify/decode steps across block `52` (`3,392`) and block `53` (`3,456`) while `guard_w` is still in
    // the trailing window `[end - WINDOW .. end)` (and with `guard_w` bound on block `52` itself).
    {
        let mut tbl = BlockTable::new(112).unwrap();
        let mut st = LaneBlockState { owner: card(), prompt_len: 3_328, ..Default::default() };
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &card_prompt).is_none());
        let plans = cache.plan_stitches(&pools, 0, &card_prompt, 0);
        assert_eq!(plans.len(), 1);
        let heal_start = plans[0].heal_start;
        assert_eq!(heal_start, 1_792);
        let hb = heal_start / BLOCK;
        st.prompt_len = heal_start;
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, 0, plans[0].stitch_start, || {
            cs_at(plans[0].stitch_start)
        });
        assert!(matches!(cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &card_prompt, &plans[0]), StitchApplyOutcome::Applied { .. }));
        let guard_w = tbl.get(BlockKind::Window, BlockIndex::new((hb - 1) as u32)).unwrap().expect("stitch zero guard");
        assert!(cache.is_stitch_guard(guard_w));
        assert!(!cache.entry_is_valid_kv(&pools, BlockKind::Window, guard_w));

        // Put a full computed `Full` block at `hb` and bind `guard_w` on `Window` block `hb`, then seal a crossed
        // verify step at `heal_start + BLOCK + 3` (`crossed = heal_start + BLOCK`): `EntryTree` node `hb` must get
        // `window == None` (never `guard_w`) and `TurnCheckpoint` must refuse to hold `guard_w`.
        let b1 = heal_start + BLOCK;
        let step1_end = b1 + 3;
        cache.ensure_span_blocks(&mut pools, &mut tbl, heal_start, BLOCK + 3).unwrap();
        let fe_hb = tbl.get(BlockKind::Full, BlockIndex::new(hb as u32)).unwrap().unwrap();
        pools.full.record_mut(fe_hb.slot()).unwrap().set_length(BLOCK as u32).unwrap();
        tbl.clear_kind_entry(&mut pools.window, BlockIndex::new(hb as u32)).unwrap();
        tbl.fill(&mut pools.window, BlockIndex::new(hb as u32), guard_w.slot(), guard_w.generation()).unwrap();
        st.written = step1_end;
        cache.seal_verify_step(
            &mut pools,
            &tbl,
            &mut st,
            &card_prompt[..step1_end],
            step1_end - 1,
            Some((b1, cs_at(b1))),
            || cs_at(step1_end),
        );
        assert_eq!(st.sealed.len(), hb + 1);
        assert_eq!(cache.tree.handle(st.sealed[hb]).unwrap().window(), None, "guard_w must never become an EntryTree Window handle");
        assert!(st.turn_ckpt.is_none(), "TurnCheckpoint must never hold a stitch zero guard");
        assert_eq!(st.turn_ckpt_miss, Some(TurnEndMiss::BlockNotLive));

        // Complete block `hb + 1` (`b1 .. b2`) with a real computed `Window` slot, landing on `b2`:
        // block `hb + 1`'s handle in `EntryTree` gets its computed `Window` slot, while `TurnCheckpoint` at `b2`
        // still sees `guard_w` in `[b2 - WINDOW .. b1)` and refuses to pin or retain it.
        let b2 = b1 + BLOCK;
        let guard_refs_before = pools.window.record(guard_w.slot()).unwrap().refs();
        for pos in step1_end..b2 {
            cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
            cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
        }
        let we_next = tbl.get(BlockKind::Window, BlockIndex::new((hb + 1) as u32)).unwrap().unwrap();
        assert!(!cache.is_stitch_guard(we_next));
        cache.seal_verify_step(&mut pools, &tbl, &mut st, &card_prompt[..b2], b2 - 1, None, || cs_at(b2));
        assert_eq!(st.sealed.len(), hb + 2);
        assert_eq!(cache.tree.handle(st.sealed[hb + 1]).unwrap().window(), Some(we_next));
        assert!(st.turn_ckpt.is_none(), "trailing window still holds guard_w: no TurnCheckpoint may be taken");
        assert_eq!(st.turn_ckpt_miss, Some(TurnEndMiss::BlockNotLive));
        assert_eq!(pools.window.record(guard_w.slot()).unwrap().refs(), guard_refs_before, "guard_w gained zero checkpoint refs");

        let out = cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&card_prompt[..b2]), false);
        assert_eq!(out, TurnEndStart::NotSaved(TurnEndMiss::BlockNotLive));
        assert!(
            cache.starts.values().all(|s| s.entries.iter().all(|&(_, _, e)| !cache.is_stitch_guard(e))),
            "no retained start may ever hold a stitch guard"
        );
    }

    // Phase 2: Once the stitched lane completes its `>= 1,024`-token healing ramp (`guard_w` completely slid out),
    // a crossed verify step across `5,120` takes a valid `TurnCheckpoint` with zero stitch guards and saves at `offset = 63`.
    {
        let prompt_len = card_prompt.len(); // 5,008
        let mut tbl = BlockTable::new(112).unwrap();
        let mut st = LaneBlockState { owner: card(), prompt_len, ..Default::default() };
        assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &card_prompt).is_none());
        let plans = cache.plan_stitches(&pools, 0, &card_prompt, 0);
        cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, 0, plans[0].stitch_start, || {
            cs_at(plans[0].stitch_start)
        });
        assert!(matches!(cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &card_prompt, &plans[0]), StitchApplyOutcome::Applied { .. }));
        let mut p = st.written;
        while p < prompt_len {
            let next = effective_pf_target(p, prompt_len);
            cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, p, next - p, || cs_at(next));
            p = next;
        }
        let mut history = card_prompt.clone();
        history.push(70_000);
        let mut full_gpu = vec![CLEARED_GPU_TABLE_ENTRY; 112];
        let mut win_gpu = vec![CLEARED_GPU_TABLE_ENTRY; 112];
        let end = 5_120 + 63;
        while st.written < end {
            let p0 = st.written;
            let n_keep = 5.min(end - p0);
            let step_end = p0 + n_keep;
            let boundary = step_end / BLOCK * BLOCK;
            let crossed = (!step_end.is_multiple_of(BLOCK) && boundary > p0).then(|| (boundary, cs_at(boundary)));
            let alloc = cache.ensure_span_blocks_tracking(&mut pools, &mut tbl, p0, 1 + K).unwrap();
            cache.finish_verify_span_to_slices(&mut pools, &mut tbl, &mut st, &alloc, p0, n_keep, &mut full_gpu, &mut win_gpu).unwrap();
            while history.len() < step_end {
                history.push(70_000 + (history.len() - prompt_len) as u32);
            }
            cache.seal_verify_step(&mut pools, &tbl, &mut st, &history, step_end - 1, crossed, || cs_at(step_end));
            history.push(70_000 + (history.len() - prompt_len) as u32);
        }
        let ckpt = st.turn_ckpt.as_ref().expect("healed stitched lane holds TurnCheckpoint at 5,120");
        assert_eq!(ckpt.end, 5_120);
        assert!(ckpt.window.iter().all(|&(_, we)| !cache.is_stitch_guard(we) && cache.entry_is_valid_kv(&pools, BlockKind::Window, we)));
        let out = cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&history[..end]), false);
        assert_eq!(out, TurnEndStart::Saved);
        assert!(cache.starts.values().all(|s| s.entries.iter().all(|&(_, _, e)| !cache.is_stitch_guard(e))));
    }

    drain(cache, pools);
}