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
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
//! Per-request scheduler fairness for the traffic record (`response.sched`).
//!
//! Times are milliseconds on one caller-supplied epoch clock. The record is keyed by the request
//! ordinal (`req`, the same value as the job sequence Aurora uses). A lane slot is reused, so it
//! is not an identity. Numbers only: counts, durations, and null when a value was never observed.

use serde_json::{json, Value};

/// What the request was waiting on. Queue is admission, before the lane is runnable.
pub(crate) const PHASE_QUEUE: u8 = 0;
pub(crate) const PHASE_PREFILL: u8 = 1;
pub(crate) const PHASE_DECODE: u8 = 2;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Phase {
    Queue,
    Prefill,
    Decode,
}

impl Phase {
    pub(crate) fn name(self) -> &'static str {
        match self {
            Phase::Queue => "queue",
            Phase::Prefill => "prefill",
            Phase::Decode => "decode",
        }
    }

    fn code(self) -> u8 {
        match self {
            Phase::Queue => PHASE_QUEUE,
            Phase::Prefill => PHASE_PREFILL,
            Phase::Decode => PHASE_DECODE,
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct OpenWait {
    kind: Phase,
    since: u64,
}

/// One request's fairness counters. The clock is an argument so a test can step it.
#[derive(Clone, Debug)]
pub(crate) struct RequestSched {
    req: u64,
    lane: Option<usize>,
    align: usize,
    arrived_ms: Option<u64>,
    admitted: bool,
    queue_ms: u64,
    phase: Phase,
    pos: usize,
    end: usize,
    first_runnable: Option<u64>,
    first_dispatch: Option<u64>,
    first_output: Option<u64>,
    terminal: Option<u64>,
    open: Option<OpenWait>,
    prefill_unscheduled_ms: u64,
    decode_unscheduled_ms: u64,
    prefill_wait_max_ms: u64,
    decode_wait_max_ms: u64,
    prefill_skips: u64,
    decode_skips: u64,
    /// Running prefill-span aggregates. The mean is derived at snapshot time.
    span_count: u64,
    span_sum: u64,
    span_min: Option<u64>,
    span_max: Option<u64>,
    span_short: u64,
    computed: u64,
    in_flight: Option<usize>,
    output_enqueued: u64,
    censored: bool,
}

impl Default for RequestSched {
    fn default() -> Self {
        Self::unbound()
    }
}

impl RequestSched {
    pub(crate) fn unbound() -> Self {
        Self {
            req: 0,
            lane: None,
            align: crate::blocks::BLOCK,
            arrived_ms: None,
            admitted: false,
            queue_ms: 0,
            phase: Phase::Queue,
            pos: 0,
            end: 0,
            first_runnable: None,
            first_dispatch: None,
            first_output: None,
            terminal: None,
            open: None,
            prefill_unscheduled_ms: 0,
            decode_unscheduled_ms: 0,
            prefill_wait_max_ms: 0,
            decode_wait_max_ms: 0,
            prefill_skips: 0,
            decode_skips: 0,
            span_count: 0,
            span_sum: 0,
            span_min: None,
            span_max: None,
            span_short: 0,
            computed: 0,
            in_flight: None,
            output_enqueued: 0,
            censored: false,
        }
    }

    /// The request ordinal, its lane once admitted, and the open wait (kind and start), for the
    /// dispatch trace (`INK_DISPATCH_TRACE`) to log every change to what `close_wait` will book.
    pub(crate) fn trace_key(&self) -> (u64, Option<usize>, Option<(Phase, u64)>) {
        (self.req, self.lane, self.open.map(|o| (o.kind, o.since)))
    }

    pub(crate) fn started(&self) -> bool {
        self.arrived_ms.is_some()
    }

    pub(crate) fn arrive(&mut self, req: u64, now: u64) {
        if self.arrived_ms.is_some() {
            return;
        }
        self.req = req;
        self.arrived_ms = Some(now);
        self.phase = Phase::Queue;
    }

    /// Admission. Closes queue time. Does not start the runnable wait (lane prep is still ahead).
    /// A request serve preempted under pool pressure is admitted again later, perhaps on another lane: only
    /// the lane changes then, and `queue_ms` stays the wait before its first admission.
    pub(crate) fn admit(&mut self, lane: usize, now: u64) {
        if self.terminal.is_some() {
            return;
        }
        if self.admitted {
            self.lane = Some(lane);
            return;
        }
        self.admitted = true;
        self.lane = Some(lane);
        if let Some(arrived) = self.arrived_ms {
            self.queue_ms = now.saturating_sub(arrived);
        }
    }

    /// The lane can take a prefill or decode span. Opens the runnable wait.
    pub(crate) fn mark_runnable(&mut self, phase: Phase, pos: usize, end: usize, now: u64) {
        if self.terminal.is_some() {
            return;
        }
        if self.first_runnable.is_none() {
            self.first_runnable = Some(now);
        }
        self.phase = phase;
        self.pos = pos;
        self.end = end;
        if self.open.is_none() {
            self.open = Some(OpenWait { kind: phase, since: now });
        }
    }

    /// A step passed this runnable request over. The wait stays open, so the skips are one stretch.
    pub(crate) fn skip(&mut self, _now: u64) {
        if self.terminal.is_some() || self.in_flight.is_some() {
            return;
        }
        let Some(open) = self.open else { return };
        match open.kind {
            Phase::Prefill => self.prefill_skips = self.prefill_skips.saturating_add(1),
            Phase::Decode => self.decode_skips = self.decode_skips.saturating_add(1),
            Phase::Queue => {}
        }
    }

    /// The step gave this request a span. Closes the runnable wait. A prefill span is remembered
    /// until its rows are committed or the request is cancelled.
    pub(crate) fn dispatch(&mut self, phase: Phase, tokens: usize, is_tail: bool, now: u64) {
        if self.terminal.is_some() || tokens == 0 {
            return;
        }
        self.phase = phase;
        self.close_wait(now, false);
        if self.first_dispatch.is_none() {
            self.first_dispatch = Some(now);
        }
        if phase == Phase::Prefill {
            let n = tokens as u64;
            self.span_count = self.span_count.saturating_add(1);
            self.span_sum = self.span_sum.saturating_add(n);
            self.span_min = Some(self.span_min.map_or(n, |m| m.min(n)));
            self.span_max = Some(self.span_max.map_or(n, |m| m.max(n)));
            if tokens < self.align && !is_tail {
                self.span_short = self.span_short.saturating_add(1);
            }
            self.in_flight = Some(tokens);
        }
    }

    /// The prefill span's rows were computed. Books them once. If prompt remains, the next wait opens.
    /// After a terminal timestamp, a late success books the outstanding span once and does not
    /// move that timestamp or reopen a wait. A second commit finds nothing in flight.
    pub(crate) fn commit_prefill(&mut self, tokens: usize, pos: usize, now: u64) {
        if self.terminal.is_some() {
            if self.in_flight.take().is_some() {
                self.computed = self.computed.saturating_add(tokens as u64);
            }
            return;
        }
        self.pos = pos;
        if self.in_flight.take().is_some() {
            self.computed = self.computed.saturating_add(tokens as u64);
        }
        if pos < self.end {
            self.phase = Phase::Prefill;
            self.open = Some(OpenWait { kind: Phase::Prefill, since: now });
        } else {
            self.phase = Phase::Decode;
            self.open = Some(OpenWait { kind: Phase::Decode, since: now });
        }
    }

    /// A decode step finished. The next decode wait opens. Prefill totals are left alone.
    pub(crate) fn commit_decode(&mut self, pos: usize, now: u64) {
        if self.terminal.is_some() {
            return;
        }
        self.pos = pos;
        self.phase = Phase::Decode;
        self.in_flight = None;
        self.open = Some(OpenWait { kind: Phase::Decode, since: now });
    }

    pub(crate) fn enqueue_output(&mut self, n: u64, now: u64) {
        if self.terminal.is_some() || n == 0 {
            return;
        }
        if self.first_output.is_none() {
            self.first_output = Some(now);
        }
        self.output_enqueued = self.output_enqueued.saturating_add(n);
    }

    /// Client gone or the lane dropped the request. An open wait is closed and marked censored.
    /// An in-flight prefill span stays outstanding: its rows are not computed without a successful
    /// completion. The terminal timestamp is this instant.
    pub(crate) fn cancel(&mut self, phase: Phase, pos: usize, end: usize, now: u64) {
        if self.terminal.is_some() {
            return;
        }
        if !self.admitted {
            if let Some(arrived) = self.arrived_ms {
                self.queue_ms = now.saturating_sub(arrived);
            }
        }
        self.phase = phase;
        self.pos = pos;
        self.end = end;
        self.close_wait(now, true);
        self.terminal = Some(now);
    }

    /// Cancel using the phase and position already stored (the connection thread does not own the lane).
    pub(crate) fn cancel_open(&mut self, now: u64) {
        let phase = self.phase;
        let pos = self.pos;
        let end = self.end;
        self.cancel(phase, pos, end, now);
    }

    /// The request finished without a cancel. An open wait closes, and it is not censored.
    pub(crate) fn finish(&mut self, now: u64) {
        if self.terminal.is_some() {
            return;
        }
        self.close_wait(now, false);
        self.terminal = Some(now);
    }

    /// The stream ended without Done and without a client cancel. The open wait closes
    /// without the censor flag. An in-flight span stays outstanding, the same as cancel.
    pub(crate) fn seal(&mut self, now: u64) {
        if self.terminal.is_some() {
            return;
        }
        if !self.admitted {
            if let Some(arrived) = self.arrived_ms {
                self.queue_ms = now.saturating_sub(arrived);
            }
        }
        self.close_wait(now, false);
        self.terminal = Some(now);
    }

    /// The in-flight prefill span failed. Those rows are not computed. Idempotent.
    /// Does not move a terminal timestamp.
    pub(crate) fn fail_inflight(&mut self) {
        self.in_flight = None;
    }

    /// The lane stopped being runnable. Closes the open wait without a skip and without censoring,
    /// so the blocked stretch is not runnable-unscheduled time.
    pub(crate) fn block(&mut self, now: u64) {
        if self.terminal.is_some() {
            return;
        }
        self.close_wait(now, false);
    }

    /// Opens a wait that backpressure or deferral had closed, without resetting one that is already open.
    /// No-op while a span is in flight or the request is terminal.
    pub(crate) fn reopen_if_idle(&mut self, phase: Phase, pos: usize, end: usize, now: u64) {
        if self.terminal.is_some() || self.in_flight.is_some() || self.open.is_some() {
            return;
        }
        self.mark_runnable(phase, pos, end, now);
    }

    fn close_wait(&mut self, now: u64, censor: bool) {
        let Some(open) = self.open.take() else { return };
        let dt = now.saturating_sub(open.since);
        match open.kind {
            Phase::Prefill => {
                self.prefill_unscheduled_ms = self.prefill_unscheduled_ms.saturating_add(dt);
                self.prefill_wait_max_ms = self.prefill_wait_max_ms.max(dt);
            }
            Phase::Decode => {
                self.decode_unscheduled_ms = self.decode_unscheduled_ms.saturating_add(dt);
                self.decode_wait_max_ms = self.decode_wait_max_ms.max(dt);
            }
            Phase::Queue => {}
        }
        if censor {
            self.censored = true;
        }
    }

    pub(crate) fn snapshot(&self) -> SchedSnapshot {
        let steps = self.span_count;
        let dispatched = self.span_sum;
        let short = self.span_short;
        let (min, max, mean) = if steps == 0 {
            (None, None, None)
        } else {
            let mean = dispatched as f64 / steps as f64;
            (self.span_min, self.span_max, Some(mean))
        };
        let computed = if self.in_flight.is_some() { None } else { Some(self.computed) };
        SchedSnapshot {
            req: self.req,
            lane: self.lane,
            queue_ms: self.queue_ms,
            runnable_unscheduled_ms: self.prefill_unscheduled_ms,
            decode_unscheduled_ms: self.decode_unscheduled_ms,
            prefill_wait_max_ms: self.prefill_wait_max_ms,
            decode_wait_max_ms: self.decode_wait_max_ms,
            prefill_skips: self.prefill_skips,
            decode_skips: self.decode_skips,
            t_runnable_ms: self.first_runnable,
            t_dispatch_ms: self.first_dispatch,
            t_output_ms: self.first_output,
            t_terminal_ms: self.terminal,
            prefill_steps: steps,
            prefill_tokens_min: min,
            prefill_tokens_mean: mean,
            prefill_tokens_max: max,
            prefill_short_nontail: short,
            prefill_tokens_dispatched: dispatched,
            prefill_tokens_computed: computed,
            censored: u64::from(self.censored),
            phase: u64::from(self.phase.code()),
            prefill_pos: self.pos as u64,
            prefill_end: self.end as u64,
            output_enqueued: self.output_enqueued,
        }
    }
}

/// Numbers copied onto `response.sched`. Absent clocks and an unknown min/mean/max are null.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct SchedSnapshot {
    pub(crate) req: u64,
    pub(crate) lane: Option<usize>,
    pub(crate) queue_ms: u64,
    pub(crate) runnable_unscheduled_ms: u64,
    pub(crate) decode_unscheduled_ms: u64,
    pub(crate) prefill_wait_max_ms: u64,
    pub(crate) decode_wait_max_ms: u64,
    pub(crate) prefill_skips: u64,
    pub(crate) decode_skips: u64,
    pub(crate) t_runnable_ms: Option<u64>,
    pub(crate) t_dispatch_ms: Option<u64>,
    pub(crate) t_output_ms: Option<u64>,
    pub(crate) t_terminal_ms: Option<u64>,
    pub(crate) prefill_steps: u64,
    pub(crate) prefill_tokens_min: Option<u64>,
    pub(crate) prefill_tokens_mean: Option<f64>,
    pub(crate) prefill_tokens_max: Option<u64>,
    pub(crate) prefill_short_nontail: u64,
    pub(crate) prefill_tokens_dispatched: u64,
    pub(crate) prefill_tokens_computed: Option<u64>,
    pub(crate) censored: u64,
    pub(crate) phase: u64,
    pub(crate) prefill_pos: u64,
    pub(crate) prefill_end: u64,
    pub(crate) output_enqueued: u64,
}

fn opt_u64(v: Option<&Value>, key: &str) -> Result<Option<u64>, String> {
    match v {
        None | Some(Value::Null) => Ok(None),
        Some(v) => v.as_u64().map(Some).ok_or_else(|| format!("response.sched.{key} is not a number")),
    }
}

fn req_u64(obj: &serde_json::Map<String, Value>, key: &str) -> Result<u64, String> {
    obj.get(key).and_then(|v| v.as_u64()).ok_or_else(|| format!("response.sched.{key} missing"))
}

impl SchedSnapshot {
    pub(crate) fn to_json(&self) -> Value {
        let opt = |n: Option<u64>| match n {
            Some(n) => json!(n),
            None => Value::Null,
        };
        json!({
            "req": self.req,
            "lane": self.lane.map(|n| n as u64),
            "queue_ms": self.queue_ms,
            "runnable_unscheduled_ms": self.runnable_unscheduled_ms,
            "decode_unscheduled_ms": self.decode_unscheduled_ms,
            "prefill_wait_max_ms": self.prefill_wait_max_ms,
            "decode_wait_max_ms": self.decode_wait_max_ms,
            "prefill_skips": self.prefill_skips,
            "decode_skips": self.decode_skips,
            "t_runnable_ms": opt(self.t_runnable_ms),
            "t_dispatch_ms": opt(self.t_dispatch_ms),
            "t_output_ms": opt(self.t_output_ms),
            "t_terminal_ms": opt(self.t_terminal_ms),
            "prefill_steps": self.prefill_steps,
            "prefill_tokens_min": opt(self.prefill_tokens_min),
            "prefill_tokens_mean": self.prefill_tokens_mean.map(|n| json!(n)).unwrap_or(Value::Null),
            "prefill_tokens_max": opt(self.prefill_tokens_max),
            "prefill_short_nontail": self.prefill_short_nontail,
            "prefill_tokens_dispatched": self.prefill_tokens_dispatched,
            "prefill_tokens_computed": opt(self.prefill_tokens_computed),
            "censored": self.censored,
            "phase": self.phase,
            "prefill_pos": self.prefill_pos,
            "prefill_end": self.prefill_end,
            "output_enqueued": self.output_enqueued,
        })
    }

    pub(crate) fn from_json(v: &Value) -> Result<Self, String> {
        let obj = v.as_object().ok_or("response.sched must be an object")?;
        let mean = match obj.get("prefill_tokens_mean") {
            None | Some(Value::Null) => None,
            Some(v) => Some(v.as_f64().ok_or("response.sched.prefill_tokens_mean is not a number")?),
        };
        let lane = match obj.get("lane") {
            None | Some(Value::Null) => None,
            Some(v) => Some(
                usize::try_from(v.as_u64().ok_or("response.sched.lane is not a number")?)
                    .map_err(|_| "response.sched.lane is not a lane index".to_string())?,
            ),
        };
        Ok(Self {
            req: req_u64(obj, "req")?,
            lane,
            queue_ms: req_u64(obj, "queue_ms")?,
            runnable_unscheduled_ms: req_u64(obj, "runnable_unscheduled_ms")?,
            decode_unscheduled_ms: req_u64(obj, "decode_unscheduled_ms")?,
            prefill_wait_max_ms: req_u64(obj, "prefill_wait_max_ms")?,
            decode_wait_max_ms: req_u64(obj, "decode_wait_max_ms")?,
            prefill_skips: req_u64(obj, "prefill_skips")?,
            decode_skips: req_u64(obj, "decode_skips")?,
            t_runnable_ms: opt_u64(obj.get("t_runnable_ms"), "t_runnable_ms")?,
            t_dispatch_ms: opt_u64(obj.get("t_dispatch_ms"), "t_dispatch_ms")?,
            t_output_ms: opt_u64(obj.get("t_output_ms"), "t_output_ms")?,
            t_terminal_ms: opt_u64(obj.get("t_terminal_ms"), "t_terminal_ms")?,
            prefill_steps: req_u64(obj, "prefill_steps")?,
            prefill_tokens_min: opt_u64(obj.get("prefill_tokens_min"), "prefill_tokens_min")?,
            prefill_tokens_mean: mean,
            prefill_tokens_max: opt_u64(obj.get("prefill_tokens_max"), "prefill_tokens_max")?,
            prefill_short_nontail: req_u64(obj, "prefill_short_nontail")?,
            prefill_tokens_dispatched: req_u64(obj, "prefill_tokens_dispatched")?,
            prefill_tokens_computed: opt_u64(obj.get("prefill_tokens_computed"), "prefill_tokens_computed")?,
            censored: req_u64(obj, "censored")?,
            phase: req_u64(obj, "phase")?,
            prefill_pos: req_u64(obj, "prefill_pos")?,
            prefill_end: req_u64(obj, "prefill_end")?,
            output_enqueued: req_u64(obj, "output_enqueued")?,
        })
    }
}

/// What one launched row should record. `prefill_span` and `in_decode` are the rows that
/// actually ran. A planned row that was filtered out is a skip. A decode-plan row that still
/// has prompt left is one prefill token.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LaneNote {
    Prefill { tokens: usize, tail: bool },
    Decode,
    Skip,
}

