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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! Why each ready lane waited at each scheduler step (`INK_DISPATCH_TRACE=1`, an internal diagnostic).
//!
//! Always on: per-reason counters in `/health` (`dispatch_waits`). Every scheduler step that reaches
//! the planner counts its ready lanes, the ones it dispatched, and one reason for each one it did not.
//! `ready == dispatched + sum(skipped)` holds after every step.
//!
//! With `INK_DISPATCH_TRACE=1` (needs `--record-dir`; independent of `INK_REQUEST_FAIRNESS`), compact JSONL goes to
//! `<record-dir>/dispatch-YYYYMMDD.jsonl`: a `start` line, one `step` line per planned step (idle and
//! no-dispatch steps included), a `wait` line at every change to a request's open wait in `response.sched`
//! (the same transitions that book it), `idle` lines around the scheduler's blocking wait for work, and an
//! `end` line. Each line has a gapless `seq`; a dropped line leaves a gap and is counted in `end`. Lines
//! are batched in memory and handed to the recorder's writer thread, so the step loop never writes.
//! The format is in TRACE-FORMAT.md at the repository root.
use crate::scheduler::{LaneState, PlanSkip};
use std::io::Write;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

/// Version of the trace line format. Bump on a renamed or re-meant field.
pub(super) const DISPATCH_TRACE_VERSION: u32 = 1;

/// Hand a batch to the writer once it holds this much.
const FLUSH_BYTES: usize = 64 * 1024;
/// Or once the oldest buffered line is this old.
const FLUSH_US: u64 = 200_000;
/// Past this, lines are dropped (and counted) instead of buffered.
const MAX_BUFFERED_BYTES: usize = 32 * 1024 * 1024;

/// Why a ready lane was not dispatched in a step. Each is one decision point in the code:
/// the serve-side `runnable` gate (in its order), singleflight, the planner's [`PlanSkip`], or the
/// span block allocation after the plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum WaitReason {
    /// Planner state `Admitted` or `Restoring`: the lane's context is still being prepared.
    Restore,
    /// Planner state other than `Ready`, `Admitted` or `Restoring`.
    LaneState,
    /// The client is gone; the lane is released at the next opportunity.
    Cancelled,
    /// Output backpressure: the request's event queue is full (`JobOutput::backpressured`).
    Backpressure,
    /// Deferred by KV pool pressure in an earlier step or stitch (`pool_deferred`).
    PoolDeferred,
    /// An `.ikv` stitch is staging on the background worker.
    IkvStage,
    /// Following another lane's prefill of the same prefix (`find_prefill_leaders`).
    Singleflight,
    /// [`PlanSkip::Share`].
    Share,
    /// [`PlanSkip::Ceiling`].
    Ceiling,
    /// [`PlanSkip::TickPolicy`].
    TickPolicy,
    /// [`PlanSkip::Budget`].
    Budget,
    /// [`PlanSkip::PrefillCap`].
    PrefillCap,
    /// Planned, but its span blocks could not be allocated, so it was deferred.
    PoolExhausted,
    /// Planned, but left out of the dispatch for another reason (a DSpark verify fallback). A span
    /// that fails is failed before the step is noted: its request is gone, so it is not ready.
    Dropped,
}

impl WaitReason {
    pub(super) const ALL: [WaitReason; 14] = [
        WaitReason::Restore,
        WaitReason::LaneState,
        WaitReason::Cancelled,
        WaitReason::Backpressure,
        WaitReason::PoolDeferred,
        WaitReason::IkvStage,
        WaitReason::Singleflight,
        WaitReason::Share,
        WaitReason::Ceiling,
        WaitReason::TickPolicy,
        WaitReason::Budget,
        WaitReason::PrefillCap,
        WaitReason::PoolExhausted,
        WaitReason::Dropped,
    ];

    pub(super) fn name(self) -> &'static str {
        match self {
            WaitReason::Restore => "restore",
            WaitReason::LaneState => "lane_state",
            WaitReason::Cancelled => "cancelled",
            WaitReason::Backpressure => "backpressure",
            WaitReason::PoolDeferred => "pool_deferred",
            WaitReason::IkvStage => "ikv_stage",
            WaitReason::Singleflight => "singleflight",
            WaitReason::Share => "share",
            WaitReason::Ceiling => "ceiling",
            WaitReason::TickPolicy => "tick_policy",
            WaitReason::Budget => "budget",
            WaitReason::PrefillCap => "prefill_cap",
            WaitReason::PoolExhausted => "pool_exhausted",
            WaitReason::Dropped => "dropped",
        }
    }

    fn index(self) -> usize {
        self as usize
    }
}

impl From<PlanSkip> for WaitReason {
    fn from(s: PlanSkip) -> Self {
        match s {
            PlanSkip::Share => WaitReason::Share,
            PlanSkip::Ceiling => WaitReason::Ceiling,
            PlanSkip::TickPolicy => WaitReason::TickPolicy,
            PlanSkip::Budget => WaitReason::Budget,
            PlanSkip::PrefillCap => WaitReason::PrefillCap,
        }
    }
}

/// The serve-side gate in front of the planner: the first condition, in the scheduler's order,
/// that keeps a lane from being runnable this step. `None` is runnable.
pub(super) fn gate(
    state: LaneState,
    cancelled: bool,
    backpressured: bool,
    pool_deferred: bool,
    ikv_stage: bool,
) -> Option<WaitReason> {
    if state != LaneState::Ready {
        return Some(match state {
            LaneState::Admitted | LaneState::Restoring => WaitReason::Restore,
            _ => WaitReason::LaneState,
        });
    }
    if cancelled {
        Some(WaitReason::Cancelled)
    } else if backpressured {
        Some(WaitReason::Backpressure)
    } else if pool_deferred {
        Some(WaitReason::PoolDeferred)
    } else if ikv_stage {
        Some(WaitReason::IkvStage)
    } else {
        None
    }
}

/// A lane with work this step (prefill or decode, whether or not the gate let it run).
#[derive(Clone, Copy, Debug)]
pub(super) struct Ready {
    pub(super) lane: usize,
    pub(super) req: u64,
    /// The gate (or singleflight) that kept it out of the planner's inputs.
    pub(super) gate: Option<WaitReason>,
    /// Its `pool_deferred` flag after the step's span allocation.
    pub(super) pool_deferred_after: bool,
}

/// The reason each ready lane not in `dispatched` waited: its gate, else the planner's skip,
/// else (planned but not dispatched) pool exhaustion or a drop.
pub(super) fn explain(
    ready: &[Ready],
    dispatched: &[usize],
    skips: &[(usize, PlanSkip)],
    out: &mut Vec<(usize, u64, WaitReason)>,
) {
    out.clear();
    for r in ready {
        if dispatched.contains(&r.lane) {
            continue;
        }
        let why = r.gate.unwrap_or_else(|| match skips.iter().find(|s| s.0 == r.lane) {
            Some(&(_, s)) => s.into(),
            None if r.pool_deferred_after => WaitReason::PoolExhausted,
            None => WaitReason::Dropped,
        });
        out.push((r.lane, r.req, why));
    }
}

/// Always-on counters for `/health`.
#[derive(Default)]
pub(super) struct DispatchCounters {
    steps: AtomicU64,
    no_dispatch_steps: AtomicU64,
    ready: AtomicU64,
    dispatched: AtomicU64,
    skipped: [AtomicU64; WaitReason::ALL.len()],
}

impl DispatchCounters {
    pub(super) fn note(&self, ready: usize, dispatched: usize, skipped: &[(usize, u64, WaitReason)]) {
        self.steps.fetch_add(1, Ordering::Relaxed);
        if dispatched == 0 {
            self.no_dispatch_steps.fetch_add(1, Ordering::Relaxed);
        }
        self.ready.fetch_add(ready as u64, Ordering::Relaxed);
        self.dispatched.fetch_add(dispatched as u64, Ordering::Relaxed);
        for &(_, _, why) in skipped {
            self.skipped[why.index()].fetch_add(1, Ordering::Relaxed);
        }
    }

    pub(super) fn steps(&self) -> u64 {
        self.steps.load(Ordering::Relaxed)
    }

    pub(super) fn to_json(&self) -> serde_json::Value {
        let skipped: serde_json::Map<String, serde_json::Value> = WaitReason::ALL
            .iter()
            .map(|r| (r.name().to_string(), self.skipped[r.index()].load(Ordering::Relaxed).into()))
            .collect();
        serde_json::json!({
            "steps": self.steps.load(Ordering::Relaxed),
            "no_dispatch_steps": self.no_dispatch_steps.load(Ordering::Relaxed),
            "ready": self.ready.load(Ordering::Relaxed),
            "dispatched": self.dispatched.load(Ordering::Relaxed),
            "skipped": skipped,
        })
    }
}

struct Buf {
    bytes: Vec<u8>,
    /// Lines in `bytes`.
    batch_lines: u64,
    /// Next line's `seq`; every line takes one, written or dropped.
    seq: u64,
    dropped: u64,
    /// Monotonic µs of the first line in `bytes`.
    oldest_us: Option<u64>,
    ended: bool,
}

/// Where a batch goes: the recorder's writer queue in serve, a vector in tests. `false` drops it.
pub(super) type Sink = Box<dyn Fn(u64, Vec<u8>) -> bool + Send + Sync>;

/// Waits up to the given time for the sink's queued batches to reach the file.
pub(super) type Drain = Box<dyn Fn(Duration) + Send + Sync>;

/// The buffered trace writer. Cheap to call from the scheduler and connection threads alike.
pub(super) struct DispatchTrace {
    origin: Instant,
    buf: Mutex<Buf>,
    sink: Sink,
    drain: Drain,
    /// A step line waiting for its GPU launch time (only the scheduler thread touches it).
    pending: Mutex<Option<Vec<u8>>>,
}

fn epoch_us() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_micros() as u64)
}

impl DispatchTrace {
    pub(super) fn new(origin: Instant, sink: Sink) -> Self {
        Self {
            origin,
            buf: Mutex::new(Buf {
                bytes: Vec::with_capacity(FLUSH_BYTES * 2),
                batch_lines: 0,
                seq: 0,
                dropped: 0,
                oldest_us: None,
                ended: false,
            }),
            sink,
            drain: Box::new(|_| {}),
            pending: Mutex::new(None),
        }
    }

    pub(super) fn with_drain(mut self, drain: Drain) -> Self {
        self.drain = drain;
        self
    }

    /// A trace whose batches go to `dispatch-YYYYMMDD.jsonl` in `dir`.
    pub(super) fn to_record_dir(origin: Instant, dir: std::path::PathBuf) -> Self {
        let rec = std::sync::Arc::new(crate::record::Recorder::dispatch(dir));
        let queue = rec.clone();
        Self::new(origin, Box::new(move |epoch_ms, bytes| rec.record_bytes(epoch_ms, bytes)))
            .with_drain(Box::new(move |wait| queue.finish(wait)))
    }

    /// Append one line, `{"t":kind,"seq":..,"epoch_us":..,"mono_us":..` then `body`, and flush the
    /// batch if it is due (`force` flushes now).
    fn line(&self, kind: &str, force: bool, body: impl FnOnce(&mut Vec<u8>)) {
        self.line_at(kind, force, false, |o, _, _| body(o));
    }

    /// [`Self::line`] with the line's `seq` and the dropped count so far passed to `body`, all in
    /// one critical section. `last` makes it the final line: nothing is written after it.
    fn line_at(&self, kind: &str, force: bool, last: bool, body: impl FnOnce(&mut Vec<u8>, u64, u64)) {
        // The batch is handed to the sink under the same lock, so batches reach the file in `seq`
        // order (the recorder's sink only enqueues, without blocking).
        let mut b = self.buf.lock().unwrap_or_else(|e| e.into_inner());
        if b.ended {
            return;
        }
        b.ended = last;
        let seq = b.seq;
        b.seq += 1;
        let mono = self.origin.elapsed().as_micros() as u64;
        if b.bytes.len() >= MAX_BUFFERED_BYTES {
            b.dropped += 1;
        } else {
            let start = b.bytes.len();
            let _ = write!(b.bytes, r#"{{"t":"{kind}","seq":{seq},"epoch_us":{},"mono_us":{mono}"#, epoch_us());
            let dropped = b.dropped;
            body(&mut b.bytes, seq, dropped);
            b.bytes.extend_from_slice(b"}\n");
            debug_assert!(b.bytes.len() > start);
            b.batch_lines += 1;
            b.oldest_us.get_or_insert(mono);
        }
        let due = force
            || last
            || b.bytes.len() >= FLUSH_BYTES
            || b.oldest_us.is_some_and(|t| mono.saturating_sub(t) >= FLUSH_US);
        if due && b.batch_lines > 0 {
            b.oldest_us = None;
            let lines = std::mem::take(&mut b.batch_lines);
            let bytes = std::mem::replace(&mut b.bytes, Vec::with_capacity(FLUSH_BYTES * 2));
            if !(self.sink)(epoch_us() / 1000, bytes) {
                b.dropped += lines;
            }
        }
    }

    pub(super) fn start(&self, lanes: usize, max_bypass: u32, prefill_share: u32) {
        self.line("start", true, |o| {
            let _ = write!(
                o,
                r#","v":{DISPATCH_TRACE_VERSION},"pid":{},"lanes":{lanes},"max_bypass":{max_bypass},"prefill_share":{prefill_share},"reasons":["#,
                std::process::id()
            );
            for (k, r) in WaitReason::ALL.iter().enumerate() {
                let _ = write!(o, r#"{}"{}""#, if k > 0 { "," } else { "" }, r.name());
            }
            o.push(b']');
        });
    }

    /// One planned step: `kind` is what ran (`prefill`, `decode`, `verify`, or `none`).
    /// Monotonic µs of `t` on the trace clock.
    pub(super) fn mono_us(&self, t: Instant) -> u64 {
        t.saturating_duration_since(self.origin).as_micros() as u64
    }

    /// One planned step, written after the step's `response.sched` transitions. `kind` is what ran
    /// (`prefill`, `decode`, `verify`, or `none`); `begin` is when the planner was called. A step
    /// that dispatched something waits for [`Self::launch`] to add its GPU commit time; a `none`
    /// step is written now. A step never launched is written with `"launch_mono_us":null` at the
    /// next step, idle or end line.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn step(
        &self,
        step: u64,
        kind: &str,
        begin: Instant,
        ready: usize,
        dispatched: &[(usize, u64)],
        skipped: &[(usize, u64, WaitReason)],
    ) {
        self.flush_pending(None);
        let mut o = Vec::with_capacity(64 + 12 * (dispatched.len() + skipped.len()));
        let _ = write!(
            o,
            r#","step":{step},"kind":"{kind}","begin_mono_us":{},"ready":{ready},"disp":["#,
            self.mono_us(begin)
        );
        for (k, (lane, req)) in dispatched.iter().enumerate() {
            let _ = write!(o, "{}[{lane},{req}]", if k > 0 { "," } else { "" });
        }
        o.extend_from_slice(br#"],"skip":["#);
        for (k, (lane, req, why)) in skipped.iter().enumerate() {
            let _ = write!(o, r#"{}[{lane},{req},"{}"]"#, if k > 0 { "," } else { "" }, why.name());
        }
        o.push(b']');
        if dispatched.is_empty() {
            self.line("step", false, |out| {
                out.extend_from_slice(&o);
                out.extend_from_slice(br#","launch_mono_us":null"#);
            });
        } else {
            *self.pending.lock().unwrap_or_else(|e| e.into_inner()) = Some(o);
        }
    }

    /// The planned step's command buffer was committed now: write its step line.
    pub(super) fn launch(&self) {
        self.flush_pending(Some(Instant::now()));
    }

    fn flush_pending(&self, launch: Option<Instant>) {
        let Some(body) = self.pending.lock().unwrap_or_else(|e| e.into_inner()).take() else { return };
        self.line("step", false, |out| {
            out.extend_from_slice(&body);
            match launch {
                Some(t) => {
                    let _ = write!(out, r#","launch_mono_us":{}"#, self.mono_us(t));
                }
                None => out.extend_from_slice(br#","launch_mono_us":null"#),
            }
        });
    }

    /// A request's open wait changed during the `response.sched` transition `op`, at `sched_ms` on
    /// its clock. `was`/`now` are the open wait (kind, since ms) before and after; a closed or
    /// replaced `was` was booked from its `since` to `sched_ms`.
    pub(super) fn wait(
        &self,
        op: &str,
        (req, lane, was): (u64, Option<usize>, Option<(crate::fairness::Phase, u64)>),
        now: Option<(crate::fairness::Phase, u64)>,
        sched_ms: u64,
    ) {
        self.line("wait", false, |o| {
            let lane = lane.map_or(-1, |l| l as i64);
            let _ = write!(o, r#","op":"{op}","req":{req},"lane":{lane},"sched_ms":{sched_ms},"was":"#);
            for (k, w) in [was, now].into_iter().enumerate() {
                if k == 1 {
                    o.extend_from_slice(br#","now":"#);
                }
                match w {
                    Some((ph, since)) => {
                        let _ = write!(o, r#"["{}",{since}]"#, ph.name());
                    }
                    None => o.extend_from_slice(b"null"),
                }
            }
        });
    }

    /// The scheduler blocks for new work (`begin`) or wakes with it (`end`).
    pub(super) fn idle(&self, begin: bool) {
        self.flush_pending(None);
        // Forced both ways: the scheduler may block for a long time right after `begin`.
        self.line("idle", true, |o| {
            let _ = write!(o, r#","ev":"{}""#, if begin { "begin" } else { "end" });
        });
    }

    /// The last line: how many lines the trace numbered (this one included) and how many of
    /// them were dropped. Later calls write nothing.
    pub(super) fn end(&self) {
        self.flush_pending(None);
        self.line_at("end", true, true, |o, seq, dropped| {
            let _ = write!(o, r#","lines":{},"dropped":{dropped}"#, seq + 1);
        });
    }

    /// [`Self::end`], then wait up to `wait` for the writer to put every batch in the file. For
    /// scheduler exit and the stop signal, before the process ends.
    pub(super) fn finish(&self, wait: Duration) {
        self.end();
        (self.drain)(wait);
    }

    pub(super) fn dropped(&self) -> u64 {
        self.buf.lock().unwrap_or_else(|e| e.into_inner()).dropped
    }

    pub(super) fn lines(&self) -> u64 {
        self.buf.lock().unwrap_or_else(|e| e.into_inner()).seq
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};
    use std::sync::Arc;

    const W: u32 = 4;

    fn decoder() -> ServeLaneInput {
        ServeLaneInput { runnable: true, n_past: 64, pf_end: 64, has_pending_decode: true }
    }

    fn prefiller() -> ServeLaneInput {
        ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 16, has_pending_decode: false }
    }

    fn planner(n: usize, share: u32) -> ServeStepPlanner {
        let mut p = ServeStepPlanner::new(n, W).with_prefill_share(share);
        for i in 0..n {
            p.on_admit(i);
        }
        p
    }

    fn chosen(plan: &ServeStepPlan) -> Vec<usize> {
        match plan {
            ServeStepPlan::Decode(l) => l.clone(),
            ServeStepPlan::Prefill(s) => s.iter().map(|s| s.0).collect(),
        }
    }

    /// Plan once and return (dispatched, skipped reasons) through `explain`, every lane ready
    /// and ungated, request id = 100 + lane.
    fn reasons(
        p: &mut ServeStepPlanner,
        inputs: &[ServeLaneInput],
        budget: usize,
        cap: usize,
    ) -> (Vec<usize>, Vec<(usize, WaitReason)>) {
        let (plan, _) = p.plan_with_prefill_limit(inputs, budget, 64, cap);
        let disp = plan.as_ref().map(chosen).unwrap_or_default();
        let ready: Vec<Ready> = (0..inputs.len())
            .map(|lane| Ready { lane, req: 100 + lane as u64, gate: None, pool_deferred_after: false })
            .collect();
        let mut out = Vec::new();
        explain(&ready, &disp, p.skips(), &mut out);
        assert_eq!(disp.len() + out.len(), inputs.len(), "every ready lane is dispatched or explained");
        p.complete_step();
        (
            disp,
            out.into_iter()
                .map(|(l, req, w)| {
                    assert_eq!(req, 100 + l as u64);
                    (l, w)
                })
                .collect(),
        )
    }

    #[test]
    fn share_picks_prefill_and_the_decoder_waits_on_the_share() {
        let mut p = planner(2, 60);
        let (disp, why) = reasons(&mut p, &[decoder(), prefiller()], 4096, usize::MAX);
        assert_eq!(disp, [1]);
        assert_eq!(why, [(0, WaitReason::Share)]);
    }

    #[test]
    fn share_credit_below_zero_picks_decode_and_the_prefiller_waits_on_the_share() {
        let mut p = planner(2, 60);
        let inputs = [decoder(), prefiller()];
        reasons(&mut p, &inputs, 4096, usize::MAX);
        p.charge_step(1_000_000);
        assert!(p.credit() < 0);
        let (disp, why) = reasons(&mut p, &inputs, 4096, usize::MAX);
        assert_eq!(disp, [0]);
        assert_eq!(why, [(1, WaitReason::Share)]);
    }

    #[test]
    fn tick_policy_and_the_prefill_ceiling() {
        let mut p = planner(2, 0);
        let inputs = [decoder(), prefiller()];
        for _ in 0..W {
            let (disp, why) = reasons(&mut p, &inputs, 4096, usize::MAX);
            assert_eq!((disp, why), (vec![0], vec![(1, WaitReason::TickPolicy)]));
        }
        // The prefiller is at W: it preempts, and the decoder waits on the ceiling.
        let (disp, why) = reasons(&mut p, &inputs, 4096, usize::MAX);
        assert_eq!((disp, why), (vec![1], vec![(0, WaitReason::Ceiling)]));
    }

    #[test]
    fn a_decoder_at_the_ceiling_overrides_the_share() {
        // Credit stays >= 0 (prefill owed) because the prefill steps are never charged, while the
        // decoder ages to W; then decode is forced against the share.
        let mut p = planner(2, 60);
        let inputs = [decoder(), prefiller()];
        for _ in 0..W {
            let (disp, why) = reasons(&mut p, &inputs, 4096, usize::MAX);
            assert_eq!((disp, why), (vec![1], vec![(0, WaitReason::Share)]));
        }
        assert!(p.credit() >= 0);
        let (disp, why) = reasons(&mut p, &inputs, 4096, usize::MAX);
        assert_eq!((disp, why), (vec![0], vec![(1, WaitReason::Ceiling)]));
    }

    #[test]
    fn budget_and_prefill_cap_leave_same_class_lanes_out() {
        // Three prefillers, 128-token budget: two 64-token blocks fit, the third waits on the budget.
        let mut p = planner(3, 0);
        let (disp, why) = reasons(&mut p, &[prefiller(), prefiller(), prefiller()], 128, usize::MAX);
        assert_eq!((disp, why), (vec![0, 1], vec![(2, WaitReason::Budget)]));
        // Contended with the cap at 128 (decoder waiting, share owed): the cap, not the budget.
        let mut p = planner(4, 60);
        let (disp, why) = reasons(&mut p, &[decoder(), prefiller(), prefiller(), prefiller()], 4096, 128);
        assert_eq!(disp, [1, 2]);
        assert_eq!(why, [(0, WaitReason::Share), (3, WaitReason::PrefillCap)]);
        // A decode step truncated to the token budget.
        let mut p = planner(3, 0);
        let (disp, why) = reasons(&mut p, &[decoder(), decoder(), decoder()], 2, usize::MAX);
        assert_eq!((disp, why), (vec![0, 1], vec![(2, WaitReason::Budget)]));
    }

    #[test]
    fn serve_gates_in_the_schedulers_order() {
        use LaneState::*;
        assert_eq!(gate(Restoring, true, true, true, true), Some(WaitReason::Restore));
        assert_eq!(gate(Admitted, false, false, false, false), Some(WaitReason::Restore));
        assert_eq!(gate(Cancelled, false, false, false, false), Some(WaitReason::LaneState));
        assert_eq!(gate(Ready, true, true, true, true), Some(WaitReason::Cancelled));
        assert_eq!(gate(Ready, false, true, true, true), Some(WaitReason::Backpressure));
        assert_eq!(gate(Ready, false, false, true, true), Some(WaitReason::PoolDeferred));
        assert_eq!(gate(Ready, false, false, false, true), Some(WaitReason::IkvStage));
        assert_eq!(gate(Ready, false, false, false, false), None);
    }

    #[test]
    fn gated_singleflight_pool_exhausted_and_dropped_lanes() {
        // Lanes 0..3 gated (not planner inputs), lane 3 planned and dispatched, lane 4 planned but
        // pool-exhausted, lane 5 planned and dropped.
        let mut p = planner(6, 0);
        let mut inputs = [prefiller(); 6];
        for inp in &mut inputs[..3] {
            inp.runnable = false;
        }
        let (plan, _) = p.plan_with_prefill_limit(&inputs, 4096, 64, usize::MAX);
        assert_eq!(chosen(&plan.unwrap()), [3, 4, 5]);
        let gates = [
            Some(WaitReason::Backpressure),
            Some(WaitReason::Singleflight),
            Some(WaitReason::Restore),
            None,
            None,
            None,
        ];
        let ready: Vec<Ready> = (0..6)
            .map(|lane| Ready { lane, req: lane as u64, gate: gates[lane], pool_deferred_after: lane == 4 })
            .collect();
        let mut out = Vec::new();
        explain(&ready, &[3], p.skips(), &mut out);
        let why: Vec<_> = out.iter().map(|&(l, _, w)| (l, w)).collect();
        assert_eq!(
            why,
            [
                (0, WaitReason::Backpressure),
                (1, WaitReason::Singleflight),
                (2, WaitReason::Restore),
                (4, WaitReason::PoolExhausted),
                (5, WaitReason::Dropped),
            ]
        );
    }

    #[test]
    fn counters_add_up_over_a_seeded_walk() {
        let counters = DispatchCounters::default();
        let mut p = planner(8, 60);
        let mut seed = 7u64;
        let mut next = || {
            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            (seed >> 33) as usize
        };
        let mut inputs: Vec<ServeLaneInput> =
            (0..8).map(|i| if i % 2 == 0 { decoder() } else { prefiller() }).collect();
        let mut out = Vec::new();
        for _ in 0..500 {
            let gates: Vec<Option<WaitReason>> = (0..8)
                .map(|_| match next() % 10 {
                    0 => Some(WaitReason::Backpressure),
                    1 => Some(WaitReason::Restore),
                    _ => None,
                })
                .collect();
            for (i, inp) in inputs.iter_mut().enumerate() {
                inp.runnable = gates[i].is_none();
            }
            let (plan, _) = p.plan_with_prefill_limit(&inputs, 64 * (1 + next() % 4), 64, usize::MAX);
            let disp = plan.as_ref().map(chosen).unwrap_or_default();
            let ready: Vec<Ready> = (0..8)
                .map(|lane| Ready { lane, req: lane as u64, gate: gates[lane], pool_deferred_after: false })
                .collect();
            explain(&ready, &disp, p.skips(), &mut out);
            assert!(out.iter().all(|r| r.2 != WaitReason::Dropped), "every left-out lane has a decision: {out:?}");
            counters.note(ready.len(), disp.len(), &out);
            if plan.is_some() {
                p.charge_step(1_000 + (next() % 50_000) as u64);
            }
            p.complete_step();
        }
        let v = counters.to_json();
        let skipped: u64 = v["skipped"].as_object().unwrap().values().map(|x| x.as_u64().unwrap()).sum();
        assert_eq!(v["steps"], 500);
        assert_eq!(v["ready"].as_u64().unwrap(), 500 * 8);
        assert_eq!(v["dispatched"].as_u64().unwrap() + skipped, v["ready"].as_u64().unwrap());
        for r in [WaitReason::Share, WaitReason::Budget, WaitReason::Backpressure, WaitReason::Restore] {
            assert!(v["skipped"][r.name()].as_u64().unwrap() > 0, "{} never seen", r.name());
        }
    }

    fn captured(force_drop: bool) -> (DispatchTrace, Arc<Mutex<Vec<u8>>>) {
        let got = Arc::new(Mutex::new(Vec::new()));
        let sink = got.clone();
        let t = DispatchTrace::new(
            Instant::now(),
            Box::new(move |_, bytes| {
                if force_drop {
                    return false;
                }
                sink.lock().unwrap().extend_from_slice(&bytes);
                true
            }),
        );
        (t, got)
    }

    fn parse(bytes: &[u8]) -> Vec<serde_json::Value> {
        std::str::from_utf8(bytes).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect()
    }

    #[test]
    fn trace_lines_are_valid_json_with_gapless_seq_and_an_end_count() {
        use crate::fairness::Phase;
        let (t, got) = captured(false);
        t.start(4, 16, 60);
        t.idle(true);
        t.idle(false);
        t.wait("mark_runnable", (7, Some(2), None), Some((Phase::Prefill, 1200)), 1200);
        t.wait("dispatch", (7, Some(2), Some((Phase::Prefill, 1200))), None, 1203);
        let begin = Instant::now();
        t.step(1, "prefill", begin, 3, &[(2, 7)], &[(0, 5, WaitReason::Share), (1, 6, WaitReason::Backpressure)]);
        t.launch();
        t.step(2, "decode", begin, 1, &[(0, 5)], &[]);
        t.step(3, "none", begin, 0, &[], &[]);
        t.end();
        t.end();
        let lines = parse(&got.lock().unwrap());
        assert_eq!(lines.len(), 9);
        for (k, l) in lines.iter().enumerate() {
            assert_eq!(l["seq"], k as u64);
            assert!(l["epoch_us"].as_u64().unwrap() > 1_700_000_000_000_000);
            assert!(l["mono_us"].is_u64());
        }
        assert_eq!(lines[0]["t"], "start");
        assert_eq!(lines[0]["reasons"].as_array().unwrap().len(), WaitReason::ALL.len());
        assert_eq!(lines[4]["was"], serde_json::json!(["prefill", 1200]));
        assert!(lines[4]["now"].is_null());
        let step1 = &lines[5];
        assert_eq!(step1["disp"], serde_json::json!([[2, 7]]));
        assert_eq!(step1["skip"], serde_json::json!([[0, 5, "share"], [1, 6, "backpressure"]]));
        assert!(step1["begin_mono_us"].as_u64().unwrap() <= step1["launch_mono_us"].as_u64().unwrap());
        // Step 2 was never launched: it is written, launch null, when step 3 arrives.
        assert_eq!((lines[6]["step"].as_u64(), lines[6]["launch_mono_us"].is_null()), (Some(2), true));
        assert_eq!((lines[7]["kind"].as_str(), lines[7]["launch_mono_us"].is_null()), (Some("none"), true));
        assert_eq!(lines[8]["t"], "end");
        assert_eq!(lines[8]["lines"], 9);
        assert_eq!(lines[8]["dropped"], 0);
    }

    /// The trace rides the `response.sched` transitions without turning on `response.sched`: one
    /// `wait` line per change to the open wait, none for a transition that leaves it as it was.
    #[test]
    fn wait_lines_follow_the_booked_transitions_without_request_fairness() {
        use crate::fairness::Phase;
        let (t, got) = captured(false);
        let t = Arc::new(t);
        let (out, _events) = super::super::job_events();
        out.state.arm_fairness(Instant::now(), false, Some(&t));
        out.fair("arrive", |s, now| s.arrive(42, now));
        out.fair("admit", |s, now| s.admit(3, now));
        out.fair("mark_runnable", |s, now| s.mark_runnable(Phase::Prefill, 0, 400, now));
        out.fair("skip", |s, now| s.skip(now));
        out.fair("dispatch", |s, now| s.dispatch(Phase::Prefill, 64, false, now));
        out.fair("commit_prefill", |s, now| s.commit_prefill(64, 64, now));
        out.fair("cancel", |s, now| s.cancel(Phase::Prefill, 64, 400, now));
        assert!(out.fair_snapshot().is_none(), "response.sched stays off");
        t.end();
        let lines = parse(&got.lock().unwrap());
        let ops: Vec<_> =
            lines.iter().filter(|l| l["t"] == "wait").map(|l| l["op"].as_str().unwrap().to_string()).collect();
        assert_eq!(ops, ["mark_runnable", "dispatch", "commit_prefill", "cancel"]);
        for l in lines.iter().filter(|l| l["t"] == "wait") {
            assert_eq!((l["req"].as_u64(), l["lane"].as_i64()), (Some(42), Some(3)));
        }
        assert!(lines[0]["was"].is_null() && lines[0]["now"][0] == "prefill");
        assert!(lines[3]["was"][0] == "prefill" && lines[3]["now"].is_null());
    }

    /// A sink whose writer thread stays held on a latch until `drain` runs, proving `finish` returns
    /// only after the background writer has written every queued batch.
    fn held_writer() -> (DispatchTrace, Arc<Mutex<Vec<u8>>>) {
        let written = Arc::new(Mutex::new(Vec::new()));
        let (queued, queued_cvar) = (Arc::new(Mutex::new(0u64)), Arc::new(std::sync::Condvar::new()));
        let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new()));
        let (tx, rx) = std::sync::mpsc::channel::<Vec<u8>>();
        let (out, left, left_cvar, gate_bg) = (written.clone(), queued.clone(), queued_cvar.clone(), gate.clone());
        std::thread::spawn(move || {
            while let Ok(bytes) = rx.recv() {
                let g = gate_bg.0.lock().unwrap();
                let (_g, timeout) = gate_bg
                    .1
                    .wait_timeout_while(g, crate::serve::TEST_HANG_GUARD, |open| !*open)
                    .unwrap();
                assert!(!timeout.timed_out(), "hang guard: held_writer latch never opened");
                out.lock().unwrap().extend_from_slice(&bytes);
                let mut q = left.lock().unwrap();
                *q -= 1;
                left_cvar.notify_all();
            }
        });
        let tx = Mutex::new(tx);
        let enq = queued.clone();
        let t = DispatchTrace::new(
            Instant::now(),
            Box::new(move |_, bytes| {
                *enq.lock().unwrap() += 1;
                tx.lock().unwrap().send(bytes).is_ok()
            }),
        )
        .with_drain(Box::new(move |wait| {
            *gate.0.lock().unwrap() = true;
            gate.1.notify_all();
            let q = queued.lock().unwrap();
            let (_q, timeout) = queued_cvar.wait_timeout_while(q, wait, |rem| *rem > 0).unwrap();
            assert!(!timeout.timed_out(), "hang guard: writer did not drain within {wait:?}");
        }));
        (t, written)
    }

    /// `finish` returns only once the end line is in the file, not merely queued for the writer.
    #[test]
    fn finish_drains_the_writer_before_returning() {
        let (t, written) = held_writer();
        t.start(1, 16, 0);
        t.step(1, "none", Instant::now(), 0, &[], &[]);
        assert!(written.lock().unwrap().is_empty(), "writer must still be held before finish drains it");
        t.finish(crate::serve::TEST_HANG_GUARD);
        let lines = parse(&written.lock().unwrap());
        assert_eq!(lines.len(), 3);
        assert_eq!(lines.last().unwrap()["t"], "end");
    }

    /// The scheduler blocks right after `idle begin`: everything before it, and the line itself,
    /// must already be handed to the writer.
    #[test]
    fn idle_begin_and_end_both_flush() {
        let (t, got) = captured(false);
        t.wait("mark_runnable", (1, Some(0), None), Some((crate::fairness::Phase::Decode, 5)), 5);
        t.step(1, "none", Instant::now(), 0, &[], &[]);
        t.idle(true);
        let lines = parse(&got.lock().unwrap());
        assert_eq!(lines.iter().map(|l| l["t"].as_str().unwrap()).collect::<Vec<_>>(), ["wait", "step", "idle"]);
        t.wait("mark_runnable", (2, Some(0), None), Some((crate::fairness::Phase::Decode, 9)), 9);
        t.idle(false);
        assert_eq!(parse(&got.lock().unwrap()).len(), 5);
    }

    /// `end` reads the count, writes its line and closes the trace in one critical section: with
    /// other threads writing `wait` lines all the while, the end line is the last line, its `lines`
    /// is its own `seq + 1`, and every line before it is numbered below it.
    #[test]
    fn end_is_atomic_against_concurrent_writers() {
        for _ in 0..200 {
            let (t, got) = captured(false);
            let t = Arc::new(t);
            t.start(1, 16, 0);
            let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let writers: Vec<_> = (0..3)
                .map(|w| {
                    let (t, stop) = (t.clone(), stop.clone());
                    std::thread::spawn(move || {
                        while !stop.load(Ordering::Relaxed) {
                            t.wait("block", (w, Some(0), Some((crate::fairness::Phase::Decode, 1))), None, 2);
                        }
                    })
                })
                .collect();
            while t.lines() < 20 {
                std::thread::yield_now();
            }
            let enders: Vec<_> = (0..2)
                .map(|_| {
                    let t = t.clone();
                    std::thread::spawn(move || t.end())
                })
                .collect();
            for e in enders {
                e.join().unwrap();
            }
            stop.store(true, Ordering::Relaxed);
            for w in writers {
                w.join().unwrap();
            }
            let lines = parse(&got.lock().unwrap());
            let ends: Vec<_> = lines.iter().filter(|l| l["t"] == "end").collect();
            assert_eq!(ends.len(), 1, "one end line");
            let end = lines.last().unwrap();
            assert_eq!(end["t"], "end", "nothing after end");
            assert_eq!(end["lines"].as_u64().unwrap(), end["seq"].as_u64().unwrap() + 1);
            assert_eq!(end["lines"].as_u64().unwrap(), lines.len() as u64);
        }
    }

    #[test]
    fn a_refused_batch_is_counted_as_dropped_lines() {
        let (t, _) = captured(true);
        t.start(1, 16, 0);
        t.step(1, "none", Instant::now(), 0, &[], &[]);
        t.idle(false);
        assert_eq!(t.dropped(), 3, "start and the idle end force a flush; both batches were refused");
        assert_eq!(t.lines(), 3);
    }

    /// The cost per step line at 64 lanes (8 dispatched, 56 skipped), formatting and buffering
    /// included. Run with `--ignored --nocapture`; it reads the clock, so it is not a gate.
    #[test]
    #[ignore = "microbenchmark"]
    fn bench_step_line_cost() {
        let t = DispatchTrace::new(Instant::now(), Box::new(|_, bytes| !std::hint::black_box(bytes).is_empty()));
        let disp: Vec<(usize, u64)> = (0..8).map(|l| (l, 1000 + l as u64)).collect();
        let skip: Vec<(usize, u64, WaitReason)> = (8..64).map(|l| (l, 1000 + l as u64, WaitReason::Budget)).collect();
        let counters = DispatchCounters::default();
        let n = 200_000u64;
        let began = Instant::now();
        for s in 0..n {
            t.step(s, "decode", began, 64, &disp, &skip);
            t.launch();
        }
        let traced = began.elapsed();
        let began = Instant::now();
        for _ in 0..n {
            counters.note(64, 8, std::hint::black_box(&skip));
        }
        let counted = began.elapsed();
        let p = &mut planner(64, 60);
        let inputs: Vec<ServeLaneInput> = (0..64).map(|i| if i < 8 { decoder() } else { prefiller() }).collect();
        let ready: Vec<Ready> =
            (0..64).map(|lane| Ready { lane, req: lane as u64, gate: None, pool_deferred_after: false }).collect();
        let mut out = Vec::new();
        let began = Instant::now();
        for _ in 0..n / 10 {
            let (plan, _) = p.plan_with_prefill_limit(&inputs, 4096, 64, usize::MAX);
            let disp = plan.as_ref().map(chosen).unwrap_or_default();
            explain(&ready, &disp, p.skips(), &mut out);
            p.charge_step(10_000);
            p.complete_step();
        }
        let planned = began.elapsed();
        println!(
            "dispatch trace @64 lanes: step line {:.0} ns, counters {:.0} ns, plan+explain {:.0} ns per step; {} bytes/line",
            traced.as_nanos() as f64 / n as f64,
            counted.as_nanos() as f64 / n as f64,
            planned.as_nanos() as f64 / (n / 10) as f64,
            {
                let (t2, got) = captured(false);
                t2.step(0, "decode", Instant::now(), 64, &disp, &skip);
                t2.launch();
                t2.end();
                let len = got.lock().unwrap().iter().position(|&b| b == b'\n').unwrap() + 1;
                len
            }
        );
    }
}