SpeculativeSequencer

class SpeculativeSequencer<S, A>(sequencer: TurnSequencer<A>, game: SpeculativeGame<S, A>, initialState: S, scope: CoroutineScope)

A wrapper over TurnSequencer that applies local actions optimistically before their committed index arrives, then rolls back and replays if the committed order differs from what was predicted.

Mechanism

On propose:

  1. The action is applied to speculativeState. If SpeculativeGame.apply rejects it, the exception reaches the caller and nothing else happens: no pending entry, no proposal.

  2. Only then is the action appended to a pending-input buffer.

  3. The underlying TurnSequencer.propose is called and suspends until a quorum commits.

  4. If propose throws (e.g. us.tractat.kuilt.raft.LeadershipLostException, or this call's own cancellation), that call withdraws its entry and speculativeState is rebuilt from the authoritative snapshot plus whatever is still pending.

On each TurnEvent.Committed emission received by the background collector:

  • Duplicate key (same DedupKey as a previously applied entry): the authoritative snapshot does not move, since the ClientSessionTable gate prevents a double-apply. A pending entry of equal value is discarded as its stale twin. The confirmed count still advances.

  • Match (the committed action equals a pending one, first-apply): the oldest such entry is discarded and the authoritative snapshot advances. If that entry was the oldest of all, the prediction was right and no replay is needed; otherwise the order differed, and the remaining pending inputs are replayed on top.

  • No match (a foreign peer's action, or one whose proposer already gave up on it, first-apply): the authoritative snapshot advances and all pending inputs are replayed on top.

The authoritative snapshot is always the fold of the committed log, whatever the buffer holds, so a mistake in matching never reaches it. The buffer only decides what is predicted on top, and speculativeState always equals that fold with the buffer applied after it. That prediction can stay wrong: an entry nothing retires keeps being applied for as long as it is there. The two known ways in are an action whose equality does not survive the codec (#3065) and a retry answered from the leader's cache (#3064).

A rejected action leaves the state unchanged

A move can be legal when proposed and illegal by the time it is replayed, because another player's move landed first. So when SpeculativeGame.apply throws an Exception anywhere but step 1 above, the action is treated as having no effect on that state:

  • In a replay, it is skipped for that replay and stays pending. Its own commit or failure still retires it, and a later base may make it legal again.

  • On a committed action, the authoritative snapshot does not move and a warning is logged. Every replica folds the same log with the same pure apply, so every replica refuses the same action at the same position and they stay identical. propose still returns normally for such an action: it did commit.

Rejecting this way is what keeps the collector alive: an exception escaping it would freeze speculativeState for good, and on Kotlin/Native would abort the process. It covers an Exception from SpeculativeGame.apply and nothing else, so these still end the collector: an Error from apply, a throw from SpeculativeGame.snapshot or SpeculativeGame.restore, a commit that will not decode, and a failed SpeculativeGame.fromSnapshot. The last is deliberate, since folding later commits over a snapshot that was never installed would corrupt the state silently. What an undecodable commit and a failed install should do instead is tracked by #3066.

What "equal" has to mean for A

A commit carries no token this sequencer could recognise as its own: the DedupKey is minted inside the node during TurnSequencer.propose, after the entry exists. So a commit is matched by value, with ==, and two consequences follow.

  • A needs value equality that survives the codec. A commit arrives as a copy decoded from the log, never the instance that was proposed. With identity equals, or a ByteArray property in a data class, a local action never matches its own commit: it is applied once as a foreign action and again as a pending one, and stays pending. Use a data class of values. Lifting this requirement is tracked by #3065.

  • Equal actions are interchangeable. A foreign action equal to a pending local one retires it. The state still converges, because the local action's own commit then applies as foreign, but between those two commits the prediction omits it. Likewise a failed propose whose entry a commit already claimed retires an equal entry instead, since that commit may really have been the other proposal's. Without that, the other entry would stay pending forever.

Constraints

Usage

val speculative = SpeculativeSequencer(
sequencer = TurnSequencer(node, Move.serializer()),
game = myGame, // SpeculativeGame<GameState, Move>
initialState = state0,
scope = viewModelScope, // or a scope tied to session lifetime
)

// Observe for UI — always up to date with speculative state:
speculative.speculativeState.collect { render(it) }

// Propose a local player's move (suspends until quorum confirms):
try {
speculative.propose(myMove)
} catch (e: LeadershipLostException) { /* retry */}

// Durable propose with a caller-owned request ID for cross-crash exactly-once:
try {
speculative.propose(myMove, requestId = nextSerial)
} catch (e: LeadershipLostException) { /* retry with same requestId */}

Parameters

sequencer

The backing TurnSequencer. Lifetime is owned by the caller.

game

The consumer-owned state machine. Must be pure and deterministic.

initialState

The authoritative starting state (before any actions).

scope

The CoroutineScope that owns the background committed-event collector. Cancel this scope to stop the collector.

Samples

runTest(UnconfinedTestDispatcher(), timeout = TEST_WEDGE_BACKSTOP) {
    // A trivially pure game: state is a list of committed integers.
    val counterGame = object : SpeculativeGame<List<Int>, Int> {
        override fun apply(state: List<Int>, action: Int): List<Int> = state + action
        override fun snapshot(state: List<Int>): List<Int> = state.toList()
        override fun restore(snapshot: List<Int>): List<Int> = snapshot.toList()
    }

    val node = FakeRaftNode()
    node.setRole(RaftRole.Leader)
    val sequencer = TurnSequencer(node, Int.serializer())

    // Hold the quorum open, so the in-flight window this sequencer exists to fill is
    // actually observable. A real Raft round-trip suspends inside propose; the default
    // FakeRaftNode commits without ever suspending, which would collapse the window to
    // nothing and make the optimistic state indistinguishable from the committed state.
    val quorum = CompletableDeferred<Unit>()
    val commit = node.proposeBehavior
    node.proposeBehavior = { command -> quorum.await(); commit(command) }

    val speculative = SpeculativeSequencer(
        sequencer = sequencer,
        game = counterGame,
        initialState = emptyList(),
        scope = backgroundScope,
    )

    // Optimistic apply: speculativeState reflects 42 immediately, while the proposal is
    // still in flight — no quorum has committed anything yet.
    val proposed = async { speculative.propose(42) }
    assertEquals(listOf(42), speculative.speculativeState.value)
    assertEquals(1, speculative.pendingCount)

    // Once quorum confirms, pending count drops to 0 and the same state is authoritative.
    quorum.complete(Unit)
    val indexed = proposed.await()
    assertEquals(42, indexed.action)
    speculative.awaitConfirmedCount(1)
    assertEquals(0, speculative.pendingCount)
    assertEquals(listOf(42), speculative.speculativeState.value)
}

Constructors

Link copied to clipboard
constructor(sequencer: TurnSequencer<A>, game: SpeculativeGame<S, A>, initialState: S, scope: CoroutineScope)

Properties

Link copied to clipboard
val confirmedCount: StateFlow<Int>

The number of committed events processed by the background collector.

Link copied to clipboard

The number of locally proposed actions waiting for confirmation.

Link copied to clipboard
val speculativeState: StateFlow<S>

The current speculative game state, including all locally proposed but not-yet-confirmed actions on top of the last authoritative snapshot.

Functions

Link copied to clipboard
suspend fun awaitConfirmedCount(count: Int)

Suspends until at least count committed events have been processed by the background collector. Use in tests to synchronize assertions after pushing commits via FakeRaftNode.pushCommitted.

Link copied to clipboard
suspend fun propose(action: A): IndexedAction<A>

Proposes action for Raft replication and returns after a quorum commits it.

suspend fun propose(action: A, requestId: Long): IndexedAction<A>

Proposes action with a caller-pinned requestId for cross-crash exactly-once, then returns after a quorum commits it (same semantics as propose).