gpu-operator icon indicating copy to clipboard operation
gpu-operator copied to clipboard

[Feature]: Replace the package-global clusterPolicyCtrl and run tests with -race

Open CloneOfAlex opened this issue 1 month ago • 4 comments

Motivation controllers/clusterpolicy_controller.go:61 declares a package-level clusterPolicyCtrl that the ClusterPolicy reconciler mutates in init() and other controllers read (the upgrade controller at upgrade_controller.go:135; state_manager.go:615 and 665 read operatorNamespace). This causes an unsynchronized read across controller goroutines (#3061) and makes the code hard to test in isolation.

Proposal

  1. Build the controller state per reconcile (or behind an accessor with a lock), and have other controllers derive what they need (OpenShift/DTK detection, namespace) from their own reads.
  2. Add -race to make unit-test and to any envtest suite that starts more than one controller, so this class of bug is caught in CI.

Related: #3061.

CloneOfAlex avatar Oct 13 '26 18:10 CloneOfAlex

@CloneOfAlex

Could you provide more details about the problem you encountered and your proposed solution?

francisguillier avatar Oct 19 '26 23:10 francisguillier

Thanks @francisguillier — here's the detail.

The problem

clusterPolicyCtrl (controllers/clusterpolicy_controller.go:61) is a package-level ClusterPolicyController. The ClusterPolicy reconciler writes it on every reconcile in init() (state_manager.go:766+): operatorNamespace, openshift, and ocpDriverToolkit.enabled/requested via initOCPParams(). Other code reads it directly:

Reader Field(s) Location
UpgradeReconciler (separate controller, own goroutine) openshift, ocpDriverToolkit.enabled upgrade_controller.go:135
setPodSecurityLabelsForNamespace operatorNamespace state_manager.go:615
ocpEnsureNamespaceMonitoring operatorNamespace state_manager.go:665

MaxConcurrentReconciles: 1 serializes each controller with itself, but not the ClusterPolicy and Upgrade controllers with each other, so the access at line 135 is an unsynchronized read/write across goroutines.

Why it matters

  1. Order-dependent behavior (OpenShift + DTK). If the upgrade controller reconciles before the first ClusterPolicy reconcile, it sees openshift == "" and builds its selector with app=nvidia-driver-daemonset instead of openshift.driver-toolkit=true. With DTK enabled that matches no driver pods, so upgrade state is wrong until the next requeue. Same cluster, different result depending on which controller runs first.
  2. Data race. Undefined behavior under the Go memory model. It's invisible today because make unit-test doesn't run with -race and no test drives two controllers concurrently.
  3. Testability. Tests have to mutate and restore the global (clusterpolicy_controller_test.go:477-483), which makes them order-sensitive and unsafe for t.Parallel().

To be transparent: I found this through code review, not a production incident (same as #3061). Here are two tests against current main, using the existing newTestUpgradeReconciler helper:

  • TestUpgradeSelectorDependsOnClusterPolicyReconcileOrder (deterministic, passes): shows the selector flipping based only on whether clusterPolicyCtrl has been populated yet.
  • TestUpgradeReconcileRacesWithClusterPolicyInit: runs the real UpgradeReconciler.Reconcile path concurrently with writes to the same fields init() writes. go test -race -run RacesWith ./controllers/ reports:
WARNING: DATA RACE
Read at 0x000005a73278 by goroutine 60:
  controllers.(*UpgradeReconciler).reconcileClusterPolicyDriverUpgrades()
      controllers/upgrade_controller.go:135
  controllers.(*UpgradeReconciler).Reconcile()
      controllers/upgrade_controller.go:115
Previous write at 0x000005a73278 by goroutine 59:
  ...

The write side in this test stands in for init()/initOCPParams(), since driving the real ClusterPolicy reconcile needs a cluster; the read side is the real upgrade reconcile path.

controllers/upgrade_controller_race_test.go
package controllers

import (
	"context"
	"sync"
	"testing"

	upgrade_v1alpha1 "github.com/NVIDIA/k8s-operator-libs/api/upgrade/v1alpha1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	gpuv1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1"
)

func autoUpgradeClusterPolicy() *gpuv1.ClusterPolicy {
	cp := &gpuv1.ClusterPolicy{ObjectMeta: metav1.ObjectMeta{Name: "cluster-policy"}}
	cp.Spec.Driver.UpgradePolicy = &upgrade_v1alpha1.DriverUpgradePolicySpec{AutoUpgrade: true}
	return cp
}

// Same cluster (OpenShift + DTK), two different selectors depending on
// whether the ClusterPolicy controller has populated clusterPolicyCtrl yet.
func TestUpgradeSelectorDependsOnClusterPolicyReconcileOrder(t *testing.T) {
	saved := clusterPolicyCtrl
	t.Cleanup(func() { clusterPolicyCtrl = saved })

	clusterPolicyCtrl = ClusterPolicyController{}
	r, sm := newTestUpgradeReconciler(t, autoUpgradeClusterPolicy())
	_, err := r.Reconcile(context.Background(), upgradeSingletonRequest())
	require.NoError(t, err)
	before := sm.buildLabels

	clusterPolicyCtrl = ClusterPolicyController{openshift: "4.16"}
	clusterPolicyCtrl.ocpDriverToolkit.enabled = true
	r, sm = newTestUpgradeReconciler(t, autoUpgradeClusterPolicy())
	_, err = r.Reconcile(context.Background(), upgradeSingletonRequest())
	require.NoError(t, err)
	after := sm.buildLabels

	assert.Equal(t, map[string]string{DriverLabelKey: DriverLabelValue}, before)
	assert.Equal(t, map[string]string{ocpDriverToolkitIdentificationLabel: ocpDriverToolkitIdentificationValue}, after)
}

// Run with -race.
func TestUpgradeReconcileRacesWithClusterPolicyInit(t *testing.T) {
	saved := clusterPolicyCtrl
	t.Cleanup(func() { clusterPolicyCtrl = saved })
	clusterPolicyCtrl = ClusterPolicyController{}

	r, _ := newTestUpgradeReconciler(t, autoUpgradeClusterPolicy())

	var wg sync.WaitGroup
	wg.Add(2)
	go func() { // stands in for ClusterPolicyReconciler -> init() -> initOCPParams()
		defer wg.Done()
		for i := 0; i < 100; i++ {
			clusterPolicyCtrl.openshift = "4.16"
			clusterPolicyCtrl.ocpDriverToolkit.enabled = i%2 == 0
		}
	}()
	go func() { // real UpgradeReconciler path
		defer wg.Done()
		for i := 0; i < 100; i++ {
			_, _ = r.Reconcile(context.Background(), upgradeSingletonRequest())
		}
	}()
	wg.Wait()
}

Proposed solution (incremental, small PRs)

  1. Internal reads use the receiver. state_manager.go:615/665/775 reference clusterPolicyCtrl.operatorNamespace from inside methods on n *ClusterPolicyController; switch them to n.operatorNamespace. No behavior change.
  2. Decouple the upgrade controller. UpgradeReconciler already receives OperatorNamespace from main.go. Have it determine OpenShift/DTK from its own reads (OpenshiftVersion(ctx) plus the ClusterPolicy spec / DTK imagestream check via its own client), or factor that detection into a shared helper both controllers call. That removes the last external reader; #3061 tracks the bug side of this step.
  3. Remove the global. Hold the ClusterPolicyController on ClusterPolicyReconciler (or build it per reconcile), so tests construct their own instance instead of swapping a package variable.
  4. Add -race to CI. Add it to make unit-test (or a separate unit-test-race target if the slowdown is a concern), and keep a concurrent test like the one above. For what it's worth, the current unit suite (all packages except e2e) already passes under -race, so enabling it shouldn't break anything — but it won't catch this bug on its own without a test that exercises the concurrency.

I'm happy to open PRs for these, starting with 1 and 4 since they're lowest risk. Let me know if you'd prefer a different approach for step 2.

CloneOfAlex avatar Oct 20 '26 15:10 CloneOfAlex

@CloneOfAlex

I’m not sure I understand the deployment problem you’re trying to solve. Could you please provide:

  • Issue summary: What is happening, and what behavior do you expect?
  • Steps to reproduce: Include the relevant environment details and configuration.
  • Proposed fix: Explain how the fix addresses the problem. Without these details, we won’t be able to assess the issue and will close it. Thanks

francisguillier avatar Nov 05 '26 22:11 francisguillier

@francisguillier here it is in that format.

Issue summary On OpenShift with the Driver Toolkit (DTK) and driver auto-upgrade enabled, the upgrade controller builds its driver-pod selector from the package-global clusterPolicyCtrl (controllers/upgrade_controller.go:135). That global is only populated by the ClusterPolicy reconciler. If the upgrade controller reconciles first (for example right after the operator restarts), it uses app=nvidia-driver-daemonset instead of openshift.driver-toolkit=true, matches no driver pods, and computes the wrong upgrade state until a later requeue. The read is also an unsynchronized read/write across two controller goroutines. Expected: the upgrade controller computes the same selector regardless of which controller ran first.

Steps to reproduce

  • Unit level (current main): go test -race -run RacesWith ./controllers/ with the test in my previous comment reports DATA RACE at upgrade_controller.go:135. TestUpgradeSelectorDependsOnClusterPolicyReconcileOrder shows the selector flipping based only on reconcile order.
  • Cluster: OpenShift with driver.useOpenShiftDriverToolkit=true and driver.upgradePolicy.autoUpgrade=true. Restart the operator pod while a driver upgrade is pending, then check the first upgrade reconcile's logs for the driver-pod selector. I haven't run the cluster scenario myself; it follows from the code path.

Proposed fix Have the upgrade controller determine OpenShift/DTK from its own reads (or a shared helper) instead of the global, then remove the global. Add -race to make unit-test; the suite already passes under it. Small PRs, in the order listed in my previous comment.

CloneOfAlex avatar Nov 05 '26 23:11 CloneOfAlex