pub(crate) fn note_for_lane(
    n_past: usize,
    pf_end: usize,
    prefill_span: Option<(usize, usize)>,
    in_decode: bool,
) -> LaneNote {
    if let Some((p0, tokens)) = prefill_span {
        let tail = pf_end > 0 && p0.saturating_add(tokens) >= pf_end;
        return LaneNote::Prefill { tokens, tail };
    }
    if in_decode && n_past < pf_end {
        let tail = pf_end > 0 && n_past.saturating_add(1) >= pf_end;
        return LaneNote::Prefill { tokens: 1, tail };
    }
    if in_decode {
        return LaneNote::Decode;
    }
    LaneNote::Skip
}

#[cfg(test)]
fn numbers_only(v: &Value) {
    match v {
        Value::Null | Value::Number(_) => {}
        Value::Object(map) => {
            for child in map.values() {
                numbers_only(child);
            }
        }
        Value::Array(items) => {
            for child in items {
                numbers_only(child);
            }
        }
        other => panic!("response.sched holds a non-number: {other}"),
    }
}

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

    /// Delayed admission, two skips as one prefill wait, a finished span plus a short in-flight span,
    /// then cancel. A second request reuses the lane, is never dispatched, and does not touch the first.
    #[test]
    fn fairness_delayed_admit_two_skips_partial_cancel() {
        let mut a = RequestSched::unbound();
        a.arrive(4, 5_000_000);
        a.admit(1, 5_000_500);
        a.mark_runnable(Phase::Prefill, 0, 400, 5_000_560);
        a.skip(5_000_700);
        a.skip(5_000_900);
        a.dispatch(Phase::Prefill, 64, false, 5_001_000);
        a.commit_prefill(64, 64, 5_001_050);
        a.enqueue_output(2, 5_001_080);
        a.dispatch(Phase::Prefill, 16, false, 5_001_100);
        let outstanding = a.snapshot();
        assert_eq!(outstanding.prefill_tokens_dispatched, 80);
        assert_eq!(outstanding.prefill_tokens_computed, None, "in-flight rows are unknown");
        assert!(outstanding.to_json()["prefill_tokens_computed"].is_null());

        a.cancel(Phase::Prefill, 64, 400, 5_001_250);
        let early = a.snapshot();
        assert_eq!(early.prefill_tokens_computed, None, "disconnect does not book the failed span");
        assert_eq!(early.t_terminal_ms, Some(5_001_250));
        assert_eq!(early.prefill_pos, 64);

        let mut late = a.clone();
        a.fail_inflight();
        a.fail_inflight();
        let snap = a.snapshot();
        late.commit_prefill(16, 80, 5_001_300);
        late.commit_prefill(16, 96, 5_001_350);
        late.cancel(Phase::Prefill, 80, 400, 5_001_400);
        let reconciled = late.snapshot();
        assert_eq!(reconciled.prefill_tokens_computed, Some(80), "late success books the span once");
        assert_eq!(reconciled.prefill_tokens_dispatched, 80);
        assert_eq!(reconciled.t_terminal_ms, Some(5_001_250), "reconcile keeps the disconnect time");
        assert_eq!(reconciled.prefill_pos, 64);
        assert_eq!(snap.req, 4, "ordinal, not the lane");
        assert_eq!(snap.lane, Some(1));
        assert_eq!(snap.queue_ms, 500, "admission queue");
        assert_eq!(snap.runnable_unscheduled_ms, 490, "ready for prefill but not in a span");
        assert_ne!(snap.queue_ms, snap.runnable_unscheduled_ms);
        assert_eq!(snap.prefill_skips, 2);
        assert_eq!(snap.prefill_wait_max_ms, 440, "both skips are one uninterrupted wait");
        assert!(snap.prefill_wait_max_ms > 50, "the later 50 ms wait is shorter");
        assert_eq!(snap.decode_unscheduled_ms, 0);
        assert_eq!(snap.decode_wait_max_ms, 0);
        assert_eq!(snap.decode_skips, 0);
        assert_eq!(snap.t_runnable_ms, Some(5_000_560));
        assert_eq!(snap.t_dispatch_ms, Some(5_001_000));
        assert_eq!(snap.t_output_ms, Some(5_001_080));
        assert_eq!(snap.t_terminal_ms, Some(5_001_250));
        assert_eq!(snap.prefill_steps, 2);
        assert_eq!(snap.prefill_tokens_dispatched, 80);
        assert_eq!(snap.prefill_tokens_computed, Some(64), "a failed span is not computed");
        assert_eq!(snap.prefill_short_nontail, 1, "16 is short and does not finish the prompt");
        assert_eq!(snap.prefill_tokens_min, Some(16));
        assert_eq!(snap.prefill_tokens_max, Some(64));
        let derived = snap.prefill_tokens_dispatched as f64 / snap.prefill_steps as f64;
        assert_eq!(snap.prefill_tokens_mean, Some(derived));
        assert_eq!(derived, 40.0);
        assert_eq!(snap.censored, 0, "cancel fell during the in-flight span, whose wait had already closed");
        assert_eq!(snap.phase, u64::from(PHASE_PREFILL));
        assert_eq!(snap.prefill_pos, 64);
        assert_eq!(snap.prefill_end, 400);
        assert_eq!(snap.output_enqueued, 2);

        let frozen = snap.clone();
        // Lane 1 is reused by a request that never receives a span.
        let mut b = RequestSched::unbound();
        b.arrive(9, 8_000_000);
        b.admit(1, 8_000_250);
        b.mark_runnable(Phase::Prefill, 0, 128, 8_000_300);
        b.skip(8_000_360);
        b.skip(8_000_420);
        b.cancel(Phase::Prefill, 0, 128, 8_000_500);
        let other = b.snapshot();
        assert_eq!(a.snapshot(), frozen, "the reused lane must not write into request 4");
        assert_eq!(other.req, 9);
        assert_eq!(other.lane, Some(1));
        assert_ne!(other.req, frozen.req);
        assert_eq!(other.queue_ms, 250);
        assert_eq!(other.runnable_unscheduled_ms, 200);
        assert_ne!(other.queue_ms, other.runnable_unscheduled_ms);
        assert_eq!(other.prefill_skips, 2);
        assert_eq!(other.prefill_wait_max_ms, 200);
        assert_eq!(other.prefill_steps, 0);
        assert_eq!(other.prefill_tokens_dispatched, 0);
        assert_eq!(other.prefill_tokens_min, None, "never dispatched: min is unknown");
        assert_eq!(other.prefill_tokens_mean, None);
        assert_eq!(other.prefill_tokens_max, None);
        assert_eq!(other.t_dispatch_ms, None);
        assert_eq!(other.censored, 1, "cancel closed the open prefill wait");
        assert_eq!(other.prefill_pos, 0);
        assert_eq!(other.prefill_end, 128);
        assert_eq!(other.output_enqueued, 0);
        assert_eq!(other.t_runnable_ms, Some(8_000_300));
        assert_eq!(other.t_output_ms, None);
        assert_eq!(other.t_terminal_ms, Some(8_000_500));

        let metrics = ResponseMetrics {
            prompt_tokens: 400,
            completion_tokens: 2,
            ttft_ms: 1,
            total_ms: 2,
            queue_ms: snap.queue_ms,
            prefill_ms: 1,
            decode_ms: 0,
            finish_reason: "cancelled".into(),
            status_code: 499,
            generation_finish_reason: None,
            delivery_status: None,
            reuse: None,
            sched: Some(snap.clone()),
            ..ResponseMetrics::default()
        };
        let body = metrics.to_json();
        numbers_only(&body["sched"]);
        assert_eq!(body["sched"]["req"], 4);
        assert!(body["sched"]["prefill_tokens_min"].is_number());
        let back = ResponseMetrics::from_json(&body).unwrap();
        assert_eq!(back.sched, Some(snap));

        let bare = other.to_json();
        numbers_only(&bare);
        assert!(bare["prefill_tokens_min"].is_null());
        assert_eq!(SchedSnapshot::from_json(&bare).unwrap(), other);
    }

    #[test]
    fn fairness_blocked_interval_is_excluded_from_the_wait() {
        let mut s = RequestSched::unbound();
        s.arrive(1, 0);
        s.admit(0, 0);
        s.mark_runnable(Phase::Prefill, 0, 128, 100);
        s.block(150);
        s.block(400);
        s.mark_runnable(Phase::Prefill, 0, 128, 400);
        s.dispatch(Phase::Prefill, 64, false, 420);
        let snap = s.snapshot();
        assert_eq!(snap.runnable_unscheduled_ms, 70, "50 before the block plus 20 after it");
        assert_eq!(snap.prefill_skips, 0, "a block is not a skip");
        assert_eq!(snap.censored, 0);
        assert_eq!(snap.prefill_wait_max_ms, 50);
    }

    #[test]
    fn fairness_filtered_plan_and_one_prompt_row() {
        assert_eq!(note_for_lane(100, 100, None, false), LaneNote::Skip, "dropped from the launched set");
        assert_eq!(note_for_lane(100, 100, None, true), LaneNote::Decode);
        assert_eq!(
            note_for_lane(10, 11, None, true),
            LaneNote::Prefill { tokens: 1, tail: true },
            "one prompt row on the decode plan is prefill"
        );

        let mut launched = RequestSched::unbound();
        launched.arrive(1, 0);
        launched.admit(0, 0);
        launched.mark_runnable(Phase::Decode, 100, 100, 0);
        match note_for_lane(100, 100, None, true) {
            LaneNote::Decode => launched.dispatch(Phase::Decode, 1, false, 10),
            other => panic!("expected decode, got {other:?}"),
        }
        let mut filtered = RequestSched::unbound();
        filtered.arrive(2, 0);
        filtered.admit(1, 0);
        filtered.mark_runnable(Phase::Decode, 100, 100, 0);
        match note_for_lane(100, 100, None, false) {
            LaneNote::Skip => filtered.skip(10),
            other => panic!("expected skip, got {other:?}"),
        }
        assert_eq!(launched.snapshot().prefill_steps, 0);
        assert_eq!(launched.snapshot().t_dispatch_ms, Some(10));
        assert_eq!(filtered.snapshot().prefill_steps, 0);
        assert_eq!(filtered.snapshot().prefill_tokens_dispatched, 0);
        assert_eq!(filtered.snapshot().decode_skips, 1);
        assert_eq!(filtered.snapshot().t_dispatch_ms, None);

        let mut row = RequestSched::unbound();
        row.arrive(3, 0);
        row.admit(0, 0);
        row.mark_runnable(Phase::Prefill, 10, 11, 0);
        match note_for_lane(10, 11, None, true) {
            LaneNote::Prefill { tokens, tail } => row.dispatch(Phase::Prefill, tokens, tail, 5),
            other => panic!("expected one-row prefill, got {other:?}"),
        }
        row.commit_prefill(1, 11, 6);
        let snap = row.snapshot();
        assert_eq!(snap.prefill_tokens_dispatched, 1);
        assert_eq!(snap.prefill_tokens_computed, Some(1), "commit_prefill sees the in-flight row");
        assert_eq!(snap.prefill_steps, 1);

        let mut missed = RequestSched::unbound();
        missed.arrive(4, 0);
        missed.admit(0, 0);
        missed.mark_runnable(Phase::Prefill, 10, 11, 0);
        missed.dispatch(Phase::Decode, 1, false, 5);
        missed.commit_prefill(1, 11, 6);
        assert_eq!(
            missed.snapshot().prefill_tokens_computed,
            Some(0),
            "a decode dispatch leaves commit_prefill with nothing in flight"
        );
    }

    /// A request serve preempts under pool pressure stops being runnable (`block`), waits in the queue, and is
    /// admitted again on another lane: the queued stretch is not runnable-unscheduled time, nothing is censored,
    /// `queue_ms` stays the wait before the first admission, and later lines carry the new lane.
    #[test]
    fn fairness_preempted_request_is_admitted_again_on_another_lane() {
        let mut r = RequestSched::unbound();
        r.arrive(7, 1_000);
        r.admit(1, 1_040);
        r.mark_runnable(Phase::Decode, 200, 200, 1_050);
        r.dispatch(Phase::Decode, 1, false, 1_060);
        r.commit_decode(201, 1_070);
        // Preempted 30 ms into its next decode wait; 500 ms in the queue; admitted on lane 0.
        r.block(1_100);
        r.admit(0, 1_600);
        assert_eq!(r.trace_key(), (7, Some(0), None));
        r.mark_runnable(Phase::Prefill, 128, 202, 1_610);
        r.dispatch(Phase::Prefill, 74, true, 1_620);
        r.commit_prefill(74, 202, 1_640);
        r.finish(1_650);
        let snap = r.snapshot();
        assert_eq!(snap.lane, Some(0));
        assert_eq!(snap.queue_ms, 40, "the wait before the first admission");
        assert_eq!(snap.decode_unscheduled_ms, 10 + 30 + 10, "the 500 ms in the queue are not booked");
        assert_eq!(snap.runnable_unscheduled_ms, 10, "the one prefill wait on the new lane");
        assert_eq!(snap.censored, 0);
    }
}