Skip to content

fix: a three-node cluster forms, elects one leader, and does it race-free (#275, #278) - #279

Merged
scttfrdmn merged 1 commit into
mainfrom
fix/single-node-leadership
Aug 3, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
fix/single-node-leadership

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

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.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 that as a peer would reintroduce #275.

B2, pre-existing, and what made it permanent. 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 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.

site map aliased write
`calculateClusterStats` `cm.nodes` `UpdateNodeInfo`
`sendSyncMessage` `gp.memberlist` `performGossip`, `handleSyncMessage`
`performGossip` `gp.memberlist` (pointer slice) `handleAliveMessage`
`broadcastMessage` `gp.memberlist` (pointer slice) same shape; safe only by an ID filter two lines away

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:

mutation caught by
seed guard → `if false {` `TestCheckVoteMajority_WaitsForSeedsBeforeSelfElecting`
`SetLeader(newLeader)` removed from heartbeat path `TestStepDown_ClearsClusterLeadership/a_heartbeat` (`GetLeader() = "incumbent", want "real-leader"`)
`SetLeader("")` removed from vote path `TestStepDown_ClearsClusterLeadership/a_vote_request`
`expectsPeers` → `len(SeedNodes) > 0` `TestExpectsPeers/only_ourselves_is_a_cluster_of_one`
`calculateClusterStats` → shallow copy `TestCalculateClusterStats_TalliesUnderTheLock` (3 race reports)
`performGossip` → pointer slice `TestGossipProtocol_PerformGossipResolvesAddressesUnderTheLock` (2 race reports)

Gates

  • `go build ./...` · `go vet ./...` · `gofmt -l .` — clean
  • `go test -count=1 -race -covermode=atomic ./...` — pass
  • `coverage-gate.sh` — 35 packages at or above floor
  • `golangci-lint --new-from-merge-base=origin/main` — 0 issues
  • `gosec` — 2 findings, both the pre-existing `G404`s at `consensus.go:930,933`
  • `go test -race -tags=distributed ./tests/` — green, zero races, for the first time

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.

…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 scttfrdmn added the type: bug Something isn't working as expected label Aug 3, 2026
@scttfrdmn scttfrdmn added priority: high Important issue that should be addressed soon area: distributed Distributed coordination and consensus labels Aug 3, 2026
@scttfrdmn
scttfrdmn enabled auto-merge (squash) August 3, 2026 18:18
@scttfrdmn
scttfrdmn merged commit f13ccfe into main Aug 3, 2026
27 checks passed
@scttfrdmn
scttfrdmn deleted the fix/single-node-leadership branch September 20, 2026 05:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: distributed Distributed coordination and consensus priority: high Important issue that should be addressed soon type: bug Something isn't working as expected

Projects

None yet

1 participant