Skip to content

fix: guard shared instance maps with a RWMutex - #127

Open
FlavioPulli wants to merge 1 commit into
evolution-foundation:mainfrom
FlavioPulli:fix/instance-map-race
Open

fix: guard shared instance maps with a RWMutex#127
FlavioPulli wants to merge 1 commit into
evolution-foundation:mainfrom
FlavioPulli:fix/instance-map-race

Conversation

@FlavioPulli

Copy link
Copy Markdown

killChannel, clientPointer and myClientPointer are created in main.go and shared by reference across all service packages and every MyClient. ReconnectClient deletes from all three without a lock, StartClient writes to them, the Disconnected handler triggers ReconnectClient from a goroutine, and every HTTP handler reads them concurrently. Go fatals on concurrent map access — we hit this in production as fatal error: concurrent map writes / internal/runtime/maps.fatal during reconnection bursts (stack through whatsmeowService.StartClient/ReconnectClient), which kills the entire process and every connected instance with it.

This adds a single exported sync.RWMutex in the whatsmeow service package guarding the three maps everywhere they are touched. Lock scopes are kept minimal: values are copied out under RLock and the lock is released before any long call (Disconnect, Connect, StartInstance, channel sends), so no lock is ever held across network operations. As a side effect the killChannel check-and-delete paths became atomic, closing a latent double-close race.

go build ./... and go vet ./... clean.

Three maps are created once in cmd/evolution-go/main.go — killChannel
(map[string]chan bool), clientPointer (map[string]*whatsmeow.Client) and
myClientPointer (map[string]*MyClient) — and shared by reference across
every service package (whatsmeow, instance, sendMessage, chat, call,
community, group, label, message, newsletter, user) and every *MyClient
value. None of the reads, writes or deletes on them were synchronized.

In production this fatals the process: ReconnectClient (whatsmeow.go)
deletes from all three maps without a lock, StartClient writes to
clientPointer/myClientPointer while its select loop and other goroutines
(schedulePresenceUpdates, teardownQR, myEventHandler's LoggedOut/poll-vote
paths) read killChannel/clientPointer, and every HTTP handler in the
peripheral packages reads clientPointer via ensureClientConnected — all
concurrently, since events.Disconnected fires ReconnectClient in its own
goroutine while requests keep flowing in. Go's runtime treats concurrent
map writes, or a read racing a write, as fatal — unrecoverable, not a
panic — and that is exactly what showed up in production as
internal/runtime/maps.fatal during bursts of reconnects.

The fix adds one exported sync.RWMutex (ClientMapsMu, in the new
pkg/whatsmeow/service/client_maps.go) shared by every package that touches
these maps. Every indexed read takes RLock/RUnlock, every write (assign or
delete) takes Lock/Unlock, and every guarded scope is kept as short as
possible: the client/channel value is copied into a local variable while
holding the lock, the lock is released, and only then is the value used
for anything that can block or take a while (IsConnected/Disconnect,
channel sends inside select, StartInstance/ReconnectClient/StartClient,
network calls). This also closes a couple of adjacent bugs for free:
StartClient's kill-signal select and schedulePresenceUpdates now
re-resolve the channel from the map on each loop iteration instead of
evaluating a stale expression, and ClearInstanceCache/Delete's
check-then-delete on killChannel is now atomic, so two concurrent cleanups
can no longer double-close the same channel.

No lock is ever held across a call into another guarded function
(ReconnectClient -> StartInstance -> StartClient all close their lock
scopes before calling the next), so there is no new deadlock risk.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @FlavioPulli, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@Matheusagostinho

Copy link
Copy Markdown

We hit this in production — confirming the bug with a crash trace.

Running evoapicloud/evolution-go:0.7.2 (Docker, Postgres 16), 5 instances, ~4 of them paired. The process died twice with the Go runtime aborting on unsynchronized map access:

fatal error: concurrent map read and map write
fatal error: concurrent map writes

docker inspect confirms the correlation — RestartCount: 2, matching exactly the two fatal errors in the log. Since these are runtime fatal errors and not panics, recover() is not an option: every occurrence kills the process and takes all instances down with it.

The goroutine dump at the time of the crash shows the concurrency context:

pkg/instance/service.instances.Connect
pkg/whatsmeow/service.(*MyClient).handleQRCodes
pkg/events/webhook.(*webhookProducer).Produce
go.mau.fi/whatsmeow.(*Client).unlockedConnect

The trigger appears to be concurrent connects: in our case, several instances reconnecting while another was in an active QR pairing flow and webhooks were being dispatched.

Worth noting that the codebase already acknowledges the hazard — the comment on teardownQR in pkg/whatsmeow/service/whatsmeow.go states that clientPointer/myClientPointer/killChannel are "unsynchronized service-wide maps" and that touching them from another goroutine "risks a fatal error: concurrent map writes". That workaround protects a single call site, but the maps stay unguarded everywhere else — clientPointer alone is read in 5 places and written in 4, with no mutex anywhere in the file.

This PR addresses exactly that. Any chance of getting it reviewed?

Operational impact for anyone else hitting this: restarting the container does not bring instances back — they stay down until an explicit POST /instance/connect per instance. So each crash means a full outage until someone reconnects them manually.

Happy to put together a minimal reproduction (parallel /instance/connect calls) if that would help move this along — let me know.

@FlavioPulli

Copy link
Copy Markdown
Author

@Matheusagostinho thank you — that is the most useful thing that has happened to this PR. Two independent deployments, two different scales, same goroutine dump.

Your RestartCount: 2 matching the two fatals is the detail I did not have. And you documented something I had not written down anywhere: restarting the container does not bring the instances back — they stay down until an explicit POST /instance/connect per instance. So each crash is a full outage until someone reconnects them by hand, which is a good deal worse than "the process restarts".

On our side the trigger is the same shape: a deploy recreates the container, the API boot fires the connects nearly together, and one instance ends up in a state where /instance/connect is a no-op and status stays Connected:false forever.

One thing that may help you while this waits: POST /instance/forcereconnect/{instanceId} recovers a single instance without restarting the container, so you do not take the healthy ones down with the broken one. It needs the global API key (the per-instance token gives 401), a {"number":"..."} body (without it, 400), and the {instanceId} is the UUID from instances.id, not the token. That is a workaround for the symptom, not a fix for the race — this PR is the fix.

Housekeeping: on #128 @iagocotta asked that PRs target develop rather than main. I had moved my others across but missed this one, which is now #167 — same change, ported and re-audited against develop (four hunks here touch code that does not exist on that branch, and I checked all 61 map accesses there rather than assuming the site lists matched). Whichever branch the maintainers prefer, the fix is available on both.

Your offer of a minimal reproduction with parallel /instance/connect calls still stands? That would make this much harder to leave sitting — a failing test beats two field reports.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants