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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
use super::*;

fn small_cfg() -> SchedulerConfig {
    SchedulerConfig {
        lanes: vec!["a".into(), "b".into(), "c".into(), "d".into()],
        prefixes: vec!["p1".into(), "p2".into()],
        request_lengths: vec![2, 4],
        block_size: 2,
        window_size: 2,
        max_pos: 4,
        max_span: 2,
        step_token_budget: 2,
        mem_budget: 6,
        disk_budget: 4,
        max_queue: 2,
        max_bypass: 2,
        start_point_stride_blocks: 1,
    }
}

#[test]
fn explicit_lane_lifecycle_and_illegal_transitions() {
    let mut s = Scheduler::new(small_cfg()).unwrap();
    assert_eq!(s.lanes()[0].state, LaneState::Idle);
    // Cannot admit before Queued.
    assert!(s.admit(0).is_err());
    assert_eq!(s.arrive(0, "p1", 4).unwrap(), ArriveOutcome::Queued);
    assert_eq!(s.lanes()[0].state, LaneState::Queued);
    // Cannot begin_restore before Admitted.
    assert!(s.begin_restore(0).is_err());
    s.admit(0).unwrap();
    assert_eq!(s.lanes()[0].state, LaneState::Admitted);
    // Cannot finish_restore before Restoring.
    assert!(s.finish_restore(0).is_err());
    s.begin_restore(0).unwrap();
    assert_eq!(s.lanes()[0].state, LaneState::Restoring);
    s.finish_restore(0).unwrap();
    assert_eq!(s.lanes()[0].state, LaneState::Ready);

    // Run through prefill (pos 0->2) and decode (pos 2->3->4) to Finished.
    let mut slid = 0usize;
    while s.lanes()[0].pos < s.lanes()[0].target {
        if s.slide_window(0) {
            slid += 1;
        }
        let step = s.build_step().unwrap().expect("step built");
        assert_eq!(step.lanes, vec![0]);
        assert_eq!(s.lanes()[0].state, LaneState::InStep);
        // complete_step must fail before gpu_execute!
        assert!(s.complete_step().is_err());
        s.gpu_execute().unwrap();
        let done = s.complete_step().unwrap();
        assert_eq!(done.survived, vec![0]);
        assert_eq!(s.lanes()[0].state, LaneState::Ready);
        s.check_invariants().unwrap();
    }
    assert!(slid >= 1, "explicit slide_window exercised during decode");
    s.finish_ready(0).unwrap();
    assert_eq!(s.lanes()[0].state, LaneState::Finished);
    assert_eq!(s.reserved_total(), 0);
    assert_eq!(s.admitted_total(), 0);
    s.check_invariants().unwrap();
}

#[test]
fn cancel_in_step_waits_for_gpu_and_io_barrier() {
    let mut s = Scheduler::new(small_cfg()).unwrap();
    s.arrive(0, "p1", 4).unwrap();
    s.admit(0).unwrap();
    s.begin_restore(0).unwrap();
    s.finish_restore(0).unwrap();

    let step = s.build_step().unwrap().unwrap();
    assert_eq!(step.lanes, vec![0]);
    assert_eq!(s.lanes()[0].state, LaneState::InStep);
    let res_before = s.lanes()[0].reservation;
    let mem_before = s.mem_used();
    assert!(res_before > 0 && mem_before > 0);

    // Client disconnects mid-step: must enter Cancelling and HOLD slot, blocks, pins, reservation!
    assert_eq!(s.cancel(0).unwrap(), LaneState::Cancelling);
    assert_eq!(s.lanes()[0].state, LaneState::Cancelling);
    assert_eq!(s.lanes()[0].reservation, res_before);
    assert_eq!(s.mem_used(), mem_before);
    assert!(!s.step_pins().is_empty());
    // Cannot reuse the slot while Cancelling!
    assert!(s.arrive(0, "p1", 2).is_err());
    // Cannot finish step until GPU completes!
    assert!(s.complete_step().is_err());
    s.check_invariants().unwrap();

    // GPU work finishes -> complete_step transitions Cancelling -> Cancelled and frees everything.
    s.gpu_execute().unwrap();
    let done = s.complete_step().unwrap();
    assert_eq!(done.cancelled, vec![0]);
    assert_eq!(s.lanes()[0].state, LaneState::Cancelled);
    assert_eq!(s.lanes()[0].reservation, 0);
    assert_eq!(s.lanes()[0].admit_budget, 0);
    assert_eq!(s.mem_used(), 0);
    assert!(s.step_pins().is_empty());
    s.check_invariants().unwrap();

    // Slot is now cleanly reusable.
    assert_eq!(s.arrive(0, "p2", 2).unwrap(), ArriveOutcome::Queued);
}

#[test]
fn cancel_in_restore_io_waits_for_disk_read_barrier() {
    let mut cfg = small_cfg();
    cfg.mem_budget = 4;
    cfg.disk_budget = 4;
    let mut s = Scheduler::new(cfg).unwrap();

    // Seed a kept prefill start point at (p1, 2) (`target = 4` -> `PromptEnd = 2`) and spill its blocks to disk.
    s.arrive(0, "p1", 4).unwrap();
    s.admit(0).unwrap();
    s.begin_restore(0).unwrap();
    s.finish_restore(0).unwrap();
    s.build_step().unwrap();
    s.gpu_execute().unwrap();
    s.complete_step().unwrap();
    s.cancel(0).unwrap();

    // Fill memory with p2 on lane 1 so p1's cold blocks spill to disk under pressure.
    s.arrive(1, "p2", 4).unwrap();
    s.admit(1).unwrap();
    s.begin_restore(1).unwrap();
    s.finish_restore(1).unwrap();
    // Trigger pressure: lane 1 needs 2 private blocks, mem_used == 2 (p1's 2 sealed blocks),
    // mem_budget == 4 -> let's push another block or spill p1 explicitly via pressure.
    s.build_step().unwrap();
    s.gpu_execute().unwrap();
    s.complete_step().unwrap();
    // Now mem_used == 4 (p1: 2 blocks, p2: 2 sealed blocks), lane 1 at pos 2 needs 2 more!
    assert!(s.mem_pressure());
    let wb1 = s.start_cold_writeback().expect("cold writeback 1");
    s.complete_step_io().unwrap();
    assert_eq!(s.block_tier(&wb1), BlockTier::Disk);

    // Cancel lane 1 to free budget, then admit lane 2 on p1 -> Restoring with disk block!
    s.cancel(1).unwrap();
    s.arrive(2, "p1", 4).unwrap();
    s.admit(2).unwrap();
    s.begin_restore(2).unwrap();
    assert_eq!(s.lanes()[2].state, LaneState::Restoring);

    // Start async disk restore read, then cancel mid-read!
    s.begin_restore_io(2, &wb1).unwrap();
    assert_eq!(s.cancel(2).unwrap(), LaneState::Cancelling);
    assert_eq!(s.lanes()[2].state, LaneState::Cancelling);
    assert!(s.lanes()[2].reservation > 0, "reservation held until disk I/O completes");
    assert!(s.arrive(2, "p1", 2).is_err(), "slot cannot be reused during restore I/O");

    // Once disk read completes, lane transitions Cancelling -> Cancelled and releases cleanly.
    assert_eq!(s.complete_restore_io(2).unwrap(), LaneState::Cancelled);
    assert_eq!(s.lanes()[2].state, LaneState::Cancelled);
    assert_eq!(s.lanes()[2].reservation, 0);
    assert_eq!(s.lanes()[2].admit_budget, 0);
    s.check_invariants().unwrap();
}

#[test]
fn starvation_bound_enforced_across_ready_and_queued_adversarially() {
    // W = 2: 1 prefiller + 3 decoders competing for StepTokenBudget = 2.
    let mut cfg = small_cfg();
    cfg.lanes = vec!["l0".into(), "l1".into(), "l2".into(), "l3".into()];
    cfg.request_lengths = vec![2, 4];
    cfg.step_token_budget = 2;
    cfg.mem_budget = 16;
    cfg.max_bypass = 2;
    let mut s = Scheduler::new(cfg).unwrap();

    // Put l0, l1, l2 into decode phase (target=2 -> prompt_end=0 -> decoding from pos 0)
    // and l3 into prefill phase (target=4 -> prompt_end=2 -> prefilling at pos 0).
    for (l, len) in [(0, 2), (1, 2), (2, 2), (3, 4)] {
        s.arrive(l, "p1", len).unwrap();
        s.admit(l).unwrap();
        s.begin_restore(l).unwrap();
        s.finish_restore(l).unwrap();
    }
    assert!(s.is_decoding(0) && s.is_decoding(1) && s.is_decoding(2));
    assert!(s.is_prefilling(3));

    // Run steps until all complete; verify l3 (prefiller) is NEVER bypassed > W=2 ticks!
    let mut max_seen = 0u32;
    for _ in 0..32 {
        for l in 0..4 {
            if s.lanes()[l].state == LaneState::Ready
                && s.lanes()[l].pos == s.lanes()[l].target
            {
                s.finish_ready(l).unwrap();
            }
        }
        if s.lanes().iter().all(|l| l.state == LaneState::Finished) {
            break;
        }
        for l in 0..4 {
            s.slide_window(l);
        }
        let _step = s.build_step().unwrap().expect("step built");
        for l in s.lanes() {
            max_seen = max_seen.max(l.wait_ticks);
            assert!(
                l.wait_ticks <= 2,
                "starvation bound violated: {} > 2",
                l.wait_ticks
            );
        }
        s.check_invariants().unwrap();
        s.gpu_execute().unwrap();
        s.complete_step().unwrap();
    }
    assert!(s.lanes().iter().all(|l| l.state == LaneState::Finished));
    assert!((1..=2).contains(&max_seen));
}

/// Layer 4 Gate (`docs/ROADMAP.md:139`):
/// Bimodal workload mixing short (`2K` = 2048 tokens) and long (`64K` = 65536 tokens)
/// requests under a tight memory budget where `64K` requests force queueing + starvation-
/// bound promotion while clients disconnect mid-step (`InStep -> Cancelling -> Cancelled`),
/// proving zero memory/slot leak and bounded wait ticks (`<= W`).
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn bimodal_2k_64k_tight_budget_with_mid_step_disconnects() {
    const BLK: u32 = 64;
    const WIN: u32 = 1024;
    const SHORT_2K: u32 = 2048;
    const LONG_64K: u32 = 65536;
    // Worst-case blocks:
    //   2K:  full=32, win=min(SpanBound(64)=18, 32)=18 -> 50 blocks
    //   64K: full=1024, win=18 -> 1042 blocks
    let wc_2k = worst_case_blocks(SHORT_2K, BLK, WIN, BLK);
    let wc_64k = worst_case_blocks(LONG_64K, BLK, WIN, BLK);
    assert_eq!(wc_2k, 50);
    assert_eq!(wc_64k, 1042);

    // Tight budget: 1150 blocks -> fits ONE 64K (1042) + TWO 2K (100), OR many 2K,
    // so when 3+ 2K lanes are running (150 blocks), a queued 64K lane CANNOT fit until
    // starvation-bound W blocks further 2K leapfrogging and lets 2K lanes drain!
    let mem_budget = wc_64k + 2 * wc_2k + 8; // 1150 blocks
    let w_bound = 3u32;
    let cfg = SchedulerConfig {
        lanes: (0..8).map(|i| format!("lane{i}")).collect(),
        prefixes: vec!["short".into(), "long".into()],
        request_lengths: vec![SHORT_2K, LONG_64K],
        block_size: BLK,
        window_size: WIN,
        max_pos: LONG_64K,
        max_span: BLK,
        step_token_budget: 256,
        mem_budget,
        disk_budget: 128,
        max_queue: 4,
        max_bypass: w_bound,
        start_point_stride_blocks: 16,
    };
    let mut s = Scheduler::new(cfg).unwrap();

    // Phase 1: fill 4 lanes with 2K requests (200 blocks admitted -> remaining 950 < 1042).
    for l in 0..4 {
        assert_eq!(s.arrive(l, "short", SHORT_2K).unwrap(), ArriveOutcome::Queued);
        s.admit(l).unwrap();
        s.begin_restore(l).unwrap();
        s.finish_restore(l).unwrap();
    }
    assert!(!s.can_fit_request(LONG_64K), "tight budget must force 64K to queue");

    // Phase 2: enqueue a 64K request on lane 4, plus a flood of 2K requests behind it!
    assert_eq!(s.arrive(4, "long", LONG_64K).unwrap(), ArriveOutcome::Queued);
    assert_eq!(s.arrive(5, "short", SHORT_2K).unwrap(), ArriveOutcome::Queued);
    assert_eq!(s.arrive(6, "short", SHORT_2K).unwrap(), ArriveOutcome::Queued);
    assert_eq!(s.arrive(7, "short", SHORT_2K).unwrap(), ArriveOutcome::Queued);

    // Younger 2K requests leapfrog lane 4 (64K) ONLY up to W=3 times, then lane 4 hits W
    // and blocks any further younger 2K leapfrogging!
    assert!(s.can_admit_now(5));
    s.admit(5).unwrap();
    assert_eq!(s.lanes()[4].wait_ticks, 1);
    assert!(s.can_admit_now(6));
    s.admit(6).unwrap();
    assert_eq!(s.lanes()[4].wait_ticks, 2);
    assert!(s.can_admit_now(7));
    s.admit(7).unwrap();
    assert_eq!(s.lanes()[4].wait_ticks, 3);
    assert_eq!(s.lanes()[4].wait_ticks, w_bound);

    // Advance admitted 5,6,7 to Ready.
    for l in 5..=7 {
        s.begin_restore(l).unwrap();
        s.finish_restore(l).unwrap();
    }

    // Now run steps with mid-step client disconnects (lanes 1, 5, 6 disconnect mid-step!)
    // and new 2K arrivals attempting to leapfrog lane 4 while it sits at wait_ticks == W.
    let mut mid_step_cancels = 0usize;
    let mut disconnected_once = BTreeSet::new();
    let mut completed_2k = 0usize;
    let mut completed_64k = 0usize;
    let mut max_wait_observed = 0u32;
    let mut extra_short_submitted = 0usize;
    let mut long_admitted = false;

    for tick in 0..4000 {
        // Track wait_ticks bound across EVERY waiting state.
        for l in s.lanes() {
            if l.state.is_waiting() {
                max_wait_observed = max_wait_observed.max(l.wait_ticks);
                assert!(
                    l.wait_ticks <= w_bound,
                    "tick {tick}: lane {} ({:?}) exceeded W={w_bound}: {}",
                    l.name,
                    l.state,
                    l.wait_ticks
                );
            }
        }

        // Finish any completed Ready lanes.
        for l in 0..8 {
            if s.lanes()[l].state == LaneState::Ready && s.lanes()[l].pos == s.lanes()[l].target
            {
                let was_long = s.lanes()[l].target == LONG_64K;
                s.finish_ready(l).unwrap();
                if was_long {
                    completed_64k += 1;
                } else {
                    completed_2k += 1;
                }
            }
        }

        // Submit a few extra 2K requests while lane 4 is queued at W to prove zero leapfrogging!
        if !long_admitted && extra_short_submitted < 2 {
            if let Some(idle_l) = (0..8).find(|&i| s.lanes()[i].state.is_terminal_or_idle()) {
                if s.arrive(idle_l, "short", SHORT_2K).unwrap() == ArriveOutcome::Queued {
                    extra_short_submitted += 1;
                    // Lane 4 is at W=3 -> younger queued 2K MUST NOT be allowed to admit!
                    if s.lanes()[4].state == LaneState::Queued
                        && s.lanes()[4].wait_ticks >= w_bound
                    {
                        assert!(
                            !s.can_admit_now(idle_l),
                            "younger 2K lane {idle_l} illegally leapfrogged 64K lane 4 at W"
                        );
                    }
                }
            }
        }

        // Evict cold memory blocks and start-point states lazily if under pressure.
        while s.mem_pressure() {
            if s.evict_clean_or_unref_mem() {
                continue;
            }
            if s.start_cold_writeback().is_some() {
                s.complete_step_io().unwrap();
                continue;
            }
            if s.reclaim_cold_disk() {
                continue;
            }
            break;
        }
        while s.state_mem_pressure() {
            if s.evict_clean_start_state().is_some() {
                continue;
            }
            if s.spill_start_state().is_some() {
                continue;
            }
            if s.reclaim_cold_disk() {
                continue;
            }
            break;
        }

        // Admit eligible queued lanes (lane 4 admits as soon as enough 2K lanes drain!).
        while let Some(admitted) = s.admit_next().unwrap() {
            if admitted == 4 {
                long_admitted = true;
            }
        }
        for l in 0..8 {
            if s.can_advance_admitted(l) {
                s.begin_restore(l).unwrap();
            }
            if s.lanes()[l].state == LaneState::Restoring {
                for b in s.lane_block_set(l) {
                    if s.blocks().get(&b).is_some_and(|r| r.tier == BlockTier::Disk) {
                        while s.mem_used() >= s.config().mem_budget {
                            if !s.evict_clean_or_unref_mem() {
                                if s.start_cold_writeback().is_some() {
                                    s.complete_step_io().unwrap();
                                } else if !s.reclaim_cold_disk() {
                                    break;
                                }
                            }
                        }
                        s.restore_block(l, &b).unwrap();
                    }
                }
                if !s.start_state_ready(l) {
                    while s.state_mem_used() >= s.state_mem_budget() {
                        if s.evict_clean_start_state().is_none()
                            && s.spill_start_state().is_none()
                            && !s.reclaim_cold_disk()
                        {
                            break;
                        }
                    }
                    s.restore_start_state(l).unwrap();
                }
                s.finish_restore(l).unwrap();
            }
        }

        // All drained?
        if s.lanes().iter().all(|l| l.state.is_terminal_or_idle()) {
            break;
        }
        for l in 0..8 {
            s.slide_window(l);
        }

        // Build & execute one step, injecting mid-step disconnects on lanes 1, 5, 6 and
        // on a second 64K request if desired.
        let Some(step) = s.build_step().unwrap() else {
            panic!("deadlock at tick {tick}: no lane could make progress");
        };

        // Inject mid-step disconnects once per victim while InStep (before gpu_execute!).
        for &victim in &[1usize, 5, 6] {
            if !disconnected_once.contains(&victim)
                && step.lanes.contains(&victim)
                && s.lanes()[victim].state == LaneState::InStep
                && s.lanes()[victim].pos >= 128
            {
                disconnected_once.insert(victim);
                assert_eq!(s.cancel(victim).unwrap(), LaneState::Cancelling);
                // Verify barrier: slot & reservation remain held while Cancelling!
                assert!(s.lanes()[victim].reservation > 0);
                mid_step_cancels += 1;
            }
        }

        s.gpu_execute().unwrap();
        let done = s.complete_step().unwrap();
        for c in &done.cancelled {
            assert_eq!(s.lanes()[*c].state, LaneState::Cancelled);
            assert_eq!(s.lanes()[*c].reservation, 0);
            assert_eq!(s.lanes()[*c].admit_budget, 0);
        }
        if tick % 25 == 0 {
            s.check_invariants().unwrap();
        }
    }

    s.check_invariants().unwrap();
    assert!(long_admitted, "64K request must be promoted and admitted");
    assert_eq!(completed_64k, 1, "64K request must complete cleanly");
    assert!(completed_2k >= 4, "surviving 2K requests must complete");
    assert_eq!(mid_step_cancels, 3, "all 3 mid-step disconnects exercised");
    assert!(max_wait_observed <= w_bound);
    assert_eq!(s.reserved_total(), 0, "zero reservation leak after drain");
    assert_eq!(s.admitted_total(), 0, "zero admission budget leak after drain");
    assert!(
        s.lanes().iter().all(|l| l.state.is_terminal_or_idle()),
        "all lanes drained cleanly"
    );
    // Every remaining in-memory block must be a sealed cold prefix block (zero unsealed tails!).
    assert!(
        s.blocks().values().all(|b| b.sealed && b.tier.is_present()),
        "zero leaked private tail blocks"
    );
}

#[test]
fn serve_step_planner_enforces_starvation_bound_and_cancel_barrier() {
    let mut p = ServeStepPlanner::new(3, 2);
    for l in 0..3 {
        p.on_admit(l);
    }
    // Lane 0 is decoding; lane 1 is prefilling (256 tokens); lane 2 is decoding.
    let inputs = [
        ServeLaneInput { runnable: true, n_past: 64, pf_end: 64, has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: 0, pf_end: 256, has_pending_decode: false },
        ServeLaneInput { runnable: true, n_past: 64, pf_end: 64, has_pending_decode: true },
    ];

    // Step 1: tie at wait_ticks=0 -> decoders win; prefiller wait_ticks becomes 1.
    let plan1 = p.plan_and_begin_step(&inputs, 128, 64).unwrap();
    assert_eq!(plan1, ServeStepPlan::Decode(vec![0, 2]));
    assert_eq!(p.state(0), LaneState::InStep);
    assert_eq!(p.wait_ticks(1), 1);

    // Client 2 disconnects mid-step -> Cancelling, NOT immediately freed!
    assert!(!p.request_cancel(2));
    assert_eq!(p.state(2), LaneState::Cancelling);
    let freed = p.complete_step();
    assert_eq!(freed, vec![2]);
    assert_eq!(p.state(2), LaneState::Cancelled);
    assert_eq!(p.state(0), LaneState::Ready);

    // Step 2: lane 1 wait_ticks=1 < W=2 -> decoder bursts a 2nd step; prefiller hits W=2.
    let inputs2 = [
        ServeLaneInput { runnable: true, n_past: 65, pf_end: 64, has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: 0, pf_end: 256, has_pending_decode: false },
        ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false },
    ];
    let plan2 = p.plan_and_begin_step(&inputs2, 128, 64).unwrap();
    assert_eq!(plan2, ServeStepPlan::Decode(vec![0]));
    assert_eq!(p.wait_ticks(1), 2);
    assert_eq!(p.wait_ticks(0), 0);
    assert!(p.complete_step().is_empty());

    // Step 3: lane 1 hit ceiling W=2 while lane 0 is at 0 -> prefiller preempts!
    let inputs3 = [
        ServeLaneInput { runnable: true, n_past: 66, pf_end: 64, has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: 0, pf_end: 256, has_pending_decode: false },
        ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false },
    ];
    let plan3 = p.plan_and_begin_step(&inputs3, 128, 64).unwrap();
    assert_eq!(plan3, ServeStepPlan::Prefill(vec![(1, 0, 128)]));
    assert_eq!(p.wait_ticks(1), 0);
    assert_eq!(p.wait_ticks(0), 1);
    assert!(p.complete_step().is_empty());
}

#[test]
fn serve_step_planner_bursts_w_decodes_before_yielding_to_prefill() {
    let w = 16u32;
    let mut p = ServeStepPlanner::new(3, w);
    for l in 0..3 {
        p.on_admit(l);
    }
    let mut n_past = [64usize, 64, 0];
    let pf_end = [64usize, 64, 8192];

    // Round 1: decoders burst W=16 consecutive 1-token steps while prefiller waits 1..=16.
    for step in 1..=w {
        let inputs = [
            ServeLaneInput { runnable: true, n_past: n_past[0], pf_end: pf_end[0], has_pending_decode: true },
            ServeLaneInput { runnable: true, n_past: n_past[1], pf_end: pf_end[1], has_pending_decode: true },
            ServeLaneInput { runnable: true, n_past: n_past[2], pf_end: pf_end[2], has_pending_decode: false },
        ];
        let plan = p.plan_and_begin_step(&inputs, 4096, 64).unwrap();
        assert_eq!(plan, ServeStepPlan::Decode(vec![0, 1]), "step {step} must burst decode");
        assert_eq!(p.wait_ticks(2), step);
        assert_eq!(p.wait_ticks(0), 0);
        assert_eq!(p.wait_ticks(1), 0);
        n_past[0] += 1;
        n_past[1] += 1;
        assert!(p.complete_step().is_empty());
    }

    // Step W+1: prefiller reached W=16 -> prefill preempts for 1 step.
    let inputs = [
        ServeLaneInput { runnable: true, n_past: n_past[0], pf_end: pf_end[0], has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: n_past[1], pf_end: pf_end[1], has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: n_past[2], pf_end: pf_end[2], has_pending_decode: false },
    ];
    let plan = p.plan_and_begin_step(&inputs, 4096, 64).unwrap();
    assert_eq!(plan, ServeStepPlan::Prefill(vec![(2, 0, 4096)]));
    assert_eq!(p.wait_ticks(2), 0);
    assert_eq!(p.wait_ticks(0), 1);
    assert_eq!(p.wait_ticks(1), 1);
    n_past[2] += 4096;
    assert!(p.complete_step().is_empty());

    // Round 2: decoders immediately burst another W=16 steps before the remaining prefill runs.
    for step in 1..=w {
        let inputs = [
            ServeLaneInput { runnable: true, n_past: n_past[0], pf_end: pf_end[0], has_pending_decode: true },
            ServeLaneInput { runnable: true, n_past: n_past[1], pf_end: pf_end[1], has_pending_decode: true },
            ServeLaneInput { runnable: true, n_past: n_past[2], pf_end: pf_end[2], has_pending_decode: false },
        ];
        let plan = p.plan_and_begin_step(&inputs, 4096, 64).unwrap();
        assert_eq!(plan, ServeStepPlan::Decode(vec![0, 1]), "round 2 step {step} must burst decode");
        assert_eq!(p.wait_ticks(2), step);
        n_past[0] += 1;
        n_past[1] += 1;
        assert!(p.complete_step().is_empty());
    }
    let inputs = [
        ServeLaneInput { runnable: true, n_past: n_past[0], pf_end: pf_end[0], has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: n_past[1], pf_end: pf_end[1], has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: n_past[2], pf_end: pf_end[2], has_pending_decode: false },
    ];
    let plan = p.plan_and_begin_step(&inputs, 4096, 64).unwrap();
    assert_eq!(plan, ServeStepPlan::Prefill(vec![(2, 4096, 4096)]));
    assert!(p.complete_step().is_empty());
}

#[test]
fn serve_step_planner_adversarial_multi_prefill_wait_ticks_bounded() {
    let w = 4u32;
    let nlanes = 12usize;
    let mut p = ServeStepPlanner::new(nlanes, w);
    for l in 0..nlanes {
        p.on_admit(l);
    }
    // Lanes 0..2 are active decoders; lanes 3..11 are 9 heavy prefillers (4096 tokens each)
    // that will all hit wait_ticks == W simultaneously while step_token_budget == 4096.
    let mut n_past = vec![64usize; nlanes];
    let mut pf_end = vec![64usize; nlanes];
    for l in 3..nlanes {
        n_past[l] = 0;
        pf_end[l] = 4096;
    }
    let mut decode_steps = 0usize;
    let mut prefill_steps = 0usize;
    for step in 0..80 {
        let inputs: Vec<ServeLaneInput> = (0..nlanes)
            .map(|l| {
                // Toggle lane 5 backpressure off/on on steps 7..10 to test staggered ceiling ties.
                let bp = l == 5 && (7..=10).contains(&step);
                ServeLaneInput {
                    runnable: !bp && n_past[l] < pf_end[l] + 300,
                    n_past: n_past[l],
                    pf_end: pf_end[l],
                    has_pending_decode: n_past[l] >= pf_end[l],
                }
            })
            .collect();
        let Some(plan) = p.plan_and_begin_step(&inputs, 4096, 64) else {
            break;
        };
        for l in 0..nlanes {
            assert!(p.wait_ticks(l) <= w, "step {step} lane {l} exceeded W={w}: {}", p.wait_ticks(l));
        }
        match plan {
            ServeStepPlan::Decode(lanes) => {
                decode_steps += 1;
                for l in lanes {
                    n_past[l] += 1;
                }
            }
            ServeStepPlan::Prefill(spans) => {
                prefill_steps += 1;
                let total_toks: usize = spans.iter().map(|&(_, _, t)| t).sum();
                assert!(total_toks <= 4096);
                for (l, p0, t) in spans {
                    assert_eq!(p0, n_past[l]);
                    n_past[l] += t;
                }
            }
        }
        assert!(p.complete_step().is_empty());
    }
    assert!(decode_steps > prefill_steps * 2, "decoders must burst between prefill rounds ({decode_steps} dec vs {prefill_steps} pf)");
    for l in 3..nlanes {
        assert!(n_past[l] >= pf_end[l], "prefiller {l} starved: n_past={} < {}", n_past[l], pf_end[l]);
    }
}

#[test]
fn walk_scheduler_trace_satisfies_invariants_across_seeds() {
    let cfg = small_cfg();
    let mut total_cancel = 0;
    let mut total_step_bypass = 0;
    let mut total_slide = 0;
    for seed in 0..8 {
        let (trace, stats) = walk_scheduler_trace(cfg.clone(), seed, 120).unwrap();
        assert!(trace.steps.len() >= 10);
        assert!(stats.max_wait_ticks_seen <= cfg.max_bypass);
        total_cancel += stats.cancel_in_step;
        total_step_bypass += stats.step_bypasses;
        total_slide += stats.slide_windows;
    }
    assert!(total_cancel > 0, "walks must exercise cancel-in-step");
    assert!(total_step_bypass > 0, "walks must exercise step bypass");
    assert!(total_slide > 0, "walks must exercise explicit slide_window");
    let (tr, _) = walk_scheduler_trace(cfg, 0, 60).unwrap();
    let (data, check, tlc_cfg) = render_cache_scheduler_tla_bundle(&[tr]).unwrap();
    assert!(data.contains("MODULE TraceData"));
    assert!(check.contains("InitConforms == (stepIdx = 1) => Init"));
    assert!(check.contains("StepConforms == [][TraceNext]_vars"));
    assert!(check.contains("ActionConforms == [][StepActionCheck]_<<vars, traceIdx, stepIdx>>"));
    assert!(tlc_cfg.contains("BypassBoundHolds"));
    assert!(tlc_cfg.contains("NoDecodeBlocksSealed"));
    assert!(tlc_cfg.contains("ActionConforms"));
}

#[test]
fn multi_block_prefill_span_decode_unsealed_and_start_state_tier() {
    let cfg = SchedulerConfig {
        lanes: vec!["a".into(), "b".into(), "c".into()],
        prefixes: vec!["p1".into(), "p2".into(), "p3".into()],
        request_lengths: vec![6],
        block_size: 2,
        window_size: 2,
        max_pos: 6,
        max_span: 4, // crosses 2 blocks (4 tokens) in a single prefill step (`U56`)!
        step_token_budget: 4,
        mem_budget: 8,
        disk_budget: 6,
        max_queue: 1,
        max_bypass: 2,
        start_point_stride_blocks: 1,
    };
    let mut s = Scheduler::new(cfg).unwrap();
    s.arrive(0, "p1", 6).unwrap();
    s.admit(0).unwrap();
    s.begin_restore(0).unwrap();
    s.finish_restore(0).unwrap();

    // Single prefill step advances 0 -> 4 (`PromptEnd(6) = 4`), sealing BOTH (p1, 2) and (p1, 4)!
    let step = s.build_step().unwrap().unwrap();
    assert_eq!(step.spans[&0], 4);
    // Guard `build_step` on in-flight writeback (`U61`) once step completes.
    s.gpu_execute().unwrap();
    let done = s.complete_step().unwrap();
    assert_eq!(done.sealed_boundaries, vec![(0, 2), (0, 4)]);
    assert!(s.start_points()[&("p1".into(), 2)].kept);
    assert!(s.start_points()[&("p1".into(), 4)].kept);
    assert_eq!(s.start_points()[&("p1".into(), 4)].state_tier, BlockTier::Memory);

    // Slide window at pos 4 (`History(4) = {1}`, pruning block 0) before decode steps 4->5->6.
    assert!(s.slide_window(0));
    for expected_pos in [5u32, 6] {
        s.slide_window(0);
        let dstep = s.build_step().unwrap().unwrap();
        assert_eq!(dstep.spans[&0], 1);
        s.gpu_execute().unwrap();
        let ddone = s.complete_step().unwrap();
        assert!(ddone.sealed_boundaries.is_empty(), "decode blocks must NEVER seal (U58)");
        assert_eq!(s.lanes()[0].pos, expected_pos);
        assert!(!s.start_points().contains_key(&("p1".into(), 6)));
        assert!(matches!(s.lanes()[0].full.get(&2), Some(BlockId::Priv { lane: 0, idx: 2, .. })));
        s.check_invariants().unwrap();
    }
    s.finish_ready(0).unwrap();
    s.check_invariants().unwrap();
}

#[test]
fn serve_step_planner_skips_restoring_lanes_without_blocking_ready_decoders() {
    let mut p = ServeStepPlanner::new(3, 4);
    p.on_admit(0);
    p.admit_queued(1, LaneState::Queued);
    p.start_restore(1);
    p.admit_queued(2, LaneState::Queued);
    p.start_restore(2);
    assert_eq!(p.state(1), LaneState::Restoring);
    assert_eq!(p.state(2), LaneState::Restoring);

    let inputs = [
        ServeLaneInput { runnable: true, n_past: 64, pf_end: 64, has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: 0, pf_end: 1024, has_pending_decode: false },
        ServeLaneInput { runnable: true, n_past: 0, pf_end: 1024, has_pending_decode: false },
    ];
    for _ in 0..6 {
        let plan = p.plan_and_begin_step(&inputs, 4096, 64).unwrap();
        assert_eq!(plan, ServeStepPlan::Decode(vec![0]));
        assert_eq!(p.wait_ticks(1), 0, "Restoring lane must not accrue wait_ticks");
        assert!(p.complete_step().is_empty());
    }

    // Mid-restore cancel immediately transitions Restoring -> Cancelled.
    assert!(p.request_cancel(2));
    assert_eq!(p.state(2), LaneState::Cancelled);

    // Finishing restore transitions Restoring -> Ready so lane 1 joins step planning.
    p.finish_restore(1);
    assert_eq!(p.state(1), LaneState::Ready);
}

// ---- GPU-time share for prefill (`ServeStepPlanner::with_prefill_share`) ----------------

/// Deterministic pseudo-random sequence for synthetic step times (no clock).
fn lcg(seed: &mut u64) -> u64 {
    *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
    *seed >> 33
}

/// One decoder that never finishes and one prompt that never finishes, so every step is contended.
/// Returns the decode and prefill time charged and the longest run of each class.
fn contended_run(share: u32, steps: usize, mut step_us: impl FnMut(bool) -> u64) -> (u64, u64, usize, usize) {
    let w = 16;
    let mut p = ServeStepPlanner::new(2, w).with_prefill_share(share);
    p.on_admit(0);
    p.on_admit(1);
    let (mut n_dec, mut n_pf) = (1usize << 40, 0usize);
    let (mut t_dec, mut t_pf) = (0u64, 0u64);
    let (mut run, mut last, mut max_dec_run, mut max_pf_run) = (0usize, None, 0usize, 0usize);
    for _ in 0..steps {
        let inputs = [
            ServeLaneInput { runnable: true, n_past: n_dec, pf_end: 1, has_pending_decode: true },
            ServeLaneInput { runnable: true, n_past: n_pf, pf_end: 1 << 40, has_pending_decode: false },
        ];
        let plan = p.plan_and_begin_step(&inputs, 4096, 64).unwrap();
        assert!(p.wait_ticks(0) <= w && p.wait_ticks(1) <= w);
        let prefill = matches!(plan, ServeStepPlan::Prefill(_));
        if prefill {
            n_pf += 4096;
        } else {
            n_dec += 1;
        }
        run = if last == Some(prefill) { run + 1 } else { 1 };
        last = Some(prefill);
        if prefill {
            max_pf_run = max_pf_run.max(run);
        } else {
            max_dec_run = max_dec_run.max(run);
        }
        let us = step_us(prefill);
        if prefill {
            t_pf += us;
        } else {
            t_dec += us;
        }
        p.charge_step(us);
        assert!(p.complete_step().is_empty());
    }
    (t_dec, t_pf, max_dec_run, max_pf_run)
}

#[test]
fn serve_step_share_holds_prefill_near_its_target_over_any_window() {
    for share in [35u32, 50, 60, 70, 100] {
        let mut seed = u64::from(share);
        let mut times = Vec::new();
        // Decode steps of 150-200 ms (64 lanes) and prefill chunks of 0.3-1.0 s.
        let (t_dec, t_pf, _, _) = contended_run(share, 4000, |prefill| {
            let us = if prefill { 300_000 + lcg(&mut seed) % 700_000 } else { 150_000 + lcg(&mut seed) % 50_000 };
            times.push((prefill, us));
            us
        });
        let total = (t_dec + t_pf) as f64;
        let got = t_pf as f64 / total;
        if share < 100 {
            assert!((got - f64::from(share) / 100.0).abs() < 0.01, "share {share}: prefill got {got:.3}");
        } else {
            // Decoders still get a step whenever one reaches the ceiling W.
            assert!(got > 0.95, "share 100: prefill got {got:.3}");
        }
        // Over every window the prefill time is the target share to within one step either side
        // (credit stays in [-(100-s) * max prefill step, s * max decode step]; no ceiling fires here).
        if share < 100 {
            let s = f64::from(share) / 100.0;
            let bound = s * 200_000.0 + (1.0 - s) * 1_000_000.0;
            for start in (0..times.len()).step_by(97) {
                let (mut d, mut pf) = (0.0, 0.0);
                for &(prefill, us) in &times[start..] {
                    if prefill {
                        pf += us as f64;
                    } else {
                        d += us as f64;
                    }
                    let lag = s * (d + pf) - pf;
                    assert!(lag.abs() <= bound + 1.0, "share {share}: window from {start} lags by {lag}");
                }
            }
        }
    }
}

#[test]
fn serve_step_share_zero_keeps_the_tick_policy() {
    // Share 0: sixteen decodes, then one prefill, whatever the step times.
    let mut seed = 7;
    let mut p = ServeStepPlanner::new(2, 16);
    p.on_admit(0);
    p.on_admit(1);
    for step in 0..170 {
        let inputs = [
            ServeLaneInput { runnable: true, n_past: 10 + step, pf_end: 1, has_pending_decode: true },
            ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 40, has_pending_decode: false },
        ];
        let plan = p.plan_and_begin_step(&inputs, 4096, 64).unwrap();
        assert_eq!(matches!(plan, ServeStepPlan::Prefill(_)), step % 17 == 16, "step {step}");
        p.charge_step(lcg(&mut seed) % 2_000_000);
        p.complete_step();
    }
}

#[test]
fn serve_step_share_never_starves_either_class() {
    // Decode steps that take no time against 4 s prefill chunks, and the reverse: the share
    // alone would give one class every step; the W ceiling still serves the other.
    for (share, dec_us, pf_us) in [(60, 0, 8_000_000), (60, 8_000_000, 0), (100, 1, 1), (1, 1, 4_000_000), (99, 4_000_000, 1)] {
        let (_, _, max_dec_run, max_pf_run) =
            contended_run(share, 2000, |prefill| if prefill { pf_us } else { dec_us });
        assert!(max_dec_run <= 16, "share {share}: {max_dec_run} decode steps in a row");
        assert!(max_pf_run <= 16, "share {share}: {max_pf_run} prefill steps in a row");
    }
    // Share 100 gives decoders only the ceiling: W prefill steps, then one decode.
    let (_, _, max_dec_run, max_pf_run) = contended_run(100, 340, |_| 1000);
    assert_eq!((max_dec_run, max_pf_run), (1, 16));
}

#[test]
fn serve_step_share_credit_is_charged_clamped_and_reset() {
    let mut p = ServeStepPlanner::new(2, 16).with_prefill_share(60);
    p.on_admit(0);
    p.on_admit(1);
    let both = [
        ServeLaneInput { runnable: true, n_past: 9, pf_end: 1, has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 20, has_pending_decode: false },
    ];
    // Contended with credit 0: prefill is owed first.
    assert!(matches!(p.plan_and_begin_step(&both, 4096, 64), Some(ServeStepPlan::Prefill(_))));
    assert_eq!(p.pending(), Some(StepClass::Prefill));
    p.charge_step(1_000);
    assert_eq!(p.credit(), -40 * 1_000);
    assert_eq!(p.pending(), None);
    p.charge_step(1_000); // no step pending: nothing charged twice
    assert_eq!(p.credit(), -40_000);
    p.complete_step();
    assert!(matches!(p.plan_and_begin_step(&both, 4096, 64), Some(ServeStepPlan::Decode(_))));
    p.charge_step(0); // a step always charges at least 1 us
    assert_eq!(p.credit(), -40_000 + 60);
    p.complete_step();
    assert!(matches!(p.plan_and_begin_step(&both, 4096, 64), Some(ServeStepPlan::Decode(_))));
    p.charge_step(u64::MAX); // charged as one maximal step
    assert_eq!(p.credit(), -40_000 + 60 + 60 * SHARE_CHARGE_CAP_US as i64);
    p.complete_step();
    // Decode alone: no contention, the credit resets and nothing is charged.
    let alone = [both[0], ServeLaneInput { runnable: false, ..both[1] }];
    assert!(matches!(p.plan_and_begin_step(&alone, 4096, 64), Some(ServeStepPlan::Decode(_))));
    assert_eq!((p.credit(), p.pending()), (0, None));
    p.charge_step(5_000);
    assert_eq!(p.credit(), 0);
    p.complete_step();
}

/// A stand-in model whose next token is a function of a lane's whole token history, like the
/// engine's batch-invariant arithmetic (DESIGN Decision 2). A scheduler that skipped, repeated,
/// reordered or mixed a lane's positions would change some request's output.
#[derive(Clone)]
struct HashLane {
    request: usize,
    toks: Vec<u32>,
    n_past: usize,
    pf_end: usize,
    hist: u64,
    out: Vec<u32>,
}

impl HashLane {
    fn feed(&mut self, p0: usize, t: usize) {
        assert_eq!(p0, self.n_past, "request {}: span must start at the lane's position", self.request);
        for &tok in &self.toks[p0..p0 + t] {
            self.hist = (self.hist ^ u64::from(tok)).wrapping_mul(0x100000001b3);
        }
        self.n_past += t;
        if self.n_past >= self.pf_end {
            let next = (self.hist >> 40) as u32 % 50_000;
            self.toks.push(next);
            self.out.push(next);
        }
    }
}

/// Serve `prompts` (arriving at the given steps) on `lanes` lanes and return each request's output.
fn serve_hash_model(prompts: &[(usize, Vec<u32>)], lanes: usize, share: u32, gen: usize, seed: u64) -> Vec<Vec<u32>> {
    let mut seed = seed;
    let mut p = ServeStepPlanner::new(lanes, 16).with_prefill_share(share);
    let mut slot: Vec<Option<HashLane>> = vec![None; lanes];
    let mut outputs = vec![Vec::new(); prompts.len()];
    let mut next_req = 0;
    let mut done = 0;
    let mut step = 0usize;
    while done < prompts.len() {
        for (l, s) in slot.iter_mut().enumerate() {
            if s.is_none() && next_req < prompts.len() && prompts[next_req].0 <= step {
                let toks = prompts[next_req].1.clone();
                *s = Some(HashLane { request: next_req, pf_end: toks.len(), toks, n_past: 0, hist: 0xcbf29ce484222325, out: Vec::new() });
                p.on_admit(l);
                next_req += 1;
            }
        }
        let inputs: Vec<ServeLaneInput> = slot
            .iter()
            .map(|s| match s {
                Some(h) => ServeLaneInput {
                    // Random backpressure, as from a slow client.
                    runnable: !lcg(&mut seed).is_multiple_of(7),
                    n_past: h.n_past,
                    pf_end: h.pf_end,
                    has_pending_decode: h.out.len() < gen,
                },
                None => ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false },
            })
            .collect();
        let budget = 64 + (lcg(&mut seed) % 4) as usize * 256;
        match p.plan_and_begin_step(&inputs, budget, 64) {
            Some(ServeStepPlan::Decode(chosen)) => {
                for i in chosen {
                    let h = slot[i].as_mut().unwrap();
                    h.feed(h.n_past, 1);
                }
                p.charge_step(100_000 + lcg(&mut seed) % 100_000);
            }
            Some(ServeStepPlan::Prefill(spans)) => {
                for (i, p0, t) in spans {
                    slot[i].as_mut().unwrap().feed(p0, t);
                }
                p.charge_step(50_000 + lcg(&mut seed) % 900_000);
            }
            None => {}
        }
        p.complete_step();
        for (l, s) in slot.iter_mut().enumerate() {
            if s.as_ref().is_some_and(|h| h.out.len() >= gen) {
                let h = s.take().unwrap();
                outputs[h.request] = h.out;
                p.on_finish(l);
                done += 1;
            }
        }
        step += 1;
        assert!(step < 1_000_000, "serving did not finish");
    }
    outputs
}

#[test]
fn serve_step_share_only_reorders_work_so_outputs_are_identical() {
    let mut seed = 11u64;
    let prompts: Vec<(usize, Vec<u32>)> = (0..12)
        .map(|r| {
            let len = 1 + (lcg(&mut seed) % 3000) as usize;
            (r * 5, (0..len).map(|_| (lcg(&mut seed) % 50_000) as u32).collect())
        })
        .collect();
    // Solo: one lane, one request at a time, no contention.
    let solo = serve_hash_model(&prompts, 1, 0, 24, 1);
    for (lanes, share, run_seed) in [(4, 0, 2), (4, 60, 3), (8, 35, 4), (8, 100, 5), (3, 60, 6), (12, 70, 7)] {
        assert_eq!(serve_hash_model(&prompts, lanes, share, 24, run_seed), solo, "lanes {lanes} share {share}");
    }
}

#[test]
fn serve_step_share_credit_stays_within_one_capped_step() {
    // Share 1%: one maximal prefill chunk puts the credit at its floor; the ceiling then forces
    // another prefill while the credit is negative, and the credit is clamped, not unbounded.
    let cap = SHARE_CHARGE_CAP_US as i64;
    let mut p = ServeStepPlanner::new(2, 16).with_prefill_share(1);
    p.on_admit(0);
    p.on_admit(1);
    let mut n_dec = 9;
    for step in 0..18 {
        let inputs = [
            ServeLaneInput { runnable: true, n_past: n_dec, pf_end: 1, has_pending_decode: true },
            ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 40, has_pending_decode: false },
        ];
        let prefill = matches!(p.plan_and_begin_step(&inputs, 4096, 64), Some(ServeStepPlan::Prefill(_)));
        assert_eq!(prefill, step == 0 || step == 17, "step {step}");
        n_dec += usize::from(!prefill);
        p.charge_step(if prefill { u64::MAX } else { 1 });
        assert!(p.credit() >= -99 * cap && p.credit() <= cap, "step {step}: credit {}", p.credit());
        p.complete_step();
    }
    assert_eq!(p.credit(), -99 * cap);
}

/// Stella Codex's counterexample on 1da1f05: a 60% target, W = 16, 1 ms prefill chunks
/// against 100 ms decode steps. Sixteen chunks take 16 ms and then the decoder reaches W, so
/// prefill can get only 16 / 116 of the time: the target is infeasible under W. The planner
/// must keep W (the hard guarantee), and the whole shortfall must be the ceiling-forced
/// decode time, reported apart from the share-chosen time.
#[test]
fn serve_step_share_infeasible_under_w_is_bounded_by_the_ceiling() {
    let mut p = ServeStepPlanner::new(2, 16).with_prefill_share(60);
    p.on_admit(0);
    p.on_admit(1);
    let (mut n_dec, mut n_pf, mut run, mut max_pf_run) = (9usize, 0usize, 0usize, 0usize);
    for _ in 0..17_000 {
        let inputs = [
            ServeLaneInput { runnable: true, n_past: n_dec, pf_end: 1, has_pending_decode: true },
            ServeLaneInput { runnable: true, n_past: n_pf, pf_end: 1 << 40, has_pending_decode: false },
        ];
        let prefill = matches!(p.plan_and_begin_step(&inputs, 4096, 64), Some(ServeStepPlan::Prefill(_)));
        assert!(p.wait_ticks(0) <= 16 && p.wait_ticks(1) <= 16);
        run = if prefill { run + 1 } else { 0 };
        max_pf_run = max_pf_run.max(run);
        if prefill {
            n_pf += 4096;
        } else {
            n_dec += 1;
        }
        p.charge_step(if prefill { 1_000 } else { 100_000 });
        p.complete_step();
    }
    let s = p.share_stats();
    assert_eq!(max_pf_run, 16, "the ceiling caps prefill runs at W");
    assert_eq!((s.prefill_wall_us, s.decode_wall_us), (16_000_000, 100_000_000));
    let delivered = s.prefill_wall_us as f64 / (s.prefill_wall_us + s.decode_wall_us) as f64;
    assert!((delivered - 16.0 / 116.0).abs() < 1e-3, "delivered {delivered:.4}");
    // After the first decode (credit still negative from the first chunk), every decode step
    // was forced by the ceiling while prefill was owed time.
    assert_eq!((s.forced_decode_steps, s.forced_decode_wall_us), (999, s.decode_wall_us - 100_000));
    assert_eq!(s.forced_prefill_steps, 0);
    // Leaving out the forced steps, the share-chosen time meets the target trivially, and the
    // shortfall against 60% is explained by forced decode time.
    let shortfall = 0.6 * (s.prefill_wall_us + s.decode_wall_us) as f64 - s.prefill_wall_us as f64;
    assert!(shortfall > 0.0 && shortfall <= s.forced_decode_wall_us as f64 + 100_000.0);
    // Charged time equals wall time here: both are below the cap.
    assert_eq!((s.prefill_charged_us, s.decode_charged_us), (s.prefill_wall_us, s.decode_wall_us));
}

#[test]
fn serve_step_share_stats_separate_wall_from_capped_charge() {
    let mut p = ServeStepPlanner::new(2, 16).with_prefill_share(60);
    p.on_admit(0);
    p.on_admit(1);
    let both = [
        ServeLaneInput { runnable: true, n_past: 9, pf_end: 1, has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 20, has_pending_decode: false },
    ];
    p.plan_and_begin_step(&both, 4096, 64);
    p.charge_step(3 * SHARE_CHARGE_CAP_US);
    let s = p.share_stats();
    assert_eq!((s.prefill_wall_us, s.prefill_charged_us), (3 * SHARE_CHARGE_CAP_US, SHARE_CHARGE_CAP_US));
}

/// Stella Codex's reproducer on 15d7e83: with W = 16 a prefill step at a decoder's 15th bypass
/// left lane 17 at its 16th, the decoder then won at W, and lane 17 was bypassed 17 times in a
/// row while its saturating counter still read 16. The count here is independent of the planner.
#[test]
fn continuous_ready_lane_respects_bypass_limit_after_arrivals() {
    let mut p = ServeStepPlanner::new(64, 16).with_prefill_share(60);
    let mut missed = [0; 64];
    let mut past = [0; 64];
    past[0] = 9;
    for tick in 0..40 {
        if tick == 0 { p.on_admit(0); p.on_admit(1); }
        if tick == 2 { for i in 2..64 { p.on_admit(i); } }
        let inputs: Vec<_> = (0..64).map(|i| ServeLaneInput {
            runnable: i < 2 || tick >= 2, n_past: past[i], pf_end: if i == 0 { 1 } else { 200_000 }, has_pending_decode: i == 0,
        }).collect();
        let mut served = [false; 64];
        let us = match p.plan_and_begin_step(&inputs, 4096, 64).unwrap() {
            ServeStepPlan::Decode(ids) => { for i in ids { served[i] = true; past[i] += 1; } 100_000 }
            ServeStepPlan::Prefill(spans) => { for (i, start, count) in spans { assert_eq!(start, past[i]); served[i] = true; past[i] += count; } 1_000 }
        };
        p.charge_step(us);
        p.complete_step();
        for i in 0..64 {
            if inputs[i].runnable && !served[i] {
                missed[i] += 1;
                assert!(missed[i] <= 16, "tick={tick} lane={i} actual={} recorded={}", missed[i], p.wait_ticks(i));
            } else { missed[i] = 0; }
        }
    }
}

/// A lane in a scripted serve step: prefilling or decoding, and runnable or held back
/// (client backpressure, pool or cache deferral).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Scripted {
    Prefill,
    Decode,
    HeldPrefill,
    HeldDecode,
}

/// One scripted step: its live lanes, and the step time to charge (`None`: failed before charging).
type ScriptStep<'a> = (&'a [(usize, Scripted)], Option<u64>);

/// Run scripted steps through the serve planner and count, independently of `wait_ticks`, the
/// consecutive steps each runnable lane is not served (the `ghost` of specs/ServeStepBypass.tla).
/// Lanes missing from a step are idle; a lane appearing is admitted, one leaving is finished.
/// `charge` is the step time to charge, `None` for a step that failed before charging. Returns
/// the largest run of consecutive bypasses.
fn scripted_bypass_run(w: u32, share: u32, budget: usize, steps: &[ScriptStep]) -> u32 {
    scripted_bypass_run_aligned(w, share, budget, 0, steps)
}

/// The same run with a block alignment (serve passes 64). Prefillers start inside a block on odd
/// lanes, so minimum spans differ by lane.
fn scripted_bypass_run_aligned(w: u32, share: u32, budget: usize, align: usize, steps: &[ScriptStep]) -> u32 {
    const N: usize = 4;
    let mut p = ServeStepPlanner::new(N, w).with_prefill_share(share);
    let mut live = [false; N];
    let mut missed = [0u32; N];
    let mut worst = 0;
    for &(lanes, charge) in steps {
        let mut inputs = [ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false }; N];
        let mut now = [false; N];
        for &(i, lane) in lanes {
            now[i] = true;
            let decoding = matches!(lane, Scripted::Decode | Scripted::HeldDecode);
            inputs[i] = ServeLaneInput {
                runnable: matches!(lane, Scripted::Prefill | Scripted::Decode),
                n_past: if decoding { 64 } else if align > 0 && i % 2 == 1 { 7 * i } else { 0 },
                pf_end: if decoding { 64 } else { 100_000 },
                has_pending_decode: decoding,
            };
        }
        for i in 0..N {
            match (live[i], now[i]) {
                (false, true) => p.on_admit(i),
                (true, false) => p.on_finish(i),
                _ => {}
            }
        }
        live = now;
        let mut served = [false; N];
        match p.plan_and_begin_step(&inputs, budget, align) {
            Some(ServeStepPlan::Decode(ids)) => ids.into_iter().for_each(|i| served[i] = true),
            Some(ServeStepPlan::Prefill(spans)) => spans.into_iter().for_each(|(i, _, _)| served[i] = true),
            None => {}
        }
        if let Some(us) = charge {
            p.charge_step(us);
        }
        p.complete_step();
        for i in 0..N {
            missed[i] = if inputs[i].runnable && !served[i] { missed[i] + 1 } else { 0 };
            worst = worst.max(missed[i]);
            assert!(p.wait_ticks(i) >= missed[i], "lane {i}: counter {} under-counts {}", p.wait_ticks(i), missed[i]);
            assert!(p.wait_ticks(i) <= w, "lane {i}: counter {} passed W = {w}", p.wait_ticks(i));
        }
    }
    worst
}

/// TLC's `BypassOldRule` counterexample (W = 2, four lanes, every lane runnable), replayed on the
/// planner: two prefill steps take one prefiller each while the decoder ages to W, then the decoder
/// wins at W and the second-ranked prefiller is passed over a third time. The fix reserves a token
/// for every prefiller at W - 1 once the decoder is at W - 1, so the second prefill step takes both.
#[test]
fn prefill_at_w_minus_one_is_served_before_the_decoder_reaches_w() {
    use Scripted::*;
    let steps: &[ScriptStep] = &[
        (&[(3, Decode)], Some(1_000)),
        (&[(0, Prefill), (1, Prefill), (2, Prefill), (3, Decode)], None),
        (&[(1, Prefill), (2, Prefill), (3, Decode)], None),
        (&[(2, Prefill), (3, Decode)], None),
        (&[(2, Prefill), (3, Decode)], None),
    ];
    assert_eq!(scripted_bypass_run(2, 60, 2, steps), 2);
}

/// TLC's `BypassOldRuleBackpressure` counterexample (W = 2, three lanes): a decoder held back by
/// backpressure kept its age W while a prefiller aged to W; when it came back, the decoder won
/// and the prefiller was passed over a third time in a row. A held lane is not bypassed, so the
/// planner caps its age at W - 1 and the prefiller at W runs first.
#[test]
fn held_back_lane_cannot_return_at_w_against_a_waiting_lane() {
    use Scripted::*;
    let steps: &[ScriptStep] = &[
        (&[(1, Decode), (2, Prefill)], None),
        (&[(0, Prefill), (1, Decode), (2, Prefill)], Some(1_000)),
        (&[(0, Decode), (1, HeldDecode), (2, Prefill)], Some(1_000)),
        (&[(0, HeldDecode), (1, Decode), (2, Prefill)], Some(1_000)),
        (&[(0, Decode), (1, Decode), (2, Prefill)], Some(1_000)),
    ];
    assert_eq!(scripted_bypass_run(2, 60, 2, steps), 2);
}

/// Random arrivals, finishes and holds at the model's W = 2 and 3 and at production W = 16, for
/// every share: no runnable lane is ever passed over more than W steps in a row, and the counter
/// never under-counts.
#[test]
fn serve_step_bypass_bound_holds_under_random_holds_and_arrivals() {
    random_holds_and_arrivals_stay_within_w(4, 0);
}

/// The same with serve's block alignment, at every kind of budget the server accepts for four
/// lanes: one token per lane, under one block, one block and a part (the budgets where c2a26ce's
/// aligned step left the second prefiller at the ceiling to a 17th bypass), two blocks and a part,
/// and room for every lane's block.
#[test]
fn serve_step_bypass_bound_holds_with_block_alignment_at_every_budget() {
    for budget in [4, 48, 64, 101, 104, 117, 130, 200, 4096] {
        random_holds_and_arrivals_stay_within_w(budget, 64);
    }
}

fn random_holds_and_arrivals_stay_within_w(budget: usize, align: usize) {
    use Scripted::*;
    for (w, share, seed) in [2u32, 3, 16].into_iter().flat_map(|w| [(w, 0u32, 1u64), (w, 35, 2), (w, 60, 3), (w, 100, 4)]) {
        let mut seed = seed;
        let mut lanes: Vec<Option<Scripted>> = vec![None; 4];
        let mut steps = Vec::new();
        for _ in 0..4000 {
            for lane in lanes.iter_mut() {
                let r = lcg(&mut seed) % 64;
                *lane = match (*lane, r) {
                    (None, 0..=3) => Some(Prefill),
                    (None, 4..=5) => Some(Decode),
                    (Some(_), 0) => None,
                    (Some(Prefill | HeldPrefill), 3..=8) => Some(HeldPrefill),
                    (Some(Decode | HeldDecode), 3..=8) => Some(HeldDecode),
                    (Some(HeldPrefill), _) => Some(Prefill),
                    (Some(HeldDecode), _) => Some(Decode),
                    (other, _) => other,
                };
            }
            let charge = (!lcg(&mut seed).is_multiple_of(8)).then(|| lcg(&mut seed) % 200_000);
            steps.push((lanes.iter().enumerate().filter_map(|(i, l)| l.map(|l| (i, l))).collect::<Vec<_>>(), charge));
        }
        let borrowed: Vec<ScriptStep> = steps.iter().map(|(l, c)| (l.as_slice(), *c)).collect();
        assert!(
            scripted_bypass_run_aligned(w, share, budget, align, &borrowed) <= w,
            "W {w} share {share} budget {budget} align {align}"
        );
    }
}

/// The constructed case: W = 16, the tick policy, one decoder and two prefillers that reach the
/// ceiling together, and a step budget of one block and a part (104 tokens, 64-token blocks).
/// c2a26ce gave the first prefiller its block and made the second wait: a 17th bypass in a row.
/// Both are owed this step. The first takes its block, the second what is left (a part-block
/// span), and its next span stops at the block boundary.
#[test]
fn two_prefillers_at_the_ceiling_are_both_served_when_one_block_fits() {
    const W: u32 = 16;
    let mut p = ServeStepPlanner::new(3, W);
    for i in 0..3 {
        p.on_admit(i);
    }
    let mut inputs = [
        ServeLaneInput { runnable: true, n_past: 128, pf_end: 128, has_pending_decode: true },
        ServeLaneInput { runnable: true, n_past: 64, pf_end: 8_000, has_pending_decode: false },
        ServeLaneInput { runnable: true, n_past: 64, pf_end: 8_000, has_pending_decode: false },
    ];
    for _ in 0..W {
        assert_eq!(p.plan_and_begin_step(&inputs, 104, 64), Some(ServeStepPlan::Decode(vec![0])));
        inputs[0].n_past += 1;
        inputs[0].pf_end += 1;
        p.complete_step();
    }
    assert_eq!((p.wait_ticks(1), p.wait_ticks(2)), (W, W), "both prefillers are at the ceiling");
    let plan = p.plan_and_begin_step(&inputs, 104, 64);
    assert_eq!(plan, Some(ServeStepPlan::Prefill(vec![(1, 64, 64), (2, 64, 40)])));
    p.complete_step();
    assert_eq!((p.wait_ticks(1), p.wait_ticks(2)), (0, 0), "neither was passed over a 17th time");
    assert!((0..3).all(|i| p.wait_ticks(i) <= W));
    // The lane left inside a block realigns: its next span stops at the boundary.
    inputs[1].n_past += 64;
    inputs[2].n_past += 40;
    inputs[0].runnable = false;
    let plan = p.plan_and_begin_step(&inputs, 104, 64);
    assert_eq!(plan, Some(ServeStepPlan::Prefill(vec![(1, 128, 64), (2, 104, 24)])));
}

/// Stella Codex's three-lane W = 1 counterexample on 15d7e83 (TLC's `BypassOldRuleW1`): the
/// tick policy preempts for the older prefiller, its long chunk takes the whole budget, the new
/// prefiller is passed over, and then the decoder at W wins against it. At W = 1 the reserve
/// covers every prefiller once a decoder is runnable.
#[test]
fn three_lanes_at_w_one_serve_the_new_prefiller_with_the_old() {
    use Scripted::*;
    let steps: &[ScriptStep] = &[
        (&[(1, Decode), (2, Prefill)], Some(1_000)),
        (&[(0, Prefill), (1, Decode), (2, Prefill)], Some(1_000)),
        (&[(0, Prefill), (1, Decode)], Some(1_000)),
        (&[(0, Prefill), (1, Decode)], Some(1_000)),
    ];
    assert_eq!(scripted_bypass_run(1, 0, 2, steps), 1);
}

/// Stella Codex's arrivals workload from her oracle (W = 16, 64 lanes, share 60%, the other
/// 62 prefillers arriving at tick 2) at a given token budget. Returns the first
/// `(tick, lane, bypasses)` past W, if any, counted independently of `wait_ticks`.
fn arrivals_first_overrun(budget: usize) -> Option<(usize, usize, u32)> {
    const LANES: usize = 64;
    let mut p = ServeStepPlanner::new(LANES, 16).with_prefill_share(60);
    let mut ready = [false; LANES];
    let mut missed = [0u32; LANES];
    let mut past = [0usize; LANES];
    past[0] = 9;
    for tick in 0..72 {
        for (i, r) in ready.iter_mut().enumerate() {
            if (i < 2 && tick == 0) || (i >= 2 && tick == 2) {
                p.on_admit(i);
                *r = true;
            }
        }
        let inputs: Vec<_> = (0..LANES)
            .map(|i| ServeLaneInput {
                runnable: ready[i],
                n_past: past[i],
                pf_end: if i == 0 { 1 } else { 2_000_000 },
                has_pending_decode: i == 0,
            })
            .collect();
        let mut served = [false; LANES];
        let us = match p.plan_and_begin_step(&inputs, budget, 64).unwrap() {
            ServeStepPlan::Decode(ids) => {
                for i in ids {
                    served[i] = true;
                    past[i] += 1;
                }
                100_000
            }
            ServeStepPlan::Prefill(spans) => {
                for (i, start, count) in spans {
                    assert_eq!(start, past[i]);
                    served[i] = true;
                    past[i] += count;
                }
                1_000
            }
        };
        p.charge_step(us);
        p.complete_step();
        for i in 0..LANES {
            missed[i] = if ready[i] && !served[i] { missed[i] + 1 } else { 0 };
            if missed[i] > 16 {
                return Some((tick, i, missed[i]));
            }
        }
    }
    None
}

/// Stella Codex's re-review of d4d5544. The bound holds when the budget covers one token for
/// every runnable lane, aligned or not (`BypassSmallBudget` in ServeStepBypass.tla is the witness
/// below that); serve refuses more lanes than its chunk (`check_lanes_within_chunk`). A budget of
/// 32 is below the 64 lanes, and lane 48 is bypassed 17 times. A budget of 64 is one token per
/// lane and one block: c2a26ce's aligned step served one prefiller per step there and bypassed
/// lane 17 seventeen times; the owed lanes now share the block. A budget of 4096 gives every
/// prefiller a block.
#[test]
fn chunk_smaller_than_the_lanes_is_outside_the_bypass_bound() {
    assert_eq!(arrivals_first_overrun(32), Some((18, 48, 17)));
    assert_eq!(arrivals_first_overrun(64), None);
    assert_eq!(arrivals_first_overrun(104), None);
    assert_eq!(arrivals_first_overrun(4096), None);
}

fn decoding() -> ServeLaneInput {
    ServeLaneInput { runnable: true, n_past: 100, pf_end: 100, has_pending_decode: true }
}

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

/// A lane the planner picks but serve then leaves unserved (its `ensure_span_blocks` hit pool
/// pressure) keeps its place in line: the next plan that picks it lists it first, so serve offers
/// it blocks before the lanes that ran. Its counter stays as the plan left it.
#[test]
fn a_lane_left_unserved_is_listed_first_until_a_step_serves_it() {
    let mut p = ServeStepPlanner::new(3, 4);
    for i in 0..3 {
        p.on_admit(i);
    }
    let dec = [decoding(); 3];
    assert_eq!(p.plan_and_begin_step(&dec, 4096, 64), Some(ServeStepPlan::Decode(vec![0, 1, 2])));
    p.unserve(2);
    p.complete_step();
    assert!(p.is_owed(2));
    assert_eq!(p.wait_ticks(2), 0, "the pool held it back, not the planner: no bypass is counted");
    // Pool-deferred, it sits the next step out and stays owed.
    let held = [decoding(), decoding(), ServeLaneInput { runnable: false, ..decoding() }];
    assert_eq!(p.plan_and_begin_step(&held, 4096, 64), Some(ServeStepPlan::Decode(vec![0, 1])));
    p.complete_step();
    assert!(p.is_owed(2));
    // Woken, it is offered blocks first; once a step serves it, the order is the planner's again.
    assert_eq!(p.plan_and_begin_step(&dec, 4096, 64), Some(ServeStepPlan::Decode(vec![2, 0, 1])));
    p.complete_step();
    assert!(!p.is_owed(2));
    assert_eq!(p.plan_and_begin_step(&dec, 4096, 64), Some(ServeStepPlan::Decode(vec![0, 1, 2])));
    p.complete_step();
    assert_eq!(p.defer_stats(), DeferStats { unserved_prefill: 0, unserved_decode: 1, owed_first_plans: 1 });
}

/// Prefill spans keep their lengths; only their order changes, and two owed lanes keep the order
/// they were left unserved in.
#[test]
fn owed_prefill_spans_go_first_oldest_first() {
    let mut p = ServeStepPlanner::new(3, 4);
    for i in 0..3 {
        p.on_admit(i);
    }
    let pf = [ServeLaneInput { pf_end: 64, ..prefilling() }; 3];
    let spans = |plan: Option<ServeStepPlan>| match plan {
        Some(ServeStepPlan::Prefill(s)) => s,
        other => panic!("expected prefill, got {other:?}"),
    };
    assert_eq!(spans(p.plan_and_begin_step(&pf, 4096, 64)), vec![(0, 0, 64), (1, 0, 64), (2, 0, 64)]);
    p.unserve(2);
    p.unserve(1);
    p.unserve(1); // a second call for the same lane in the same step changes nothing
    p.complete_step();
    assert_eq!(spans(p.plan_and_begin_step(&pf, 4096, 64)), vec![(2, 0, 64), (1, 0, 64), (0, 0, 64)]);
    p.unserve(1);
    p.complete_step();
    assert!(!p.is_owed(2) && p.is_owed(1));
    assert_eq!(spans(p.plan_and_begin_step(&pf, 4096, 64)), vec![(1, 0, 64), (0, 0, 64), (2, 0, 64)]);
    p.complete_step();
    assert_eq!(p.defer_stats(), DeferStats { unserved_prefill: 3, unserved_decode: 0, owed_first_plans: 2 });
}

/// `unserve` only touches a lane the current plan picked, and a finished, cancelled or readmitted
/// lane is not owed.
#[test]
fn unserve_ignores_lanes_outside_the_step() {
    let mut p = ServeStepPlanner::new(2, 4);
    p.on_admit(0);
    p.on_admit(1);
    let idle = ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false };
    p.plan_and_begin_step(&[decoding(), idle], 4096, 64);
    p.unserve(1);
    assert!(!p.is_owed(1));
    assert_eq!(p.wait_ticks(1), 0);
    assert_eq!(p.state(1), LaneState::Ready);
    p.complete_step();
    assert_eq!(p.state(0), LaneState::Ready);
    p.unserve(0);
    assert!(!p.is_owed(0), "outside a step nothing is unserved");
    assert_eq!(p.defer_stats(), DeferStats::default());

    p.plan_and_begin_step(&[decoding(), decoding()], 4096, 64);
    p.unserve(0);
    p.unserve(1);
    p.complete_step();
    assert!(p.is_owed(0) && p.is_owed(1));
    p.on_finish(0);
    assert!(p.request_cancel(1));
    assert!(!p.is_owed(0) && !p.is_owed(1));
}

/// Serve picks a lane of one class, leaves it unserved and wakes it at once, step after step. The
/// always-runnable lane of the other class must still run within `W` steps (BypassBound in
/// specs/ServeStepDefer.tla). Restoring the deferred lane's age plus one (6ee65d2) let a decoder
/// tie a prefiller at `W`, and the tie goes to decode: `W + 1`.
fn other_class_bypasses(w: u32, share: u32) -> (u32, u32) {
    let mut p = ServeStepPlanner::new(2, w).with_prefill_share(share);
    p.on_admit(0);
    p.on_admit(1);
    let inputs = [decoding(), prefilling()];
    if share > 0 {
        // One share-selected prefill step charged at the cap: the share now prefers decode.
        assert!(matches!(p.plan_and_begin_step(&inputs, 4096, 64), Some(ServeStepPlan::Prefill(_))));
        p.charge_step(SHARE_CHARGE_CAP_US);
        p.complete_step();
    }
    let (mut bypassed, mut max_wait) = (0u32, 0u32);
    while let ServeStepPlan::Decode(lanes) = p.plan_and_begin_step(&inputs, 4096, 64).unwrap() {
        assert_eq!(lanes, vec![0]);
        p.unserve(0); // its block was not there: no GPU step, no charge
        bypassed += 1;
        max_wait = max_wait.max(p.wait_ticks(1));
        p.complete_step();
        assert!(bypassed <= 4 * w + 4, "the prefiller never ran");
    }
    (bypassed, max_wait)
}

#[test]
fn a_lane_unserved_every_step_does_not_hold_the_other_class_past_w() {
    for (w, share) in [(1u32, 0u32), (2, 0), (4, 0), (16, 0), (16, 60)] {
        let (bypassed, max_wait) = other_class_bypasses(w, share);
        assert!(
            bypassed <= w && max_wait <= w,
            "W={w} share={share}: bypassed {bypassed} steps, wait_ticks {max_wait}"
        );
    }
}

/// Steady pool pressure: six prefillers and two decoders, and the pool lets one prefill span
/// through per step; serve leaves the rest unserved and wakes them at once. Deferral is the pool's
/// doing, so it must not move GPU time: prefill keeps its configured share (60%), decode is never
/// held more than one step, and the prefillers take turns. 6ee65d2 counted each deferral as a
/// bypass, the prefillers sat at `W` and the ceiling forced prefill to 84.5% of step time.
#[test]
fn steady_pool_pressure_keeps_the_prefill_share() {
    const W: u32 = 16;
    const NPF: usize = 6;
    let n = NPF + 2;
    let mut p = ServeStepPlanner::new(n, W).with_prefill_share(60);
    let mut inputs = vec![ServeLaneInput { pf_end: 1 << 26, ..prefilling() }; n];
    for i in 0..n {
        p.on_admit(i);
    }
    for input in &mut inputs[NPF..] {
        *input = decoding();
    }
    let (mut pf_us, mut dec_us) = (0u64, 0u64);
    let mut served = [0u64; NPF];
    let (mut dec_gap, mut max_dec_gap, mut max_wait) = (0u32, 0u32, 0u32);
    for _ in 0..6000 {
        match p.plan_with_prefill_limit(&inputs, 4096, 64, 1024).0.unwrap() {
            ServeStepPlan::Prefill(spans) => {
                let (first, _, t) = spans[0];
                inputs[first].n_past += t;
                served[first] += 1;
                for &(i, _, _) in &spans[1..] {
                    p.unserve(i);
                }
                p.charge_step(100_000);
                pf_us += 100_000;
                dec_gap += 1;
                max_dec_gap = max_dec_gap.max(dec_gap);
            }
            ServeStepPlan::Decode(_) => {
                p.charge_step(10_000);
                dec_us += 10_000;
                dec_gap = 0;
            }
        }
        max_wait = (0..n).map(|i| p.wait_ticks(i)).fold(max_wait, u32::max);
        p.complete_step();
    }
    let share = 100.0 * pf_us as f64 / (pf_us + dec_us) as f64;
    assert!((59.0..=61.0).contains(&share), "prefill took {share:.1}% of step time, configured 60%");
    assert_eq!(max_dec_gap, 1, "decode held {max_dec_gap} steps in a row");
    assert!(max_wait <= W, "wait_ticks {max_wait}");
    let (lo, hi) = (served.iter().min().unwrap(), served.iter().max().unwrap());
    assert!(hi - lo <= 1, "prefillers do not take turns: {served:?}");
    assert!(p.defer_stats().owed_first_plans > 0);
}

/// When a step's token budget or `contended_prefill_limit` cannot fit all same-class lanes at equal
/// `wait_ticks`, an owed lane wins the equal-age tie over a lane that just ran, rather than being
/// truncated out of `picked` or starved of leftover prefill tokens.
#[test]
fn owed_lanes_win_equal_age_ties_under_step_budget_caps() {
    // 1. Decode budget cap: 3 decoders, step 1 picks [0, 1, 2] and leaves lane 2 unserved;
    //    step 2 with budget 2 at equal wait_ticks (0) must include owed lane 2 -> [2, 0].
    let mut p = ServeStepPlanner::new(3, 4);
    for i in 0..3 {
        p.on_admit(i);
    }
    let dec = [decoding(); 3];
    assert_eq!(p.plan_and_begin_step(&dec, 3, 64), Some(ServeStepPlan::Decode(vec![0, 1, 2])));
    p.unserve(2);
    p.complete_step();
    assert_eq!(p.plan_and_begin_step(&dec, 2, 64), Some(ServeStepPlan::Decode(vec![2, 0])));
    p.complete_step();
    assert!(!p.is_owed(2));
    assert_eq!(p.defer_stats(), DeferStats { unserved_prefill: 0, unserved_decode: 1, owed_first_plans: 1 });

    // 2. Contended prefill cap (`INK_PREFILL_STEP_CAP`): 2 prefillers + 1 decoder with share 60%.
    //    Step 1 (cap 256) gives lane 0 192 tokens and lane 1 64 tokens, then leaves lane 1 unserved.
    //    Step 2 (cap 256) at equal wait_ticks (0) must give owed lane 1 the 192 tokens and lane 0 64;
    //    and if cap is 64 (room for 1 prefiller), owed lane 1 is picked rather than excluded.
    let mut p2 = ServeStepPlanner::new(3, 4).with_prefill_share(60);
    for i in 0..3 {
        p2.on_admit(i);
    }
    let mut inputs = [prefilling(), prefilling(), decoding()];
    assert_eq!(
        p2.plan_with_prefill_limit(&inputs, 4096, 64, 256).0,
        Some(ServeStepPlan::Prefill(vec![(0, 0, 192), (1, 0, 64)]))
    );
    inputs[0].n_past = 192;
    p2.unserve(1);
    p2.complete_step();
    assert_eq!(
        p2.plan_with_prefill_limit(&inputs, 4096, 64, 256).0,
        Some(ServeStepPlan::Prefill(vec![(1, 0, 192), (0, 192, 64)]))
    );
    p2.unserve(1);
    p2.complete_step();
    assert_eq!(
        p2.plan_with_prefill_limit(&inputs, 4096, 64, 64).0,
        Some(ServeStepPlan::Prefill(vec![(1, 0, 64)]))
    );
    p2.complete_step();
    assert!(!p2.is_owed(1));
}

/// A request serve preempted under pool pressure and admitted again takes the age its old lane had
/// (`unserve`, then `wait_ticks`), capped at `W - 1` like any lane that sat out (`Rested` in
/// specs/ServeStepBypass.tla): it runs within two steps, not `W + 1` steps behind the decoder again.
#[test]
fn resumed_lane_takes_the_age_and_owed_place_of_the_lane_it_left() {
    const W: u32 = 4;
    let mut p = ServeStepPlanner::new(2, W);
    p.on_admit(0);
    p.on_admit(1);
    let prefill = ServeLaneInput { runnable: true, n_past: 0, pf_end: 1 << 16, has_pending_decode: false };
    let decode = ServeLaneInput { runnable: true, n_past: 100, pf_end: 100, has_pending_decode: true };
    let free = ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false };
    // (1) A non-picked deferred lane at age W preempted for another keeps age capped at W - 1 (`Rested`).
    for _ in 0..W {
        assert!(matches!(p.plan_and_begin_step(&[prefill, decode], 4096, 64), Some(ServeStepPlan::Decode(_))));
        p.complete_step();
    }
    let (age, owed) = (p.wait_ticks(0), p.is_owed(0));
    assert_eq!((age, owed), (W, false));
    p.on_finish(0);
    assert_eq!(p.state(0), LaneState::Finished, "the lane is free for the next admission");
    for _ in 0..3 {
        assert!(matches!(p.plan_and_begin_step(&[free, decode], 4096, 64), Some(ServeStepPlan::Decode(_))));
        p.complete_step();
    }
    p.on_admit(0);
    assert_eq!(p.wait_ticks(0), 0);
    p.restore_preempted(0, age, owed);
    assert_eq!(p.wait_ticks(0), W - 1);
    assert!(matches!(p.plan_and_begin_step(&[prefill, decode], 4096, 64), Some(ServeStepPlan::Decode(_))));
    p.complete_step();
    assert!(matches!(p.plan_and_begin_step(&[prefill, decode], 4096, 64), Some(ServeStepPlan::Prefill(_))));
    // A lane that is not `Ready` (here in the step) is left alone.
    p.restore_preempted(0, 2, true);
    assert_eq!((p.wait_ticks(0), p.is_owed(0)), (0, false));
    p.complete_step();

    // (2) A picked lane left unserved (`owed`) and preempted restores its `owed` place in line on its new lane.
    let mut p2 = ServeStepPlanner::new(2, W);
    p2.on_admit(0);
    p2.on_admit(1);
    assert_eq!(
        p2.plan_with_prefill_limit(&[prefill, prefill], 128, 64, 64).0,
        Some(ServeStepPlan::Prefill(vec![(0, 0, 64), (1, 0, 64)]))
    );
    p2.unserve(1);
    let (age2, owed2) = (p2.wait_ticks(1), p2.is_owed(1));
    assert_eq!((age2, owed2), (0, true));
    p2.on_finish(1);
    p2.complete_step();
    p2.on_admit(1);
    p2.restore_preempted(1, age2, owed2);
    assert!(p2.is_owed(1));
    assert_eq!(
        p2.plan_with_prefill_limit(&[prefill, prefill], 64, 64, 64).0,
        Some(ServeStepPlan::Prefill(vec![(1, 0, 64)]))
    );
    p2.complete_step();
}