Repository navigation
feat(consensus): add a grpc transport, membership changes, leadership transfer and encryption at rest - #131
Merged
juicycleff merged 12 commits intoNov 18, 2026
Conversation
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.
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.
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
…e 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.
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.
# Conflicts: # extensions/consensus/README.md # extensions/consensus/llm.txt
…features # Conflicts: # extensions/consensus/README.md # extensions/consensus/llm.txt
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.
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.
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
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.
…ncryption
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.
Contributor
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
juicycleff
added a commit
that referenced
this pull request
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.
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #130. This adds the three consensus features #130 left as "not implemented", fixes the bugs that turned up when they were combined, and rewrites the consensus docs to match the code. Merge #130 first; this PR's base will then move to
main.gRPC transport
transport.type: grpcnow runs a real transport. It is one unary gRPC call with a custom codec that carries the same versioned envelope as TCP and HTTP, so there is no protoc step and the version, size and payload checks are shared.TLSManager, andRequirePeerIdentitychecksFromagainst the peer certificate.Stopreturns promptly.Membership changes and leadership transfer
AddNodeadds the server as a learner, then promotes it once it has caught up.RemoveNodeworks on any server, the leader included.join: trueand waits to be added.TransferLeadershipbrings the target up to date, sends TimeoutNow, and gives up after an election timeout. Writes are refused while it runs.GetClusterManagerand the admin routes all use the real implementation.Encryption at rest
security.enable_encryptionseals every value the node stores (log, term, vote, snapshots and their metadata) with AES-256-GCM.Service.ReencryptStoragere-encrypts while the node serves.Bugs fixed while combining
Applyhung until its deadline when a leadership change truncated its entry. It now fails at once withraft.ErrProposalDropped, and waiters are matched by index and term.timeout,no_sync,no_grow_syncand read-only mode were ignored. They now reach BoltDB.Docs
The README,
llm.txt,QUICKSTART.mdand the consensus pages underdocs/are rewritten against the code. Checking every claim also corrected some old ones:pre_voteis read from config and never used);Service(), because resolving them from the container after start fails.Behaviour changes
transport.type: grpcis accepted.ErrGRPCNotImplementedandErrMembershipChangeUnsupported, both added in fix(consensus): make raft safe and wire the service, verify farp schemas #130, are removed.bind_addris also the address other nodes record, so it can't be0.0.0.0.ConfigChangeMsgtypes are removed.ErrConfigChangeInProgressErrLeadershipTransferInProgressErrLeadershipTransferFailedErrLearnerNotCaughtUpErrProposalDroppedStill not implemented
Linearizable reads, a pre-vote round, and discovery other than the static peer list in the extension.
Testing
go test -race ./...passes inextensions/consensus.extensions/hls, which builds consensus through a replace directive, still builds.