inky-engine 3.0.2

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
//! Bounded speculative verification planner, multi-token acceptance budget accounting,
//! and greedy acceptance helpers (`PR #42` / `PR #80` / `t-audit-pr42-port`).
//!
//! Pure `std` logic with zero Metal dependency so `ServeStepPlanner` and scheduler tests
//! exercise verification arena bounds (`spans * (1 + k) <= lg_rows = 128`), context/reply
//! clamping, stop-in-middle truncation, and multi-token reply budget accounting directly.

#![allow(dead_code)]

use std::collections::VecDeque;

/// Supported `--draft-k` bounds for opt-in DSpark speculative decoding in `inky serve`.
pub const MIN_DRAFT_K: usize = 1;
pub const MAX_DRAFT_K: usize = 4;
pub const DEFAULT_DRAFT_K: usize = 3;

/// Reason a candidate speculative verify batch fell back cleanly to standard 1-token decode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VerifyFallbackReason {
    CapacityExceeded { spans: usize, k: usize, needed_rows: usize, lg_rows: usize },
    IneligibleLane,
    ZeroDraftBudget,
    MultiSpanRequiresHgemm,
    /// `INK_PROMPT_LOOKUP`: the drafts' expected acceptance does not pay for the verify rows.
    CostGate,
}

/// Per-lane eligibility snapshot for speculative verification on a planned decode batch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VerifyLaneEligibility {
    pub lane: usize,
    pub p0: usize,
    pub max_k: usize,
    pub kv_cap: usize,
    pub eligible: bool,
}

/// Scheduler dispatch decision for a planned decode batch when `--dspark` is enabled.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodeStepDispatch {
    /// Execute a GPU speculative verify step with shared draft length `k` (`1..=MAX_DRAFT_K`).
    /// `decode_lanes` stay on the 1-token decode path in the same step. One ineligible lane
    /// does not drop the rest of the batch.
    Verify { lanes: Vec<usize>, k: usize, decode_lanes: Vec<usize> },
    /// Fall back cleanly to standard 1-token `encode_decode` for every lane in the batch without failing lanes.
    FallbackDecode { lanes: Vec<usize>, reason: VerifyFallbackReason },
}

/// Check the `spans * (1 + k) <= lg_rows` batch logits arena invariant before encoding a verify step.
pub fn check_verify_rows_fit(spans: usize, k: usize, lg_rows: usize) -> Result<usize, VerifyFallbackReason> {
    let step_len = 1usize.saturating_add(k);
    let needed_rows = spans.saturating_mul(step_len);
    if spans == 0 || needed_rows > lg_rows {
        return Err(VerifyFallbackReason::CapacityExceeded { spans, k, needed_rows, lg_rows });
    }
    Ok(needed_rows)
}

/// Decide whether a planned `ServeStepPlan::Decode` batch runs as a speculative verify step or
/// falls back cleanly to standard 1-token decode:
/// - Ineligible lanes (tool grammar, LoopCD, no draft budget) are listed in `decode_lanes` and
///   do not disqualify eligible lanes.
/// - Shared `k` is the minimum clamped `k` across the lanes that verify (`1..=requested_k`).
/// - Enforces `verify_lanes * (1 + k) <= lg_rows` (128): if exceeded, falls back to standard
///   1-token decode for that step without failing or dropping any lane.
/// - Requires `hgemm` whenever more than one lane verifies.
/// - A step where every lane is ineligible or has no draft still falls back as one batch.
pub fn select_verify_or_decode_fallback(
    dec_lanes: &[usize],
    elig: &[VerifyLaneEligibility],
    requested_k: usize,
    lg_rows: usize,
    hgemm: bool,
) -> DecodeStepDispatch {
    let lanes = dec_lanes.to_vec();
    if lanes.is_empty() || requested_k == 0 {
        return DecodeStepDispatch::FallbackDecode { lanes, reason: VerifyFallbackReason::ZeroDraftBudget };
    }
    if elig.len() != lanes.len() {
        return DecodeStepDispatch::FallbackDecode { lanes, reason: VerifyFallbackReason::IneligibleLane };
    }
    let mut verify_lanes = Vec::new();
    let mut decode_lanes = Vec::new();
    let mut shared_k = requested_k;
    let mut saw_ineligible = false;
    for (idx, c) in elig.iter().enumerate() {
        if c.lane != lanes[idx] {
            return DecodeStepDispatch::FallbackDecode { lanes, reason: VerifyFallbackReason::IneligibleLane };
        }
        if !c.eligible {
            saw_ineligible = true;
            decode_lanes.push(c.lane);
            continue;
        }
        let Some(clamped) = clamp_k(c.p0, c.max_k.min(requested_k), c.kv_cap) else {
            decode_lanes.push(c.lane);
            continue;
        };
        if clamped == 0 {
            decode_lanes.push(c.lane);
            continue;
        }
        shared_k = shared_k.min(clamped);
        verify_lanes.push(c.lane);
    }
    if verify_lanes.is_empty() {
        let reason = if saw_ineligible {
            VerifyFallbackReason::IneligibleLane
        } else {
            VerifyFallbackReason::ZeroDraftBudget
        };
        return DecodeStepDispatch::FallbackDecode { lanes, reason };
    }
    if verify_lanes.len() > 1 && !hgemm {
        return DecodeStepDispatch::FallbackDecode { lanes, reason: VerifyFallbackReason::MultiSpanRequiresHgemm };
    }
    if let Err(reason) = check_verify_rows_fit(verify_lanes.len(), shared_k, lg_rows) {
        return DecodeStepDispatch::FallbackDecode { lanes, reason };
    }
    DecodeStepDispatch::Verify { lanes: verify_lanes, k: shared_k, decode_lanes }
}

/// A mixed verify plus a peeled decode reads the weights twice.
/// Split only when measured accepted drafts pay for that extra pass.
/// `accepted / steps` is the mean accepted drafts per verify lane. The bonus
/// token is not in `accepted`. No finished verify yet means do not split.
/// An empty peel is not a split.
pub fn split_pays(verify_lanes: usize, peeled_lanes: usize, accepted: u64, steps: u64) -> bool {
    if peeled_lanes == 0 {
        return true;
    }
    if verify_lanes == 0 || steps == 0 {
        return false;
    }
    let v = verify_lanes as u128;
    let n = v + peeled_lanes as u128;
    v * u128::from(accepted) > n * u128::from(steps)
}

/// How one decode lane takes part in a `INK_PROMPT_LOOKUP` verify step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlLaneRole {
    /// Drafts (a prompt-lookup match, a DSpark fallback proposal, or a one-hot filler when it has neither).
    Draft { matched: bool },
    /// Rides the verify span but keeps only its first row, sampled exactly as 1-token decode samples it:
    /// a lane whose tool-call JSON grammar is open, whose thinking budget may change its ban inside the
    /// span, or whose reply budget has no room for a draft.
    Pinned,
    /// Cannot share a verify forward at all (its first guided draw, or a LoopCD lane: verify rows carry no
    /// LoopCD blend). The step decodes 1 token for every lane.
    Blocker,
}

/// One lane's input to [`plan_prompt_lookup_step`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlLane {
    pub lane: usize,
    pub p0: usize,
    pub kv_cap: usize,
    pub role: PlLaneRole,
}

/// Decide a `INK_PROMPT_LOOKUP` decode step. Eligibility is per lane, never per step: lanes without a
/// match draft a one-hot filler (exact: its acceptance is `p(filler)`, it only costs rows) and pinned lanes
/// keep one token, so neither stops the other lanes drafting. Only a [`PlLaneRole::Blocker`], no matched
/// lane at all, `!hgemm` with several lanes, or no row/KV room for even `k = 1` falls back to decode.
/// Shared `k` is `requested_k` clamped to the logits arena (`spans * (1 + k) <= lg_rows`) and to every
/// lane's K/V room.
pub fn plan_prompt_lookup_step(
    lanes: &[PlLane],
    requested_k: usize,
    lg_rows: usize,
    hgemm: bool,
) -> DecodeStepDispatch {
    let ids: Vec<usize> = lanes.iter().map(|l| l.lane).collect();
    let fallback = |reason| DecodeStepDispatch::FallbackDecode { lanes: ids.clone(), reason };
    if lanes.is_empty() || requested_k == 0 {
        return fallback(VerifyFallbackReason::ZeroDraftBudget);
    }
    if lanes.iter().any(|l| l.role == PlLaneRole::Blocker) {
        return fallback(VerifyFallbackReason::IneligibleLane);
    }
    if lanes.len() > 1 && !hgemm {
        return fallback(VerifyFallbackReason::MultiSpanRequiresHgemm);
    }
    if !lanes.iter().any(|l| l.role == PlLaneRole::Draft { matched: true }) {
        return fallback(VerifyFallbackReason::ZeroDraftBudget);
    }
    let mut k = requested_k.min((lg_rows / lanes.len()).saturating_sub(1));
    for l in lanes {
        match clamp_k(l.p0, k, l.kv_cap) {
            Some(c) => k = c,
            None => return fallback(VerifyFallbackReason::ZeroDraftBudget),
        }
    }
    if k == 0 {
        let needed_rows = lanes.len() * 2;
        return fallback(VerifyFallbackReason::CapacityExceeded { spans: lanes.len(), k: 1, needed_rows, lg_rows });
    }
    DecodeStepDispatch::Verify { lanes: ids, k, decode_lanes: Vec::new() }
}

/// FNV-1a over the raw IEEE-754 bits of one vocabulary row.
pub fn logit_hash(row: &[f32]) -> u64 {
    let mut h = 0u64;
    for &x in row {
        h = (h ^ u64::from(x.to_bits())).wrapping_mul(0x100000001b3);
    }
    h
}

/// One lane ready for speculative verification. `lane` is the caller's lane index.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VerifyCand {
    pub lane: usize,
    pub p0: usize,
    pub k: usize,
    pub kv_cap: usize,
}

/// One verification span packed into the current GPU verify step (`t = 1 + k`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VerifySpanPlan {
    pub lane: usize,
    pub p0: usize,
    pub k: usize,
}

/// Largest `k` such that `p0 + 1 + k <= kv_cap`, or `None` when the committed token at `p0`
/// itself does not fit the lane's K/V capacity.
pub fn clamp_k(p0: usize, k: usize, kv_cap: usize) -> Option<usize> {
    let room = kv_cap.saturating_sub(p0);
    if room == 0 {
        return None;
    }
    Some(k.min(room - 1))
}

/// Remaining tokens a lane may still emit before hitting either `max` generated tokens or
/// `ctx - 1` (`prompt + gen + 1 <= ctx`).
pub fn reply_budget(prompt: usize, gen: usize, max: usize, ctx: usize) -> usize {
    max.saturating_sub(gen).min(ctx.saturating_sub(prompt.saturating_add(gen).saturating_add(1)))
}

/// Pack verify spans into one GPU verify step bounded by `rows` (`Engine::verify_row_capacity()`,
/// at most `MAX_SPANS = 128` vocabulary rows in `b.lg`).
///
/// - Each span position consumes one activation row and one vocabulary row (`t = 1 + k`), so
///   `spans.len() * (1 + k) <= rows` always holds (preventing the 256-into-128 row overflow).
/// - A span that does not fit the remaining `rows` budget stops packing so that lane and all
///   lanes behind it wait in order for the next step; verify spans are never split or mixed
///   into prefill.
/// - Lanes in one `encode_verify` call share one `k`.
/// - Without `multi` (`!hgemm`), at most one span runs per step.
pub fn plan_verify(cands: &[VerifyCand], rows: usize, multi: bool) -> Vec<VerifySpanPlan> {
    let mut budget = rows;
    let mut out = Vec::new();
    if rows == 0 {
        return out;
    }
    for c in cands {
        if !multi && !out.is_empty() {
            break;
        }
        let Some(k) = clamp_k(c.p0, c.k.min(rows - 1), c.kv_cap) else {
            continue;
        };
        let t = 1 + k;
        if t > budget {
            break;
        }
        if out.first().is_some_and(|p: &VerifySpanPlan| p.k != k) {
            break;
        }
        budget -= t;
        out.push(VerifySpanPlan { lane: c.lane, p0: c.p0, k });
    }
    out
}

/// Result of greedy (`temp == 0`) verification over `k` draft tokens and `k + 1` target argmaxes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GreedyKeep {
    pub emitted: Vec<u32>,
    pub n_keep: usize,
    pub finished: bool,
    pub rows: Vec<usize>,
    /// Token past the accepted drafts (`None` when a stop token inside the accepted drafts ended the block).
    pub bonus: Option<u32>,
}

/// Greedy verification (`temperature == 0`).
/// A draft is kept iff it equals that row's target argmax (`rows[i] == drafts[i]`).
/// On mismatch, emits the target's correction token `rows[n_acc]` and stops.
/// If an accepted draft is in `stop`, emits only through that stop token with `bonus = None`.
pub fn accept_greedy(drafts: &[u32], rows: &[u32], stop: &[u32]) -> GreedyKeep {
    assert_eq!(rows.len(), drafts.len() + 1, "one argmax per draft, plus the bonus row");
    let mut emitted = Vec::new();
    let mut used = Vec::new();
    let mut n_acc = 0usize;
    for i in 0..drafts.len() {
        if rows[i] != drafts[i] {
            break;
        }
        emitted.push(drafts[i]);
        used.push(i);
        n_acc += 1;
        if stop.contains(&drafts[i]) {
            return GreedyKeep { emitted, n_keep: 1 + n_acc, finished: true, rows: used, bonus: None };
        }
    }
    let bonus = rows[n_acc];
    emitted.push(bonus);
    used.push(n_acc);
    GreedyKeep { emitted, n_keep: 1 + n_acc, finished: stop.contains(&bonus), rows: used, bonus: Some(bonus) }
}

/// Multi-token emission accounting for a verified lane (`emit_q` + `reply_budget`).
/// Ensures up to `min(accepted + 1, remaining_max_tokens)` tokens are emitted per verify step,
/// never stopping after 1 token when `reply_budget == 2`.
#[derive(Clone, Debug)]
pub struct SpecEmitState {
    pub pf_end: usize,
    pub gen: usize,
    pub max_tokens: usize,
    pub ctx: usize,
    pub emit_q: VecDeque<u32>,
}

impl SpecEmitState {
    pub fn new(pf_end: usize, max_tokens: usize, ctx: usize) -> Self {
        Self { pf_end, gen: 0, max_tokens, ctx, emit_q: VecDeque::new() }
    }

    /// Remaining reply budget at the current `(pf_end, gen)` cursor.
    pub fn remaining_budget(&self) -> usize {
        reply_budget(self.pf_end, self.gen, self.max_tokens, self.ctx)
    }

    /// Clamp a candidate draft slice `drafts` so `1 + k <= remaining_budget()`.
    /// With `remaining_budget == 2`, `k == 1` (`1` draft + `1` bonus = `2` emitted tokens).
    pub fn clamp_draft_count(&self, drafts_len: usize) -> usize {
        drafts_len.min(self.remaining_budget().saturating_sub(1))
    }

    /// Emit one token through `send_tok` (`false` if client disconnected), returning
    /// `Some(finish_reason)` when the lane finishes (`"cancelled"`, `"stop"`, or `"length"`).
    pub fn emit_token(
        &mut self,
        tok: u32,
        stop: &[u32],
        mut send_tok: impl FnMut(u32) -> bool,
    ) -> Option<&'static str> {
        let ok = send_tok(tok);
        self.gen += 1;
        let budget = self.remaining_budget();
        if !ok {
            Some("cancelled")
        } else if stop.contains(&tok) {
            Some("stop")
        } else if budget == 0 {
            Some("length")
        } else {
            None
        }
    }

    /// Drain all queued tokens in `emit_q`, stopping immediately on disconnect, stop token,
    /// or exhausted `reply_budget`.
    pub fn drain_queue(&mut self, stop: &[u32], mut send_tok: impl FnMut(u32) -> bool) -> Option<&'static str> {
        while let Some(tok) = self.emit_q.pop_front() {
            if let Some(reason) = self.emit_token(tok, stop, &mut send_tok) {
                self.emit_q.clear();
                return Some(reason);
            }
        }
        None
    }
}

#[cfg(test)]
mod verify_planner_tests {
    #[test]
    fn split_pays_only_when_measured_drafts_cover_the_extra_pass() {
        assert!(split_pays(4, 0, 0, 0));
        assert!(!split_pays(4, 20, 12, 0));
        assert!(split_pays(20, 4, 40, 20));
        assert!(!split_pays(4, 20, 12, 4));
        assert!(split_pays(1, 1, 3, 1));
        assert!(!split_pays(1, 1, 2, 1));
        assert!(!split_pays(0, 1, 10, 1));
    }

    use super::*;
    use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};

    #[test]
    fn verify_budget_waits_and_clamps_to_capacity() {
        let c = |lane, p0, k, kv_cap| VerifyCand { lane, p0, k, kv_cap };
        // Two spans of 4, budget 4: the second does not fit and waits.
        let p = plan_verify(&[c(0, 10, 3, 100), c(1, 10, 3, 100)], 4, true);
        assert_eq!(p, vec![VerifySpanPlan { lane: 0, p0: 10, k: 3 }]);
        // Without hgemm a second lane waits even when budget remains.
        let p = plan_verify(&[c(0, 1, 1, 100), c(1, 1, 1, 100)], 100, false);
        assert_eq!(p.len(), 1);
        assert_eq!(p[0].lane, 0);
        // Near K/V boundary: p0=60, cap=64, k=7 -> k=3 because 60+1+3 == 64.
        let p = plan_verify(&[c(0, 60, 7, 64)], 4096, false);
        assert_eq!(p, vec![VerifySpanPlan { lane: 0, p0: 60, k: 3 }]);
        assert!(60 + 1 + p[0].k <= 64);
        // Only committed token fits: k clamps to 0 (t=1).
        let p = plan_verify(&[c(0, 63, 7, 64)], 4096, true);
        assert_eq!(p[0].k, 0);
        // Committed token past cache: lane skipped cleanly without calling encode.
        assert!(plan_verify(&[c(0, 64, 1, 64)], 4096, true).is_empty());
        // Different k is not packed into a step that already fixed k.
        let p = plan_verify(&[c(0, 10, 3, 100), c(1, 10, 1, 100)], 100, true);
        assert_eq!(p.len(), 1);
        assert_eq!(p[0].k, 3);
    }

    #[test]
    fn verify_logit_arena_bounds_256_requested_rows_to_128() {
        let cands: Vec<_> = (0..64).map(|lane| VerifyCand { lane, p0: 10, k: 3, kv_cap: 64 }).collect();
        // 64 lanes * (1 + 3) = 256 requested rows; 128-row arena packs 32 spans (128 rows).
        let plans = plan_verify(&cands, 128, true);
        assert_eq!(plans.len(), 32);
        assert_eq!(plans.iter().map(|p| p.k + 1).sum::<usize>(), 128);
        let waiting = plan_verify(&cands[32..], 128, true);
        assert_eq!(waiting.len(), 32);
        assert_eq!(waiting.first().unwrap().lane, 32);
        assert_eq!(waiting.last().unwrap().lane, 63);
        assert_eq!(plan_verify(&cands, 2, true), vec![VerifySpanPlan { lane: 0, p0: 10, k: 1 }]);
    }

    #[test]
    fn final_verify_block_emits_full_two_token_reply_budget() {
        for (max_tokens, ctx, stop, want_reason) in
            [(2usize, 64usize, vec![], "length"), (10, 63, vec![], "length"), (2, 64, vec![8u32], "stop")]
        {
            let mut st = SpecEmitState::new(60, max_tokens, ctx);
            assert_eq!(st.remaining_budget(), 2);
            assert_eq!(st.clamp_draft_count(4), 1);
            let keep = accept_greedy(&[7], &[7, 8], &stop);
            assert_eq!(keep.emitted, vec![7, 8]);
            st.emit_q.extend(keep.emitted);
            let mut delivered = Vec::new();
            let reason = st.drain_queue(&stop, |tok| {
                delivered.push(tok);
                true
            });
            assert_eq!(delivered, vec![7, 8]);
            assert_eq!(st.gen, 2);
            assert_eq!(reason, Some(want_reason));
        }
    }

    #[test]
    fn verify_stop_in_middle_and_mismatch_semantics() {
        let g = accept_greedy(&[1u32, 7, 2], &[1u32, 7, 2, 9], &[7]);
        assert_eq!(g.emitted, vec![1, 7]);
        assert!(g.finished);
        assert_eq!(g.bonus, None);
        assert_eq!(g.n_keep, 3);

        let g = accept_greedy(&[1, 99, 3], &[1, 2, 3, 4], &[]);
        assert_eq!(g.emitted, vec![1, 2]);
        assert_eq!(g.bonus, Some(2));
        assert!(!g.finished);
        assert_eq!(g.n_keep, 2);

        let g = accept_greedy(&[1, 2, 3], &[1, 2, 3, 8], &[]);
        assert_eq!(g.emitted, vec![1, 2, 3, 8]);
        assert_eq!(g.bonus, Some(8));
        assert_eq!(g.n_keep, 4);
        assert_eq!(g.rows, vec![0, 1, 2, 3]);

        let g = accept_greedy(&[1, 2], &[1, 2, 7], &[7]);
        assert_eq!(g.emitted, vec![1, 2, 7]);
        assert!(g.finished);
        assert_eq!(g.bonus, Some(7));
    }

    #[test]
    fn scheduler_interleaves_prefill_and_bounded_verify_without_mixing_spans() {
        // 3 lanes: lanes 0 and 1 finish prefill and enter generation with drafts (verify),
        // while lane 2 arrives with a multi-chunk prompt and ages until preemption.
        let mut planner = ServeStepPlanner::new(3, 1);
        planner.on_admit(0);
        planner.on_admit(1);
        // Step 1: prefill lanes 0 & 1 to completion (16 tokens each).
        let p1 = planner
            .plan_and_begin_step(
                &[
                    ServeLaneInput { runnable: true, n_past: 0, pf_end: 16, has_pending_decode: false },
                    ServeLaneInput { runnable: true, n_past: 0, pf_end: 16, has_pending_decode: false },
                    ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false },
                ],
                64,
                64,
            )
            .unwrap();
        assert_eq!(p1, ServeStepPlan::Prefill(vec![(0, 0, 16), (1, 0, 16)]));
        assert!(planner.complete_step().is_empty());

        // Admit lane 2 needing prefill (128 tokens), while lanes 0 & 1 are ready to verify/decode.
        planner.on_admit(2);
        let p2 = planner
            .plan_and_begin_step(
                &[
                    ServeLaneInput { runnable: true, n_past: 16, pf_end: 16, has_pending_decode: true },
                    ServeLaneInput { runnable: true, n_past: 16, pf_end: 16, has_pending_decode: true },
                    ServeLaneInput { runnable: true, n_past: 0, pf_end: 128, has_pending_decode: false },
                ],
                64,
                128,
            )
            .unwrap();
        // Generation burst runs lanes 0 & 1 without mixing lane 2's prefill into the step;
        // verify planner packs both spans within the 128-row arena.
        assert_eq!(p2, ServeStepPlan::Decode(vec![0, 1]));
        let cands =
            [VerifyCand { lane: 0, p0: 15, k: 3, kv_cap: 64 }, VerifyCand { lane: 1, p0: 15, k: 3, kv_cap: 64 }];
        let vplans = plan_verify(&cands, 128, true);
        assert_eq!(vplans, vec![VerifySpanPlan { lane: 0, p0: 15, k: 3 }, VerifySpanPlan { lane: 1, p0: 15, k: 3 },]);
        assert!(planner.complete_step().is_empty());
    }

    #[test]
    fn serve_verify_capacity_guard_falls_back_cleanly_to_one_token_decode() {
        let make_elig =
            |n: usize, p0: usize, max_k: usize, kv_cap: usize| -> (Vec<usize>, Vec<VerifyLaneEligibility>) {
                let lanes: Vec<usize> = (0..n).collect();
                let elig = lanes
                    .iter()
                    .map(|&lane| VerifyLaneEligibility { lane, p0, max_k, kv_cap, eligible: true })
                    .collect();
                (lanes, elig)
            };

        // 32 lanes * (1 + 3) = 128 <= lg_rows(128): runs verify with k = 3.
        let (l32, e32) = make_elig(32, 64, 3, 4096);
        assert_eq!(
            select_verify_or_decode_fallback(&l32, &e32, 3, 128, true),
            DecodeStepDispatch::Verify { lanes: l32, k: 3, decode_lanes: vec![] }
        );

        // 33 lanes * (1 + 3) = 132 > lg_rows(128): cleanly falls back to 1-token decode without failing lanes.
        let (l33, e33) = make_elig(33, 64, 3, 4096);
        assert_eq!(
            select_verify_or_decode_fallback(&l33, &e33, 3, 128, true),
            DecodeStepDispatch::FallbackDecode {
                lanes: l33,
                reason: VerifyFallbackReason::CapacityExceeded { spans: 33, k: 3, needed_rows: 132, lg_rows: 128 },
            }
        );

        // k = 4: 25 * 5 = 125 fits; 26 * 5 = 130 falls back cleanly.
        let (l25, e25) = make_elig(25, 64, 4, 4096);
        assert_eq!(
            select_verify_or_decode_fallback(&l25, &e25, 4, 128, true),
            DecodeStepDispatch::Verify { lanes: l25, k: 4, decode_lanes: vec![] }
        );
        let (l26, e26) = make_elig(26, 64, 4, 4096);
        assert_eq!(
            select_verify_or_decode_fallback(&l26, &e26, 4, 128, true),
            DecodeStepDispatch::FallbackDecode {
                lanes: l26,
                reason: VerifyFallbackReason::CapacityExceeded { spans: 26, k: 4, needed_rows: 130, lg_rows: 128 },
            }
        );

        // Near KV boundary clamps shared k across the batch (p0=61, kv_cap=64 -> k=2).
        let (l2, mut e2) = make_elig(2, 10, 4, 64);
        e2[1].p0 = 61;
        assert_eq!(
            select_verify_or_decode_fallback(&l2, &e2, 4, 128, true),
            DecodeStepDispatch::Verify { lanes: l2.clone(), k: 2, decode_lanes: vec![] }
        );

        // One ineligible lane (active LoopCD or JSON grammar) is decoded on its own.
        // It does not drop the eligible lane out of verify.
        e2[1].eligible = false;
        assert_eq!(
            select_verify_or_decode_fallback(&l2, &e2, 3, 128, true),
            DecodeStepDispatch::Verify { lanes: vec![l2[0]], k: 3, decode_lanes: vec![l2[1]] }
        );
        // Every lane ineligible is still one whole-step fallback.
        e2[0].eligible = false;
        assert_eq!(
            select_verify_or_decode_fallback(&l2, &e2, 3, 128, true),
            DecodeStepDispatch::FallbackDecode { lanes: l2.clone(), reason: VerifyFallbackReason::IneligibleLane }
        );
        e2[0].eligible = true;

        // Multi-span without hgemm falls back cleanly; single-span without hgemm verifies.
        e2[1].eligible = true;
        assert_eq!(
            select_verify_or_decode_fallback(&l2, &e2, 3, 128, false),
            DecodeStepDispatch::FallbackDecode { lanes: l2, reason: VerifyFallbackReason::MultiSpanRequiresHgemm }
        );
        let (l1, e1) = make_elig(1, 10, 3, 64);
        assert_eq!(
            select_verify_or_decode_fallback(&l1, &e1, 3, 128, false),
            DecodeStepDispatch::Verify { lanes: l1, k: 3, decode_lanes: vec![] }
        );
    }

    #[test]
    fn prompt_lookup_eligibility_is_per_lane_not_per_step() {
        let lane = |lane, role| PlLane { lane, p0: 100, kv_cap: 4096, role };
        let matched = PlLaneRole::Draft { matched: true };
        let unmatched = PlLaneRole::Draft { matched: false };
        // One lane without a match and one pinned (tool grammar) lane: the matched lane still drafts.
        let lanes = [lane(0, matched), lane(3, unmatched), lane(5, PlLaneRole::Pinned)];
        assert_eq!(plan_prompt_lookup_step(&lanes, 4, 128, true), DecodeStepDispatch::Verify { lanes: vec![0, 3, 5], k: 4, decode_lanes: vec![] });
        // The suffix selector peels the no-draft lane and the ineligible lane.
        // The matched lane stays on verify.
        let elig = [
            VerifyLaneEligibility { lane: 0, p0: 100, max_k: 4, kv_cap: 4096, eligible: true },
            VerifyLaneEligibility { lane: 3, p0: 100, max_k: 0, kv_cap: 4096, eligible: true },
            VerifyLaneEligibility { lane: 5, p0: 100, max_k: 0, kv_cap: 4096, eligible: false },
        ];
        assert_eq!(
            select_verify_or_decode_fallback(&[0, 3, 5], &elig, 4, 128, true),
            DecodeStepDispatch::Verify { lanes: vec![0], k: 4, decode_lanes: vec![3, 5] }
        );
        // No lane matched: nothing to gain, plain decode.
        let none = [lane(0, unmatched), lane(1, PlLaneRole::Pinned)];
        assert_eq!(
            plan_prompt_lookup_step(&none, 4, 128, true),
            DecodeStepDispatch::FallbackDecode { lanes: vec![0, 1], reason: VerifyFallbackReason::ZeroDraftBudget }
        );
        // A LoopCD or first-draw lane cannot share the verify forward.
        let blocked = [lane(0, matched), lane(1, PlLaneRole::Blocker)];
        assert_eq!(
            plan_prompt_lookup_step(&blocked, 4, 128, true),
            DecodeStepDispatch::FallbackDecode { lanes: vec![0, 1], reason: VerifyFallbackReason::IneligibleLane }
        );
    }

    #[test]
    fn prompt_lookup_k_fits_the_logits_arena_and_kv_room() {
        let lanes: Vec<PlLane> = (0..24)
            .map(|i| PlLane { lane: i, p0: 10, kv_cap: 1 << 16, role: PlLaneRole::Draft { matched: i == 0 } })
            .collect();
        // 24 lanes: 128 / 24 = 5 rows each -> k = 4 even when 8 is asked.
        assert_eq!(plan_prompt_lookup_step(&lanes, 8, 128, true), DecodeStepDispatch::Verify { lanes: (0..24).collect(), k: 4, decode_lanes: vec![] });
        let wide: Vec<PlLane> = (0..64).map(|i| PlLane { lane: i, ..lanes[0] }).collect();
        assert_eq!(plan_prompt_lookup_step(&wide, 8, 128, true), DecodeStepDispatch::Verify { lanes: (0..64).collect(), k: 1, decode_lanes: vec![] });
        let too_wide: Vec<PlLane> = (0..65).map(|i| PlLane { lane: i, ..lanes[0] }).collect();
        assert!(matches!(
            plan_prompt_lookup_step(&too_wide, 8, 128, true),
            DecodeStepDispatch::FallbackDecode { reason: VerifyFallbackReason::CapacityExceeded { .. }, .. }
        ));
        // A lane near its K/V end clamps the shared k.
        let mut tight = lanes[..2].to_vec();
        tight[1].p0 = tight[1].kv_cap - 3;
        assert_eq!(plan_prompt_lookup_step(&tight, 8, 128, true), DecodeStepDispatch::Verify { lanes: vec![0, 1], k: 2, decode_lanes: vec![] });
        assert!(matches!(
            plan_prompt_lookup_step(&lanes[..2], 8, 128, false),
            DecodeStepDispatch::FallbackDecode { reason: VerifyFallbackReason::MultiSpanRequiresHgemm, .. }
        ));
    }
}