inky-engine 3.0.0

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
//! Prompt-lookup (n-gram) speculative drafting (`INK_PROMPT_LOOKUP=1 inky serve`).
//!
//! For each decode lane, [`PromptLookup`] indexes every n-gram (`n = MIN_ORDER..=MAX_ORDER`) of the
//! lane's committed token history (prompt plus generated) with a rolling hash, and proposes the `k`
//! tokens that followed the most recent earlier occurrence of the longest matching suffix.
//!
//! The proposal is a deterministic draft, so its draft distribution is `q = one_hot(d_j)`. Speculative
//! rejection against the target `p` then accepts `d_j` with probability `min(1, p(d_j) / 1) = p(d_j)`
//! and, on rejection, draws from `norm([p - q]_+)`, which is `p` with `d_j` zeroed and renormalised.
//! The emitted token is distributed exactly as `p` (see [`onehot_accept`] and the tests below), and at
//! temperature 0 the rule reduces to "accept iff `d_j` is the target argmax", so greedy output is
//! identical with drafting on or off.
//!
//! Memory is bounded: the index is an open-addressed table of at most [`MAX_SLOTS`] 8-byte slots per
//! lane (most recent occurrence wins; an evicted entry only loses a possible proposal, never exactness),
//! and it reads the lane's own history instead of copying it. Hash hits are confirmed against the
//! history, so a collision can never propose tokens that did not follow the suffix.

/// Longest suffix tried (tokens).
pub const MAX_ORDER: usize = 8;
/// Shortest suffix that counts as a match.
pub const MIN_ORDER: usize = 1;
/// Largest draft length prompt lookup proposes (`--draft-k` up to this when `--dspark` is off).
pub const MAX_K: usize = 8;
/// Table size bound: `2^20` slots of 8 bytes = 8 MiB per lane at most. Past it the table is a cache:
/// the newest n-grams evict old ones, which can lose a proposal and never exactness.
pub const MAX_SLOTS: usize = 1 << 20;
const MIN_SLOTS: usize = 1 << 10;
const PROBE: usize = 16;
const EMPTY: u32 = u32::MAX;

#[derive(Clone, Copy)]
struct Slot {
    /// High 32 bits of the n-gram hash (the low bits pick the slot); hits are confirmed against the history.
    key: u32,
    /// Index in the history of the token that followed the n-gram (`EMPTY` = unused slot).
    next: u32,
}

const EMPTY_SLOT: Slot = Slot { key: 0, next: EMPTY };

#[inline]
fn tag(key: u64) -> u32 {
    (key >> 32) as u32
}

/// One lane's n-gram index over its committed history.
pub struct PromptLookup {
    slots: Vec<Slot>,
    used: usize,
    /// History length already indexed.
    len: usize,
    /// FNV of the indexed history's first token and length checks keep `sync` honest when a lane's
    /// history is replaced (new request, resume) rather than extended.
    first: Option<u32>,
    last: Option<u32>,
}

/// A prompt-lookup proposal: `tokens.len() == k`, and the suffix length that matched.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Proposal {
    pub tokens: Vec<u32>,
    pub order: usize,
}

#[inline]
fn mix(mut x: u64) -> u64 {
    x ^= x >> 30;
    x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9);
    x ^= x >> 27;
    x = x.wrapping_mul(0x94d0_49bb_1331_11eb);
    x ^ (x >> 31)
}

/// Hashes of the suffixes of `hist[..end]` of length `1..=MAX_ORDER` (index `n - 1`), read backwards so
/// each longer suffix extends the shorter one in O(1).
#[inline]
fn suffix_keys(hist: &[u32], end: usize, out: &mut [u64; MAX_ORDER]) -> usize {
    let n_max = MAX_ORDER.min(end);
    let mut h = 0x9e37_79b9_7f4a_7c15u64;
    for n in 1..=n_max {
        h = mix(h ^ (u64::from(hist[end - n]) + 1).wrapping_mul(0x1000_0000_01b3));
        out[n - 1] = mix(h ^ n as u64);
    }
    n_max
}

impl Default for PromptLookup {
    fn default() -> Self {
        Self::new()
    }
}

impl PromptLookup {
    pub fn new() -> Self {
        Self { slots: Vec::new(), used: 0, len: 0, first: None, last: None }
    }

    #[cfg(test)]
    /// History length indexed so far.
    pub fn indexed_len(&self) -> usize {
        self.len
    }

    #[cfg(test)]
    /// Bytes the table holds (bounded by `MAX_SLOTS * 8`).
    pub fn table_bytes(&self) -> usize {
        self.slots.len() * std::mem::size_of::<Slot>()
    }

    pub fn clear(&mut self) {
        self.slots.clear();
        self.used = 0;
        self.len = 0;
        self.first = None;
        self.last = None;
    }

    /// Bring the index up to `hist`, indexing only the new tokens. A history that is not an extension
    /// of the indexed one (a new request on the lane, or a rollback) is re-indexed from scratch.
    pub fn sync(&mut self, hist: &[u32]) {
        let extends = hist.len() >= self.len
            && (self.len == 0 || (hist.first().copied() == self.first && hist.get(self.len - 1).copied() == self.last));
        if !extends {
            self.clear();
        }
        if self.slots.is_empty() && hist.len() > 1 {
            self.slots = vec![EMPTY_SLOT; MIN_SLOTS];
        }
        let mut keys = [0u64; MAX_ORDER];
        // The n-grams ending at `t - 1` get their continuation once token `t` exists.
        for t in self.len.max(1)..hist.len() {
            if (self.used + MAX_ORDER) * 4 > self.slots.len() && self.slots.len() < MAX_SLOTS {
                self.rebuild(hist, t, self.slots.len() * 2);
            }
            self.index_pos(hist, t, &mut keys);
        }
        self.len = hist.len();
        self.first = hist.first().copied();
        self.last = hist.last().copied();
    }

    /// Re-index `hist[..t]` (continuations `1..t`) into a table of `cap` slots.
    fn rebuild(&mut self, hist: &[u32], t: usize, cap: usize) {
        self.slots = vec![EMPTY_SLOT; cap.clamp(MIN_SLOTS, MAX_SLOTS)];
        self.used = 0;
        let mut keys = [0u64; MAX_ORDER];
        for s in 1..t {
            self.index_pos(hist, s, &mut keys);
        }
    }

    /// Index the n-grams ending at `t - 1` with continuation `t`. A full probe window grows the table
    /// (re-indexing through `t`) while it is under its bound; only at the bound does the newest entry evict
    /// the home slot, which loses an old proposal and never exactness.
    fn index_pos(&mut self, hist: &[u32], t: usize, keys: &mut [u64; MAX_ORDER]) {
        let n = suffix_keys(hist, t, keys);
        for &key in &keys[(MIN_ORDER - 1)..n] {
            if self.insert(key, t as u32) {
                continue;
            }
            if self.slots.len() < MAX_SLOTS {
                self.rebuild(hist, t + 1, self.slots.len() * 2);
                return;
            }
            let home = (key as usize) & (self.slots.len() - 1);
            self.slots[home] = Slot { key: tag(key), next: t as u32 };
        }
    }

    fn insert(&mut self, key: u64, next: u32) -> bool {
        let mask = self.slots.len() - 1;
        let home = (key as usize) & mask;
        for p in 0..PROBE {
            let s = &mut self.slots[(home + p) & mask];
            if s.next == EMPTY {
                *s = Slot { key: tag(key), next };
                self.used += 1;
                return true;
            }
            if s.key == tag(key) {
                s.next = next; // most recent occurrence wins
                return true;
            }
        }
        false
    }

    fn find(&self, key: u64) -> Option<usize> {
        if self.slots.is_empty() {
            return None;
        }
        let mask = self.slots.len() - 1;
        let home = (key as usize) & mask;
        for p in 0..PROBE {
            let s = self.slots[(home + p) & mask];
            if s.next == EMPTY {
                return None;
            }
            if s.key == tag(key) {
                return Some(s.next as usize);
            }
        }
        None
    }

    /// The longest suffix of `hist` (`MAX_ORDER` down to `MIN_ORDER`) that occurred earlier in `hist`,
    /// and the `k` tokens that followed its most recent earlier occurrence. Tokens past the end of the
    /// history continue from the proposal itself (a repeating pattern keeps repeating). `hist` must be
    /// the history last passed to [`Self::sync`].
    pub fn propose(&self, hist: &[u32], k: usize) -> Option<Proposal> {
        if k == 0 || hist.len() < 2 {
            return None;
        }
        debug_assert_eq!(hist.len(), self.len, "propose after sync");
        let end = hist.len();
        let mut keys = [0u64; MAX_ORDER];
        let n_max = suffix_keys(hist, end, &mut keys).min(end - 1);
        for n in (MIN_ORDER..=n_max).rev() {
            let Some(next) = self.find(keys[n - 1]) else { continue };
            // Confirm against the history: a hash collision or an evicted-and-reused slot proposes nothing.
            if next < n || next >= end || hist[next - n..next] != hist[end - n..end] {
                continue;
            }
            let mut tokens = Vec::with_capacity(k);
            for j in 0..k {
                let at = next + j;
                tokens.push(if at < end { hist[at] } else { tokens[at - end] });
            }
            return Some(Proposal { tokens, order: n });
        }
        None
    }
}

/// Recent per-position acceptance of one lane's drafts: accepted drafts and rejections (a round that kept
/// fewer drafts than it verified ended on one rejection). The rate `acc / (acc + rej)` is the maximum
/// likelihood per-position acceptance of a geometric run. It starts at the optimistic prior
/// [`PRIOR_ACC`] / [`PRIOR_REJ`] so a new request drafts and learns, and both counts halve once they pass
/// [`ACCEPT_WINDOW`], so the rate follows the request's recent rounds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AcceptStats {
    acc: u32,
    rej: u32,
}

/// Prior accepted drafts and rejections of a lane with no rounds yet (rate 3/4).
pub const PRIOR_ACC: u32 = 3;
pub const PRIOR_REJ: u32 = 1;
/// Past this many accepted plus rejected, both counts halve.
pub const ACCEPT_WINDOW: u32 = 64;

impl Default for AcceptStats {
    fn default() -> Self {
        Self { acc: PRIOR_ACC, rej: PRIOR_REJ }
    }
}

impl AcceptStats {
    /// One verified round of `k` drafts that kept `accepted` of them.
    pub fn record(&mut self, accepted: usize, k: usize) {
        self.acc += accepted.min(k) as u32;
        self.rej += u32::from(accepted < k);
        while self.acc + self.rej > ACCEPT_WINDOW {
            self.acc = self.acc.div_ceil(2);
            self.rej = self.rej.div_ceil(2);
        }
    }

    /// Per-position acceptance in `(0, 1)`.
    pub fn rate(&self) -> f64 {
        f64::from(self.acc) / f64::from(self.acc + self.rej)
    }
}

/// One decode lane's prompt-lookup state: its n-gram index and its recent acceptance, both owned by the
/// request (`owner`, the job's sequence number) running on the lane. A different owner starts both from
/// scratch, so nothing from one request can propose for, or gate, another; [`Self::release`] drops the
/// index's memory when the request leaves the lane.
#[derive(Default)]
pub struct LaneLookup {
    owner: Option<u64>,
    index: PromptLookup,
    stats: AcceptStats,
}

impl LaneLookup {
    /// Sync the index to `hist` (the owner's committed history) and propose up to `k` drafts.
    pub fn propose(&mut self, owner: u64, hist: &[u32], k: usize) -> Option<Proposal> {
        if self.owner != Some(owner) {
            self.release();
            self.owner = Some(owner);
        }
        self.index.sync(hist);
        self.index.propose(hist, k)
    }

    /// The owner's recent per-position acceptance (the prior before its first round).
    pub fn rate(&self) -> f64 {
        self.stats.rate()
    }

    /// One verified round of the owner's drafts.
    pub fn record(&mut self, accepted: usize, k: usize) {
        self.stats.record(accepted, k);
    }

    /// The request left the lane: forget it and free the index.
    pub fn release(&mut self) {
        *self = Self::default();
    }

    #[cfg(test)]
    pub fn owner(&self) -> Option<u64> {
        self.owner
    }

    #[cfg(test)]
    pub fn table_bytes(&self) -> usize {
        self.index.slots.capacity() * std::mem::size_of::<Slot>()
    }
}

/// Default cost of one extra verify row per lane, as a share of a 1-token decode step
/// (`INK_PL_ROW_COST` overrides it; `0` turns the gate off).
pub const DEFAULT_ROW_COST: f64 = 0.125;
/// After this many verify steps in a row declined, the next one runs anyway, so lanes measure again.
pub const PROBE_EVERY: u32 = 16;

/// Expected accepted drafts in a round of `k` at per-position acceptance `r`: `r + r^2 + ... + r^k`.
pub fn expected_accepted(r: f64, k: usize) -> f64 {
    let mut sum = 0.0;
    let mut p = 1.0;
    for _ in 0..k {
        p *= r;
        sum += p;
    }
    sum
}

/// The step-level cost gate for prompt-lookup verify. A verify step of `L` lanes and shared draft length `k`
/// costs `1 + row_cost * k` decode steps (each lane reads `k` more rows) and emits `L + sum_i E_i(k)` tokens,
/// where `E_i` is [`expected_accepted`] at lane `i`'s recent rate (lanes without a draft add nothing); a
/// decode step emits `L`. The gate picks the smallest `k` in `1..=k_max` with the most tokens per unit cost,
/// and verifies only when that beats decode. After [`PROBE_EVERY`] declines in a row it verifies anyway at
/// that `k`, so lanes whose drafts were judged too weak are measured again. `row_cost == 0` is the gate off:
/// every planned step verifies at the planner's `k`.
#[derive(Clone, Debug)]
pub struct CostGate {
    pub row_cost: f64,
    declined: u32,
}

impl CostGate {
    pub fn new(row_cost: f64) -> Self {
        Self { row_cost, declined: 0 }
    }

    /// Tokens per decode-step cost of a verify step at `k` (`1.0` per lane is what decode gives).
    pub fn yield_at(&self, rates: &[Option<f64>], k: usize) -> f64 {
        let lanes = rates.len() as f64;
        let gain: f64 = rates.iter().flatten().map(|&r| expected_accepted(r, k)).sum();
        (lanes + gain) / (1.0 + self.row_cost * k as f64)
    }

    /// The `k` to verify at, or `None` to decode. `rates[i]` is lane `i`'s recent acceptance when it has a
    /// draft, `None` when it rides with a filler or is pinned to one token.
    pub fn decide(&mut self, rates: &[Option<f64>], k_max: usize) -> Option<usize> {
        if k_max == 0 || rates.is_empty() {
            return None;
        }
        if self.row_cost == 0.0 {
            // Gate off: every planned verify runs at the planner's k (the behaviour before the gate).
            return Some(k_max);
        }
        let mut best = (1, self.yield_at(rates, 1));
        for k in 2..=k_max {
            let y = self.yield_at(rates, k);
            if y > best.1 {
                best = (k, y);
            }
        }
        if best.1 > rates.len() as f64 || self.declined >= PROBE_EVERY {
            self.declined = 0;
            Some(best.0)
        } else {
            self.declined += 1;
            None
        }
    }
}

/// The acceptance rule for a one-hot draft: `q(d) = 1`, so accept with probability `min(1, p(d) / q(d))
/// = p(d)`. `u` is uniform on `[0, 1)`; `p >= 1` accepts without a draw.
#[inline]
pub fn onehot_accept(p_d: f32, u: f32) -> bool {
    p_d >= 1.0 || u < p_d
}

#[cfg(test)]
/// Greedy acceptance over `drafts` against per-row target argmaxes `rows` (`rows.len() == drafts.len() + 1`):
/// the accepted prefix, then the target's own token. The reference the greedy exactness tests compare to.
pub fn greedy_accept(drafts: &[u32], rows: &[u32]) -> Vec<u32> {
    assert_eq!(rows.len(), drafts.len() + 1);
    let mut out = Vec::with_capacity(rows.len());
    for (d, &r) in drafts.iter().zip(rows) {
        out.push(r);
        if *d != r {
            return out;
        }
    }
    out.push(rows[drafts.len()]);
    out
}

#[cfg(test)]
/// What offline replay measures for one generated stream: drafts proposed and accepted at draft length
/// `k`, assuming the target emits the recorded tokens (for a one-hot draft, `P(accept d) = p(d)` equals
/// `P(recorded token = d)`, so the expected acceptance is the same).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ReplayStats {
    pub generated: usize,
    pub steps: usize,
    pub steps_with_match: usize,
    pub proposed: usize,
    pub accepted: usize,
    /// `accept_hist[a]` counts steps with `a` accepted drafts (`0..=k`).
    pub accept_hist: Vec<usize>,
    /// `by_order[n] = (steps, accepted drafts)` for steps whose match had suffix length `n`.
    pub by_order: Vec<(usize, usize)>,
}

#[cfg(test)]
impl ReplayStats {
    pub fn add(&mut self, o: &ReplayStats) {
        self.generated += o.generated;
        self.steps += o.steps;
        self.steps_with_match += o.steps_with_match;
        self.proposed += o.proposed;
        self.accepted += o.accepted;
        if self.accept_hist.len() < o.accept_hist.len() {
            self.accept_hist.resize(o.accept_hist.len(), 0);
        }
        for (a, b) in self.accept_hist.iter_mut().zip(&o.accept_hist) {
            *a += b;
        }
        if self.by_order.len() < o.by_order.len() {
            self.by_order.resize(o.by_order.len(), (0, 0));
        }
        for (a, b) in self.by_order.iter_mut().zip(&o.by_order) {
            a.0 += b.0;
            a.1 += b.1;
        }
    }
}

#[cfg(test)]
/// Simulate prompt-lookup decoding of `generated` after `prompt` at draft length `k`: each step drafts
/// from the committed history, accepts the drafts that equal the next recorded tokens, and commits the
/// accepted drafts plus one target token. Steps without a match emit one token.
pub fn replay(prompt: &[u32], generated: &[u32], k: usize) -> ReplayStats {
    let mut idx = PromptLookup::new();
    replay_with(prompt, generated, k, |hist, k| {
        idx.sync(hist);
        idx.propose(hist, k).map(|p| (p.tokens, p.order))
    })
}

#[cfg(test)]
/// [`replay`] with any proposer: `propose(history, k)` returns up to `k` drafts and the match length it
/// used (`0` when it does not say), or `None` for no proposal. Used to compare drafting policies offline.
pub fn replay_with(
    prompt: &[u32],
    generated: &[u32],
    k: usize,
    mut propose: impl FnMut(&[u32], usize) -> Option<(Vec<u32>, usize)>,
) -> ReplayStats {
    let mut st = ReplayStats {
        accept_hist: vec![0; k + 1],
        by_order: vec![(0, 0); MAX_ORDER + 1],
        generated: generated.len(),
        ..Default::default()
    };
    let mut hist = prompt.to_vec();
    let mut at = 0;
    while at < generated.len() {
        st.steps += 1;
        let mut take = 1;
        if let Some((tokens, order)) = propose(&hist, k).filter(|(t, _)| !t.is_empty()) {
            st.steps_with_match += 1;
            let room = generated.len() - at - 1;
            let kk = tokens.len().min(k).min(room);
            st.proposed += kk;
            let acc = tokens[..kk].iter().zip(&generated[at..]).take_while(|(a, b)| a == b).count();
            st.accepted += acc;
            st.accept_hist[acc] += 1;
            let o = order.min(MAX_ORDER);
            st.by_order[o].0 += 1;
            st.by_order[o].1 += acc;
            take = acc + 1;
        }
        hist.extend_from_slice(&generated[at..at + take]);
        at += take;
    }
    st
}

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

    fn brute(hist: &[u32], k: usize) -> Option<Proposal> {
        let end = hist.len();
        for n in (MIN_ORDER..=MAX_ORDER.min(end.saturating_sub(1))).rev() {
            let needle = &hist[end - n..];
            for s in (0..end - n).rev() {
                if &hist[s..s + n] == needle {
                    let next = s + n;
                    let mut t = Vec::new();
                    for j in 0..k {
                        let at = next + j;
                        t.push(if at < end { hist[at] } else { t[at - end] });
                    }
                    return Some(Proposal { tokens: t, order: n });
                }
            }
        }
        None
    }

    fn lcg(seed: &mut u64) -> u64 {
        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
        *seed >> 33
    }

    #[test]
    fn longest_most_recent_suffix_and_its_continuation() {
        let mut ix = PromptLookup::new();
        // "1 2 3 4 9 | 2 3 4 7 | 1 2 3 4" -> the order-4 suffix [1 2 3 4] last occurred at 0, followed by 9.
        let h = [1, 2, 3, 4, 9, 2, 3, 4, 7, 1, 2, 3, 4];
        ix.sync(&h);
        let p = ix.propose(&h, 3).unwrap();
        assert_eq!(p.order, 4);
        assert_eq!(p.tokens, vec![9, 2, 3]);
        // Shorter suffix [3 4] alone would pick the most recent (followed by 7); longest wins.
        let h2 = [5, 3, 4, 7, 8, 3, 4];
        ix.sync(&h2); // not an extension: re-index
        let p2 = ix.propose(&h2, 2).unwrap();
        assert_eq!((p2.order, p2.tokens), (2, vec![7, 8]));
    }

    #[test]
    fn most_recent_occurrence_wins_and_no_match_is_none() {
        let mut ix = PromptLookup::new();
        let h = [7, 1, 7, 2, 7];
        ix.sync(&h);
        assert_eq!(ix.propose(&h, 1).unwrap().tokens, vec![2]);
        let fresh = [1, 2, 3, 4];
        ix.sync(&fresh);
        assert_eq!(ix.propose(&fresh, 3), None);
        assert_eq!(ix.propose(&fresh[..0], 3), None);
    }

    #[test]
    fn proposal_runs_on_into_a_repeating_pattern() {
        let mut ix = PromptLookup::new();
        let h = [4, 5, 4, 5, 4];
        ix.sync(&h);
        let p = ix.propose(&h, 5).unwrap();
        assert_eq!(p.tokens, vec![5, 4, 5, 4, 5]);
    }

    #[test]
    fn incremental_sync_matches_brute_force_and_full_reindex() {
        let mut seed = 7u64;
        for trial in 0..10 {
            let vocab = 3 + (trial % 5) as u64;
            let mut hist: Vec<u32> = Vec::new();
            let mut inc = PromptLookup::new();
            for _ in 0..300 {
                hist.push(lcg(&mut seed) as u32 % vocab as u32);
                inc.sync(&hist);
                let mut full = PromptLookup::new();
                full.sync(&hist);
                let want = brute(&hist, 4);
                assert_eq!(inc.propose(&hist, 4), want, "incremental, len {}", hist.len());
                assert_eq!(full.propose(&hist, 4), want, "full, len {}", hist.len());
            }
        }
    }

    #[test]
    fn rewritten_history_is_reindexed_not_trusted() {
        let mut ix = PromptLookup::new();
        let a = [1, 2, 3, 1, 2];
        ix.sync(&a);
        assert_eq!(ix.propose(&a, 1).unwrap().tokens, vec![3]);
        // Same length, different contents (a new request on the lane): nothing from `a` may leak.
        let b = [9, 8, 7, 6, 2];
        ix.sync(&b);
        assert_eq!(ix.propose(&b, 1), None);
        // A shorter history (rollback) re-indexes too.
        ix.sync(&b[..3]);
        assert_eq!(ix.indexed_len(), 3);
        assert_eq!(ix.propose(&b[..3], 1), None);
    }

    #[test]
    fn forced_hash_collisions_are_confirmed_against_history() {
        let mut ix = PromptLookup::new();
        let h = [1, 2, 3, 4, 5, 6];
        ix.sync(&h);
        // Corrupt every slot to point at a continuation whose n-gram does not match the suffix.
        for s in ix.slots.iter_mut().filter(|s| s.next != EMPTY) {
            s.next = 2;
        }
        assert_eq!(ix.propose(&h, 2), None, "a stale or colliding slot must never propose");
    }

    #[test]
    fn memory_is_bounded_on_long_histories() {
        let mut seed = 99u64;
        let mut ix = PromptLookup::new();
        let mut hist: Vec<u32> = Vec::new();
        for _ in 0..100_000 {
            hist.push((lcg(&mut seed) % 50_000) as u32);
        }
        ix.sync(&hist);
        assert!(ix.table_bytes() <= MAX_SLOTS * 8, "table {} bytes", ix.table_bytes());
        // Still finds a planted repeat at the end of a long history.
        let tail: Vec<u32> = hist[99_000..99_010].to_vec();
        hist.extend_from_slice(&tail);
        ix.sync(&hist);
        let p = ix.propose(&hist, 3).unwrap();
        assert_eq!(p.order, MAX_ORDER);
        assert_eq!(p.tokens, hist[99_010..99_013].to_vec());
    }

    #[test]
    fn greedy_accept_is_target_argmax_chain() {
        assert_eq!(greedy_accept(&[5, 6, 7], &[5, 6, 7, 8]), vec![5, 6, 7, 8]);
        assert_eq!(greedy_accept(&[5, 9, 7], &[5, 6, 7, 8]), vec![5, 6]);
        assert_eq!(greedy_accept(&[1, 6, 7], &[5, 6, 7, 8]), vec![5]);
    }

    /// One verify position with a one-hot draft at `d`, using the given acceptance rule and two uniforms;
    /// on rejection the residual `norm([p - one_hot(d)]_+)` is drawn by inverse CDF.
    fn onehot_step(p: &[f64], d: usize, u_acc: f64, u_res: f64, accept: impl Fn(f32, f32) -> bool) -> usize {
        if accept(p[d] as f32, u_acc as f32) {
            return d;
        }
        let total: f64 = p.iter().enumerate().filter(|&(i, _)| i != d).map(|(_, &x)| x).sum();
        let mut r = u_res * total;
        let mut last = d;
        for (i, &x) in p.iter().enumerate() {
            if i == d || x <= 0.0 {
                continue;
            }
            last = i;
            r -= x;
            if r <= 0.0 {
                return i;
            }
        }
        last
    }

    /// The output distribution of [`onehot_step`] integrated over a midpoint grid of both uniforms:
    /// exact up to `O(1 / grid)` per cell, so a correct rule lands within `2 / grid` of `p`.
    fn onehot_output_dist(p: &[f64], d: usize, grid: usize, accept: impl Fn(f32, f32) -> bool + Copy) -> Vec<f64> {
        let mut out = vec![0.0; p.len()];
        let w = 1.0 / (grid * grid) as f64;
        for i in 0..grid {
            let ua = (i as f64 + 0.5) / grid as f64;
            for j in 0..grid {
                let ur = (j as f64 + 0.5) / grid as f64;
                out[onehot_step(p, d, ua, ur, accept)] += w;
            }
        }
        out
    }

    fn tvd(a: &[f64], b: &[f64]) -> f64 {
        0.5 * a.iter().zip(b).map(|(x, y)| (x - y).abs()).sum::<f64>()
    }

    #[test]
    fn onehot_rejection_emits_exactly_the_target_distribution() {
        let p = [0.05, 0.4, 0.25, 0.2, 0.1];
        for d in 0..p.len() {
            let got = onehot_output_dist(&p, d, 400, onehot_accept);
            assert!(tvd(&got, &p) < 2.0 / 400.0, "draft {d}: {got:?} vs {p:?}");
        }
        // p(d) = 1 always accepts; p(d) = 0 always rejects and redistributes over the rest.
        let certain = [0.0, 1.0, 0.0];
        assert!(tvd(&onehot_output_dist(&certain, 1, 50, onehot_accept), &certain) < 1e-12);
        let never = [0.5, 0.0, 0.5];
        assert!(tvd(&onehot_output_dist(&never, 1, 200, onehot_accept), &never) < 2.0 / 200.0);
    }

    #[test]
    fn planted_slip_accepting_the_draft_without_the_p_check_is_caught() {
        let p = [0.05, 0.4, 0.25, 0.2, 0.1];
        // The slip: take d_j whenever it is proposed. The same harness must flag it for every draft.
        let slip = |_: f32, _: f32| true;
        for d in 0..p.len() {
            let got = onehot_output_dist(&p, d, 400, slip);
            assert!(tvd(&got, &p) > 0.5, "slip at draft {d} went unnoticed: {got:?}");
        }
        // A subtler slip (accept with p(d) squared-root, i.e. too often) is caught as well.
        let lenient = |pd: f32, u: f32| u < pd.sqrt();
        assert!(tvd(&onehot_output_dist(&p, 0, 400, lenient), &p) > 0.1);
    }

    #[test]
    fn accept_stats_start_at_the_prior_and_follow_recent_rounds() {
        let mut st = AcceptStats::default();
        assert_eq!(st.rate(), 0.75);
        // Full rounds raise it, empty rounds lower it.
        st.record(4, 4);
        assert_eq!(st.rate(), 7.0 / 8.0);
        st.record(0, 4);
        assert_eq!(st.rate(), 7.0 / 9.0);
        // A long run of misses drives it towards 0, the window halves the counts, and it never reaches 0
        // (so a zero-cost gate always verifies); a run of hits brings it back within the window.
        for _ in 0..500 {
            st.record(0, 4);
        }
        assert!(st.acc + st.rej <= ACCEPT_WINDOW && st.rate() > 0.0 && st.rate() < 0.05, "{st:?}");
        for _ in 0..40 {
            st.record(4, 4);
        }
        assert!(st.rate() > 0.9, "{st:?}");
    }

    #[test]
    fn lane_lookup_is_owned_by_one_request_and_released_empty() {
        let mut l = LaneLookup::default();
        let a = [1, 2, 3, 1, 2];
        assert_eq!(l.propose(7, &a, 1).unwrap().tokens, vec![3]);
        l.record(0, 4);
        l.record(0, 4);
        assert!(l.rate() < 0.75);
        // Another request on the lane whose history extends `a` token for token: nothing of request 7 carries
        // over (a fresh index finds the same match from the history alone, and the estimate is the prior).
        let b = [1, 2, 3, 1, 2, 9, 9];
        let p = l.propose(8, &b, 1);
        assert_eq!(l.owner(), Some(8));
        assert_eq!(l.rate(), AcceptStats::default().rate());
        let mut fresh = PromptLookup::new();
        fresh.sync(&b);
        assert_eq!(p, fresh.propose(&b, 1));
        assert!(l.table_bytes() > 0);
        l.release();
        assert_eq!((l.owner(), l.table_bytes()), (None, 0));
        assert_eq!(l.rate(), AcceptStats::default().rate());
    }

    #[test]
    fn expected_accepted_is_the_geometric_partial_sum() {
        assert_eq!(expected_accepted(0.5, 0), 0.0);
        assert_eq!(expected_accepted(0.5, 3), 0.5 + 0.25 + 0.125);
        assert_eq!(expected_accepted(1.0, 4), 4.0);
        assert_eq!(expected_accepted(0.0, 4), 0.0);
    }

    #[test]
    fn cost_gate_free_rows_always_verify_at_full_k() {
        // Row cost 0 (INK_PL_ROW_COST=0) is #259: every planned verify runs at the planner's k.
        let mut g = CostGate::new(0.0);
        for rates in [vec![Some(0.01)], vec![Some(0.9), None, None], vec![None, Some(1e-6)]] {
            for k in 1..=MAX_K {
                assert_eq!(g.decide(&rates, k), Some(k), "{rates:?} k {k}");
            }
        }
        assert_eq!(g.decide(&[], 4), None);
        assert_eq!(g.decide(&[Some(0.5)], 0), None);
    }

    #[test]
    fn cost_gate_verifies_only_when_expected_acceptance_pays_and_picks_k() {
        let mut g = CostGate::new(0.125);
        // One lane at 0.9: E(k) - 0.125 k peaks at the largest k (0.9^k > 0.125 up to k = 19).
        assert_eq!(g.decide(&[Some(0.9)], 4), Some(4));
        // One lane at 0.3: E(1) = 0.3 > 0.125, but each further row costs more than it returns.
        let y = |k| g.yield_at(&[Some(0.3)], k);
        assert!(y(1) > 1.0 && y(1) > y(2) && y(2) > y(3));
        assert_eq!(g.decide(&[Some(0.3)], 4), Some(1));
        // One lane at 0.1 does not pay even at k = 1.
        assert_eq!(g.decide(&[Some(0.1)], 4), None);
        // Riders dilute: a 0.5 lane pays alone, not among 7 rider lanes whose rows cost the same.
        assert_eq!(g.decide(&[Some(0.5)], 4), Some(2));
        let mut riders = vec![None; 7];
        riders.push(Some(0.5));
        assert_eq!(g.decide(&riders, 4), None);
        // Several good lanes pay for the riders.
        let mixed = [Some(0.8), Some(0.8), Some(0.8), None];
        assert!(g.decide(&mixed, 4).is_some());
    }

    #[test]
    fn cost_gate_probes_after_a_run_of_declines() {
        let mut g = CostGate::new(0.5);
        let weak = [Some(0.2)];
        for step in 1..=PROBE_EVERY {
            assert_eq!(g.decide(&weak, 4), None, "step {step}");
        }
        // After PROBE_EVERY declines in a row the next step runs as a probe at the best (cheapest) k, and the
        // count starts again.
        assert_eq!(g.decide(&weak, 4), Some(1));
        assert_eq!(g.decide(&weak, 4), None);
        // A step that pays resets the run too.
        assert_eq!(g.decide(&[Some(0.99)], 4).map(|k| k >= 1), Some(true));
        for _ in 1..=PROBE_EVERY {
            assert_eq!(g.decide(&weak, 4), None);
        }
        assert_eq!(g.decide(&weak, 4), Some(1));
    }

    #[test]
    fn replay_counts_accepted_drafts_on_a_repeating_stream() {
        let prompt = [1, 2, 3, 4, 5, 6, 7, 8];
        let generated = [1, 2, 3, 4, 5, 6, 7, 8];
        let st = replay(&prompt, &generated, 3);
        assert_eq!(st.generated, 8);
        // Step 1: suffix [8] has no earlier occurrence -> 1 token. Step 2: [1] matched at 0, drafts [2,3,4]
        // all accepted plus the target's 5. Step 3: [1..5] matched, only 2 tokens of room left: both accepted.
        assert_eq!(st.steps, 3);
        assert_eq!(st.accepted, 5);
        assert_eq!((st.accept_hist[3], st.accept_hist[2], st.accept_hist[0]), (1, 1, 0));
        let none = replay(&[1, 2, 3], &[9, 10, 11], 3);
        assert_eq!((none.accepted, none.steps_with_match), (0, 0));
    }
}