Skip to content

fix(eventing): prevent send on closed channel in EmitToAll - #1993

Merged
toddbaert merged 2 commits into
open-feature:mainfrom
anxkhn:fix/eventing-emit-vs-close-race
Aug 14, 2026
Merged

toddbaert merged 2 commits into
open-feature:mainfrom
anxkhn:fix/eventing-emit-vs-close-race

Conversation

@anxkhn

@anxkhn anxkhn commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

this pr

fixes a lifecycle race in rpc eventing that can panic with send on closed channel when subscriber cancellation overlaps EmitToAll.

the fix

  • keep each notifier and its lifecycle state in a subscription object
  • serialize sends with notifier closure so a closed channel is never selected for a send
  • snapshot subscriptions under the map lock, then release it before potentially blocking sends
  • let unsubscribe interrupt a blocked send, preserving blocking delivery for active subscribers without allowing one stalled subscriber to block unrelated cleanup
  • avoid deleting a newer subscription if an id is reused

testing

adds regression coverage for cancellation racing with repeated broadcasts and for one stalled subscriber not blocking another subscriber's cleanup.

  • make test
  • go test -race ./flagd/pkg/service/flag-evaluation/...
  • gofmt on changed files
  • make lint (changed files clean; existing staticcheck findings remain in untouched files)

@anxkhn
anxkhn requested review from a team as code owners July 10, 2026 19:40
@netlify

netlify Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for polite-licorice-3db33c canceled.

Name Link
🔨 Latest commit a114268
🔍 Latest deploy log https://app.netlify.com/projects/polite-licorice-3db33c/deploys/6a7f21031127a300087166f0

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Jul 10, 2026
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown

Caution

Review failed

An 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Subscriber 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.

Changes

Subscriber cancellation synchronization

Layer / File(s) Summary
Subscription lifecycle and delivery coordination
flagd/pkg/service/flag-evaluation/eventing.go
Subscription wrappers coordinate guarded sends, stop signaling, broadcast delivery, and unsubscribe handling.
Watcher cleanup and service wiring
flagd/pkg/service/flag-evaluation/eventing.go, flagd/pkg/service/flag-evaluation/connect_service.go, flagd/pkg/service/flag-evaluation/connect_service_test.go
Watcher termination removes the matching subscription before closing its notifier. Service setup and watcher tests use the pointer-based subscription map.
Concurrency regression coverage
flagd/pkg/service/flag-evaluation/eventing_test.go
Tests cover concurrent cancellation and emission, blocked subscribers, cleanup, bookkeeping, and notification delivery after unsubscribe.

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
Loading

Suggested reviewers: aepfli

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the eventing race and the prevention of sends on closed channels, which matches the primary change.
Description check ✅ Passed The description directly explains the lifecycle race, the implementation, and the regression tests covered by the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
flagd/pkg/service/flag-evaluation/eventing_test.go (2)

167-171: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Silence 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 //nolint inside 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 value

Good regression coverage for the panic fix.

The test correctly drains every notifier concurrently while hammering EmitToAll during 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 on eventing.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

📥 Commits

Reviewing files that changed from the base of the PR and between d99a3e3 and 3f8f6c8.

📒 Files selected for processing (2)
  • flagd/pkg/service/flag-evaluation/eventing.go
  • flagd/pkg/service/flag-evaluation/eventing_test.go

@anxkhn

anxkhn commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

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.

@anxkhn
anxkhn force-pushed the fix/eventing-emit-vs-close-race branch from 3f8f6c8 to fa35245 Compare July 27, 2026 14:47
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jul 27, 2026
@anxkhn

anxkhn commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Pushed a revision addressing the latest review/CI feedback.

@anxkhn
anxkhn force-pushed the fix/eventing-emit-vs-close-race branch from fa35245 to 35dac19 Compare July 27, 2026 15:06

@Baltsat Baltsat left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@anxkhn
anxkhn force-pushed the fix/eventing-emit-vs-close-race branch from 35dac19 to d9f0b9f Compare August 12, 2026 05:23
@toddbaert

Copy link
Copy Markdown
Member

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.

Thanks @Baltsat, dug into this properly. Two separate things in your review:

  1. "A notification can be delivered after Unsubscribe returns." Yep, real; I reproduced it (~50% in your scenario). You're right about the mechanism.

  2. "...so it's a blocking defect." Not in practice, IIUC. I traced the callers: the notifier is a per-stream buffered(1) channel the handler never closes, it just stops reading on return. So a stray late delivery lands in a buffer nobody reads and gets GC'd. No panic/deadlock/etc. So it's real but not an actual bug given how we use it, and IMO doesn't block the fix unless I'm misunderstanding.

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 (TestNoDeliveryAfterUnsubscribe) that fails without the tweak and passes with it.

@toddbaert toddbaert left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Will merge this week unless I hear objections.

@toddbaert
toddbaert requested a review from Baltsat August 12, 2026 20:14
@toddbaert
toddbaert force-pushed the fix/eventing-emit-vs-close-race branch from d2c2687 to 8cbb447 Compare August 12, 2026 20:16

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
flagd/pkg/service/flag-evaluation/eventing_test.go (1)

202-212: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 35dac19 and d2c2687.

📒 Files selected for processing (2)
  • flagd/pkg/service/flag-evaluation/eventing.go
  • flagd/pkg/service/flag-evaluation/eventing_test.go

@open-feature open-feature deleted a comment from coderabbitai Bot Aug 13, 2026
@open-feature open-feature deleted a comment from coderabbitai Bot Aug 13, 2026
anxkhn and others added 2 commits August 14, 2026 10:06
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]>
@toddbaert
toddbaert force-pushed the fix/eventing-emit-vs-close-race branch from 8cbb447 to a114268 Compare August 14, 2026 14:06
@sonarqubecloud

Copy link
Copy Markdown

@toddbaert
toddbaert merged commit 8d7d41f into open-feature:main Aug 14, 2026
13 checks passed
@github-actions github-actions Bot mentioned this pull request Aug 14, 2026
toddbaert added a commit that referenced this pull request Aug 14, 2026
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]>
toddbaert pushed a commit that referenced this pull request Aug 14, 2026
🤖 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants