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

[Feature]: Use exponential backoff instead of fixed 5 s requeues for failing NVIDIADriver/GPUCluster states

Open CloneOfAlex opened this issue 1 month ago • 4 comments

Motivation When a state is not ready, NVIDIADriverReconciler.Reconcile and GPUClusterReconciler.Reconcile return RequeueAfter: 5s with a nil error, including when a state reports an ErrInfo (a render or apply error that will not fix itself). The controllers' exponential rate limiter (minDelayCR..maxDelayCR) is bypassed, so a permanently broken pool re-renders and re-applies every manifest about 720 times an hour, with matching log volume.

Proposal

  • When any state returns ErrInfo, return the error so the rate limiter applies backoff.
  • Keep a short requeue only for "waiting for pods", or rely on the DaemonSet watches the state manager already registers to trigger the next reconcile.

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, including a correction to my own proposal.

The problem

When a state isn't ready, both reconcilers return RequeueAfter: 5s with a nil error. That includes the case where a state reported ErrInfo:

  • NVIDIADriverReconciler.Reconcile: nvidiadriver_controller.go:222
  • GPUClusterReconciler.Reconcile: gpucluster_controller.go:139 (state error) and :146 (waiting on operands)

Two consequences follow:

  1. No backoff. With RequeueAfter > 0 and a nil error, controller-runtime calls Queue.Forget(req) (internal/controller/controller.go:498-504), which resets the item's failure count. The ItemExponentialFailureRateLimiter configured in SetupWithManager never engages, and the controller retries exactly every 5s, indefinitely.
  2. A full pass every time. Each retry is a complete SyncState: it re-renders all manifests, re-applies every object (see #3070 for what that costs per object), and logs the error (state/manager.go:103) plus the not-ready message. For an error that can't clear on its own, e.g. a render failure from an invalid spec combination, that's 3600/5 = 720 full passes per hour per CR.

Reproduction (unit tests against current main)

To be transparent: this comes from code review, not an observed incident. These tests use the existing fakeStateManager / FakeConditionUpdater helpers:

  • TestNVIDIADriverPermanentStateErrorRequeuesEvery5s: a state returns a render ErrInfo; five consecutive reconciles each return RequeueAfter: 5s, err == nil.
  • TestControllerRateLimiterCapIsBelowFixedRequeue: the configured limiter's delays:
    backoff with minDelayCR=100ms maxDelayCR=3s: [100ms 200ms 400ms 800ms 1.6s 3s 3s 3s]
    
controllers/requeue_backoff_test.go
package controllers

import (
	"context"
	"errors"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/util/workqueue"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client/fake"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"

	gpuv1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1"
	nvidiav1alpha1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1alpha1"
	"github.com/NVIDIA/gpu-operator/internal/state"
)

// A state that fails to render (an error that will not clear until the CR or
// cluster changes) is retried every 5s forever, with a nil error, so the
// controller's rate limiter never sees a failure and never backs off.
func TestNVIDIADriverPermanentStateErrorRequeuesEvery5s(t *testing.T) {
	scheme := runtime.NewScheme()
	require.NoError(t, nvidiav1alpha1.AddToScheme(scheme))
	require.NoError(t, gpuv1.AddToScheme(scheme))

	driver := &nvidiav1alpha1.NVIDIADriver{ObjectMeta: metav1.ObjectMeta{Name: "test-driver"}}
	c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(driver).
		WithStatusSubresource(&nvidiav1alpha1.NVIDIADriver{}).Build()

	renderErr := errors.New("failed to create k8s objects from manifests: template: invalid value")
	r := &NVIDIADriverReconciler{
		Client:                c,
		Scheme:                scheme,
		conditionUpdater:      &FakeConditionUpdater{},
		nodeSelectorValidator: &FakeNodeSelectorValidator{},
		stateManager: &fakeStateManager{results: state.Results{
			Status: state.SyncStateNotReady,
			StatesStatus: []state.Result{
				{StateName: "state-driver", Status: state.SyncStateNotReady, ErrInfo: renderErr},
			},
		}},
	}
	req := ctrl.Request{NamespacedName: types.NamespacedName{Name: driver.Name}}

	for i := 0; i < 5; i++ {
		res, err := r.Reconcile(context.Background(), req)
		require.NoError(t, err, "a permanent state error is not surfaced to controller-runtime")
		assert.Equal(t, 5*time.Second, res.RequeueAfter, "attempt %d: fixed 5s, no backoff", i+1)
	}
	// 3600s / 5s = 720 full SyncState passes per hour per NVIDIADriver.
}

// Simply returning the error instead would make retries *faster*, not slower:
// the controllers' limiter is capped at maxDelayCR (3s), below the current 5s.
func TestControllerRateLimiterCapIsBelowFixedRequeue(t *testing.T) {
	rl := workqueue.NewTypedItemExponentialFailureRateLimiter[reconcile.Request](minDelayCR, maxDelayCR)
	item := reconcile.Request{NamespacedName: types.NamespacedName{Name: "test-driver"}}

	var delays []time.Duration
	for i := 0; i < 8; i++ {
		delays = append(delays, rl.When(item))
	}
	t.Logf("backoff with minDelayCR=%v maxDelayCR=%v: %v", minDelayCR, maxDelayCR, delays)

	assert.Equal(t, 100*time.Millisecond, delays[0])
	assert.Equal(t, 3*time.Second, delays[len(delays)-1], "backoff is capped at 3s")
	assert.Less(t, delays[len(delays)-1], 5*time.Second, "steady-state retry would be faster than today's 5s")
}

Correction to my original proposal

I proposed returning the error so the rate limiter applies backoff. As-is, that would make things worse. All controllers share minDelayCR/maxDelayCR (clusterpolicy_controller.go:54-55), and the cap is 3s, so a permanently failing state would retry every 3s instead of every 5s, plus a Reconciler error log line each time. The fix has to change the limiter for these two controllers, not just the return value.

Proposed solution

  1. Waiting on pods: rely on the watch, not the 5s poll. state-driver already watches its DaemonSets (driver.go:169-181) with a label predicate but no generation predicate, so DaemonSet status changes (pods becoming ready) already enqueue the NVIDIADriver. The 5s poll is redundant there. I'd keep a slow safety-net requeue (e.g. 1 min, matching GPUCluster's Ready path). I'd confirm GPUCluster's operand states have equivalent DaemonSet watches as part of the PR.
  2. State errors: return the error, with a dedicated limiter. Give NVIDIADriver and GPUCluster their own ItemExponentialFailureRateLimiter, e.g. 5s → 5 min, instead of the shared 100ms → 3s used by ClusterPolicy/upgrade/node-labeling. A persistent failure then settles at about 12 passes/hour instead of 720. The first retries stay quick, so transient API errors still recover fast.
  3. Optionally, reconcile.TerminalError for clearly permanent errors (render/validation failures driven only by the CR spec). Those wouldn't requeue at all. The existing watches (NVIDIADriver generation changes, ClusterPolicy, GPUCluster, node labels) re-trigger when an input changes. This needs the error type preserved: driver.go currently wraps the apply and status errors with %v (e.g. "failed to create/update objects: %v"), which loses the type. Those would move to %w, plus a typed render error to classify on.

Trade-off: TerminalError is only safe when every input that could fix the error is watched. If a fix comes from something unwatched (a Secret, a ConfigMap, a registry change), a terminal error would wait for an unrelated event. That's why I'd ship step 2 first, since it's safe for every error class and gets most of the benefit, and treat step 3 as a follow-up with an explicit allow-list of permanent errors.

I'm happy to open a PR for steps 1 and 2 with these tests updated to assert the new behavior.

CloneOfAlex avatar Oct 20 '26 16:10 CloneOfAlex

Thanks for the detailed analysis and the correction regarding the existing limiter.

My concern with increasing the backoff cap is recovery latency after a user fixes the underlying problem. Both controllers watch their CR specs and owned DaemonSets, but their watch coverage differs: NVIDIADriver also watches relevant node-label changes, while GPUCluster has no direct Node watch. Node changes may trigger GPUCluster reconciliation indirectly through DaemonSet updates, but that is not guaranteed for every fix. Neither controller directly watches all other recovery inputs, such as RBAC changes.

Given those gaps, I’d prefer to retain the current retry interval unless we have measurements showing that its reconciliation cost warrants slower recovery. We can revisit backoff alongside improved watch coverage and a defined recovery-latency requirement. Closing this for now.

rahulait avatar Nov 05 '26 06:11 rahulait

Thanks @rahulait, that's a fair trade-off. Without watches on every recovery input (Node for GPUCluster, RBAC, Secrets/ConfigMaps), a longer backoff cap could delay recovery after a user fixes something, and I don't have measurements showing the 5 s retry is a real cost. Agreed on revisiting it together with better watch coverage and a defined recovery-latency target.

CloneOfAlex avatar Nov 05 '26 23:11 CloneOfAlex