Fix backup dequeued twice from a stale cached Queued copy #10624
<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 |
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 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!
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.
@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.
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.
@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
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)
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)
}
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}
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
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.
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.
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.
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.
<!-- 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:
ReadyToStart, InProgress, and post-progress states.| 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>
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.
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.
omlahore
dieg666
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
Queuedcopy in the cache, moving a running or finished backup back toReadyToStart. It now skips backups the tracker reports as running and patchesReadyToStartwith an optimistic lock.Does your change fix a particular issue?
Fixes #10623
Please indicate you've done the following:
make new-changelog) or comment/kind changelog-not-requiredon this PR.site/content/docs/main.