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

[Feature]: State manager should read before create instead of creating every object on every reconcile

Open CloneOfAlex opened this issue 1 month ago • 4 comments

Motivation internal/state/state_skel.go:createOrUpdateObjs (line 301) calls Create for every rendered object on every reconcile and treats AlreadyExists as the signal to fall back to Get + Update. NVIDIADriver and GPUCluster requeue every 5 s while NotReady (and GPUCluster every minute when Ready), so a steady-state cluster sends a constant stream of failing Create calls: API server load, audit-log noise, and admission webhooks invoked for no change.

Proposal Get the object from the informer cache first; Create only on NotFound; Update only when the desired hash differs. Server-side apply (see the drift-detection proposal filed alongside this) would also remove the pattern.

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

createOrUpdateObjs (internal/state/state_skel.go:301) handles every rendered object on every reconcile like this:

  1. Create. If that returns AlreadyExists (409):
  2. live Get
  3. DaemonSets only: skip if the nvidia.com/last-applied-hash annotation matches the desired hash
  4. otherwise, Update unconditionally

So in steady state, nothing has changed, but every object still costs a failing Create plus a Get. Every non-DaemonSet object (ServiceAccount, Role, RoleBinding, ClusterRole/Binding, ConfigMap, Service, …) also gets an Update. The hash check that prevents that already exists, but it only applies to DaemonSets.

This runs often. NVIDIADriver and GPUCluster requeue every 5s while NotReady (nvidiadriver_controller.go:222, gpucluster_controller.go:139/146/241), and GPUCluster every minute when Ready (gpucluster_controller.go:114/156). The calls don't change anything, but each one still goes through authn/authz, admission (including any validating webhooks on those kinds), and audit logging.

Measurement

To be transparent: I found this through code review, not a production incident. Here's a unit test against current main that counts calls using the existing fake client and interceptor helpers. It uses a ServiceAccount, Role, RoleBinding, ConfigMap, and DaemonSet (the namespaced part of state-driver):

steady state, per reconcile of 5 unchanged objects: Create=5 (409=5) Get=5 Update=4

That's 14 API calls per reconcile that change nothing, for one state and one node pool. At the 5s NotReady requeue, that's about 170 calls/minute. The real state-driver adds ClusterRole/ClusterRoleBinding (and SCC on OpenShift), and state-dra-driver renders around 25 objects.

internal/state/state_skel_steady_state_test.go
package state

import (
	"context"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/fake"
	"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
)

type apiCallCounts struct {
	create, createAlreadyExists, get, update int
}

func newNamespacedUnstructured(group, kind, name string) *unstructured.Unstructured {
	o := &unstructured.Unstructured{}
	o.SetGroupVersionKind(schema.GroupVersionKind{Group: group, Version: "v1", Kind: kind})
	o.SetName(name)
	o.SetNamespace("test-ns")
	return o
}

// renderDriverLikeObjects returns freshly "rendered" objects on each call, the way
// the driver state re-renders its manifests on every reconcile: ServiceAccount,
// Role, RoleBinding, ConfigMap and DaemonSet (the namespaced part of state-driver).
func renderDriverLikeObjects() []*unstructured.Unstructured {
	return []*unstructured.Unstructured{
		newServiceAccountUnstructured("nvidia-driver", "test-ns"),
		newNamespacedUnstructured(rbacv1.GroupName, "Role", "nvidia-driver"),
		newNamespacedUnstructured(rbacv1.GroupName, "RoleBinding", "nvidia-driver"),
		newConfigMapUnstructured("nvidia-driver-cfg", "test-ns"),
		newDaemonSetUnstructured("nvidia-driver-daemonset", "test-ns"),
	}
}

// TestCreateOrUpdateObjsSteadyStateAPICalls documents the API traffic
// createOrUpdateObjs generates when nothing has changed. Every steady-state
// reconcile issues one failing Create (409 AlreadyExists) and one Get per object,
// plus an unconditional Update for every object that is not a DaemonSet.
func TestCreateOrUpdateObjsSteadyStateAPICalls(t *testing.T) {
	scheme := runtime.NewScheme()
	require.NoError(t, corev1.AddToScheme(scheme))
	require.NoError(t, appsv1.AddToScheme(scheme))
	require.NoError(t, rbacv1.AddToScheme(scheme))

	var c apiCallCounts
	fakeClient := fake.NewClientBuilder().WithScheme(scheme).
		WithInterceptorFuncs(interceptor.Funcs{
			Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
				c.create++
				err := cl.Create(ctx, obj, opts...)
				if apierrors.IsAlreadyExists(err) {
					c.createAlreadyExists++
				}
				return err
			},
			Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
				c.get++
				return cl.Get(ctx, key, obj, opts...)
			},
			Update: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
				c.update++
				return cl.Update(ctx, obj, opts...)
			},
		}).Build()
	skel := newTestSkel(t, fakeClient)
	ctx := context.Background()

	// First reconcile: everything is created.
	require.NoError(t, skel.createOrUpdateObjs(ctx, noopSetControllerReference, renderDriverLikeObjects()))
	assert.Equal(t, apiCallCounts{create: 5}, c)

	// Steady state: nothing changed, re-run the same reconcile a few times.
	const reconciles = 3
	c = apiCallCounts{}
	for i := 0; i < reconciles; i++ {
		require.NoError(t, skel.createOrUpdateObjs(ctx, noopSetControllerReference, renderDriverLikeObjects()))
	}
	t.Logf("steady state, per reconcile of 5 unchanged objects: Create=%d (409=%d) Get=%d Update=%d",
		c.create/reconciles, c.createAlreadyExists/reconciles, c.get/reconciles, c.update/reconciles)

	// 5 failing Creates + 5 Gets + 4 Updates (the DaemonSet hash check skips only the DaemonSet)
	// = 14 API calls per reconcile, none of which change anything.
	assert.Equal(t, apiCallCounts{
		create:              5 * reconciles,
		createAlreadyExists: 5 * reconciles,
		get:                 5 * reconciles,
		update:              4 * reconciles,
	}, c)
}

Proposed solution (staged)

  1. Get first, extend the hash skip to all kinds (small PR, no config change):
    • Get → on NotFound, Create; on found, compare the hash annotation and Update only on mismatch.
    • utils.GetObjectHash is already computed for DaemonSets; this applies it to every kind.
    • Steady state drops from 14 → 5 calls (5 live Gets, no 409s, no Updates). I'd update the test above to assert that.
  2. Serve those Gets from the cache (optional follow-up). The manager client does not cache unstructured objects today (client.CacheOptions.Unstructured is unset in main.go), so the Gets in step 1 are still live. Enabling it would bring steady state to roughly zero API calls. The cost is an informer per GVK the states touch, which means memory plus list/watch RBAC for cluster-scoped kinds like ClusterRole and DeviceClass. That's worth evaluating separately rather than bundling.
  3. Server-side apply is the longer-term alternative: one Patch per object, no 409s, and field ownership. It changes semantics (field managers, migration from Update-managed fields), so I'd treat it as its own design discussion.

One trade-off to call out for step 1: today's unconditional Update also reverts out-of-band edits to non-DaemonSet objects on every reconcile. With a hash skip, an edit that doesn't touch the annotation would persist until the desired spec changes. DaemonSets already behave this way, so this makes behavior consistent rather than new, but it's a change for the other kinds. The drift-detection proposal I filed alongside this one is meant to close that gap.

I'm happy to open the PR for step 1 with the test. Let me know if you'd rather keep the unconditional Update for some kinds (e.g. RBAC) for drift correction.

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 For NVIDIADriver and GPUCluster, every reconcile sends a Create for every rendered object. Each one fails with 409 AlreadyExists and falls back to Get, plus an unconditional Update for every non-DaemonSet object. Nothing has changed, but the API server still pays for authn/authz, admission webhooks and audit logging on each call. Expected: no writes when the desired state is unchanged.

Steps to reproduce

  1. Install the operator and create an NVIDIADriver (or GPUCluster).
  2. With nothing changing, watch API server metrics for the operator's service account, e.g. apiserver_request_total{verb="POST",code="409"} and {verb="PUT"}, or the audit log. Both increase on every requeue (every 5 s while NotReady, every minute for a Ready GPUCluster).
  3. Unit level: the test in my previous comment measures 5 Creates (all 409), 5 Gets and 4 Updates per reconcile of 5 unchanged objects.

Proposed fix In createOrUpdateObjs, Get first, Create only on NotFound, and extend the existing DaemonSet hash-annotation skip to all kinds so Update happens only when the desired hash changes. That takes steady state from 14 calls to 5 Gets in the test. Small PR, no config change.

CloneOfAlex avatar Nov 05 '26 23:11 CloneOfAlex