kuilt-cluster
kuilt-cluster is the server-cluster facade for kuilt-raft. It packages the two-tier overlay topology — a complete-graph voter core (K_m) plus a sparse learner periphery — as two high-level types: ServerCluster (server side) and ClusterClient (client side).
Servers and clients must run the same kuilt build. A ClusterClient is a Raft learner, so it speaks Raft's message format, and that format changes between releases: upgrading the servers strands every deployed client still on the old build, which cannot read their messages — and an old enough one does not survive them. Check an app or protocol version before starting a ClusterClient. See "Every peer in a group runs the same version" in :kuilt-raft's module documentation.
What it provides
ClusterClient (commonMain)
Wraps a Raft learner RaftNode and exposes:
propose(command)— proposes with an auto-minted monotonicrequestId. Forwards to the current leader; suspends until committed. Returns the committedLogEntry.propose(command, requestId)— cross-crash exactly-once overload. Persist therequestIdbefore calling; replay it after a crash or failover. The server'sClientSessionTable.shouldApplydeduplicates retries.committed: Flow<Committed>— the committed log stream. Single-collection contract (mirror ofRaftNode.committed): collect once perClusterClient; fan out withshareInif multiple consumers are needed.role: StateFlow<RaftRole>— alwaysRaftRole.Learnerin the relay model.close()— closes the underlyingRaftNode, stops the reconnect loop and leaves the room it joined, so the fabric sees no further dials. Idempotent, and runs on even if its caller is already cancelled. It can hang on a peer that has stopped reading; see its KDoc.
Obtain an instance via clusterClientWithNode(raftNode) (tests / caller-managed transport) or via CoroutineScope.clusterClient() (production relay-room path).
// Tests use FakeRaftNode; production uses a real raftNode over a SeamRaftTransport.
val fakeNode = FakeRaftNode(
initialRole = RaftRole.Leader,
clientId = ClientId("stable-client-id"),
)
val client: ClusterClient = clusterClientWithNode(fakeNode)
// Propose with an auto-minted requestId — at-least-once but survives failover. ClientIdentity.Auto
// only: a real node with a durable id refuses this form, which a FakeRaftNode does not model.
val entry = client.propose("set x=1".encodeToByteArray())
// Propose with a caller-pinned requestId for cross-crash exactly-once semantics.
val dedupEntry = client.propose("set y=2".encodeToByteArray(), requestId = 42L)
// Collect the committed stream and apply through ClientSessionTable for dedup.
val table = ClientSessionTable()
val committed = client.committed
.filterIsInstance<Committed.Entry>()
.first { table.shouldApply(it.entry.dedupKey) }
println("Committed at index ${committed.entry.index}")
// Report current Raft role (always Learner in the relay model).
println("Role: ${client.role.value}")
client.close()ClusterEndpoints (commonMain)
Value class holding the ordered endpoint List<Tag> and rotation policy (default: deterministic round-robin via ServerClusterReconnect).
val endpoints = ClusterEndpoints(
endpoints = listOf(serverTag1, serverTag2, serverTag3),
)VoterMesh (commonMain)
An M-voter Raft mesh — a complete-graph (K_M) cluster of voter RaftNodes. Exposes voterNodes: Map<NodeId, RaftNode>, committed: Flow<Committed> from the first voter (for single-consumer scenarios), and awaitLeader(). Node lifetimes are tied to the injected CoroutineScope.
Used directly in tests (wired via MultiNodeRaftSim from :kuilt-raft-test) and as the voter layer inside ServerCluster.
ManagedSeam (commonMain)
A Seam whose backing Seam can be hot-swapped on transport tear without recreating the RaftNode. The client builds its RoutedRaftTransport and RaftNode once over a ManagedSeam; on reconnect only the backing seam is swapped, so the node keeps its identity, log, and its single collector of incoming across failovers. This is the primitive that makes CoroutineScope.clusterClient()'s cross-server reconnect possible.
Thread-safe: the current backing-seam pointer is guarded by an atomicfu reentrant lock (never held across a suspend); incoming is a hot MutableSharedFlow stable across swaps, and each swap cancels the previous per-swap relay coroutine before starting the next, so at most one collector of any backing seam is ever live (single-collection preserved). Correct under a multi-threaded dispatcher.
ServerCluster (jvmAndAndroidMain)
Server-side cluster facade: an M-voter VoterMesh plus a relay accept loop that admits learner clients via KtorRoomHost. Each admitted WebSocket connection is a two-peer Room; the server derives the learner's NodeId from the room roster and registers the connection's spoke with the RaftRelayHub. Registering is what admits it: a reconciler on every voter, acting only while that voter leads, commits one membership change adding every registered learner it does not yet have, built from its current membership. Concurrent admissions batch into one change and never undo each other. A learner is only ever added unless the cluster is built with a learnerGrace, in which case one disconnected for that long is removed; a reconnect under the same NodeId inside the grace keeps it. The hub routes each learner-inbound frame by its RaftRelay.dest to exactly that voter's inbound and preserves the true sender as RaftRelay.origin — no leader-sniffing, no sender-restamping in either direction.
val cluster = serverScope.serverCluster(
host = KtorRoomHost(application, path = "/ws/cluster",
serverPeerId = PeerId("server-1"),
pattern = Pattern("cluster-room"),
deviceKeyStore = serverKeyStore, // this server's key
admission = HostAdmission(AdmissionPolicy.open(), RevocationList.inMemory())),
voterIds = listOf(NodeId("server-1")),
raftConfig = RaftConfig(/* … */),
)
serverScope.launch { cluster.start() } // relay accept loop
val leader = cluster.awaitLeader()
cluster.committed.collect { /* apply entries */ }
cluster.close()Dependency direction
:kuilt-cluster
api(:kuilt-core) ← Loom, Seam, PeerId, Tag
api(:kuilt-raft) ← RaftNode, ClusterConfig, ClientSessionTable, Committed
api(:kuilt-session) ← ServerClusterReconnect, SeamRoomFactory
impl(:kuilt-websocket) ← KtorRoomHost (jvmAndAndroidMain only)No arrow points back into :kuilt-core. :kuilt-session does NOT depend on :kuilt-raft — no cycle.
Failover model
On transport tear ServerClusterReconnect advances to the next endpoint from the ClusterEndpoints list and reconnects. Cross-server resume always degrades to fresh-join: each server's reconnect-window registry is in-memory and per-host-room, so server-B holds no seat for a device server-A admitted. ClusterClient leaves a torn room and joins the next endpoint fresh rather than waiting on a return the next server cannot restore. Reconnect is correct; it costs a re-snapshot on the learner's log.
Exactly-once proposals
propose(command) delegates to RaftNode.propose, which auto-mints a monotonic requestId. propose(command, requestId) is the public cross-crash exactly-once overload. The server's ClientSessionTable.shouldApply filters duplicates.
NodeId ↔ PeerId alignment constraint
Each voter's NodeId must equal NodeId(serverPeerId.value) — the server's KtorRoomHost.serverPeerId cast to a NodeId. The RaftRelayHub carries the true voter as the RaftRelay.origin (never re-stamping it with the relaying server's fabric sender), and the client's player relay transport (playerRelayTransport) maps that origin back to a NodeId for Raft routing and credit. Mismatched IDs cause silently dropped AppendEntries.
See docs/architecture.md#server-cluster-topology and docs/usage.md#server-cluster-topology-kuilt-cluster-jvmandroid.