Repository navigation
dispatcher: fix goroutines leak on swap - #5241
Conversation
If an alertgroup is marked as destroyed, and we receive a new alert that would go inside it, we now swap it with a new one. When we do that we can't rely on the maintenance job to stop the old group anymore, since it won't be present anymore in the map. So upon a successful "swap" we need to cancel the previous alert group that was in the map, to avoid its goroutine continuing. In addition we also self-cancel inside the alertgroup itself, if we find it is destroyed, so that the goroutine stops running when the first of "doMaintenance", run on destroyed, or swapped out, happens. In addition we fix a more unlikely deletion from the marker in doMaintenance. Signed-off-by: Guido Trotter <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Enterprise Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between afc153dc879c7dc31246b486c345324e9d1c0e26 and b4448e6. 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThis PR fixes a goroutine leak occurring during aggregation-group replacement. When a new group replaces an old one via compare-and-swap, the displaced group is now canceled and its run loop exits early if destroyed. Marker cleanup is deferred until map removal succeeds. Tests validate the fixes. ChangesGroup replacement and cleanup lifecycle
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@dispatch/dispatch.go`:
- Around line 329-334: The marker deletion can race with a replacement group
flushed by groupAlert() (e.g. via ag.resetTimer(0)), so change the unconditional
d.marker.DeleteByGroupKey(ag.routeID, ag.GroupKey()) to a conditional delete
that only removes the marker if it belongs to this specific aggrGroup instance:
add or use a marker method that accepts the routeID, GroupKey and an identifier
for the aggrGroup (e.g. pointer/address or a group instance ID) and only deletes
when the stored marker entry matches that identifier, or atomically
read-compare-delete the marker entry before deleting; locate the deletion call
around d.marker.DeleteByGroupKey and update callers (and marker interface)
accordingly so replacement groups aren’t clobbered.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: aca4023c-d9ed-436b-b33f-3ee1773f5855
📒 Files selected for processing (2)
dispatch/dispatch.godispatch/dispatch_test.go
There was a problem hiding this comment.
🧹 Nitpick comments (5)
notify/mute.go (1)
235-252: 💤 Low valueOwner check placement is inconsistent with
TimeMuteStage.In
TimeMuteStage(line 169) theAggrGroupIDcheck happens beforemuter.Mutesis called; here it's done after. This is a small inconsistency that means ifmuter.Mutesreturns an error, missing-owner is never surfaced. Consider relocating this block to mirrorTimeMuteStage(right after theNowextraction at line 232) so both stages have identical validation order.♻️ Proposed reorder
now, ok := Now(ctx) if !ok { return ctx, alerts, errors.New("missing now timestamp") } + owner, ok := AggrGroupID(ctx) + if !ok { + return ctx, nil, errors.New("aggregation group ID missing") + } + active, _, err := tas.muter.Mutes(activeTimeIntervalNames, now) if err != nil { return ctx, alerts, err } - owner, ok := AggrGroupID(ctx) - if !ok { - return ctx, nil, errors.New("aggregation group ID missing") - } - var mutedBy []string🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@notify/mute.go` around lines 235 - 252, The owner existence check (AggrGroupID(ctx)) should be performed before calling tas.muter.Mutes to match TimeMuteStage's validation order; move the owner/ok block so it runs immediately after obtaining now (the Now extraction) and before the call to tas.muter.Mutes(activeTimeIntervalNames, now), then use the validated owner variable when calling tas.marker.SetMuted(routeID, gkey, owner, mutedBy).types/types.go (1)
110-114: 💤 Low valueDoc comment slightly out of sync with new behavior.
The comment still says "the muted marker is removed" when the list is nil/empty, but the new
SetMutedalways retains the map entry (it just storesnil/emptymutedBy) and onlyDeleteIfOwnedByremoves the entry. Also, the trailing;reads as truncated. Consider clarifying that the entry is just marked as unmuted and that cleanup happens viaDeleteIfOwnedBy.📝 Proposed doc tweak
// SetMuted marks the group as muted, and sets the names of the time // intervals that mute it. If the list of names is nil or the empty slice - // then the muted marker is removed. The owner identifies the aggrGroup - // instance writing the marker; + // then the group is no longer reported as muted, but the entry remains + // in the map until DeleteIfOwnedBy is called. The owner identifies the + // aggrGroup instance writing the marker and is consulted by + // DeleteIfOwnedBy on cleanup. SetMuted(routeID, groupKey string, owner uuid.UUID, timeIntervalNames []string)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@types/types.go` around lines 110 - 114, Update the SetMuted doc comment to reflect current behavior: explain that SetMuted(routeID, groupKey string, owner uuid.UUID, timeIntervalNames []string) will always keep the aggrGroup map entry and stores a nil/empty mutedBy slice to mark the entry as unmuted, rather than removing the map entry; clarify that actual cleanup/removal of the entry is performed by DeleteIfOwnedBy, and remove the trailing semicolon/fragment to make the sentence complete.dispatch/dispatch_test.go (1)
828-886: ⚡ Quick winGood regression coverage. Minor: consider also asserting that the displaced group's marker entry is cleaned up.
The test correctly verifies the displaced
rungoroutine exits after CAS replacement. To make the regression coverage tighter against the original memory-leak symptom, you could also write a marker entry owned bydisplacedbefore starting itsrun, and assert that the entry is gone after the displaced goroutine exits (i.e. the deferredDeleteIfOwnedByfired with the right owner). This guards both the goroutine and the marker-state cleanup paths in one test.📝 Optional addition
+ // Owner-aware marker cleanup must also fire on exit. + marker.SetMuted(route.ID(), displaced.GroupKey(), displaced.id, []string{"weekends"}) + _, isMuted := marker.Muted(route.ID(), displaced.GroupKey()) + require.True(t, isMuted) + // Start the run goroutine on the displaced group — this is the orphan // candidate. Without the fix it would never exit. go displaced.run(func(context.Context, ...*types.Alert) bool { return true }) @@ // And its run goroutine must have exited. select { case <-displaced.done: case <-time.After(2 * time.Second): t.Fatal("displaced aggrGroup.run goroutine did not exit after CAS replacement") } + + // The deferred DeleteIfOwnedBy(owner=displaced.id) must have run and + // removed the marker entry that displaced wrote. + _, isMuted = marker.Muted(route.ID(), displaced.GroupKey()) + require.False(t, isMuted, "displaced group's marker entry must be cleaned up after run exits")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@dispatch/dispatch_test.go` around lines 828 - 886, Add an assertion to TestGroupAlert_DisplacedAggrGroupGoroutineExits that verifies the marker entry owned by the displaced aggrGroup is removed after CAS replacement: before starting go displaced.run(...), create a marker entry for displaced (using the test's marker and the displaced group's fingerprint/owner), then after waiting for <-displaced.done assert the marker.DeleteIfOwnedBy (or equivalent Remove/DeleteIfOwnedBy API) no longer finds that entry (i.e. it was cleaned up by the displaced group's deferred cleanup); reference the test function TestGroupAlert_DisplacedAggrGroupGoroutineExits, the displaced variable, marker, and the DeleteIfOwnedBy cleanup API in your changes.notify/event.go (1)
42-50: ⚡ Quick winDefensive improvement: handle missing
AggrGroupIDexplicitly.
AggrGroupID(ctx)returnsuuid.UUIDwith a boolean indicating presence. Line 42 discards the ok flag, so ifAggrGroupIDwere missing (zero value),aggrGroupID.String()would emit"00000000-0000-0000-0000-000000000000"instead of an empty string.While
AggrGroupIDis always set during dispatch initialization (dispatch/dispatch.go:695), event.go'sextractAlertGroupInfois a generic context accessor. For defensive robustness, consider explicitly handling the case whereAggrGroupIDis absent:📝 Proposed fix
- aggrGroupID, _ := AggrGroupID(ctx) + aggrGroupID, hasAggrGroupID := AggrGroupID(ctx) return &eventrecorderpb.AlertGroupInfo{ GroupKey: groupKey.String(), GroupLabels: eventrecorder.LabelSetAsProto(groupLabels), GroupId: groupKey.Hash(), ReceiverName: receiverName, Matchers: eventrecorder.MatchersAsProto(groupMatchers), - GroupUuid: aggrGroupID.String(), + GroupUuid: func() string { + if !hasAggrGroupID { + return "" + } + return aggrGroupID.String() + }(), }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@notify/event.go` around lines 42 - 50, AggrGroupID(ctx) currently discards its presence flag so GroupUuid may become the zero-UUID string; call it as aggrGroupID, ok := AggrGroupID(ctx) (or similar) in extractAlertGroupInfo, then set GroupUuid to aggrGroupID.String() only when ok is true, otherwise set GroupUuid to the empty string; reference the AggrGroupID function and the GroupUuid field in eventrecorderpb.AlertGroupInfo when making the change.dispatch/dispatch.go (1)
522-558: 💤 Low valueOrphaned context on LoadOrStore-then-insert path warrants consideration.
The swap path at lines 532–538 correctly cancels the displaced group's context. However, the concern at lines 550–558 is valid: when
agExisting.insert(ctx, alert)succeeds at line 555 and we return at line 556, the freshly-createdagfrom line 522 is never started and never canceled.Since
newAggrGroupcallscontext.WithCancel(d.ctx)at line 694, the orphanedag.cancelremains registered as a child context ond.ctxuntil the dispatcher itself is torn down. Under sustained high contention, this accumulates unnecessary context state.The suggested fix—deferring
ag.cancel()at the top ofgroupAlertafter creatingag, then conditionally unsetting it before the successful completion paths—would prevent this small leak. This is a minor, optional cleanup that improves resource hygiene without changing behavior.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@dispatch/dispatch.go` around lines 522 - 558, The new aggrGroup created by newAggrGroup(...) (ag) can be orphaned if agExisting.insert(ctx, alert) returns true, so after creating ag at the start of groupAlert defer ag.cancel() to ensure its cancel func is invoked if we never start it; then, before any successful path that will start and own ag (the CompareAndSwap branch where swapped==true and the LoadOrStore branch where we stored the new group and break to run it), cancel the deferred cancellation (e.g., set a flag or clear the defer) so ag.cancel() is not called prematurely; also ensure the early return path after agExisting.insert(...) unsets the defer so the newly created ag is properly canceled by the defer instead of leaking its context.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@dispatch/dispatch_test.go`:
- Around line 828-886: Add an assertion to
TestGroupAlert_DisplacedAggrGroupGoroutineExits that verifies the marker entry
owned by the displaced aggrGroup is removed after CAS replacement: before
starting go displaced.run(...), create a marker entry for displaced (using the
test's marker and the displaced group's fingerprint/owner), then after waiting
for <-displaced.done assert the marker.DeleteIfOwnedBy (or equivalent
Remove/DeleteIfOwnedBy API) no longer finds that entry (i.e. it was cleaned up
by the displaced group's deferred cleanup); reference the test function
TestGroupAlert_DisplacedAggrGroupGoroutineExits, the displaced variable, marker,
and the DeleteIfOwnedBy cleanup API in your changes.
In `@dispatch/dispatch.go`:
- Around line 522-558: The new aggrGroup created by newAggrGroup(...) (ag) can
be orphaned if agExisting.insert(ctx, alert) returns true, so after creating ag
at the start of groupAlert defer ag.cancel() to ensure its cancel func is
invoked if we never start it; then, before any successful path that will start
and own ag (the CompareAndSwap branch where swapped==true and the LoadOrStore
branch where we stored the new group and break to run it), cancel the deferred
cancellation (e.g., set a flag or clear the defer) so ag.cancel() is not called
prematurely; also ensure the early return path after agExisting.insert(...)
unsets the defer so the newly created ag is properly canceled by the defer
instead of leaking its context.
In `@notify/event.go`:
- Around line 42-50: AggrGroupID(ctx) currently discards its presence flag so
GroupUuid may become the zero-UUID string; call it as aggrGroupID, ok :=
AggrGroupID(ctx) (or similar) in extractAlertGroupInfo, then set GroupUuid to
aggrGroupID.String() only when ok is true, otherwise set GroupUuid to the empty
string; reference the AggrGroupID function and the GroupUuid field in
eventrecorderpb.AlertGroupInfo when making the change.
In `@notify/mute.go`:
- Around line 235-252: The owner existence check (AggrGroupID(ctx)) should be
performed before calling tas.muter.Mutes to match TimeMuteStage's validation
order; move the owner/ok block so it runs immediately after obtaining now (the
Now extraction) and before the call to tas.muter.Mutes(activeTimeIntervalNames,
now), then use the validated owner variable when calling
tas.marker.SetMuted(routeID, gkey, owner, mutedBy).
In `@types/types.go`:
- Around line 110-114: Update the SetMuted doc comment to reflect current
behavior: explain that SetMuted(routeID, groupKey string, owner uuid.UUID,
timeIntervalNames []string) will always keep the aggrGroup map entry and stores
a nil/empty mutedBy slice to mark the entry as unmuted, rather than removing the
map entry; clarify that actual cleanup/removal of the entry is performed by
DeleteIfOwnedBy, and remove the trailing semicolon/fragment to make the sentence
complete.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: b91800cf-ffbf-4e72-ad22-0c252565f2db
📥 Commits
Reviewing files that changed from the base of the PR and between 180be2e and afc153dc879c7dc31246b486c345324e9d1c0e26.
📒 Files selected for processing (8)
dispatch/dispatch.godispatch/dispatch_test.gonotify/event.gonotify/mute.gonotify/mute_test.gonotify/notify.gotypes/types.gotypes/types_test.go
afc153d to
180be2e
Compare
Signed-off-by: Guido Trotter <[email protected]>
* Fix dispatcher goroutines leak on swap If an alertgroup is marked as destroyed, and we receive a new alert that would go inside it, we now swap it with a new one. When we do that we can't rely on the maintenance job to stop the old group anymore, since it won't be present anymore in the map. So upon a successful "swap" we need to cancel the previous alert group that was in the map, to avoid its goroutine continuing. In addition we also self-cancel inside the alertgroup itself, if we find it is destroyed, so that the goroutine stops running when the first of "doMaintenance", run on destroyed, or swapped out, happens. In addition we fix a more unlikely deletion from the marker in doMaintenance. Signed-off-by: Guido Trotter <[email protected]> * Add a TODO about the DeleteByGroupKey call Signed-off-by: Guido Trotter <[email protected]> --------- Signed-off-by: Guido Trotter <[email protected]> Co-authored-by: Guido Trotter <[email protected]>
## Summary - Bump Alertmanager v0.32.0 -> **v0.34.1** (Dockerfile, versions.env, docker-compose, proxy test fallback). v0.32.0 leaks dispatcher goroutines on group swap (fixed in v0.32.2, prometheus/alertmanager#5241): prod hit ~706k goroutines / 7.4 GB RSS. - Route `group_by: [alertname, severity]` (was `[alertname, source, target, protocol]` = one aggregation group, and one Discord request, per alert; ~1,674 groups / ~470 req/min vs Discord ~150/min; Discord notifier does not retry 429). - Intervals: default 1m/15m/12h; critical 30s/5m/4h; info 1m/30m/24h. - New `deploy/alertmanager/templates/discord.tmpl` (baked into image at `/etc/alertmanager/templates/discord.tmpl`) defining `discord.meshmon.title` / `discord.meshmon.message`; all three receivers reference them. ## Breaking changes v0.32.0 -> v0.34.1 (release notes reviewed) - v0.33.0: `--enable-feature=auto-gomaxprocs` removed (no-op since v0.29; we do not use it). `alertmanager_marked_alerts` metric removed. Go `types` package marker types moved (library-only). New `group-key-in-metrics` feature flag. - v0.34.0: `alertmanager_notifications_failed_total{reason}` now distinguishes `authError` (401/403) and `rateLimited` (429) from `clientError`; Discord now reports `reason`. Update any dashboards/alerts matching `reason="clientError"`. - v0.33.1 / v0.34.1: bugfixes only (silence snapshot compat; inhibition un-mute fixes). v0.32.1: dispatcher contended-route fix. - No config-schema breaking changes found. ## Validation (prom/alertmanager:v0.34.1) `amtool check-config`: SUCCESS (3 receivers, 1 inhibit rule, 1 template). `amtool template render` with 2 firing + 1 resolved: ``` [FIRING:2] PathPacketLossCritical (critical) Packet loss **Firing (2)** • fra-1 → sgp-2 (icmp) • fra-1 → nyc-1 (udp) **Resolved (1)** • ams-1 → hel-1 (icmp) ``` With 50 firing alerts the list is capped at 35 and ends with `… (35 of 50 shown)`. Image builds locally and contains `/etc/alertmanager/templates/discord.tmpl`. ## Expected Discord volume Groups collapse from one per path to one per (alertname, severity) (a handful), with a 15m repeat/update cadence instead of 5m: roughly 1,674 groups -> <10, i.e. ~470 req/min -> a few per minute at steady state. ## Deploy Image is built by CI on main push as `ghcr.io/w3champions/meshmon-alertmanager:main-<full 40-char sha>` (and `latest`). Downstream (docker-compose-files `meshmon/alertmanager/alertmanager.yml` override) must reference the same template names; recommended extra flag `--cluster.listen-address=` (no gossip) is handled there. --------- Co-authored-by: Marco de Abreu <[email protected]>

If an alertgroup is marked as destroyed, and we receive a new alert that would go inside it, we now swap it with a new one. When we do that we can't rely on the maintenance job to stop the old group anymore, since it won't be present anymore in the map.
So upon a successful "swap" we need to cancel the previous alert group that was in the map, to avoid its goroutine continuing. In addition we also self-cancel inside the alertgroup itself, if we find it is destroyed, so that the goroutine stops running when the first of "doMaintenance", run on destroyed, or swapped out, happens.
In addition we fix a more unlikely deletion from the marker in doMaintenance.
Pull Request Checklist
Please check all the applicable boxes.
Which user-facing changes does this PR introduce?
Summary by CodeRabbit