Skip to content

fix(sync): avoid send on closed channel in fileinfo watcher Close - #1992

Merged
toddbaert merged 3 commits into
open-feature:mainfrom
anxkhn:fix/fileinfo-watcher-close-after-goroutine-stop
Jul 20, 2026
Merged

toddbaert merged 3 commits into
open-feature:mainfrom
anxkhn:fix/fileinfo-watcher-close-after-goroutine-stop

Conversation

@anxkhn

@anxkhn anxkhn commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

The FILEINFO file watcher (core/pkg/sync/file/fileinfo_watcher.go) can crash flagd with panic: send on closed channel at shutdown.

The watcher's timer goroutine is the sole sender on evChan and erChan, but Close() closed both channels without coordinating with that goroutine. If the ticker fires while Close() runs, the goroutine can be mid-send on evChan and hit the panic. The realistic trigger is filepath Sync() returning on context cancel: its defer fs.watcher.Close() runs while the same context is stopping the timer goroutine, so a send can still be in flight exactly as the channel is closed.

This only affects the non-default fileinfo watcher (selected by watchType == "fileinfo"); the default fsnotify watcher is unaffected. The window is narrow, but the panic is unrecovered and takes the process down.

Fix

Close() now stops the timer goroutine before it closes the channels the goroutine sends on:

  • Add a done channel (closed once, guarded by a sync.Once) and a sync.WaitGroup to fileInfoWatcher.
  • Close() signals done, waits for the goroutine to exit (wg.Wait()), and only then closes evChan/erChan, so no send can race with the close.
  • done is also added to the timer goroutine's select and to every send in update(), so an in-flight send is aborted promptly and shutdown cannot deadlock on a full, unread buffer.

No happy-path behavior changes.

Changes

  • core/pkg/sync/file/fileinfo_watcher.go: add done/stopOnce/wg; make Close() stop-then-close; make the timer goroutine and the three sends (erChan in run, both evChan sends in update) abortable on done.
  • core/pkg/sync/file/fileinfo_watcher_test.go: add Test_fileInfoWatcher_Close_racesWithTimer, which drives the timer at a fast tick with a stat func that emits an event every tick, then calls Close() with no reader draining the channels. It panics before this change and passes after. makeTestWatcher gains the done field so the existing close test keeps compiling.

Notes

  • make test-core (-race), golangci-lint v2.7.2, and gofmt all pass locally; core/pkg/sync/file coverage is ~69.9% and the full core/pkg/... -race suite has no regressions.
  • The new test is red -> green: reverting only the Close/run/update coordination (keeping the field so it compiles) reproduces the exact panic: send on closed channel; with the fix it is race-clean across repeated runs.

The FILEINFO file watcher's timer goroutine is the sole sender on evChan
and erChan, but Close() closed both channels without coordinating with
that goroutine. If the ticker fired while Close ran (for example when
filepath Sync returns on context cancel and its deferred watcher.Close()
executes), the goroutine could be mid-send on evChan and hit
"panic: send on closed channel", crashing flagd. This only affects the
non-default fileinfo watcher; the default fsnotify watcher is unaffected.

Give the watcher a done channel (guarded by a sync.Once) and a
sync.WaitGroup. Close now signals the goroutine to stop and aborts any
in-flight send, waits for the goroutine to exit, and only then closes the
channels, so no send can race with the close. The stop signal is also
added to the run loop's select and to every send in update so shutdown is
prompt and cannot deadlock on a full buffer.

Adds a regression test that drives the timer at a fast tick with a stat
func that emits an event every tick, then calls Close with no reader
draining the channels; it panics before this change and passes after.

Signed-off-by: Anas Khan <[email protected]>
@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 77c1bd0
🔍 Latest deploy log https://app.netlify.com/projects/polite-licorice-3db33c/deploys/6a5e18a712bea00008e5679f

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jul 10, 2026
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1cdfdab1-658f-460a-81aa-4f723e2b0bcf

📥 Commits

Reviewing files that changed from the base of the PR and between aa6f91b and 77c1bd0.

📒 Files selected for processing (1)
  • core/pkg/sync/file/fileinfo_watcher_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/pkg/sync/file/fileinfo_watcher_test.go

