← Back to Official Package Registry
Tier 2: Distributed & Wire Protocols • Consensus & Gossipv1.0.0 • 37 KB • Ed25519 Verified

cluster_raft@1.0.0

Deterministic Raft leader election, replicated log & quorum commit state machine plus SWIM gossip membership & failure detector.

use [cluster_raft]use [cluster_raft/swim]
veko pkg add cluster_raft@1.0.0
Run in Browser PlaygroundDownload 1.0.0.vkpRaw demo.vk

cluster_raft

Embeddable pure-Veko deterministic Raft Consensus Engine (Ongaro & Ousterhout) and SWIM Infection-Style Gossip Membership (cluster_raft, cluster_raft/swim).

Overview

cluster_raft provides deterministic consensus and decentralized failure detection for distributed Veko services without coupling the core state machines to a fixed network transport:

  • cluster_raft:
  • Explicit I/O-free state machine implementing the Raft consensus algorithm (.follower, .candidate, .leader).
  • Term monotonicity, RequestVote with Section 5.4.1 Election Restriction (up-to-date log comparison), majority quorum promotion, AppendEntries prevLogIndex/prevLogTerm consistency verification, fast conflict_index log backup, conflicting tail truncation, Section 5.4.2 current-term majority commit rule, and an integrated replicated key-value state machine (kv_state).
  • cluster_raft/swim:
  • Scalable Weakly-consistent Infection-style Process Group Membership (Das, Gupta, Motivala).
  • Randomized k-peer probe selection (ping / ping-req(k)), .alive / .suspect / .dead state precedence, automatic self-suspicion refutation via incarnation number increments, bounded O(log N) infection-style piggybacked event dissemination, and tick-driven suspicion timeout sweeps.

Installation

powershell
veko pkg add cluster_raft@1.0.0

Import the modules in .vk source files:

rebol
use [
    raft = cluster_raft
    swim = cluster_raft/swim
]

Wire Protocol & Architecture Notes

Deterministic Step-Driven Raft Engine

Rather than hiding background sockets or wall-clock timers inside opaque threads, RaftNode exposes pure state-transition functions (tick-election, handle-request-vote, handle-vote-response, propose, build-append-entries, handle-append-entries, handle-append-response). Callers can drive RaftNode over grpc_proto, TCP streams, UDP packets, channels, or deterministic fault-injection simulators.

Safety invariants enforced by cluster_raft:

  1. Election Safety & Log Completeness (Section 5.4.1): handle-request-vote grants at most one vote per term and only when (req.last_log_term > local_term) or (req.last_log_term == local_term and req.last_log_index >= local_index).
  2. Log Matching & Tail Truncation (Section 5.3): handle-append-entries verifies prev_log_index and prev_log_term before mutating the log, truncates suffixes only when an existing index has a conflicting term, and returns conflict_index (first index of the conflicting term) so leaders converge in one round per conflicting term.
  3. Current-Term Commit Rule (Section 5.4.2): handle-append-response advances commit_index to N only when log[N].term == node.current_term and N is replicated on quorum-size nodes, preventing the classic Figure 8 stale-term overwrite hazard.

SWIM Bounded-Infection Gossip

MemberList maintains per-peer { state, incarnation, updated_tick } records and an outbox of GossipEvent items piggybacked onto protocol probes via drain-piggyback. Each event is transmitted at most retransmit_mult * ceil(log2(N + 1)) times, achieving epidemic cluster convergence with constant per-node message overhead.

Complete API Reference

cluster_raft

  • Structs: LogEntry, RequestVoteReq, RequestVoteResp, AppendEntriesReq, AppendEntriesResp, RaftNode
  • Functions:
  • new-node [id str, peers block[str]] RaftNode
  • quorum-size [node RaftNode] i64
  • last-log-index [node RaftNode] i64 / last-log-term [node RaftNode] i64 / term-at-index [node RaftNode, idx i64] i64
  • tick-election [mut node RaftNode] RequestVoteReq
  • handle-request-vote [mut node RaftNode, req RequestVoteReq] RequestVoteResp
  • handle-vote-response [mut node RaftNode, resp RequestVoteResp] enum
  • propose [mut node RaftNode, cmd map] LogEntry
  • propose-put [mut node RaftNode, key str, val any] LogEntry
  • propose-del [mut node RaftNode, key str] LogEntry
  • kv-get [node RaftNode, key str] any
  • build-append-entries [node RaftNode, peer_id str] AppendEntriesReq
  • handle-append-entries [mut node RaftNode, req AppendEntriesReq] AppendEntriesResp
  • handle-append-response [mut node RaftNode, resp AppendEntriesResp] i64

cluster_raft/swim

  • Structs: Member, GossipEvent, MemberList
  • Functions:
  • new-member-list [self_id str, self_addr str /seed rng_seed i64 = 42] MemberList
  • join-member [mut ml MemberList, id str, addr str /incarnation inc i64 = 0] enum
  • suspect-node [mut ml MemberList, target_id str] bool
  • refute-suspicion [mut ml MemberList /min-incarnation min_inc i64 = -1] i64
  • confirm-dead [mut ml MemberList, target_id str] bool
  • advance-tick [mut ml MemberList] block[str]
  • apply-gossip [mut ml MemberList, events block[GossipEvent]] i64
  • select-probe-targets [mut ml MemberList, k i64] block[Member]
  • drain-piggyback [mut ml MemberList, max_events i64] block[GossipEvent]
  • max-transmits [ml MemberList] i64
  • get-member [ml MemberList, id str] Member
  • alive-members [ml MemberList] block[Member]

Idiomatic Veko Examples

3-Node Raft Election and Replicated KV Commit

rebol
use [raft = cluster_raft]

ids = ['n1' 'n2' 'n3']
mut n1 = raft/new-node 'n1' ids
mut n2 = raft/new-node 'n2' ids
mut n3 = raft/new-node 'n3' ids

rv = raft/tick-election mut n1
_ = raft/handle-vote-response mut n1 (raft/handle-request-vote mut n2 rv)

_ = raft/propose-put mut n1 'leader_addr' '10.0.0.1:9000'
ae = raft/build-append-entries n1 'n2'
resp = raft/handle-append-entries mut n2 ae
_ = raft/handle-append-response mut n1 resp

print (raft/kv-get n1 'leader_addr')

SWIM Suspicion and Incarnation Refutation

rebol
use [swim = cluster_raft/swim]

mut n1 = swim/new-member-list 'n1' '10.0.0.1:7946'
mut n2 = swim/new-member-list 'n2' '10.0.0.2:7946'
_ = swim/join-member mut n1 'n2' '10.0.0.2:7946'
_ = swim/join-member mut n2 'n1' '10.0.0.1:7946'

_ = swim/suspect-node mut n1 'n2'
rumor = swim/drain-piggyback mut n1 4
_ = swim/apply-gossip mut n2 rumor

refutation = swim/drain-piggyback mut n2 4
_ = swim/apply-gossip mut n1 refutation
print (swim/get-member n1 'n2').state
packages/cluster_raft/examples/demo.vkSelf-contained runnable example & assertion suite
Raw .vk
// packages/cluster_raft/examples/demo.vk
// Self-contained verification suite & cluster simulation for `cluster_raft` and `cluster_raft/swim`.

use [
	raft = cluster_raft
	swim = cluster_raft/swim
]

assert-true = fn [cond bool, label str] enum [
	if not cond [
		println (str/join ['[FAIL] ' label] '')
		os/exit 1
	]
	print (str/join ['[PASS] ' label] '')
	.ok
]

replicate-one-round = fn [mut leader raft/RaftNode, followers block[raft/RaftNode]] block[raft/RaftNode] [
	mut updated = []
	mut i = 0
	while i < (len followers) [
		mut f = followers[i]
		ae = raft/build-append-entries leader f.id
		resp = raft/handle-append-entries mut f ae
		_ = raft/handle-append-response mut leader resp
		push mut updated f
		i = i + 1
	]
	updated
]

// --- 1. 5-Node Raft Cluster Election in Term 1 ---
all_ids = ['n1' 'n2' 'n3' 'n4' 'n5']
mut n1 = raft/new-node 'n1' all_ids
mut n2 = raft/new-node 'n2' all_ids
mut n3 = raft/new-node 'n3' all_ids
mut n4 = raft/new-node 'n4' all_ids
mut n5 = raft/new-node 'n5' all_ids

rv1 = raft/tick-election mut n1
v2 = raft/handle-request-vote mut n2 rv1
v3 = raft/handle-request-vote mut n3 rv1
_ = raft/handle-vote-response mut n1 v2
role_after_quorum = raft/handle-vote-response mut n1 v3

_ = assert-true (role_after_quorum == .leader and n1.current_term == 1 and (raft/quorum-size n1) == 3) '5-node Raft cluster elects n1 as leader in term 1 upon 3/5 quorum'

// --- 2. Quorum Log Replication & Deterministic KV State Machine ---
_ = raft/propose-put mut n1 'region' 'ca-west-1'
_ = raft/propose-put mut n1 'epoch' 10
_ = raft/propose-put mut n1 'temp_key' 'ephemeral'
_ = raft/propose-del mut n1 'temp_key'

// Round 1 replicates entries 1..4 to followers and advances n1.commit_index = 4;
// Round 2 heartbeats leader_commit = 4 so all followers apply entries 1..4 to kv_state.
mut peers_r1 = replicate-one-round mut n1 [n2 n3 n4 n5]
peers_r2 = replicate-one-round mut n1 peers_r1
n2 = peers_r2[0]
n3 = peers_r2[1]
n4 = peers_r2[2]
n5 = peers_r2[3]

rep_ok_1 = n1.commit_index == 4 and (raft/kv-get n1 'epoch') == 10 and (not (map/has? n1.kv_state 'temp_key'))
rep_ok_2 = n2.commit_index == 4 and (raft/kv-get n2 'region') == 'ca-west-1' and (raft/kv-get n4 'epoch') == 10 and (raft/kv-get n5 'epoch') == 10
_ = assert-true (rep_ok_1 and rep_ok_2) 'quorum replication commits and applies KV mutations across all 5 nodes'

// --- 3. Network Partition: Minority Leader Cannot Commit; Majority Elects Term-2 Leader ---
// Partition: {n1, n5} isolated from majority {n2, n3, n4}.
// Old leader n1 proposes an entry that replicates only to n5 (2/5 < quorum 3 -> uncommitted!).
_ = raft/propose-put mut n1 'split_brain' 'stale-term-1'
ae_n5 = raft/build-append-entries n1 'n5'
resp_n5 = raft/handle-append-entries mut n5 ae_n5
_ = raft/handle-append-response mut n1 resp_n5
_ = assert-true (n1.commit_index == 4 and (not (map/has? n1.kv_state 'split_brain'))) 'isolated minority leader (2/5) cannot advance commit_index'

// Majority partition {n2, n3, n4} elects n2 in term 2
rv_t2 = raft/tick-election mut n2
v3_t2 = raft/handle-request-vote mut n3 rv_t2
v4_t2 = raft/handle-request-vote mut n4 rv_t2
_ = raft/handle-vote-response mut n2 v3_t2
_ = raft/handle-vote-response mut n2 v4_t2
_ = assert-true (n2.role == .leader and n2.current_term == 2) 'majority partition {n2, n3, n4} elects n2 as leader in term 2'

// Verify §5.4.1 Election Restriction: a lagging candidate with older log is denied vote
mut lagging = raft/new-node 'lagging' all_ids
put mut lagging .current_term 2
stale_rv = raft/tick-election mut lagging
// lagging is at term 3, but its last_log_term = 0 < n3.last_log_term = 1!
deny_resp = raft/handle-request-vote mut n3 stale_rv
_ = assert-true ((not deny_resp.vote_granted) and n3.current_term == 3) 'Raft section 5.4.1 rejects candidate with less up-to-date log'

// Advance n2 to term 4 so {n2, n3, n4} continue cleanly after the term-3 probe
put mut n2 .current_term 3
rv_t4 = raft/tick-election mut n2
_ = raft/handle-vote-response mut n2 (raft/handle-request-vote mut n3 rv_t4)
_ = raft/handle-vote-response mut n2 (raft/handle-request-vote mut n4 rv_t4)

_ = raft/propose-put mut n2 'epoch' 20
_ = raft/propose-put mut n2 'leader' 'n2'
mut maj_p1 = replicate-one-round mut n2 [n3 n4]
maj_p2 = replicate-one-round mut n2 maj_p1
n3 = maj_p2[0]
n4 = maj_p2[1]
_ = assert-true (n2.commit_index == 6 and (raft/kv-get n2 'epoch') == 20 and (raft/kv-get n3 'leader') == 'n2') 'new leader n2 commits entries 5..6 across majority quorum'

// --- 4. Partition Heal: Old Leader Steps Down & Truncates Conflicting Uncommitted Tail ---
// When n2 sends AppendEntries to n1 & n5, initial next_index=7 fails consistency at prev_log_index=6,
// backs up via conflict_index to overwrite index 5 (term 1 -> term 4), and reconciles kv_state!
mut healed = [n1 n5]
mut sync_round = 0
while sync_round < 3 [
	healed = replicate-one-round mut n2 healed
	sync_round = sync_round + 1
]
n1 = healed[0]
n5 = healed[1]

heal_ok_1 = n1.role == .follower and n1.current_term == 4 and n1.leader_id == 'n2' and n1.commit_index == 6
heal_ok_2 = (raft/kv-get n1 'epoch') == 20 and (raft/kv-get n1 'leader') == 'n2' and (not (map/has? n1.kv_state 'split_brain'))
heal_ok_3 = (raft/kv-get n5 'epoch') == 20 and (len n1.log) == 6 and (len n5.log) == 6
_ = assert-true (heal_ok_1 and heal_ok_2 and heal_ok_3) 'healed old leader n1 steps down, truncates uncommitted split-brain tail, and reconciles KV state'

