Liking cljdoc? Tell your friends :D

urd.consensus.algorithms.raft

Raft as a pure state machine on urd.consensus.node.

Ported from etcd-io/raft (read at Aug 2026). Scope: leader election with PreVote, log replication with per-peer progress, durable hard state and log entries, log truncation on a conflicting suffix, and membership changes including joint consensus. Out of scope: snapshots, leadership transfer, read-index/lease reads, CheckQuorum, and inflight-based flow control.

The durability barrier

raft.go:546 routes exactly {MsgAppResp, MsgVoteResp, MsgPreVoteResp} into msgsAfterAppend; everything else is sent immediately. Those three are the node's binding commitments: acknowledging an append or publishing a vote is a promise that survives a restart. Here they go into :then of a persist-then and everything else is a bare :send.

durable? follows MustSync (rawnode.go:191-198): fsync iff entries are non-empty, or the vote changed, or the term changed. A commit-index change alone is recoverable by replay, so it is a buffered write.

The self-addressed message, and why we do not use one

etcd-raft models the leader's own durability as a MsgAppResp from itself to itself, delayed by the fsync (raft.go:845), and the candidate's self-vote as a MsgVoteResp from itself to itself (raft.go:1059). That removes the leader/follower asymmetry from commit advancement: the leader's own entry counts toward the quorum only once durable, exactly like everyone else's.

We keep the semantics but not the mechanism. urd has no effect for "deliver this event to myself", and routing a self-addressed message through [:send ...] would send it over the simulated network, where it can be delayed, duplicated, or dropped -- a self-ack that the drop-rate can lose is a liveness bug. Instead the node associates each local append acknowledgement and self-vote with the write that carries it, then consumes it on persisted. The ordering guarantee is identical (the ack lands after the write is durable, before the gated messages go out), and it stays inside the state machine.

The ABA hazard

rawnode.go:266-363 explains it at length: a persist completion must be dropped if the term changed while it was in flight, or a stale completion marks entries durable that a newer append has since overwritten. urd's persist-then carries :epoch and the persisted event echoes it, so we set :epoch to the term at issue time and treat a mismatch as a no-op.

Completions are correlated by a CALLER-SUPPLIED token: we mint one per write, key :pending-writes by it, and match on the way back.

This was originally a FIFO queue, popped from the front, on the assumption that interpreters complete writes in issue order. urd's own simulator does not: a non-durable write completes at the current tick while a durable one completes persist-latency ticks later (sim.cljc:178), so a LATER buffered write routinely lands before an EARLIER fsync. And because an outstanding self-ack forces a write on every subsequent step, that reordering was the default path rather than a rare race -- the leader counted its own entry as durable while the entry was still in flight, which is the exact loss this barrier exists to prevent.

Truncation

log.go:109-131 (maybeAppend) plus log_unstable.go:191-213 (truncateAndAppend). etcd-raft leaves the truncation implicit -- storage has to infer it from an append at a lower index. We set :truncate-from on the persist-then instead. Note that a conflict at or below the commit index is a Raft invariant violation; etcd-raft panics, and so do we.

Portability

Everything here is .cljc with no host interop except one character-code helper. Time is logical (set-timer, in ticks) and the randomized election timeout is derived from a portable hash of (peer-id, term) rather than from a host PRNG -- urd has no effect that yields a random number, only one that yields random peers.

Raft as a pure state machine on `urd.consensus.node`.

Ported from `etcd-io/raft` (read at Aug 2026). Scope: leader election with
PreVote, log replication with per-peer progress, durable hard state and log
entries, log truncation on a conflicting suffix, and membership changes
including joint consensus. Out of scope: snapshots, leadership transfer,
read-index/lease reads, CheckQuorum, and inflight-based flow control.

## The durability barrier

`raft.go:546` routes exactly {MsgAppResp, MsgVoteResp, MsgPreVoteResp} into
`msgsAfterAppend`; everything else is sent immediately. Those three are the
node's binding commitments: acknowledging an append or publishing a vote is a
promise that survives a restart. Here they go into `:then` of a `persist-then`
and everything else is a bare `:send`.

`durable?` follows `MustSync` (`rawnode.go:191-198`): fsync iff entries are
non-empty, or the vote changed, or the term changed. A commit-index change
alone is recoverable by replay, so it is a buffered write.

## The self-addressed message, and why we do not use one

etcd-raft models the leader's own durability as a `MsgAppResp` from itself to
itself, delayed by the fsync (`raft.go:845`), and the candidate's self-vote as
a `MsgVoteResp` from itself to itself (`raft.go:1059`). That removes the
leader/follower asymmetry from commit advancement: the leader's own entry
counts toward the quorum only once durable, exactly like everyone else's.

We keep the *semantics* but not the mechanism. urd has no effect for
"deliver this event to myself", and routing a self-addressed message through
`[:send ...]` would send it over the simulated network, where it can be
delayed, duplicated, or dropped -- a self-ack that the drop-rate can lose is a
liveness bug. Instead the node associates each local append acknowledgement and self-vote
with the write that carries it, then consumes it on `persisted`. The
ordering guarantee is identical (the ack lands after the write is durable,
before the gated messages go out), and it stays inside the state machine.

## The ABA hazard

`rawnode.go:266-363` explains it at length: a persist completion must be
dropped if the term changed while it was in flight, or a stale completion
marks entries durable that a newer append has since overwritten. urd's
`persist-then` carries `:epoch` and the `persisted` event echoes it, so we set
`:epoch` to the term at issue time and treat a mismatch as a no-op.

Completions are correlated by a CALLER-SUPPLIED token: we mint one per write,
key `:pending-writes` by it, and match on the way back.

This was originally a FIFO queue, popped from the front, on the assumption
that interpreters complete writes in issue order. urd's own simulator does
not: a non-durable write completes at the current tick while a durable one
completes `persist-latency` ticks later (`sim.cljc:178`), so a LATER buffered
write routinely lands before an EARLIER fsync. And because an outstanding
self-ack forces a write on every subsequent step, that reordering was the
default path rather than a rare race -- the leader counted its own entry as
durable while the entry was still in flight, which is the exact loss this
barrier exists to prevent.

## Truncation

`log.go:109-131` (`maybeAppend`) plus `log_unstable.go:191-213`
(`truncateAndAppend`). etcd-raft leaves the truncation implicit -- storage has
to infer it from an append at a lower index. We set `:truncate-from` on the
`persist-then` instead. Note that a conflict at or below the commit index is a
Raft invariant violation; etcd-raft panics, and so do we.

## Portability

Everything here is `.cljc` with no host interop except one character-code
helper. Time is logical (`set-timer`, in ticks) and the randomized election
timeout is derived from a portable hash of (peer-id, term) rather than from a
host PRNG -- urd has no effect that yields a random *number*, only one that
yields random *peers*.
raw docstring

checkpoint-recordsclj/s

(checkpoint-records st)

The durable log, rewritten as the shortest sequence that replays to st.

compact bounds MEMORY; this is what bounds the durable log, and without it a node whose in-memory log is twenty entries still replays twenty thousand on restart -- the store is the history whatever the state machine has forgotten.

Two records, and their order is the contract replay reads:

  1. the compacted boundary and the entries still held, written as one record so a :log-base can never arrive without the entries it rebases;
  2. the hard state, which is a merge and can follow.

store/checkpoint! takes records precisely so this can live here, in the namespace that knows what a Raft write means, rather than in a store that would have to guess.

The durable log, rewritten as the shortest sequence that replays to `st`.

`compact` bounds MEMORY; this is what bounds the durable log, and without it
a node whose in-memory log is twenty entries still replays twenty thousand on
restart -- the store is the history whatever the state machine has forgotten.

Two records, and their order is the contract `replay` reads:

1. the compacted boundary and the entries still held, written as one record
   so a `:log-base` can never arrive without the entries it rebases;
2. the hard state, which is a merge and can follow.

`store/checkpoint!` takes records precisely so this can live here, in the
namespace that knows what a Raft write means, rather than in a store that
would have to guess.
sourceraw docstring

committed-indexclj/s

(committed-index ids acked)

quorum/majority.go:120-162. The largest index acked by a majority of ids.

Voters with no information contribute 0, which is why the slice is filled from the right before sorting -- the unfilled slots are the zeroes that end up on the left. The answer is the element at position n - (n/2 + 1).

`quorum/majority.go:120-162`. The largest index acked by a majority of `ids`.

Voters with no information contribute 0, which is why the slice is filled from
the right before sorting -- the unfilled slots are the zeroes that end up on
the left. The answer is the element at position n - (n/2 + 1).
sourceraw docstring

compactclj/s

(compact st)
(compact st retain)

Drop applied entries below the retention window, keeping indices ABSOLUTE.

Safe only up to :applied: an entry that has not been handed to the application cannot be reconstructed from anywhere, and an entry above the commit index may still be truncated by a future leader. So the window is measured back from applied, never from last-index.

:base-term keeps the term of the entry at the new base, because prevLogTerm matching must still work across the boundary -- a follower asked to append there has to be able to answer. Compaction without it turns the boundary into a permanent mismatch.

Returns the state unchanged when there is nothing worth dropping, so callers need not check.

Drop applied entries below the retention window, keeping indices ABSOLUTE.

Safe only up to `:applied`: an entry that has not been handed to the
application cannot be reconstructed from anywhere, and an entry above the
commit index may still be truncated by a future leader. So the window is
measured back from `applied`, never from `last-index`.

`:base-term` keeps the term of the entry at the new base, because
`prevLogTerm` matching must still work across the boundary -- a follower
asked to append there has to be able to answer. Compaction without it turns
the boundary into a permanent mismatch.

Returns the state unchanged when there is nothing worth dropping, so callers
need not check.
sourceraw docstring

config-entry?clj/s

(config-entry? e)

Does this entry carry a validator set change?

Does this entry carry a validator set change?
sourceraw docstring

default-configclj/s

source

default-log-retentionclj/s

How many applied entries to keep after compacting.

etcd's SnapshotCatchUpEntries (5000 against a SnapshotCount of 10000), and its reason is worth restating because it is not obvious: compacting all the way to applied means any follower even ONE entry behind can no longer be served from the log and needs a snapshot instead -- and since sending one is slow, the leader compacts again while it is in flight. The cycle sustains itself. Retaining a tail is what breaks it.

How many applied entries to keep after compacting.

etcd's `SnapshotCatchUpEntries` (5000 against a `SnapshotCount` of 10000),
and its reason is worth restating because it is not obvious: compacting all
the way to `applied` means any follower even ONE entry behind can no longer
be served from the log and needs a snapshot instead -- and since sending one
is slow, the leader compacts again while it is in flight. The cycle sustains
itself. Retaining a tail is what breaks it.
sourceraw docstring

entry-atclj/s

(entry-at st i)

The entry at i, or nil if out of range or compacted away.

The entry at `i`, or nil if out of range or compacted away.
sourceraw docstring

find-conflictclj/s

(find-conflict st entries)

log.go:154-167. The index of the first entry whose term disagrees with ours, or the first index past our log, or 0 if the entries are all already present.

`log.go:154-167`. The index of the first entry whose term disagrees with
ours, or the first index past our log, or 0 if the entries are all already
present.
sourceraw docstring

find-conflict-by-termclj/s

(find-conflict-by-term st index term)

log.go:182-194. The max guess <= index with term(guess) <= term, or where our term is unknown. Returns [index term].

Used on BOTH sides of a rejection: the follower computes the hint, the leader consumes it to skip a whole term at a time instead of decrementing by one.

`log.go:182-194`. The max guess <= `index` with term(guess) <= `term`, or
where our term is unknown. Returns [index term].

Used on BOTH sides of a rejection: the follower computes the hint, the leader
consumes it to skip a whole term at a time instead of decrementing by one.
sourceraw docstring

joint-committed-indexclj/s

(joint-committed-index ids0 ids1 acked)

quorum/joint.go:47-56. Committed in both halves.

`quorum/joint.go:47-56`. Committed in both halves.
sourceraw docstring

joint-vote-resultclj/s

(joint-vote-result ids0 ids1 votes)

quorum/joint.go:58-75. Both halves must agree; either losing loses.

`quorum/joint.go:58-75`. Both halves must agree; either losing loses.
sourceraw docstring

last-indexclj/s

(last-index st)
source

last-termclj/s

(last-term st)
source

makeclj/s

(make)

A Raft node. Per-node configuration is supplied through the simulator's :node-config, or merged into init's config by a runtime.

Legacy compacted logs without a voter snapshot require :restored-membership with the authoritative :index, :validators and :outgoing at that index. The index must lie between the compacted boundary and the durable commit.

A Raft node. Per-node configuration is supplied through the simulator's
`:node-config`, or merged into `init`'s config by a runtime.

Legacy compacted logs without a voter snapshot require `:restored-membership`
with the authoritative `:index`, `:validators` and `:outgoing` at that index.
The index must lie between the compacted boundary and the durable commit.
sourceraw docstring

max-indexclj/s

The committed index of an EMPTY config.

etcd uses math.MaxUint64 (rendered ∞) so that a half-populated joint config behaves like the populated half under min. We use ##Inf, which is the same identity element for min and is portable -- a 64-bit unsigned literal is not, since ClojureScript has no 64-bit integers.

The committed index of an EMPTY config.

etcd uses math.MaxUint64 (rendered `∞`) so that a half-populated joint config
behaves like the populated half under `min`. We use `##Inf`, which is the same
identity element for `min` and is portable -- a 64-bit unsigned literal is
not, since ClojureScript has no 64-bit integers.
sourceraw docstring

randomized-election-timeoutclj/s

(randomized-election-timeout id term et)
(randomized-election-timeout id term draw et)

A timeout in [et, 2*et), deterministic in (peer-id, term, draw).

etcd-raft draws this from globalRand (raft.go, resetRandomizedElectionTimeout) on every reset. We cannot: a state machine may not draw a random number, and urd's :sample effect returns random PEERS, not a random number. Deriving it instead keeps runs replayable and still breaks split votes, because two nodes campaigning at once get different offsets.

draw is a per-node counter of how many times the election timer has been armed, and WITHOUT IT this function is a livelock. PreVote deliberately does not bump the term -- that is its whole point (become-pre-candidate) -- so a key of (id, term) alone is CONSTANT across repeated pre-vote rounds. Two nodes that split a pre-vote would re-campaign after exactly the same interval, split again, and do so forever, deterministically, with no term ever advancing to break the tie. etcd redraws on every reset and so has no such case; the term-keyed version resolved repeated splits only in the one configuration where the term moves.

Seeded through rng/from-key, not rng/make. xorshift32 is GF(2)-linear, so one round does not decorrelate structured seeds: with plain make, five peers won 296/367/477/400/460 elections over 2000 terms against an expectation of 400, about 5.8 sigma at the low end. Safety never depended on a fair lottery, but a skewed one makes the simulator explore a skewed space -- and the same composition made SCP's leader election degenerate completely.

A timeout in [et, 2*et), deterministic in (peer-id, term, draw).

etcd-raft draws this from `globalRand` (`raft.go`,
`resetRandomizedElectionTimeout`) on every `reset`. We cannot: a state machine
may not draw a random number, and urd's `:sample` effect returns random PEERS,
not a random number. Deriving it instead keeps runs replayable and still
breaks split votes, because two nodes campaigning at once get different
offsets.

`draw` is a per-node counter of how many times the election timer has been
armed, and WITHOUT IT this function is a livelock. PreVote deliberately does
not bump the term -- that is its whole point (`become-pre-candidate`) -- so a
key of (id, term) alone is CONSTANT across repeated pre-vote rounds. Two nodes
that split a pre-vote would re-campaign after exactly the same interval,
split again, and do so forever, deterministically, with no term ever
advancing to break the tie. etcd redraws on every reset and so has no such
case; the term-keyed version resolved repeated splits only in the one
configuration where the term moves.

Seeded through `rng/from-key`, not `rng/make`. xorshift32 is GF(2)-linear, so
one round does not decorrelate structured seeds: with plain `make`, five peers
won 296/367/477/400/460 elections over 2000 terms against an expectation of
400, about 5.8 sigma at the low end. Safety never depended on a fair lottery,
but a skewed one makes the simulator explore a skewed space -- and the same
composition made SCP's leader election degenerate completely.
sourceraw docstring

term-atclj/s

(term-at st i)

The term at index i, or nil if unknown.

Index 0 is the sentinel before an uncompacted log with term 0, which is what makes an append anchored at (index 0, term 0) match an empty log. After compaction :log-base plays the same role and :base-term is its term, so an append anchored at the boundary still matches.

The term at index `i`, or nil if unknown.

Index 0 is the sentinel before an uncompacted log with term 0, which is what
makes an append anchored at (index 0, term 0) match an empty log. After
compaction `:log-base` plays the same role and `:base-term` is its term, so
an append anchored at the boundary still matches.
sourceraw docstring

up-to-date?clj/s

(up-to-date? st cand-term cand-index)

Raft 5.4.1: is (last-term, last-index) at least as up to date as ours?

Raft 5.4.1: is (last-term, last-index) at least as up to date as ours?
sourceraw docstring

vote-resultclj/s

(vote-result ids votes)

quorum/majority.go:165-198. :won, :lost, or :pending.

Tri-state, and that matters: a candidate that has merely not-yet-won must keep waiting, while one that has lost must step down immediately.

`quorum/majority.go:165-198`. :won, :lost, or :pending.

Tri-state, and that matters: a candidate that has merely not-yet-won must keep
waiting, while one that has lost must step down immediately.
sourceraw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close