inky-engine 3.0.0

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
--------------------------- MODULE VerifyWindowRing ---------------------------
\* Layout and lifecycle model for Layer 3 sliding-window block-pool ring
\* allocation, post-verify window pruning (`ServeBlockCache::finish_verify_span`
\* / `VerifySession::reconcile_after_rollback`), and GPU block-table sync
\* (`Engine::sync_lane_block_table` / `Engine::sync_committed_lane_block_table`).
\*
\* Models a bounded `WinPoolCap`-slot `Window` pool (`WinPoolCap < MaxPos / BlockSize`,
\* so slots must recycle as the sliding window advances), variable-length spans,
\* speculative verify batches of length `1 + k` (`k \in 1..MaxK`) keeping
\* `nKeep \in 0..(1 + k)` positions, and `Prune` followed by `Sync` as separate
\* actions.

EXTENDS Integers, Sequences, FiniteSets

CONSTANTS
    BlockSize,      \* Positions per KV block (`BLOCK = 64` in production, 2 here)
    Window,         \* Sliding-window width (`EXT = WINDOW = 1024` in production, 4 or 6 here)
    MaxK,           \* Max draft tokens per verify step (`MAX_DRAFT_K`, 2 or 3 here)
    MaxPos,         \* Max stream length (`10` or `12` here; `MaxPos / BlockSize > WinPoolCap`)
    WinPoolCap,     \* Total slots in the Window BlockPool (`3` or `4` here)
    Bug             \* "none" | "sync_prev_pos" | "sync_before_prune" | "over_prune_draft"

ASSUME
    /\ BlockSize >= 2
    /\ Window >= BlockSize
    /\ (Window % BlockSize) = 0
    /\ MaxK >= 2
    /\ MaxPos >= Window + 2 * BlockSize
    /\ (MaxPos % BlockSize) = 0
    /\ WinPoolCap >= (Window \div BlockSize) + 1
    /\ Bug \in {"none", "sync_prev_pos", "sync_before_prune", "over_prune_draft"}

NumBlocks == MaxPos \div BlockSize
Blocks    == 0..(NumBlocks - 1)
WinSlots  == 1..WinPoolCap

\* Exact mirror of `blocks::first_live_window_block_at(pos, Window, BlockSize)`:
\* `pos.saturating_sub(Window - 1) / BlockSize`.
FirstNeeded(p) ==
    IF p <= Window - 1 THEN 0 ELSE (p - (Window - 1)) \div BlockSize

SpanWinBlocks(p0, t) ==
    FirstNeeded(p0) .. ((p0 + t - 1) \div BlockSize)

CommittedWinBlocks(p) ==
    IF p = 0 THEN {} ELSE FirstNeeded(p) .. ((p - 1) \div BlockSize)

MinSet(S) == CHOOSE x \in S : \A y \in S : x <= y

LowestFree(used) ==
    CHOOSE s \in WinSlots : ~used[s] /\ \A s2 \in WinSlots : (~used[s2]) => s <= s2

RECURSIVE AllocWin(_, _, _)
AllocWin(tbl, used, blks) ==
    IF blks = {} THEN <<tbl, used>>
    ELSE LET b == MinSet(blks)
             s == LowestFree(used)
         IN AllocWin([tbl EXCEPT ![b] = s], [used EXCEPT ![s] = TRUE], blks \ {b})

ClearBlocks(tbl, used, blks) ==
    LET freedSlots == {tbl[b] : b \in {x \in blks : tbl[x] # 0}}
        tbl2       == [b \in Blocks |-> IF b \in blks THEN 0 ELSE tbl[b]]
        used2      == [s \in WinSlots |-> IF s \in freedSlots THEN FALSE ELSE used[s]]
    IN <<tbl2, used2>>

VARIABLES
    phase,          \* "ready" | "verified" | "pruned"
    pos,            \* Committed stream length (`0..MaxPos`), or `p0` while `phase = "verified"`
    verifyK,        \* Active `k` (`0..MaxK`)
    draftAlloc,     \* Subset of `Blocks` newly allocated by `StartVerify`
    winTbl,         \* `[Blocks -> 0..WinPoolCap]` host `BlockTable` (`0` = None)
    winGpu,         \* `[Blocks -> 0..WinPoolCap]` GPU `bt_buf` (`0` = CLEARED_GPU_TABLE_ENTRY)
    poolUsed,       \* `[WinSlots -> BOOLEAN]` allocated bit per Window pool slot
    postSyncClean,  \* TRUE right after an eager post-step sync (`SyncAfterVerify`)
    syncOk          \* FALSE iff any pre-step or post-step sync checked a non-resident block

vars == <<phase, pos, verifyK, draftAlloc, winTbl, winGpu, poolUsed, postSyncClean, syncOk>>

BlocksResident(tbl, used, req) ==
    \A b \in req : tbl[b] # 0 /\ used[tbl[b]]

Init ==
    /\ phase         = "ready"
    /\ pos           = 0
    /\ verifyK       = 0
    /\ draftAlloc    = {}
    /\ winTbl        = [b \in Blocks |-> 0]
    /\ winGpu        = [b \in Blocks |-> 0]
    /\ poolUsed      = [s \in WinSlots |-> FALSE]
    /\ postSyncClean = TRUE
    /\ syncOk        = TRUE

\* Plain prefill or 1-token decode span `[pos, pos + t)`:
\* allocate needed blocks, sync GPU table for `[pos, pos + t)`, then prune `< FirstNeeded(pos + t)`.
AdvanceSpan(t) ==
    /\ phase = "ready"
    /\ t >= 1
    /\ t <= BlockSize + 1
    /\ pos + t <= MaxPos
    /\ LET req    == SpanWinBlocks(pos, t)
           need   == {b \in req : winTbl[b] = 0}
           freeCt == Cardinality({s \in WinSlots : ~poolUsed[s]})
       IN /\ Cardinality(need) <= freeCt
          /\ LET a1     == AllocWin(winTbl, poolUsed, need)
                 tbl1   == a1[1]
                 used1  == a1[2]
                 okPre  == BlocksResident(tbl1, used1, req)
                 end    == pos + t
                 exp    == {b \in Blocks : b < FirstNeeded(end) /\ tbl1[b] # 0}
                 c2     == ClearBlocks(tbl1, used1, exp)
             IN /\ pos'           = end
                /\ winTbl'        = c2[1]
                /\ poolUsed'      = c2[2]
                /\ winGpu'        = tbl1
                /\ postSyncClean' = (exp = {})
                /\ syncOk'        = (syncOk /\ okPre)
                /\ UNCHANGED <<phase, verifyK, draftAlloc>>

\* Begin speculative verify batch `[pos, pos + 1 + k)`:
\* allocate needed blocks from the bounded Window ring and sync GPU `bt_buf`.
StartVerify(k) ==
    /\ phase = "ready"
    /\ k \in 1..MaxK
    /\ pos + 1 + k <= MaxPos
    /\ LET t      == 1 + k
           req    == SpanWinBlocks(pos, t)
           need   == {b \in req : winTbl[b] = 0}
           freeCt == Cardinality({s \in WinSlots : ~poolUsed[s]})
       IN /\ Cardinality(need) <= freeCt
          /\ LET a1    == AllocWin(winTbl, poolUsed, need)
                 tbl1  == a1[1]
                 used1 == a1[2]
                 okPre == BlocksResident(tbl1, used1, req)
             IN /\ phase'         = "verified"
                /\ verifyK'       = k
                /\ draftAlloc'    = need
                /\ winTbl'        = tbl1
                /\ winGpu'        = tbl1
                /\ poolUsed'      = used1
                /\ postSyncClean' = TRUE
                /\ syncOk'        = (syncOk /\ okPre)
                /\ UNCHANGED pos

\* Separate Action 1 after verify: release rejected draft blocks and prune expired window blocks
\* (or, under `Bug = "sync_before_prune"`, sync BEFORE pruning!).
PruneAfterVerify(nKeep) ==
    /\ phase = "verified"
    /\ nKeep \in 0..(1 + verifyK)
    /\ LET acceptedEnd == pos + nKeep
           rej         == IF nKeep = 0
                          THEN draftAlloc
                          ELSE {b \in draftAlloc : b * BlockSize >= acceptedEnd}
           pruneLim    == IF Bug = "over_prune_draft"
                          THEN FirstNeeded(pos + 1 + verifyK)
                          ELSE FirstNeeded(acceptedEnd)
           cRej        == ClearBlocks(winTbl, poolUsed, rej)
           tblRej      == cRej[1]
           usedRej     == cRej[2]
           exp         == IF nKeep = 0 /\ Bug # "over_prune_draft"
                          THEN {}
                          ELSE {b \in Blocks : b < pruneLim /\ tblRej[b] # 0}
           cAll        == ClearBlocks(tblRej, usedRej, exp)
       IN IF Bug = "sync_before_prune"
          THEN \* Faulted order: sync runs on `tblRej` BEFORE `exp` is pruned, leaving freed slots in `winGpu`.
               LET okSync == BlocksResident(tblRej, usedRej, CommittedWinBlocks(acceptedEnd))
               IN /\ phase'         = "ready"
                  /\ pos'           = acceptedEnd
                  /\ verifyK'       = 0
                  /\ draftAlloc'    = {}
                  /\ winTbl'        = cAll[1]
                  /\ poolUsed'      = cAll[2]
                  /\ winGpu'        = tblRej
                  /\ postSyncClean' = TRUE
                  /\ syncOk'        = (syncOk /\ okSync)
          ELSE /\ phase'         = "pruned"
               /\ pos'           = acceptedEnd
               /\ draftAlloc'    = {}
               /\ winTbl'        = cAll[1]
               /\ poolUsed'      = cAll[2]
               /\ postSyncClean' = FALSE
               /\ UNCHANGED <<verifyK, winGpu, syncOk>>

\* Separate Action 2 after verify: validate resident blocks at committed head `pos` and sync `winGpu`.
SyncAfterVerify ==
    /\ phase = "pruned"
    /\ LET reqBlocks == IF Bug = "sync_prev_pos"
                        THEN (IF pos = 0 THEN {} ELSE SpanWinBlocks(pos - 1, 1))
                        ELSE CommittedWinBlocks(pos)
           okSync    == BlocksResident(winTbl, poolUsed, reqBlocks)
       IN /\ phase'         = "ready"
          /\ verifyK'       = 0
          /\ winGpu'        = winTbl
          /\ postSyncClean' = TRUE
          /\ syncOk'        = (syncOk /\ okSync)
          /\ UNCHANGED <<pos, draftAlloc, winTbl, poolUsed>>

Next ==
    \/ \E t \in 1..(BlockSize + 1) : AdvanceSpan(t)
    \/ \E k \in 1..MaxK : StartVerify(k)
    \/ \E nKeep \in 0..(1 + MaxK) : PruneAfterVerify(nKeep)
    \/ SyncAfterVerify
    \/ (phase = "ready" /\ pos = MaxPos /\ UNCHANGED vars)

Spec == Init /\ [][Next]_vars

\* Invariant 1: Every pre-step and post-verify sync finds all target blocks resident and valid.
\* Violated by `Bug = "sync_prev_pos"` (reproducing `src/serve.rs:2464` missing Window block panic!).
SyncTargetResident == syncOk = TRUE

\* Invariant 2: After an eager post-verify sync (`postSyncClean = TRUE`), GPU `bt_buf` matches `winTbl`
\* identically and holds zero dangling pointers to freed/reusable pool slots.
\* Violated by `Bug = "sync_before_prune"`.
GpuNoDanglingSlot ==
    postSyncClean =>
        \A b \in Blocks :
            /\ winGpu[b] = winTbl[b]
            /\ (winGpu[b] # 0 => poolUsed[winGpu[b]])

\* Invariant 3: Whenever a lane is `ready` (or during `verified` attention on `[pos, pos + 1 + verifyK)`),
\* every block a subsequent step at `pos` or the active attention kernel reads is resident.
\* Violated by `Bug = "over_prune_draft"`.
NextStepWindowResident ==
    /\ (phase \in {"ready", "pruned"} => BlocksResident(winTbl, poolUsed, CommittedWinBlocks(pos)))
    /\ (phase = "verified" =>
            /\ BlocksResident(winTbl, poolUsed, SpanWinBlocks(pos, 1 + verifyK))
            /\ (\A b \in SpanWinBlocks(pos, 1 + verifyK) : winGpu[b] = winTbl[b]))

\* Invariant 4: Exact 1-to-1 conservation between `poolUsed` and distinct non-zero slots in `winTbl`.
PoolSlotConservation ==
    /\ \A b1, b2 \in Blocks : (b1 # b2 /\ winTbl[b1] # 0) => winTbl[b1] # winTbl[b2]
    /\ \A s \in WinSlots : poolUsed[s] <=> (\E b \in Blocks : winTbl[b] = s)
=============================================================================