Skip to content

Data race: sendSyncMessage marshals the memberlist outside gp.mu, and its map copy is shallow #278

Closed

Description

@scttfrdmn

The race

WARNING: DATA RACE
Write at 0x00c000198c10 by goroutine 10:
  (*GossipProtocol).performGossip()   internal/distributed/gossip.go:896
  (*GossipProtocol).gossipLoop()      internal/distributed/gossip.go:874

Previous read at 0x00c000198c10 by goroutine 51:
  time.(*Time).MarshalJSON()
  encoding/json.Marshal()
  (*GossipProtocol).sendSyncMessage()        internal/distributed/gossip.go:1140
  (*GossipProtocol).handleJoinMessage.func1() internal/distributed/gossip.go:504

The address is gp.localNode.LastSeen. performGossip stamps it under gp.mu
(gossip.go:895-896); sendSyncMessage marshals it without holding the lock.

Why the existing lock does not help

sendSyncMessage looks synchronized — it takes gp.mu.RLock() and copies the map:

gp.mu.RLock()
nodes := make(map[string]*GossipNode)
maps.Copy(nodes, gp.memberlist)   // shallow: *GossipNode pointers, shared
gp.mu.RUnlock()
...
data, _ := json.Marshal(syncMsg)  // outside the lock, walks into the shared structs

maps.Copy copies the *GossipNode values, so the copy aliases the originals — and this node's
entry aliases gp.localNode itself, because NewGossipProtocol stores the same pointer
(gossip.go:233-234):

gp.memberlist[gp.localNode.ID] = &GossipNode{Info: gp.localNode, ...}

So the marshal walks a struct that performGossip is concurrently writing. performGossip already
gets this right for its own message — gossip.go:923-924 marshals under the lock, with a comment
saying why. sendSyncMessage is the one that does not.

The read is not confined to localNode, either: handleSyncMessage (gossip.go:815-821) writes
localNode.Info, .Incarnation, .State, .StateChange, and .Suspicion on the shared
*GossipNode values under gp.mu, and the unlocked marshal reads all of them.

Impact

Beyond being UB: the payload can be marshalled from a half-updated struct, so a peer can be told a
node's new LastSeen with its old incarnation, or the reverse. handleSyncMessage gates merges on
remoteNode.Incarnation > localNode.Incarnation, so an inconsistent pair is not merely noisy — it
decides whether the update is applied at all.

Suggested fix

Either marshal under the lock, as performGossip does, or deep-copy what goes out. Marshalling
under RLock is the smaller change and matches the neighbouring code; the copy is preferable if the
memberlist grows enough that holding the lock across a marshal matters, in which case the copy has
to be genuinely deep — GossipNode.Info and .Suspicion are both pointers.

Worth auditing the other maps.Copy/range-and-send sites in this file for the same shallow-copy
assumption.

How it was found

-race on a three-node -tags=distributed run while fixing #275. Pre-existing and unrelated to
that fix — it reproduces on any cluster where a node joins while the gossip loop is running, which
is every cluster. It has been invisible because no CI job builds that tag (#240), and because a
one-node cluster has no joiner.

Activity

  1. added
    type: bug
    priority: high
    area: distributed
    effort: small
    on Aug 3, 2026
  2. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    OwnerAuthor

    Fixed in #279 — and it was four sites, not one. Recording that here because the pattern is what matters, not the individual call.

    sendSyncMessage was where -race first pointed, but after fixing it TestMultiNodeCluster still reported races at two more sites, and an audit of every maps.Copy and pointer-collecting loop in the package turned up a fourth:

    site map aliased against
    GossipProtocol.sendSyncMessage gp.memberlist performGossip, handleSyncMessage
    ClusterManager.calculateClusterStats cm.nodes UpdateNodeInfo
    GossipProtocol.performGossip gp.memberlist (pointer slice, read .Info.Address after unlock) handleAliveMessage
    GossipProtocol.broadcastMessage gp.memberlist (same shape) same shape — safe today only because an ID filter two lines away excludes the one NodeInfo anything mutates in place

    Two additions to the original report:

    calculateClusterStats is the one with a consequence beyond a stale read. It classifies a node by Status and, in the same loop iteration, sums CacheSize and CacheHitRate from it. So a node counted alive on a torn read contributes figures from a different moment into ClusterStats.TotalCacheSize — the number a size-aware balancing strategy routes on. The two halves of the tally can disagree about which snapshot they came from.

    broadcastMessage was not racing and was still changed. Its safety is a property of a filter two lines away rather than of the code doing the read, and that is exactly the reasoning that made the other three wrong. Left as-is it is the next instance waiting to happen.

    The fix in each case removes the aliasing rather than synchronizing around it: tally, marshal, or resolve the address inside the critical section and carry out only values. GetNodes and GetMemberlist had always done this correctly, twenty lines away in the same files — the pattern was known, just not applied.

    Two regression tests, both race tests rather than assertion tests: each drives a gossip round and an inbound alive message concurrently, and under -race fails on the defect and passes after it. Without -race they pass either way, which their doc comments say explicitly so a green run without the flag is not later mistaken for coverage. Verified by mutation — reverting each fix produces 3 and 2 race reports respectively.

    The invariant is now stated in internal/distributed/doc.go under Membership Maps and Locking, since it was got wrong four separate times: never carry a pointer out of a membership map across the unlock, because copying the map copies the pointers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: distributedeffort: smallpriority: hightype: bug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions