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
use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};

pub(super) const SERVE_STEP_MAX_BYPASS: u32 = 16;

/// Default `--prefill-share`: percent of charged step time (each step capped at 4 s) prefill gets while decoders also wait.
pub(super) const SERVE_PREFILL_SHARE: u32 = 60;

/// The live scheduler calls this after it has applied backpressure and cache deferrals.
#[inline]
pub(super) fn plan(
    planner: &mut ServeStepPlanner,
    inputs: &[ServeLaneInput],
    budget: usize,
    align: usize,
    prefill_step_cap: Option<usize>,
) -> Option<ServeStepPlan> {
    #[cfg(test)]
    let before = super::scheduler_trace::snapshot(planner, inputs.len());
    // Absent, or zero, is today's chunk: no extra limit on a contended prefill.
    let limit = prefill_step_cap.filter(|n| *n > 0).unwrap_or(usize::MAX);
    let (decision, _effective_budget) = planner.plan_with_prefill_limit(inputs, budget, align, limit);
    #[cfg(test)]
    if let Some(ages) = before {
        // The frame carries the incoming budget, the cap (0: none) and the budget the planner used,
        // so the trace check binds how the cap shortens a step, not only the slicing that follows.
        let cap = prefill_step_cap.filter(|n| *n > 0).unwrap_or(0);
        super::scheduler_trace::record(planner, inputs, (budget, cap, _effective_budget), align, &ages, decision.as_ref());
    }
    decision
}

/// The live scheduler calls this with the measured wall time of each step it executed.
#[inline]
pub(super) fn charge(planner: &mut ServeStepPlanner, elapsed: std::time::Duration) {
    let elapsed_us = u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX);
    #[cfg(test)]
    let before = super::scheduler_trace::charge_snapshot(planner);
    planner.charge_step(elapsed_us);
    #[cfg(test)]
    if let Some(before) = before {
        super::scheduler_trace::record_charge(planner, elapsed_us, before);
    }
}

/// Wall time of one step's GPU intervals, each counted exactly once: the step's command buffer
/// and any GPU work dispatched after it before the step's results are used (DSpark's rejection
/// sampling, batched or per span). The clock is an argument so tests can delay the work.
pub(super) struct StepTime<C: FnMut() -> std::time::Instant> {
    clock: C,
    total: std::time::Duration,
}

impl<C: FnMut() -> std::time::Instant> StepTime<C> {
    pub(super) fn new(clock: C) -> Self {
        Self { clock, total: std::time::Duration::ZERO }
    }

    /// Add an interval measured elsewhere (the command buffer from encode to completion).
    pub(super) fn add(&mut self, interval: std::time::Duration) {
        self.total += interval;
    }

    /// Run synchronous GPU work and add its wall time.
    pub(super) fn time<T>(&mut self, work: impl FnOnce() -> T) -> T {
        let start = (self.clock)();
        let out = work();
        self.total += (self.clock)().saturating_duration_since(start);
        out
    }

    pub(super) fn total(&self) -> std::time::Duration {
        self.total
    }
}

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

    const CAP: usize = 1024;
    const CHUNK: usize = 4096;
    const PREFILL_US_PER_TOKEN: u64 = 25; // synthetic: a 4096-token step is 102.4 ms
    const DECODE_STEP_US: u64 = 10_000;

    fn prefill_tokens(plan: &ServeStepPlan) -> usize {
        match plan {
            ServeStepPlan::Prefill(spans) => spans.iter().map(|&(_, _, n)| n).sum(),
            ServeStepPlan::Decode(_) => 0,
        }
    }

    /// One prefiller with a long prompt and one waiting decoder: the contended prefill step,
    /// its tokens and the effective budget the planner returns, at the cap and without it.
    #[test]
    fn prefill_cap_bounds_the_contended_step_and_reports_its_budget() {
        let prefill = ServeLaneInput { runnable: true, n_past: 0, pf_end: 16384, has_pending_decode: false };
        let decode = ServeLaneInput { runnable: true, n_past: 128, pf_end: 128, has_pending_decode: true };
        for (limit, want) in [(CAP, CAP), (usize::MAX, CHUNK)] {
            let mut planner = ServeStepPlanner::new(2, SERVE_STEP_MAX_BYPASS).with_prefill_share(SERVE_PREFILL_SHARE);
            planner.on_admit(0);
            planner.on_admit(1);
            let (plan, effective) = planner.plan_with_prefill_limit(&[prefill, decode], CHUNK, 64, limit);
            let plan = plan.expect("both classes wait, so a step is planned");
            assert!(matches!(plan, ServeStepPlan::Prefill(_)), "share starts at 0, so prefill goes first: {plan:?}");
            assert_eq!(effective, want, "limit {limit}");
            assert_eq!(prefill_tokens(&plan), want, "limit {limit}");
        }
        // Uncontended (no decoder waiting): the cap never applies.
        let mut planner = ServeStepPlanner::new(1, SERVE_STEP_MAX_BYPASS).with_prefill_share(SERVE_PREFILL_SHARE);
        planner.on_admit(0);
        let (plan, effective) = planner.plan_with_prefill_limit(&[prefill], CHUNK, 64, CAP);
        assert_eq!((prefill_tokens(&plan.unwrap()), effective), (CHUNK, CHUNK));
    }

    /// More runnable lanes than the cap: the effective budget still rises to one token per
    /// runnable lane, and that floor funds the ceiling reservation. Every prefiller the step owes
    /// (at W, or at W - 1 with the decoder at W - 1) is served, and no lane is passed over more
    /// than W steps in a row. Only an owed lane takes a span that is not whole blocks: it has no
    /// block left to take, and may not wait.
    #[test]
    fn prefill_cap_keeps_the_per_lane_floor_and_the_ceiling_reservation() {
        let n = CAP + 6;
        let w = 3;
        let mut planner = ServeStepPlanner::new(n, w).with_prefill_share(SERVE_PREFILL_SHARE);
        let mut inputs = vec![ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 20, has_pending_decode: false }; n];
        inputs[0] = ServeLaneInput { runnable: true, n_past: 1, pf_end: 1, has_pending_decode: true };
        for i in 0..n {
            planner.on_admit(i);
        }
        let mut prefill_steps = 0;
        let mut reserved_seen = 0;
        let mut part_spans = 0;
        let mut missed = vec![0u32; n];
        for _ in 0..24 {
            let dec_wait = planner.wait_ticks(0);
            let reserve_at = if dec_wait + 1 >= w { w - 1 } else { w };
            // Wait is snapshotted before the plan: a served lane's wait_ticks is reset to 0.
            let owed: std::collections::BTreeSet<usize> = (1..n).filter(|&i| planner.wait_ticks(i) >= reserve_at).collect();
            let (plan, effective) = planner.plan_with_prefill_limit(&inputs, CHUNK, 64, CAP);
            let mut served = std::collections::BTreeSet::new();
            let micros = match plan.unwrap() {
                ServeStepPlan::Prefill(spans) => {
                    prefill_steps += 1;
                    assert_eq!(effective, n, "the floor lifts the cap to one token per runnable lane");
                    let tokens: usize = spans.iter().map(|&(_, _, c)| c).sum();
                    assert!(tokens <= n);
                    served.extend(spans.iter().map(|&(i, _, _)| i));
                    assert!(owed.is_subset(&served), "an owed prefiller was made to wait: {:?}", owed.difference(&served).collect::<Vec<_>>());
                    reserved_seen += owed.len();
                    for (i, pos, c) in spans {
                        assert_eq!(inputs[i].n_past, pos);
                        if c % 64 != 0 || (pos + c) % 64 != 0 {
                            // A part-block span: an owed lane without a block, or a lane such a
                            // span left inside a block coming back to the boundary.
                            assert!(owed.contains(&i) || (pos % 64 != 0 && (pos + c) % 64 == 0), "lane {i} sliver {c} at {pos}");
                            part_spans += 1;
                        }
                        inputs[i].n_past += c;
                    }
                    tokens as u64 * PREFILL_US_PER_TOKEN
                }
                ServeStepPlan::Decode(lanes) => {
                    assert_eq!(effective, CHUNK, "a decode step is not shortened");
                    served.extend(lanes);
                    inputs[0].n_past += 1;
                    inputs[0].pf_end += 1;
                    DECODE_STEP_US
                }
            };
            charge(&mut planner, std::time::Duration::from_micros(micros));
            planner.complete_step();
            for i in 0..n {
                missed[i] = if served.contains(&i) { 0 } else { missed[i] + 1 };
                assert!(missed[i] <= w, "lane {i} passed over {} steps in a row (W = {w})", missed[i]);
            }
        }
        assert!(prefill_steps > 0 && reserved_seen > 0, "the reservation was exercised ({prefill_steps} steps, {reserved_seen} lanes)");
        assert!(part_spans > 0, "1029 prefillers owed at once cannot each have a block of 1030 tokens");
    }

    /// From the start of contention, the steps and the synthetic step time until the waiting
    /// decoder is dispatched, at the cap and without it.
    fn decoder_wait(limit: usize) -> (u32, u64) {
        let mut planner = ServeStepPlanner::new(2, SERVE_STEP_MAX_BYPASS).with_prefill_share(SERVE_PREFILL_SHARE);
        planner.on_admit(0);
        planner.on_admit(1);
        let mut inputs = [
            ServeLaneInput { runnable: true, n_past: 0, pf_end: 30_000, has_pending_decode: false },
            ServeLaneInput { runnable: true, n_past: 128, pf_end: 128, has_pending_decode: true },
        ];
        let (mut steps, mut waited_us) = (0, 0);
        loop {
            let (plan, _) = planner.plan_with_prefill_limit(&inputs, CHUNK, 64, limit);
            match plan.unwrap() {
                ServeStepPlan::Decode(lanes) => {
                    assert_eq!(lanes, [1]);
                    return (steps, waited_us);
                }
                ServeStepPlan::Prefill(spans) => {
                    let tokens: usize = spans.iter().map(|&(_, _, c)| c).sum();
                    for (i, _, c) in spans {
                        inputs[i].n_past += c;
                    }
                    let us = tokens as u64 * PREFILL_US_PER_TOKEN;
                    charge(&mut planner, std::time::Duration::from_micros(us));
                    planner.complete_step();
                    steps += 1;
                    waited_us += us;
                    assert!(steps <= SERVE_STEP_MAX_BYPASS, "decoder bypassed past W");
                }
            }
        }
    }

    /// A planner where the share prefers decode (credit < 0) and the prefiller has been
    /// bypassed W steps, so the next plan is prefill forced by the ceiling against the share.
    /// Built with no cap, so both arms of the witness start from identical state.
    fn at_the_bypass_ceiling() -> (ServeStepPlanner, [ServeLaneInput; 2]) {
        let mut planner = ServeStepPlanner::new(2, SERVE_STEP_MAX_BYPASS).with_prefill_share(SERVE_PREFILL_SHARE);
        planner.on_admit(0);
        planner.on_admit(1);
        let mut inputs = [
            ServeLaneInput { runnable: true, n_past: 0, pf_end: 30_000, has_pending_decode: false },
            ServeLaneInput { runnable: true, n_past: 128, pf_end: 128, has_pending_decode: true },
        ];
        // One share-selected prefill step charged at the 4 s limit drives the credit far below 0.
        let (plan, _) = planner.plan_with_prefill_limit(&inputs, CHUNK, 64, usize::MAX);
        let ServeStepPlan::Prefill(spans) = plan.unwrap() else { panic!("share starts at 0: prefill first") };
        for (i, _, c) in spans {
            inputs[i].n_past += c;
        }
        charge(&mut planner, std::time::Duration::from_micros(crate::scheduler::SHARE_CHARGE_CAP_US));
        planner.complete_step();
        // Then decode W times: each step bypasses the prefiller, and 10 ms steps don't repay the credit.
        for _ in 0..SERVE_STEP_MAX_BYPASS {
            let (plan, _) = planner.plan_with_prefill_limit(&inputs, CHUNK, 64, usize::MAX);
            assert_eq!(plan, Some(ServeStepPlan::Decode(vec![1])));
            charge(&mut planner, std::time::Duration::from_micros(DECODE_STEP_US));
            planner.complete_step();
        }
        assert!(planner.credit() < 0, "the share still prefers decode");
        assert_eq!(planner.wait_ticks(0), SERVE_STEP_MAX_BYPASS, "the prefiller is at the ceiling");
        assert_eq!(planner.wait_ticks(1), 0);
        (planner, inputs)
    }

    /// The witness: the ceiling forces prefill against the share's preference, and the cap
    /// shortens that forced step exactly as it shortens a share-selected one.
    #[test]
    fn prefill_cap_bounds_a_step_the_bypass_ceiling_forced() {
        let mut sizes = Vec::new();
        for limit in [CAP, usize::MAX] {
            let (mut planner, inputs) = at_the_bypass_ceiling();
            let forced_before = planner.share_stats().forced_prefill_steps;
            let (plan, effective) = planner.plan_with_prefill_limit(&inputs, CHUNK, 64, limit);
            let plan = plan.unwrap();
            assert!(matches!(plan, ServeStepPlan::Prefill(_)), "the ceiling forces prefill: {plan:?}");
            assert_eq!(planner.pending(), Some(crate::scheduler::StepClass::Prefill));
            let tokens = prefill_tokens(&plan);
            charge(&mut planner, std::time::Duration::from_micros(tokens as u64 * PREFILL_US_PER_TOKEN));
            assert_eq!(planner.share_stats().forced_prefill_steps, forced_before + 1, "counted as forced against the share");
            sizes.push((limit, tokens, effective));
        }
        assert_eq!(sizes, [(CAP, CAP, CAP), (usize::MAX, CHUNK, CHUNK)]);
    }

    #[test]
    fn prefill_cap_shortens_the_decoders_wait_not_its_step_count() {
        let (capped_steps, capped_us) = decoder_wait(CAP);
        let (open_steps, open_us) = decoder_wait(usize::MAX);
        // The share decides how many prefill steps go first; the cap only makes each one shorter.
        assert_eq!(capped_steps, open_steps);
        assert_eq!(capped_steps, 1);
        assert_eq!(capped_us, CAP as u64 * PREFILL_US_PER_TOKEN);
        assert_eq!(open_us, CHUNK as u64 * PREFILL_US_PER_TOKEN);
        assert!(capped_us < open_us);
    }

    /// The launch option stays off until a cap is passed through `plan`.
    #[test]
    fn prefill_step_cap_option_is_off_until_set() {
        let prefill = ServeLaneInput { runnable: true, n_past: 0, pf_end: 16384, has_pending_decode: false };
        let decode = ServeLaneInput { runnable: true, n_past: 128, pf_end: 128, has_pending_decode: true };
        let inputs = [prefill, decode];
        for (cap, want) in [(None, CHUNK), (Some(CAP), CAP)] {
            let mut planner = ServeStepPlanner::new(2, SERVE_STEP_MAX_BYPASS).with_prefill_share(SERVE_PREFILL_SHARE);
            planner.on_admit(0);
            planner.on_admit(1);
            let plan = plan(&mut planner, &inputs, CHUNK, 64, cap).expect("both classes wait, so a step is planned");
            assert!(matches!(plan, ServeStepPlan::Prefill(_)), "share starts at 0, so prefill goes first: {cap:?} {plan:?}");
            assert_eq!(prefill_tokens(&plan), want, "{cap:?}");
        }
    }

    /// Several prefill lanes at the bypass ceiling used to split the step as one large
    /// span, one unaligned remainder, and then a 1-token span per remaining lane. Those
    /// slivers reset `wait_ticks` and leave the lane off a 64-token boundary. While every
    /// lane at the ceiling can have a block, each gets whole blocks and none a sliver: at the
    /// full chunk and at the 1024 contended cap.
    #[test]
    fn prefill_ceiling_split_does_not_emit_one_token_slivers() {
        // (step budget, cap, prefill lanes). The cap is contended by the decoder.
        for (step_budget, limit, n_prefill) in [(4096, usize::MAX, 64), (4096, usize::MAX, 40), (4096, 1024, 16)] {
            let spans = ceiling_split(step_budget, limit, n_prefill);
            assert_eq!(spans.len(), n_prefill, "limit {limit}: every lane at the ceiling is served, got {spans:?}");
            for &(lane, pos, t) in &spans {
                assert_eq!(pos, 0);
                assert!(t >= 64 && t % 64 == 0, "lane {lane} sliver t={t} limit {limit}");
                assert_eq!((pos + t) % 64, 0, "lane {lane} ends off a block");
            }
            let served: Vec<usize> = spans.iter().map(|s| s.0).collect();
            let want: Vec<usize> = (1..=n_prefill).collect();
            assert_eq!(served, want, "FIFO by wait, then lane index, limit {limit}");
        }
    }

    /// The prefill step the ceiling forces at W = 2 once `n_prefill` prefillers and one decoder
    /// have waited through two decode steps.
    fn ceiling_split(step_budget: usize, limit: usize, n_prefill: usize) -> Vec<(usize, usize, usize)> {
        let w = 2u32;
        let n = n_prefill + 1;
        let mut planner = ServeStepPlanner::new(n, w);
        for i in 0..n {
            planner.on_admit(i);
        }
        let mut inputs = vec![ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 20, has_pending_decode: false }; n];
        inputs[0] = ServeLaneInput { runnable: true, n_past: 64, pf_end: 64, has_pending_decode: true };
        for _ in 0..w {
            let plan = planner.plan_with_prefill_limit(&inputs, step_budget, 64, usize::MAX).0.unwrap();
            assert!(matches!(plan, ServeStepPlan::Decode(_)), "aging should decode, limit {limit}: {plan:?}");
            inputs[0].n_past += 1;
            inputs[0].pf_end += 1;
            planner.complete_step();
        }
        let (plan, _) = planner.plan_with_prefill_limit(&inputs, step_budget, 64, limit);
        let ServeStepPlan::Prefill(spans) = plan.unwrap() else { panic!("ceiling forces prefill, limit {limit}") };
        spans
    }

    /// More lanes at the ceiling than the step has blocks. c2a26ce served budget/64 of them and
    /// passed the rest over a W + 1st time. Every one is owed a span now: blocks go out oldest
    /// first while a token stays for each lane behind, and the lanes without a block share what
    /// is left, one token at least. The total is the budget.
    #[test]
    fn prefill_ceiling_split_serves_every_lane_when_the_blocks_run_out() {
        // (step budget, cap, prefill lanes, lanes with a block, the next lane's span).
        // 63 * 64 + 48 + 16 = 4096 and 15 * 64 + 40 + 24 = 1024.
        for (step_budget, limit, n_prefill, blocks, part) in [(4096, usize::MAX, 80, 63, 48), (4096, 1024, 40, 15, 40)] {
            let spans = ceiling_split(step_budget, limit, n_prefill);
            let served: Vec<usize> = spans.iter().map(|s| s.0).collect();
            assert_eq!(served, (1..=n_prefill).collect::<Vec<_>>(), "limit {limit}: every lane at the ceiling, oldest first");
            let sizes: Vec<usize> = spans.iter().map(|s| s.2).collect();
            let mut want = vec![64; blocks];
            want.push(part);
            want.resize(n_prefill, 1);
            assert_eq!(sizes, want, "limit {limit}");
            assert_eq!(sizes.iter().sum::<usize>(), step_budget.min(limit));
        }
    }

    /// More ready prefills than budget/64: the later lanes wait, keep their order, and
    /// are the first spans of the next prefill step.
    #[test]
    fn prefill_slots_above_budget_over_align_wait_and_are_served_next() {
        let n = 70;
        let mut planner = ServeStepPlanner::new(n, 16);
        for i in 0..n {
            planner.on_admit(i);
        }
        let mut inputs = vec![ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 20, has_pending_decode: false }; n];
        let (plan, _) = planner.plan_with_prefill_limit(&inputs, 4096, 64, usize::MAX);
        let ServeStepPlan::Prefill(spans) = plan.unwrap() else { panic!("only prefill is runnable") };
        assert_eq!(spans.len(), 64, "{spans:?}");
        assert_eq!(spans.iter().map(|s| s.0).collect::<Vec<_>>(), (0..64).collect::<Vec<_>>());
        for &(i, _, t) in &spans {
            assert!(t >= 64 && t % 64 == 0, "lane {i} t={t}");
            inputs[i].n_past += t;
        }
        planner.complete_step();
        for i in 64..n {
            assert_eq!(planner.wait_ticks(i), 1, "lane {i} waited");
        }
        for i in 0..64 {
            assert_eq!(planner.wait_ticks(i), 0, "lane {i} was served");
        }
        let (plan, _) = planner.plan_with_prefill_limit(&inputs, 4096, 64, usize::MAX);
        let ServeStepPlan::Prefill(spans) = plan.unwrap() else { panic!("the waiters are still prefilling") };
        let served: Vec<usize> = spans.iter().map(|s| s.0).take(6).collect();
        assert_eq!(served, (64..n).collect::<Vec<_>>(), "the six that waited go first: {spans:?}");
        assert!(spans.iter().all(|&(_, _, t)| t >= 64 && t % 64 == 0));
    }

    /// A lane with fewer than 64 tokens left finishes that tail. The ceiling split must
    /// not turn the tail into a 1-token span while every lane at the ceiling can have a whole
    /// span: 20 lanes at 4096, and 16 at the 1024 cap (15 blocks and the 20-token tail).
    #[test]
    fn prefill_short_tail_finishes_instead_of_a_sliver() {
        for (limit, n_prefill) in [(usize::MAX, 20), (1024, 16)] {
            let w = 2u32;
            let n = n_prefill + 1;
            let tail = n - 1;
            let mut planner = ServeStepPlanner::new(n, w);
            for i in 0..n {
                planner.on_admit(i);
            }
            let mut inputs = vec![ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 20, has_pending_decode: false }; n];
            inputs[0] = ServeLaneInput { runnable: true, n_past: 64, pf_end: 64, has_pending_decode: true };
            inputs[tail].pf_end = 20;
            for _ in 0..w {
                let plan = planner.plan_with_prefill_limit(&inputs, 4096, 64, usize::MAX).0.unwrap();
                assert!(matches!(plan, ServeStepPlan::Decode(_)), "{plan:?}");
                inputs[0].n_past += 1;
                inputs[0].pf_end += 1;
                planner.complete_step();
            }
            let mut steps = 0;
            while inputs[tail].n_past < inputs[tail].pf_end {
                steps += 1;
                assert!(steps <= 8, "tail starved, limit {limit}");
                let plan = planner.plan_with_prefill_limit(&inputs, 4096, 64, limit).0.unwrap();
                match plan {
                    ServeStepPlan::Decode(_) => {
                        inputs[0].n_past += 1;
                        inputs[0].pf_end += 1;
                    }
                    ServeStepPlan::Prefill(spans) => {
                        for &(i, pos, t) in &spans {
                            assert_eq!(inputs[i].n_past, pos);
                            assert_ne!(t, 1, "sliver on lane {i}, limit {limit}: {spans:?}");
                            if i == tail {
                                assert_eq!(t, inputs[tail].pf_end - inputs[tail].n_past, "tail finishes");
                            }
                            inputs[i].n_past += t;
                        }
                    }
                }
                planner.complete_step();
            }
            assert_eq!(inputs[tail].n_past, 20, "limit {limit}");
        }
    }

    /// A lane whose position is inside a block aligns up to the next 64-token boundary
    /// and does not run past it. The following step, now on a boundary, takes full blocks.
    #[test]
    fn prefill_mid_block_start_aligns_to_the_next_boundary() {
        for budget in [200usize, 4096] {
            let mut planner = ServeStepPlanner::new(1, 16);
            planner.on_admit(0);
            let mut input = [ServeLaneInput { runnable: true, n_past: 20, pf_end: 8_000, has_pending_decode: false }];
            let (plan, _) = planner.plan_with_prefill_limit(&input, budget, 64, usize::MAX);
            let ServeStepPlan::Prefill(spans) = plan.unwrap() else { panic!("{budget}") };
            assert_eq!(spans, vec![(0, 20, 44)], "budget {budget}: up to 64, not past it, got {spans:?}");
            input[0].n_past = 64;
            planner.complete_step();
            let (plan, _) = planner.plan_with_prefill_limit(&input, budget, 64, usize::MAX);
            let ServeStepPlan::Prefill(spans) = plan.unwrap() else { panic!("{budget}") };
            let t = spans[0].2;
            assert_eq!(spans[0].1, 64);
            assert!(t >= 64 && t % 64 == 0 && t <= budget, "budget {budget}: next step is whole blocks, t={t}");
            assert_eq!((64 + t) % 64, 0);
        }
    }
}