📝 Walkthrough

Walkthrough

The file watcher now coordinates timer goroutine shutdown before closing channels. Event and error sends can abort during shutdown, and a concurrency test covers closing while timer events are being emitted.

Changes

File watcher shutdown

Layer / File(s) Summary
Coordinate watcher shutdown
core/pkg/sync/file/fileinfo_watcher.go
The watcher initializes shutdown state, makes Close() idempotent, waits for the timer goroutine to exit, and guards event and error sends against shutdown.
Validate shutdown race
core/pkg/sync/file/fileinfo_watcher.go, core/pkg/sync/file/fileinfo_watcher_test.go
A test closes a busy 1ms timer watcher twice and verifies safe termination and closure of both output channels.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: djosephsen, alexandraoberaigner

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main fix: preventing a send-on-closed-channel race in fileinfo watcher shutdown.
Description check ✅ Passed The description is directly about the same shutdown-race fix and matches the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


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: 2

🧹 Nitpick comments (1)
core/pkg/sync/file/fileinfo_watcher_test.go (1)

45-58: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Make the race setup deterministic.

The 512-slot buffer cannot be assumed to fill during a 20 ms sleep, so the test may never reach the documented blocked-send state. Use an unbuffered channel and signal when statFunc is entered instead of sleeping.

Proposed test setup
 watcher := makeTestWatcher(t, map[string]fs.FileInfo{
     "foo": &mockFileInfo{name: "foo", modTime: time.Now()},
 })
+watcher.evChan = make(chan fsnotify.Event)
+statCalled := make(chan struct{})

 watcher.statFunc = func(_ string) (fs.FileInfo, error) {
+    close(statCalled)
     return &mockFileInfo{name: "foo", modTime: time.Now().Add(time.Hour)}, nil
 }

 watcher.run(context.Background(), time.Millisecond)
-time.Sleep(20 * time.Millisecond)
+<-statCalled
🤖 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 `@core/pkg/sync/file/fileinfo_watcher_test.go` around lines 45 - 58, Make
Test_fileInfoWatcher_Close_racesWithTimer deterministic by replacing the
watcher’s event channel with an unbuffered channel and adding a synchronization
signal from statFunc when it is entered. Wait on that signal before invoking the
close/race logic, rather than relying on the fixed 20 ms sleep, ensuring the
goroutine reaches the blocked send state described by the test.
🤖 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 `@core/pkg/sync/file/fileinfo_watcher_test.go`:
- Around line 60-70: Add a second call to fileInfoWatcher.Close() in the test
after the initial close succeeds, and assert it returns nil without panicking.
Keep the existing channel-closure assertions to verify repeated Close remains
idempotent.

In `@core/pkg/sync/file/fileinfo_watcher.go`:
- Around line 55-65: Make fileInfoWatcher.Close fully idempotent by moving the
done signal, f.wg.Wait(), and both channel closures inside the existing
f.stopOnce.Do callback; subsequent Close calls must perform no operations and
must not panic.

---

Nitpick comments:
In `@core/pkg/sync/file/fileinfo_watcher_test.go`:
- Around line 45-58: Make Test_fileInfoWatcher_Close_racesWithTimer
deterministic by replacing the watcher’s event channel with an unbuffered
channel and adding a synchronization signal from statFunc when it is entered.
Wait on that signal before invoking the close/race logic, rather than relying on
the fixed 20 ms sleep, ensuring the goroutine reaches the blocked send state
described by the test.
🪄 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: a36fd104-91af-49d3-9555-523d7e7c97f5

📥 Commits

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

📒 Files selected for processing (2)
  • core/pkg/sync/file/fileinfo_watcher.go
  • core/pkg/sync/file/fileinfo_watcher_test.go

Comment thread core/pkg/sync/file/fileinfo_watcher.go Resolved
// fileInfoWatcher explicitly implements file.Watcher
var _ Watcher = &fileInfoWatcher{}

// Close calls close on the underlying fsnotify.Watcher

@toddbaert toddbaert Jul 16, 2026 •

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.

Whoops, that was inaccurate thanks for fixing.

Comment thread core/pkg/sync/file/fileinfo_watcher.go Outdated
wg sync.WaitGroup
}

// NewFsNotifyWatcher returns a new fsNotifyWatcher

@toddbaert toddbaert Jul 16, 2026 •

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.

Suggested change
// NewFsNotifyWatcher returns a new fsNotifyWatcher
// NewFileInfoWatcher returns a new fileInfoWatcher

Comment on lines +55 to +56
// nothing reads Events()/Errors(), so the buffer fills and the goroutine ends
// up blocked mid-send, which is exactly when the unguarded Close() panicked

@toddbaert toddbaert Jul 16, 2026 •

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.

so the buffer fills

Am I confused?

the 512 buffer never fills with ~20 events; the real mechanism is context.Background() never cancels, so the goroutine keeps ticking/sending after Close, I think... right?

I think the test is correct, but this isn't the right mechanism by which it works, unless I'm confused.

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

This improves things, but I think coderabbit did spot some remaining issues that are similar here and here. I think they are worth addressing.

Also some nits from me:

@sonarqubecloud

Copy link
Copy Markdown

@toddbaert
toddbaert merged commit a7339ea into open-feature:main Jul 20, 2026
13 checks passed
@github-actions github-actions Bot mentioned this pull request Jul 20, 2026
toddbaert pushed a commit that referenced this pull request Jul 27, 2026
🤖 I have created a release *beep* *boop*
---


<details><summary>flagd: 0.16.1</summary>

##
[0.16.1](flagd/v0.16.0...flagd/v0.16.1)
(2026-07-27)


### 🐛 Bug Fixes

* add server ReadTimeouts, update security deps
([#1980](#1980))
([0e1e8b3](0e1e8b3))
* handle invalid selector errors
([#1976](#1976))
([409a62e](409a62e))
* **security:** update module google.golang.org/grpc to v1.82.1
[security] ([#2005](#2005))
([4281adf](4281adf))
* **security:** update vulnerability-updates [security]
([#1984](#1984))
([2a5a6b6](2a5a6b6))


### ✨ New Features

* **sync:** configurable gRPC keepalive enforcement on sync server
([#1999](#1999))
([19e57b9](19e57b9))
</details>

<details><summary>flagd-proxy: 0.9.7</summary>

##
[0.9.7](flagd-proxy/v0.9.6...flagd-proxy/v0.9.7)
(2026-07-27)


### 🐛 Bug Fixes

* add server ReadTimeouts, update security deps
([#1980](#1980))
([0e1e8b3](0e1e8b3))
* **security:** update module google.golang.org/grpc to v1.82.1
[security] ([#2005](#2005))
([4281adf](4281adf))
* **security:** update vulnerability-updates [security]
([#1984](#1984))
([2a5a6b6](2a5a6b6))
</details>

<details><summary>core: 0.16.1</summary>

##
[0.16.1](core/v0.16.0...core/v0.16.1)
(2026-07-27)


### 🐛 Bug Fixes

* **certreloader:** re-check reload condition under write lock
([#1994](#1994))
([86489da](86489da))
* handle invalid selector errors
([#1976](#1976))
([409a62e](409a62e))
* readyz never true of multiple gRPC syncs are used
([#1985](#1985))
([29833e8](29833e8))
* **security:** update module google.golang.org/grpc to v1.82.1
[security] ([#2005](#2005))
([4281adf](4281adf))
* **security:** update vulnerability-updates [security]
([#1984](#1984))
([2a5a6b6](2a5a6b6))
* **sync:** avoid send on closed channel in fileinfo watcher Close
([#1992](#1992))
([a7339ea](a7339ea))
* **sync:** handle non-string YAML map keys in config parsing
([#1990](#1990))
([3c72e6f](3c72e6f))
* **sync:** re-establish file watch after delete and restore
([#2001](#2001))
([d434adf](d434adf))
* **sync:** synchronize readiness state
([#2006](#2006))
([317a7e0](317a7e0))


### ✨ New Features

* improve ETag and body hash support to blob/http sync
([#1991](#1991))
([1e210d4](1e210d4))


### 🧹 Chore

* fix flaky test
([7ff137d](7ff137d))
</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.

2 participants