SpeculativeGame

interface SpeculativeGame<S, A>

Consumer-owned description of a deterministic turn-based game, used by SpeculativeSequencer to apply, snapshot, and restore game state.

The three operations together form the state-management contract that enables optimistic apply with rollback + replay:

  • apply drives the game forward one action at a time — used for both optimistic apply and deterministic replay.

  • snapshot captures an authoritative checkpoint after every confirmed action — the rollback origin.

  • restore reinstates a snapshot as the current state — the first step of a rollback before replay.

Constraints

  • apply must be deterministic and pure. Given the same state and action, it must always produce an identical successor state. Non-determinism (e.g. reading a clock or random number) breaks replay correctness.

  • snapshot must produce an independent copy. If S is mutable, snapshot must deep-copy the state; if S is immutable (e.g. a data class), the identity function { it } suffices.

  • Serialization is the caller's responsibility. SpeculativeSequencer does not serialize Ssnapshot and restore are an in-memory contract only.

Log compaction

When Raft installs a compacted snapshot to catch a lagging node up, the install surfaces on TurnSequencer.events as a TurnEvent.Reset. SpeculativeSequencer handles it by rehydrating: it discards its pending-input buffer (the install resets the committed log to a point the buffer may pre-date) and rebuilds the authoritative state from the snapshot via fromSnapshot. Subsequent committed actions fold on top of the rehydrated baseline. Implement fromSnapshot if your session enables log compaction; the default throws, which fails loud the first time a snapshot install arrives rather than silently corrupting state.

Type Parameters

S

The game-state type.

A

The action type.

Functions

Link copied to clipboard
abstract fun apply(state: S, action: A): S

Returns the successor state after applying action to state.

Link copied to clipboard
open fun fromSnapshot(bytes: ByteArray): S

Rebuilds the authoritative game state from a Raft snapshot install's embedded bytes.

Link copied to clipboard
abstract fun restore(snapshot: S): S

Returns the game state represented by snapshot.

Link copied to clipboard
abstract fun snapshot(state: S): S

Returns an independent snapshot of state that SpeculativeSequencer can hold as the authoritative rollback origin.