canopy icon indicating copy to clipboard operation
canopy copied to clipboard

bug: data race and leaked dialing counter in DialForOutboundPeers causes node to stop connecting new peers

Open Sertug17 opened this issue 3 months ago • 1 comments

Summary

DialForOutboundPeers() in p2p/p2p.go has two related bugs in the initial config peer dial loop:

  1. Data race the dialing variable is written from spawned goroutines and read from the main loop without any synchronization.
  2. Counter never decremented goroutines increment dialing but never decrement it after DialWithBackoff returns, so the counter stays permanently inflated.

Affected Code

File: p2p/p2p.go → DialForOutboundPeers()

for _, peerString := range p.config.DialPeers {
    peerAddress, err := getPeerFromString(peerString)
    if err != nil {
        continue
    }
    go func() {
        dialing++ // ← unsynchronized write from goroutine
        p.DialWithBackoff(peerAddress, true)
        // ← dialing is NEVER decremented after DialWithBackoff returns
    }()
}

// main loop reads dialing without synchronization:
if outbound > 0 && outbound+dialing >= p.config.MaxOutbound {
    return // ← falsely triggered once initial goroutines finish
}

Impact

  • After the initial DialPeers goroutines complete, dialing stays permanently at len(p.config.DialPeers).
  • The main dial loop evaluates outbound + dialing >= MaxOutbound as true and stops dialing new peers, even when the node is well under its outbound peer limit.
  • Running with the -race flag will surface the data race on dialing.

Steps to Reproduce

  1. Set one or more entries in DialPeers in node config
  2. Start node with go run -race ./cmd/...
  3. Observe data race warning on dialing in DialForOutboundPeers
  4. After initial dial goroutines finish, observe node stops making new outbound connections despite being under MaxOutbound

Suggested Fix

Use sync/atomic and add a deferred decrement:

var dialing atomic.Int64

for _, peerString := range p.config.DialPeers {
    peerAddress, err := getPeerFromString(peerString)
    if err != nil {
        continue
    }
    go func() {
        dialing.Add(1)
        defer dialing.Add(-1)
        p.DialWithBackoff(peerAddress, true)
    }()
}

// main loop:
if outbound > 0 && int64(outbound)+dialing.Load() >= int64(p.config.MaxOutbound) {
    return
}

Sertug17 avatar Aug 04 '26 18:08 Sertug17

Seen this exact pattern before. The leaked counter is actually the worse of the two bugs; the race is loud but the permanent counter inflation silently starves outbound dials. The question is whether the dial path needs a separate counter at all, or whether in-flight state can be derived from the connections themselves. Have you run -race over the rest of the dial path? The same unsynchronized increment pattern may exist in the retry logic. Happy to take a look at the relevant code if helpful.

exocognosis avatar Oct 04 '26 22:10 exocognosis