inky-engine 0.2.2

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple Silicon M5 Macs (Metal 4)
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
---------------------------- MODULE CacheScheduler ----------------------------
\* Coupled model of the block cache and lane scheduler (docs/DESIGN.md,
\* sections "Blocks", "Scheduler", and "Models").
\*
\* Vocabulary matches specs/BlockLayout.tla:
\*   - Kinds == {"full", "window"}: the two cache block kinds;
\*   - BlockSize (B in BlockLayout), WindowSize (W in BlockLayout): positions
\*     per block and sliding-window width in positions;
\*   - Window, History, SpanWindow, Full, SpanBound: exact logical block sets;
\*   - start point, span, pin, sealed block, unsealed tail, memory/disk tiers;
\*   - MaxBypass: the scheduler's bypass bound W covering Ready, Restoring,
\*     and Queued lanes.

EXTENDS Integers, FiniteSets, Sequences, TLC

CONSTANTS
    Lanes,          \* Set of lane slots, e.g. {a, b}
    Prefixes,       \* Set of token prefixes, e.g. {p1, p2}
    RequestLengths, \* Allowed request target lengths, e.g. {2, 4}
    BlockSize,      \* Positions per block (64 in production, 2 here)
    WindowSize,     \* Sliding-window positions (1024 in production, 2 here)
    MaxPos,          \* Maximum context positions (4 or 8 here)
    MaxSpan,         \* Maximum tokens per prefill span (2 here)
    StepTokenBudget, \* Aggregate token budget across all spans in one step
    MemBudget,       \* Memory budget in blocks
    DiskBudget,      \* Disk budget in blocks
    MaxQueue,        \* Queue limit before 429 refusal
    MaxBypass,       \* Bypass bound W for Ready, Restoring, and Queued lanes
    Bug              \* "none" or reversed-witness selector (see ASSUME below)

ASSUME
    /\ BlockSize > 0
    /\ WindowSize >= BlockSize
    /\ MaxPos >= BlockSize
    /\ MaxPos % BlockSize = 0
    /\ RequestLengths # {}
    /\ \A r \in RequestLengths : r \in 1..MaxPos /\ r % BlockSize = 0
    /\ MaxSpan \in 1..BlockSize
    /\ StepTokenBudget >= MaxSpan
    /\ MemBudget >= 2
    /\ DiskBudget >= 2
    /\ MaxQueue >= 0
    /\ MaxBypass >= 1
    /\ Bug \in {
           "none",
           "cancel_in_step",
           "restore_split",
           "boundary_window_dropped",
           "unpruned_window",
           "no_decode_priority",
           "queued_bypass",
           "deferred_tied_429",
           "eager_hot_writeback"
       }

Kinds == {"full", "window"}
Tiers == {"none", "memory", "disk", "both"}
BlkIdx == 0..((MaxPos - 1) \div BlockSize)
Boundaries == {k \in 1..MaxPos : k % BlockSize = 0}
DefaultPrefix == CHOOSE p \in Prefixes : TRUE
DefaultTarget == CHOOSE r \in RequestLengths : TRUE
ProbeLane == CHOOSE l \in Lanes : TRUE

\* Canonical block identifiers:
\*   - TreeIds: sealed blocks in the shared prefix tree, keyed by (prefix, kind, idx);
\*   - PrivIds: private unsealed tail blocks being written by one lane (lane, kind).
TreeIds == {<<"tree", p, k, i>> : p \in Prefixes, k \in Kinds, i \in BlkIdx}
PrivIds == {<<"priv", l, k>> : l \in Lanes, k \in Kinds}
BlockIds == TreeIds \cup PrivIds
NoBlock == <<"none">>

BlockKind(b) == b[3]

\* Logical block-range helpers (identical to specs/BlockLayout.tla).
Ceil(n, d) == (n + d - 1) \div d
SpanBound(c) == Ceil(WindowSize - 1 + c, BlockSize) + 1
Window(lo, hi) == IF hi < lo THEN {} ELSE {p \div BlockSize : p \in lo..hi}
History(n) == Window(IF n > WindowSize THEN n - WindowSize ELSE 0, n - 1)
SpanWindow(n, c) == Window(IF n >= WindowSize THEN n - WindowSize + 1 ELSE 0, n + c - 1)
Full(n) == Window(0, n - 1)

TotalFullBlocks(m) == Cardinality(Full(m))
MaxWinBlocks(m) ==
    LET bound == SpanBound(MaxSpan)
        allW  == Cardinality(Full(m))
    IN IF bound < allW THEN bound ELSE allW
WorstCaseBlocks(m) == TotalFullBlocks(m) + MaxWinBlocks(m)

EmptyData == [i \in 0..(BlockSize - 1) |-> 0]
FullData  == [i \in 0..(BlockSize - 1) |-> 1]
EmptyBlock == [
    tier     |-> "none",
    sealed   |-> FALSE,
    idx      |-> 0,
    length   |-> 0,
    data     |-> EmptyData,
    refCount |-> 0
]
EmptyBlkMap == [i \in BlkIdx |-> NoBlock]
EmptyStart == [
    kept      |-> FALSE,
    stateKept |-> FALSE,
    full      |-> {},
    win       |-> {}
]

LaneLifecycleStates == {
    "Queued", "Admitted", "Restoring", "Ready",
    "InStep", "Cancelling", "Cancelled", "Finished"
}
SlotStates == {"Idle", "Refused"} \cup LaneLifecycleStates
MemHoldingStates == {"Restoring", "Ready", "InStep", "Cancelling"}
AdmittedStates == {"Admitted"} \cup MemHoldingStates
WaitingStates == {"Queued", "Admitted", "Restoring", "Ready"}

RECURSIVE SumBy(_, _)
SumBy(S, f) ==
    IF S = {} THEN 0
    ELSE LET x == CHOOSE v \in S : TRUE IN f[x] + SumBy(S \ {x}, f)

VARIABLES
    blocks,         \* [BlockIds -> BlockRecord]
    startPoints,    \* [Prefixes \X Boundaries -> StartPointRecord]
    laneState,      \* [Lanes -> SlotStates]
    lanePrefix,     \* [Lanes -> Prefixes]
    laneTarget,     \* [Lanes -> RequestLengths]
    lanePos,        \* [Lanes -> 0..MaxPos]
    laneFull,       \* [Lanes -> [BlkIdx -> BlockIds \cup {NoBlock}]]
    laneWin,        \* [Lanes -> [BlkIdx -> BlockIds \cup {NoBlock}]]
    reservation,    \* [Lanes -> 0..MemBudget]
    admitBudget,    \* [Lanes -> 0..MemBudget]
    waitTicks,      \* [Lanes -> 0..(MaxBypass + 1)]
    queueSeq,       \* Seq(Lanes): FIFO arrival order of currently Queued lanes (no duplicates)
    stepActive,     \* BOOLEAN: one step in flight
    stepLanes,      \* Subset of Lanes in the current step
    stepSpan,       \* [Lanes -> 0..MaxSpan]
    stepPins,       \* Subset of BlockIds pinned in memory by the step's spans
    stepIO,         \* Subset of BlockIds with pending disk I/O in this step
    gpuDone         \* BOOLEAN: GPU work of the in-flight step has completed

vars == <<
    blocks, startPoints,
    laneState, lanePrefix, laneTarget, lanePos, laneFull, laneWin,
    reservation, admitBudget, waitTicks, queueSeq,
    stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone
>>

RemoveLane(seq, x) == SelectSeq(seq, LAMBDA y : y # x)
QueueIdx(l)        == CHOOSE i \in 1..Len(queueSeq) : queueSeq[i] = l
OlderQueued(a, b)  == QueueIdx(a) < QueueIdx(b)

\* ---- Derived Queries & Referrer Accounting --------------------------------

InMemory(b) == blocks[b].tier \in {"memory", "both"}
OnDisk(b)   == blocks[b].tier \in {"disk", "both"}
Present(b)  == blocks[b].tier # "none"

MemUsed  == Cardinality({b \in BlockIds : InMemory(b)})
DiskUsed == Cardinality({b \in BlockIds : OnDisk(b)})

LaneBlockSet(f, w) ==
    ({f[i] : i \in BlkIdx} \cup {w[i] : i \in BlkIdx}) \ {NoBlock}

LaneBlocks(l) == LaneBlockSet(laneFull[l], laneWin[l])

OwningLaneStates == AdmittedStates
LaneReferrersOf(b, st, lf, lw) ==
    {<<"lane", l>> : l \in {q \in Lanes : st[q] \in OwningLaneStates /\ b \in LaneBlockSet(lf[q], lw[q])}}

StartReferrersOf(b, sp) ==
    {<<"start", pk[1], pk[2]>> : pk \in {x \in DOMAIN sp :
        sp[x].kept /\ (b \in sp[x].full \/ (Bug # "boundary_window_dropped" /\ b \in sp[x].win))}}

AllReferrersOf(b, st, lf, lw, sp) ==
    LaneReferrersOf(b, st, lf, lw) \cup StartReferrersOf(b, sp)

LaneReferrers(b)  == LaneReferrersOf(b, laneState, laneFull, laneWin)
StartReferrers(b) == StartReferrersOf(b, startPoints)
Referrers(b)      == AllReferrersOf(b, laneState, laneFull, laneWin, startPoints)

SyncRefCounts(blks, st, lf, lw, sp) ==
    [b \in BlockIds |->
        IF blks[b].tier = "none" THEN EmptyBlock
        ELSE LET refs == Cardinality(AllReferrersOf(b, st, lf, lw, sp))
             IN IF ~blks[b].sealed /\ refs = 0 THEN EmptyBlock
                ELSE [blks[b] EXCEPT !.refCount = refs]]

ReservedTotal       == SumBy({l \in Lanes : laneState[l] \in MemHoldingStates}, reservation)
AdmittedTotal       == SumBy({l \in Lanes : laneState[l] \in AdmittedStates}, admitBudget)
QueuedLanes         == {l \in Lanes : laneState[l] = "Queued"}
ReadyLanes          == {l \in Lanes : laneState[l] = "Ready"}
RestoringLanes      == {l \in Lanes : laneState[l] = "Restoring"}
ActiveRestoring     == {r \in RestoringLanes : \E rb \in LaneBlocks(r) : blocks[rb].tier = "disk"}
SteppableReady      == {l \in ReadyLanes : lanePos[l] < laneTarget[l]}

\* Positions below PromptEnd(t) are prompt prefill (spans up to MaxSpan);
\* positions at or above PromptEnd(t) are token-by-token decode (1-token spans).
PromptEnd(t)    == IF t > BlockSize THEN t - BlockSize ELSE 0
IsPrefilling(l) == laneState[l] = "Ready" /\ lanePos[l] < PromptEnd(laneTarget[l])
IsDecoding(l)   == laneState[l] = "Ready" /\ lanePos[l] >= PromptEnd(laneTarget[l]) /\ lanePos[l] < laneTarget[l]

NeedAllocMap == [l \in Lanes |->
    IF laneState[l] = "Ready" /\ lanePos[l] < laneTarget[l]
    THEN (IF laneFull[l][lanePos[l] \div BlockSize] = NoBlock THEN 1 ELSE 0) +
         (IF laneWin[l][lanePos[l] \div BlockSize] = NoBlock THEN 1 ELSE 0)
    ELSE 0]

CurrentWorkingSet(l) ==
    Cardinality(LaneBlocks(l)) +
        (IF lanePos[l] < laneTarget[l] THEN
            (IF laneFull[l][lanePos[l] \div BlockSize] = NoBlock THEN 1 ELSE 0) +
            (IF laneWin[l][lanePos[l] \div BlockSize] = NoBlock THEN 1 ELSE 0)
         ELSE 0)

ColdMemBlocks ==
    {b \in BlockIds : InMemory(b) /\ LaneReferrers(b) = {} /\ b \notin stepIO}

ColdDiskBlocks ==
    {b \in BlockIds : OnDisk(b) /\ LaneReferrers(b) = {} /\ b \notin stepIO}

MatchingBoundaries(p, maxP) ==
    {k \in Boundaries : k <= maxP /\ startPoints[<<p, k>>].kept}

BestBoundary(p, maxP) ==
    LET ms == MatchingBoundaries(p, maxP)
    IN IF ms = {} THEN 0
       ELSE CHOOSE k \in ms : \A j \in ms : k >= j

\* ---- Initial State --------------------------------------------------------

Init ==
    /\ blocks      = [b \in BlockIds |-> EmptyBlock]
    /\ startPoints = [pk \in Prefixes \X Boundaries |-> EmptyStart]
    /\ laneState   = [l \in Lanes |-> "Idle"]
    /\ lanePrefix  = [l \in Lanes |-> DefaultPrefix]
    /\ laneTarget  = [l \in Lanes |-> DefaultTarget]
    /\ lanePos     = [l \in Lanes |-> 0]
    /\ laneFull    = [l \in Lanes |-> EmptyBlkMap]
    /\ laneWin     = [l \in Lanes |-> EmptyBlkMap]
    /\ reservation = [l \in Lanes |-> 0]
    /\ admitBudget = [l \in Lanes |-> 0]
    /\ waitTicks   = [l \in Lanes |-> 0]
    /\ queueSeq    = << >>
    /\ stepActive  = FALSE
    /\ stepLanes   = {}
    /\ stepSpan    = [l \in Lanes |-> 0]
    /\ stepPins    = {}
    /\ stepIO      = {}
    /\ gpuDone     = FALSE

\* ---- Request Arrival, Queueing, Admission & 429 Refusal -------------------

DiskStartCount(p, maxP) ==
    LET k == BestBoundary(p, maxP)
    IN IF k = 0 THEN 0
       ELSE Cardinality({b \in startPoints[<<p, k>>].full \cup startPoints[<<p, k>>].win : blocks[b].tier = "disk"})

CanFitRequest(p, reqLen) ==
    LET wc       == WorstCaseBlocks(reqLen)
        splitBug == Bug = "restore_split" /\ DiskStartCount(p, reqLen) >= 2
    IN IF splitBug
       THEN AdmittedTotal + 1 <= MemBudget
       ELSE AdmittedTotal + wc <= MemBudget

CanFitAdmit(l) == CanFitRequest(lanePrefix[l], laneTarget[l])

CanAdmitNow(l) ==
    /\ CanFitAdmit(l)
    \* Longest-waiting fitting Queued lane first, with FIFO arrival order (queueSeq)
    \* breaking ties; once any older Queued lane hits MaxBypass, no younger arrival
    \* may leapfrog it (even if both are clamped at MaxBypass).
    /\ \A q \in (QueuedLanes \ {l}) :
           CanFitAdmit(q) =>
               (waitTicks[l] > waitTicks[q] \/ (waitTicks[l] = waitTicks[q] /\ OlderQueued(l, q)))
    /\ \A q \in (QueuedLanes \ {l}) :
           waitTicks[q] >= MaxBypass =>
               (OlderQueued(l, q) \/ waitTicks[l] > waitTicks[q])

CanAdvanceAdmitted(l) ==
    /\ laneState[l] = "Admitted"
    /\ (   (Bug = "restore_split" /\ DiskStartCount(lanePrefix[l], laneTarget[l]) >= 2)
        \/ ReservedTotal + WorstCaseBlocks(laneTarget[l]) <= MemBudget)

CanAdvanceRestoring(l) ==
    /\ laneState[l] = "Restoring"
    /\ (   \A b \in LaneBlocks(l) : InMemory(b)
        \/ MemUsed < MemBudget
        \/ ColdMemBlocks # {})

\* Waiting lanes across Ready, Restoring, Admitted, and Queued that can advance
\* without waiting for running lanes to finish and release admission budget;
\* passing any of them over in BuildStep consumes one tick of its MaxBypass budget.
ActionableWaiting ==
    SteppableReady
        \cup {l \in Lanes : CanAdvanceAdmitted(l)}
        \cup {l \in Lanes : CanAdvanceRestoring(l)}
        \cup {q \in QueuedLanes : CanAdmitNow(q)}

StepBypassed(chosen) == ActionableWaiting \ chosen

\* Atomic arrival capacity check (matching serve.rs): requests within MaxQueue
\* enqueue into "Queued" (and when MaxQueue is reached, a fitting request that
\* respects queued bypass bounds admits directly); requests beyond capacity or
\* over MemBudget receive immediate HTTP 429 ("Refused") without entering "Queued".
Arrive(l, p, reqLen) ==
    /\ laneState[l] \in {"Idle", "Refused", "Cancelled", "Finished"}
    /\ p \in Prefixes
    /\ reqLen \in RequestLengths
    /\ IF Bug = "deferred_tied_429"
       THEN /\ laneState'   = [laneState EXCEPT ![l] = "Queued"]
            /\ lanePrefix'  = [lanePrefix EXCEPT ![l] = p]
            /\ laneTarget'  = [laneTarget EXCEPT ![l] = reqLen]
            /\ lanePos'     = [lanePos EXCEPT ![l] = 0]
            /\ laneFull'    = [laneFull EXCEPT ![l] = EmptyBlkMap]
            /\ laneWin'     = [laneWin EXCEPT ![l] = EmptyBlkMap]
            /\ reservation' = [reservation EXCEPT ![l] = 0]
            /\ admitBudget' = [admitBudget EXCEPT ![l] = 0]
            /\ waitTicks'   = [waitTicks EXCEPT ![l] = 0]
            /\ queueSeq'    = Append(queueSeq, l)
       ELSE LET wc       == WorstCaseBlocks(reqLen)
                splitBug == Bug = "restore_split" /\ DiskStartCount(p, reqLen) >= 2
                canEnqueue == wc <= MemBudget /\ Cardinality(QueuedLanes) < MaxQueue
                canDirectAdmit ==
                    /\ wc <= MemBudget
                    /\ Cardinality(QueuedLanes) = MaxQueue
                    /\ CanFitRequest(p, reqLen)
                    /\ \A q \in QueuedLanes : ~CanFitAdmit(q) /\ waitTicks[q] < MaxBypass
            IN IF canEnqueue
               THEN /\ laneState'   = [laneState EXCEPT ![l] = "Queued"]
                    /\ lanePrefix'  = [lanePrefix EXCEPT ![l] = p]
                    /\ laneTarget'  = [laneTarget EXCEPT ![l] = reqLen]
                    /\ lanePos'     = [lanePos EXCEPT ![l] = 0]
                    /\ laneFull'    = [laneFull EXCEPT ![l] = EmptyBlkMap]
                    /\ laneWin'     = [laneWin EXCEPT ![l] = EmptyBlkMap]
                    /\ reservation' = [reservation EXCEPT ![l] = 0]
                    /\ admitBudget' = [admitBudget EXCEPT ![l] = 0]
                    /\ waitTicks'   = [waitTicks EXCEPT ![l] = 0]
                    /\ queueSeq'    = Append(queueSeq, l)
               ELSE IF canDirectAdmit
               THEN /\ laneState'   = [laneState EXCEPT ![l] = "Admitted"]
                    /\ lanePrefix'  = [lanePrefix EXCEPT ![l] = p]
                    /\ laneTarget'  = [laneTarget EXCEPT ![l] = reqLen]
                    /\ lanePos'     = [lanePos EXCEPT ![l] = 0]
                    /\ laneFull'    = [laneFull EXCEPT ![l] = EmptyBlkMap]
                    /\ laneWin'     = [laneWin EXCEPT ![l] = EmptyBlkMap]
                    /\ reservation' = [reservation EXCEPT ![l] = 0]
                    /\ admitBudget' = [admitBudget EXCEPT ![l] = IF splitBug THEN 1 ELSE wc]
                    /\ waitTicks'   = [q \in Lanes |->
                                        IF q = l THEN 0
                                        ELSE IF q \in QueuedLanes THEN waitTicks[q] + 1
                                        ELSE waitTicks[q]]
                    /\ UNCHANGED queueSeq
               ELSE /\ laneState'   = [laneState EXCEPT ![l] = "Refused"]
                    /\ lanePrefix'  = [lanePrefix EXCEPT ![l] = DefaultPrefix]
                    /\ laneTarget' = [laneTarget EXCEPT ![l] = DefaultTarget]
                    /\ lanePos'     = [lanePos EXCEPT ![l] = 0]
                    /\ laneFull'    = [laneFull EXCEPT ![l] = EmptyBlkMap]
                    /\ laneWin'     = [laneWin EXCEPT ![l] = EmptyBlkMap]
                    /\ reservation' = [reservation EXCEPT ![l] = 0]
                    /\ admitBudget' = [admitBudget EXCEPT ![l] = 0]
                    /\ waitTicks'   = [waitTicks EXCEPT ![l] = 0]
                    /\ UNCHANGED queueSeq
    /\ UNCHANGED <<blocks, startPoints, stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

\* Reversed-witness action only (Bug = "deferred_tied_429"): models deferred overflow
\* queueing where tied waitTicks can retroactively 429 an already-queued request.
Refuse429(l) ==
    /\ Bug = "deferred_tied_429"
    /\ laneState[l] = "Queued"
    /\ ~CanAdmitNow(l)
    /\ \/ WorstCaseBlocks(laneTarget[l]) > MemBudget
       \/ /\ Cardinality(QueuedLanes) > MaxQueue
          /\ \A q \in QueuedLanes : waitTicks[l] <= waitTicks[q]
    /\ laneState'  = [laneState EXCEPT ![l] = "Refused"]
    /\ lanePrefix' = [lanePrefix EXCEPT ![l] = DefaultPrefix]
    /\ laneTarget' = [laneTarget EXCEPT ![l] = DefaultTarget]
    /\ lanePos'    = [lanePos EXCEPT ![l] = 0]
    /\ waitTicks'  = [waitTicks EXCEPT ![l] = 0]
    /\ queueSeq'   = RemoveLane(queueSeq, l)
    /\ UNCHANGED <<blocks, startPoints, laneFull, laneWin, reservation, admitBudget,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

Admit(l) ==
    /\ laneState[l] = "Queued"
    /\ CanAdmitNow(l)
    /\ LET wc       == WorstCaseBlocks(laneTarget[l])
           splitBug == Bug = "restore_split" /\ DiskStartCount(lanePrefix[l], laneTarget[l]) >= 2
           bypassed == {q \in (QueuedLanes \ {l}) :
                            OlderQueued(q, l) /\ waitTicks[q] < MaxBypass}
       IN /\ laneState'   = [laneState EXCEPT ![l] = "Admitted"]
          /\ admitBudget' = [admitBudget EXCEPT ![l] = IF splitBug THEN 1 ELSE wc]
          \* Preserve waitTicks[l] across Queued -> Admitted so queued age carries forward.
          /\ waitTicks'   = [q \in Lanes |->
                                IF q = l THEN waitTicks[l]
                                ELSE IF q \in bypassed THEN waitTicks[q] + 1
                                ELSE waitTicks[q]]
          /\ queueSeq'    = RemoveLane(queueSeq, l)
    /\ UNCHANGED <<blocks, startPoints, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, reservation,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

\* ---- Prefix Matching & Atomic Working-Set Reservation (Restoring) ---------

BeginRestore(l) ==
    /\ laneState[l] = "Admitted"
    /\ LET p        == lanePrefix[l]
           wc       == WorstCaseBlocks(laneTarget[l])
           k        == BestBoundary(p, laneTarget[l])
           sp       == IF k = 0 THEN EmptyStart ELSE startPoints[<<p, k>>]
           diskCnt  == Cardinality({b \in sp.full \cup sp.win : blocks[b].tier = "disk"})
           splitBug == Bug = "restore_split" /\ diskCnt >= 2
           nf       == [i \in BlkIdx |->
                         IF \E b \in sp.full : b[4] = i
                         THEN CHOOSE b \in sp.full : b[4] = i
                         ELSE NoBlock]
           nw       == [i \in BlkIdx |->
                         IF \E b \in sp.win : b[4] = i
                         THEN CHOOSE b \in sp.win : b[4] = i
                         ELSE NoBlock]
           res      == IF splitBug
                       THEN Cardinality({b \in sp.full \cup sp.win : InMemory(b)})
                       ELSE wc
           nst      == [laneState EXCEPT ![l] = "Restoring"]
           nlf      == [laneFull EXCEPT ![l] = nf]
           nlw      == [laneWin EXCEPT ![l] = nw]
       IN /\ (splitBug \/ ReservedTotal + res <= MemBudget)
          /\ laneState'   = nst
          /\ lanePos'     = [lanePos EXCEPT ![l] = k]
          /\ laneFull'    = nlf
          /\ laneWin'     = nlw
          /\ reservation' = [reservation EXCEPT ![l] = res]
          /\ blocks'      = SyncRefCounts(blocks, nst, nlf, nlw, startPoints)
    \* Preserve waitTicks[l] across Admitted -> Restoring so queued age carries forward.
    /\ UNCHANGED <<startPoints, lanePrefix, laneTarget, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

RestoreBlock(l, b) ==
    /\ laneState[l] = "Restoring"
    /\ b \in LaneBlocks(l)
    /\ blocks[b].tier = "disk"
    /\ MemUsed < MemBudget
    \* Longest-waiting restoring lane reads first; waitTicks counts bypassed step ticks
    \* and stays intact across Restoring -> Ready until the lane joins BuildStep.
    /\ \A r \in ActiveRestoring : waitTicks[l] >= waitTicks[r]
    /\ blocks' = [blocks EXCEPT ![b].tier = "both"]
    /\ reservation' = [reservation EXCEPT ![l] =
                        IF Bug = "restore_split" /\ @ < WorstCaseBlocks(laneTarget[l])
                        THEN @ + 1
                        ELSE @]
    /\ UNCHANGED <<startPoints, laneState, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

FinishRestore(l) ==
    /\ laneState[l] = "Restoring"
    /\ \A b \in LaneBlocks(l) : InMemory(b)
    /\ laneState' = [laneState EXCEPT ![l] = "Ready"]
    \* Preserve waitTicks[l] across Restoring -> Ready so waiting age carries into BuildStep.
    /\ UNCHANGED <<blocks, startPoints, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, reservation, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

\* ---- Lazy Spill & Tier Eviction Under Memory / Disk Pressure --------------

MemPressure ==
    /\ ColdMemBlocks # {}
    /\ \/ (MemUsed >= MemBudget /\ \E l \in RestoringLanes : \E b \in LaneBlocks(l) : ~InMemory(b))
       \/ (SteppableReady # {} /\ MemUsed + SumBy(SteppableReady, NeedAllocMap) > MemBudget)

EvictCleanOrUnrefMem ==
    /\ MemPressure
    /\ \E b \in {d \in ColdMemBlocks : OnDisk(d) \/ blocks[d].refCount = 0} :
        LET nextTier == IF blocks[b].refCount = 0 /\ ~OnDisk(b) THEN "none" ELSE "disk"
        IN blocks' = [blocks EXCEPT ![b] =
                        IF nextTier = "none" THEN EmptyBlock
                        ELSE [@ EXCEPT !.tier = "disk"]]
    /\ UNCHANGED <<startPoints, laneState, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, reservation, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

\* Cold tree blocks (LaneReferrers = {}) are written to SSD lazily ONLY under
\* MemPressure and dropped from memory once on disk. Victim selection among
\* eligible cold blocks uses nondeterministic \E choice, soundly over-approximating
\* production LRU order without recency-timestamp state explosion.
StartColdWriteback ==
    /\ stepIO = {}
    /\ MemPressure
    /\ {b \in ColdMemBlocks : OnDisk(b) \/ blocks[b].refCount = 0} = {}
    /\ DiskUsed < DiskBudget
    /\ \E b \in {d \in ColdMemBlocks : blocks[d].tier = "memory" /\ blocks[d].sealed} :
        stepIO' = {b}
    /\ UNCHANGED <<blocks, startPoints, laneState, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, reservation, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, gpuDone>>

ReclaimColdDisk ==
    /\ DiskUsed + Cardinality(stepIO) >= DiskBudget
    /\ (MemPressure \/ \E b \in ColdDiskBlocks : blocks[b].refCount = 0)
    /\ \/ /\ \E b \in {d \in ColdDiskBlocks : blocks[d].refCount = 0} :
                LET nextTier == IF InMemory(b) THEN "memory" ELSE "none"
                IN blocks' = [blocks EXCEPT ![b] =
                                IF nextTier = "none" THEN EmptyBlock
                                ELSE [@ EXCEPT !.tier = "memory"]]
          /\ UNCHANGED startPoints
       \/ /\ ~\E b \in ColdDiskBlocks : blocks[b].refCount = 0
          /\ \E pk \in DOMAIN startPoints :
                /\ startPoints[pk].kept
                /\ ((startPoints[pk].full \cup startPoints[pk].win) \cap stepIO) = {}
                /\ \E b \in startPoints[pk].full \cup startPoints[pk].win :
                        b \in ColdDiskBlocks \cup ColdMemBlocks
                /\ LET nsp == [startPoints EXCEPT ![pk] = EmptyStart]
                   IN /\ startPoints' = nsp
                      /\ blocks' = SyncRefCounts(blocks, laneState, laneFull, laneWin, nsp)
    /\ UNCHANGED <<laneState, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, reservation, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

DropUnreferenced(b) ==
    /\ Present(b)
    /\ blocks[b].refCount = 0
    /\ b \notin stepPins \cup stepIO
    /\ blocks' = [blocks EXCEPT ![b] = EmptyBlock]
    /\ UNCHANGED <<startPoints, laneState, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, reservation, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

\* ---- Window Sliding & Lane Completion -------------------------------------

SlideWindow(l) ==
    /\ laneState[l] = "Ready"
    /\ LET keep == History(lanePos[l])
           nw   == [i \in BlkIdx |-> IF i \in keep THEN laneWin[l][i] ELSE NoBlock]
       IN /\ nw # laneWin[l]
          /\ laneWin' = [laneWin EXCEPT ![l] = nw]
          /\ blocks'  = SyncRefCounts(blocks, laneState, laneFull, [laneWin EXCEPT ![l] = nw], startPoints)
    /\ UNCHANGED <<startPoints, laneState, lanePrefix, laneTarget, lanePos,
                   laneFull, reservation, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

FinishReady(l) ==
    /\ laneState[l] = "Ready"
    /\ lanePos[l] = laneTarget[l]
    /\ LET nst == [laneState EXCEPT ![l] = "Finished"]
           nlf == [laneFull EXCEPT ![l] = EmptyBlkMap]
           nlw == [laneWin EXCEPT ![l] = EmptyBlkMap]
       IN /\ laneState'   = nst
          /\ lanePrefix'  = [lanePrefix EXCEPT ![l] = DefaultPrefix]
          /\ laneTarget'  = [laneTarget EXCEPT ![l] = DefaultTarget]
          /\ lanePos'     = [lanePos EXCEPT ![l] = 0]
          /\ laneFull'    = nlf
          /\ laneWin'     = nlw
          /\ reservation' = [reservation EXCEPT ![l] = 0]
          /\ admitBudget' = [admitBudget EXCEPT ![l] = 0]
          /\ waitTicks'   = [waitTicks EXCEPT ![l] = 0]
          /\ blocks'      = SyncRefCounts(blocks, nst, nlf, nlw, startPoints)
    /\ UNCHANGED <<startPoints, queueSeq, stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

\* ---- One Step In Flight (BuildStep -> GpuExecute & CompleteStepIO -> FinishStep) ----

SpanSize(l, c) ==
    IF IsDecoding(l)
    THEN c = 1
    ELSE /\ IsPrefilling(l)
         /\ c \in 1..MaxSpan
         /\ lanePos[l] + c <= PromptEnd(laneTarget[l])
         /\ c <= BlockSize - (lanePos[l] % BlockSize)

BuildStep(chosen, spans) ==
    /\ ~stepActive
    /\ chosen # {}
    /\ chosen \subseteq SteppableReady
    /\ SumBy(chosen, spans) <= StepTokenBudget
    /\ \A l \in chosen : SpanSize(l, spans[l])
    /\ \A l \in (Lanes \ chosen) : spans[l] = 0
    /\ LET maxW       == CHOOSE w \in {waitTicks[r] : r \in SteppableReady} :
                             \A u \in {waitTicks[r] : r \in SteppableReady} : w >= u
           NeedFullAlloc(l) == laneFull[l][lanePos[l] \div BlockSize] = NoBlock
           NeedWinAlloc(l)  == laneWin[l][lanePos[l] \div BlockSize] = NoBlock
           NewFullIds == {<<"priv", l, "full">>   : l \in {q \in chosen : NeedFullAlloc(q)}}
           NewWinIds  == {<<"priv", l, "window">> : l \in {q \in chosen : NeedWinAlloc(q)}}
           NewIds     == NewFullIds \cup NewWinIds
           allocCnt   == Cardinality(NewIds)
           \* Ready decoders excluded from chosen whose private tail blocks fit in memory.
           FitUnchosenDecoders ==
               {d \in (SteppableReady \ chosen) :
                   IsDecoding(d) /\ MemUsed + allocCnt + NeedAllocMap[d] <= MemBudget}
           HasMaxDecoder ==
               \E d \in SteppableReady :
                   IsDecoding(d) /\ waitTicks[d] = maxW /\ MemUsed + NeedAllocMap[d] <= MemBudget
       IN /\ IF Bug = "no_decode_priority"
             THEN /\ \E l \in chosen : waitTicks[l] = maxW
                  /\ FitUnchosenDecoders # {} =>
                         /\ SumBy(chosen, spans) = StepTokenBudget
                         /\ ~\E p \in chosen : IsPrefilling(p) /\ waitTicks[p] < maxW
                         /\ ~\E p \in chosen : IsPrefilling(p) /\ spans[p] > 1
             ELSE \E leader \in chosen :
                      /\ waitTicks[leader] = maxW
                      /\ HasMaxDecoder => IsDecoding(leader)
                      /\ FitUnchosenDecoders # {} =>
                             /\ SumBy(chosen, spans) = StepTokenBudget
                             /\ \A q \in (chosen \ {leader}) :
                                    IsDecoding(q) \/ waitTicks[q] >= MaxBypass
                             /\ IsPrefilling(leader) => spans[leader] = 1
          /\ IF Bug = "queued_bypass"
             THEN \A r \in (SteppableReady \ chosen) : waitTicks[r] < MaxBypass
             ELSE \A w \in StepBypassed(chosen) : waitTicks[w] < MaxBypass
          /\ \A b \in NewIds : blocks[b].tier = "none"
          /\ MemUsed + allocCnt <= MemBudget
          /\ LET nlf == [l \in Lanes |->
                            IF l \in chosen /\ NeedFullAlloc(l)
                            THEN [laneFull[l] EXCEPT ![lanePos[l] \div BlockSize] = <<"priv", l, "full">>]
                            ELSE laneFull[l]]
                 nlw == [l \in Lanes |->
                            IF l \in chosen /\ NeedWinAlloc(l)
                            THEN [laneWin[l] EXCEPT ![lanePos[l] \div BlockSize] = <<"priv", l, "window">>]
                            ELSE laneWin[l]]
                 nst == [l \in Lanes |-> IF l \in chosen THEN "InStep" ELSE laneState[l]]
                 blks1 == [b \in BlockIds |->
                            IF b \in NewIds
                            THEN LET owner == b[2]
                                 IN [tier |-> "memory", sealed |-> FALSE,
                                     idx |-> lanePos[owner] \div BlockSize,
                                     length |-> 0, data |-> EmptyData, refCount |-> 1]
                            ELSE blocks[b]]
                 blks2 == SyncRefCounts(blks1, nst, nlf, nlw, startPoints)
                 PinsFor(l) ==
                    {nlf[l][i] : i \in Full(lanePos[l] + spans[l])} \cup
                    {nlw[l][i] : i \in SpanWindow(lanePos[l], spans[l])}
                 allPins == UNION {PinsFor(l) : l \in chosen}
                 ioCand == {b \in allPins : blks2[b].sealed /\ blks2[b].tier = "memory"}
                 pendIO == IF Bug = "eager_hot_writeback" /\ ioCand # {} /\ DiskUsed < DiskBudget
                           THEN {CHOOSE b \in ioCand : TRUE}
                           ELSE {}
             IN /\ NoBlock \notin allPins
                /\ \A b \in allPins : blks2[b].tier \in {"memory", "both"}
                /\ blocks'     = blks2
                /\ laneFull'   = nlf
                /\ laneWin'    = nlw
                /\ laneState'  = nst
                /\ stepActive' = TRUE
                /\ stepLanes'  = chosen
                /\ stepSpan'   = spans
                /\ stepPins'   = allPins
                /\ stepIO'     = pendIO
                /\ gpuDone'    = FALSE
                /\ waitTicks'  = [q \in Lanes |->
                                    IF q \in chosen THEN 0
                                    ELSE IF q \in StepBypassed(chosen)
                                    THEN IF waitTicks[q] <= MaxBypass THEN waitTicks[q] + 1 ELSE waitTicks[q]
                                    ELSE waitTicks[q]]
    /\ UNCHANGED <<startPoints, lanePrefix, laneTarget, lanePos, reservation, admitBudget, queueSeq>>

GpuExecute ==
    /\ stepActive
    /\ ~gpuDone
    /\ blocks' = [b \in BlockIds |->
        IF \E l \in stepLanes :
            /\ b \in {laneFull[l][lanePos[l] \div BlockSize], laneWin[l][lanePos[l] \div BlockSize]}
            /\ Present(b)
            /\ ~blocks[b].sealed
        THEN LET l   == CHOOSE q \in stepLanes :
                            b \in {laneFull[q][lanePos[q] \div BlockSize],
                                   laneWin[q][lanePos[q] \div BlockSize]}
                 off == lanePos[l] % BlockSize
                 cnt == stepSpan[l]
             IN [blocks[b] EXCEPT
                    !.length = off + cnt,
                    !.data   = [i \in 0..(BlockSize - 1) |->
                                  IF i >= off /\ i < off + cnt THEN 1 ELSE blocks[b].data[i]]]
        ELSE blocks[b]]
    /\ gpuDone' = TRUE
    /\ UNCHANGED <<startPoints, laneState, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, reservation, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, stepIO>>

CompleteStepIO ==
    /\ stepIO # {}
    /\ DiskUsed + Cardinality(stepIO) <= DiskBudget
    /\ blocks' = [b \in BlockIds |->
                    IF b \in stepIO /\ blocks[b].tier = "memory"
                    THEN [blocks[b] EXCEPT !.tier =
                            IF Bug = "eager_hot_writeback" \/ LaneReferrers(b) # {}
                            THEN "both"
                            ELSE "disk"]
                    ELSE blocks[b]]
    /\ stepIO' = {}
    /\ UNCHANGED <<startPoints, laneState, lanePrefix, laneTarget, lanePos,
                   laneFull, laneWin, reservation, admitBudget, waitTicks, queueSeq,
                   stepActive, stepLanes, stepSpan, stepPins, gpuDone>>

FinishStep ==
    /\ stepActive
    /\ gpuDone
    /\ stepIO = {}
    /\ LET Surviving     == {l \in stepLanes : laneState[l] = "InStep"}
           CancellingSet == {l \in stepLanes : laneState[l] = "Cancelling"}
           BoundaryLanes == {l \in Surviving : (lanePos[l] + stepSpan[l]) % BlockSize = 0}
           PublishedTreeIds ==
               UNION {{<<"tree", lanePrefix[l], "full",   ((lanePos[l] + stepSpan[l]) \div BlockSize) - 1>>,
                       <<"tree", lanePrefix[l], "window", ((lanePos[l] + stepSpan[l]) \div BlockSize) - 1>>} :
                      l \in BoundaryLanes}
           RetiredPrivIds ==
               UNION {{<<"priv", l, "full">>, <<"priv", l, "window">>} : l \in BoundaryLanes \cup CancellingSet}
           npos == [l \in Lanes |->
                    IF l \in CancellingSet THEN 0
                    ELSE IF l \in Surviving THEN lanePos[l] + stepSpan[l]
                    ELSE lanePos[l]]
           npfx == [l \in Lanes |-> IF l \in CancellingSet THEN DefaultPrefix ELSE lanePrefix[l]]
           ntgt == [l \in Lanes |-> IF l \in CancellingSet THEN DefaultTarget ELSE laneTarget[l]]
           nlf == [l \in Lanes |->
                    IF l \in CancellingSet THEN EmptyBlkMap
                    ELSE IF l \in BoundaryLanes
                    THEN LET bi == (npos[l] \div BlockSize) - 1
                         IN [laneFull[l] EXCEPT ![bi] = <<"tree", lanePrefix[l], "full", bi>>]
                    ELSE laneFull[l]]
           nlw == [l \in Lanes |->
                    IF l \in CancellingSet THEN EmptyBlkMap
                    ELSE IF l \in Surviving
                    THEN LET rawW == IF l \in BoundaryLanes
                                     THEN LET bi == (npos[l] \div BlockSize) - 1
                                          IN [laneWin[l] EXCEPT ![bi] = <<"tree", lanePrefix[l], "window", bi>>]
                                     ELSE laneWin[l]
                         IN IF Bug = "unpruned_window"
                            THEN rawW
                            ELSE [i \in BlkIdx |-> IF i \in History(npos[l]) THEN rawW[i] ELSE NoBlock]
                    ELSE laneWin[l]]
           blksSealed == [b \in BlockIds |->
                            IF b \in RetiredPrivIds THEN EmptyBlock
                            ELSE IF b \in PublishedTreeIds
                            THEN [tier     |-> IF blocks[b].tier \in {"disk", "both"} THEN "both" ELSE "memory",
                                  sealed   |-> TRUE,
                                  idx      |-> b[4],
                                  length   |-> BlockSize,
                                  data     |-> FullData,
                                  refCount |-> blocks[b].refCount]
                            ELSE blocks[b]]
           nsp == [pk \in Prefixes \X Boundaries |->
                    IF \E l \in BoundaryLanes : lanePrefix[l] = pk[1] /\ npos[l] = pk[2]
                    THEN [kept      |-> TRUE,
                          stateKept |-> TRUE,
                          full      |-> {<<"tree", pk[1], "full", i>>   : i \in Full(pk[2])},
                          win       |-> {<<"tree", pk[1], "window", i>> : i \in History(pk[2])}]
                    ELSE startPoints[pk]]
           nst == [l \in Lanes |->
                    IF l \in CancellingSet THEN "Cancelled"
                    ELSE IF l \in Surviving THEN "Ready"
                    ELSE laneState[l]]
           nres == [l \in Lanes |-> IF l \in CancellingSet THEN 0 ELSE reservation[l]]
           nadm == [l \in Lanes |-> IF l \in CancellingSet THEN 0 ELSE admitBudget[l]]
           blksFinal == SyncRefCounts(blksSealed, nst, nlf, nlw, nsp)
       IN /\ blocks'      = blksFinal
          /\ startPoints' = nsp
          /\ lanePos'     = npos
          /\ lanePrefix'  = npfx
          /\ laneTarget'  = ntgt
          /\ laneState'   = nst
          /\ laneFull'    = nlf
          /\ laneWin'     = nlw
          /\ reservation' = nres
          /\ admitBudget' = nadm
          /\ stepActive'  = FALSE
          /\ stepLanes'   = {}
          /\ stepSpan'    = [l \in Lanes |-> 0]
          /\ stepPins'    = {}
          /\ gpuDone'     = FALSE
    /\ UNCHANGED <<waitTicks, queueSeq, stepIO>>

\* ---- Client Disconnect / Cancellation -------------------------------------

Cancel(l) ==
    /\ laneState[l] \in {"Queued", "Admitted", "Restoring", "Ready", "InStep"}
    /\ IF laneState[l] = "InStep" /\ Bug # "cancel_in_step"
       THEN /\ laneState' = [laneState EXCEPT ![l] = "Cancelling"]
            /\ UNCHANGED <<blocks, lanePrefix, laneTarget, lanePos, laneFull, laneWin,
                           reservation, admitBudget, waitTicks, queueSeq>>
       ELSE LET nst == [laneState EXCEPT ![l] = "Cancelled"]
                nlf == [laneFull EXCEPT ![l] = EmptyBlkMap]
                nlw == [laneWin EXCEPT ![l] = EmptyBlkMap]
                blks1 == SyncRefCounts(blocks, nst, nlf, nlw, startPoints)
            IN /\ laneState'   = nst
               /\ lanePrefix'  = [lanePrefix EXCEPT ![l] = DefaultPrefix]
               /\ laneTarget'  = [laneTarget EXCEPT ![l] = DefaultTarget]
               /\ lanePos'     = [lanePos EXCEPT ![l] = 0]
               /\ laneFull'    = nlf
               /\ laneWin'     = nlw
               /\ reservation' = [reservation EXCEPT ![l] = 0]
               /\ admitBudget' = [admitBudget EXCEPT ![l] = 0]
               /\ waitTicks'   = [waitTicks EXCEPT ![l] = 0]
               /\ queueSeq'    = IF laneState[l] = "Queued" THEN RemoveLane(queueSeq, l) ELSE queueSeq
               /\ blocks'      = blks1
    /\ UNCHANGED <<startPoints, stepActive, stepLanes, stepSpan, stepPins, stepIO, gpuDone>>

\* ---- Next-State Relation & Disjoint Fairness ------------------------------

AdvanceLane(l) ==
    \/ Refuse429(l)
    \/ Admit(l)
    \/ BeginRestore(l)
    \/ (\E b \in BlockIds : RestoreBlock(l, b))
    \/ FinishRestore(l)
    \/ FinishReady(l)

MemReclaim ==
    \/ EvictCleanOrUnrefMem
    \/ StartColdWriteback
    \/ ReclaimColdDisk

AnyBuildStep ==
    \E chosen \in ((SUBSET Lanes) \ {{}}), spans \in [Lanes -> 0..MaxSpan] : BuildStep(chosen, spans)

StepProgress ==
    \/ GpuExecute
    \/ CompleteStepIO
    \/ FinishStep

FairSchedulerActions ==
    \/ (\E l \in Lanes : AdvanceLane(l))
    \/ MemReclaim
    \/ AnyBuildStep
    \/ StepProgress

UnfairEnvActions ==
    \/ (\E l \in Lanes, p \in Prefixes, r \in RequestLengths : Arrive(l, p, r))
    \/ (\E l \in Lanes : SlideWindow(l) \/ Cancel(l))
    \/ (\E b \in BlockIds : DropUnreferenced(b))

Next == FairSchedulerActions \/ UnfairEnvActions

Fairness ==
    /\ (\A l \in Lanes : WF_vars(AdvanceLane(l)))
    /\ WF_vars(MemReclaim)
    /\ WF_vars(AnyBuildStep)
    /\ WF_vars(StepProgress)

Spec == Init /\ [][Next]_vars /\ Fairness
SpecSafety == Init /\ [][Next]_vars
SymmetryLanesAndPrefixes == Permutations(Lanes) \cup Permutations(Prefixes)

\* ---- Safety Invariants (docs/DESIGN.md "Models") --------------------------

TypeOK ==
    /\ \A b \in BlockIds :
        /\ blocks[b].tier \in Tiers
        /\ blocks[b].sealed \in BOOLEAN
        /\ blocks[b].idx \in BlkIdx
        /\ blocks[b].length \in 0..BlockSize
        /\ blocks[b].data \in [0..(BlockSize - 1) -> {0, 1}]
        /\ blocks[b].refCount \in Nat
    /\ \A pk \in Prefixes \X Boundaries :
        /\ startPoints[pk].kept \in BOOLEAN
        /\ startPoints[pk].stateKept \in BOOLEAN
        /\ startPoints[pk].full \subseteq TreeIds
        /\ startPoints[pk].win \subseteq TreeIds
    /\ laneState \in [Lanes -> SlotStates]
    /\ lanePrefix \in [Lanes -> Prefixes]
    /\ laneTarget \in [Lanes -> RequestLengths]
    /\ lanePos \in [Lanes -> 0..MaxPos]
    /\ reservation \in [Lanes -> 0..MemBudget]
    /\ admitBudget \in [Lanes -> 0..MemBudget]
    /\ waitTicks \in [Lanes -> 0..(MaxBypass + 1)]
    /\ queueSeq \in Seq(Lanes)
    /\ Len(queueSeq) = Cardinality(QueuedLanes)
    /\ \A i \in 1..Len(queueSeq) : queueSeq[i] \in QueuedLanes
    /\ \A i, j \in 1..Len(queueSeq) : i # j => queueSeq[i] # queueSeq[j]
    /\ stepActive \in BOOLEAN
    /\ stepLanes \subseteq Lanes
    /\ stepPins \subseteq BlockIds
    /\ stepIO \subseteq BlockIds
    /\ gpuDone \in BOOLEAN

StepBlocksInMemoryAndOwned ==
    /\ (stepActive =>
        /\ \A l \in stepLanes :
            /\ laneState[l] \in {"InStep", "Cancelling"}
            /\ \A i \in Full(lanePos[l] + stepSpan[l]) :
                laneFull[l][i] # NoBlock /\ laneFull[l][i] \in stepPins
            /\ \A i \in SpanWindow(lanePos[l], stepSpan[l]) :
                laneWin[l][i] # NoBlock /\ laneWin[l][i] \in stepPins
        /\ \A b \in stepPins :
            /\ InMemory(b)
            /\ LaneReferrers(b) # {}
            /\ blocks[b].refCount >= 1)
    /\ \A b \in stepIO :
        /\ InMemory(b)
        /\ Referrers(b) # {}
        /\ blocks[b].refCount >= 1

SealedValid ==
    \A b \in BlockIds :
        (Present(b) /\ blocks[b].sealed) =>
            /\ b \in TreeIds
            /\ blocks[b].length = BlockSize
            /\ blocks[b].data = FullData

SealedNeverWritten ==
    \A b \in BlockIds :
        (Present(b) /\ blocks[b].sealed /\ blocks'[b].tier # "none") =>
            /\ blocks'[b].sealed = TRUE
            /\ blocks'[b].length = blocks[b].length
            /\ blocks'[b].data = blocks[b].data

UnsealedPrivateInvisibleZero ==
    \A b \in BlockIds :
        (Present(b) /\ ~blocks[b].sealed) =>
            /\ b \in PrivIds
            /\ Cardinality(Referrers(b)) = 1
            /\ Cardinality(LaneReferrers(b)) = 1
            /\ StartReferrers(b) = {}
            /\ blocks[b].tier = "memory"
            /\ blocks[b].length <= BlockSize
            /\ (~stepActive => blocks[b].length < BlockSize)
            /\ \A i \in blocks[b].length..(BlockSize - 1) : blocks[b].data[i] = 0

RefCountMatchesReferrers ==
    \A b \in BlockIds :
        /\ blocks[b].refCount = Cardinality(Referrers(b))
        /\ blocks[b].refCount > 0 => Present(b)
        /\ ~Present(b) => blocks[b].refCount = 0

StartPointsKept ==
    \A pk \in Prefixes \X Boundaries :
        startPoints[pk].kept =>
            /\ startPoints[pk].stateKept = TRUE
            /\ Cardinality(startPoints[pk].full) = Cardinality(Full(pk[2]))
            /\ Cardinality(startPoints[pk].win) = Cardinality(History(pk[2]))
            /\ \A i \in Full(pk[2]) :
                \E b \in startPoints[pk].full :
                    Present(b) /\ blocks[b].sealed /\ BlockKind(b) = "full" /\ blocks[b].idx = i
            /\ \A i \in History(pk[2]) :
                \E b \in startPoints[pk].win :
                    Present(b) /\ blocks[b].sealed /\ BlockKind(b) = "window" /\ blocks[b].idx = i

LaneHistoryCovered ==
    \A l \in Lanes :
        laneState[l] \in {"Restoring", "Ready", "InStep"} =>
            /\ \A i \in Full(lanePos[l]) :
                laneFull[l][i] # NoBlock /\ Present(laneFull[l][i])
            /\ \A i \in History(lanePos[l]) :
                laneWin[l][i] # NoBlock /\ Present(laneWin[l][i])

BudgetsAndReservations ==
    /\ MemUsed <= MemBudget
    /\ DiskUsed <= DiskBudget
    /\ ReservedTotal <= MemBudget
    /\ \A l \in Lanes :
        laneState[l] \in {"Restoring", "Ready", "InStep"} =>
            reservation[l] >= CurrentWorkingSet(l)

ColdBlocksSpillable ==
    \A b \in BlockIds :
        (InMemory(b) /\ LaneReferrers(b) = {} /\ b \notin stepIO) =>
            /\ blocks[b].sealed = TRUE
            /\ b \notin stepPins
            /\ \/ OnDisk(b)
               \/ blocks[b].refCount = 0
               \/ DiskUsed + Cardinality(stepIO) < DiskBudget
               \/ ColdDiskBlocks # {}
               \/ StartReferrers(b) # {}

BypassBoundHolds ==
    \A l \in Lanes :
        laneState[l] \in WaitingStates => waitTicks[l] <= MaxBypass

StepBudgetHolds ==
    stepActive =>
        /\ SumBy(stepLanes, stepSpan) <= StepTokenBudget
        /\ \A l \in stepLanes :
            lanePos[l] >= PromptEnd(laneTarget[l]) => stepSpan[l] = 1

QueueBounded ==
    /\ Cardinality(QueuedLanes) <= MaxQueue
    /\ \A q \in QueuedLanes : WorstCaseBlocks(laneTarget[q]) <= MemBudget

\* ---- Temporal Properties (Action Safety + Liveness) -----------------------
\* Every `l \in Lanes` is symmetric in `Init`, `Next`, and `Fairness`. Moreover,
\* the only exits from `"Queued"` are `{"Admitted", "Refused", "Cancelled"}`, and
\* no transition from `AdmittedStates` can reach `"Refused"` without first hitting
\* `{"Finished", "Cancelled"}`. Hence `LiveRequestResolves` on `ProbeLane` holds
\* iff BOTH (a) every queued request is admitted, refused, or cancelled AND
\* (b) every admitted/restoring lane finishes or is cancelled, while keeping a
\* minimal 2-state Buchi tableau in TLC.

ActionSealedImmutable == [][SealedNeverWritten]_vars

QueuedNeverRefused ==
    \A l \in Lanes : laneState[l] = "Queued" => laneState'[l] # "Refused"

ActionNoQueuedRefusal == [][QueuedNeverRefused]_vars

LazyColdWritebackStep ==
    /\ \A b \in BlockIds :
        (b \notin stepIO /\ b \in stepIO') =>
            /\ MemPressure
            /\ LaneReferrers(b) = {}
            /\ blocks[b].sealed = TRUE
            /\ blocks[b].tier = "memory"
    /\ \A b \in BlockIds :
        (~OnDisk(b) /\ (OnDisk(b))') =>
            /\ (MemPressure \/ b \in stepIO)
            /\ blocks[b].sealed = TRUE
            /\ blocks[b].tier = "memory"
            /\ (b \notin stepIO => LaneReferrers(b) = {})
            /\ blocks'[b].tier = (IF LaneReferrers(b) = {} THEN "disk" ELSE "both")

ActionLazyColdWriteback == [][LazyColdWritebackStep]_vars

DecodePriorityStep ==
    (~stepActive /\ stepActive') =>
        LET maxW == CHOOSE w \in {waitTicks[r] : r \in SteppableReady} :
                        \A u \in {waitTicks[r] : r \in SteppableReady} : w >= u
            stepAlloc == SumBy(stepLanes', NeedAllocMap)
            FitUnchosenDecoders ==
                {d \in (SteppableReady \ stepLanes') :
                    IsDecoding(d) /\ MemUsed + stepAlloc + NeedAllocMap[d] <= MemBudget}
            HasMaxDecoder ==
                \E d \in SteppableReady :
                    IsDecoding(d) /\ waitTicks[d] = maxW /\ MemUsed + NeedAllocMap[d] <= MemBudget
        IN \E leader \in stepLanes' :
            /\ waitTicks[leader] = maxW
            /\ HasMaxDecoder => IsDecoding(leader)
            /\ FitUnchosenDecoders # {} =>
                   /\ SumBy(stepLanes', stepSpan') = StepTokenBudget
                   /\ \A q \in (stepLanes' \ {leader}) :
                          IsDecoding(q) \/ waitTicks[q] >= MaxBypass
                   /\ IsPrefilling(leader) => stepSpan'[leader] = 1

ActionDecodePriority == [][DecodePriorityStep]_vars

LiveRequestResolves ==
    (laneState[ProbeLane] \in ({"Queued"} \cup AdmittedStates))
        ~> (laneState[ProbeLane] \in {"Refused", "Cancelled", "Finished"})

=============================================================================