// --- 5. SWIM 5-Node Gossip, Suspicion Refutation & Dead Confirmation ---
mut s1 = swim/new-member-list/seed 's1' '10.0.0.1:7946' 101
mut s2 = swim/new-member-list/seed 's2' '10.0.0.2:7946' 202
mut s3 = swim/new-member-list/seed 's3' '10.0.0.3:7946' 303

mut idx = 1
while idx <= 5 [
	id = str/join ['s' (mold idx)] ''
	addr = str/join ['10.0.0.' (mold idx) ':7946'] ''
	if id != 's1' [ _ = swim/join-member mut s1 id addr ]
	if id != 's2' [ _ = swim/join-member mut s2 id addr ]
	if id != 's3' [ _ = swim/join-member mut s3 id addr ]
	idx = idx + 1
]

probes = swim/select-probe-targets mut s1 3
_ = assert-true ((len probes) == 3 and probes[0].id != 's1' and probes[1].id != 's1') 'SWIM randomized k-peer probe target selection excludes self'

// s1 suspects s3 -> gossips to s2 -> s2 gossips to s3 -> s3 refutes by bumping incarnation to 1!
_ = swim/suspect-node mut s1 's3'
pkt_1_to_2 = swim/drain-piggyback mut s1 8
_ = swim/apply-gossip mut s2 pkt_1_to_2
_ = assert-true ((swim/get-member s2 's3').state == .suspect) 'SWIM suspicion rumor propagates via piggybacked gossip'

pkt_2_to_3 = swim/drain-piggyback mut s2 8
_ = swim/apply-gossip mut s3 pkt_2_to_3
refute_pkt = swim/drain-piggyback mut s3 8
_ = swim/apply-gossip mut s1 refute_pkt
_ = swim/apply-gossip mut s2 refute_pkt
m3_on_s1 = swim/get-member s1 's3'
m3_on_s2 = swim/get-member s2 's3'
_ = assert-true (s3.incarnation == 1 and m3_on_s1.state == .alive and m3_on_s1.incarnation == 1 and m3_on_s2.state == .alive) 'SWIM node s3 refutes false suspicion via incarnation bump (0 -> 1)'

// Crash s5 and advance ticks past suspect_timeout_ticks (5) -> confirmed .dead
_ = swim/suspect-node mut s1 's5'
mut t = 0
mut dead_ids = []
while t < 5 [
	exp = swim/advance-tick mut s1
	if (len exp) > 0 [ dead_ids = exp ]
	t = t + 1
]
_ = assert-true ((len dead_ids) == 1 and dead_ids[0] == 's5' and (swim/get-member s1 's5').state == .dead and (len (swim/alive-members s1)) == 4) 'SWIM confirms unresponsive suspect peer s5 as .dead after timeout ticks'

print 'cluster_raft: all verification checks passed'
Cryptographic Provenance

Ed25519 Signature & Merkle Integrity

Registry URL: https://veko-lang.org/pkg/cluster_raft/1.0.0.vkp
Archive SHA-256: 0a2103b9ca8853a7db87a558a67167adfcee7510e336056779ec043b794ad7aa
Merkle Root: ee1d325d8b12d4ca7a220720c517f557acf8069b3f2acd6226ddc65cf166d87d
Signer Trust Key: ed25519:27406074d8681da1d4e6420f5d887cac15c313334c249ac047ba9d4e2df72b70
Embedded VKP1 Manifest

manifest.json

{"name":"cluster_raft","version":"1.0.0","tier":2.0,"tier_label":"Tier 2: Distributed & Wire Protocols","category":"Consensus & Gossip","description":"Deterministic Raft leader election, replicated log & quorum commit state machine plus SWIM gossip membership & failure detector.","modules":["cluster_raft","cluster_raft/swim"],"homepage":"https://veko-lang.org/packages/cluster_raft"}
Bundle Entry PathSizeLeaf SHA-256 Digest
README.md6 KB73a30f7327babfa0919365f8c9017ab2729ce61947c4eed501f5f0590daa3d48
examples/demo.vk7 KB18a8af00dfa3e3ac2eccaa066d037c86f7e2f6d1b9325b12816f210e5f574332
mod.vk13 KB4716892def758d082bc4ff8061a815300dac6ae94fc3b1f92bab5e4aafb1c58b
swim.vk9 KB3470d675010f02c6c54455db18896949b94a3494d5a82e95ce63941050d7083c