From 9cc9a3b48d96fcac4137096dff1f8b0675acff8d Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Wed, 4 Nov 2026 15:53:45 +0300 Subject: [PATCH 01/26] fix(postgres): stop backup jobs from fighting over the WAL archive destination The ObjectStore a Postgres Cluster archives its WAL to is shared by every backup of the app, yet each running BackupJob server-side applied its own strategy's destination onto it every five seconds with forced ownership. Two BackupJobs of one app with different BackupClasses flipped the destination back and forth until the healthy backup failed too, and a webhook or apiserver blip during that apply failed the BackupJob at once. A BackupJob now writes the destination only before its cnpg.io/Backup exists, and waits, with a WaitingForOtherBackup condition, while another running BackupJob of the app has a Backup in flight. The check reads the informer cache, so jobs released together, or one created while another's Backup is not yet cached, can still both proceed; an atomic per-application claim is a separate change. Write errors that cannot succeed on retry (invalid, bad request, forbidden) still fail the job at once. Any other is retried for the backup deadline counted from its first failure since the job last left the queue, recorded in a DestinationApplied condition. Once the Backup exists the Cluster is only read, and a failed read is returned for a controller retry instead of failing the running backup. The plugin rollout deadline counts from the attach rather than from the job's start, so queueing before the attach no longer shortens it. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../backupcontroller/backupjob_controller.go | 8 - .../backupjob_restore_lock.go | 12 +- .../cnpgstrategy_controller.go | 136 +++++- .../cnpgstrategy_controller_test.go | 438 +++++++++++++++++- 4 files changed, 563 insertions(+), 31 deletions(-) diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index b86278649..bbba19fad 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -315,14 +315,6 @@ func (r *BackupJobReconciler) handleProjectionError(ctx context.Context, j *back } // markBackupJobFailed records a terminal Failed phase on the BackupJob. -// -// Coupling note: a failure that fires before reconcileCNPG's StartedAt block -// has set backupJob.Status.StartedAt leaves StartedAt nil. The CNPG path's -// cnpgDefaultBackupDeadline check only fires once StartedAt is set, so an -// early-failure retry that reaches the StartedAt block restarts the deadline -// budget from the retry's StartedAt - intentional, since retries are -// user-driven and a fresh budget is what users expect after correcting the -// cause of the previous failure. func (r *BackupJobReconciler) markBackupJobFailed(ctx context.Context, backupJob *backupsv1alpha1.BackupJob, message string) (ctrl.Result, error) { logger := getLogger(ctx) now := metav1.Now() diff --git a/internal/backupcontroller/backupjob_restore_lock.go b/internal/backupcontroller/backupjob_restore_lock.go index 06f165285..c40d59aef 100644 --- a/internal/backupcontroller/backupjob_restore_lock.go +++ b/internal/backupcontroller/backupjob_restore_lock.go @@ -32,12 +32,12 @@ const ConditionReasonRestoreInProgress = "RestoreInProgress" // // A backup must not start against an application a restore is rewriting. It // would capture a half-restored state at best, and on the CNPG path it does -// worse: every BackupJob reconcile re-applies the Cluster's barman plugin, and -// one landing between the restore re-rendering the Cluster with its new -// serverName and the plugin being attached can put the restored cluster back -// on the source's WAL prefix, where its recovery fails with "Expected empty -// archive". Plan-created runs are the ones that hit this, since nothing else -// looks at restores before creating a BackupJob. +// worse: a BackupJob applies the Cluster's barman plugin before it creates +// its Backup, and an apply landing between the restore re-rendering the +// Cluster with its new serverName and the plugin being attached can put the +// restored cluster back on the source's WAL prefix, where its recovery fails +// with "Expected empty archive". Plan-created runs are the ones that hit +// this, since nothing else looks at restores before creating a BackupJob. func activeRestoreTargeting(ctx context.Context, c client.Client, namespace string, app corev1.TypedLocalObjectReference) (string, error) { app = NormalizeApplicationRef(app) list := &backupsv1alpha1.RestoreJobList{} diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 19f255c6c..a2a429b4f 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -176,7 +176,9 @@ const ( cnpgRecoveryMaxInspectPods = 5 // Cap on the wall-clock time a BackupJob waits for the barman-cloud - // plugin rollout before the cnpg.io/Backup exists. A Backup that exists + // plugin rollout, counted from the attach, or retries writing the WAL + // archive destination, counted from the first failure since the job last + // left the queue, before the cnpg.io/Backup exists. A Backup that exists // is not capped: CloudNativePG keeps a healthy one pending while another // backup of the same Cluster runs, or while it restarts one on another // instance, so no fixed deadline tells those apart from a stuck one. @@ -195,6 +197,12 @@ const ( // instance pods must postdate (see cnpgPluginRolloutPending). backupCondPluginRolledOut = "PluginRolledOut" + // Condition Type recorded while writing the WAL archive destination keeps + // failing. Its LastTransitionTime marks the first failure, so the retry + // budget is not spent by time the job waited for another backup of the + // app before it tried. + backupCondDestinationApplied = "DestinationApplied" + cnpgPodRoleLabel = "cnpg.io/podRole" cnpgPodRoleInstance = "instance" ) @@ -321,7 +329,23 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp rollout := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) awaitingRollout := existingBackup == nil && rollout != nil && rollout.Status == metav1.ConditionFalse - attachment, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName, existingBackup != nil || awaitingRollout) + // The ObjectStore is the Cluster's WAL archive destination, shared by + // every backup of the app, so it is written only before this job's + // Backup exists and only while no other job's Backup is in flight. + writeDestination := existingBackup == nil + if writeDestination { + holder, err := r.otherCNPGBackupInFlight(ctx, j, clusterName) + if err != nil { + return ctrl.Result{}, err + } + if holder != "" { + apimeta.RemoveStatusCondition(&j.Status.Conditions, backupCondDestinationApplied) + return r.waitCNPGBackupJob(ctx, j, "WaitingForOtherBackup", fmt.Sprintf( + "waiting for BackupJob %s of the same application to finish its backup, which writes to the shared WAL archive destination", holder)) + } + } + + attachment, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName, existingBackup != nil || awaitingRollout, writeDestination) if err != nil { if apierrors.IsNotFound(err) { // HelmRelease has not yet rendered the Cluster (fresh app, or @@ -340,7 +364,33 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil } - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to attach barman-cloud plugin to Cluster: %v", err)) + if !writeDestination { + // Only the live Cluster was read for a Backup already running; + // a failed read says nothing about that Backup. + return ctrl.Result{}, fmt.Errorf("read cnpg.io/Cluster %s/%s: %w", j.Namespace, clusterName, err) + } + message := fmt.Sprintf("failed to attach barman-cloud plugin to Cluster: %v", err) + if apierrors.IsInvalid(err) || apierrors.IsBadRequest(err) || apierrors.IsForbidden(err) { + return r.markBackupJobFailed(ctx, j, message) + } + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: backupCondDestinationApplied, + Status: metav1.ConditionFalse, + Reason: "ClusterPluginApplyRetrying", + Message: message, + }) + failingSince := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationApplied).LastTransitionTime + if cnpgBackupDeadlineExceeded(&failingSince) { + return r.markBackupJobFailed(ctx, j, message) + } + return r.waitCNPGBackupJob(ctx, j, "ClusterPluginApplyRetrying", message) + } + if writeDestination { + apimeta.RemoveStatusCondition(&j.Status.Conditions, backupCondDestinationApplied) + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready != nil && + (ready.Reason == "WaitingForOtherBackup" || ready.Reason == "ClusterPluginApplyRetrying") { + apimeta.RemoveStatusCondition(&j.Status.Conditions, "Ready") + } } if attachment.serverName != serverName { logger.Info("preserving the live Cluster's barman serverName over the strategy template's", @@ -377,7 +427,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp return ctrl.Result{}, err } if pending != "" { - if cnpgBackupDeadlineExceeded(j.Status.StartedAt) { + if cnpgBackupDeadlineExceeded(&rollout.LastTransitionTime) { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( "barman-cloud plugin rollout did not finish within %s: %s", cnpgDefaultBackupDeadline, pending)) } @@ -486,16 +536,16 @@ func cnpgBackupFailedMessage(b *cnpgtypes.Backup, errText string) string { return message } -// cnpgBackupDeadlineExceeded reports whether enough wall-clock time has -// elapsed since the BackupJob started that we should stop waiting for the -// barman-cloud plugin rollout and fail the run. Returns false when -// StartedAt is nil so the very first reconcile (which sets StartedAt) does -// not trip the gate. -func cnpgBackupDeadlineExceeded(startedAt *metav1.Time) bool { - if startedAt == nil { +// cnpgBackupDeadlineExceeded reports whether more than the backup deadline +// has passed since the BackupJob began the step it is waiting on: the plugin +// rollout, counted from the attach, or retrying the destination write, +// counted from the first failure since the job last left the queue behind +// another backup. Returns false for a nil time. +func cnpgBackupDeadlineExceeded(since *metav1.Time) bool { + if since == nil { return false } - return time.Since(startedAt.Time) > cnpgDefaultBackupDeadline + return time.Since(since.Time) > cnpgDefaultBackupDeadline } // cnpgPurgeNeeded decides whether the controller should delete the live @@ -601,7 +651,10 @@ var cnpgClusterGVR = schema.GroupVersionResource{ // With attach unset, a Cluster that has no barman-cloud plugin yet is left // untouched and only reported missing, so the caller can record that it is // about to roll the Cluster before it does. -func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, namespace, clusterName string, t *strategyv1alpha1.CNPGTemplate, serverName string, attach bool) (cnpgPluginAttachment, error) { +// +// With write unset nothing is written: only what the live Cluster carries is +// reported. +func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, namespace, clusterName string, t *strategyv1alpha1.CNPGTemplate, serverName string, attach, write bool) (cnpgPluginAttachment, error) { // Live read: the cached Cluster can predate a restore re-render, and the // serverName, the flavor and the UID below must come from the current // object. @@ -626,6 +679,9 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name return attachment, nil } } + if !write { + return attachment, nil + } serverName = attachment.serverName // The ObjectStore is named after the Cluster (distinct kind, same @@ -801,6 +857,60 @@ func (r *BackupJobReconciler) findCNPGBackupForJob(ctx context.Context, j *backu return &list.Items[0], nil } +// otherCNPGBackupInFlight returns the name of another BackupJob that is still +// running and whose cnpg.io/Backup of clusterName has not finished, or "" when +// there is none. A Backup left behind by a finished or deleted job does not +// hold the queue. +func (r *BackupJobReconciler) otherCNPGBackupInFlight(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName string) (string, error) { + list := &cnpgtypes.BackupList{} + if err := r.List(ctx, list, client.InNamespace(j.Namespace)); err != nil { + return "", err + } + var holders []string + for i := range list.Items { + b := &list.Items[i] + owner := b.Labels[backupsv1alpha1.OwningJobNameLabel] + if b.Spec.Cluster.Name != clusterName || owner == "" || owner == j.Name { + continue + } + if b.Status.Phase == cnpgBackupPhaseComplete || b.Status.Phase == cnpgBackupPhaseFailed { + continue + } + ownerJob := &backupsv1alpha1.BackupJob{} + if err := r.Get(ctx, client.ObjectKey{Namespace: j.Namespace, Name: owner}, ownerJob); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return "", err + } + if ownerJob.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || ownerJob.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + continue + } + holders = append(holders, owner) + } + if len(holders) == 0 { + return "", nil + } + sort.Strings(holders) + return holders[0], nil +} + +// waitCNPGBackupJob requeues the BackupJob and records why it waits in its +// Ready condition, writing the status only when the conditions changed. +func (r *BackupJobReconciler) waitCNPGBackupJob(ctx context.Context, j *backupsv1alpha1.BackupJob, reason, message string) (ctrl.Result, error) { + if apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: reason, + Message: message, + }) { + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil +} + // createCNPGBackupArtifact materialises a Cozystack Backup resource carrying // the metadata callers need to drive a future restore. The source app's // spec.databases / spec.users are snapshotted into Status.UnderlyingResources diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 551209fac..c94630470 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3,6 +3,7 @@ package backupcontroller import ( "context" + "errors" "fmt" "strings" "testing" @@ -19,6 +20,7 @@ import ( "k8s.io/client-go/dynamic" dynamicfake "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes/scheme" + clienttesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -1099,7 +1101,7 @@ func TestApplyClusterPluginBackup_NotFoundOnMissingCluster(t *testing.T) { }, } - _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-missing", tmpl, "postgres-missing", true) + _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-missing", tmpl, "postgres-missing", true, true) if err == nil { t.Fatalf("expected NotFound error, got nil") } @@ -1739,7 +1741,7 @@ func TestApplyClusterPluginBackup_ReadsTheLiveClusterNotTheCache(t *testing.T) { BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"}, } - got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true) + got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true, true) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -1949,7 +1951,7 @@ func TestApplyClusterPluginBackup_PreservesLiveServerName(t *testing.T) { BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"}, } - got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true) + got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true, true) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -2118,7 +2120,7 @@ func TestApplyClusterPluginBackup_PatchesExistingCluster(t *testing.T) { }, } - if _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "tenant-app", true); err != nil { + if _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "tenant-app", true, true); err != nil { t.Fatalf("unexpected error: %v", err) } @@ -2480,6 +2482,434 @@ func TestReconcileCNPG_BackupPhaseOutcome(t *testing.T) { } } +// newAttachedObjectStoreFixture is a Cluster that already runs the barman-cloud +// plugin, whose ObjectStore currently points at liveDestination; the strategy +// of the fixture's BackupJob points at s3://bucket/. +func newAttachedObjectStoreFixture(t *testing.T, startedAt time.Time, liveDestination string) *cnpgRolloutFixture { + t.Helper() + f := newCNPGRolloutFixture(t, newRolloutBackupJob(startedAt), + newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)), + newRolloutInstancePod(time.Now().Add(-time.Hour))) + store := &cnpgtypes.ObjectStore{ + ObjectMeta: metav1.ObjectMeta{Namespace: rolloutNS, Name: rolloutCluster}, + Spec: cnpgtypes.ObjectStoreSpec{Configuration: cnpgtypes.BarmanObjectStoreConfiguration{DestinationPath: liveDestination}}, + } + if err := f.c.Create(context.Background(), store); err != nil { + t.Fatalf("seed ObjectStore: %v", err) + } + return f +} + +func (f *cnpgRolloutFixture) liveDestination() string { + f.t.Helper() + store := &cnpgtypes.ObjectStore{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: rolloutCluster}, store); err != nil { + f.t.Fatalf("get ObjectStore: %v", err) + } + return store.Spec.Configuration.DestinationPath +} + +// seedCNPGBackup creates a cnpg.io/Backup of cluster owned by the BackupJob +// named owner; an empty owner leaves it unlabelled, as a Backup created by +// hand. +func (f *cnpgRolloutFixture) seedCNPGBackup(name, owner, cluster, phase string) { + f.t.Helper() + var labels map[string]string + if owner != "" { + labels = map[string]string{ + backupsv1alpha1.OwningJobNameLabel: owner, + backupsv1alpha1.OwningJobNamespaceLabel: rolloutNS, + } + } + b := &cnpgtypes.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: rolloutNS, Name: name, Labels: labels}, + Spec: cnpgtypes.BackupSpec{Cluster: cnpgtypes.ClusterReference{Name: cluster}}, + Status: cnpgtypes.BackupStatus{Phase: phase}, + } + if err := f.c.Create(context.Background(), b); err != nil { + f.t.Fatalf("seed cnpg.io/Backup %s: %v", name, err) + } +} + +func (f *cnpgRolloutFixture) setJobCondition(cond metav1.Condition) { + f.t.Helper() + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + f.t.Fatalf("get BackupJob: %v", err) + } + j.Status.Conditions = append(j.Status.Conditions, cond) + if err := f.c.Status().Update(context.Background(), j); err != nil { + f.t.Fatalf("seed BackupJob condition: %v", err) + } +} + +func (f *cnpgRolloutFixture) seedOtherBackupJob(name string, phase backupsv1alpha1.BackupJobPhase) { + f.t.Helper() + other := newRolloutBackupJob(time.Now().Add(-time.Hour)) + other.Name = name + other.Status.Phase = phase + if err := f.c.Create(context.Background(), other); err != nil { + f.t.Fatalf("seed BackupJob %s: %v", name, err) + } +} + +// The ObjectStore is the Cluster's WAL archive destination, so a BackupJob +// whose cnpg.io/Backup is already running must not keep re-applying it: a +// second BackupJob of the same app with another destination would otherwise +// flip it back and forth under both backups. +func TestReconcileCNPG_RunningBackupDoesNotReapplyObjectStore(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") + + j, _ := f.pass() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob failed: %s", j.Status.Message) + } + if got := f.liveDestination(); got != "s3://other/" { + t.Fatalf("a pass over a running backup re-applied the ObjectStore: destination %q", got) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready != nil && ready.Reason == "WaitingForOtherBackup" { + t.Fatalf("a running backup waits on itself: %+v", ready) + } +} + +func TestReconcileCNPG_WaitsForAnotherRunningBackupOfTheApp(t *testing.T) { + cases := []struct { + name string + otherJob backupsv1alpha1.BackupJobPhase + seedJob bool + otherBackup string + owner string + cluster string + wantWait bool + }{ + {name: "another running job with a running Backup holds it", seedJob: true, otherJob: backupsv1alpha1.BackupJobPhaseRunning, otherBackup: "running", wantWait: true}, + {name: "another running job with a pending Backup holds it", seedJob: true, otherJob: backupsv1alpha1.BackupJobPhaseRunning, otherBackup: "pending", wantWait: true}, + {name: "a completed Backup of another job does not", seedJob: true, otherJob: backupsv1alpha1.BackupJobPhaseRunning, otherBackup: cnpgBackupPhaseComplete}, + {name: "a failed Backup of another job does not", seedJob: true, otherJob: backupsv1alpha1.BackupJobPhaseRunning, otherBackup: cnpgBackupPhaseFailed}, + {name: "a Backup of a failed job does not", seedJob: true, otherJob: backupsv1alpha1.BackupJobPhaseFailed, otherBackup: "pending"}, + {name: "a Backup of a succeeded job does not", seedJob: true, otherJob: backupsv1alpha1.BackupJobPhaseSucceeded, otherBackup: "pending"}, + {name: "a Backup whose job is gone does not", otherBackup: "pending"}, + {name: "a Backup of another Cluster does not", seedJob: true, otherJob: backupsv1alpha1.BackupJobPhaseRunning, otherBackup: "running", cluster: "postgres-other"}, + {name: "a Backup created by hand does not", otherBackup: "running", owner: "-"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + if tc.seedJob { + f.seedOtherBackupJob("bj-other", tc.otherJob) + } + owner, cluster := "bj-other", rolloutCluster + if tc.owner == "-" { + owner = "" + } + if tc.cluster != "" { + cluster = tc.cluster + } + f.seedCNPGBackup("bj-other-cnpg", owner, cluster, tc.otherBackup) + // client-go refuses a Get with an empty name before it reaches + // the apiserver; the fake client answers NotFound instead. + statusWrites := 0 + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if key.Name == "" { + return errors.New("resource name may not be empty") + } + return cl.Get(ctx, key, obj, opts...) + }, + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + statusWrites++ + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }) + + j, backups := f.pass() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob failed: %s", j.Status.Message) + } + ours := 0 + for _, b := range backups { + if b.Labels[backupsv1alpha1.OwningJobNameLabel] == "bj" { + ours++ + } + } + ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready") + if tc.wantWait { + if got := f.liveDestination(); got != "s3://other/" { + t.Errorf("the waiting job applied its destination over a running backup: %q", got) + } + if ours != 0 { + t.Errorf("the waiting job created %d cnpg.io/Backup(s)", ours) + } + if ready == nil || ready.Status != metav1.ConditionFalse || ready.Reason != "WaitingForOtherBackup" || !strings.Contains(ready.Message, "bj-other") { + t.Errorf("Ready = %+v, want False/WaitingForOtherBackup naming bj-other", ready) + } + statusWrites = 0 + f.pass() + if statusWrites != 0 { + t.Errorf("a second pass with the same holder wrote the BackupJob status %d time(s)", statusWrites) + } + + held := &cnpgtypes.Backup{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj-other-cnpg"}, held); err != nil { + t.Fatalf("get holder Backup: %v", err) + } + held.Status.Phase = cnpgBackupPhaseComplete + if err := f.c.Update(context.Background(), held); err != nil { + t.Fatalf("complete holder Backup: %v", err) + } + j, _ = f.pass() + if got := f.liveDestination(); got != "s3://bucket/" { + t.Errorf("once the holder finished, destination = %q, want the job's own s3://bucket/", got) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready != nil && ready.Reason == "WaitingForOtherBackup" { + t.Errorf("Ready still names the finished holder: %+v", ready) + } + return + } + if got := f.liveDestination(); got != "s3://bucket/" { + t.Errorf("destination = %q, want the job's own s3://bucket/", got) + } + if ours != 1 { + t.Errorf("got %d cnpg.io/Backups for the job, want 1", ours) + } + }) + } +} + +func TestReconcileCNPG_ObjectStoreApplyErrors(t *testing.T) { + expired := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)) + webhookDown := apierrors.NewInternalError(errors.New(`failed calling webhook "mcluster.cnpg.io": connect: connection refused`)) + invalid := apierrors.NewInvalid(schema.GroupKind{Group: cnpgtypes.BarmanGroupVersion.Group, Kind: "ObjectStore"}, rolloutCluster, nil) + cases := []struct { + name string + err error + startedAt time.Time + // failingSince seeds an earlier failure of the same write. + failingSince time.Time + wantPhase backupsv1alpha1.BackupJobPhase + }{ + {name: "a transient error is retried", err: webhookDown, startedAt: time.Now()}, + {name: "a transient error failing since past the deadline fails", err: webhookDown, startedAt: expired, failingSince: expired, wantPhase: backupsv1alpha1.BackupJobPhaseFailed}, + {name: "a transient error after a long wait is retried", err: webhookDown, startedAt: expired}, + {name: "an invalid object fails at once", err: invalid, startedAt: time.Now(), wantPhase: backupsv1alpha1.BackupJobPhaseFailed}, + {name: "a bad request fails at once", err: apierrors.NewBadRequest("malformed"), startedAt: time.Now(), wantPhase: backupsv1alpha1.BackupJobPhaseFailed}, + {name: "a forbidden write fails at once", err: apierrors.NewForbidden(schema.GroupResource{Resource: "objectstores"}, rolloutCluster, errors.New("denied")), startedAt: time.Now(), wantPhase: backupsv1alpha1.BackupJobPhaseFailed}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, tc.startedAt, "s3://other/") + if !tc.failingSince.IsZero() { + f.setJobCondition(metav1.Condition{ + Type: backupCondDestinationApplied, Status: metav1.ConditionFalse, Reason: "ClusterPluginApplyRetrying", + Message: "earlier failure", LastTransitionTime: metav1.NewTime(tc.failingSince), + }) + } + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgtypes.ObjectStore); ok { + return tc.err + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + + j, backups := f.pass() + if j.Status.Phase != tc.wantPhase { + t.Fatalf("BackupJob phase = %q (%s), want %q", j.Status.Phase, j.Status.Message, tc.wantPhase) + } + if len(backups) != 0 { + t.Errorf("a cnpg.io/Backup was created although the ObjectStore was not applied: %+v", backups) + } + if tc.wantPhase == "" { + ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready") + if ready == nil || ready.Reason != "ClusterPluginApplyRetrying" || !strings.Contains(ready.Message, "connection refused") { + t.Errorf("Ready = %+v, want ClusterPluginApplyRetrying carrying the error", ready) + } + } + }) + } +} + +// A write that recovers clears the retry state, so a later failure gets a +// fresh budget and Ready no longer reports the retry. +func TestReconcileCNPG_ObjectStoreApplyRecovers(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + failing := true + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgtypes.ObjectStore); ok && failing { + return apierrors.NewInternalError(errors.New("webhook down")) + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + j, _ := f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationApplied); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s = %+v after a failed write, want False", backupCondDestinationApplied, cond) + } + + failing = false + j, backups := f.pass() + if len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups after the write recovered, want 1", len(backups)) + } + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationApplied); cond != nil { + t.Errorf("%s = %+v left over after the write recovered", backupCondDestinationApplied, cond) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready != nil && ready.Reason == "ClusterPluginApplyRetrying" { + t.Errorf("Ready still reports the retry: %+v", ready) + } +} + +// An error reading the holder's BackupJob is not taken as "no holder". +func TestReconcileCNPG_HolderLookupErrorIsReturned(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.seedCNPGBackup("bj-other-cnpg", "bj-other", rolloutCluster, "running") + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if key.Name == "bj-other" { + return apierrors.NewServiceUnavailable("cache not synced") + } + return cl.Get(ctx, key, obj, opts...) + }, + }) + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(context.Background(), j, f.resolved); err == nil { + t.Fatalf("reconcileCNPG swallowed the holder lookup error") + } + if got := f.liveDestination(); got != "s3://other/" { + t.Errorf("destination written although the holder could not be read: %q", got) + } +} + +// The rollout deadline counts from when the plugin was attached, not from +// the job's start, which may lie behind a long wait for another backup. +func TestReconcileCNPG_PluginRolloutDeadlineCountsFromAttach(t *testing.T) { + expired := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)) + f := newCNPGRolloutFixture(t, newRolloutBackupJob(expired), + newRolloutCluster(cnpgClusterHealthyPhase), newRolloutInstancePod(time.Now().Add(-time.Hour))) + + f.pass() // latch + j, _ := f.pass() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("a rollout that just began failed on the job's old start: %s", j.Status.Message) + } + if cond := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); cond == nil || cond.Reason != "WaitingForPluginRollout" { + t.Fatalf("Ready = %+v, want WaitingForPluginRollout", cond) + } + + rollout := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) + rollout.LastTransitionTime = metav1.NewTime(expired) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("age the rollout: %v", err) + } + j, _ = f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(j.Status.Message, "rollout did not finish") { + t.Fatalf("phase = %q (%s), want Failed on a rollout older than the deadline", j.Status.Phase, j.Status.Message) + } +} + +// Waiting for another backup resets the retry budget of the destination +// write, so the queue does not spend it. +func TestReconcileCNPG_QueueResetsDestinationRetryBudget(t *testing.T) { + expired := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)) + f := newAttachedObjectStoreFixture(t, expired, "s3://other/") + f.setJobCondition(metav1.Condition{ + Type: backupCondDestinationApplied, Status: metav1.ConditionFalse, Reason: "ClusterPluginApplyRetrying", + Message: "earlier failure", LastTransitionTime: metav1.NewTime(expired), + }) + f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) + f.seedCNPGBackup("bj-other-cnpg", "bj-other", rolloutCluster, "running") + + j, _ := f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationApplied); cond != nil { + t.Fatalf("%s = %+v kept while waiting for another backup", backupCondDestinationApplied, cond) + } + + held := &cnpgtypes.Backup{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj-other-cnpg"}, held); err != nil { + t.Fatalf("get holder Backup: %v", err) + } + held.Status.Phase = cnpgBackupPhaseComplete + if err := f.c.Update(context.Background(), held); err != nil { + t.Fatalf("complete holder Backup: %v", err) + } + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgtypes.ObjectStore); ok { + return apierrors.NewInternalError(errors.New("webhook down")) + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + j, _ = f.pass() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the first failure after the queue failed the job: %s", j.Status.Message) + } +} + +func TestOtherCNPGBackupInFlight_IgnoresTheJobsOwnBackup(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + holder, err := f.r.otherCNPGBackupInFlight(context.Background(), j, rolloutCluster) + if err != nil { + t.Fatalf("otherCNPGBackupInFlight: %v", err) + } + if holder != "" { + t.Fatalf("the job waits on its own Backup: holder %q", holder) + } +} + +// Once the job's Backup exists the Cluster is only read; a failed read is +// returned for a retry and neither fails the running backup nor starts the +// destination retry budget. +func TestReconcileCNPG_ClusterReadErrorDoesNotFailRunningBackup(t *testing.T) { + for name, readErr := range map[string]error{ + "internal error": apierrors.NewInternalError(errors.New("blip")), + // A write answered Forbidden fails the job; a read must not. + "forbidden": apierrors.NewForbidden(schema.GroupResource{Group: cnpgtypes.GroupName, Resource: "clusters"}, rolloutCluster, errors.New("denied")), + } { + t.Run(name, func(t *testing.T) { testClusterReadErrorKeepsBackup(t, readErr) }) + } +} + +func testClusterReadErrorKeepsBackup(t *testing.T, readErr error) { + expired := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)) + f := newAttachedObjectStoreFixture(t, expired, "s3://other/") + f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") + f.setJobCondition(metav1.Condition{ + Type: backupCondDestinationApplied, Status: metav1.ConditionFalse, Reason: "ClusterPluginApplyRetrying", + Message: "earlier failure", LastTransitionTime: metav1.NewTime(expired), + }) + dyn := f.r.Interface.(*dynamicfake.FakeDynamicClient) + dyn.PrependReactor("get", "clusters", func(clienttesting.Action) (bool, runtime.Object, error) { + return true, nil, readErr + }) + + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(context.Background(), j, f.resolved); err == nil { + t.Fatalf("a failed Cluster read was not returned for a retry") + } + persisted := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, persisted); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if persisted.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("a failed Cluster read failed the running backup: %s", persisted.Status.Message) + } +} + // cnpgRolloutFixture drives reconcileCNPG against one Postgres app whose // Cluster and instance pods a test swaps between passes, standing in for // CNPG rolling the instances. From 570fcec7253286d597308dc14fc8dc31ad5d0ef2 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:04:57 +0300 Subject: [PATCH 02/26] fix(postgres): hold a queued backup job while its application is restored The restore gate in Reconcile looks only at a BackupJob that has not started, and the CNPG driver stamps StartedAt on its first pass. A job that then waits behind another backup of the application, for as long as that backup runs, writes the WAL archive destination and the Cluster plugin once released without looking for a restore that began in the meantime. A write landing while the restore re-renders the Cluster can put the restored Cluster back on the source's WAL prefix, where recovery fails with "Expected empty archive". Every pass that is about to write the destination now looks for a restore of the application and holds the job the way the gate does. A job whose Backup already runs writes nothing and is not held. The hold resets the retry budget of the destination write, as the wait for another backup does, so time spent behind a restore does not fail the job on the first error after it. Signed-off-by: Alexey Artamonov Assisted-by: LLM --- .../backupjob_restore_lock.go | 11 +- .../cnpgstrategy_controller.go | 11 ++ .../cnpgstrategy_controller_test.go | 172 +++++++++++++++++- 3 files changed, 187 insertions(+), 7 deletions(-) diff --git a/internal/backupcontroller/backupjob_restore_lock.go b/internal/backupcontroller/backupjob_restore_lock.go index c40d59aef..3782527d9 100644 --- a/internal/backupcontroller/backupjob_restore_lock.go +++ b/internal/backupcontroller/backupjob_restore_lock.go @@ -130,13 +130,14 @@ func ptrString(s *string) string { return *s } -// holdForRestore keeps a BackupJob that has not started yet waiting while a -// restore writes into its application. It stays non-terminal, so a scheduled -// run still happens once the restore ends, only later than its slot. +// holdForRestore keeps a BackupJob waiting while a restore writes into its +// application: one that has not started yet, or a CNPG one about to write +// its WAL archive destination. It stays non-terminal, so a scheduled run +// still happens once the restore ends, only later than its slot. // // A failed status write is returned so the manager retries it with backoff. -// The job is held either way, since nothing past the gate ran, but a hold -// nobody can see reads as a run stuck for no reason. +// The job is held either way, since it writes nothing past the hold, but a +// hold nobody can see reads as a run stuck for no reason. func (r *BackupJobReconciler) holdForRestore(ctx context.Context, j *backupsv1alpha1.BackupJob, restore string) (ctrl.Result, error) { if j.Status.Phase == backupsv1alpha1.BackupJobPhaseEmpty { j.Status.Phase = backupsv1alpha1.BackupJobPhasePending diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index a2a429b4f..eec19819c 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -334,6 +334,17 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp // Backup exists and only while no other job's Backup is in flight. writeDestination := existingBackup == nil if writeDestination { + // The gate in Reconcile sees only a job that has not started, and + // this one may have waited in the queue for as long as a restore + // takes to begin. + restore, err := activeRestoreTargeting(ctx, r.Client, j.Namespace, j.Spec.ApplicationRef) + if err != nil { + return ctrl.Result{}, err + } + if restore != "" { + apimeta.RemoveStatusCondition(&j.Status.Conditions, backupCondDestinationApplied) + return r.holdForRestore(ctx, j, restore) + } holder, err := r.otherCNPGBackupInFlight(ctx, j, clusterName) if err != nil { return ctrl.Result{}, err diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index c94630470..f4ec68fb9 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -22,6 +22,7 @@ import ( "k8s.io/client-go/kubernetes/scheme" clienttesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" @@ -2852,6 +2853,163 @@ func TestReconcileCNPG_QueueResetsDestinationRetryBudget(t *testing.T) { } } +// seedRestoreOfApp starts a RestoreJob that writes into the fixture's app. +func (f *cnpgRolloutFixture) seedRestoreOfApp() *backupsv1alpha1.RestoreJob { + f.t.Helper() + appGroup := backupsv1alpha1.DefaultApplicationAPIGroup + strategyGroup := strategyv1alpha1.GroupVersion.Group + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: rolloutNS, Name: "app-backup"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{APIGroup: &appGroup, Kind: postgresAppKind, Name: rolloutApp}, + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &strategyGroup, Kind: strategyv1alpha1.CNPGStrategyKind, Name: "cnpg-strategy"}, + }, + } + restore := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: rolloutNS, Name: "app-restore"}, + Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: backup.Name}}, + } + for _, obj := range []client.Object{backup, restore} { + if err := f.c.Create(context.Background(), obj); err != nil { + f.t.Fatalf("seed %T: %v", obj, err) + } + } + return restore +} + +// A job past its start writes the WAL archive destination only while no +// restore rewrites its application. The restore gate in Reconcile looks only +// at a job that has not started, and a job released from the queue, or one +// still before its first write, has started long ago: a write landing during +// the restore can put the restored Cluster back on the source's WAL prefix. +func TestReconcileCNPG_HoldsTheDestinationWriteWhileTheAppIsRestored(t *testing.T) { + for _, queued := range []bool{true, false} { + t.Run(fmt.Sprintf("released from the queue=%t", queued), func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + if queued { + f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) + f.seedCNPGBackup("bj-other-cnpg", "bj-other", rolloutCluster, "running") + if j, _ := f.pass(); apimeta.FindStatusCondition(j.Status.Conditions, "Ready").Reason != "WaitingForOtherBackup" { + t.Fatalf("Ready = %+v, want the job queued", apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } + } + restore := f.seedRestoreOfApp() + if queued { + held := &cnpgtypes.Backup{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj-other-cnpg"}, held); err != nil { + t.Fatalf("get holder Backup: %v", err) + } + held.Status.Phase = cnpgBackupPhaseComplete + if err := f.c.Update(context.Background(), held); err != nil { + t.Fatalf("complete holder Backup: %v", err) + } + holder := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj-other"}, holder); err != nil { + t.Fatalf("get holder BackupJob: %v", err) + } + holder.Status.Phase = backupsv1alpha1.BackupJobPhaseSucceeded + if err := f.c.Status().Update(context.Background(), holder); err != nil { + t.Fatalf("finish holder BackupJob: %v", err) + } + } + + j, backups, res := f.passResult() + if got := f.liveDestination(); got != "s3://other/" { + t.Errorf("destination written during a restore of the app: %q", got) + } + for _, b := range backups { + if b.Labels[backupsv1alpha1.OwningJobNameLabel] == "bj" { + t.Errorf("a cnpg.io/Backup was created during a restore of the app: %s", b.Name) + } + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != ConditionReasonRestoreInProgress { + t.Errorf("Ready = %+v, want %s", ready, ConditionReasonRestoreInProgress) + } + if res.RequeueAfter == 0 { + t.Errorf("a held job is not requeued: %+v", res) + } + + restore.Status.Phase = backupsv1alpha1.RestoreJobPhaseSucceeded + if err := f.c.Status().Update(context.Background(), restore); err != nil { + t.Fatalf("finish the restore: %v", err) + } + f.pass() + if got := f.liveDestination(); got != "s3://bucket/" { + t.Errorf("once the restore finished, destination = %q, want the job's own s3://bucket/", got) + } + }) + } +} + +// A job whose Backup already runs writes nothing, so a restore does not hold +// it: holding would strand a backup that is already moving data. +func TestReconcileCNPG_RestoreDoesNotHoldARunningBackup(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") + f.seedRestoreOfApp() + + j, _ := f.pass() + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForCNPGBackup" { + t.Errorf("Ready = %+v, want the running backup still followed", ready) + } +} + +// An error looking for a restore is not taken as "no restore". +func TestReconcileCNPG_RestoreLookupErrorIsReturned(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*backupsv1alpha1.RestoreJobList); ok { + return apierrors.NewServiceUnavailable("cache not synced") + } + return cl.List(ctx, list, opts...) + }, + }) + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(context.Background(), j, f.resolved); err == nil { + t.Fatalf("reconcileCNPG swallowed the restore lookup error") + } + if got := f.liveDestination(); got != "s3://other/" { + t.Errorf("destination written although restores could not be listed: %q", got) + } +} + +// Waiting for a restore resets the retry budget of the destination write, +// as waiting for another backup does, so the restore does not spend it. +func TestReconcileCNPG_RestoreResetsDestinationRetryBudget(t *testing.T) { + expired := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)) + f := newAttachedObjectStoreFixture(t, expired, "s3://other/") + f.setJobCondition(metav1.Condition{ + Type: backupCondDestinationApplied, Status: metav1.ConditionFalse, Reason: "ClusterPluginApplyRetrying", + Message: "earlier failure", LastTransitionTime: metav1.NewTime(expired), + }) + restore := f.seedRestoreOfApp() + + j, _ := f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationApplied); cond != nil { + t.Fatalf("%s = %+v kept while waiting for a restore", backupCondDestinationApplied, cond) + } + + restore.Status.Phase = backupsv1alpha1.RestoreJobPhaseSucceeded + if err := f.c.Status().Update(context.Background(), restore); err != nil { + t.Fatalf("finish the restore: %v", err) + } + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgtypes.ObjectStore); ok { + return apierrors.NewInternalError(errors.New("webhook down")) + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + if j, _ = f.pass(); j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the first failure after the restore failed the job: %s", j.Status.Message) + } +} + func TestOtherCNPGBackupInFlight_IgnoresTheJobsOwnBackup(t *testing.T) { f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") @@ -2987,6 +3145,15 @@ func newRolloutInstancePod(created time.Time) *corev1.Pod { // pass runs one reconcile and returns the persisted BackupJob and the // cnpg.io/Backups that exist afterwards. func (f *cnpgRolloutFixture) pass() (*backupsv1alpha1.BackupJob, []cnpgtypes.Backup) { + f.t.Helper() + j, backups, _ := f.passResult() + return j, backups +} + +// passResult is pass that also returns the reconcile result: the controller +// watches only BackupJobs, so a pass that waits on anything else is woken +// only by its own requeue. +func (f *cnpgRolloutFixture) passResult() (*backupsv1alpha1.BackupJob, []cnpgtypes.Backup, ctrl.Result) { f.t.Helper() ctx := context.Background() key := client.ObjectKey{Namespace: rolloutNS, Name: "bj"} @@ -2994,7 +3161,8 @@ func (f *cnpgRolloutFixture) pass() (*backupsv1alpha1.BackupJob, []cnpgtypes.Bac if err := f.c.Get(ctx, key, j); err != nil { f.t.Fatalf("get BackupJob: %v", err) } - if _, err := f.r.reconcileCNPG(ctx, j, f.resolved); err != nil { + res, err := f.r.reconcileCNPG(ctx, j, f.resolved) + if err != nil { f.t.Fatalf("reconcileCNPG: %v", err) } got := &backupsv1alpha1.BackupJob{} @@ -3005,7 +3173,7 @@ func (f *cnpgRolloutFixture) pass() (*backupsv1alpha1.BackupJob, []cnpgtypes.Bac if err := f.c.List(ctx, backups, client.InNamespace(rolloutNS)); err != nil { f.t.Fatalf("list cnpg.io/Backups: %v", err) } - return got, backups.Items + return got, backups.Items, res } // observeCNPG makes the next live read see cluster, as CNPG has written it. From 567f07d7080223b8808834092b8e313fbd79262d Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:06:31 +0300 Subject: [PATCH 03/26] fix(postgres): time the plugin rollout from the write that attached it The PluginRolledOut latch is recorded before the Cluster write that attaches the barman-cloud plugin, and its time was used both as the start of the rollout deadline and as the age every instance pod must exceed to count as rolled. Now that a failing write is retried for up to the backup deadline, the attach can come long after the latch: the deadline was then spent before the rollout began, and a pod recreated between the latch and the attach, without the plugin sidecar, passed as rolled, so a Backup was created that CloudNativePG fails for good. The latch now carries its own reason, and the write that finds the plugin missing and attaches it re-stamps the condition, once, with the time it was attempted. A plugin someone else attached after the latch, another backup job or a restore, keeps the latch time: the rollout it started can be over by the time this job writes, and its instances would otherwise never count as rolled. Signed-off-by: Alexey Artamonov Assisted-by: LLM --- .../cnpgstrategy_controller.go | 31 +++++ .../cnpgstrategy_controller_test.go | 109 ++++++++++++++++++ 2 files changed, 140 insertions(+) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index eec19819c..e1fe84f8a 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -197,6 +197,11 @@ const ( // instance pods must postdate (see cnpgPluginRolloutPending). backupCondPluginRolledOut = "PluginRolledOut" + // Reason of the PluginRolledOut latch recorded before the write that + // attaches the plugin. The write that attaches it replaces the latch with + // its own time, which retries can put long after the latch. + cnpgReasonAttachingPlugin = "AttachingPlugin" + // Condition Type recorded while writing the WAL archive destination keeps // failing. Its LastTransitionTime marks the first failure, so the retry // budget is not spent by time the job waited for another backup of the @@ -356,6 +361,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } } + attemptedAt := metav1.Now() attachment, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName, existingBackup != nil || awaitingRollout, writeDestination) if err != nil { if apierrors.IsNotFound(err) { @@ -419,9 +425,34 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ Type: backupCondPluginRolledOut, Status: metav1.ConditionFalse, + Reason: cnpgReasonAttachingPlugin, + Message: message, + }) + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, Reason: "WaitingForPluginRollout", Message: message, }) + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil + } + if rollout.Reason == cnpgReasonAttachingPlugin && attachment.missing { + // Instances recreated between the latch and this write run + // without the plugin, and the rollout deadline starts here. A + // plugin someone else attached since the latch keeps it: the + // rollout that attach started may already be over. + message := fmt.Sprintf("attached the barman-cloud plugin to cnpg.io/Cluster %s/%s, waiting for its instances to roll", j.Namespace, clusterName) + apimeta.RemoveStatusCondition(&j.Status.Conditions, backupCondPluginRolledOut) + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: backupCondPluginRolledOut, + Status: metav1.ConditionFalse, + Reason: "WaitingForPluginRollout", + Message: message, + LastTransitionTime: attemptedAt, + }) apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index f4ec68fb9..b4b73b7e1 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -2814,6 +2814,115 @@ func TestReconcileCNPG_PluginRolloutDeadlineCountsFromAttach(t *testing.T) { } } +// The rollout is measured from the write that attached the plugin, not from +// the latch recorded before it: retries of a failing write can lie between +// the two, and an instance recreated in that time runs without the plugin. +func TestReconcileCNPG_PluginRolloutCountsFromTheSuccessfulAttach(t *testing.T) { + cases := []struct { + name string + // podBetween recreates the instance after the latch and before the + // attach; otherwise it predates both. + podBetween bool + }{ + {name: "an instance recreated before the attach still has to roll", podBetween: true}, + {name: "retries before the attach do not spend the rollout deadline"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + expired := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)).Truncate(time.Second) + oldPod := newRolloutInstancePod(expired.Add(-time.Hour)) + f := newCNPGRolloutFixture(t, newRolloutBackupJob(expired.Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), oldPod) + + j, _ := f.pass() // latch + latch := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) + if latch == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + latch.LastTransitionTime = metav1.NewTime(expired) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("age the latch: %v", err) + } + + failing := true + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgtypes.Cluster); ok && failing { + return apierrors.NewInternalError(errors.New(`failed calling webhook "mcluster.cnpg.io"`)) + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + if j, _ = f.pass(); j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("a failed attach failed the job: %s", j.Status.Message) + } + if tc.podBetween { + f.replacePod(oldPod, newRolloutInstancePod(expired.Add(time.Minute))) + } + + failing = false + attachAt := time.Now().Truncate(time.Second) + j, backups := f.pass() + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created in the pass that attached the plugin: %+v", backups) + } + rollout := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) + if rollout == nil || rollout.Status != metav1.ConditionFalse || rollout.LastTransitionTime.Time.Before(attachAt) { + t.Fatalf("%s = %+v, want False since the attach at %s", backupCondPluginRolledOut, rollout, attachAt) + } + + attached := &cnpgtypes.Cluster{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: rolloutCluster}, attached); err != nil { + t.Fatalf("get Cluster: %v", err) + } + f.observeCNPG(newRolloutCluster(cnpgClusterHealthyPhase, attached.Spec.Plugins...)) + j, backups = f.pass() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("a rollout that began with the attach failed: %s", j.Status.Message) + } + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created against an instance older than the attach: %+v", backups) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || !strings.Contains(ready.Message, "predates") { + t.Errorf("Ready = %+v, want the instance that predates the plugin", ready) + } + }) + } +} + +// A plugin attached by someone else after the latch, another backup job or +// a restore, started the rollout before this job's write, which only finds +// it there: instances that rolled since the latch carry the plugin. +func TestReconcileCNPG_PluginAttachedByAnotherWriterKeepsTheLatch(t *testing.T) { + oldPod := newRolloutInstancePod(time.Now().Add(-time.Hour).Truncate(time.Second)) + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), oldPod) + + j, _ := f.pass() // latch + latch := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) + if latch == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + latchedAt := time.Now().Add(-10 * time.Minute).Truncate(time.Second) + latch.LastTransitionTime = metav1.NewTime(latchedAt) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("age the latch: %v", err) + } + f.observeCNPG(newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster))) + f.replacePod(oldPod, newRolloutInstancePod(latchedAt.Add(5*time.Minute))) + + var backups []cnpgtypes.Backup + for range 3 { + if j, backups = f.pass(); len(backups) != 0 || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + break + } + } + if len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups against instances that rolled with the plugin; Ready = %+v", + len(backups), apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } +} + // Waiting for another backup resets the retry budget of the destination // write, so the queue does not spend it. func TestReconcileCNPG_QueueResetsDestinationRetryBudget(t *testing.T) { From 61d64a69f12e6712a5950c943a46dcc565191fd4 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:07:56 +0300 Subject: [PATCH 04/26] test(postgres): pin the requeue and the read-only pass of a running backup Three guards of the CNPG driver could be reverted with the package tests still green. The controller watches only BackupJobs, so a job waiting in the queue or retrying the destination write is woken by nothing but its own requeue, and the tests dropped the result. A job whose Backup runs must not consult the queue, or two jobs that passed it together wait on each other forever, and must patch neither the ObjectStore nor the Cluster plugin, yet only the ObjectStore content was checked. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller_test.go | 32 ++++++++++++++++--- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index b4b73b7e1..e738b6c0e 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -2561,6 +2561,17 @@ func (f *cnpgRolloutFixture) seedOtherBackupJob(name string, phase backupsv1alph func TestReconcileCNPG_RunningBackupDoesNotReapplyObjectStore(t *testing.T) { f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") + // Two jobs can pass the queue together, since it reads the cache; once + // both have a Backup neither may wait on the other. + f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) + f.seedCNPGBackup("bj-other-cnpg", "bj-other", rolloutCluster, "running") + writes := 0 + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + writes++ + return cl.Patch(ctx, obj, patch, opts...) + }, + }) j, _ := f.pass() if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { @@ -2569,8 +2580,11 @@ func TestReconcileCNPG_RunningBackupDoesNotReapplyObjectStore(t *testing.T) { if got := f.liveDestination(); got != "s3://other/" { t.Fatalf("a pass over a running backup re-applied the ObjectStore: destination %q", got) } - if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready != nil && ready.Reason == "WaitingForOtherBackup" { - t.Fatalf("a running backup waits on itself: %+v", ready) + if writes != 0 { + t.Errorf("a pass over a running backup patched %d object(s); the ObjectStore and the Cluster plugin are only read", writes) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForCNPGBackup" { + t.Fatalf("Ready = %+v, want the running backup followed rather than queued", ready) } } @@ -2624,7 +2638,7 @@ func TestReconcileCNPG_WaitsForAnotherRunningBackupOfTheApp(t *testing.T) { }, }) - j, backups := f.pass() + j, backups, res := f.passResult() if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { t.Fatalf("BackupJob failed: %s", j.Status.Message) } @@ -2645,8 +2659,13 @@ func TestReconcileCNPG_WaitsForAnotherRunningBackupOfTheApp(t *testing.T) { if ready == nil || ready.Status != metav1.ConditionFalse || ready.Reason != "WaitingForOtherBackup" || !strings.Contains(ready.Message, "bj-other") { t.Errorf("Ready = %+v, want False/WaitingForOtherBackup naming bj-other", ready) } + if res.RequeueAfter == 0 { + t.Errorf("a queued job is not requeued, and nothing else wakes it when the holder finishes: %+v", res) + } statusWrites = 0 - f.pass() + if _, _, res = f.passResult(); res.RequeueAfter == 0 { + t.Errorf("a queued job whose status did not change is not requeued: %+v", res) + } if statusWrites != 0 { t.Errorf("a second pass with the same holder wrote the BackupJob status %d time(s)", statusWrites) } @@ -2715,7 +2734,7 @@ func TestReconcileCNPG_ObjectStoreApplyErrors(t *testing.T) { }, }) - j, backups := f.pass() + j, backups, res := f.passResult() if j.Status.Phase != tc.wantPhase { t.Fatalf("BackupJob phase = %q (%s), want %q", j.Status.Phase, j.Status.Message, tc.wantPhase) } @@ -2727,6 +2746,9 @@ func TestReconcileCNPG_ObjectStoreApplyErrors(t *testing.T) { if ready == nil || ready.Reason != "ClusterPluginApplyRetrying" || !strings.Contains(ready.Message, "connection refused") { t.Errorf("Ready = %+v, want ClusterPluginApplyRetrying carrying the error", ready) } + if res.RequeueAfter == 0 { + t.Errorf("a retried write is not requeued: %+v", res) + } } }) } From 66268d8508271b82670db719ceb9e72240df04e7 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:08:10 +0300 Subject: [PATCH 05/26] refactor(postgres): drop a Ready reset every later path overwrites After a successful destination write each path of the CNPG driver sets or removes Ready later in the same pass, and writes the status after it, so clearing a stale WaitingForOtherBackup or ClusterPluginApplyRetrying reason there could never outlive the pass, and no test could pin it. Signed-off-by: Alexey Artamonov Assisted-by: LLM --- internal/backupcontroller/cnpgstrategy_controller.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index e1fe84f8a..821f82e07 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -404,10 +404,6 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } if writeDestination { apimeta.RemoveStatusCondition(&j.Status.Conditions, backupCondDestinationApplied) - if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready != nil && - (ready.Reason == "WaitingForOtherBackup" || ready.Reason == "ClusterPluginApplyRetrying") { - apimeta.RemoveStatusCondition(&j.Status.Conditions, "Ready") - } } if attachment.serverName != serverName { logger.Info("preserving the live Cluster's barman serverName over the strategy template's", From a02bff7fadba6bd00b9fb531a74d8bb2f1c4c9d9 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:21:59 +0300 Subject: [PATCH 06/26] docs(postgres): say what the CNPG backup deadlines are counted from The rollout deadline starts at the latch when another writer attached the plugin and at the write otherwise, and a wait for a restore resets the destination retry budget just as a wait for another backup does. The comments on the deadline and on the two conditions still described only the attach and the queue. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 821f82e07..1d8c6eebf 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -176,10 +176,11 @@ const ( cnpgRecoveryMaxInspectPods = 5 // Cap on the wall-clock time a BackupJob waits for the barman-cloud - // plugin rollout, counted from the attach, or retries writing the WAL - // archive destination, counted from the first failure since the job last - // left the queue, before the cnpg.io/Backup exists. A Backup that exists - // is not capped: CloudNativePG keeps a healthy one pending while another + // plugin rollout, counted from the PluginRolledOut condition, or retries + // writing the WAL archive destination, counted from the first failure + // since the last successful write or the last wait for another backup or + // a restore, before the cnpg.io/Backup exists. A Backup that exists is + // not capped: CloudNativePG keeps a healthy one pending while another // backup of the same Cluster runs, or while it restarts one on another // instance, so no fixed deadline tells those apart from a stuck one. cnpgDefaultBackupDeadline = 30 * time.Minute @@ -193,8 +194,8 @@ const ( // instance, and a cnpg.io/Backup created meanwhile fails with "requested // plugin is not available" or "instance manager was restarted during // backup" and never recovers. False holds the Backup back; its - // LastTransitionTime, written before the plugin is attached, is what the - // instance pods must postdate (see cnpgPluginRolloutPending). + // LastTransitionTime is what the instance pods must postdate (see + // cnpgReasonAttachingPlugin and cnpgPluginRolloutPending). backupCondPluginRolledOut = "PluginRolledOut" // Reason of the PluginRolledOut latch recorded before the write that @@ -205,7 +206,7 @@ const ( // Condition Type recorded while writing the WAL archive destination keeps // failing. Its LastTransitionTime marks the first failure, so the retry // budget is not spent by time the job waited for another backup of the - // app before it tried. + // app, or for a restore of it, before it tried. backupCondDestinationApplied = "DestinationApplied" cnpgPodRoleLabel = "cnpg.io/podRole" @@ -576,9 +577,8 @@ func cnpgBackupFailedMessage(b *cnpgtypes.Backup, errText string) string { // cnpgBackupDeadlineExceeded reports whether more than the backup deadline // has passed since the BackupJob began the step it is waiting on: the plugin -// rollout, counted from the attach, or retrying the destination write, -// counted from the first failure since the job last left the queue behind -// another backup. Returns false for a nil time. +// rollout or retrying the destination write (see cnpgDefaultBackupDeadline). +// Returns false for a nil time. func cnpgBackupDeadlineExceeded(since *metav1.Time) bool { if since == nil { return false From 93c3ee62c45d33c2e8b31857f81624cd08e59d99 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 22:15:46 +0300 Subject: [PATCH 07/26] test(postgres): pin which holder a queued backup job names When two jobs of the application hold the queue, the job waiting behind them names one of them in its Ready message, and the sort is what keeps that name stable however the cache orders their Backups. Without it the message can change from one poll to the next, and each change writes the BackupJob status again; nothing failed when the sort was removed. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller_test.go | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index e738b6c0e..6240500e5 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3141,6 +3141,34 @@ func TestReconcileCNPG_RestoreResetsDestinationRetryBudget(t *testing.T) { } } +// With two jobs holding the queue the wait names the same one on every pass, +// whatever order the cache lists their Backups in, so a waiting job does not +// rewrite its status each poll. +func TestReconcileCNPG_QueueNamesOneHolderAcrossPasses(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.seedOtherBackupJob("holder-z", backupsv1alpha1.BackupJobPhaseRunning) + f.seedOtherBackupJob("holder-a", backupsv1alpha1.BackupJobPhaseRunning) + f.seedCNPGBackup("a-cnpg", "holder-z", rolloutCluster, "running") + f.seedCNPGBackup("z-cnpg", "holder-a", rolloutCluster, "running") + statusWrites := 0 + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + statusWrites++ + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }) + + j, _ := f.pass() + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForOtherBackup" || !strings.Contains(ready.Message, "holder-a ") { + t.Fatalf("Ready = %+v, want WaitingForOtherBackup naming holder-a", ready) + } + statusWrites = 0 + f.pass() + if statusWrites != 0 { + t.Errorf("a second pass with the same two holders wrote the BackupJob status %d time(s)", statusWrites) + } +} + func TestOtherCNPGBackupInFlight_IgnoresTheJobsOwnBackup(t *testing.T) { f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") From 7efe33e87de1e3683e1e4378ba0843846151922b Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:05:32 +0300 Subject: [PATCH 08/26] test(postgres): check the stored phase of a backup job per cnpg Backup phase The phase test read the BackupJob it passed to the reconciler, which holds the phase in memory whether or not the status write happened. A completed Backup could then leave the stored BackupJob Running, so the Plan would never see the run finish, and no test in the package noticed. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- internal/backupcontroller/cnpgstrategy_controller_test.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 6240500e5..a5d1d5b44 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -2421,6 +2421,13 @@ func TestReconcileCNPG_BackupPhaseOutcome(t *testing.T) { if j.Status.Phase != tc.wantPhase { t.Fatalf("BackupJob phase = %q (%s), want %q", j.Status.Phase, j.Status.Message, tc.wantPhase) } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(job), stored); err != nil { + t.Fatalf("get BackupJob after reconcile: %v", err) + } + if stored.Status.Phase != tc.wantPhase { + t.Fatalf("stored BackupJob phase = %q, want %q", stored.Status.Phase, tc.wantPhase) + } message := j.Status.Message if tc.wantPhase == backupsv1alpha1.BackupJobPhaseRunning { From 8061e2dbd9c4f875d2e620847aaa10a005322d4a Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 22:13:55 +0300 Subject: [PATCH 09/26] test(postgres): describe what the backup deadline test still guards The deadline no longer applies to a failed cnpg.io/Backup, which now fails its BackupJob at once; it only bounds the wait for the barman-cloud plugin rollout, and the comment still claimed the former. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- internal/backupcontroller/cnpgstrategy_controller_test.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index a5d1d5b44..65f979afb 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -1000,10 +1000,9 @@ func TestUnmarshalCNPGBackupSnapshot_RejectsMissingOrWrongKind(t *testing.T) { } } -// TestCNPGBackupDeadlineExceeded locks in the wall-clock cap that prevents a -// perpetually-failed cnpg.io/Backup from pinning the BackupJob in Running -// forever. Without this guard the Plan-controller queue would back up -// behind a single broken backup. +// TestCNPGBackupDeadlineExceeded locks in the wall-clock cap on waiting for +// the barman-cloud plugin rollout, so a rollout that never finishes fails the +// BackupJob instead of pinning it in Running. func TestCNPGBackupDeadlineExceeded(t *testing.T) { cases := []struct { name string From 32ca678077c3437b0ebb646b28e2fcfa719afff3 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Fri, 6 Nov 2026 15:58:37 +0300 Subject: [PATCH 10/26] fix(postgres): give a held backup job its plugin rollout deadline back A job that latched the barman-cloud plugin rollout and then waited for another backup of the application, or for a restore of it, had that wait charged to the rollout deadline. Released after more than the deadline, it failed on the first instance that was not ready yet with "rollout did not finish", although no rollout of its own had been running while it waited. The hold is now recorded in a DestinationWriteHeld condition, and its release time restarts the rollout deadline when it is later than the rollout's start. The instance pods are still measured against the rollout's start: one that rolled while the job was held carries the plugin and counts. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 36 +++- .../cnpgstrategy_controller_test.go | 171 ++++++++++++++++++ 2 files changed, 205 insertions(+), 2 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 1d8c6eebf..fc3fded4c 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -176,7 +176,8 @@ const ( cnpgRecoveryMaxInspectPods = 5 // Cap on the wall-clock time a BackupJob waits for the barman-cloud - // plugin rollout, counted from the PluginRolledOut condition, or retries + // plugin rollout, counted from the PluginRolledOut condition or from the + // release recorded in DestinationWriteHeld, whichever is later, or retries // writing the WAL archive destination, counted from the first failure // since the last successful write or the last wait for another backup or // a restore, before the cnpg.io/Backup exists. A Backup that exists is @@ -209,6 +210,13 @@ const ( // app, or for a restore of it, before it tried. backupCondDestinationApplied = "DestinationApplied" + // Condition Type recorded while the job is held off writing the WAL + // archive destination, by another backup of the app in flight or by a + // restore of it, and set False when released. The release time restarts + // the plugin rollout deadline, which that wait must not spend; the + // instance pods still have to postdate the rollout's own start. + backupCondDestinationWriteHeld = "DestinationWriteHeld" + cnpgPodRoleLabel = "cnpg.io/podRole" cnpgPodRoleInstance = "instance" ) @@ -349,6 +357,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } if restore != "" { apimeta.RemoveStatusCondition(&j.Status.Conditions, backupCondDestinationApplied) + apimeta.SetStatusCondition(&j.Status.Conditions, cnpgDestinationWriteHeld(ConditionReasonRestoreInProgress)) return r.holdForRestore(ctx, j, restore) } holder, err := r.otherCNPGBackupInFlight(ctx, j, clusterName) @@ -357,9 +366,18 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } if holder != "" { apimeta.RemoveStatusCondition(&j.Status.Conditions, backupCondDestinationApplied) + apimeta.SetStatusCondition(&j.Status.Conditions, cnpgDestinationWriteHeld("WaitingForOtherBackup")) return r.waitCNPGBackupJob(ctx, j, "WaitingForOtherBackup", fmt.Sprintf( "waiting for BackupJob %s of the same application to finish its backup, which writes to the shared WAL archive destination", holder)) } + if apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationWriteHeld) != nil { + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: backupCondDestinationWriteHeld, + Status: metav1.ConditionFalse, + Reason: "Released", + Message: "nothing holds the WAL archive destination write any more", + }) + } } attemptedAt := metav1.Now() @@ -466,7 +484,12 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp return ctrl.Result{}, err } if pending != "" { - if cnpgBackupDeadlineExceeded(&rollout.LastTransitionTime) { + deadlineFrom := rollout.LastTransitionTime + if held := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationWriteHeld); held != nil && + held.LastTransitionTime.After(deadlineFrom.Time) { + deadlineFrom = held.LastTransitionTime + } + if cnpgBackupDeadlineExceeded(&deadlineFrom) { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( "barman-cloud plugin rollout did not finish within %s: %s", cnpgDefaultBackupDeadline, pending)) } @@ -933,6 +956,15 @@ func (r *BackupJobReconciler) otherCNPGBackupInFlight(ctx context.Context, j *ba return holders[0], nil } +func cnpgDestinationWriteHeld(reason string) metav1.Condition { + return metav1.Condition{ + Type: backupCondDestinationWriteHeld, + Status: metav1.ConditionTrue, + Reason: reason, + Message: "held off writing the WAL archive destination", + } +} + // waitCNPGBackupJob requeues the BackupJob and records why it waits in its // Ready condition, writing the status only when the conditions changed. func (r *BackupJobReconciler) waitCNPGBackupJob(ctx context.Context, j *backupsv1alpha1.BackupJob, reason, message string) (ctrl.Result, error) { diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 65f979afb..1f0b88312 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3447,6 +3447,41 @@ func TestReconcileCNPG_AttachedPluginDoesNotDelayBackup(t *testing.T) { if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut); cond != nil { t.Errorf("%s condition = %+v on a Cluster the driver did not roll", backupCondPluginRolledOut, cond) } + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationWriteHeld); cond != nil { + t.Errorf("%s condition = %+v on a job nothing held", backupCondDestinationWriteHeld, cond) + } +} + +// A release older than the rollout, from a wait before the plugin was +// attached, does not shorten the rollout that began after it. +func TestReconcileCNPG_EarlierReleaseDoesNotShortenTheRollout(t *testing.T) { + expired := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)) + j := newRolloutBackupJob(expired.Add(-time.Hour)) + j.Status.Conditions = []metav1.Condition{ + { + Type: backupCondDestinationWriteHeld, + Status: metav1.ConditionFalse, + Reason: "Released", + LastTransitionTime: metav1.NewTime(expired), + }, + { + Type: backupCondPluginRolledOut, + Status: metav1.ConditionFalse, + Reason: "WaitingForPluginRollout", + LastTransitionTime: metav1.NewTime(time.Now().Add(-time.Minute)), + }, + } + f := newCNPGRolloutFixture(t, j, + newRolloutCluster("Waiting for user action", buildBarmanPlugin(rolloutCluster, rolloutCluster)), + newRolloutInstancePod(expired.Add(-time.Hour))) + + got, backups := f.pass() + if got.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("a rollout that began a minute ago failed on an older release: %s", got.Status.Message) + } + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created against an unfinished rollout: %+v", backups) + } } // TestReconcileCNPG_PluginRolloutWaitIsBounded: a rollout that never ends @@ -3476,6 +3511,142 @@ func TestReconcileCNPG_PluginRolloutWaitIsBounded(t *testing.T) { } } +// A job whose plugin rollout started, and which then waited for another +// backup of the app or for a restore of it, gets the rollout deadline back +// from the moment it was released: that wait is not a rollout of its own. +// The instance pods still count as rolled from the rollout's own start. +func TestReconcileCNPG_HeldJobRolloutDeadlineCountsFromRelease(t *testing.T) { + type hold struct { + name string + seed func(f *cnpgRolloutFixture) (release func()) + waiting string + } + holds := []hold{ + { + name: "another backup", + waiting: "WaitingForOtherBackup", + seed: func(f *cnpgRolloutFixture) func() { + f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) + f.seedCNPGBackup("bj-other-cnpg", "bj-other", rolloutCluster, "running") + return func() { + held := &cnpgtypes.Backup{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj-other-cnpg"}, held); err != nil { + f.t.Fatalf("get holder Backup: %v", err) + } + held.Status.Phase = cnpgBackupPhaseComplete + if err := f.c.Update(context.Background(), held); err != nil { + f.t.Fatalf("complete holder Backup: %v", err) + } + } + }, + }, + { + name: "a restore", + waiting: ConditionReasonRestoreInProgress, + seed: func(f *cnpgRolloutFixture) func() { + restore := f.seedRestoreOfApp() + return func() { + restore.Status.Phase = backupsv1alpha1.RestoreJobPhaseSucceeded + if err := f.c.Status().Update(context.Background(), restore); err != nil { + f.t.Fatalf("finish the restore: %v", err) + } + } + }, + }, + } + stampedAt := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)).Truncate(time.Second) + newHeldRollout := func(t *testing.T, h hold, cluster *cnpgtypes.Cluster, pod *corev1.Pod) *cnpgRolloutFixture { + t.Helper() + j := newRolloutBackupJob(stampedAt.Add(-time.Hour)) + j.Status.Conditions = []metav1.Condition{{ + Type: backupCondPluginRolledOut, + Status: metav1.ConditionFalse, + Reason: "WaitingForPluginRollout", + LastTransitionTime: metav1.NewTime(stampedAt), + }} + f := newCNPGRolloutFixture(t, j, cluster, pod) + release := h.seed(f) + got, backups := f.pass() + for _, b := range backups { + if b.Labels[backupsv1alpha1.OwningJobNameLabel] == "bj" { + t.Fatalf("a held job created cnpg.io/Backup %s", b.Name) + } + } + if got.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("a held job did not wait: %s", got.Status.Message) + } + if ready := apimeta.FindStatusCondition(got.Status.Conditions, "Ready"); ready == nil || ready.Reason != h.waiting { + t.Fatalf("Ready = %+v, want %s", ready, h.waiting) + } + release() + return f + } + + for _, h := range holds { + t.Run(h.name+": the rollout is still waited for after the release", func(t *testing.T) { + f := newHeldRollout(t, h, + newRolloutCluster("Waiting for user action", buildBarmanPlugin(rolloutCluster, rolloutCluster)), + newRolloutInstancePod(stampedAt.Add(-time.Hour))) + + releasedAt := time.Now().Truncate(time.Second) + j, backups := f.pass() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("time held by %s was charged to the rollout: %s", h.name, j.Status.Message) + } + for _, b := range backups { + if b.Labels[backupsv1alpha1.OwningJobNameLabel] == "bj" { + t.Fatalf("cnpg.io/Backup %s was created against an unfinished rollout", b.Name) + } + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForPluginRollout" { + t.Fatalf("Ready = %+v, want WaitingForPluginRollout", ready) + } + released := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationWriteHeld) + if released == nil || released.Status != metav1.ConditionFalse || released.LastTransitionTime.Time.Before(releasedAt) { + t.Fatalf("%s = %+v, want False since the release at %s", backupCondDestinationWriteHeld, released, releasedAt) + } + if rollout := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut); rollout == nil || !rollout.LastTransitionTime.Time.Equal(stampedAt) { + t.Errorf("%s = %+v, want its stamp kept at %s", backupCondPluginRolledOut, rollout, stampedAt) + } + + released.LastTransitionTime = metav1.NewTime(stampedAt) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("age the release: %v", err) + } + j, _ = f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(j.Status.Message, "rollout did not finish") { + t.Fatalf("phase = %q (%s), want Failed once the rollout outlived the deadline after the release", j.Status.Phase, j.Status.Message) + } + }) + + t.Run(h.name+": an instance that rolled while the job was held counts", func(t *testing.T) { + f := newHeldRollout(t, h, + newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)), + newRolloutInstancePod(stampedAt.Add(time.Minute))) + + var j *backupsv1alpha1.BackupJob + own := 0 + for range 3 { + var backups []cnpgtypes.Backup + j, backups = f.pass() + own = 0 + for _, b := range backups { + if b.Labels[backupsv1alpha1.OwningJobNameLabel] == "bj" { + own++ + } + } + if own != 0 || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + break + } + } + if own != 1 { + t.Fatalf("got %d cnpg.io/Backups of the job against an instance that rolled after the rollout began; Ready = %+v, phase %q (%s)", + own, apimeta.FindStatusCondition(j.Status.Conditions, "Ready"), j.Status.Phase, j.Status.Message) + } + }) + } +} + // TestReconcileCNPGRestore_MissingStrategyFailsClosedAfterDeadline covers the // restore-path blocker: a RestoreJob whose referenced CNPG Strategy CR never // appears must NOT requeue forever. requeueRestoreStrategyNotReady gates From 258c5359b606897d144248500dc2c752d2498756 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Fri, 6 Nov 2026 16:08:26 +0300 Subject: [PATCH 11/26] fix(postgres): restart the plugin rollout whenever a backup job attaches it Only the first attach after the latch restarted the rollout. In the platform flow the chart renders no spec.plugins, so an in-place restore recreates the Cluster without the plugin, and a backup job held through that restore attaches it again once released. The rollout condition then still carried its earlier start, the restored instances were newer than it and ready, and the Backup was created in the same pass, before CloudNativePG had rolled anything; such a Backup fails with "requested plugin is not available" or "instance manager was restarted". Every write of the job that finds the plugin missing now starts the rollout over. A plugin attached by another writer is still timed from the latch. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 25 ++++++----- .../cnpgstrategy_controller_test.go | 45 ++++++++++++++++++- 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index fc3fded4c..83ce9b41e 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -175,12 +175,13 @@ const ( // against an unreachable target reproduces the same FATAL. cnpgRecoveryMaxInspectPods = 5 - // Cap on the wall-clock time a BackupJob waits for the barman-cloud - // plugin rollout, counted from the PluginRolledOut condition or from the - // release recorded in DestinationWriteHeld, whichever is later, or retries - // writing the WAL archive destination, counted from the first failure - // since the last successful write or the last wait for another backup or - // a restore, before the cnpg.io/Backup exists. A Backup that exists is + // Cap on the wall-clock time a BackupJob spends before its + // cnpg.io/Backup exists on each of two waits. The plugin rollout is + // counted from the PluginRolledOut condition, or from the release + // recorded in DestinationWriteHeld when that is later. Retrying the WAL + // archive destination write is counted from the first failure since the + // last successful write or the last wait for another backup or a + // restore. A Backup that exists is // not capped: CloudNativePG keeps a healthy one pending while another // backup of the same Cluster runs, or while it restarts one on another // instance, so no fixed deadline tells those apart from a stuck one. @@ -200,8 +201,9 @@ const ( backupCondPluginRolledOut = "PluginRolledOut" // Reason of the PluginRolledOut latch recorded before the write that - // attaches the plugin. The write that attaches it replaces the latch with - // its own time, which retries can put long after the latch. + // attaches the plugin. Every write of this job that attaches it replaces + // the condition with its own time, which retries can put long after the + // latch. cnpgReasonAttachingPlugin = "AttachingPlugin" // Condition Type recorded while writing the WAL archive destination keeps @@ -454,9 +456,10 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil } - if rollout.Reason == cnpgReasonAttachingPlugin && attachment.missing { - // Instances recreated between the latch and this write run - // without the plugin, and the rollout deadline starts here. A + if attachment.missing { + // This write attached the plugin, so its rollout starts here: + // instances recreated since the latch, or by a restore that + // re-rendered the Cluster without the plugin, run without it. A // plugin someone else attached since the latch keeps it: the // rollout that attach started may already be over. message := fmt.Sprintf("attached the barman-cloud plugin to cnpg.io/Cluster %s/%s, waiting for its instances to roll", j.Namespace, clusterName) diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 1f0b88312..8f0035aa6 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -2830,6 +2830,11 @@ func TestReconcileCNPG_PluginRolloutDeadlineCountsFromAttach(t *testing.T) { if cond := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); cond == nil || cond.Reason != "WaitingForPluginRollout" { t.Fatalf("Ready = %+v, want WaitingForPluginRollout", cond) } + attached := &cnpgtypes.Cluster{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: rolloutCluster}, attached); err != nil { + t.Fatalf("get Cluster: %v", err) + } + f.observeCNPG(newRolloutCluster(cnpgClusterHealthyPhase, attached.Spec.Plugins...)) rollout := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) rollout.LastTransitionTime = metav1.NewTime(expired) @@ -2919,8 +2924,9 @@ func TestReconcileCNPG_PluginRolloutCountsFromTheSuccessfulAttach(t *testing.T) } // A plugin attached by someone else after the latch, another backup job or -// a restore, started the rollout before this job's write, which only finds -// it there: instances that rolled since the latch carry the plugin. +// the chart re-rendering a restored Cluster outside the platform flow, +// started the rollout before this job's write, which only finds it there: +// instances that rolled since the latch carry the plugin. func TestReconcileCNPG_PluginAttachedByAnotherWriterKeepsTheLatch(t *testing.T) { oldPod := newRolloutInstancePod(time.Now().Add(-time.Hour).Truncate(time.Second)) f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), @@ -3452,6 +3458,41 @@ func TestReconcileCNPG_AttachedPluginDoesNotDelayBackup(t *testing.T) { } } +// An in-place restore of the platform flow recreates the Cluster without the +// barman-cloud plugin, so a job held through it attaches the plugin again +// once released. That attach starts a rollout of its own, which the +// instances restored after the job's first rollout began have not done. +func TestReconcileCNPG_ReattachAfterRestoreRestartsTheRollout(t *testing.T) { + stampedAt := time.Now().Add(-10 * time.Minute).Truncate(time.Second) + j := newRolloutBackupJob(stampedAt.Add(-time.Hour)) + j.Status.Conditions = []metav1.Condition{{ + Type: backupCondPluginRolledOut, + Status: metav1.ConditionFalse, + Reason: "WaitingForPluginRollout", + LastTransitionTime: metav1.NewTime(stampedAt), + }} + f := newCNPGRolloutFixture(t, j, newRolloutCluster(cnpgClusterHealthyPhase), + newRolloutInstancePod(time.Now().Add(-2*time.Minute))) + restore := f.seedRestoreOfApp() + if got, _ := f.pass(); apimeta.FindStatusCondition(got.Status.Conditions, "Ready").Reason != ConditionReasonRestoreInProgress { + t.Fatalf("Ready = %+v, want the job held by the restore", apimeta.FindStatusCondition(got.Status.Conditions, "Ready")) + } + restore.Status.Phase = backupsv1alpha1.RestoreJobPhaseSucceeded + if err := f.c.Status().Update(context.Background(), restore); err != nil { + t.Fatalf("finish the restore: %v", err) + } + + attachAt := time.Now().Truncate(time.Second) + got, backups := f.pass() + if len(backups) != 0 { + t.Fatalf("cnpg.io/Backup created in the pass that attached the plugin to the restored Cluster: %+v", backups) + } + rollout := apimeta.FindStatusCondition(got.Status.Conditions, backupCondPluginRolledOut) + if rollout == nil || rollout.Status != metav1.ConditionFalse || rollout.LastTransitionTime.Time.Before(attachAt) { + t.Fatalf("%s = %+v, want False since the attach at %s", backupCondPluginRolledOut, rollout, attachAt) + } +} + // A release older than the rollout, from a wait before the plugin was // attached, does not shorten the rollout that began after it. func TestReconcileCNPG_EarlierReleaseDoesNotShortenTheRollout(t *testing.T) { From a6af14ce7486deafee2d95a2f15bbba0a6bc175c Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 9 Nov 2026 10:40:54 +0300 Subject: [PATCH 12/26] fix(postgres): build a backup's artifact from the destination it was written to The WAL archive destination is written by the pass that creates the cnpg.io/Backup and not again while it runs, yet the artifact took the destination, the endpoint and the credentials Secret from the strategy rendered when the Backup completed. A strategy or BackupClass edited while the backup ran gave an artifact that pointed somewhere nothing had been written, and a restore from it found no data. The pass that writes the destination now records it on the cnpg.io/Backup it creates, and the artifact is built from that record. The record lives on the Backup rather than on the BackupJob because a tenant can edit its BackupJobs but has no access to postgresql.cnpg.io objects: a record a tenant could rewrite would point the artifact, and a restore from it, which takes its S3 keys from the strategy, at an endpoint of the tenant's choosing. The artifact size probe measures the same place: the recorded location and credentials Secret, with the Secret keys and the endpoint CA, which the record does not carry, from the strategy. Should those no longer fit after an edit, the probe reports no size instead of measuring somewhere else. A record that cannot be read, or that names no destination path, creates no artifact and fails the job, since the strategy may no longer match the write. A Backup without a record was created by a controller that kept none, and its artifact is built from the strategy as before. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpg_artifact_size_test.go | 73 +++++++- .../cnpgstrategy_controller.go | 97 +++++++++- .../cnpgstrategy_controller_test.go | 169 +++++++++++++++++- 3 files changed, 323 insertions(+), 16 deletions(-) diff --git a/internal/backupcontroller/cnpg_artifact_size_test.go b/internal/backupcontroller/cnpg_artifact_size_test.go index 85e55e8c2..29209c5f1 100644 --- a/internal/backupcontroller/cnpg_artifact_size_test.go +++ b/internal/backupcontroller/cnpg_artifact_size_test.go @@ -284,7 +284,7 @@ func TestCreateCNPGBackupArtifact_SizeBytes(t *testing.T) { r := reconcilerWithLister(t, l) r.Client = newCNPGStrategyTestClient(t, s3CredsSecret("tenant", "creds")) - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "srv", "postgresql", rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -311,7 +311,7 @@ func TestCreateCNPGBackupArtifact_ExistingBackupSkipsProbe(t *testing.T) { cnpgBk := &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}, Status: cnpgtypes.BackupStatus{BackupID: "20261021T100000"}} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: *newSizedBarmanObjectStore()} - if _, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", rendered, newPostgresApp("pg", "tenant")); err != nil { + if _, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")); err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } if l.calls != 0 { @@ -331,7 +331,7 @@ func TestCreateCNPGBackupArtifact_AlreadyExistsRefetchReadsPastTheCache(t *testi store := newCNPGStrategyTestClient(t, backup) r := &BackupJobReconciler{Client: staleCache(t, store), APIReader: notFoundOnce(t, store)} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://b/"}} - got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if err != nil || got == nil || got.Name != "bj-race" { t.Fatalf("createCNPGBackupArtifact = %v, %v; want the Backup that already exists", got, err) } @@ -349,7 +349,7 @@ func TestCreateCNPGBackupArtifact_UnreadableExistingBackupIsRetried(t *testing.T store := newCNPGStrategyTestClient(t, backup) r := &BackupJobReconciler{Client: staleCache(t, store), APIReader: failingReads(t, store)} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://b/"}} - _, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", rendered, newPostgresApp("pg", "tenant")) + _, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if !errors.Is(err, errBackupNotReadBack) { t.Errorf("err = %v, want errBackupNotReadBack", err) } @@ -409,7 +409,7 @@ func TestCreateCNPGBackupArtifact_FailedExistenceCheckSkipsProbe(t *testing.T) { cnpgBk := &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}, Status: cnpgtypes.BackupStatus{BackupID: "20261021T100000"}} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: *newSizedBarmanObjectStore()} - got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if err != nil || got == nil { t.Fatalf("createCNPGBackupArtifact = %v, %v; a transient read must not fail the backup", got, err) } @@ -451,3 +451,66 @@ func TestReconcileCNPG_RejectedCreateFailsTheJob(t *testing.T) { t.Errorf("phase = %q, want Failed for a rejected Create", persisted.Status.Phase) } } + +// The probe measures the base backup where it was written: the destination +// recorded on the cnpg.io/Backup when it was created, not the strategy as +// it reads by the time the backup completes. +func TestCreateCNPGBackupArtifact_SizeProbeReadsTheRecordedDestination(t *testing.T) { + apiGroup := backupsv1alpha1.DefaultApplicationAPIGroup + j := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "bj-moved"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{APIGroup: &apiGroup, Kind: postgresAppKind, Name: "pg"}, + }, + } + cnpgBk := &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}, Status: cnpgtypes.BackupStatus{BackupID: "20261021T100000"}} + rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: *newSizedBarmanObjectStore()} + oldCreds := "creds-before-edit" + written := cnpgDestination{DestinationPath: "s3://old-bkt/before/edit/", EndpointURL: "https://old.example:9000", S3SecretRef: &oldCreds} + l := &fakeS3Lister{objects: []s3ObjectInfo{{Key: "before/edit/srv/base/20261021T100000/data.tar.gz", Size: 42}}} + r := reconcilerWithLister(t, l) + r.Client = newCNPGStrategyTestClient(t, s3CredsSecret("tenant", oldCreds)) + + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", written, rendered, newPostgresApp("pg", "tenant")) + if err != nil { + t.Fatalf("createCNPGBackupArtifact: %v", err) + } + if l.bucket != "old-bkt" || l.prefix != "before/edit/srv/base/20261021T100000/" { + t.Errorf("listed %s/%s, want the recorded destination old-bkt/before/edit/srv/base/20261021T100000/", l.bucket, l.prefix) + } + if l.conn.Endpoint != "old.example:9000" { + t.Errorf("probed endpoint %q, want the recorded old.example:9000", l.conn.Endpoint) + } + if got.Status.Artifact == nil || got.Status.Artifact.SizeBytes != 42 { + t.Errorf("Artifact = %#v, want SizeBytes 42", got.Status.Artifact) + } +} + +// A backup recorded without a credentials Secret is not measured with the +// Secret the strategy names now: that Secret belongs to another location. +func TestCreateCNPGBackupArtifact_SizeProbeSkipsARecordWithoutCredentials(t *testing.T) { + apiGroup := backupsv1alpha1.DefaultApplicationAPIGroup + j := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "bj-nocreds"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{APIGroup: &apiGroup, Kind: postgresAppKind, Name: "pg"}, + }, + } + cnpgBk := &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}, Status: cnpgtypes.BackupStatus{BackupID: "20261021T100000"}} + rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: *newSizedBarmanObjectStore()} + written := cnpgDestination{DestinationPath: "s3://bkt/tenant/pg/", EndpointURL: "https://s3.example:8443"} + l := &fakeS3Lister{objects: []s3ObjectInfo{{Key: "x", Size: 1}}} + r := reconcilerWithLister(t, l) + r.Client = newCNPGStrategyTestClient(t, s3CredsSecret("tenant", "creds")) + + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", written, rendered, newPostgresApp("pg", "tenant")) + if err != nil { + t.Fatalf("createCNPGBackupArtifact: %v", err) + } + if l.calls != 0 { + t.Errorf("S3 listed %d times with the strategy's Secret for a backup recorded without one", l.calls) + } + if got.Status.Artifact == nil || got.Status.Artifact.SizeBytes != 0 { + t.Errorf("Artifact = %#v, want no size", got.Status.Artifact) + } +} diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 83ce9b41e..190e2db6c 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -219,6 +219,11 @@ const ( // instance pods still have to postdate the rollout's own start. backupCondDestinationWriteHeld = "DestinationWriteHeld" + // Annotation on a cnpg.io/Backup carrying, as JSON, the WAL archive + // destination written by the pass that created it: the destination + // path, the endpoint URL and the name of the credentials Secret. + cnpgWrittenDestinationAnnotation = "backups.cozystack.io/cnpg-written-destination" + cnpgPodRoleLabel = "cnpg.io/podRole" cnpgPodRoleInstance = "instance" ) @@ -526,7 +531,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp "cluster", clusterName, "live", attachment.flavor, "application", specFlavor) } - cnpgBackup, err := r.ensureCNPGBackup(ctx, j, clusterName) + cnpgBackup, err := r.ensureCNPGBackup(ctx, j, clusterName, cnpgDestinationOf(rendered)) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure cnpg.io/Backup: %v", err)) } @@ -546,7 +551,11 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if j.Status.BackupRef != nil { return ctrl.Result{}, nil } - artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, rendered, app) + destination, err := cnpgArtifactDestination(cnpgBackup, rendered) + if err != nil { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf("refusing to create the Backup artifact: %v", err)) + } + artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, destination, rendered, app) if err != nil { return r.failBackupArtifact(ctx, j, err) } @@ -869,7 +878,12 @@ func currentBarmanServerName(c *cnpgtypes.Cluster) string { // ensureCNPGBackup creates a one-shot postgresql.cnpg.io/Backup CR labelled // with the BackupJob, or returns the existing one if a previous reconcile // already created it. Idempotency relies on the OwningJob labels. -func (r *BackupJobReconciler) ensureCNPGBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName string) (*cnpgtypes.Backup, error) { +// +// written is the destination this pass wrote to the ObjectStore. A pass +// reaches the create only after that write: a job without a Backup writes +// the destination on every pass, and a pass that wrote nothing, or wrote it +// and waits for the plugin rollout, returns before this point. +func (r *BackupJobReconciler) ensureCNPGBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName string, written cnpgDestination) (*cnpgtypes.Backup, error) { existing, err := r.findCNPGBackupForJob(ctx, j) if err != nil { return nil, err @@ -877,6 +891,10 @@ func (r *BackupJobReconciler) ensureCNPGBackup(ctx context.Context, j *backupsv1 if existing != nil { return existing, nil } + record, err := json.Marshal(written) + if err != nil { + return nil, fmt.Errorf("encode the WAL archive destination: %w", err) + } obj := &cnpgtypes.Backup{ ObjectMeta: metav1.ObjectMeta{ @@ -887,6 +905,7 @@ func (r *BackupJobReconciler) ensureCNPGBackup(ctx context.Context, j *backupsv1 backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, cnpgClusterLabel: clusterName, }, + Annotations: map[string]string{cnpgWrittenDestinationAnnotation: string(record)}, }, Spec: cnpgtypes.BackupSpec{ Method: cnpgtypes.BackupMethodPlugin, @@ -984,6 +1003,67 @@ func (r *BackupJobReconciler) waitCNPGBackupJob(ctx context.Context, j *backupsv return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil } +// cnpgDestination is the WAL archive destination recorded in +// cnpgWrittenDestinationAnnotation. S3SecretRef is nil when the strategy +// names no credentials Secret. +type cnpgDestination struct { + DestinationPath string `json:"destinationPath"` + EndpointURL string `json:"endpointURL,omitempty"` + S3SecretRef *string `json:"s3SecretRef,omitempty"` +} + +func cnpgDestinationOf(t *strategyv1alpha1.CNPGTemplate) cnpgDestination { + d := cnpgDestination{ + DestinationPath: t.BarmanObjectStore.DestinationPath, + EndpointURL: t.BarmanObjectStore.EndpointURL, + } + if t.BarmanObjectStore.S3Credentials != nil { + name := t.BarmanObjectStore.S3Credentials.SecretRef.Name + d.S3SecretRef = &name + } + return d +} + +// cnpgArtifactDestination returns the destination the artifact of b names: +// the one recorded when b was created. A Backup without the record was +// created by a controller that kept none, and falls back to the strategy +// rendered now. A record that names no destination is an error: the +// strategy may have changed since the write, so it cannot stand in. +func cnpgArtifactDestination(b *cnpgtypes.Backup, rendered *strategyv1alpha1.CNPGTemplate) (cnpgDestination, error) { + raw, ok := b.Annotations[cnpgWrittenDestinationAnnotation] + if !ok { + return cnpgDestinationOf(rendered), nil + } + var d cnpgDestination + if err := json.Unmarshal([]byte(raw), &d); err != nil { + return cnpgDestination{}, fmt.Errorf("read the %s annotation of cnpg.io/Backup %s/%s: %w", cnpgWrittenDestinationAnnotation, b.Namespace, b.Name, err) + } + if d.DestinationPath == "" { + return cnpgDestination{}, fmt.Errorf("the %s annotation of cnpg.io/Backup %s/%s names no destination path", cnpgWrittenDestinationAnnotation, b.Namespace, b.Name) + } + return d, nil +} + +// cnpgProbeStore is the object store the size probe reads: the location +// and the credentials Secret recorded for the backup, with the Secret keys +// and the endpoint CA the record does not carry taken from the strategy. +// After a strategy edit those may not fit the recorded location; the probe +// then reports no size rather than measuring somewhere else. +func cnpgProbeStore(rendered *strategyv1alpha1.BarmanObjectStoreTemplate, destination cnpgDestination) *strategyv1alpha1.BarmanObjectStoreTemplate { + store := rendered.DeepCopy() + store.DestinationPath = destination.DestinationPath + store.EndpointURL = destination.EndpointURL + if destination.S3SecretRef == nil { + store.S3Credentials = nil + } else { + if store.S3Credentials == nil { + store.S3Credentials = &strategyv1alpha1.S3CredentialsTemplate{} + } + store.S3Credentials.SecretRef.Name = *destination.S3SecretRef + } + return store +} + // createCNPGBackupArtifact materialises a Cozystack Backup resource carrying // the metadata callers need to drive a future restore. The source app's // spec.databases / spec.users are snapshotted into Status.UnderlyingResources @@ -995,6 +1075,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( resolved *ResolvedBackupConfig, cnpgBackup *cnpgtypes.Backup, clusterName, serverName, flavor string, + destination cnpgDestination, rendered *strategyv1alpha1.CNPGTemplate, sourceApp *postgresapp.Postgres, ) (*backupsv1alpha1.Backup, error) { @@ -1010,12 +1091,12 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( driverMD := map[string]string{ cnpgBackupNameKey: cnpgBackup.Name, cnpgServerNameKey: serverName, - cnpgDestinationPathKey: rendered.BarmanObjectStore.DestinationPath, - cnpgEndpointURLKey: rendered.BarmanObjectStore.EndpointURL, + cnpgDestinationPathKey: destination.DestinationPath, + cnpgEndpointURLKey: destination.EndpointURL, cnpgClusterNameKey: clusterName, } - if rendered.BarmanObjectStore.S3Credentials != nil { - driverMD[cnpgS3SecretRefKey] = rendered.BarmanObjectStore.S3Credentials.SecretRef.Name + if destination.S3SecretRef != nil { + driverMD[cnpgS3SecretRefKey] = *destination.S3SecretRef } // Copied rather than read back at restore time: barman retention deletes // the cnpg.io/Backup while the artifact can still be restored from. @@ -1048,7 +1129,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( }, } if probe { - backup.Status.Artifact.SizeBytes = r.cnpgArtifactSizeBytes(ctx, j.Namespace, &rendered.BarmanObjectStore, serverName, cnpgBackup.Status.BackupID) + backup.Status.Artifact.SizeBytes = r.cnpgArtifactSizeBytes(ctx, j.Namespace, cnpgProbeStore(&rendered.BarmanObjectStore, destination), serverName, cnpgBackup.Status.BackupID) } if j.Spec.PlanRef != nil { backup.Spec.PlanRef = j.Spec.PlanRef diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 8f0035aa6..23e4c182f 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -1075,7 +1075,7 @@ func TestCreateCNPGBackupArtifact_AlreadyExistsReturnsExisting(t *testing.T) { } sourceApp := newPostgresApp("pg", "tenant") - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", rendered, sourceApp) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", cnpgDestinationOf(rendered), rendered, sourceApp) if err != nil { t.Fatalf("expected AlreadyExists to be swallowed, got error %v", err) } @@ -2207,7 +2207,7 @@ func TestEnsureCNPGBackup_UsesPluginMethod(t *testing.T) { c := newCNPGStrategyTestClient(t, j) r := &BackupJobReconciler{Client: c} - bk, err := r.ensureCNPGBackup(context.Background(), j, "postgres-app") + bk, err := r.ensureCNPGBackup(context.Background(), j, "postgres-app", cnpgDestination{DestinationPath: "s3://bucket/"}) if err != nil { t.Fatalf("ensureCNPGBackup: %v", err) } @@ -5311,7 +5311,7 @@ func TestCreateCNPGBackupArtifact_RecordsMajorVersion(t *testing.T) { rendered := &strategyv1alpha1.CNPGTemplate{ BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://b/"}, } - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -5492,3 +5492,166 @@ func TestReconcileCNPGRestore_RefusesCrossMajorRestore(t *testing.T) { }) } } + +func (f *cnpgRolloutFixture) setStrategyDestination(destination, endpoint, secret string) { + f.t.Helper() + strategy := &strategyv1alpha1.CNPG{} + if err := f.c.Get(context.Background(), client.ObjectKey{Name: "cnpg-strategy"}, strategy); err != nil { + f.t.Fatalf("get strategy: %v", err) + } + strategy.Spec.Template.BarmanObjectStore.DestinationPath = destination + strategy.Spec.Template.BarmanObjectStore.EndpointURL = endpoint + strategy.Spec.Template.BarmanObjectStore.S3Credentials = &strategyv1alpha1.S3CredentialsTemplate{SecretRef: corev1.LocalObjectReference{Name: secret}} + if err := f.c.Update(context.Background(), strategy); err != nil { + f.t.Fatalf("update strategy: %v", err) + } +} + +// completeOwnBackup applies edit, when given, to the job's cnpg.io/Backup and +// marks it completed. +func (f *cnpgRolloutFixture) completeOwnBackup(edit func(b *cnpgtypes.Backup)) { + f.t.Helper() + backups := &cnpgtypes.BackupList{} + if err := f.c.List(context.Background(), backups, client.InNamespace(rolloutNS)); err != nil { + f.t.Fatalf("list cnpg.io/Backups: %v", err) + } + for i := range backups.Items { + b := &backups.Items[i] + if b.Labels[backupsv1alpha1.OwningJobNameLabel] != "bj" { + continue + } + if edit != nil { + edit(b) + } + b.Status.Phase = cnpgBackupPhaseComplete + if err := f.c.Update(context.Background(), b); err != nil { + f.t.Fatalf("complete cnpg.io/Backup: %v", err) + } + return + } + f.t.Fatalf("the job has no cnpg.io/Backup") +} + +func (f *cnpgRolloutFixture) artifact() *backupsv1alpha1.Backup { + f.t.Helper() + artifact := &backupsv1alpha1.Backup{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, artifact); err != nil { + if apierrors.IsNotFound(err) { + return nil + } + f.t.Fatalf("get Backup artifact: %v", err) + } + return artifact +} + +// The destination is written by the pass that creates the cnpg.io/Backup and +// not again while it runs, so the artifact has to name what that pass wrote: +// a strategy edited while the backup runs does not reach the backup, and must +// not reach its artifact either. The BackupJob, which a tenant can edit, +// carries no part of it. +func TestReconcileCNPG_ArtifactNamesTheDestinationItsBackupWasCreatedWith(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.setStrategyDestination("s3://bucket/", "https://s3.one", "creds-one") + + j, backups := f.pass() + if len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups after the first pass, want 1; Ready = %+v", len(backups), apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } + if got := f.liveDestination(); got != "s3://bucket/" { + t.Fatalf("destination = %q, want s3://bucket/", got) + } + want := `{"destinationPath":"s3://bucket/","endpointURL":"https://s3.one","s3SecretRef":"creds-one"}` + if got := backups[0].Annotations[cnpgWrittenDestinationAnnotation]; got != want { + t.Fatalf("%s on the created cnpg.io/Backup = %q, want %q", cnpgWrittenDestinationAnnotation, got, want) + } + + f.setStrategyDestination("s3://edited/", "https://s3.two", "creds-two") + j.Annotations = map[string]string{cnpgWrittenDestinationAnnotation: `{"destinationPath":"s3://tenant/","endpointURL":"https://tenant","s3SecretRef":"creds-one"}`} + if err := f.c.Update(context.Background(), j); err != nil { + t.Fatalf("annotate BackupJob: %v", err) + } + f.completeOwnBackup(nil) + j, _ = f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Fatalf("phase = %q (%s), want Succeeded", j.Status.Phase, j.Status.Message) + } + artifact := f.artifact() + if artifact == nil { + t.Fatalf("no Backup artifact") + } + md := artifact.Spec.DriverMetadata + if md[cnpgDestinationPathKey] != "s3://bucket/" || md[cnpgEndpointURLKey] != "https://s3.one" || md[cnpgS3SecretRefKey] != "creds-one" { + t.Fatalf("artifact driver metadata = %v, want the destination written with the Backup (s3://bucket/, https://s3.one, creds-one)", md) + } +} + +// A strategy without credentials records none, and the artifact names none. +func TestReconcileCNPG_ArtifactOfARecordWithoutCredentials(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://bucket/") + if _, backups := f.pass(); len(backups) != 1 || backups[0].Annotations[cnpgWrittenDestinationAnnotation] != `{"destinationPath":"s3://bucket/"}` { + t.Fatalf("cnpg.io/Backups after the first pass = %+v, want one recording only s3://bucket/", backups) + } + f.setStrategyDestination("s3://edited/", "https://s3.two", "creds-two") + f.completeOwnBackup(nil) + j, _ := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Fatalf("phase = %q (%s), want Succeeded", j.Status.Phase, j.Status.Message) + } + md := f.artifact().Spec.DriverMetadata + if _, ok := md[cnpgS3SecretRefKey]; ok || md[cnpgDestinationPathKey] != "s3://bucket/" || md[cnpgEndpointURLKey] != "" { + t.Fatalf("artifact driver metadata = %v, want s3://bucket/ with no endpoint and no credentials", md) + } +} + +// A record that names no usable destination cannot say where the backup is, +// so no artifact is created rather than one pointing at the strategy as it +// reads now. +func TestReconcileCNPG_ArtifactRefusedForAnUnusableDestinationRecord(t *testing.T) { + for name, value := range map[string]string{ + "empty": "", + "unreadable": "{not json", + "not an object": `"s3://bucket/"`, + "null": "null", + "no fields": "{}", + "empty destination": `{"destinationPath":"","endpointURL":"https://s3.one"}`, + // Decoding sets the destination path and skips the mistyped + // endpoint, which would leave the artifact on the default one. + "mistyped endpoint": `{"destinationPath":"s3://bucket/","endpointURL":7}`, + } { + t.Run(name, func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + if _, backups := f.pass(); len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups after the first pass, want 1", len(backups)) + } + f.completeOwnBackup(func(b *cnpgtypes.Backup) { + if b.Annotations == nil { + b.Annotations = map[string]string{} + } + b.Annotations[cnpgWrittenDestinationAnnotation] = value + }) + j, _ := f.pass() + if f.artifact() != nil { + t.Fatalf("an artifact was created from the record %q", value) + } + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(j.Status.Message, cnpgWrittenDestinationAnnotation) { + t.Fatalf("phase = %q (%s), want Failed naming %s", j.Status.Phase, j.Status.Message, cnpgWrittenDestinationAnnotation) + } + }) + } +} + +// A cnpg.io/Backup created by a controller that recorded nothing keeps +// getting its artifact from the strategy. +func TestReconcileCNPG_ArtifactOfABackupWithoutARecord(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://bucket/") + f.seedCNPGBackup("bj-legacy", "bj", rolloutCluster, cnpgBackupPhaseComplete) + + j, _ := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Fatalf("phase = %q (%s), want Succeeded", j.Status.Phase, j.Status.Message) + } + artifact := f.artifact() + if artifact == nil || artifact.Spec.DriverMetadata[cnpgDestinationPathKey] != "s3://bucket/" { + t.Fatalf("artifact = %+v, want one built from the strategy", artifact) + } +} From e5ccde82e2258a55e97b0dd6e5375caed5b59b86 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 9 Nov 2026 10:47:21 +0300 Subject: [PATCH 13/26] fix(postgres): read cnpg Backups from the apiserver before writing the destination The queue that keeps two BackupJobs of one application from writing the WAL archive destination at once listed cnpg.io/Backups from the informer cache. The controller runs one reconcile at a time under leader election, so a Backup created by one job's pass already exists when the next pass starts, but the cache can still miss it. The next job then took the queue as empty, rewrote the destination under the running backup and left that backup's recorded destination naming a place its WAL no longer went. A job could likewise miss its own fresh Backup, write the destination again and create a second Backup. The queue now lists Backups from the apiserver, and a job that finds no Backup of its own in the cache checks the apiserver before it writes or creates one. Only a leader handover, when two processes reconcile for a moment, can still let two jobs through. The pass that creates the Backup no longer looks it up a second time right before the create. Nothing can create it in between, and once the lookup can reach the apiserver, a failed second lookup would come after the destination write and fail the job instead of retrying. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 35 +++-- .../cnpgstrategy_controller_test.go | 130 +++++++++++++++++- 2 files changed, 150 insertions(+), 15 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 190e2db6c..3eb3421d6 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -531,7 +531,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp "cluster", clusterName, "live", attachment.flavor, "application", specFlavor) } - cnpgBackup, err := r.ensureCNPGBackup(ctx, j, clusterName, cnpgDestinationOf(rendered)) + cnpgBackup, err := r.ensureCNPGBackup(ctx, j, clusterName, existingBackup, cnpgDestinationOf(rendered)) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure cnpg.io/Backup: %v", err)) } @@ -876,18 +876,16 @@ func currentBarmanServerName(c *cnpgtypes.Cluster) string { } // ensureCNPGBackup creates a one-shot postgresql.cnpg.io/Backup CR labelled -// with the BackupJob, or returns the existing one if a previous reconcile -// already created it. Idempotency relies on the OwningJob labels. +// with the BackupJob, or returns existing, the job's Backup as looked up at +// the start of the pass. It does not look again: a reconcile of the same +// job cannot run in between, and a failed lookup here would come after the +// destination write and fail the job. // // written is the destination this pass wrote to the ObjectStore. A pass // reaches the create only after that write: a job without a Backup writes // the destination on every pass, and a pass that wrote nothing, or wrote it // and waits for the plugin rollout, returns before this point. -func (r *BackupJobReconciler) ensureCNPGBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName string, written cnpgDestination) (*cnpgtypes.Backup, error) { - existing, err := r.findCNPGBackupForJob(ctx, j) - if err != nil { - return nil, err - } +func (r *BackupJobReconciler) ensureCNPGBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName string, existing *cnpgtypes.Backup, written cnpgDestination) (*cnpgtypes.Backup, error) { if existing != nil { return existing, nil } @@ -923,17 +921,27 @@ func (r *BackupJobReconciler) ensureCNPGBackup(ctx context.Context, j *backupsv1 // findCNPGBackupForJob returns the cnpg.io/Backup labelled with the // BackupJob's OwningJob{Name,Namespace}, if any. Returns (nil, nil) when // no match is found. +// +// A miss in the cache is checked against the apiserver: the cache can lag +// behind a Backup the previous pass created, and taking that miss as no +// Backup would write the destination under it and create a second one. func (r *BackupJobReconciler) findCNPGBackupForJob(ctx context.Context, j *backupsv1alpha1.BackupJob) (*cnpgtypes.Backup, error) { - list := &cnpgtypes.BackupList{} - if err := r.List(ctx, list, + opts := []client.ListOption{ client.InNamespace(j.Namespace), client.MatchingLabels{ backupsv1alpha1.OwningJobNameLabel: j.Name, backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, }, - ); err != nil { + } + list := &cnpgtypes.BackupList{} + if err := r.List(ctx, list, opts...); err != nil { return nil, err } + if len(list.Items) == 0 { + if err := r.apiReader().List(ctx, list, opts...); err != nil { + return nil, err + } + } if len(list.Items) == 0 { return nil, nil } @@ -944,9 +952,12 @@ func (r *BackupJobReconciler) findCNPGBackupForJob(ctx context.Context, j *backu // running and whose cnpg.io/Backup of clusterName has not finished, or "" when // there is none. A Backup left behind by a finished or deleted job does not // hold the queue. +// +// The Backups are read from the apiserver, not the cache, which can still +// miss a Backup another job's earlier pass created. func (r *BackupJobReconciler) otherCNPGBackupInFlight(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName string) (string, error) { list := &cnpgtypes.BackupList{} - if err := r.List(ctx, list, client.InNamespace(j.Namespace)); err != nil { + if err := r.apiReader().List(ctx, list, client.InNamespace(j.Namespace)); err != nil { return "", err } var holders []string diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 23e4c182f..de525f0a7 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "slices" "strings" "testing" "time" @@ -2207,7 +2208,7 @@ func TestEnsureCNPGBackup_UsesPluginMethod(t *testing.T) { c := newCNPGStrategyTestClient(t, j) r := &BackupJobReconciler{Client: c} - bk, err := r.ensureCNPGBackup(context.Background(), j, "postgres-app", cnpgDestination{DestinationPath: "s3://bucket/"}) + bk, err := r.ensureCNPGBackup(context.Background(), j, "postgres-app", nil, cnpgDestination{DestinationPath: "s3://bucket/"}) if err != nil { t.Fatalf("ensureCNPGBackup: %v", err) } @@ -2567,8 +2568,8 @@ func (f *cnpgRolloutFixture) seedOtherBackupJob(name string, phase backupsv1alph func TestReconcileCNPG_RunningBackupDoesNotReapplyObjectStore(t *testing.T) { f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") - // Two jobs can pass the queue together, since it reads the cache; once - // both have a Backup neither may wait on the other. + // Two jobs can still pass the queue together, across a leader handover; + // once both have a Backup neither may wait on the other. f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) f.seedCNPGBackup("bj-other-cnpg", "bj-other", rolloutCluster, "running") writes := 0 @@ -5655,3 +5656,126 @@ func TestReconcileCNPG_ArtifactOfABackupWithoutARecord(t *testing.T) { t.Fatalf("artifact = %+v, want one built from the strategy", artifact) } } + +// cacheLaggingBehind makes the reconciler's cached client miss the named +// cnpg.io/Backups, as an informer does right after they are created, while +// its uncached reader sees them. +func (f *cnpgRolloutFixture) cacheLaggingBehind(hidden ...string) { + f.r.APIReader = f.c + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if err := cl.List(ctx, list, opts...); err != nil { + return err + } + if backups, ok := list.(*cnpgtypes.BackupList); ok { + backups.Items = slices.DeleteFunc(backups.Items, func(b cnpgtypes.Backup) bool { + return slices.Contains(hidden, b.Name) + }) + } + return nil + }, + }) +} + +// Reconciles run one at a time, so a Backup created by one pass exists by +// the next; the queue has to see it even when the cache does not yet, or +// the next job rewrites the destination under it and the record on that +// Backup no longer names where its WAL goes. +func TestReconcileCNPG_QueueSeesABackupTheCacheHasNotCaught(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) + f.seedCNPGBackup("bj-other-cnpg", "bj-other", rolloutCluster, "running") + f.cacheLaggingBehind("bj-other-cnpg") + + j, backups := f.pass() + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForOtherBackup" { + t.Fatalf("Ready = %+v, want WaitingForOtherBackup", ready) + } + if got := f.liveDestination(); got != "s3://other/" { + t.Fatalf("destination = %q, rewritten under the other job's Backup", got) + } + if len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups, want only the other job's", len(backups)) + } +} + +// The job's own Backup, missing from the cache right after it was created, +// is neither created again nor written under. +func TestReconcileCNPG_OwnBackupTheCacheHasNotCaught(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") + f.cacheLaggingBehind("bj-cnpg") + + _, backups := f.pass() + if len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups, want the job's one", len(backups)) + } + if got := f.liveDestination(); got != "s3://other/" { + t.Fatalf("destination = %q, rewritten under the job's own Backup", got) + } +} + +// failingBackupLists makes the uncached reader fail the cnpg.io/Backup lists +// for which fail, given whether the list selects the job's own Backup by +// label and how many such lists came before, returns true. +func (f *cnpgRolloutFixture) failingBackupLists(fail func(own bool, n int) bool) { + counts := map[bool]int{} + f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*cnpgtypes.BackupList); ok { + o := &client.ListOptions{} + o.ApplyOptions(opts) + own := o.LabelSelector != nil && !o.LabelSelector.Empty() + counts[own]++ + if fail(own, counts[own]) { + return apierrors.NewServiceUnavailable("apiserver unavailable") + } + } + return cl.List(ctx, list, opts...) + }, + }) +} + +// A failed apiserver read of the Backups is retried, not taken as the job +// failing: nothing has been written yet that the retry would not redo. +func TestReconcileCNPG_BackupListErrorIsReturned(t *testing.T) { + for name, own := range map[string]bool{"own Backup": true, "queue": false} { + t.Run(name, func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.failingBackupLists(func(o bool, _ int) bool { return o == own }) + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(context.Background(), j, f.resolved); err == nil { + t.Fatalf("reconcileCNPG swallowed the Backup list error") + } + got := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, got); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if got.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob failed on a Backup list error: %s", got.Status.Message) + } + if dest := f.liveDestination(); dest != "s3://other/" { + t.Fatalf("destination = %q, written although the Backups could not be read", dest) + } + }) + } +} + +// The pass that writes the destination looks its own Backup up once, at the +// start: a second lookup before the create could only fail, after the write, +// and fail the job with it. +func TestReconcileCNPG_LooksUpItsOwnBackupOncePerPass(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f.failingBackupLists(func(own bool, n int) bool { return own && n > 1 }) + + j, backups := f.pass() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob failed: %s", j.Status.Message) + } + if len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups, want 1", len(backups)) + } +} From 325d2b815c6b310c33d415957442d08a79197b77 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 9 Nov 2026 14:34:04 +0300 Subject: [PATCH 14/26] fix(postgres): keep the plugin attach time when its status write is lost The rollout check took the attach time from the PluginRolledOut condition on the BackupJob, which the pass that attaches the plugin writes only after the Cluster apply went through. When that status write is lost to a conflict or a controller restart, the next pass finds the plugin attached and falls back to the latch written before the attach. An instance recreated between the latch and the attach then counts as one that rolled with the plugin, and the cnpg.io/Backup is created against an instance that has no plugin sidecar; a latch older than the deadline also fails a rollout that has only just begun. The apply that attaches the plugin now records the time on the Cluster itself, so the record cannot be lost apart from the attach. The rollout check and its deadline use the later of the two times. A record that does not parse fails the job rather than guess which instances rolled. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 56 +++++++-- .../cnpgstrategy_controller_test.go | 112 ++++++++++++++++++ 2 files changed, 157 insertions(+), 11 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 3eb3421d6..5869103ca 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -177,14 +177,15 @@ const ( // Cap on the wall-clock time a BackupJob spends before its // cnpg.io/Backup exists on each of two waits. The plugin rollout is - // counted from the PluginRolledOut condition, or from the release + // counted from the attach, the later of the PluginRolledOut condition and + // the Cluster's cnpgPluginAttachedAtAnnotation, or from the release // recorded in DestinationWriteHeld when that is later. Retrying the WAL // archive destination write is counted from the first failure since the // last successful write or the last wait for another backup or a - // restore. A Backup that exists is - // not capped: CloudNativePG keeps a healthy one pending while another - // backup of the same Cluster runs, or while it restarts one on another - // instance, so no fixed deadline tells those apart from a stuck one. + // restore. A Backup that exists is not capped: CloudNativePG keeps a + // healthy one pending while another backup of the same Cluster runs, or + // while it restarts one on another instance, so no fixed deadline tells + // those apart from a stuck one. cnpgDefaultBackupDeadline = 30 * time.Minute cnpgClusterHealthyPhase = "Cluster in healthy state" @@ -195,9 +196,10 @@ const ( // instance pod spec (the plugin injects its sidecar), so CNPG rolls every // instance, and a cnpg.io/Backup created meanwhile fails with "requested // plugin is not available" or "instance manager was restarted during - // backup" and never recovers. False holds the Backup back; its - // LastTransitionTime is what the instance pods must postdate (see - // cnpgReasonAttachingPlugin and cnpgPluginRolloutPending). + // backup" and never recovers. False holds the Backup back; the instance + // pods must postdate its LastTransitionTime and the Cluster's + // cnpgPluginAttachedAtAnnotation (see cnpgReasonAttachingPlugin and + // cnpgPluginRolloutPending). backupCondPluginRolledOut = "PluginRolledOut" // Reason of the PluginRolledOut latch recorded before the write that @@ -224,6 +226,12 @@ const ( // path, the endpoint URL and the name of the credentials Secret. cnpgWrittenDestinationAnnotation = "backups.cozystack.io/cnpg-written-destination" + // Annotation on a cnpg.io/Cluster carrying, as RFC 3339, when a backup + // job attached the barman-cloud plugin. It is written by the same apply + // that attaches the plugin, so unlike the PluginRolledOut condition it + // cannot be lost to a failed BackupJob status write after the attach. + cnpgPluginAttachedAtAnnotation = "backups.cozystack.io/barman-plugin-attached-at" + cnpgPodRoleLabel = "cnpg.io/podRole" cnpgPodRoleInstance = "instance" ) @@ -487,12 +495,25 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil } - pending, err := r.cnpgPluginRolloutPending(ctx, j.Namespace, clusterName, attachment, rollout.LastTransitionTime) + // The Cluster's record covers an attach whose status write was lost. + attachedAt := rollout.LastTransitionTime + if attachment.attachedAt != "" { + recorded, err := time.Parse(time.RFC3339, attachment.attachedAt) + if err != nil { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "cannot tell when the barman-cloud plugin was attached: the %s annotation of cnpg.io/Cluster %s/%s: %v", + cnpgPluginAttachedAtAnnotation, j.Namespace, clusterName, err)) + } + if recorded.After(attachedAt.Time) { + attachedAt = metav1.NewTime(recorded) + } + } + pending, err := r.cnpgPluginRolloutPending(ctx, j.Namespace, clusterName, attachment, attachedAt) if err != nil { return ctrl.Result{}, err } if pending != "" { - deadlineFrom := rollout.LastTransitionTime + deadlineFrom := attachedAt if held := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationWriteHeld); held != nil && held.LastTransitionTime.After(deadlineFrom.Time) { deadlineFrom = held.LastTransitionTime @@ -744,6 +765,7 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name flavor: cnpgImageFlavor(existing.Spec.ImageName), clusterStatus: existing.Status, } + attachment.attachedAt = existing.Annotations[cnpgPluginAttachedAtAnnotation] if live := currentBarmanServerName(existing); live != "" { attachment.serverName = live } else { @@ -788,6 +810,15 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name patch := newCNPGClusterPatch(namespace, clusterName) patch.Spec.Plugins = []cnpgtypes.PluginConfiguration{buildBarmanPlugin(objStoreName, serverName)} + // Re-sent unchanged on later applies: the field manager owns it, and an + // apply that left it out would delete it. + stamp := existing.Annotations[cnpgPluginAttachedAtAnnotation] + if attachment.missing { + stamp = metav1.Now().UTC().Format(time.RFC3339) + } + if stamp != "" { + patch.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: stamp} + } if err := r.Patch(ctx, patch, client.Apply, client.FieldOwner(cnpgFieldManager), client.ForceOwnership); err != nil { return cnpgPluginAttachment{}, err } @@ -802,7 +833,10 @@ type cnpgPluginAttachment struct { // flavor is the image flavor the live Cluster runs. flavor string // missing reports a Cluster that carried no barman-cloud plugin. - missing bool + missing bool + // attachedAt is the cnpgPluginAttachedAtAnnotation the Cluster carried, + // "" when no backup job attached the plugin. + attachedAt string clusterStatus cnpgtypes.ClusterStatus } diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index de525f0a7..255be9a27 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -2924,6 +2924,118 @@ func TestReconcileCNPG_PluginRolloutCountsFromTheSuccessfulAttach(t *testing.T) } } +// The status write that records the attach can be lost after the attach +// itself went through, by a conflict or a restart; an instance recreated +// between the latch and the attach still has to roll, and the rollout +// deadline still counts from the attach. +func TestReconcileCNPG_LostAttachRecordStillWaitsForTheRollout(t *testing.T) { + latchedAt := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)).Truncate(time.Second) + oldPod := newRolloutInstancePod(latchedAt.Add(-time.Hour)) + f := newCNPGRolloutFixture(t, newRolloutBackupJob(latchedAt.Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), oldPod) + + j, _ := f.pass() // latch + latch := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) + if latch == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + latch.LastTransitionTime = metav1.NewTime(latchedAt) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("age the latch: %v", err) + } + f.replacePod(oldPod, newRolloutInstancePod(latchedAt.Add(time.Minute))) + + base := f.r.Client + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + return apierrors.NewConflict(backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource(), obj.GetName(), errors.New("the object has been modified")) + }, + }) + j = &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(context.Background(), j, f.resolved); err == nil { + t.Fatalf("the pass that attached the plugin reported no lost status write") + } + f.r.Client = base + + attached := &cnpgtypes.Cluster{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: rolloutCluster}, attached); err != nil { + t.Fatalf("get Cluster: %v", err) + } + if len(attached.Spec.Plugins) == 0 { + t.Fatalf("the plugin was not attached") + } + live := newRolloutCluster(cnpgClusterHealthyPhase, attached.Spec.Plugins...) + live.Annotations = attached.Annotations + f.observeCNPG(live) + + var backups []cnpgtypes.Backup + for range 3 { + if j, backups = f.pass(); len(backups) != 0 || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + break + } + } + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created against an instance recreated before the attach: %+v", backups) + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the job failed instead of waiting for the rollout: %s", j.Status.Message) + } +} + +// A later write to a Cluster that already carries the plugin re-sends the +// attach record as it is: moving it would make the instances that rolled +// with the plugin look older than the attach. +func TestReconcileCNPG_LaterWriteKeepsTheAttachRecord(t *testing.T) { + const stamp = "2026-01-02T03:04:05Z" + cluster := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) + cluster.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: stamp} + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), cluster, + newRolloutInstancePod(time.Now().Add(-time.Hour))) + + var sent []map[string]string + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgtypes.Cluster); ok { + sent = append(sent, obj.GetAnnotations()) + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + if _, backups := f.pass(); len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups, want the one this pass creates", len(backups)) + } + if len(sent) != 1 { + t.Fatalf("got %d Cluster writes, want 1", len(sent)) + } + if got := sent[0][cnpgPluginAttachedAtAnnotation]; got != stamp { + t.Errorf("the write sent %s = %q, want the recorded %q", cnpgPluginAttachedAtAnnotation, got, stamp) + } +} + +// An attach record that does not parse cannot tell which instances rolled +// with the plugin, so the job fails naming it instead of guessing. +func TestReconcileCNPG_UnreadableAttachRecordFailsTheJob(t *testing.T) { + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), newRolloutInstancePod(time.Now().Add(-time.Hour))) + if j, _ := f.pass(); apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + live := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) + live.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: "yesterday"} + f.observeCNPG(live) + + j, backups := f.pass() + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created with an unreadable attach record: %+v", backups) + } + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(j.Status.Message, cnpgPluginAttachedAtAnnotation) { + t.Errorf("phase %q, message %q; want Failed naming %s", j.Status.Phase, j.Status.Message, cnpgPluginAttachedAtAnnotation) + } +} + // A plugin attached by someone else after the latch, another backup job or // the chart re-rendering a restored Cluster outside the platform flow, // started the rollout before this job's write, which only finds it there: From 8d92aee796edaa1d4347b964e1d06de9d8fef655 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 9 Nov 2026 14:40:44 +0300 Subject: [PATCH 15/26] test(postgres): pin that an older attach record keeps the latch The rollout check takes the later of the latch and the Cluster's attach record. A record left by an earlier attach of a plugin since removed is older than the latch when someone who keeps no record attaches the plugin again, and taking it would accept an instance recreated before the latch as one that rolled with the plugin. The record is absent not only when no backup job attached the plugin but also when the chart did, or a controller that kept no record, so the comment on the field says that. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 3 +- .../cnpgstrategy_controller_test.go | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 5869103ca..37597678d 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -835,7 +835,8 @@ type cnpgPluginAttachment struct { // missing reports a Cluster that carried no barman-cloud plugin. missing bool // attachedAt is the cnpgPluginAttachedAtAnnotation the Cluster carried, - // "" when no backup job attached the plugin. + // "" when it carries no record: the plugin was attached by the chart, or + // before the record existed. attachedAt string clusterStatus cnpgtypes.ClusterStatus } diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 255be9a27..b9a10b56e 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -2985,6 +2985,44 @@ func TestReconcileCNPG_LostAttachRecordStillWaitsForTheRollout(t *testing.T) { } } +// A record older than the latch is left from an earlier attach of a plugin +// since removed; the plugin found now was attached by someone who keeps no +// record, after the latch, so an instance recreated between the record and +// the latch still has to roll. +func TestReconcileCNPG_AttachRecordOlderThanTheLatchKeepsTheLatch(t *testing.T) { + latchedAt := time.Now().Add(-10 * time.Minute).Truncate(time.Second) + oldPod := newRolloutInstancePod(latchedAt.Add(-2 * time.Hour)) + f := newCNPGRolloutFixture(t, newRolloutBackupJob(latchedAt.Add(-2*time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), oldPod) + + j, _ := f.pass() // latch + latch := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) + if latch == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + latch.LastTransitionTime = metav1.NewTime(latchedAt) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("age the latch: %v", err) + } + f.replacePod(oldPod, newRolloutInstancePod(latchedAt.Add(-time.Minute))) + live := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) + live.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: latchedAt.Add(-time.Hour).UTC().Format(time.RFC3339)} + f.observeCNPG(live) + + var backups []cnpgtypes.Backup + for range 3 { + if j, backups = f.pass(); len(backups) != 0 || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + break + } + } + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created against an instance recreated before the latch: %+v", backups) + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the job failed instead of waiting for the rollout: %s", j.Status.Message) + } +} + // A later write to a Cluster that already carries the plugin re-sends the // attach record as it is: moving it would make the instances that rolled // with the plugin look older than the attach. From fe03589d9136e2d8c6152c3a518d1e443aae0855 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 9 Nov 2026 15:42:34 +0300 Subject: [PATCH 16/26] test(postgres): cover a lost attach record on the retry of a failed attach A status write that fails with the apiserver unavailable takes the same path as one lost to a conflict, but the attach it follows can itself be the retry of an apply that failed first, which leaves its own condition on the job. The test now runs that sequence as well, so the rollout check is held to it whichever way the record was lost. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller_test.go | 133 +++++++++++------- 1 file changed, 81 insertions(+), 52 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index b9a10b56e..4753dda68 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -2925,63 +2925,92 @@ func TestReconcileCNPG_PluginRolloutCountsFromTheSuccessfulAttach(t *testing.T) } // The status write that records the attach can be lost after the attach -// itself went through, by a conflict or a restart; an instance recreated -// between the latch and the attach still has to roll, and the rollout -// deadline still counts from the attach. +// itself went through, by a conflict, an apiserver that is briefly +// unavailable, or a restart, including on the retry of an attach that +// failed; an instance recreated between the latch and the attach still has +// to roll, and the rollout deadline still counts from the attach. func TestReconcileCNPG_LostAttachRecordStillWaitsForTheRollout(t *testing.T) { - latchedAt := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)).Truncate(time.Second) - oldPod := newRolloutInstancePod(latchedAt.Add(-time.Hour)) - f := newCNPGRolloutFixture(t, newRolloutBackupJob(latchedAt.Add(-time.Hour)), - newRolloutCluster(cnpgClusterHealthyPhase), oldPod) + jobs := backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource() + for _, tc := range []struct { + name string + failFirstAttach bool + statusWriteError error + }{ + {name: "conflict", statusWriteError: apierrors.NewConflict(jobs, "bj", errors.New("the object has been modified"))}, + {name: "retried attach, apiserver unavailable", failFirstAttach: true, statusWriteError: apierrors.NewServiceUnavailable("the server is currently unable to handle the request")}, + } { + t.Run(tc.name, func(t *testing.T) { + latchedAt := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)).Truncate(time.Second) + oldPod := newRolloutInstancePod(latchedAt.Add(-time.Hour)) + f := newCNPGRolloutFixture(t, newRolloutBackupJob(latchedAt.Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), oldPod) - j, _ := f.pass() // latch - latch := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) - if latch == nil { - t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) - } - latch.LastTransitionTime = metav1.NewTime(latchedAt) - if err := f.c.Status().Update(context.Background(), j); err != nil { - t.Fatalf("age the latch: %v", err) - } - f.replacePod(oldPod, newRolloutInstancePod(latchedAt.Add(time.Minute))) + j, _ := f.pass() // latch + latch := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) + if latch == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + latch.LastTransitionTime = metav1.NewTime(latchedAt) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("age the latch: %v", err) + } + f.replacePod(oldPod, newRolloutInstancePod(latchedAt.Add(time.Minute))) - base := f.r.Client - f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ - SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { - return apierrors.NewConflict(backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource(), obj.GetName(), errors.New("the object has been modified")) - }, - }) - j = &backupsv1alpha1.BackupJob{} - if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { - t.Fatalf("get BackupJob: %v", err) - } - if _, err := f.r.reconcileCNPG(context.Background(), j, f.resolved); err == nil { - t.Fatalf("the pass that attached the plugin reported no lost status write") - } - f.r.Client = base + base := f.r.Client + if tc.failFirstAttach { + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgtypes.Cluster); ok { + return apierrors.NewServiceUnavailable("the server is currently unable to handle the request") + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + if j, _ = f.pass(); apimeta.IsStatusConditionTrue(j.Status.Conditions, backupCondPluginRolledOut) { + t.Fatalf("a failed attach reported the rollout done: %+v", j.Status.Conditions) + } + if applied := apimeta.FindStatusCondition(j.Status.Conditions, backupCondDestinationApplied); applied == nil || applied.Reason != "ClusterPluginApplyRetrying" { + t.Fatalf("%s = %+v, want the attach retrying", backupCondDestinationApplied, applied) + } + } + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + return tc.statusWriteError + }, + }) + j = &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(context.Background(), j, f.resolved); err == nil { + t.Fatalf("the pass that attached the plugin reported no lost status write") + } + f.r.Client = base - attached := &cnpgtypes.Cluster{} - if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: rolloutCluster}, attached); err != nil { - t.Fatalf("get Cluster: %v", err) - } - if len(attached.Spec.Plugins) == 0 { - t.Fatalf("the plugin was not attached") - } - live := newRolloutCluster(cnpgClusterHealthyPhase, attached.Spec.Plugins...) - live.Annotations = attached.Annotations - f.observeCNPG(live) + attached := &cnpgtypes.Cluster{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: rolloutCluster}, attached); err != nil { + t.Fatalf("get Cluster: %v", err) + } + if len(attached.Spec.Plugins) == 0 { + t.Fatalf("the plugin was not attached") + } + live := newRolloutCluster(cnpgClusterHealthyPhase, attached.Spec.Plugins...) + live.Annotations = attached.Annotations + f.observeCNPG(live) - var backups []cnpgtypes.Backup - for range 3 { - if j, backups = f.pass(); len(backups) != 0 || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { - break - } - } - if len(backups) != 0 { - t.Fatalf("a cnpg.io/Backup was created against an instance recreated before the attach: %+v", backups) - } - if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { - t.Fatalf("the job failed instead of waiting for the rollout: %s", j.Status.Message) + var backups []cnpgtypes.Backup + for range 3 { + if j, backups = f.pass(); len(backups) != 0 || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + break + } + } + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created against an instance recreated before the attach: %+v", backups) + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the job failed instead of waiting for the rollout: %s", j.Status.Message) + } + }) } } From 8a631311a7ac4f751c14e11742182801730ad4f2 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 9 Nov 2026 15:51:56 +0300 Subject: [PATCH 17/26] fix(postgres): fail a backup job whose plugin attach record is in the future The rollout check takes the later of the latch and the Cluster's attach record, and the record is never rewritten while the plugin stays attached. A record that parses but lies in the future made every instance look older than the plugin and counted the rollout deadline from that time, so the job waited past the deadline by as far as the record lay ahead, without end for one far enough out. Such a record says no more about when the plugin was attached than one that does not parse, and fails the job the same way. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 4 ++ .../cnpgstrategy_controller_test.go | 39 ++++++++++++------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 37597678d..ac58fa4bc 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -499,6 +499,10 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp attachedAt := rollout.LastTransitionTime if attachment.attachedAt != "" { recorded, err := time.Parse(time.RFC3339, attachment.attachedAt) + if recorded.After(time.Now()) { + // Every instance would predate it, and the deadline would count from it. + err = fmt.Errorf("%s is in the future", attachment.attachedAt) + } if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( "cannot tell when the barman-cloud plugin was attached: the %s annotation of cnpg.io/Cluster %s/%s: %v", diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 4753dda68..2f116734b 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3083,23 +3083,32 @@ func TestReconcileCNPG_LaterWriteKeepsTheAttachRecord(t *testing.T) { } // An attach record that does not parse cannot tell which instances rolled -// with the plugin, so the job fails naming it instead of guessing. +// with the plugin, so the job fails naming it instead of guessing. One in the +// future would hold every instance as older than the plugin and push the +// rollout deadline out by as far as it lies ahead, so it fails the same way. func TestReconcileCNPG_UnreadableAttachRecordFailsTheJob(t *testing.T) { - f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), - newRolloutCluster(cnpgClusterHealthyPhase), newRolloutInstancePod(time.Now().Add(-time.Hour))) - if j, _ := f.pass(); apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) == nil { - t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) - } - live := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) - live.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: "yesterday"} - f.observeCNPG(live) + for _, tc := range []struct{ name, record string }{ + {name: "does not parse", record: "yesterday"}, + {name: "in the future", record: time.Now().Add(time.Hour).UTC().Format(time.RFC3339)}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), newRolloutInstancePod(time.Now().Add(-time.Hour))) + if j, _ := f.pass(); apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + live := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) + live.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: tc.record} + f.observeCNPG(live) - j, backups := f.pass() - if len(backups) != 0 { - t.Fatalf("a cnpg.io/Backup was created with an unreadable attach record: %+v", backups) - } - if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(j.Status.Message, cnpgPluginAttachedAtAnnotation) { - t.Errorf("phase %q, message %q; want Failed naming %s", j.Status.Phase, j.Status.Message, cnpgPluginAttachedAtAnnotation) + j, backups := f.pass() + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created with an unreadable attach record: %+v", backups) + } + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(j.Status.Message, cnpgPluginAttachedAtAnnotation) { + t.Errorf("phase %q, message %q; want Failed naming %s", j.Status.Phase, j.Status.Message, cnpgPluginAttachedAtAnnotation) + } + }) } } From b4551eb379f22b9e2121daa96bf53bf5999e8120 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Mon, 9 Nov 2026 23:58:57 +0300 Subject: [PATCH 18/26] fix(postgres): read restores from the apiserver before writing the destination A backup job that is about to write the WAL archive destination first checks for a restore of its application, because a write landing during the restore puts the restored Cluster back on the source's WAL prefix and the restore fails with an expected-empty-archive error after it has purged the target. That check read RestoreJobs from the informer cache, which can still miss one created a moment ago. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../backupjob_restore_lock.go | 4 +-- .../cnpgstrategy_controller.go | 5 ++-- .../cnpgstrategy_controller_test.go | 28 +++++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/internal/backupcontroller/backupjob_restore_lock.go b/internal/backupcontroller/backupjob_restore_lock.go index 3782527d9..6b662cad5 100644 --- a/internal/backupcontroller/backupjob_restore_lock.go +++ b/internal/backupcontroller/backupjob_restore_lock.go @@ -38,7 +38,7 @@ const ConditionReasonRestoreInProgress = "RestoreInProgress" // restored cluster back on the source's WAL prefix, where its recovery fails // with "Expected empty archive". Plan-created runs are the ones that hit // this, since nothing else looks at restores before creating a BackupJob. -func activeRestoreTargeting(ctx context.Context, c client.Client, namespace string, app corev1.TypedLocalObjectReference) (string, error) { +func activeRestoreTargeting(ctx context.Context, c client.Reader, namespace string, app corev1.TypedLocalObjectReference) (string, error) { app = NormalizeApplicationRef(app) list := &backupsv1alpha1.RestoreJobList{} if err := c.List(ctx, list, client.InNamespace(namespace)); err != nil { @@ -80,7 +80,7 @@ func activeRestoreTargeting(ctx context.Context, c client.Client, namespace stri // reads options.targetNamespace, so the option is looked at only when the // Backup's strategy is Velero — the CNPG and Job-based drivers ignore it and // restore in place. -func restoreJobTarget(ctx context.Context, c client.Client, rj *backupsv1alpha1.RestoreJob) (corev1.TypedLocalObjectReference, bool, error) { +func restoreJobTarget(ctx context.Context, c client.Reader, rj *backupsv1alpha1.RestoreJob) (corev1.TypedLocalObjectReference, bool, error) { backup := &backupsv1alpha1.Backup{} if err := c.Get(ctx, client.ObjectKey{Namespace: rj.Namespace, Name: rj.Spec.BackupRef.Name}, backup); err != nil { if client.IgnoreNotFound(err) == nil { diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index ac58fa4bc..cae1a95d1 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -365,8 +365,9 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if writeDestination { // The gate in Reconcile sees only a job that has not started, and // this one may have waited in the queue for as long as a restore - // takes to begin. - restore, err := activeRestoreTargeting(ctx, r.Client, j.Namespace, j.Spec.ApplicationRef) + // takes to begin. Read from the apiserver: the cache can still miss + // a RestoreJob created a moment ago. + restore, err := activeRestoreTargeting(ctx, r.apiReader(), j.Namespace, j.Spec.ApplicationRef) if err != nil { return ctrl.Result{}, err } diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 2f116734b..0b0531f59 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3209,6 +3209,34 @@ func (f *cnpgRolloutFixture) seedRestoreOfApp() *backupsv1alpha1.RestoreJob { return restore } +// The restore check before the destination write reads the apiserver: the +// cache can still miss a RestoreJob created a moment ago, and a write landing +// in that gap can put the restored Cluster back on the source's WAL prefix. +func TestReconcileCNPG_RestoreCheckReadsPastTheCache(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + f.seedRestoreOfApp() + f.r.APIReader = f.c + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*backupsv1alpha1.RestoreJobList); ok { + return nil + } + return cl.List(ctx, list, opts...) + }, + }) + + j, backups := f.pass() + if got := f.liveDestination(); got != "s3://other/" { + t.Errorf("destination written during a restore the cache had not caught: %q", got) + } + if len(backups) != 0 { + t.Errorf("a cnpg.io/Backup was created during a restore the cache had not caught: %+v", backups) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != ConditionReasonRestoreInProgress { + t.Errorf("Ready = %+v, want %s", ready, ConditionReasonRestoreInProgress) + } +} + // A job past its start writes the WAL archive destination only while no // restore rewrites its application. The restore gate in Reconcile looks only // at a job that has not started, and a job released from the queue, or one From 9a8025ca1432f73fcdca79ed0584f009160aa9fa Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Tue, 10 Nov 2026 00:00:52 +0300 Subject: [PATCH 19/26] fix(postgres): record the serverName a backup was archived under The artifact took its destination from the record written when the cnpg.io/Backup was created, but its serverName, the archive prefix under that destination, from the live Cluster when the backup completed. A restore that re-renders the Cluster in between gives it another serverName, and the artifact then pairs the original destination with a prefix the backup was never written to, so a later restore searches the wrong archive. The record now carries the serverName too; a record written before it did still falls back to the live Cluster. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 16 +++++-- .../cnpgstrategy_controller_test.go | 46 ++++++++++++++++++- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index cae1a95d1..75c3b3f06 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -223,7 +223,8 @@ const ( // Annotation on a cnpg.io/Backup carrying, as JSON, the WAL archive // destination written by the pass that created it: the destination - // path, the endpoint URL and the name of the credentials Secret. + // path, the endpoint URL, the name of the credentials Secret and the + // serverName the Cluster archived under. cnpgWrittenDestinationAnnotation = "backups.cozystack.io/cnpg-written-destination" // Annotation on a cnpg.io/Cluster carrying, as RFC 3339, when a backup @@ -557,7 +558,9 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp "cluster", clusterName, "live", attachment.flavor, "application", specFlavor) } - cnpgBackup, err := r.ensureCNPGBackup(ctx, j, clusterName, existingBackup, cnpgDestinationOf(rendered)) + written := cnpgDestinationOf(rendered) + written.ServerName = serverName + cnpgBackup, err := r.ensureCNPGBackup(ctx, j, clusterName, existingBackup, written) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure cnpg.io/Backup: %v", err)) } @@ -581,6 +584,11 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("refusing to create the Backup artifact: %v", err)) } + // A restore can re-render the Cluster under another serverName + // between the backup and this pass. + if destination.ServerName != "" { + serverName = destination.ServerName + } artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, destination, rendered, app) if err != nil { return r.failBackupArtifact(ctx, j, err) @@ -1056,11 +1064,13 @@ func (r *BackupJobReconciler) waitCNPGBackupJob(ctx context.Context, j *backupsv // cnpgDestination is the WAL archive destination recorded in // cnpgWrittenDestinationAnnotation. S3SecretRef is nil when the strategy -// names no credentials Secret. +// names no credentials Secret. ServerName is empty in a record written +// before it carried one. type cnpgDestination struct { DestinationPath string `json:"destinationPath"` EndpointURL string `json:"endpointURL,omitempty"` S3SecretRef *string `json:"s3SecretRef,omitempty"` + ServerName string `json:"serverName,omitempty"` } func cnpgDestinationOf(t *strategyv1alpha1.CNPGTemplate) cnpgDestination { diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 0b0531f59..8604d8c1a 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -5777,7 +5777,7 @@ func TestReconcileCNPG_ArtifactNamesTheDestinationItsBackupWasCreatedWith(t *tes if got := f.liveDestination(); got != "s3://bucket/" { t.Fatalf("destination = %q, want s3://bucket/", got) } - want := `{"destinationPath":"s3://bucket/","endpointURL":"https://s3.one","s3SecretRef":"creds-one"}` + want := `{"destinationPath":"s3://bucket/","endpointURL":"https://s3.one","s3SecretRef":"creds-one","serverName":"` + rolloutCluster + `"}` if got := backups[0].Annotations[cnpgWrittenDestinationAnnotation]; got != want { t.Fatalf("%s on the created cnpg.io/Backup = %q, want %q", cnpgWrittenDestinationAnnotation, got, want) } @@ -5802,10 +5802,52 @@ func TestReconcileCNPG_ArtifactNamesTheDestinationItsBackupWasCreatedWith(t *tes } } +// The serverName is the archive prefix under the destination, so the record +// carries it too: a restore that re-renders the Cluster between the backup +// and its artifact gives the live Cluster another one. A record written +// before it carried a serverName falls back to the live Cluster. +func TestReconcileCNPG_ArtifactNamesTheServerNameItsBackupWasCreatedWith(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://bucket/") + _, backups := f.pass() + want := `{"destinationPath":"s3://bucket/","serverName":"` + rolloutCluster + `"}` + if len(backups) != 1 || backups[0].Annotations[cnpgWrittenDestinationAnnotation] != want { + t.Fatalf("cnpg.io/Backups after the first pass = %+v, want one recording %s", backups, want) + } + f.observeCNPG(newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, "restored-server"))) + f.completeOwnBackup(nil) + j, _ := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Fatalf("phase = %q (%s), want Succeeded", j.Status.Phase, j.Status.Message) + } + artifact := f.artifact() + if got := artifact.Spec.DriverMetadata[cnpgServerNameKey]; got != rolloutCluster { + t.Errorf("artifact serverName = %q, want %q recorded with the Backup", got, rolloutCluster) + } + if !strings.HasPrefix(artifact.Status.Artifact.URI, "cnpg://"+rolloutCluster+"/") { + t.Errorf("artifact URI = %q, want it under %s", artifact.Status.Artifact.URI, rolloutCluster) + } +} + +func TestReconcileCNPG_ArtifactOfARecordWithoutServerName(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://bucket/") + f.pass() + f.observeCNPG(newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, "live-server"))) + f.completeOwnBackup(func(b *cnpgtypes.Backup) { + b.Annotations[cnpgWrittenDestinationAnnotation] = `{"destinationPath":"s3://bucket/"}` + }) + j, _ := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Fatalf("phase = %q (%s), want Succeeded", j.Status.Phase, j.Status.Message) + } + if got := f.artifact().Spec.DriverMetadata[cnpgServerNameKey]; got != "live-server" { + t.Errorf("artifact serverName = %q, want the live Cluster's live-server", got) + } +} + // A strategy without credentials records none, and the artifact names none. func TestReconcileCNPG_ArtifactOfARecordWithoutCredentials(t *testing.T) { f := newAttachedObjectStoreFixture(t, time.Now(), "s3://bucket/") - if _, backups := f.pass(); len(backups) != 1 || backups[0].Annotations[cnpgWrittenDestinationAnnotation] != `{"destinationPath":"s3://bucket/"}` { + if _, backups := f.pass(); len(backups) != 1 || backups[0].Annotations[cnpgWrittenDestinationAnnotation] != `{"destinationPath":"s3://bucket/","serverName":"`+rolloutCluster+`"}` { t.Fatalf("cnpg.io/Backups after the first pass = %+v, want one recording only s3://bucket/", backups) } f.setStrategyDestination("s3://edited/", "https://s3.two", "creds-two") From c69787ff49badeed6907cb69fec244ec84bbdb67 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Tue, 10 Nov 2026 00:03:02 +0300 Subject: [PATCH 20/26] perf(postgres): list only the Cluster's own backups for the queue Every pass of a backup job waiting for another one reads the cnpg.io/Backups from the apiserver, and the read covered every Backup in the namespace, so a namespace with a long backup history paid for it on each poll of each waiting job. The queue only looks at Backups this controller created for the Cluster, which have carried the cluster and owning-job labels since the driver was introduced, so it now asks the apiserver for those alone. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 9 ++- .../cnpgstrategy_controller_test.go | 61 ++++++++++++++++--- 2 files changed, 60 insertions(+), 10 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 75c3b3f06..a4bb0a3b9 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -1002,10 +1002,15 @@ func (r *BackupJobReconciler) findCNPGBackupForJob(ctx context.Context, j *backu // hold the queue. // // The Backups are read from the apiserver, not the cache, which can still -// miss a Backup another job's earlier pass created. +// miss a Backup another job's earlier pass created. Only the ones this +// controller created for the Cluster are asked for, by the labels +// ensureCNPGBackup has always set, so a waiting job's poll does not fetch +// the namespace's whole Backup history. func (r *BackupJobReconciler) otherCNPGBackupInFlight(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName string) (string, error) { list := &cnpgtypes.BackupList{} - if err := r.apiReader().List(ctx, list, client.InNamespace(j.Namespace)); err != nil { + if err := r.apiReader().List(ctx, list, client.InNamespace(j.Namespace), + client.MatchingLabels{cnpgClusterLabel: clusterName}, + client.HasLabels{backupsv1alpha1.OwningJobNameLabel}); err != nil { return "", err } var holders []string diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 8604d8c1a..25a72b746 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -15,6 +15,7 @@ import ( apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" @@ -2518,19 +2519,20 @@ func (f *cnpgRolloutFixture) liveDestination() string { } // seedCNPGBackup creates a cnpg.io/Backup of cluster owned by the BackupJob -// named owner; an empty owner leaves it unlabelled, as a Backup created by -// hand. +// named owner, labelled as ensureCNPGBackup labels it; an empty owner leaves +// it unlabelled, as a Backup created by hand. func (f *cnpgRolloutFixture) seedCNPGBackup(name, owner, cluster, phase string) { f.t.Helper() - var labels map[string]string + var backupLabels map[string]string if owner != "" { - labels = map[string]string{ + backupLabels = map[string]string{ backupsv1alpha1.OwningJobNameLabel: owner, backupsv1alpha1.OwningJobNamespaceLabel: rolloutNS, + cnpgClusterLabel: cluster, } } b := &cnpgtypes.Backup{ - ObjectMeta: metav1.ObjectMeta{Namespace: rolloutNS, Name: name, Labels: labels}, + ObjectMeta: metav1.ObjectMeta{Namespace: rolloutNS, Name: name, Labels: backupLabels}, Spec: cnpgtypes.BackupSpec{Cluster: cnpgtypes.ClusterReference{Name: cluster}}, Status: cnpgtypes.BackupStatus{Phase: phase}, } @@ -2595,6 +2597,43 @@ func TestReconcileCNPG_RunningBackupDoesNotReapplyObjectStore(t *testing.T) { } } +// The queue reads the apiserver on every pass of every waiting job, so it +// asks only for the Backups this controller created for the Cluster rather +// than the namespace's whole Backup history. +func TestReconcileCNPG_QueueListsOnlyTheClustersOwnedBackups(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://bucket/") + var selectors []labels.Selector + f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*cnpgtypes.BackupList); ok { + lo := &client.ListOptions{} + lo.ApplyOptions(opts) + selectors = append(selectors, lo.LabelSelector) + } + return cl.List(ctx, list, opts...) + }, + }) + f.pass() + owned := labels.Set{cnpgClusterLabel: rolloutCluster, backupsv1alpha1.OwningJobNameLabel: "bj-other"} + foreignCluster := labels.Set{cnpgClusterLabel: "postgres-other", backupsv1alpha1.OwningJobNameLabel: "bj-other"} + unowned := labels.Set{cnpgClusterLabel: rolloutCluster} + var queue labels.Selector + for _, s := range selectors { + if s == nil { + s = labels.Everything() + } + if s.Matches(owned) { + queue = s + } + } + if queue == nil { + t.Fatalf("no cnpg.io/Backup list would find another job's Backup; selectors = %v", selectors) + } + if queue.Matches(foreignCluster) || queue.Matches(unowned) { + t.Errorf("queue selector %q, want it to match only owned Backups of %s", queue, rolloutCluster) + } +} + func TestReconcileCNPG_WaitsForAnotherRunningBackupOfTheApp(t *testing.T) { cases := []struct { name string @@ -5974,16 +6013,22 @@ func TestReconcileCNPG_OwnBackupTheCacheHasNotCaught(t *testing.T) { } // failingBackupLists makes the uncached reader fail the cnpg.io/Backup lists -// for which fail, given whether the list selects the job's own Backup by -// label and how many such lists came before, returns true. +// for which fail, given whether the list selects only the job's own Backup +// (it would not find another job's) and how many such lists came before, +// returns true. func (f *cnpgRolloutFixture) failingBackupLists(fail func(own bool, n int) bool) { counts := map[bool]int{} + anotherJobs := labels.Set{ + backupsv1alpha1.OwningJobNameLabel: "bj-other", + backupsv1alpha1.OwningJobNamespaceLabel: rolloutNS, + cnpgClusterLabel: rolloutCluster, + } f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { if _, ok := list.(*cnpgtypes.BackupList); ok { o := &client.ListOptions{} o.ApplyOptions(opts) - own := o.LabelSelector != nil && !o.LabelSelector.Empty() + own := o.LabelSelector != nil && !o.LabelSelector.Matches(anotherJobs) counts[own]++ if fail(own, counts[own]) { return apierrors.NewServiceUnavailable("apiserver unavailable") From d37701a32747a3b2b6a82e7637efc0c09135ec1d Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Tue, 10 Nov 2026 00:07:01 +0300 Subject: [PATCH 21/26] fix(postgres): tolerate an attach record slightly ahead of the clock An attach record in the future failed the backup job at once, because it would hold every instance as older than the plugin. A record a few minutes ahead is also what a leadership change between controllers whose clocks differ leaves behind after an attach that worked, and failing then throws away a backup that would have run. Within that margin the job now keeps waiting: the instances predate the record, so the rollout check holds the backup, and the deadline counted from the record is not spent by the wait. Only a record further ahead is taken as corrupt and fails the job. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 44 +++++++++++++------ .../cnpgstrategy_controller_test.go | 35 +++++++++++++-- 2 files changed, 62 insertions(+), 17 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index a4bb0a3b9..a9eb6fabc 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -233,6 +233,11 @@ const ( // cannot be lost to a failed BackupJob status write after the attach. cnpgPluginAttachedAtAnnotation = "backups.cozystack.io/barman-plugin-attached-at" + // How far ahead of this controller's clock an attach record may be + // before it is taken as corrupt rather than as written by a leader whose + // clock ran ahead. + cnpgAttachClockSkewTolerance = 5 * time.Minute + cnpgPodRoleLabel = "cnpg.io/podRole" cnpgPodRoleInstance = "instance" ) @@ -499,20 +504,18 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } // The Cluster's record covers an attach whose status write was lost. attachedAt := rollout.LastTransitionTime - if attachment.attachedAt != "" { - recorded, err := time.Parse(time.RFC3339, attachment.attachedAt) - if recorded.After(time.Now()) { - // Every instance would predate it, and the deadline would count from it. - err = fmt.Errorf("%s is in the future", attachment.attachedAt) - } - if err != nil { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "cannot tell when the barman-cloud plugin was attached: the %s annotation of cnpg.io/Cluster %s/%s: %v", - cnpgPluginAttachedAtAnnotation, j.Namespace, clusterName, err)) - } - if recorded.After(attachedAt.Time) { - attachedAt = metav1.NewTime(recorded) - } + recorded, ok, err := cnpgRecordedAttach(attachment.attachedAt) + if err == nil && ok && time.Until(recorded) > cnpgAttachClockSkewTolerance { + // Every instance would predate it, and the deadline would count from it. + err = fmt.Errorf("%s is in the future", attachment.attachedAt) + } + if err != nil { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "cannot tell when the barman-cloud plugin was attached: the %s annotation of cnpg.io/Cluster %s/%s: %v", + cnpgPluginAttachedAtAnnotation, j.Namespace, clusterName, err)) + } + if ok && recorded.After(attachedAt.Time) { + attachedAt = metav1.NewTime(recorded) } pending, err := r.cnpgPluginRolloutPending(ctx, j.Namespace, clusterName, attachment, attachedAt) if err != nil { @@ -897,6 +900,19 @@ func (r *BackupJobReconciler) cnpgPluginRolloutPending(ctx context.Context, name return "", nil } +// cnpgRecordedAttach parses a cnpgPluginAttachedAtAnnotation value; ok is +// false for "", a Cluster that carries no record. +func cnpgRecordedAttach(raw string) (recorded time.Time, ok bool, err error) { + if raw == "" { + return time.Time{}, false, nil + } + recorded, err = time.Parse(time.RFC3339, raw) + if err != nil { + return time.Time{}, false, err + } + return recorded, true, nil +} + func podReady(pod *corev1.Pod) bool { for _, c := range pod.Status.Conditions { if c.Type == corev1.PodReady { diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 25a72b746..85afa0c65 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3122,9 +3122,10 @@ func TestReconcileCNPG_LaterWriteKeepsTheAttachRecord(t *testing.T) { } // An attach record that does not parse cannot tell which instances rolled -// with the plugin, so the job fails naming it instead of guessing. One in the -// future would hold every instance as older than the plugin and push the -// rollout deadline out by as far as it lies ahead, so it fails the same way. +// with the plugin, so the job fails naming it instead of guessing. One further +// ahead than controller clocks drift apart would hold every instance as older +// than the plugin and push the rollout deadline out by as far as it lies +// ahead, so it fails the same way. func TestReconcileCNPG_UnreadableAttachRecordFailsTheJob(t *testing.T) { for _, tc := range []struct{ name, record string }{ {name: "does not parse", record: "yesterday"}, @@ -3151,6 +3152,34 @@ func TestReconcileCNPG_UnreadableAttachRecordFailsTheJob(t *testing.T) { } } +// A record a little ahead of this controller's clock is what a leadership +// change between controllers whose clocks differ leaves behind, so the job +// waits for the clocks to agree rather than failing an attach that worked. +func TestReconcileCNPG_AttachRecordSlightlyAheadWaits(t *testing.T) { + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), newRolloutInstancePod(time.Now().Add(-time.Hour))) + if j, _ := f.pass(); apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + live := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) + live.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: time.Now().Add(time.Minute).UTC().Format(time.RFC3339)} + f.observeCNPG(live) + + j, backups, res := f.passResult() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the job failed on a record a minute ahead: %s", j.Status.Message) + } + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created before the rollout could be judged: %+v", backups) + } + if res.RequeueAfter == 0 { + t.Errorf("a waiting job is not requeued: %+v", res) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForPluginRollout" { + t.Errorf("Ready = %+v, want WaitingForPluginRollout", ready) + } +} + // A plugin attached by someone else after the latch, another backup job or // the chart re-rendering a restored Cluster outside the platform flow, // started the rollout before this job's write, which only finds it there: From a27de054cabac5bdc15f7113bc772bf5963d3726 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Tue, 10 Nov 2026 00:07:37 +0300 Subject: [PATCH 22/26] fix(postgres): wait for the rollout another backup job's attach started Only the job that attaches the barman-cloud plugin waited for the instance rollout it causes. A second job of the same application that started meanwhile found the plugin already there, had no rollout of its own to wait for and created its cnpg.io/Backup at once, against instances CNPG was still recreating, and such a Backup fails for good. The queue does not hold it either, since the attaching job has no Backup yet. The attach record on the Cluster says when the plugin was attached, so a job without a rollout of its own now waits for instances newer than it while the attach is recent enough for that rollout to be running. An older attach has had its rollout judged by the job that made it. The record belongs to that job, so one this job cannot read, or one further ahead than controller clocks drift, is skipped rather than failing it; the latter would otherwise hold every later job of the application for as long as it lies ahead. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 23 ++++++++++ .../cnpgstrategy_controller_test.go | 44 +++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index a9eb6fabc..bdc04bb0e 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -551,6 +551,29 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp }) apimeta.RemoveStatusCondition(&j.Status.Conditions, "Ready") rolledOut = true + } else if existingBackup == nil && attachment.attachedAt != "" { + // Another backup job attached the plugin. Its rollout can still be + // running while the attach is recent, and later than that the + // attaching job has failed it already. The record is that job's: + // one this job cannot read does not fail it, and neither does one + // further ahead than clocks drift, which every instance would + // predate for as long as it lies ahead. + recorded, _, err := cnpgRecordedAttach(attachment.attachedAt) + if err == nil && time.Until(recorded) > cnpgAttachClockSkewTolerance { + err = fmt.Errorf("%s is in the future", attachment.attachedAt) + } + if err != nil { + logger.Info("ignoring an unusable attach record another backup job left", + "cluster", clusterName, "annotation", cnpgPluginAttachedAtAnnotation, "error", err) + } else if time.Since(recorded) < cnpgDefaultBackupDeadline { + pending, err := r.cnpgPluginRolloutPending(ctx, j.Namespace, clusterName, attachment, metav1.NewTime(recorded)) + if err != nil { + return ctrl.Result{}, err + } + if pending != "" { + return r.waitCNPGBackupJob(ctx, j, "WaitingForPluginRollout", pending) + } + } } // The chart refuses a flavor change on a live Cluster, but the app keeps diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 85afa0c65..9c41d3931 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3180,6 +3180,50 @@ func TestReconcileCNPG_AttachRecordSlightlyAheadWaits(t *testing.T) { } } +// A job that attached nothing itself still finds the plugin another backup +// job attached a moment ago, while CNPG rolls the instances for it; a Backup +// created then fails for good. It waits for that rollout as long as the +// attach is recent enough for it to be running, and an attach record it +// cannot read is not its own to fail on. +func TestReconcileCNPG_JobWithoutLatchWaitsForAnotherJobsRollout(t *testing.T) { + cases := []struct { + name string + record string + podCreated time.Time + wantBackup bool + }{ + {name: "recent attach, instance not rolled yet", record: time.Now().Add(-5 * time.Minute).UTC().Format(time.RFC3339), podCreated: time.Now().Add(-10 * time.Minute), wantBackup: false}, + {name: "recent attach, instance rolled", record: time.Now().Add(-5 * time.Minute).UTC().Format(time.RFC3339), podCreated: time.Now().Add(-time.Minute), wantBackup: true}, + {name: "attach older than the rollout deadline", record: time.Now().Add(-2 * cnpgDefaultBackupDeadline).UTC().Format(time.RFC3339), podCreated: time.Now().Add(-3 * cnpgDefaultBackupDeadline), wantBackup: true}, + {name: "unreadable record", record: "yesterday", podCreated: time.Now().Add(-time.Hour), wantBackup: true}, + {name: "record further ahead than clocks drift", record: time.Now().Add(time.Hour).UTC().Format(time.RFC3339), podCreated: time.Now().Add(-time.Hour), wantBackup: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cluster := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) + cluster.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: tc.record} + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), cluster, + newRolloutInstancePod(tc.podCreated.Truncate(time.Second))) + + j, backups, res := f.passResult() + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the job failed: %s", j.Status.Message) + } + if got := len(backups) == 1; got != tc.wantBackup { + t.Fatalf("cnpg.io/Backup created = %t, want %t; Ready = %+v", got, tc.wantBackup, apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } + if !tc.wantBackup { + if res.RequeueAfter == 0 { + t.Errorf("a waiting job is not requeued: %+v", res) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForPluginRollout" { + t.Errorf("Ready = %+v, want WaitingForPluginRollout", ready) + } + } + }) + } +} + // A plugin attached by someone else after the latch, another backup job or // the chart re-rendering a restored Cluster outside the platform flow, // started the rollout before this job's write, which only finds it there: From 5635d9d815cb7adfe13798649dfd07f0d06bd1c8 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Tue, 10 Nov 2026 00:08:24 +0300 Subject: [PATCH 23/26] test(postgres): pin that a rollout dated by the attach record runs out The deadline tests dated every rollout by the job's own condition, so a change that let a rollout dated by the Cluster's attach record wait forever would have passed them. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller_test.go | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 9c41d3931..78c9e9966 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -2887,6 +2887,36 @@ func TestReconcileCNPG_PluginRolloutDeadlineCountsFromAttach(t *testing.T) { } } +// A rollout dated by the Cluster's attach record runs out like one dated by +// the job's own condition: a record newer than the condition but older than +// the deadline fails the job too. +func TestReconcileCNPG_PluginRolloutDeadlineCountsFromTheAttachRecord(t *testing.T) { + expired := time.Now().Add(-(cnpgDefaultBackupDeadline + time.Minute)).Truncate(time.Second) + f := newCNPGRolloutFixture(t, newRolloutBackupJob(expired.Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), newRolloutInstancePod(expired.Add(-time.Hour))) + + j, _ := f.pass() // latch + latch := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) + if latch == nil { + t.Fatalf("no %s latch: %+v", backupCondPluginRolledOut, j.Status.Conditions) + } + latch.LastTransitionTime = metav1.NewTime(expired.Add(-10 * time.Minute)) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("age the latch: %v", err) + } + live := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) + live.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: expired.UTC().Format(time.RFC3339)} + f.observeCNPG(live) + + j, backups := f.pass() + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created against an instance older than the attach: %+v", backups) + } + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(j.Status.Message, "rollout did not finish") { + t.Fatalf("phase = %q (%s), want Failed on a rollout recorded longer ago than the deadline", j.Status.Phase, j.Status.Message) + } +} + // The rollout is measured from the write that attached the plugin, not from // the latch recorded before it: retries of a failing write can lie between // the two, and an instance recreated in that time runs without the plugin. From 59a11c1788fa23db53995e0de52485c7e61b1fec Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Tue, 10 Nov 2026 15:52:21 +0300 Subject: [PATCH 24/26] refactor(postgres): judge an attach record's clock drift in one place The job that attached the plugin and a job waiting on another job's attach each parsed the Cluster's attach record and applied the clock-drift margin on their own, so the two could drift apart on the next change. Both now take the record from one parser that also refuses one too far ahead, and differ only in what they do with a record they cannot use. The margin is now pinned for the waiting job from both sides: a record a minute ahead still holds it for the rollout. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 25 +++++++++---------- .../cnpgstrategy_controller_test.go | 1 + 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index bdc04bb0e..375af221c 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -505,10 +505,6 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp // The Cluster's record covers an attach whose status write was lost. attachedAt := rollout.LastTransitionTime recorded, ok, err := cnpgRecordedAttach(attachment.attachedAt) - if err == nil && ok && time.Until(recorded) > cnpgAttachClockSkewTolerance { - // Every instance would predate it, and the deadline would count from it. - err = fmt.Errorf("%s is in the future", attachment.attachedAt) - } if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( "cannot tell when the barman-cloud plugin was attached: the %s annotation of cnpg.io/Cluster %s/%s: %v", @@ -553,15 +549,12 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp rolledOut = true } else if existingBackup == nil && attachment.attachedAt != "" { // Another backup job attached the plugin. Its rollout can still be - // running while the attach is recent, and later than that the - // attaching job has failed it already. The record is that job's: - // one this job cannot read does not fail it, and neither does one - // further ahead than clocks drift, which every instance would - // predate for as long as it lies ahead. + // running while the attach is recent; past the rollout deadline + // this job stops waiting, as the attaching job normally has judged + // the rollout by then unless a wait of its own moved its deadline + // on. The record is that job's: + // one this job cannot use does not fail it. recorded, _, err := cnpgRecordedAttach(attachment.attachedAt) - if err == nil && time.Until(recorded) > cnpgAttachClockSkewTolerance { - err = fmt.Errorf("%s is in the future", attachment.attachedAt) - } if err != nil { logger.Info("ignoring an unusable attach record another backup job left", "cluster", clusterName, "annotation", cnpgPluginAttachedAtAnnotation, "error", err) @@ -924,7 +917,10 @@ func (r *BackupJobReconciler) cnpgPluginRolloutPending(ctx context.Context, name } // cnpgRecordedAttach parses a cnpgPluginAttachedAtAnnotation value; ok is -// false for "", a Cluster that carries no record. +// false for "", a Cluster that carries no record. A record further ahead of +// this controller's clock than cnpgAttachClockSkewTolerance is an error: +// every instance would predate it, and a deadline counted from it would not +// run out for as long as it lies ahead. func cnpgRecordedAttach(raw string) (recorded time.Time, ok bool, err error) { if raw == "" { return time.Time{}, false, nil @@ -933,6 +929,9 @@ func cnpgRecordedAttach(raw string) (recorded time.Time, ok bool, err error) { if err != nil { return time.Time{}, false, err } + if time.Until(recorded) > cnpgAttachClockSkewTolerance { + return time.Time{}, false, fmt.Errorf("%s is in the future", raw) + } return recorded, true, nil } diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 78c9e9966..1d36117fa 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3227,6 +3227,7 @@ func TestReconcileCNPG_JobWithoutLatchWaitsForAnotherJobsRollout(t *testing.T) { {name: "attach older than the rollout deadline", record: time.Now().Add(-2 * cnpgDefaultBackupDeadline).UTC().Format(time.RFC3339), podCreated: time.Now().Add(-3 * cnpgDefaultBackupDeadline), wantBackup: true}, {name: "unreadable record", record: "yesterday", podCreated: time.Now().Add(-time.Hour), wantBackup: true}, {name: "record further ahead than clocks drift", record: time.Now().Add(time.Hour).UTC().Format(time.RFC3339), podCreated: time.Now().Add(-time.Hour), wantBackup: true}, + {name: "record ahead within clock drift", record: time.Now().Add(time.Minute).UTC().Format(time.RFC3339), podCreated: time.Now().Add(-time.Hour), wantBackup: false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { From 1d220136461ba8e7211ad0e8fd158736beca4f6c Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 12 Nov 2026 11:10:21 +0300 Subject: [PATCH 25/26] fix(postgres): hold a backup until the plugin sees its new destination The plugin-barman-cloud sidecar reads the ObjectStore through its own cache, kept for ten seconds (DefaultTTLSeconds in plugin-barman-cloud v0.13.0) and invalidated only by the sidecar's own writes, and WAL archiving keeps it warm. The pass that changed the destination created the cnpg.io/Backup a moment later, so the base backup could be taken against the previous destination while the artifact names the new one, and a restore from it finds nothing. On a live cluster with the shipped plugin, a Backup created two to four seconds after switching the destination landed in the old bucket in two of three tries; with a fifteen second wait it landed in the new one every time. The apply that changes the ObjectStore configuration now stamps the time on the ObjectStore itself, so the record cannot be lost apart from the change, and the job creates its Backup only once that change is older than the cache can be. A change is judged on the configuration a server-side dry run of the same apply returns, so values the apiserver defaults or another field manager owns do not read as a change on every pass. That wait leaves a job with the destination written and no Backup yet, which the queue, looking only for Backups in flight, did not see: a second job with another destination wrote its own, the first took that as a change and stamped again, and the two restarted each other's wait forever. Every apply of the ObjectStore therefore also names the job that made it, which only a job without a Backup of its own and let through by the queue does, and the queue holds every other job while that one runs and has no Backup yet. Once it has one, that Backup holds the destination for as long as CloudNativePG runs it, as before, so a job stuck after its Backup finished does not hold every later backup of the application. This also covers a job waiting for the rollout of the plugin it attached, during which a second job used to switch the destination as well, including when its own write left the configuration as a restore had re-rendered it. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpgstrategy_controller.go | 170 ++++- .../cnpgstrategy_controller_test.go | 585 +++++++++++++++++- 2 files changed, 726 insertions(+), 29 deletions(-) diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 375af221c..e43deff33 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -15,6 +15,7 @@ import ( "time" corev1 "k8s.io/api/core/v1" + apiequality "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/resource" @@ -233,9 +234,30 @@ const ( // cannot be lost to a failed BackupJob status write after the attach. cnpgPluginAttachedAtAnnotation = "backups.cozystack.io/barman-plugin-attached-at" - // How far ahead of this controller's clock an attach record may be - // before it is taken as corrupt rather than as written by a leader whose - // clock ran ahead. + // Annotation on the ObjectStore carrying, as RFC 3339, when a backup job + // last changed its configuration. It is written by the apply that makes + // the change, so it cannot be lost apart from it. + cnpgDestinationChangedAtAnnotation = "backups.cozystack.io/destination-changed-at" + + // Annotation on the ObjectStore naming the BackupJob whose apply last + // wrote it. Written by that apply, it holds the destination for that job + // while it runs and has no cnpg.io/Backup of its own yet; from then on + // the queue sees that Backup instead. + cnpgDestinationWrittenByAnnotation = "backups.cozystack.io/destination-written-by" + + // How long after an ObjectStore configuration change a Backup is held. + // The plugin-barman-cloud sidecar reads the ObjectStore through its own + // cache, kept for DefaultTTLSeconds = 10 (plugin-barman-cloud v0.13.0, + // internal/cnpgi/instance/internal/client/client.go) and invalidated + // only by the sidecar's own writes, so a Backup taken sooner can use the + // previous configuration and land in the previous bucket. The margin + // covers the cache's whole-second expiry and the record's whole-second + // timestamp. + cnpgObjectStoreCacheSettle = 15 * time.Second + + // How far ahead of this controller's clock a recorded time, of a plugin + // attach or of a destination change, may be before it is taken as + // corrupt rather than as written by a leader whose clock ran ahead. cnpgAttachClockSkewTolerance = 5 * time.Minute cnpgPodRoleLabel = "cnpg.io/podRole" @@ -366,7 +388,9 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp // The ObjectStore is the Cluster's WAL archive destination, shared by // every backup of the app, so it is written only before this job's - // Backup exists and only while no other job's Backup is in flight. + // Backup exists, and only while no other job's Backup is in flight and + // no other running job without a Backup yet holds the destination it + // last wrote. writeDestination := existingBackup == nil if writeDestination { // The gate in Reconcile sees only a job that has not started, and @@ -386,6 +410,11 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if err != nil { return ctrl.Result{}, err } + if holder == "" { + if holder, err = r.destinationClaimHolder(ctx, j, clusterName); err != nil { + return ctrl.Result{}, err + } + } if holder != "" { apimeta.RemoveStatusCondition(&j.Status.Conditions, backupCondDestinationApplied) apimeta.SetStatusCondition(&j.Status.Conditions, cnpgDestinationWriteHeld("WaitingForOtherBackup")) @@ -403,7 +432,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } attemptedAt := metav1.Now() - attachment, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName, existingBackup != nil || awaitingRollout, writeDestination) + attachment, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName, existingBackup != nil || awaitingRollout, writeDestination, j.Name) if err != nil { if apierrors.IsNotFound(err) { // HelmRelease has not yet rendered the Cluster (fresh app, or @@ -504,7 +533,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } // The Cluster's record covers an attach whose status write was lost. attachedAt := rollout.LastTransitionTime - recorded, ok, err := cnpgRecordedAttach(attachment.attachedAt) + recorded, ok, err := cnpgRecordedTime(attachment.attachedAt) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( "cannot tell when the barman-cloud plugin was attached: the %s annotation of cnpg.io/Cluster %s/%s: %v", @@ -548,13 +577,11 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp apimeta.RemoveStatusCondition(&j.Status.Conditions, "Ready") rolledOut = true } else if existingBackup == nil && attachment.attachedAt != "" { - // Another backup job attached the plugin. Its rollout can still be - // running while the attach is recent; past the rollout deadline - // this job stops waiting, as the attaching job normally has judged - // the rollout by then unless a wait of its own moved its deadline - // on. The record is that job's: - // one this job cannot use does not fail it. - recorded, _, err := cnpgRecordedAttach(attachment.attachedAt) + // Another backup job attached the plugin, and its rollout can still + // be running while the attach is recent; past the rollout deadline + // this job stops waiting. The record is that job's: one this job + // cannot use does not fail it. + recorded, _, err := cnpgRecordedTime(attachment.attachedAt) if err != nil { logger.Info("ignoring an unusable attach record another backup job left", "cluster", clusterName, "annotation", cnpgPluginAttachedAtAnnotation, "error", err) @@ -577,6 +604,12 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp "cluster", clusterName, "live", attachment.flavor, "application", specFlavor) } + if changedAt := attachment.destinationChangedAt; !changedAt.IsZero() && time.Since(changedAt) < cnpgObjectStoreCacheSettle { + return r.waitCNPGBackupJob(ctx, j, "WaitingForDestinationToSettle", fmt.Sprintf( + "the WAL archive destination of cnpg.io/Cluster %s/%s changed at %s; the barman-cloud plugin can read the previous one for up to %s", + j.Namespace, clusterName, changedAt.UTC().Format(time.RFC3339), cnpgObjectStoreCacheSettle)) + } + written := cnpgDestinationOf(rendered) written.ServerName = serverName cnpgBackup, err := r.ensureCNPGBackup(ctx, j, clusterName, existingBackup, written) @@ -780,7 +813,7 @@ var cnpgClusterGVR = schema.GroupVersionResource{ // // With write unset nothing is written: only what the live Cluster carries is // reported. -func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, namespace, clusterName string, t *strategyv1alpha1.CNPGTemplate, serverName string, attach, write bool) (cnpgPluginAttachment, error) { +func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, namespace, clusterName string, t *strategyv1alpha1.CNPGTemplate, serverName string, attach, write bool, jobName string) (cnpgPluginAttachment, error) { // Live read: the cached Cluster can predate a restore re-render, and the // serverName, the flavor and the UID below must come from the current // object. @@ -836,9 +869,21 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name RetentionPolicy: t.BarmanObjectStore.RetentionPolicy, InstanceSidecarConfiguration: barmanSidecarConfiguration(), } + changedAt, err := r.objectStoreChangeRecord(ctx, objStore) + if err != nil { + return cnpgPluginAttachment{}, err + } + // Only a job without a Backup of its own writes, and the queue let it + // through, so it holds the destination from this write while it runs + // and has not created its Backup. + objStore.Annotations = map[string]string{cnpgDestinationWrittenByAnnotation: jobName} + if !changedAt.IsZero() { + objStore.Annotations[cnpgDestinationChangedAtAnnotation] = changedAt.UTC().Format(time.RFC3339) + } if err := r.Patch(ctx, objStore, client.Apply, client.FieldOwner(cnpgFieldManager), client.ForceOwnership); err != nil { return cnpgPluginAttachment{}, fmt.Errorf("apply ObjectStore %s/%s: %w", namespace, objStoreName, err) } + attachment.destinationChangedAt = changedAt patch := newCNPGClusterPatch(namespace, clusterName) patch.Spec.Plugins = []cnpgtypes.PluginConfiguration{buildBarmanPlugin(objStoreName, serverName)} @@ -857,6 +902,83 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name return attachment, nil } +// objectStoreChangeRecord returns the cnpgDestinationChangedAtAnnotation the +// apply of desired should carry: the time of this write when it changes the +// configuration, otherwise the record the live ObjectStore already carries, +// re-sent so the apply does not delete it, and zero when there is none. +// "Changes" is judged on the configuration a server-side dry run of the same +// apply returns, not on desired, so values the apiserver defaults or another +// field manager owns do not read as a change on every pass. Creating the +// ObjectStore stamps no time: the plugin cannot hold a stale copy of an +// object that did not exist, short of one deleted and recreated by hand +// within the cache's lifetime. +func (r *BackupJobReconciler) objectStoreChangeRecord(ctx context.Context, desired *cnpgtypes.ObjectStore) (time.Time, error) { + live := &cnpgtypes.ObjectStore{} + if err := r.apiReader().Get(ctx, client.ObjectKeyFromObject(desired), live); err != nil { + if apierrors.IsNotFound(err) { + return time.Time{}, nil + } + return time.Time{}, fmt.Errorf("read ObjectStore %s/%s: %w", desired.Namespace, desired.Name, err) + } + dry := desired.DeepCopy() + if err := r.Patch(ctx, dry, client.Apply, client.FieldOwner(cnpgFieldManager), client.ForceOwnership, client.DryRunAll); err != nil { + return time.Time{}, fmt.Errorf("dry-run apply ObjectStore %s/%s: %w", desired.Namespace, desired.Name, err) + } + if !apiequality.Semantic.DeepEqual(live.Spec.Configuration, dry.Spec.Configuration) { + return time.Now(), nil + } + recorded, _, err := cnpgRecordedTime(live.Annotations[cnpgDestinationChangedAtAnnotation]) + if err != nil { + // Nothing says when the cache expires; this write's time is the + // latest it can be. + return time.Now(), nil + } + return recorded, nil +} + +// destinationClaimHolder returns the BackupJob other than j that the +// ObjectStore of clusterName names as the last to write it, while that job +// is still running and has no cnpg.io/Backup of its own, or "" when there is +// none. Such a job wrote the destination before otherCNPGBackupInFlight can +// see it: it can still be waiting for the plugin cache, or for the rollout of +// the plugin it attached. Once it has a Backup, that Backup holds the +// destination while CloudNativePG runs it, and the claim stops holding, so a +// job stuck after its Backup finished does not hold every later one. +func (r *BackupJobReconciler) destinationClaimHolder(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName string) (string, error) { + store := &cnpgtypes.ObjectStore{} + if err := r.apiReader().Get(ctx, client.ObjectKey{Namespace: j.Namespace, Name: clusterName}, store); err != nil { + if apierrors.IsNotFound(err) { + return "", nil + } + return "", fmt.Errorf("read ObjectStore %s/%s: %w", j.Namespace, clusterName, err) + } + holder := store.Annotations[cnpgDestinationWrittenByAnnotation] + if holder == "" || holder == j.Name { + return "", nil + } + holderJob := &backupsv1alpha1.BackupJob{} + if err := r.Get(ctx, client.ObjectKey{Namespace: j.Namespace, Name: holder}, holderJob); err != nil { + if apierrors.IsNotFound(err) { + return "", nil + } + return "", err + } + if holderJob.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || holderJob.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + return "", nil + } + holderBackups := &cnpgtypes.BackupList{} + if err := r.apiReader().List(ctx, holderBackups, client.InNamespace(j.Namespace), client.MatchingLabels{ + backupsv1alpha1.OwningJobNameLabel: holder, + backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, + }); err != nil { + return "", fmt.Errorf("list cnpg.io/Backups of BackupJob %s/%s: %w", j.Namespace, holder, err) + } + if len(holderBackups.Items) > 0 { + return "", nil + } + return holder, nil +} + // cnpgPluginAttachment is what applyClusterPluginBackup read off the live // Cluster before applying the plugin. type cnpgPluginAttachment struct { @@ -869,8 +991,11 @@ type cnpgPluginAttachment struct { // attachedAt is the cnpgPluginAttachedAtAnnotation the Cluster carried, // "" when it carries no record: the plugin was attached by the chart, or // before the record existed. - attachedAt string - clusterStatus cnpgtypes.ClusterStatus + attachedAt string + // destinationChangedAt is the cnpgDestinationChangedAtAnnotation this + // pass applied to the ObjectStore, zero when it wrote none. + destinationChangedAt time.Time + clusterStatus cnpgtypes.ClusterStatus } // cnpgPluginRolloutPending returns why the rollout that attaching the @@ -916,12 +1041,13 @@ func (r *BackupJobReconciler) cnpgPluginRolloutPending(ctx context.Context, name return "", nil } -// cnpgRecordedAttach parses a cnpgPluginAttachedAtAnnotation value; ok is -// false for "", a Cluster that carries no record. A record further ahead of -// this controller's clock than cnpgAttachClockSkewTolerance is an error: -// every instance would predate it, and a deadline counted from it would not -// run out for as long as it lies ahead. -func cnpgRecordedAttach(raw string) (recorded time.Time, ok bool, err error) { +// cnpgRecordedTime parses a recorded time annotation, the plugin attach +// record on the Cluster or the destination change record on the ObjectStore; +// ok is false for "", an object that carries no record. A record further +// ahead of this controller's clock than cnpgAttachClockSkewTolerance is an +// error: every instance would predate it, and a deadline counted from it +// would not run out for as long as it lies ahead. +func cnpgRecordedTime(raw string) (recorded time.Time, ok bool, err error) { if raw == "" { return time.Time{}, false, nil } diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 1d36117fa..bbfc8b0d7 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -1103,7 +1103,7 @@ func TestApplyClusterPluginBackup_NotFoundOnMissingCluster(t *testing.T) { }, } - _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-missing", tmpl, "postgres-missing", true, true) + _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-missing", tmpl, "postgres-missing", true, true, "bj") if err == nil { t.Fatalf("expected NotFound error, got nil") } @@ -1743,7 +1743,7 @@ func TestApplyClusterPluginBackup_ReadsTheLiveClusterNotTheCache(t *testing.T) { BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"}, } - got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true, true) + got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true, true, "bj") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -1953,7 +1953,7 @@ func TestApplyClusterPluginBackup_PreservesLiveServerName(t *testing.T) { BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"}, } - got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true, true) + got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true, true, "bj") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -2122,7 +2122,7 @@ func TestApplyClusterPluginBackup_PatchesExistingCluster(t *testing.T) { }, } - if _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "tenant-app", true, true); err != nil { + if _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "tenant-app", true, true, "bj"); err != nil { t.Fatalf("unexpected error: %v", err) } @@ -2736,6 +2736,17 @@ func TestReconcileCNPG_WaitsForAnotherRunningBackupOfTheApp(t *testing.T) { if got := f.liveDestination(); got != "s3://bucket/" { t.Errorf("destination = %q, want the job's own s3://bucket/", got) } + if ready != nil && ready.Reason == "WaitingForOtherBackup" { + t.Errorf("Ready = %+v, the job was held", ready) + } + f.settleDestination() + _, backups = f.pass() + ours = 0 + for _, b := range backups { + if b.Labels[backupsv1alpha1.OwningJobNameLabel] == "bj" { + ours++ + } + } if ours != 1 { t.Errorf("got %d cnpg.io/Backups for the job, want 1", ours) } @@ -2819,6 +2830,8 @@ func TestReconcileCNPG_ObjectStoreApplyRecovers(t *testing.T) { } failing = false + j, _ = f.pass() + f.settleDestination() j, backups := f.pass() if len(backups) != 1 { t.Fatalf("got %d cnpg.io/Backups after the write recovered, want 1", len(backups)) @@ -3121,6 +3134,562 @@ func TestReconcileCNPG_AttachRecordOlderThanTheLatchKeepsTheLatch(t *testing.T) } } +func (f *cnpgRolloutFixture) liveObjectStore() *cnpgtypes.ObjectStore { + f.t.Helper() + store := &cnpgtypes.ObjectStore{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: rolloutCluster}, store); err != nil { + f.t.Fatalf("get ObjectStore: %v", err) + } + return store +} + +// setDestinationStamp rewrites the destination-change record on the live +// ObjectStore, as a write that long ago, or a corrupt one, would have left it. +func (f *cnpgRolloutFixture) setDestinationStamp(value string) { + f.t.Helper() + store := f.liveObjectStore() + if store.Annotations == nil { + store.Annotations = map[string]string{} + } + store.Annotations[cnpgDestinationChangedAtAnnotation] = value + if err := f.c.Update(context.Background(), store); err != nil { + f.t.Fatalf("stamp ObjectStore: %v", err) + } +} + +// settleDestination ages the destination-change record, when the ObjectStore +// carries one, as if the plugin's cache had expired since that write. +func (f *cnpgRolloutFixture) settleDestination() { + f.t.Helper() + if _, ok := f.liveObjectStore().Annotations[cnpgDestinationChangedAtAnnotation]; ok { + f.setDestinationStamp(time.Now().Add(-time.Minute).UTC().Format(time.RFC3339)) + } +} + +// addJobWithDestination adds BackupJob name of the same application, resolved +// to a strategy of its own that writes destination, and returns a function +// running one pass of it. +func (f *cnpgRolloutFixture) addJobWithDestination(name, destination string) func() *backupsv1alpha1.BackupJob { + f.t.Helper() + ctx := context.Background() + strategy := &strategyv1alpha1.CNPG{ + ObjectMeta: metav1.ObjectMeta{Name: "cnpg-strategy-" + name}, + Spec: strategyv1alpha1.CNPGSpec{Template: strategyv1alpha1.CNPGTemplate{ + BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: destination}, + }}, + } + if err := f.c.Create(ctx, strategy); err != nil { + f.t.Fatalf("seed strategy: %v", err) + } + job := newRolloutBackupJob(time.Now().Add(-time.Hour)) + job.Name = name + if err := f.c.Create(ctx, job); err != nil { + f.t.Fatalf("seed BackupJob %s: %v", name, err) + } + group := strategyv1alpha1.GroupVersion.Group + resolved := &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &group, Kind: strategyv1alpha1.CNPGStrategyKind, Name: strategy.Name}} + return func() *backupsv1alpha1.BackupJob { + f.t.Helper() + key := client.ObjectKey{Namespace: rolloutNS, Name: name} + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, key, j); err != nil { + f.t.Fatalf("get BackupJob %s: %v", name, err) + } + if _, err := f.r.reconcileCNPG(ctx, j, resolved); err != nil { + f.t.Fatalf("reconcileCNPG %s: %v", name, err) + } + if err := f.c.Get(ctx, key, j); err != nil { + f.t.Fatalf("get BackupJob %s after reconcile: %v", name, err) + } + return j + } +} + +// Two jobs of the application with different destinations, neither with a +// Backup yet, would otherwise take turns rewriting the ObjectStore, each +// write restarting the other's wait for the plugin cache so that neither +// ever creates one. The job whose write came first holds the destination, +// by its claim until it has a Backup and by that Backup afterwards, and the +// other waits for it. +func TestReconcileCNPG_JobsWithDifferentDestinationsTakeTurns(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://third/") + pass2 := f.addJobWithDestination("bj2", "s3://other/") + + var j2 *backupsv1alpha1.BackupJob + for range 5 { + f.pass() + f.settleDestination() + j2 = pass2() + f.settleDestination() + } + backups := &cnpgtypes.BackupList{} + if err := f.c.List(context.Background(), backups, client.InNamespace(rolloutNS)); err != nil { + t.Fatalf("list cnpg.io/Backups: %v", err) + } + if len(backups.Items) != 1 || backups.Items[0].Labels[backupsv1alpha1.OwningJobNameLabel] != "bj" { + t.Fatalf("cnpg.io/Backups = %+v, want exactly one, of bj, whose write came first", backups.Items) + } + if got := f.liveDestination(); got != "s3://bucket/" { + t.Errorf("destination = %q, want bj's s3://bucket/ under its running Backup", got) + } + if ready := apimeta.FindStatusCondition(j2.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForOtherBackup" || !strings.Contains(ready.Message, "BackupJob bj ") { + t.Errorf("bj2 Ready = %+v, want WaitingForOtherBackup naming bj", ready) + } +} + +// The claim names the job whose write last reached the ObjectStore, whether +// it changed the configuration, created the object or left it as it was; the +// change record is re-sent as it is by a write that changes nothing. +func TestReconcileCNPG_ClaimNamesTheJobThatWroteTheDestination(t *testing.T) { + t.Run("changed", func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + f.pass() + if got := f.liveObjectStore().Annotations[cnpgDestinationWrittenByAnnotation]; got != "bj" { + t.Errorf("%s = %q, want bj", cnpgDestinationWrittenByAnnotation, got) + } + }) + t.Run("created", func(t *testing.T) { + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)), + newRolloutInstancePod(time.Now().Add(-time.Hour))) + f.pass() + store := f.liveObjectStore() + if got := store.Annotations[cnpgDestinationWrittenByAnnotation]; got != "bj" { + t.Errorf("%s = %q, want bj", cnpgDestinationWrittenByAnnotation, got) + } + if _, ok := store.Annotations[cnpgDestinationChangedAtAnnotation]; ok { + t.Errorf("creating the ObjectStore stamped %s, which would hold the Backup for nothing", cnpgDestinationChangedAtAnnotation) + } + }) + for name, recorded := range map[string]map[string]string{ + "unchanged": {cnpgDestinationWrittenByAnnotation: "bj-old"}, + "unchanged with a stamp": {cnpgDestinationWrittenByAnnotation: "bj-old", cnpgDestinationChangedAtAnnotation: "2026-01-02T03:04:05Z"}, + } { + t.Run(name, func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://bucket/") + store := f.liveObjectStore() + store.Annotations = recorded + if err := f.c.Update(context.Background(), store); err != nil { + t.Fatalf("seed claim: %v", err) + } + var sent []map[string]string + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + po := &client.PatchOptions{} + po.ApplyOptions(opts) + if _, ok := obj.(*cnpgtypes.ObjectStore); ok && !slices.Contains(po.DryRun, metav1.DryRunAll) { + sent = append(sent, obj.GetAnnotations()) + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + f.pass() + if len(sent) != 1 { + t.Fatalf("got %d ObjectStore writes, want 1", len(sent)) + } + if got := sent[0][cnpgDestinationWrittenByAnnotation]; got != "bj" { + t.Errorf("the write sent %s = %q, want bj, the job that wrote", cnpgDestinationWrittenByAnnotation, got) + } + if got, want := sent[0][cnpgDestinationChangedAtAnnotation], recorded[cnpgDestinationChangedAtAnnotation]; got != want { + t.Errorf("the write sent %s = %q, want the recorded %q", cnpgDestinationChangedAtAnnotation, got, want) + } + }) + } +} + +// A claim stops holding the destination once its job has finished or is +// gone, so the next job writes its own. +func TestReconcileCNPG_ClaimOfAFinishedJobDoesNotHold(t *testing.T) { + for name, phase := range map[string]backupsv1alpha1.BackupJobPhase{ + "succeeded": backupsv1alpha1.BackupJobPhaseSucceeded, + "failed": backupsv1alpha1.BackupJobPhaseFailed, + "gone": "", + } { + t.Run(name, func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + if name != "gone" { + f.seedOtherBackupJob("bj-other", phase) + } + store := f.liveObjectStore() + store.Annotations = map[string]string{cnpgDestinationWrittenByAnnotation: "bj-other"} + if err := f.c.Update(context.Background(), store); err != nil { + t.Fatalf("seed claim: %v", err) + } + j, _ := f.pass() + if got := f.liveDestination(); got != "s3://bucket/" { + t.Errorf("destination = %q, want bj's s3://bucket/", got) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready != nil && ready.Reason == "WaitingForOtherBackup" { + t.Errorf("Ready = %+v, held by a %s job", ready, name) + } + }) + } +} + +// A job that attaches the plugin writes a configuration the ObjectStore may +// already carry, for instance after a restore re-rendered the Cluster +// without the plugin. Its write still claims the destination, so a job with +// another one waits through the rollout instead of switching it. +func TestReconcileCNPG_UnchangedWriteClaimsTheDestinationForTheRollout(t *testing.T) { + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), + newRolloutCluster(cnpgClusterHealthyPhase), newRolloutInstancePod(time.Now().Add(-time.Hour))) + f.seedOtherBackupJob("bj-old", backupsv1alpha1.BackupJobPhaseSucceeded) + store := &cnpgtypes.ObjectStore{ + ObjectMeta: metav1.ObjectMeta{Namespace: rolloutNS, Name: rolloutCluster, + Annotations: map[string]string{cnpgDestinationWrittenByAnnotation: "bj-old"}}, + Spec: cnpgtypes.ObjectStoreSpec{Configuration: cnpgtypes.BarmanObjectStoreConfiguration{DestinationPath: "s3://bucket/"}}, + } + if err := f.c.Create(context.Background(), store); err != nil { + t.Fatalf("seed ObjectStore: %v", err) + } + pass2 := f.addJobWithDestination("bj2", "s3://other/") + + f.pass() // latch + if j, _ := f.pass(); apimeta.FindStatusCondition(j.Status.Conditions, "Ready").Reason != "WaitingForPluginRollout" { + t.Fatalf("Ready = %+v, want bj waiting for the rollout of the plugin it attached", apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } + j2 := pass2() + if got := f.liveDestination(); got != "s3://bucket/" { + t.Errorf("destination = %q, switched during bj's rollout", got) + } + if ready := apimeta.FindStatusCondition(j2.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForOtherBackup" || !strings.Contains(ready.Message, "BackupJob bj ") { + t.Errorf("bj2 Ready = %+v, want WaitingForOtherBackup naming bj", ready) + } +} + +// The claim covers only the window before its job has a Backup the queue +// can see. Once it has one, the Backup in flight holds the destination, for +// as long as CloudNativePG runs it, and a Backup that finished does not, even +// if its job is stuck before it finishes, so that job cannot hold every later +// backup of the application for as long as it lives. +func TestReconcileCNPG_ClaimOfAJobWithItsOwnBackupDoesNotHold(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) + f.seedCNPGBackup("bj-other-cnpg", "bj-other", rolloutCluster, cnpgBackupPhaseComplete) + store := f.liveObjectStore() + store.Annotations = map[string]string{cnpgDestinationWrittenByAnnotation: "bj-other"} + if err := f.c.Update(context.Background(), store); err != nil { + t.Fatalf("seed claim: %v", err) + } + j, _ := f.pass() + if got := f.liveDestination(); got != "s3://bucket/" { + t.Errorf("destination = %q, held by a job whose Backup already finished", got) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready != nil && ready.Reason == "WaitingForOtherBackup" { + t.Errorf("Ready = %+v, held by a job whose Backup already finished", ready) + } +} + +// A claim whose job cannot be read cannot be taken as released: writing over +// it would let two jobs flip the destination again. The error goes back to +// the controller for a retry. +func TestReconcileCNPG_ClaimHolderLookupErrorIsReturned(t *testing.T) { + unavailable := apierrors.NewServiceUnavailable("apiserver unavailable") + for name, setup := range map[string]func(f *cnpgRolloutFixture){ + "holder job read fails": func(f *cnpgRolloutFixture) { + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*backupsv1alpha1.BackupJob); ok && key.Name == "bj-other" { + return unavailable + } + return cl.Get(ctx, key, obj, opts...) + }, + }) + }, + "holder Backups list fails": func(f *cnpgRolloutFixture) { + holders := labels.Set{backupsv1alpha1.OwningJobNameLabel: "bj-other", backupsv1alpha1.OwningJobNamespaceLabel: rolloutNS} + f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + lo := &client.ListOptions{} + lo.ApplyOptions(opts) + if _, ok := list.(*cnpgtypes.BackupList); ok && lo.LabelSelector != nil && lo.LabelSelector.Matches(holders) && !lo.LabelSelector.Matches(labels.Set{backupsv1alpha1.OwningJobNameLabel: "bj", backupsv1alpha1.OwningJobNamespaceLabel: rolloutNS}) { + return unavailable + } + return cl.List(ctx, list, opts...) + }, + }) + }, + } { + t.Run(name, func(t *testing.T) { + assertClaimHolderLookupErrorReturned(t, setup) + }) + } +} + +func assertClaimHolderLookupErrorReturned(t *testing.T, setup func(f *cnpgRolloutFixture)) { + t.Helper() + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) + store := f.liveObjectStore() + store.Annotations = map[string]string{cnpgDestinationWrittenByAnnotation: "bj-other"} + if err := f.c.Update(context.Background(), store); err != nil { + t.Fatalf("seed claim: %v", err) + } + setup(f) + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(context.Background(), client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(context.Background(), j, f.resolved); err == nil { + t.Fatalf("reconcileCNPG swallowed the claim holder lookup error") + } + if got := f.liveDestination(); got != "s3://other/" { + t.Errorf("destination written although the claim holder could not be read: %q", got) + } +} + +// A running job that holds the claim keeps the destination while it has no +// Backup yet, for instance while the plugin it attached rolls the instances. +func TestReconcileCNPG_ClaimOfARunningJobHolds(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + f.seedOtherBackupJob("bj-other", backupsv1alpha1.BackupJobPhaseRunning) + store := f.liveObjectStore() + store.Annotations = map[string]string{cnpgDestinationWrittenByAnnotation: "bj-other"} + if err := f.c.Update(context.Background(), store); err != nil { + t.Fatalf("seed claim: %v", err) + } + j, backups, res := f.passResult() + if got := f.liveDestination(); got != "s3://other/" { + t.Errorf("destination = %q, rewritten under bj-other's claim", got) + } + if len(backups) != 0 { + t.Errorf("a cnpg.io/Backup was created under another job's claim: %+v", backups) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForOtherBackup" || !strings.Contains(ready.Message, "bj-other") { + t.Errorf("Ready = %+v, want WaitingForOtherBackup naming bj-other", ready) + } + if res.RequeueAfter == 0 { + t.Errorf("a held job is not requeued: %+v", res) + } +} + +// The plugin sidecar reads the ObjectStore through a cache that nothing this +// controller writes invalidates, so a Backup created right after the +// destination changed can be taken against the previous one. The job holds +// the Backup until that cache has expired, and creates it afterwards. +func TestReconcileCNPG_BackupWaitsForThePluginCacheAfterADestinationChange(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + + j, backups, res := f.passResult() + if got := f.liveDestination(); got != "s3://bucket/" { + t.Fatalf("destination = %q, want the job's s3://bucket/", got) + } + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created in the pass that changed the destination: %+v", backups) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForDestinationToSettle" { + t.Errorf("Ready = %+v, want WaitingForDestinationToSettle", ready) + } + if res.RequeueAfter == 0 { + t.Errorf("a waiting job is not requeued: %+v", res) + } + stamp, err := time.Parse(time.RFC3339, f.liveObjectStore().Annotations[cnpgDestinationChangedAtAnnotation]) + if err != nil || time.Since(stamp) > time.Minute { + t.Fatalf("%s = %v (%v), want the time of this write", cnpgDestinationChangedAtAnnotation, stamp, err) + } + + if _, backups = f.pass(); len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created while the plugin cache could still hold the old destination: %+v", backups) + } + + f.setDestinationStamp(time.Now().Add(-time.Minute).UTC().Format(time.RFC3339)) + if j, backups = f.pass(); len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups once the cache expired, want 1; Ready = %+v", len(backups), apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } +} + +// A write that leaves the configuration as it was cannot leave a stale +// cache behind: the Backup is created at once, and the record of the last +// change is re-sent as it is, since an apply that left it out would delete it. +func TestReconcileCNPG_UnchangedDestinationDoesNotWait(t *testing.T) { + const stamp = "2026-01-02T03:04:05Z" + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://bucket/") + f.setDestinationStamp(stamp) + + if j, backups := f.pass(); len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups for an unchanged destination, want 1; Ready = %+v", len(backups), apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } + if got := f.liveObjectStore().Annotations[cnpgDestinationChangedAtAnnotation]; got != stamp { + t.Errorf("%s = %q, want the recorded %q", cnpgDestinationChangedAtAnnotation, got, stamp) + } +} + +// The apiserver answers an apply with the merged object: fields it defaults, +// or that another field manager owns, are there although the job never sets +// them. Judged against what the job sends, every pass would read as a change +// and the Backup would never be created; judged against the dry run of the +// same apply, an unchanged configuration stays unchanged. +func TestReconcileCNPG_FieldsTheJobDoesNotSetAreNotAChange(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://bucket/") + store := f.liveObjectStore() + store.Spec.Configuration.Wal = &cnpgtypes.WalBackupConfiguration{Compression: "gzip"} + if err := f.c.Update(context.Background(), store); err != nil { + t.Fatalf("seed ObjectStore: %v", err) + } + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + po := &client.PatchOptions{} + po.ApplyOptions(opts) + if os, ok := obj.(*cnpgtypes.ObjectStore); ok && slices.Contains(po.DryRun, metav1.DryRunAll) { + os.Spec.Configuration.Wal = &cnpgtypes.WalBackupConfiguration{Compression: "gzip"} + return nil + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + + if j, backups := f.pass(); len(backups) != 1 { + t.Fatalf("got %d cnpg.io/Backups for a configuration only the server filled in, want 1; Ready = %+v", len(backups), apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } + if _, ok := f.liveObjectStore().Annotations[cnpgDestinationChangedAtAnnotation]; ok { + t.Errorf("%s was set by a write that changed nothing", cnpgDestinationChangedAtAnnotation) + } +} + +// Without the live ObjectStore, or the dry run of the apply, the job cannot +// tell whether its write changes the destination, and taking the write as +// unchanged would create the Backup at once against a cache that may still +// hold the previous one. Either failure is retried like a failed write. +func TestReconcileCNPG_UnreadableObjectStoreIsRetried(t *testing.T) { + unavailable := apierrors.NewServiceUnavailable("apiserver unavailable") + for _, tc := range []struct { + name string + setup func(f *cnpgRolloutFixture) + }{ + {name: "live read fails", setup: func(f *cnpgRolloutFixture) { + f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*cnpgtypes.ObjectStore); ok { + return unavailable + } + return cl.Get(ctx, key, obj, opts...) + }, + }) + }}, + {name: "claim read fails", setup: func(f *cnpgRolloutFixture) { + reads := 0 + f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*cnpgtypes.ObjectStore); ok { + if reads++; reads == 1 { + return unavailable + } + } + return cl.Get(ctx, key, obj, opts...) + }, + }) + }}, + {name: "live read at the write fails", setup: func(f *cnpgRolloutFixture) { + reads := 0 + f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*cnpgtypes.ObjectStore); ok { + if reads++; reads > 1 { + return unavailable + } + } + return cl.Get(ctx, key, obj, opts...) + }, + }) + }}, + {name: "dry run fails", setup: func(f *cnpgRolloutFixture) { + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + po := &client.PatchOptions{} + po.ApplyOptions(opts) + if _, ok := obj.(*cnpgtypes.ObjectStore); ok && slices.Contains(po.DryRun, metav1.DryRunAll) { + return unavailable + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://other/") + tc.setup(f) + assertObjectStoreReadRetried(t, f) + }) + } +} + +// assertObjectStoreReadRetried runs one pass and checks it is retried, either +// by returning the error to the controller or by waiting with +// ClusterPluginApplyRetrying, without a Backup, a destination write or a +// failed job. +func assertObjectStoreReadRetried(t *testing.T, f *cnpgRolloutFixture) { + t.Helper() + ctx := context.Background() + key := client.ObjectKey{Namespace: rolloutNS, Name: "bj"} + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, key, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + res, reconcileErr := f.r.reconcileCNPG(ctx, j, f.resolved) + if err := f.c.Get(ctx, key, j); err != nil { + t.Fatalf("get BackupJob after reconcile: %v", err) + } + backups := &cnpgtypes.BackupList{} + if err := f.c.List(ctx, backups, client.InNamespace(rolloutNS)); err != nil { + t.Fatalf("list cnpg.io/Backups: %v", err) + } + if len(backups.Items) != 0 { + t.Fatalf("a cnpg.io/Backup was created although the ObjectStore could not be read: %+v", backups.Items) + } + if got := f.liveDestination(); got != "s3://other/" { + t.Errorf("destination = %q, written without knowing whether it changed", got) + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the job failed on a transient read: %s", j.Status.Message) + } + if reconcileErr != nil { + return + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "ClusterPluginApplyRetrying" { + t.Errorf("Ready = %+v, want ClusterPluginApplyRetrying", ready) + } + if res.RequeueAfter == 0 { + t.Errorf("a retried read is not requeued: %+v", res) + } +} + +// A change record that cannot be read, or that lies further ahead than +// controller clocks drift, says nothing about when the cache expires, so the +// write replaces it with its own time and the job waits once. It claims the +// destination for that wait, or another job would write its own meanwhile. +func TestReconcileCNPG_UnusableDestinationRecordIsReplaced(t *testing.T) { + for name, value := range map[string]string{ + "does not parse": "yesterday", + "far ahead": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + } { + t.Run(name, func(t *testing.T) { + f := newAttachedObjectStoreFixture(t, time.Now().Add(-time.Hour), "s3://bucket/") + f.seedOtherBackupJob("bj-old", backupsv1alpha1.BackupJobPhaseSucceeded) + store := f.liveObjectStore() + store.Annotations = map[string]string{cnpgDestinationWrittenByAnnotation: "bj-old"} + if err := f.c.Update(context.Background(), store); err != nil { + t.Fatalf("seed claim: %v", err) + } + f.setDestinationStamp(value) + + j, backups := f.pass() + if len(backups) != 0 { + t.Fatalf("a cnpg.io/Backup was created with an unusable change record: %+v", backups) + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("the job failed: %s", j.Status.Message) + } + stamp, err := time.Parse(time.RFC3339, f.liveObjectStore().Annotations[cnpgDestinationChangedAtAnnotation]) + if err != nil || time.Since(stamp) > time.Minute || time.Until(stamp) > time.Minute { + t.Fatalf("%s = %v (%v), want it replaced with the time of this write", cnpgDestinationChangedAtAnnotation, stamp, err) + } + if got := f.liveObjectStore().Annotations[cnpgDestinationWrittenByAnnotation]; got != "bj" { + t.Errorf("%s = %q, want bj, which waits on the replaced record", cnpgDestinationWrittenByAnnotation, got) + } + }) + } +} + // A later write to a Cluster that already carries the plugin re-sends the // attach record as it is: moving it would make the instances that rolled // with the plugin look older than the attach. @@ -5913,9 +6482,11 @@ func TestReconcileCNPG_ArtifactNamesTheDestinationItsBackupWasCreatedWith(t *tes f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") f.setStrategyDestination("s3://bucket/", "https://s3.one", "creds-one") + f.pass() + f.settleDestination() j, backups := f.pass() if len(backups) != 1 { - t.Fatalf("got %d cnpg.io/Backups after the first pass, want 1; Ready = %+v", len(backups), apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + t.Fatalf("got %d cnpg.io/Backups once the destination settled, want 1; Ready = %+v", len(backups), apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) } if got := f.liveDestination(); got != "s3://bucket/" { t.Fatalf("destination = %q, want s3://bucket/", got) @@ -6021,7 +6592,7 @@ func TestReconcileCNPG_ArtifactRefusedForAnUnusableDestinationRecord(t *testing. "mistyped endpoint": `{"destinationPath":"s3://bucket/","endpointURL":7}`, } { t.Run(name, func(t *testing.T) { - f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://bucket/") if _, backups := f.pass(); len(backups) != 1 { t.Fatalf("got %d cnpg.io/Backups after the first pass, want 1", len(backups)) } @@ -6175,7 +6746,7 @@ func TestReconcileCNPG_BackupListErrorIsReturned(t *testing.T) { // start: a second lookup before the create could only fail, after the write, // and fail the job with it. func TestReconcileCNPG_LooksUpItsOwnBackupOncePerPass(t *testing.T) { - f := newAttachedObjectStoreFixture(t, time.Now(), "s3://other/") + f := newAttachedObjectStoreFixture(t, time.Now(), "s3://bucket/") f.failingBackupLists(func(own bool, n int) bool { return own && n > 1 }) j, backups := f.pass() From 5c6fc10a235c8ff51939fb6b0282fcee13f82b6e Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 12 Nov 2026 17:02:40 +0300 Subject: [PATCH 26/26] test(postgres): pin three guards no test caught when changed A job whose own Backup exists skips the wait for another job's plugin rollout, and the size probe keeps the strategy's Secret key names while it takes the Secret from the record, adding a credentials block only when the strategy has none. Each of these could be changed with the suite still green: dropping the own-Backup check, or forcing the missing-credentials branch either way. Cases for a job with a running Backup next to a recent foreign attach, a strategy without credentials and a strategy with custom key names now fail on each change. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .../cnpg_artifact_size_test.go | 62 +++++++++++++++++++ .../cnpgstrategy_controller_test.go | 17 +++++ 2 files changed, 79 insertions(+) diff --git a/internal/backupcontroller/cnpg_artifact_size_test.go b/internal/backupcontroller/cnpg_artifact_size_test.go index 29209c5f1..bdf9c5d7b 100644 --- a/internal/backupcontroller/cnpg_artifact_size_test.go +++ b/internal/backupcontroller/cnpg_artifact_size_test.go @@ -514,3 +514,65 @@ func TestCreateCNPGBackupArtifact_SizeProbeSkipsARecordWithoutCredentials(t *tes t.Errorf("Artifact = %#v, want no size", got.Status.Artifact) } } + +// probeRecordedBackup runs createCNPGBackupArtifact for a backup recorded as +// written with credentials Secret recordedSecret, against rendered, and +// returns the size it measured and the connection it measured through. +func probeRecordedBackup(t *testing.T, rendered *strategyv1alpha1.CNPGTemplate, recordedSecret *corev1.Secret) (int64, s3Connection) { + t.Helper() + apiGroup := backupsv1alpha1.DefaultApplicationAPIGroup + j := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "bj-probe"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{APIGroup: &apiGroup, Kind: postgresAppKind, Name: "pg"}, + }, + } + cnpgBk := &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}, Status: cnpgtypes.BackupStatus{BackupID: "20261021T100000"}} + secretName := recordedSecret.Name + written := cnpgDestination{DestinationPath: "s3://bkt/tenant/pg/", EndpointURL: "https://s3.example:8443", S3SecretRef: &secretName} + l := &fakeS3Lister{objects: []s3ObjectInfo{{Key: "tenant/pg/srv/base/20261021T100000/data.tar.gz", Size: 42}}} + r := reconcilerWithLister(t, l) + r.Client = newCNPGStrategyTestClient(t, recordedSecret) + + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", written, rendered, newPostgresApp("pg", "tenant")) + if err != nil { + t.Fatalf("createCNPGBackupArtifact: %v", err) + } + if got.Status.Artifact == nil { + t.Fatalf("no artifact") + } + return got.Status.Artifact.SizeBytes, l.conn +} + +// A strategy that has since dropped its credentials still measures a backup +// recorded with a Secret, through that Secret and its default keys. +func TestCreateCNPGBackupArtifact_SizeProbeOfARecordedSecretUnderAStrategyWithoutCredentials(t *testing.T) { + store := newSizedBarmanObjectStore() + store.S3Credentials = nil + size, conn := probeRecordedBackup(t, &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: *store}, s3CredsSecret("tenant", "creds-recorded")) + if size != 42 { + t.Errorf("SizeBytes = %d, want 42 measured through the recorded Secret", size) + } + if conn.AccessKey != "AKID" { + t.Errorf("probed with access key %q, want the recorded Secret's AKID", conn.AccessKey) + } +} + +// The record names the Secret, not its keys: the strategy's key names stay, +// so a strategy with its own key names still reads the recorded Secret. +func TestCreateCNPGBackupArtifact_SizeProbeKeepsTheStrategysSecretKeys(t *testing.T) { + store := newSizedBarmanObjectStore() + store.S3Credentials.AccessKeyIDKey = "id" + store.S3Credentials.SecretAccessKeyKey = "key" + secret := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "creds-recorded"}, + Data: map[string][]byte{"id": []byte("CUSTOMID"), "key": []byte("custom-secret")}, + } + size, conn := probeRecordedBackup(t, &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: *store}, secret) + if size != 42 { + t.Errorf("SizeBytes = %d, want 42 measured with the strategy's key names", size) + } + if conn.AccessKey != "CUSTOMID" { + t.Errorf("probed with access key %q, want CUSTOMID read under the strategy's key name", conn.AccessKey) + } +} diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index bbfc8b0d7..5cd990f18 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -3824,6 +3824,23 @@ func TestReconcileCNPG_JobWithoutLatchWaitsForAnotherJobsRollout(t *testing.T) { } } +// A job whose own Backup already exists is past every wait before it: it +// tracks that Backup even while another job's recent attach is still rolling +// the instances, since waiting would only hold the result of a Backup that +// runs regardless. +func TestReconcileCNPG_JobWithItsOwnBackupDoesNotWaitForAnotherJobsRollout(t *testing.T) { + cluster := newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)) + cluster.Annotations = map[string]string{cnpgPluginAttachedAtAnnotation: time.Now().Add(-5 * time.Minute).UTC().Format(time.RFC3339)} + f := newCNPGRolloutFixture(t, newRolloutBackupJob(time.Now().Add(-time.Hour)), cluster, + newRolloutInstancePod(time.Now().Add(-10*time.Minute).Truncate(time.Second))) + f.seedCNPGBackup("bj-cnpg", "bj", rolloutCluster, "running") + + j, _ := f.pass() + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForCNPGBackup" { + t.Errorf("Ready = %+v, want WaitingForCNPGBackup tracking the job's own Backup", ready) + } +} + // A plugin attached by someone else after the latch, another backup job or // the chart re-rendering a restored Cluster outside the platform flow, // started the rollout before this job's write, which only finds it there: