Repository navigation
fix(eventing): prevent send on closed channel in EmitToAll - #1993
Conversation
✅ Deploy Preview for polite-licorice-3db33c canceled.
|
|
Caution Review failedAn error occurred during the review process. Please try again later. 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 |
📝 WalkthroughWalkthroughSubscriber management now uses synchronized subscription wrappers for notification delivery, cancellation, cleanup, and notifier closure. Service wiring and tests use the new internal subscription representation. New tests cover concurrent cancellation, blocked subscribers, cleanup, and post-unsubscribe delivery. ChangesSubscriber cancellation synchronization
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant Subscriber
participant EventingConfiguration
participant subscription
Subscriber->>EventingConfiguration: Subscribe
EventingConfiguration->>subscription: Register wrapper
EventingConfiguration->>subscription: Deliver notification
Subscriber->>EventingConfiguration: Unsubscribe
EventingConfiguration->>subscription: Stop and close notifier
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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
🧹 Nitpick comments (2)
flagd/pkg/service/flag-evaluation/eventing_test.go (2)
167-171: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSilence the "empty block" static-analysis hint.
SonarCloud flags the empty
for range notifier {}body. It's intentional (drain until close), and already explained by the comment above, but adding an inline comment or//nolintinside the block would satisfy the linter without behavior change.🧹 Optional tweak
go func() { defer drainers.Done() - for range notifier { - } + for range notifier { + // intentionally empty: just drain until the channel closes + } }()🤖 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 `@flagd/pkg/service/flag-evaluation/eventing_test.go` around lines 167 - 171, Silence the empty-block static-analysis warning in the goroutine draining notifier by adding an inline explanatory comment or targeted nolint directive inside the for range notifier loop, without changing its drain-until-close behavior.Source: Linters/SAST tools
139-205: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueGood regression coverage for the panic fix.
The test correctly drains every notifier concurrently while hammering
EmitToAllduring context cancellation, which reliably exercises the original "send on closed channel" race. Note this design always drains notifiers, so it does not exercise the lock-contention/stalled-cleanup scenario raised oneventing.go(lines 68-75) where a stuck consumer could block other subscribers' cleanup — consider a follow-up test with an intentionally-unread notifier if that concern is confirmed.🤖 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 `@flagd/pkg/service/flag-evaluation/eventing_test.go` around lines 139 - 205, Keep the existing regression test, and if the eventing cleanup concern is confirmed, add a follow-up test covering a stalled consumer: subscribe with an intentionally unread notifier, concurrently cancel it and another subscriber, and verify cleanup of the other subscription proceeds without blocking. Use the existing TestEmitToAllVsSubscriberCancel structure and eventing subscription/cleanup APIs.
🤖 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 `@flagd/pkg/service/flag-evaluation/eventing.go`:
- Around line 68-75: Update EmitToAll to avoid holding the read lock while
performing unbounded blocking sends: use non-blocking sends or a bounded wait
for each subscriber, then release the lock promptly so the cleanup path can
acquire eventing.mu.Lock(), remove the subscription, and close its notifier
without depending on clients draining channels.
---
Nitpick comments:
In `@flagd/pkg/service/flag-evaluation/eventing_test.go`:
- Around line 167-171: Silence the empty-block static-analysis warning in the
goroutine draining notifier by adding an inline explanatory comment or targeted
nolint directive inside the for range notifier loop, without changing its
drain-until-close behavior.
- Around line 139-205: Keep the existing regression test, and if the eventing
cleanup concern is confirmed, add a follow-up test covering a stalled consumer:
subscribe with an intentionally unread notifier, concurrently cancel it and
another subscriber, and verify cleanup of the other subscription proceeds
without blocking. Use the existing TestEmitToAllVsSubscriberCancel structure and
eventing subscription/cleanup APIs.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3778f1f8-90eb-434f-96e9-93ef6a2cf99a
📒 Files selected for processing (2)
flagd/pkg/service/flag-evaluation/eventing.goflagd/pkg/service/flag-evaluation/eventing_test.go
|
Thanks for the review. On the EmitToAll suggestion (non-blocking/bounded sends so a stalled consumer can't block cleanup): the blocking send under RLock is pre-existing behavior that this PR intentionally leaves untouched. Switching to non-blocking sends changes the delivery semantics of EmitToAll (it would start dropping notifications for slow consumers), which is a broader behavioral decision that's out of scope for this crash fix. This PR is deliberately surgical: it only makes the subscription teardown (delete from subs + close of the notifier) atomic under the write lock so EmitToAll, holding the read lock, can never observe a notifier in the map after it has been closed, which is the exact 'send on closed channel' panic being fixed. Happy to open a separate issue/PR for the stalled-consumer hardening if maintainers want to pursue it. On the empty for range notifier {} drain loop in the test: it is intentional (drain until close) and already has an explanatory comment above it; I can add an inline comment or //nolint inside the block if preferred. |
3f8f6c8 to
fa35245
Compare
|
Pushed a revision addressing the latest review/CI feedback. |
fa35245 to
35dac19
Compare
Baltsat
left a comment
There was a problem hiding this comment.
Blocking: EmitToAll releases the map lock before delivery, so an in-flight snapshot can invoke sub.send after Unsubscribe has deleted the entry and closed done. At that point both send cases can be ready and Go may choose the notifier.
I reproduced this on the exact PR head with Go 1.25.5 and -race: lock the subscription, start EmitToAll, call Unsubscribe, unlock, and assert the notifier remains empty. The test fails immediately with a notification delivered after Unsubscribe returned. The ordinary package race suite passes, so this needs a focused lifecycle regression.
Before this change, Unsubscribe could not return until the read-lock-protected send completed. Please preserve that post-unsubscribe delivery invariant and add the regression test.
35dac19 to
d9f0b9f
Compare
Thanks @Baltsat, dug into this properly. Two separate things in your review:
That said it's cheap to harden and I'd rather not rely on every future caller using a buffered/never-closed channel, so I went ahead and pushed my fix: send now checks done first before trying the notifier, plus a regression test ( |
toddbaert
left a comment
There was a problem hiding this comment.
Will merge this week unless I hear objections.
d2c2687 to
8cbb447
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
flagd/pkg/service/flag-evaluation/eventing_test.go (1)
202-212: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd an ID-reuse cleanup regression.
The PR changes watcher cleanup to preserve a newer subscription that uses the same ID. Add a test that subscribes twice with one ID, cancels the first context, and verifies that the registry still contains the second subscription and its notifier remains open.
🤖 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 `@flagd/pkg/service/flag-evaluation/eventing_test.go` around lines 202 - 212, Extend the eventing subscription tests around Subscribe to cover ID reuse: create two subscriptions with the same ID using separate contexts and notifiers, cancel the first context, then verify eventing.subs still contains the second subscription and its notifier remains open. Use the existing cleanup-wait pattern and synchronization symbols to ensure the assertion observes completed cleanup.
🤖 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 `@flagd/pkg/service/flag-evaluation/eventing.go`:
- Around line 77-80: Update eventingConfiguration.Subscribe to start a lifecycle
goroutine for the new subscription that calls sub.stop() when ctx.Done() is
signaled, and also exits when sub.done is closed. Ensure this cancellation
handling is established before the subscription can block in sub.send.
- Around line 145-146: Update the subscription shutdown flow around sub.stop()
by adding a stopAndWait method that invokes stop(), then locks and unlocks
sub.mu to wait for any in-flight send to finish. Call sub.stopAndWait() in the
Unsubscribe path so it cannot return until concurrent sends have completed.
---
Nitpick comments:
In `@flagd/pkg/service/flag-evaluation/eventing_test.go`:
- Around line 202-212: Extend the eventing subscription tests around Subscribe
to cover ID reuse: create two subscriptions with the same ID using separate
contexts and notifiers, cancel the first context, then verify eventing.subs
still contains the second subscription and its notifier remains open. Use the
existing cleanup-wait pattern and synchronization symbols to ensure the
assertion observes completed cleanup.
🪄 Autofix
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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c169e373-0c57-446a-84a1-b551b8c233be
📒 Files selected for processing (2)
flagd/pkg/service/flag-evaluation/eventing.goflagd/pkg/service/flag-evaluation/eventing_test.go
Serialize sends and channel closure per subscription so cleanup cannot race with EmitToAll. Snapshot subscriptions under the map lock before sending, and let unsubscribe interrupt a blocked send without dropping notifications for active subscribers. Cover cancellation racing with broadcasts and verify a stalled subscriber cannot block another subscriber's lifecycle cleanup. Signed-off-by: Anas Khan <[email protected]>
Signed-off-by: Todd Baert <[email protected]>
8cbb447 to
a114268
Compare
|
Fixes a bug found while working on #1993 - an extremely rare but real race (found running with `--race`) that can occur if a client disconnects right after connecting to the event stream. The easiest fix is to just send the initial ready event from the handler, not the internal subscription channel as before, because then we don't have to enhance the concurrency stuff there. Signed-off-by: Todd Baert <[email protected]>
🤖 I have created a release *beep* *boop* --- <details><summary>flagd: 0.16.2</summary> ## [0.16.2](flagd/v0.16.1...flagd/v0.16.2) (2026-08-14) ### 🐛 Bug Fixes * **eventing:** prevent send on closed channel in EmitToAll ([#1993](#1993)) ([8d7d41f](8d7d41f)) * possible race on eventstream connection ([#2025](#2025)) ([e38ecb7](e38ecb7)) * record OFREP evaluation metrics ([#2016](#2016)) ([8dd34dc](8dd34dc)) </details> <details><summary>flagd-proxy: 0.9.8</summary> ## [0.9.8](flagd-proxy/v0.9.7...flagd-proxy/v0.9.8) (2026-08-14) ### 🐛 Bug Fixes * **flagd-proxy:** set gRPC keepalive enforcement policy on the sync server ([#2022](#2022)) ([5591fa8](5591fa8)) ### 🧹 Chore * resolve open dependabot security alerts ([#2008](#2008)) ([bbb05d4](bbb05d4)) </details> <details><summary>core: 0.16.2</summary> ## [0.16.2](core/v0.16.1...core/v0.16.2) (2026-08-14) ### 🐛 Bug Fixes * **core:** register the OFO scheme at package init, not inside Sync.Init ([#2024](#2024)) ([cf2db36](cf2db36)) * **flagd-proxy:** set gRPC keepalive enforcement policy on the sync server ([#2022](#2022)) ([5591fa8](5591fa8)) * possible race on eventstream connection ([#2025](#2025)) ([e38ecb7](e38ecb7)) </details> --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). Signed-off-by: OpenFeature Bot <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>



this pr
fixes a lifecycle race in rpc eventing that can panic with
send on closed channelwhen subscriber cancellation overlapsEmitToAll.the fix
testing
adds regression coverage for cancellation racing with repeated broadcasts and for one stalled subscriber not blocking another subscriber's cleanup.
make testgo test -race ./flagd/pkg/service/flag-evaluation/...gofmton changed filesmake lint(changed files clean; existing staticcheck findings remain in untouched files)