Skip to content

fix(core): register the OFO scheme at package init, not inside Sync.Init - #2024

Merged
toddbaert merged 2 commits into
open-feature:mainfrom
yuchou87:fix/core-register-scheme-at-package-init
Aug 14, 2026
Merged

toddbaert merged 2 commits into
open-feature:mainfrom
yuchou87:fix/core-register-scheme-at-package-init

Conversation

@yuchou87

@yuchou87 yuchou87 commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

What

Moves v1beta1.AddToScheme(scheme.Scheme) out of kubernetes.Sync.Init and into
the package's init(), so the global client-go scheme is mutated once, on a single
goroutine, before anything can use it concurrently.

Fixes #2023.

Why

runtime.Scheme holds plain maps and carries no lock. apimachinery states the
contract on the type itself:

// Schemes are not expected to change at runtime and are only threadsafe after
// registration is complete.
type Scheme struct {
	gvkToType map[schema.GroupVersionKind]reflect.Type
	...

Sync.Init violates that by writing to the global scheme.Scheme at runtime.
That is harmless in flagd, which calls Init in a serial startup loop
(flagd/pkg/runtime/runtime.go:60), but flagd-proxy calls it from one goroutine
per sync target at arbitrary times (flagd-proxy/pkg/service/subscriptions/manager.go:128
→ :201), so two targets registering close together race on those maps and the Go
runtime kills the process:

fatal error: concurrent map read and map write

goroutine 2695 [running]:
k8s.io/apimachinery/pkg/runtime.(*Scheme).AddKnownTypeWithName(...)
	k8s.io/[email protected]/pkg/runtime/scheme.go:180
...
github.com/open-feature/flagd/core/pkg/sync/kubernetes.(*Sync).Init(...)
	/src/core/pkg/sync/kubernetes/kubernetes_sync.go:72
github.com/open-feature/flagd/flagd-proxy/pkg/service/subscriptions.(*Coordinator).watchResource(...)
	/src/flagd-proxy/pkg/service/subscriptions/manager.go:201
created by ...(*Coordinator).RegisterSubscription in goroutine 2694
	/src/flagd-proxy/pkg/service/subscriptions/manager.go:128

We see this roughly once an hour in a test cluster with four sync targets. Two
distinct targets registering close in time are enough — a second subscriber to an
existing target reuses the multiplexer and never calls Init. In practice it is
self-reinforcing: the crash makes every client reconnect at once, which is exactly
the condition that triggers it.

Registering at package init matches what the type documents and costs nothing: the
work was already idempotent, so doing it once instead of per-Init is strictly
less work. utilruntime.Must is the conventional Kubernetes idiom here — the call
only touches in-memory maps, so a failure would mean conflicting type definitions,
which is worth failing at startup for.

Change

All of core/pkg/sync/kubernetes/kubernetes_sync.go:

@@ -15,6 +15,7 @@ import (
 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
 	"k8s.io/apimachinery/pkg/runtime"
 	"k8s.io/apimachinery/pkg/types"
+	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
 	"k8s.io/client-go/dynamic"
 	"k8s.io/client-go/dynamic/dynamicinformer"
 	"k8s.io/client-go/kubernetes/scheme"
@@ -31,6 +32,14 @@ var (
 
 const invalidAPIVersionMsg = "invalid api version %s, expected %s"
 
+// Registering into the global client-go scheme has to happen once, before
+// anything can use it concurrently: runtime.Scheme is documented as "only
+// threadsafe after registration is complete". Doing it from Sync.Init instead
+// races on its unguarded maps, see https://github.com/open-feature/flagd/issues/2023.
+func init() {
+	utilruntime.Must(v1beta1.AddToScheme(scheme.Scheme))
+}
+
 type SyncOption func(s *Sync)
 
 type Sync struct {
@@ -73,10 +82,6 @@ func (k *Sync) Init(_ context.Context) error {
 		return fmt.Errorf("unable to parse uri %s: %w", k.URI, err)
 	}
 
-	if err := v1beta1.AddToScheme(scheme.Scheme); err != nil {
-		return fmt.Errorf("unable to v1beta1 types to scheme: %w", err)
-	}
-
 	// The created informer will not do resyncs if the given defaultEventHandlerResyncPeriod is zero.
 	// For more details on resync implications refer to tools/cache/shared_informer.go
 	factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(k.dynamicClient, resyncPeriod, k.namespace, nil)

Sync.Init's signature is unchanged, and neither caller distinguished that error
from the URI-parsing one, so this is not a breaking change.

No new dependency — utilruntime is already part of k8s.io/apimachinery. The
rest of the diff is the two tests described below.

Testing

Two regression tests in kubernetes_sync_test.go:

  • TestConcurrentInit — reproduces the reported crash directly: 16 goroutines
    calling Sync.Init concurrently. With the fix reverted this reports DATA RACE
    on 5 runs out of 5 (65–541 reports per run), pointing at AddToScheme ←
    Sync.Init; with the fix it passes. make test already runs -race, so this is
    caught in CI.
  • TestSchemeRegisteredAtPackageInit — asserts the registration happened by
    package-init time, which holds without -race too. It captures the state from an
    init() rather than reading it in the test body, because Sync.Init registers
    the types as a side effect and the pre-existing TestInit calls it — read from a
    test function, the check passes whether or not the fix is present. I verified that
    false negative before settling on this shape.

Verified against main (5c74b83): all three modules build and vet clean;
go test -race passes for ./core/... (19 packages), and for the touched package
under -count=3 and three rounds of -shuffle=on; golangci-lint reports 0 issues
for it.

Also removed a now-redundant v1beta1.AddToScheme from TestNotify — package init
covers it, and it was a second global mutation from a test.

One thing worth your call

While checking this I found that nothing in-tree appears to consume the global
registration at all.
With the init() and the k8s.io/client-go/kubernetes/scheme
import deleted outright, all three modules build and the whole kubernetes package
test suite passes (only my new guard test fails, by construction). The real dynamic
client and dynamicinformer never touch scheme.Scheme; toFFCfg uses
runtime.DefaultUnstructuredConverter; only dynamic/fake consumes a scheme, and
the tests can pass their own.

So deleting the global mutation may be the better fix. I did not propose that here
because core is an importable module and dropping a global registration is an
observable change for downstream importers, which felt like your call rather than
mine. Happy to switch this PR to the deletion if you prefer it.

@yuchou87
yuchou87 requested review from a team as code owners August 14, 2026 08:09
@netlify

netlify Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

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

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

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Aug 14, 2026
@coderabbitai

coderabbitai Bot commented Aug 14, 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 Plus

Run ID: c562a8c0-d0a9-4823-b2df-865978c4725d

📥 Commits

Reviewing files that changed from the base of the PR and between 937dfb5 and 226de56.

📒 Files selected for processing (2)
  • core/pkg/sync/kubernetes/kubernetes_sync.go
  • core/pkg/sync/kubernetes/kubernetes_sync_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • core/pkg/sync/kubernetes/kubernetes_sync.go
  • core/pkg/sync/kubernetes/kubernetes_sync_test.go

📝 Walkthrough

Walkthrough

The Kubernetes sync now registers API types during package initialization. Sync.Init no longer mutates the global scheme. Tests verify registration before use and concurrent initialization across 16 goroutines.

Changes

Kubernetes scheme registration

Layer / File(s) Summary
Package-level scheme registration
core/pkg/sync/kubernetes/kubernetes_sync.go
The package registers v1beta1 types once during initialization and removes scheme registration from Sync.Init.
Concurrent initialization validation
core/pkg/sync/kubernetes/kubernetes_sync_test.go
Tests verify package registration, concurrent Sync.Init calls, and global scheme use in TestNotify.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to 226de

This localized change moves scheme registration to package initialization and is merge-ready after normal checks; no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes moving OFO scheme registration to package initialization.
Description check ✅ Passed The description explains the concurrency issue, the proposed fix, the tests, and the reason for the design.
Linked Issues check ✅ Passed The changes address issue #2023 by completing scheme registration before concurrent Sync.Init calls.
Out of Scope Changes check ✅ Passed The code and test changes directly support issue #2023 and do not introduce unrelated scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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.

@toddbaert
toddbaert force-pushed the fix/core-register-scheme-at-package-init branch from 226de56 to bbbe823 Compare August 14, 2026 19:13
@toddbaert
toddbaert self-requested a review August 14, 2026 19:18

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

Nice catch, thanks! @yuchou87

Same addition as #2022 (review).

@toddbaert
toddbaert force-pushed the fix/core-register-scheme-at-package-init branch from bbbe823 to 8112b41 Compare August 14, 2026 19:19
yuchou87 and others added 2 commits August 14, 2026 15:20
kubernetes.Sync.Init called v1beta1.AddToScheme on the global client-go
scheme. runtime.Scheme holds several unguarded maps and apimachinery
documents it as "only threadsafe after registration is complete", so
mutating it at arbitrary runtime moments violates that contract.

flagd is unaffected because it calls Init serially at startup, but
flagd-proxy calls it from one goroutine per sync target, so two targets
registering close together race on those maps and the Go runtime kills
the process with "fatal error: concurrent map read and map write".

Moving the registration to package init keeps it single-goroutine and
happens before anything can use the scheme concurrently. The work was
already idempotent, so doing it once instead of per-Init is strictly
less work.

Signed-off-by: Yu Chou <[email protected]>
@toddbaert
toddbaert force-pushed the fix/core-register-scheme-at-package-init branch from 8112b41 to 1f472ab Compare August 14, 2026 19:20
@sonarqubecloud

Copy link
Copy Markdown

@toddbaert
toddbaert merged commit cf2db36 into open-feature:main Aug 14, 2026
13 checks passed
@github-actions github-actions Bot mentioned this pull request Aug 14, 2026
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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] flagd-proxy crashes with "concurrent map read and map write" — Sync.Init mutates the global runtime.Scheme at runtime

2 participants