inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
--------------------------- MODULE ServeMixedStep ---------------------------
\* Formal specification of mixed prefill + decode step planning, cap ceiling-lift,
\* zero-credit-delta accounting, dedicated mixed wall-time attribution, and decode-skip
\* elimination for `INK_MIXED_STEPS` (`ServeStepPlanner` in `src/scheduler.rs`,
\* `scheduler` in `src/serve.rs`, and `LiveCounters` in `src/serve/live.rs`).
\*
\* Models N lanes (1..N), block alignment Align (>= 1), starvation ceiling W (>= 1),
\* hardware step chunk Chunk (>= 1), contended prefill cap Cap (`INK_PREFILL_STEP_CAP`),
\* dynamic mix eligibility (e.g. homogeneous fallback when a LoopCD lane is active),
\* arbitrary prefill tails (min_t in 1..Align, including 1-token prefill tails), and
\* client/pool backpressure.
\*
\* Bug selects reversed negative-control witnesses (each must fail TLC with exit 12):
\*   "none"                : production amended policy (all invariants hold)
\*   "cap_ignores_ceiling" : Cap is not lifted when prefillers reach reserveAt (Johnny's counterexample -> violates BypassBound)
\*   "no_unserved_reserve" : omits W - 1 lookahead when an unserved decoder is at W - 1 (-> violates BypassBound)
\*   "starve_prefill"      : decode rows consume full Chunk without reserving first_pf_min (-> violates PrefillProgressOnMixed)
\*   "overflow_chunk"      : pf_budget fails to subtract Cardinality(dec_chosen) (-> violates ChunkBound)
\*   "double_charge"       : Mixed step charges both prefill & decode wall buckets and mutates credit (-> violates SingleWallCharge)
EXTENDS Integers, FiniteSets

CONSTANTS N, W, Align, Chunk, Cap, DynamicMix, Backpressure, AllowTail, Bug
ASSUME /\ N \in Nat /\ N >= 1
       /\ W \in Nat /\ W >= 1
       /\ Align \in Nat /\ Align >= 1
       /\ Chunk \in Nat /\ Chunk >= 1
       /\ Cap \in Nat /\ Cap >= 1
       /\ DynamicMix \in BOOLEAN /\ Backpressure \in BOOLEAN /\ AllowTail \in BOOLEAN
       /\ Bug \in {
              "none",
              "cap_ignores_ceiling",
              "no_unserved_reserve",
              "starve_prefill",
              "overflow_chunk",
              "double_charge"
          }

Lanes == 1..N
Min(a, b) == IF a < b THEN a ELSE b
Max(a, b) == IF a > b THEN a ELSE b

VARIABLES
    cls,          \* [Lanes -> {"idle", "prefill", "decode"}]
    run,          \* [Lanes -> BOOLEAN]
    tailOne,      \* [Lanes -> BOOLEAN]: TRUE when prefill lane has a 1-token final tail (Control 3), FALSE when >= Align
    wait,         \* [Lanes -> Nat]: planner wait_ticks
    ghost,        \* [Lanes -> 0..(W + 1)]: independent bypass witness
    served,       \* [Lanes -> BOOLEAN]
    creditSign,   \* {-1, 0, 1}: sign of Share credit (< 0, == 0, > 0)
    stepKind,     \* {"none", "decode", "prefill", "mixed"}
    stepTokens,   \* Nat: total token rows M_total = n_dec + T_pf in last step
    decChosen,    \* SUBSET Lanes: lanes executed on decode sub-pass (0..n_dec)
    pfChosen,     \* SUBSET Lanes: lanes executed on prefill sub-pass (n_dec..)
    wallBuckets,  \* SUBSET {"prefill", "decode", "mixed"}: wall-time buckets charged by last step
    creditMoved,  \* BOOLEAN: whether last step mutated share credit
    decSkips,     \* Nat: runnable decode lanes skipped on last step
    mixUsed,      \* BOOLEAN: whether mixing was active on last step
    phase         \* {"env", "plan"}

vars == <<
    cls, run, tailOne, wait, ghost, served, creditSign,
    stepKind, stepTokens, decChosen, pfChosen, wallBuckets, creditMoved, decSkips, mixUsed, phase
>>

Init ==
    /\ cls         = [l \in Lanes |-> "idle"]
    /\ run         = [l \in Lanes |-> FALSE]
    /\ tailOne     = [l \in Lanes |-> FALSE]
    /\ wait        = [l \in Lanes |-> 0]
    /\ ghost       = [l \in Lanes |-> 0]
    /\ served      = [l \in Lanes |-> FALSE]
    /\ creditSign  = 0
    /\ stepKind    = "none"
    /\ stepTokens  = 0
    /\ decChosen   = {}
    /\ pfChosen    = {}
    /\ wallBuckets = {}
    /\ creditMoved = FALSE
    /\ decSkips    = 0
    /\ mixUsed     = FALSE
    /\ phase       = "env"

NextCls(l) ==
    CASE cls[l] = "idle"    -> {"idle", "prefill", "decode"}
      [] cls[l] = "prefill" -> IF served[l] THEN {"prefill", "decode", "idle"} ELSE {"prefill", "idle"}
      [] cls[l] = "decode"  -> {"decode", "idle"}

Env ==
    /\ phase = "env"
    /\ \E c \in [Lanes -> {"idle", "prefill", "decode"}] :
          /\ \A l \in Lanes : c[l] \in NextCls(l)
          /\ \E r \in (IF Backpressure THEN [Lanes -> BOOLEAN] ELSE {[l \in Lanes |-> c[l] # "idle"]}),
                t1 \in (IF AllowTail THEN [Lanes -> BOOLEAN] ELSE {[l \in Lanes |-> FALSE]}) :
                /\ \A l \in Lanes : c[l] = "idle" => (~r[l] /\ ~t1[l])
                /\ \A l \in Lanes : c[l] = "decode" => ~t1[l]
                /\ cls'     = c
                /\ run'     = r
                /\ tailOne' = t1
                /\ wait'    = [l \in Lanes |-> IF c[l] # cls[l] /\ (c[l] = "idle" \/ cls[l] = "idle") THEN 0 ELSE wait[l]]
                /\ ghost'   = [l \in Lanes |-> IF c[l] = "idle" \/ ~r[l] THEN 0 ELSE ghost[l]]
    /\ served'      = [l \in Lanes |-> FALSE]
    /\ stepKind'    = "none"
    /\ stepTokens'  = 0
    /\ decChosen'   = {}
    /\ pfChosen'    = {}
    /\ wallBuckets' = {}
    /\ creditMoved' = FALSE
    /\ decSkips'    = 0
    /\ mixUsed'     = FALSE
    /\ phase'       = "plan"
    /\ UNCHANGED creditSign

Before(m, l) == wait[m] > wait[l] \/ (wait[m] = wait[l] /\ m < l)
Prefix(S, k) == {l \in S : Cardinality({m \in S : Before(m, l)}) < k}
MaxWait(S)   == CHOOSE w \in {wait[l] : l \in S} : \A u \in {wait[l] : l \in S} : w >= u
Rested(w)    == Min(w, W - 1)

MinPfSpan(l, t1) == IF t1[l] THEN 1 ELSE Align

RECURSIVE SumMinPf(_, _)
SumMinPf(S, t1) ==
    IF S = {} THEN 0
    ELSE LET l == CHOOSE x \in S : TRUE
         IN  MinPfSpan(l, t1) + SumMinPf(S \ {l}, t1)

\* Greedy prefix of `pf` in `Before` order whose minimum aligned spans fit in `pfBudget`.
FitsInBudget(pf, t1, pfBudget) ==
    {l \in pf : SumMinPf({m \in pf : Before(m, l) \/ m = l}, t1) <= pfBudget}

Plan ==
    /\ phase = "plan"
    /\ LET dec       == {l \in Lanes : cls[l] = "decode" /\ run[l]}
           pf        == {l \in Lanes : cls[l] = "prefill" /\ run[l]}
           cand      == dec \cup pf
           contended == dec # {} /\ pf # {}
           credIn    == IF contended THEN creditSign ELSE 0
       IN  \E shareOn \in BOOLEAN,
              mixOk \in (IF DynamicMix THEN BOOLEAN ELSE {TRUE}),
              nextCredAfterHomog \in {-1, 0, 1} :
             IF cand = {} THEN
                 /\ wait'        = [l \in Lanes |-> Rested(wait[l])]
                 /\ ghost'       = [l \in Lanes |-> 0]
                 /\ served'      = [l \in Lanes |-> FALSE]
                 /\ creditSign'  = 0
                 /\ stepKind'    = "none"
                 /\ stepTokens'  = 0
                 /\ decChosen'   = {}
                 /\ pfChosen'    = {}
                 /\ wallBuckets' = {}
                 /\ creditMoved' = FALSE
                 /\ decSkips'    = 0
                 /\ mixUsed'     = FALSE
             ELSE
                 LET dw             == IF dec = {} THEN -1 ELSE MaxWait(dec)
                     pw             == IF pf = {} THEN -1 ELSE MaxWait(pf)
                     prefillCeiling == pw >= W /\ dw < pw
                     shareOwed      == shareOn /\ credIn >= 0
                     chooseDecode   == IF pf = {} THEN TRUE
                                       ELSE IF dec = {} THEN FALSE
                                       ELSE ~(prefillCeiling \/ (shareOwed /\ dw < W))
                     firstPf        == IF pf = {} THEN 1 ELSE CHOOSE l \in pf : \A m \in pf : m = l \/ Before(l, m)
                     firstPfMin     == IF pf = {} THEN 0 ELSE MinPfSpan(firstPf, tailOne)
                     decCapOnMix    == IF Bug = "starve_prefill" THEN Chunk
                                       ELSE Max(0, Chunk - firstPfMin)
                     dSet           == IF chooseDecode THEN Prefix(dec, Chunk)
                                       ELSE IF mixOk /\ dec # {} THEN Prefix(dec, decCapOnMix)
                                       ELSE {}
                     unservedDec    == dec \ dSet
                     unservedAtWm1  == /\ Bug # "no_unserved_reserve"
                                       /\ \E d \in unservedDec : wait[d] + 1 >= W
                     reserveAt      == IF unservedAtWm1 THEN W - 1 ELSE W
                     urgentPf       == {l \in pf : wait[l] >= reserveAt}
                     urgentTokens   == SumMinPf(urgentPf, tailOne)
                     effCap         == IF contended THEN
                                           IF Bug = "cap_ignores_ceiling" THEN Cap
                                           ELSE Max(Cap, urgentTokens)
                                       ELSE Chunk
                     rawRoom        == IF Bug = "overflow_chunk" THEN Chunk
                                       ELSE Max(0, Chunk - Cardinality(dSet))
                     pfBudget       == IF chooseDecode THEN 0 ELSE Min(rawRoom, effCap)
                     pSet           == IF chooseDecode THEN {} ELSE FitsInBudget(pf, tailOne, pfBudget)
                     minPfTokens    == SumMinPf(pSet, tailOne)
                     \* Extra block-aligned tokens absorbed by picked non-tail spans up to pfBudget:
                     hasNonTail     == \E l \in pSet : ~tailOne[l]
                     extraMax       == IF hasNonTail /\ pfBudget >= minPfTokens
                                       THEN ((pfBudget - minPfTokens) \div Align) * Align
                                       ELSE 0
                     usedTokens     == Cardinality(dSet) + minPfTokens + extraMax
                     chosen         == dSet \cup pSet
                     sKind          == IF pSet = {} THEN "decode"
                                       ELSE IF dSet = {} THEN "prefill"
                                       ELSE "mixed"
                 IN  /\ wait'        = [l \in Lanes |-> IF l \in chosen THEN 0
                                                        ELSE IF l \in cand THEN wait[l] + 1
                                                        ELSE Rested(wait[l])]
                     /\ ghost'       = [l \in Lanes |-> IF l \in chosen THEN 0
                                                        ELSE IF l \in cand THEN Min(ghost[l] + 1, W + 1)
                                                        ELSE 0]
                     /\ served'      = [l \in Lanes |-> l \in chosen]
                     /\ stepKind'    = sKind
                     /\ stepTokens'  = usedTokens
                     /\ decChosen'   = dSet
                     /\ pfChosen'    = pSet
                     /\ wallBuckets' = CASE sKind = "decode"  -> {"decode"}
                                         [] sKind = "prefill" -> {"prefill"}
                                         [] sKind = "mixed"   ->
                                              IF Bug = "double_charge" THEN {"prefill", "decode"} ELSE {"mixed"}
                     /\ creditMoved' = IF sKind = "mixed" THEN (Bug = "double_charge")
                                       ELSE contended
                     /\ creditSign'  = IF ~contended THEN 0
                                       ELSE IF sKind = "mixed" /\ Bug # "double_charge" THEN credIn
                                       ELSE nextCredAfterHomog
                     /\ decSkips'    = Cardinality(dec \ dSet)
                     /\ mixUsed'     = ( ~chooseDecode /\ mixOk /\ dec # {} )
    /\ phase' = "env"
    /\ UNCHANGED <<cls, run, tailOne>>

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

\* --- Safety & Liveness-Bound Invariants ---

TypeOK ==
    /\ cls \in [Lanes -> {"idle", "prefill", "decode"}]
    /\ run \in [Lanes -> BOOLEAN]
    /\ tailOne \in [Lanes -> BOOLEAN]
    /\ wait \in [Lanes -> Nat]
    /\ ghost \in [Lanes -> 0..(W + 1)]
    /\ creditSign \in {-1, 0, 1}
    /\ stepKind \in {"none", "decode", "prefill", "mixed"}

\* 1. Total rows M_total = n_dec + T_pf never exceed hardware prefill chunk.
ChunkBound == stepTokens <= Chunk

\* 2. Disjoint sub-passes & Control 3: no lane is in both sub-passes, and 1-token prefill
\*    tails (`cls[l] = "prefill" /\ tailOne[l]`) NEVER enter the decode sub-pass (`decChosen`).
DisjointAndTailSafe ==
    /\ decChosen \cap pfChosen = {}
    /\ \A l \in decChosen : cls[l] = "decode"
    /\ \A l \in pfChosen  : cls[l] = "prefill"

\* 3. A planned mixed step (`mixUsed` when Chunk >= Align + 1) always advances >= 1 prefill lane.
PrefillProgressOnMixed ==
    (mixUsed /\ Chunk >= Align + 1) => (pfChosen # {} /\ stepKind = "mixed")

\* 4. Dedicated mixed wall-time counter & zero credit delta on Mixed steps (Amendment 2):
\*    every executed step charges AT MOST ONE wall-time bucket, and Mixed never mutates Share credit.
SingleWallCharge ==
    /\ Cardinality(wallBuckets) <= 1
    /\ (stepKind # "none" => Cardinality(wallBuckets) = 1)
    /\ (stepKind = "mixed" => wallBuckets = {"mixed"})

ZeroCreditDeltaOnMixed ==
    stepKind = "mixed" => ~creditMoved

\* 5. Zero decode skips on contended prefill steps whenever mixing is active and decoders fit alongside 1 block.
ZeroDecodeSkipWhenFit ==
    LET dec == {l \in Lanes : cls[l] = "decode" /\ run[l]}
    IN  (mixUsed /\ Cardinality(dec) + Align <= Chunk) => decSkips = 0

\* 6. Starvation ceiling W (`BypassBound`): holds across ALL Cap >= 1 whenever Chunk >= N * Align.
BypassBound == \A l \in Lanes : ghost[l] <= W
CounterCovers == \A l \in Lanes : wait[l] >= ghost[l]
CounterBound == \A l \in Lanes : wait[l] <= W
NoMixedStep == stepKind # "mixed"
=============================================================================