MultiNodeRaftSim

class MultiNodeRaftSim(val nodeIds: List<NodeId>, scope: CoroutineScope, nodeScope: CoroutineScope, baseConfig: RaftConfig = MULTI_NODE_SIM_BASE_CONFIG, baseSeed: Long = MULTI_NODE_SIM_SEED, maxPayloadBytes: Int? = null, nodeFactory: (NodeStart) -> RaftNode = defaultNodeFactory(nodeIds, baseConfig))

Multi-node Raft simulation harness for use in tests. See the file-level KDoc for the full determinism contract and setup ceremony.

Parameters

nodeIds

The ordered list of voter NodeIds forming the initial cluster config.

scope

The test's TestScope — used for withTimeout bounds in the await helpers.

nodeScope

Scope for node coroutines — pass TestScope.backgroundScope so the infinite heartbeat/election loops are cancelled at test teardown without kotlinx.coroutines.test.UncompletedCoroutinesError.

baseConfig

Timing parameters for every node. RaftConfig.random is overridden per node and per start (Random(simNodeSeed(baseSeed, nodeIndex, start)), see below) to ensure distinct election timeouts and guarantee convergence. Must have RaftConfig.expectVirtualTime = true for tests running under a kotlinx.coroutines.test.TestDispatcher. Defaults to MULTI_NODE_SIM_BASE_CONFIG.

baseSeed

Seed from which per-node Randoms are derived. Change to explore different election orderings; the default MULTI_NODE_SIM_SEED is stable across runs.

maxPayloadBytes

Optional payload cap forwarded to MultiNodeRaftNetwork — forces InstallSnapshot chunking in tests that exercise the snapshot-transfer path.

nodeFactory

Override to wire a custom RaftNode implementation. It is called once per start of a node, at construction and again on every restart, with a NodeStart carrying the node's id, transport, storage and scope, the start count, and that start's seeded NodeStart.random. The default wires CoroutineScope.raftNode with baseConfig.copy(random = start.random); a custom factory seeds RaftConfig.random from NodeStart.random the same way, and then derives exactly as a default node would.

A restart is a new process, so it gets a new seed

The sim seeds a node's first start with baseSeed + nodeIndex, and its k-th restart with a seed that differs from every earlier one (simNodeSeed). It never reuses one, and it picks the seed itself, so no factory can pick a wrong one (#3659). A us.tractat.kuilt.raft.ClientIdentity.Auto node mints its client id from RaftConfig.random, and the library promises that id changes on restart; in production it does, because the process draws from fresh entropy. Reseeding a restart with its first seed brings the old id back, and the restarted node's first forward reuses the old incarnation's (clientId, requestId) with different bytes, which the leader refuses with us.tractat.kuilt.raft.RequestIdConflictException (#3425).

The seed stays a pure function of baseSeed, the node's index and its start count — no clock, no entropy — so one baseSeed replays the same run, restarts included, on every target.

Constructors

Link copied to clipboard
constructor(nodeIds: List<NodeId>, scope: CoroutineScope, nodeScope: CoroutineScope, baseConfig: RaftConfig = MULTI_NODE_SIM_BASE_CONFIG, baseSeed: Long = MULTI_NODE_SIM_SEED, maxPayloadBytes: Int? = null, nodeFactory: (NodeStart) -> RaftNode = defaultNodeFactory(nodeIds, baseConfig))

Properties

Link copied to clipboard

The in-process channel network shared by all nodes. Use to inject partitions or raw messages.

Link copied to clipboard
Link copied to clipboard

Live node map — entries are removed on crash and re-added on restart.

Link copied to clipboard

Per-node durable storage — each node's log, term, and vote.

Functions

Link copied to clipboard

The applied state for id — ordered concatenation of committed commands, reset on a snapshot install. Two nodes with equal applied state have applied the same sequence of commands.

Link copied to clipboard
inline fun <reified T : RaftTraceEvent> assertNotTraced(id: NodeId, message: String = "matching event", predicate: (T) -> Boolean = { true })

Assert that no retained event of type T satisfies predicate. message describes the forbidden predicate on failure. This proves absence only in traceOf's retained snapshot, not in the node's complete history, and does not wait for future events.

Link copied to clipboard
inline fun <reified T : RaftTraceEvent> assertTraced(id: NodeId, message: String = "matching event", predicate: (T) -> Boolean = { true }): T

Assert that id's retained transcript contains an event of type T satisfying predicate. Returns the first match. message describes the predicate in a failure transcript. This does not wait; the snapshot and retention limits of traceOf apply.

Link copied to clipboard
fun assertTracedInOrder(id: NodeId, vararg predicates: (RaftTraceEvent) -> Boolean, message: String = "ordered trace subsequence")

Assert an ordered subsequence of id's retained transcript. Each predicate consumes a distinct event in collection order; unrelated events may appear between matches. An empty sequence passes. On failure, message and the first unmatched step accompany the recent transcript. This does not wait; traceOf's snapshot and retention limits apply.

Link copied to clipboard
suspend fun awaitCommit(index: Long, on: Collection<NodeId> = nodeIds, within: Duration = DEFAULT_AWAIT)

Suspend until index is committed on every node in on; fail fast with a state dump otherwise.

Link copied to clipboard
suspend fun awaitLeader(within: Duration = DEFAULT_AWAIT): RaftNode

Suspend until some node is RaftRole.Leader; return it, or fail fast with a state dump.

suspend fun awaitLeader(among: Set<NodeId>, within: Duration = DEFAULT_AWAIT): RaftNode

Suspend until a node whose id is in among is RaftRole.Leader. Use after a partition when a stale leader from the minority partition may transiently report leader status — scope the await to the surviving voters.

Link copied to clipboard
suspend fun awaitRole(id: NodeId, role: RaftRole, within: Duration = DEFAULT_AWAIT)

Suspend until node id holds role; fail fast with a state dump otherwise.

Link copied to clipboard
suspend fun awaitTrue(what: String, within: Duration = DEFAULT_AWAIT, cond: () -> Boolean)

Suspend until cond holds (polled each virtual ms); fail fast with a state dump on timeout.

Link copied to clipboard
suspend fun checkInvariants()

Assert election safety (at most one leader at a time) and state-machine safety (no two nodes committed different commands at the same log index up to the minimum known commit).

Link copied to clipboard
fun crash(id: NodeId)

Cancel node id's coroutine scope, simulating a crash. Use restart to bring it back up.

Link copied to clipboard
fun dropLink(from: NodeId, to: NodeId)

Drop messages from from to to (unidirectional). Restore with heal.

Link copied to clipboard
suspend fun dumpState(reason: String): String

Render a per-node diagnostic snapshot — roles, terms, commit indices, the durable per-term leader pin, log ranges, and an election-event histogram (Timeout / BecomeLeader / BecomeFollower) that makes leadership thrash and term inflation visible at a glance. Used as the body of the AssertionError thrown by the bounded await helpers on non-convergence, and callable directly from a failing test assertion.

Link copied to clipboard

All nodes currently reporting RaftRole.Follower.

Link copied to clipboard
fun heal()

Restore all links cleared by partition or dropLink.

Link copied to clipboard

The current leader, or null if none is known.

Link copied to clipboard
fun partition(a: Set<NodeId>, b: Set<NodeId>)

Partition nodes into two groups — messages in both directions between any node in a and any node in b are silently dropped. Restore with heal.

Link copied to clipboard

Isolate id from every other node — the offline-follower scenario. Restore with heal.

Link copied to clipboard
suspend fun proposeOnLeader(command: ByteArray, among: Set<NodeId>? = null, within: Duration = DEFAULT_AWAIT): LogEntry

Propose against the current leader, re-acquiring and retrying on NotLeaderException. Returns the committed us.tractat.kuilt.raft.LogEntry. Restricts to among if provided.

Link copied to clipboard
fun restart(id: NodeId)

Restart a previously crashed node using its durable storages entry.

Link copied to clipboard
suspend fun settle()

Let pending work at the current virtual instant drain without advancing the clock. Under StandardTestDispatcher's FIFO scheduling, yielding hands the single test thread back so already-scheduled coroutines (e.g. a freshly launched collector) run at this instant. Call after launching a collector you need to observe the next emission.

Link copied to clipboard

Snapshot of id's recorded events, oldest first, detached from the live ring. Only the most recent TRACE_RING_CAPACITY events are retained. A crashed node keeps its transcript; restart starts a fresh one. An unknown id is rejected.