Repository navigation
fix: a three-node cluster forms, elects one leader, and does it race-free (#275, #278) - #279
Merged
Merged
Conversation
…free Closes #275, closes #278. Four defects, found by probing rather than reading, and each pinned by a test that fails on the defect before it passes on the fix. startElection's majority check fired against a membership view containing only this node. Gossip learns of a peer from an inbound message and the election timer does not wait for one, so all three nodes of a seeded cluster elected themselves at term 1 on a single vote each, within the first second, before any had heard of the others. A membership map cannot tell "cluster of one" from "cluster of three that has not discovered itself"; the discriminator has to come from config, so ClusterManager.expectsPeers reads SeedNodes minus this node's own address, exactly as joinCluster already treats it. A seed list naming only yourself is what a uniform config file deployed to every node produces, and counting it as a peer would reintroduce #275. handleNetworkAppendEntries and handleNetworkRequestVote set ce.state = StateFollower without telling the cluster manager. becomeLeader called SetLeader; no step-down path did, so ClusterManager.IsLeader was effectively write-once and a deposed leader kept claiming leadership for the life of the process. That is what turned a momentary election race into a permanent split brain instead of something the next heartbeat resolved. Both paths now call SetLeader — with the new leader's ID from a heartbeat, and with "" from a vote request, since the candidate has not won anything yet. Four data races on the membership maps, all one mistake made four times. maps.Copy on a map[string]*T copies the pointers, so lock / copy / unlock / read is not synchronization: it reads the structs the gossip receive goroutine is writing. calculateClusterStats did it with cm.nodes; sendSyncMessage did it with gp.memberlist, where this node's entry aliases gp.localNode itself; performGossip and broadcastMessage did the pointer-slice form and read .Info.Address after unlocking. Each is fixed by removing the aliasing rather than locking around it — tally, marshal, or resolve the address inside the critical section and carry out only values, as GetNodes and GetMemberlist already did twenty lines away. Not merely a stale read: calculateClusterStats classifies by Status and sums CacheSize in the same iteration, so a torn read mixes moments inside a figure a balancer routes on, and handleSyncMessage gates merges on an incarnation comparison. Two -tags=distributed tests were asserting against misconfigurations. TestMultiNodeCluster set no SeedNodes, so its three managers were three clusters of one; it now seeds all three from node 0, gives each a backend because strong consistency fans the write out, and raises MaxGossipPacket past the 1024-byte default that truncates the sync mid-JSON and then reports the truncation as an authentication failure (#277). TestLoadBalancer_NodeSelection asserted a strong-consistency PUT across four addresses nothing listens on; it now asserts what its name promises and says why one reachable node out of five can carry the selection claim or the execution claim per operation, but not both. The whole -tags=distributed suite is green under -race for the first time. No CI job builds that tag, which is why all of this sat unobserved (#240).
scttfrdmn
enabled auto-merge (squash)
August 3, 2026 18:18
This was referenced Aug 3, 2026
Closed
This was referenced Aug 3, 2026
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.
Closes #275. Closes #278.
Four defects, found by probing rather than reading. Each is pinned by a test that fails on the defect before it passes on the fix — verified by mutation, not by prediction.
The split brain was two defects
B1, introduced by the single-node fix.
startElection's majority check fired against a membership view containing only this node. Gossip learns of a peer from an inbound message and the election timer does not wait for one, so a probe of three seeded nodes showed all three electing themselves at term 1 on one vote each, within the first second, before any had heard of the others.A membership map cannot distinguish "cluster of one" from "cluster of three that hasn't discovered itself." The discriminator has to come from configuration, so
ClusterManager.expectsPeersreadsSeedNodesminus this node's own address — exactly asjoinClusteralready treats it. A seed list naming only yourself is what a uniform config file deployed to every node produces, and counting that as a peer would reintroduce #275.B2, pre-existing, and what made it permanent.
handleNetworkAppendEntriesandhandleNetworkRequestVotesetce.state = StateFollowerwithout telling the cluster manager.becomeLeadercalledSetLeader; no step-down path did. SoClusterManager.IsLeaderwas effectively write-once, and a deposed leader kept reporting itself as leader for the life of the process — which is how a momentary election race became a durable split brain instead of something the next heartbeat resolved.Probe output before the fix:
```
after higher-term heartbeat: ce.state=follower cm.IsLeader=true cm.GetLeader="sd"
```
After both fixes, three seeded nodes with real advertise addresses:
```
t= 1s leaders=0 [p-0 candidate t=1 v=1 cmL=false sees="" m=3] [p-1 candidate ...] [p-2 ...]
t= 4s leaders=1 [p-0 follower t=7 cmL=false sees="p-2"] [p-1 follower sees="p-2"] [p-2 leader cmL=true sees="p-2" m=3]
...stable through t=10s
```
Four data races, all one mistake made four times (#278)
`maps.Copy` on a `map[string]*T` copies the pointers. So lock / copy / unlock / read-through-the-copy is not synchronization — it reads the very structs the gossip receive goroutine is writing.
In `sendSyncMessage` the aliasing is worse than it looks: this node's memberlist entry is `gp.localNode`, the same pointer stored at `gossip.go:233-234`.
Each is fixed by removing the aliasing rather than locking around it — tally, marshal, or resolve the address inside the critical section and carry out only values. `GetNodes` and `GetMemberlist` had always done it correctly, twenty lines away in the same files.
Not merely a stale read. `calculateClusterStats` classifies a node by `Status` and sums `CacheSize`/`CacheHitRate` from it in the same iteration, so a node counted alive on a torn read contributes figures from a different moment into the number a size-aware balancer routes on. And `handleSyncMessage` gates merges on `remoteNode.Incarnation > localNode.Incarnation`, so an inconsistently-marshaled memberlist affects whether membership converges at all.
The two new regression tests are race tests, not assertion tests: they drive a gossip round and an inbound alive message concurrently, and under `-race` fail on the defect and pass after it. Without `-race` both pass either way — stated in their doc comments so nobody later reads a green run without the flag as coverage.
Two tests were asserting against misconfigurations
`TestMultiNodeCluster` set no `SeedNodes`, and gossip has no other discovery mechanism, so its three managers were three clusters of one that had never heard of each other — which is what "Node i sees 1 nodes in cluster" three times was saying. It now seeds all three from node 0, gives each a backend (strong consistency fans the write out, so a node without one fails the operation for the whole cluster), and raises `MaxGossipPacket` past the 1024-byte default that truncates a three-member sync mid-JSON and then reports the truncation as `gossip message failed authentication` — filed separately as #277.
`TestLoadBalancer_NodeSelection` registered four peers at addresses nothing listens on and asserted a strong-consistency PUT across two of them succeeded; it timed out for 30 seconds and reported that as a defect. It now asserts what its name promises — selection chooses from the whole membership, the operation executes, the bytes reach storage — and says in a comment why one reachable node out of five can carry the selection claim or the execution claim per operation, not both. `StrategyLeastLoad` routing the second operation away from the node that served the first is the balancer working, so the second is pinned with `TargetNodes`.
Mutation verification
Every fix was verified by breaking it and watching the specific test fail:
Gates
No CI job builds `-tags=distributed`, which is why all of this sat unobserved (#240).
Package doc
A new Membership Maps and Locking section in `internal/distributed/doc.go` states the invariant the four sites violated: never carry a pointer out of a membership map across the unlock, because copying the map copies the pointers. Worth stating in the package doc precisely because it was got wrong four separate times.