Skip to content

fix(consensus): make raft safe and wire the service, verify farp schemas - #130

Merged
juicycleff merged 17 commits into
mainfrom
fix/consensus-discovery-farp
Nov 18, 2026
Merged

juicycleff merged 17 commits into
mainfrom
fix/consensus-discovery-farp

Conversation

@juicycleff

Copy link
Copy Markdown
Contributor

Fixes and missing wiring in extensions/consensus, extensions/discovery and farp, from a security and correctness review. Every fix has a regression test.

Raft correctness

  • Followers appended duplicate entries, so LastIndex went backwards and a node could vote for a candidate missing committed entries. AppendEntries now follows §5.3, and the commit index is computed correctly.
  • The log was never reloaded after a restart, and followers acknowledged entries they had failed to persist. Both fixed.
  • Responses were matched to the wrong request. They now carry a unique request ID and are handled once.
  • Further Raft bugs found and fixed:
    • any candidate named node-1 got every vote;
    • the leader applied entries twice;
    • single-node clusters never committed;
    • one unreachable peer stalled elections.
  • The log is now indexed by position: heartbeat reads take 11 ns at any size, where 100k entries took 91 µs.

Transports and the service

  • Transports: none of them carried Raft traffic. TCP and HTTP now use a typed, versioned envelope; TCP uses length-prefixed frames. Mutual TLS checks peer identity against the sender's certificate. Message size, timeouts and connection counts are capped. A mismatched protocol version fails with an error naming both versions.
  • Service: the consensus service now builds its storage, transport and Raft node from config, so 3-node clusters elect a leader and replicate through the extension, with and without mTLS. Options that can't be honoured fail at startup.
  • InstallSnapshot is implemented, so a follower that misses a compaction catches up.
  • Admin API: routes take an API key.

Discovery and farp

  • farp now verifies schema hashes, so one registrant can't replace another service's routes.
  • The memory registry no longer spins after Close or drops events.
  • Discovery deregisters by instance ID and authenticates gateway calls. A gateway token over plain HTTP to another host is refused unless AllowInsecureGateway is set.
  • The etcd backend honours its TLS settings, re-registers after a lost lease, and reuses or revokes leases.
  • The hls module gets the new storage dependencies it needs to build.

Behaviour changes

  • The network format changed and is now versioned. The earlier transports never carried Raft traffic, so there is no working older cluster to stay compatible with.
  • The default bind address is 127.0.0.1, and the default transport is TCP.
  • admin_api.enabled defaults to false.
  • AddNode and RemoveNode return ErrMembershipChangeUnsupported instead of falsely reporting success.
  • Not yet built, and failing clearly: the gRPC transport, membership changes, leadership transfer and encryption at rest.

Testing

go test -race passes across consensus, discovery and ./farp/..., and the hls module builds and passes. gofmt, vet and golangci-lint report 0 issues.

…orage

The log kept entries in a slice plus a map cache and found entries by
scanning. Get misses and GetEntriesAfter walked the whole log (about 90 us
per heartbeat at 100k entries) and cache eviction scanned the map on every
append once it was full. Append also accepted any index, so a follower that
received the same entries twice stored them twice and LastIndex could move
backwards.

The log is now a slice addressed by index, with entries[i].Index equal to
snapshotIndex+1+i. Get, Term and range reads are O(1) slice operations and
the separate cache is gone, since every entry after the snapshot is already
in memory. Append and AppendBatch require the next index and write to
storage before the entry becomes visible, so a failed write leaves nothing
behind that the node could acknowledge. TruncateAfter deletes the removed
entries from storage as well, and Get no longer falls back to storage,
which used to resurrect truncated entries.

load() was a placeholder, so a restarted node came back with an empty log
while storage still held its entries. It now reads the snapshot metadata
and every contiguous entry after it.

BadgerStorage and BoltDBStorage gain Batch and Close so they satisfy
internal.Storage and can back a raft node.

Benchmarks (Apple M-series, before -> after):
  heartbeat read, 100k entries   91422 ns -> 11 ns
  lagging follower read          48376 ns -> 333 ns
  append past cache size          5934 ns -> 611 ns
…ponses by request id

Follower side, following section 5.3 of the Raft paper:
- Entries the log already holds with the same term are skipped, the first
  conflicting entry truncates the log there, and only the rest is appended.
  A retransmitted or delayed AppendEntries no longer duplicates entries or
  shrinks the log, which had let a node vote for a candidate missing
  committed entries.
- commitIndex advances to min(leaderCommit, prevLogIndex+len(entries))
  instead of the local last index, which could commit a stale tail.
- Success is only reported once the entries are persisted, and a term or
  vote that cannot be persisted rejects the request or denies the vote.
- The RPC entry point and the message loop share one implementation, so
  followers now also apply committed entries on the message path.
- NewNode fails if term, vote or snapshot cannot be read instead of
  starting from zero, and restores the latest snapshot into the state
  machine.

Leader side:
- Every request gets a fresh id that the peer echoes. Request ids used to be
  fixed per peer, so a late response could be matched to a newer request
  and overstate matchIndex, and a vote granted in an old term could be
  counted in a new election.
- Responses are handled once, by the goroutine that sent the request. The
  message loop no longer runs the handler a second time with a dummy
  request, which double decremented nextIndex.
- matchIndex only moves forward and is bounded by what the request carried;
  nextIndex only backs off for the request it currently describes and uses
  the follower's last index as a hint.
- Committed entries are applied by a single applier goroutine, so the
  leader no longer applies an entry twice, and single node clusters commit.
- The candidate no longer waits for every vote RPC to finish before taking
  leadership, so one unreachable peer cannot stall an election.

Also removed a test hook that granted every vote to a candidate named
node-1 regardless of its log, and RPCHandler.Send* now wait for the real
response instead of returning an empty one. InstallSnapshot is still not
implemented; it now logs an error instead of acknowledging the snapshot as
installed, and the leader logs an error when a follower needs entries that
only exist in a snapshot.
…ports

None of the network transports could run a Raft cluster:
- TCP gob-encoded internal.Message with an interface payload whose types
  were never registered, and wrapped the connection in a bufio.Writer that
  was never flushed, so nothing arrived.
- HTTP JSON-decoded the payload into map[string]any, so every type
  assertion in the raft node failed and a three node cluster never elected
  a leader.
- gRPC logged "would send" and returned nil, and its server never listened.

TCP and HTTP now send a wire envelope with one typed, optional field per
RPC. Decoding checks that exactly the payload named by the message type is
present. TCP writes length-prefixed frames and flushes each one. New tests
start three node clusters over HTTP and over TCP, elect a leader and
replicate commands to every state machine.

The gRPC transport has no message service behind it, so Start and Send now
return ErrGRPCNotImplemented instead of pretending to work.

Resource limits:
- HTTP bodies go through MaxBytesReader(MaxMessageSize, default 4 MiB) and
  the server sets read, write and idle timeouts. One anonymous 512 MiB POST
  used to cost over 1 GiB of heap.
- TCP checks the frame length against MaxMessageSize before allocating.
  It used to accept gob values up to 1 GiB.
- Both transports cap inbound connections (MaxConnections, default 128).
  TCP tracks inbound connections and Stop closes them, instead of waiting
  up to 60s for each reader's deadline.
- HTTP opens its listener in Start, so a port that cannot be bound is an
  error for the caller rather than a log line.

Security:
- An empty Address now binds 127.0.0.1 rather than every interface.
- TCPTransportConfig and HTTPTransportConfig take a TLSConfig, built with
  the existing TLSManager, for both listener and client.
- RequirePeerIdentity rejects any message whose From is not a DNS SAN of the
  sender's verified client certificate, and dials peers with their node ID
  as the server name. It refuses to start without mutual TLS.
- TLSManager now verifies client certificates against CAFile when no
  separate ClientCAFile is given. Before, it fell back to the system roots,
  which never sign a cluster's own certificates.
…at cannot be applied

Several security settings were validated and then never read:
- admin_api.enable_auth and api_key: the admin API exposed /nodes/add,
  /nodes/remove, /apply and /read to anyone who could reach it. The
  existing AuthMiddleware returned nil after writing its 401, so it could
  not stop a request either. admin.WithAPIKey and admin.NewAPIFromConfig
  now put security.APIKeyMiddleware on every admin route. It takes a bearer
  token or X-Api-Key and compares SHA-256 digests in constant time.
  enable_auth without an api_key is a validation error, and routes
  registered without a key log a warning.
- security.enable_tls and enable_mtls: the consensus service builds no
  transport, so there was nothing to apply them to. Service.Start now fails
  when they are set and points at raft.NewNode with the transport
  package's TLSConfig, instead of starting as if traffic were protected.
  Start also warns that the service does not run a raft node yet.
- security.enable_encryption: nothing encrypts data at rest, so the option
  is rejected.

Defaults:
- bind_addr defaults to 127.0.0.1 instead of 0.0.0.0.
- transport.type defaults to tcp. grpc is rejected as not implemented and
  http is accepted.

The README and llm.txt describe the new rules. Response header literals in
the leadership middleware were changed to their canonical form so the
module lints clean. The headers sent are identical.
The gateway client cached schemas by the hash a registrant put in its
descriptor and never checked the content against it. A service that
registered first with another service's hash could make the gateway serve
its own paths under the victim's routes.

Fetched schema content is now hashed again with CalculateSchemaChecksum and
rejected on mismatch. The cache is keyed by instance ID and hash so one
registrant can never fill an entry another reads, and it is a bounded LRU
(DefaultSchemaCacheSize, configurable with WithSchemaCacheSize) instead of
an unbounded map.

WatchServices also ignores nil events, which a closed registry can deliver,
and seeds its manifest cache from the initial listing so the first watch
event no longer drops every other instance's routes.
…vents

After Close the watch goroutine kept receiving nil from the closed channel
in a tight loop and passed it to the callback, which made the gateway client
panic. notifyWatchers also discarded events once a watcher's 10-slot buffer
was full, so a slow consumer could miss a removal for good.

Each watch now has its own queue that holds the latest pending event per
instance ID and a done channel closed on Close or context cancellation.
Delivery never blocks the registry lock, memory stays bounded by the number
of instances, and the final state of every instance always reaches the
callback. A nil handler is rejected up front.
…ticate gateway calls

Stop sent DELETE /_farp/v1/deregister/{id} with the service name, unescaped,
so the gateway never matched the registration it had stored under the
instance ID. It also rebuilt the instance on shutdown, which produces a new
generated ID when none is configured. Stop now uses the instance registered
at startup and path escapes its ID, and an empty ID is an error.

Register and deregister requests carried no credentials and there was no way
to configure any. FARPConfig gains GatewayToken, sent as a bearer token on
both calls, and GatewayTLS (CA file, client cert and key, server name) for
private CAs and mutual TLS. The client is built once; an invalid TLS
configuration fails Run instead of being retried forever, and a token over
plain http logs a warning.

Also renames a loop variable that shadowed the cap builtin so the module
lints clean.
…s lease loss

TLSEnabled, TLSCAFile, TLSCert and TLSKey were ignored, so the client spoke
plaintext h2c and sent the configured username and password in the clear.
NewEtcdBackend now builds a tls.Config from them (system roots unless a CA
file is given, optional client certificate). Setting TLS files without
TLSEnabled, a certificate without its key, or an unreadable file is an error
instead of a silent fallback to plaintext.

When the keep-alive stream ended the backend granted a new lease but never
wrote its registrations again, so the service vanished from etcd once the
old lease expired. Registered instances are now remembered and put again
under the new lease, with backoff while etcd is unreachable; Deregister
forgets them so they are not resurrected. The lease ID was read and written
from several goroutines without a lock; it is now guarded, and Register
holds the same lock so it cannot write under a lease being replaced.
Register before Initialize returns ErrEtcdNotInitialized rather than
writing a key with no lease that would never expire.

Background goroutines (keep-alive, lease grants, watches) run on a context
that Close cancels, and each grant and re-put has a deadline, so Close no
longer waits on a stalled etcd call. A watch whose channel closes is
re-established instead of spinning on the closed channel.
The wire envelope now carries a protocol version, "v", starting at 1.
Receivers reject any other version, including a missing one, with
ErrProtocolVersion and an error that names both the sender's and the
receiver's version. The HTTP transport answers 400 with that error, so the
sender's Send returns it. TCP connections only carry data one way, so the
TCP receiver logs the error and closes the connection.

The network format changed in this release. The transports from earlier
releases never carried Raft traffic (TCP never flushed and could not encode
the payloads, HTTP decoded them into maps, gRPC dropped them), so there is
no working older cluster to stay compatible with. From here on, a change to
the envelope bumps the version instead of failing in confusing ways.
A follower whose next entry had been compacted into the leader's snapshot
could never catch up. The leader logged an error and stopped, and the
follower's InstallSnapshot handler dropped whatever it was sent.

Leader:
- When a peer's nextIndex falls at or before the snapshot index, the leader
  reads the stored snapshot and sends it with InstallSnapshot.
- The snapshot goes in chunks of at most Config.SnapshotChunkSize bytes
  (default 1 MiB), so each message fits the transport's MaxMessageSize.
- Once the peer installs the final chunk, the leader moves the peer's
  matchIndex and nextIndex past the snapshot.

Follower (section 7 of the Raft paper):
- Checks the term and assembles chunks in order. A chunk that does not
  continue the current snapshot is refused, and the leader starts again.
- On the last chunk it restores the state machine, persists the snapshot
  data and metadata, and moves lastApplied and commitIndex up to the
  snapshot.
- It keeps the log suffix that agrees with the snapshot and otherwise
  discards the whole log, from storage as well as memory.
- InstallSnapshotResponse gains a Success field so the leader knows the
  outcome.

Applying entries, taking a snapshot and restoring one now share a mutex, so
a snapshot always reflects exactly the index it records. Snapshots are taken
at lastApplied rather than an index chosen before the state machine was
read. Node.Snapshot exposes this for callers.

The wire envelope already carries both InstallSnapshot types. A new test
stops a follower, writes to the cluster, compacts the running nodes and
restarts the follower. The follower catches up through a snapshot sent in
40 byte chunks, ends with the same state machine as the others, and keeps
the snapshot across another restart.
Service.Start only logged the components it would build, so the extension
opened no listener and every node stayed a follower forever. It now builds
and starts, from config:
- storage: badger or boltdb under storage.path, or the new memory type
- the tcp or http transport on bind_addr:bind_port, with
  transport.max_message_size, max_connections and the timeouts
- with security.enable_tls, a TLS config built by the transport package's
  TLSManager; with enable_mtls, client certificates are also required and
  RequirePeerIdentity checks every sender against its certificate
- a memory state machine and a raft node whose peers are the configured
  peers list, with the raft timings, snapshot settings and a snapshot chunk
  size derived from the message limit

Service state comes from the raft node: role, term, leader, quorum (new
Node.HasQuorum and Node.Peers) and cluster info. Apply JSON-encodes the
command; it used to send fmt's %v form, which the state machine could not
parse. Snapshot goes through the raft node, so the log is compacted too.
StepDown works. AddNode and RemoveNode return
ErrMembershipChangeUnsupported, because the raft implementation has no
membership change protocol and changing peers outside the log could create
two majorities. They used to report success while changing nothing.

Settings that still cannot be honoured fail when the service is created:
transport grpc, storage pebble or postgres, discovery other than static,
and security.enable_encryption. The earlier refusal of enable_tls and
enable_mtls is gone because both are now applied.

With admin_api.enabled the admin routes are registered on the app router
through admin.NewAPIFromConfig, so enable_auth and api_key apply. The flag
now defaults to false. The routes were never registered before, so
turning them on by default would newly expose write endpoints.

End-to-end tests start three services from configuration over TCP and
HTTP, with and without mTLS, and replicate a command to every node. A node
whose certificate names another node is shut out of the cluster.
README and llm.txt describe the wired extension and what is still missing.
…emote hosts

With a GatewayToken and an http:// GatewayURL, the extension only logged a
warning and then sent the token in clear text on every register and
deregister. It now refuses: Run fails at startup with
ErrInsecureGatewayToken, and so does every gateway call, unless the
gateway host is loopback (localhost, 127.0.0.0/8 or ::1) or the new
FARPConfig.AllowInsecureGateway opt-in (WithFARPAllowInsecureGateway) is
set. https gateways and gateways without a token are unaffected.
The gateway client drops schemas it cannot fetch or whose content does not
match the descriptor hash, and it had no way to say so. A rejected schema
simply disappeared from the routes. The new WithLogger option takes a
*slog.Logger and logs each skipped schema with its service, instance ID,
schema type, claimed hash and the error. Without a logger the behaviour is
unchanged. slog keeps the farp packages free of a dependency on the forge
logger.
…eaks

Every time the keep-alive stream ended, the backend granted a new lease and
abandoned the old one, which then sat in etcd until its TTL ran out. A
flapping connection piled up leases.

Recovery now asks etcd how long the current lease has left. If the lease is
still alive (the stream broke, the lease did not expire), the backend keeps
it and restarts the keep-alive; the keys stay attached and nothing is
rewritten. Otherwise it grants a new lease, writes every registration under
it and revokes the old one. A lease whose registrations could not all be
written is never reused as is; the next attempt replaces and revokes it,
so at most one lease is outstanding. Grant, TimeToLive and Revoke go through
the backend's etcdOps seam, and tests cover reuse, replacement and repeated
failures.
The hls module builds consensus from the local checkout through a replace
directive. Now that the consensus service builds its own badger or bolt
storage, hls needs those modules in its go.mod and go.sum, or it fails to
build with a missing go.sum entry for badger.
@vercel

vercel Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
forge Ready Ready Preview Nov 18, 2026 1:57am UTC

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: all 15 follow conventional format

@github-actions github-actions Bot added the fix label Nov 16, 2026
@codecov

codecov Bot commented Nov 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.71329% with 19 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
farp/gateway/client.go 81.72% 11 Missing and 6 partials ⚠️
farp/registry/memory/registry.go 96.00% 1 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: some do not follow conventional format

Format

type(scope): description

Types: feat, fix, docs, style, refactor, test, chore, ci, build, perf, revert

@github-actions github-actions Bot added fix and removed fix labels Nov 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: some do not follow conventional format

Format

type(scope): description

Types: feat, fix, docs, style, refactor, test, chore, ci, build, perf, revert

@github-actions github-actions Bot removed the fix label Nov 18, 2026
@github-actions github-actions Bot added the fix label Nov 18, 2026
…ransfer and encryption (#131)

* feat(consensus): add a grpc transport for raft

The grpc transport type used to be rejected by config validation, and
GRPCTransport returned ErrGRPCNotImplemented from Start and Send. It is
now a working transport with the same guarantees as TCP and HTTP.

Each message is one unary call to forge.consensus.raft.v1.Transport/Send.
The service is described by hand and a custom codec carries the existing
JSON wire envelope as raw bytes, so there is no protoc step and the
protocol version and payload checks are shared with the other transports.
The receiver queues the message and answers with an empty reply; Raft
responses still travel as separate messages matched by request ID.

- MaxMessageSize is checked before sending and applied as the gRPC send
  and receive limits on both sides
- inbound connections are capped with the same limit listener as HTTP,
  and concurrent calls per connection with MaxConcurrentStreams
- keepalive pings on both sides with a server policy that accepts them,
  an idle timeout, a handshake timeout and a short reconnect backoff so a
  restarted peer is reachable again within a second
- TLS and mTLS from the TLSManager config; with RequirePeerIdentity the
  dialed server must hold the peer's certificate and every message's From
  must match the client certificate in the gRPC peer's TLS AuthInfo
- one client connection per peer, reused by every call
- refusals come back as gRPC statuses that Send maps to
  ErrProtocolVersion and ErrMessageTooLarge
- Stop drains for at most a second, then closes every connection,
  including ones still in the handshake, which grpc.Server.Stop would
  otherwise wait on for the whole connection timeout

Service.Start builds the transport from transport.* and security.*, and
config validation accepts grpc. ErrGRPCNotImplemented is removed; it was
never released.

Tests cover three node election and replication over gRPC in raft and
through the service, with and without mTLS, a node with a mismatched
certificate, sender spoofing, a server whose certificate names another
node, oversized messages on either side, protocol version mismatch and
malformed envelopes, the connection cap, connection reuse and Stop
returning promptly with idle connections open.

* docs(consensus): document the grpc transport

The README and llm.txt listed the gRPC transport as not implemented and
said config validation rejects it. Describe it as a supported transport
type instead, with how it carries the wire envelope and which settings it
honours.

* feat(consensus): add raft membership changes and leadership transfer

Membership (Raft dissertation section 4.1):
- The cluster configuration is a list of members, each a voter or a
  learner, with an address. It changes one server at a time through
  configuration entries in the log. A configuration takes effect as soon
  as its entry is appended, on leader and followers alike. Truncating the
  entry returns to the previous configuration.
- Node.AddNode adds the server as a learner, waits until it holds every
  committed entry, then promotes it to voter in a second entry. A learner
  receives the log but neither votes nor counts towards a majority, so an
  empty server cannot stall commits while it catches up. A server that
  does not catch up within twenty election timeouts is removed again and
  ErrLearnerNotCaughtUp is returned.
- Node.RemoveNode removes a server. The leader may remove itself: it keeps
  replicating without counting itself, and steps down once the new
  configuration commits.
- A second change is refused with ErrConfigChangeInProgress until the
  previous one has committed.
- Commit counting, elections and quorum checks use the voters of the
  current configuration. Learners, removed servers and servers started
  with the new Config.Join flag never start elections.
- The initial members come from AddPeer, or the new AddPeerAddress, which
  also records an address so servers added later can reach them.

Disruption (section 4.2.3):
- A vote request from a server that is not a voter in this node's
  configuration is ignored, as is any vote request that arrives within the
  minimum election timeout of hearing from a live leader. Neither changes
  the term.
- Without this, a server removed while it was down campaigns when it comes
  back and deposes the working leader.

Persistence:
- Configuration entries live in the log.
- The configuration in force at a snapshot's index is stored in the
  snapshot metadata and sent with InstallSnapshot.
- On restart the configuration is rebuilt from the snapshot and the
  remaining entries.

Leadership transfer (section 3.10):
- Node.TransferLeadership stops accepting client writes and membership
  changes, brings the target's log up to date, and sends it TimeoutNow.
  The target then starts an election at once, marked as a transfer so
  voters grant it although they heard from the leader recently.
- If the old leader has not been deposed within an election timeout, the
  transfer is abandoned and ErrLeadershipTransferFailed is returned. The
  old leader then resumes normal operation.
- TimeoutNow and its response are carried by the wire envelope.

The old configChangeCh path, which mutated the peer map outside the log
and was never started, is removed along with its exported message types.

Tests run on TCP clusters and cover:
- growing from three to five servers and shrinking back while a client
  keeps writing
- refusing a concurrent change and rolling back a learner that never
  caught up
- removing the leader
- a removed server campaigning without moving the leader's term
- membership surviving restart, compaction and snapshot install
- transfer to a chosen server, and abandoning a transfer to a stopped one
- blocking writes during a transfer
- reverting a truncated configuration

* feat(consensus): change membership and transfer leadership through the service

Service.AddNode, RemoveNode and TransferLeadership used to return
ErrMembershipChangeUnsupported or "not implemented". They now call the raft
node's AddNode, RemoveNode and TransferLeadership, so the admin routes for
adding and removing nodes and transferring leadership work too.

- A new join setting (Config.Join, WithJoin) starts a server that waits to
  be added instead of bootstrapping its own cluster. Its peers list then
  only tells it where the cluster is.
- The configured peers, with their addresses, seed the bootstrap
  membership through AddPeerAddress. bind_addr and bind_port become this
  node's address in membership entries.
- GetClusterManager returns a ClusterManager backed by the raft
  configuration instead of nil. AddNode and RemoveNode on it go through the
  log. UpdateNode is refused, because a member is changed by removing it
  and adding it again.
- Cluster info and counts list the members of the current configuration,
  learners included, instead of the static peer list.
- ErrMembershipChangeUnsupported is removed.

A new service test bootstraps three servers from config. It adds a fourth,
started with join, through the admin API and transfers leadership to it.
It then removes another server through the ClusterManager and checks that
writes still replicate. README and llm.txt describe the new behaviour.

* feat(consensus): encrypt raft storage at rest

security.enable_encryption is now a real feature instead of a rejected
option. The service wraps its storage backend in storage.EncryptedStorage,
which seals every value with AES-256-GCM before it reaches badger, boltdb
or memory: log entries, term, vote, snapshot data and snapshot metadata.

Each value carries a 5 byte header (format version and key ID) and a
random 96-bit nonce. The GCM additional data is the header plus the
storage key, so values cannot be edited, re-labelled or moved between
keys. Storage keys stay in plaintext because they only hold indexes and
range scans depend on them.

Keys are 32 bytes, read from a file or an environment variable at start
(inline keys only with allow_inline_encryption_key) and never logged.
encryption_keys lists several keys with IDs for rotation; the active key
writes and the others read, and Service.ReencryptStorage rewrites old
values under the active key while the node runs.

Start verifies a per key encrypted check value, so a wrong key fails at
start with ErrWrongKey. Encryption over a plaintext store fails with
ErrPlaintextStore and plaintext over an encrypted store fails with
ErrEncryptedStore. encryption_migrate_plaintext encrypts an existing
store in place once, storage.MigrateToPlaintext reverses it, and an
interrupted migration blocks start until it is rerun.

* fix(consensus): restart a service whose membership is already recorded

On restart the raft node rebuilds its membership from the log or snapshot,
which also adds a transport route for every member that has an address.
The service then added a route for each configured peer and failed
startup with "peer already exists". This happened for any cluster that
had taken a snapshot or changed membership, encrypted or not.

An existing route is no longer an error. The configured peers still seed
membership only for a brand new cluster: AddPeerAddress is ignored once a
configuration has been loaded, which the comments now say.

A new service test runs a plain cluster on boltdb and on badger. It grows
the cluster from three nodes to four, takes a snapshot, writes again and
restarts every node. Data, the four voters and new writes all survive. The
encrypted restart test passes again.

* fix(consensus): fail proposals dropped by a leadership change at once

Apply waited for its entry by index alone. When a leader lost its term
right after appending and the new leader overwrote that index, the waiter
was only released once some later entry was applied at the same index.
The caller usually hit its deadline first. And if this node led again and
proposed at the same index, the new waiter replaced the old one in the
map, which then hung for good.

Waiters are now keyed by index and term:
- When a follower truncates its log on a conflict, it fails every waiter
  for the removed entries with the new ErrProposalDropped. The entry was
  never applied, so the caller can retry.
- An entry discarded by an installed snapshot fails its waiter the same
  way.
- Applying an entry completes only the waiter with the same term and fails
  any other waiter at that index.

New tests force the truncation and check that Propose returns
ErrProposalDropped promptly, and that a displaced waiter is neither
completed by nor overwritten by a later entry at its index.

replicateAndRead in the service tests now retries on ErrProposalDropped or
not-leader errors, as a client would, and the comment on the encryption
tests' retrying helper describes the new behaviour.

* fix(consensus): honour BoltDB timeout, sync and read-only options

BoltDBStorage.Start opened the database with a fixed one second lock
timeout and dropped the rest of BoltDBStorageConfig. NoSync, NoGrowSync,
ReadOnly and MmapFlags were silently ignored, and so was the service's
storage.bolt_options.

Start now passes all of them to bbolt. Timeout still defaults to one
second and NoSync to false. The NoSync doc comment warns that it can lose
acknowledged writes. A read-only database must already have its bucket
and is not modified on open. Tests cover:
- the sync flags reaching the database, with safe defaults
- the lock timeout being honoured
- read-only access refusing writes

* test(consensus): retry leader operations in the service membership tests

The restart and membership service tests picked a leader once and then
called AddNode, TransferLeadership, RemoveNode or Apply on it. A leader
elected a moment earlier can lose its term in between, and one run in ten
failed with "node is not the leader". The tests now go through a small
onLeader helper. It retries on not-leader, ErrProposalDropped and
ErrConfigChangeInProgress, the errors a client would retry on, against
whichever node leads next. The final cluster info check accepts whichever
node leads at the end.

* docs(consensus): describe the wired extension, membership, grpc and encryption

The consensus pages still described the extension as unwired: Start that
built nothing, Apply always not-leader, Read and Snapshot panicking, and
the admin API, membership changes and leadership transfer missing. They
now match the code on this branch.

- QUICKSTART.md: the extension builds a real node. Followers apply entries
  and Propose can return ErrProposalDropped. The networked transports and
  disk storage are tested. Covers join, AddNode, TLS, encryption and the
  admin routes.
- index.mdx: new overview, status table and table of extension calls. The
  container section explains that the Raft node, state machine and cluster
  manager must be taken from the service.
- configuration.mdx:
  - transport.type defaults to tcp and accepts tcp, http and grpc.
  - New join key, bind_addr default 127.0.0.1, admin_api off by default,
    memory storage, bolt_options and the encryption keys.
  - Every key that is accepted but has no effect is marked.
- features.mdx: new sections on membership changes, leadership transfer,
  encryption at rest and the gRPC transport. Storage, snapshots,
  middleware, the admin API (with API key auth) and errors are updated,
  including the raft, storage and transport sentinels.
- functions.mdx: the extension and service methods as they behave now,
  ReencryptStorage, the storage encryption functions, the admin options
  and the new message types.
- README.md and llm.txt:
  - There is no pre-vote round, and raft.pre_vote has no effect.
  - The FAQ answers about leader-only jobs and storage backends are
    updated.
  - Examples use a reachable bind address.
  - The container advice is corrected.

Still stated as not implemented: linearizable reads, a pre-vote round and
discovery other than static in the extension.
@juicycleff
juicycleff force-pushed the fix/consensus-discovery-farp branch from 7931303 to 1180c1b Compare November 18, 2026 01:52
@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: all 17 follow conventional format

@github-actions github-actions Bot added fix and removed fix labels Nov 18, 2026
@juicycleff
juicycleff merged commit 2a6c517 into main Nov 18, 2026
34 checks passed

This branch was successfully deployed

1 active deployment
Preview — 1180c1b6 Deployed Nov 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants