← Back to Pull requests

Fix backup dequeued twice from a stale cached Queued copy #10624

Open
dieg666 opened this pull request with 147 lines diff across 4 files
View on GitHub
dieg666 dieg666 commented on Oct 05, 2026 10:43 UTC
Author

Thank you for contributing to Velero!

Please add a summary of your change

The queue controller could dequeue a backup a second time from a stale Queued copy in the cache, moving a running or finished backup back to ReadyToStart. It now skips backups the tracker reports as running and patches ReadyToStart with an optimistic lock.

Does your change fix a particular issue?

Fixes #10623

Please indicate you've done the following:

  • Accepted the DCO. Commits without the DCO will delay acceptance.

  • Created a changelog file (make new-changelog) or comment /kind changelog-not-required on this PR.

  • Updated the corresponding documentation in site/content/docs/main.
  • Diff: 147 lines (+145 / -2) across 4 files Reviewer: omlahore Review duration: 80876m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.44) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.44 · 147 lines diff across 4 files
    0.44
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.78 · 5 substantive comment(s)
    0.78
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    84%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.299
    Real PR Conversation Timeline
    19 items
    netlify[bot] netlify[bot] commented on Oct 05, 2026 10:43 UTC
    Bot

    <span aria-hidden="true">👷</span> Deploy request for velero pending review.


    Visit the deploys page to approve it

    | Name | Link |
    |:-:|------------------------|
    |<span aria-hidden="true">🔨</span> Latest commit | 339dd3aea5de5093ab3ac2431d4302b37b4d27c5 |

    Joeavaikath Joeavaikath commented on Oct 05, 2026 16:12 UTC
    Reviewer

    Thank you for your contribution to the Velero project.

    This is an interesting case where the lack of a resourceVersion check causes an unwanted regression in phase

    Both checks seem solid. I would think that similar optimistic locking for patches in other spots of the codebase may be required after some research

    codecov[bot] codecov[bot] commented on Oct 05, 2026 16:14 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 78.57143% with 3 lines in your changes missing coverage. Please review.
    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | pkg/controller/backup\_queue\_controller.go | 66.66% | 3 Missing :warning: |

    :loudspeaker: Thoughts on this report? Let us know!

    omlahore omlahore commented on Oct 06, 2026 09:50 UTC
    Reviewer

    Nice catch on the double dequeue, both new tests fail on main and pass with this. I think there's still a gap right after the first dequeue though. Contains ignores ReadyToStart, so a stale reconcile in that window hits the conflict and the rollback Delete removes the entry the first dequeue added. With concurrent-backups at 5 I got RunningCount 0 while the backup was still ReadyToStart, and if the backup controller's Add lands just before that Delete it runs InProgress with nothing in the tracker. Making the skip check ReadyToStart too made both cases go away for me, unless it was left out on purpose.

    dieg666 dieg666 commented on Oct 06, 2026 11:44 UTC
    Author

    @omlahore good catch, it wasn't on purpose. Contains ignores ReadyToStart because the deletion controller relies on that, so I left it alone and added IsTracked (ReadyToStart, InProgress or post-InProgress) for the queue controller's skip check, plus a regression test for a stale reconcile while the backup is ReadyToStart. Reproduced both of your cases on the previous commit and they pass now.

    One side effect: a ReadyToStart entry can already leak if the Backup is deleted before it starts, and with this change a new Backup with the same name would stay Queued. Happy to open an issue for it if you think it's worth tracking.

    @Joeavaikath agreed on the other patches, the New -> Queued patch has the same stale-cache shape. Could you take another look? Thanks both.

    omlahore omlahore approved these changes on Oct 07, 2026 07:16 UTC
    Approved Reviewer

    Thanks, the new ReadyToStart test fails with Contains in that check and passes with IsTracked. I think the leak's worth an issue, it's already on main since the backup controller returns on not found without touching the tracker, and with this a recreated backup with the same name would also sit in Queued. Clearing the key in that not found branch looks like it'd cover both, but that's probably its own PR.

    dieg666 dieg666 commented on Oct 13, 2026 08:27 UTC
    Author

    @sseago could you take a look when you have a moment? You wrote most of the queue controller, and the backup CR details are now in #10623

    kaovilai kaovilai commented on Oct 14, 2026 00:44 UTC
    Contributor

    Hi @dieg666, thanks for the contribution and for your patience!

    We're currently in the middle of the Velero 1.19.0 release process, so we haven't been able to give this PR the attention it deserves. We'll have some time to circle back to it after the release-1.19 branch is cut.

    For the current timeline, see the 1.19 Roadmap — subject to change.

    [!Note]

    Responses generated with Claude (model: GLM 5.3)

    chlins chlins commented on Oct 19, 2026 08:01 UTC
    Contributor

    The conflict is expected now that the patch uses an optimistic lock, so I think it shouldn't go through the error path (error log plus error backoff). Can you handle it like this?

    r.backupTracker.AddReadyToStart(backup.Namespace, backup.Name)
    if err := r.Client.Patch(ctx, backup, client.MergeFromWithOptions(original, client.MergeFromWithOptimisticLock{})); err != nil {
    	r.backupTracker.Delete(backup.Namespace, backup.Name)
    	if apierrors.IsConflict(err) {
    		return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
    	}
    	return ctrl.Result{}, errors.Wrapf(err, "error updating Backup status to %s", backup.Status.Phase)
    }
    

    sseago sseago commented on code on Oct 22, 2026 17:39 UTC
    Code Review
    pkg/controller/backup_queue_controller.go:1
    @@ -299,7 +303,7 @@ func (r *backupQueueReconciler) Reconcile(ctx context.Context, req ctrl.Request)
     		// (Add then deferred Delete) before this call, leaking a
     		// tracker entry that nothing would ever clean up.
     		r.backupTracker.AddReadyToStart(backup.Namespace, backup.Name)
    -		if err := kube.PatchResource(original, backup, r.Client); err != nil {
    +		if err := r.Client.Patch(ctx, backup, client.MergeFromWithOptions(original, client.MergeFromWithOptimisticLock{})); err != nil {
     			r.backupTracker.Delete(backup.Namespace, backup.Name)

    As suggested by @chlins we should detect conflict and requeue. However, I'd suggest a shorter duration. I don't think we need to wait more than a second: ctrl.Result{RequeueAfter: time.Second}

    sseago sseago requested changes on Oct 22, 2026 17:46 UTC
    Changes Requested Reviewer

    In addition to the requeue change requested, we need one more change. Imagine a scenario where there are two queued backups, backup1 and backup2. A prior backup completes, causing the reconciler to requeue all queued backups in order. We're now attempting to dequeue backup1 but we failed on conflict, so we requeue this request to try again. Moving on to backup2, velero skips it because there's an earlier runnable backup that hasn't been dequeued yet. Now we reconcile backup1 again and it starts. However, assuming that there were actually two free workers, backup2 should start now too, but we already passed on it, and it's not been requeued by the reconciler. We need to add another condition to the "requeue all queued backups on backup phase change" to cover Queued->ReadyToStart so that the dequeuing of backup1 forces re-consideration of backup2:

    diff --git a/pkg/controller/backup_queue_controller.go b/pkg/controller/backup_queue_controller.go                                                                                                                  
    --- a/pkg/controller/backup_queue_controller.go                                                                                                                                                                     
    +++ b/pkg/controller/backup_queue_controller.go                                                                                                                                                                     
    @@ -108,7 +109,9 @@ func (r *backupQueueReconciler) SetupWithManager(mgr ctrl.Manager) error {                                                                                                                      
     oldBackup.Status.Phase == velerov1api.BackupPhaseInProgress &&                                                                                                                           
                            newBackup.Status.Phase != velerov1api.BackupPhaseInProgress ||                                                                                                                              
                            oldBackup.Status.Phase != velerov1api.BackupPhaseQueued &&                                                                                                                                  
                                newBackup.Status.Phase == velerov1api.BackupPhaseQueued &&                                                                                                                              
    -                           r.backupTracker.RunningCount() < r.concurrentBackups                                                                                                                                    
    +                           r.backupTracker.RunningCount() < r.concurrentBackups ||                                                                                                                                 
    +                       oldBackup.Status.Phase == velerov1api.BackupPhaseQueued &&                                                                                                                                  
    +                           newBackup.Status.Phase == velerov1api.BackupPhaseReadyToStart                                                                                                                           
                    },                                                                                                                                                                                                  
                    CreateFunc: func(event.CreateEvent) bool {                                                                                                                                                          
                        return false                                                                                                                                                                                    
    

    dieg666 dieg666 commented on Oct 27, 2026 13:37 UTC
    Author

    Thanks @chlins, done. A conflict on the ReadyToStart patch still rolls back the tracker entry, but now requeues without going through the error path. I went with 1s instead of 5s as @sseago suggested.

    dieg666 dieg666 commented on code on Oct 27, 2026 13:38 UTC
    Code Review
    pkg/controller/backup_queue_controller.go:1
    @@ -299,7 +303,7 @@ func (r *backupQueueReconciler) Reconcile(ctx context.Context, req ctrl.Request)
     		// (Add then deferred Delete) before this call, leaking a
     		// tracker entry that nothing would ever clean up.
     		r.backupTracker.AddReadyToStart(backup.Namespace, backup.Name)
    -		if err := kube.PatchResource(original, backup, r.Client); err != nil {
    +		if err := r.Client.Patch(ctx, backup, client.MergeFromWithOptions(original, client.MergeFromWithOptimisticLock{})); err != nil {
     			r.backupTracker.Delete(backup.Namespace, backup.Name)

    Done, it now returns ctrl.Result{RequeueAfter: time.Second}, nil on conflict. The stale Queued test hits a real optimistic lock conflict and asserts that result.

    dieg666 dieg666 commented on Oct 27, 2026 13:43 UTC
    Author

    Thanks @sseago, added the Queued -> ReadyToStart condition as you suggested. I didn't add a test for it since the watch predicates here aren't unit tested today, happy to pull it into a function with a table test if you'd like.

    sseago sseago commented on Oct 27, 2026 18:11 UTC
    Contributor

    Thanks @sseago, added the Queued -> ReadyToStart condition as you suggested. I didn't add a test for it since the watch predicates here aren't unit tested today, happy to pull it into a function with a table test if you'd like.

    I'll give it another full review after we have the 1.19.0 rc1 out -- until then we're not merging any PRs to main except for release blockers.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 27, 2026 18:14 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟢 Approval recommended

    The targeted guards and optimistic locking address the reported race, with regression coverage and no unresolved blocking findings.

    No open issues 🎉

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Fixes #10623 by preventing stale cached Queued backups from being dequeued again and overwriting a running or completed backup’s phase.

    Changes:

  • Adds a tracker check covering backups in ReadyToStart, InProgress, and post-progress states.

  • Uses optimistic locking for the dequeue patch, retries conflicts, and updates queue event handling.

  • Adds regression tests for stale queued copies and a changelog entry.
  • | File | Description |
    | ---- | ----------- |
    | pkg/​controller/​backup_tracker.go | Adds IsTracked to check all tracked backup states. |
    | pkg/​controller/​backup_queue_controller.go | Guards against duplicate dequeueing and handles optimistic-lock conflicts. |
    | pkg/​controller/​backup_queue_controller_test.go | Covers stale queued copies of ready, running, and completed backups. |
    | changelogs/​unreleased/​10624-dieg666 | Records the duplicate-dequeue fix. |
    </details>

    <sub>Review effort: Balanced</sub>

    kaovilai kaovilai commented on code on Oct 27, 2026 18:17 UTC
    Code Review
    pkg/controller/backup_queue_controller.go:1
    @@ -299,8 +306,11 @@ func (r *backupQueueReconciler) Reconcile(ctx context.Context, req ctrl.Request)
     		// (Add then deferred Delete) before this call, leaking a
     		// tracker entry that nothing would ever clean up.
     		r.backupTracker.AddReadyToStart(backup.Namespace, backup.Name)
    -		if err := kube.PatchResource(original, backup, r.Client); err != nil {
    +		if err := r.Client.Patch(ctx, backup, client.MergeFromWithOptions(original, client.MergeFromWithOptimisticLock{})); err != nil {
     			r.backupTracker.Delete(backup.Namespace, backup.Name)
    +			if apierrors.IsConflict(err) {
    +				return ctrl.Result{RequeueAfter: time.Second}, nil

    Using RequeueAfter: time.Second forces a fixed-rate requeue, which bypasses controller-runtime’s normal error-based rate limiter (exponential backoff). If this path is a “not-ready-yet / transient dependency” state, returning an error (or using ctrl.Result{}, err) lets the workqueue apply default backoff and reduces hot-loop pressure.

    dieg666 dieg666 commented on code on Nov 03, 2026 09:12 UTC
    Code Review
    pkg/controller/backup_queue_controller.go:1
    @@ -299,8 +306,11 @@ func (r *backupQueueReconciler) Reconcile(ctx context.Context, req ctrl.Request)
     		// (Add then deferred Delete) before this call, leaking a
     		// tracker entry that nothing would ever clean up.
     		r.backupTracker.AddReadyToStart(backup.Namespace, backup.Name)
    -		if err := kube.PatchResource(original, backup, r.Client); err != nil {
    +		if err := r.Client.Patch(ctx, backup, client.MergeFromWithOptions(original, client.MergeFromWithOptimisticLock{})); err != nil {
     			r.backupTracker.Delete(backup.Namespace, backup.Name)
    +			if apierrors.IsConflict(err) {
    +				return ctrl.Result{RequeueAfter: time.Second}, nil

    This is on purpose: chlins asked to keep the conflict off the error path and sseago suggested the 1s requeue. A conflict here only means our cached copy is behind, so a short requeue lets the cache catch up and the next reconcile handles the backup normally. Returning the error would retry sooner on the first attempts (the limiter starts at 5ms) and log a "Reconciler error" each time, so a fixed 1s seemed the better fit.

    Reviewers
    Assignees
    dieg666 dieg666
    Labels
    risk: low confidence: 84.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 44.3% (MEDIUM) · Higher = larger blast radius
    44.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84.3% · Lower = rushed or shallow review
    84.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.0% · Safe to merge
    7.0%