fix(clickhouse): keep a quota-held archive delete and count a failed one once (#5415)

<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, security (a fix that comes through a security
advisory), docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Fixes merged to `main` reach the release lines the backport batch runs
for automatically, so do not open backport PRs by hand:
https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md
-->

## What this PR does

<!-- Link the issues this PR addresses. For a complete fix targeting the
default branch, use Closes #N (Closes owner/repository#N for another
repository). Otherwise use a non-closing reference; release-branch PRs
need manual issue linking and closure when appropriate. -->

Closes #5198.

Follow-up to #5224, closing three gaps in how a ClickHouse archive
delete on the system bucket treats a refused or failed cleanup Job.

- A cleanup Job a ResourceQuota refuses with `status unknown for
quota:`, which the quota admission returns until the quota controller
has computed the usage, released the `Backup` and left its archive in
the bucket for good, although the refusal clears by itself. It is now
retried like `exceeded quota:`; any other `Forbidden` or `Invalid`
refusal still releases the `Backup` with `ArtifactNotDeleted`.
- A cleanup Job a quota refuses now raises an `ArtifactCleanupFailed`
Warning Event on the `Backup`, so a `Backup` held terminating by a quota
says why.
- Recording a failed cleanup Job on the `Backup` starts the next
reconcile at once, while the Job cache can still hold the Job just
deleted, so one failure could be counted twice: a second Event and the
retry wait doubled once more. The UID of the counted Job is now kept on
the `Backup` under
`altinity.strategy.backups.cozystack.io/cleanup-failed-job`, and a
failed Job with that UID is only deleted.
- The restore scenario now says that the skip annotation stops only new
cleanup Jobs (a cleanup Pod that already exists can still start a
delete), and that a quota-refused delete holds the `Backup` until the
annotation releases it.

Covered by unit tests through the fake client, each guard checked by
mutation; not run against a cluster.

Out of scope, found while reviewing: the Kafka, Kubernetes, Redis and
RabbitMQ strategy controllers release a `Backup` on any `Forbidden` from
the cleanup Job create, a quota refusal included, so on a namespace
whose Job quota is full their archives are left behind the same way.

### Screenshots

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

### Downstream repositories

<!--
Cozystack is upstream for repositories that are NOT kept in sync with it
automatically, and nothing in CI compares the two sides, so a change
here can break them silently.

Which change forces what, and which file to touch, is the trigger map in
docs/agents/contributing.md under "Downstream Repositories". Walk it
before you tick anything.

IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM
TO FILL IN:

1. Walk the trigger map against the actual diff of this PR, file by
file. Do not decide from the PR title or from your memory of what you
changed.
2. For every repository you tick, open the follow-up PR there and link
it on the same line. A ticked box with no link claims work that does not
exist, which is worse than an empty box. Search that repository for an
open PR or issue covering it first, and link that instead of filing a
duplicate.
3. When the follow-up is out of scope, or needs a decision that is not
yours to make, open an issue in that repository instead, link that, and
say so in the PR body. Do not push a speculative PR into another
repository just to fill a line here.
4. Do not tick "No downstream repository is affected" to make the
checklist go away. If you are unsure, leave every box empty and say so
in the PR body, so a human decides.
-->

- [ ] No downstream repository is affected by this change
- [x] [cozystack/website](https://github.com/cozystack/website) -
follow-up: cozystack/website#809 (the ClickHouse archive delete page,
updated for the quota retry and the skip annotation wording)
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

<!--  Write a release note:
- Explain what has changed internally and for users.
- Start with the same `type(scope):` prefix as in the PR title
- Follow the guidelines at
https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md.
-->

```release-note
fix(clickhouse): a ClickHouse archive delete whose cleanup Job a ResourceQuota refuses, including before the quota's usage is known, now keeps the Backup and retries with an ArtifactCleanupFailed Warning Event instead of releasing it and leaving the archive; a failed cleanup Job is counted once.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Backups are retained when cleanup Jobs are refused due to quota
limits, with a warning and retry when quota permits.
* Repeated reconciliation of the same failed cleanup Job no longer
increments the failure count or emits duplicate warnings.
* Invalid cleanup errors continue to release the Backup, even if the
error message mentions quota.
* Clarified that cleanup may continue if a Pod has already started or a
sidecar has accepted the deletion.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
scooby87 authored and GitHub committed 2026-11-24 15:39:19 +03:00
commit fc5ece0a28
3 files changed
+174 -5

No files matched your search

@@ -51,5 +51,5 @@ The script:
- Both flows assume the strategy template uses `.Mode` to switch between
`create_remote` and `restore_remote`. See `01-create-strategy.sh`.
- On `backup.useSystemBucket: true`, deleting the Cozystack `Backup` deletes its archive through the sidecar and the `Backup` stays until that delete finished. When the ClickHouse application is already gone or no longer uses the system bucket, the platform's system bucket is no longer the one the `Backup` records its archive in (also when it changes while the delete runs), or the archive is named without its BackupJob's UID (a backup still running when the controller was upgraded, whose name another run of the same second may share), the `Backup` is released with an `ArtifactNotDeleted` Warning Event naming the archive left in the bucket; a delete that fails is retried, after a wait that starts at 30 seconds and doubles with each failure up to 30 minutes, and each failure is reported as an `ArtifactCleanupFailed` Warning Event; the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation releases it without starting a delete, though a delete the sidecar already accepted still runs to the end. A `Backup` taken before the archive name was recorded, or by a strategy that does not use `.ArchiveName`, does not name its archive and leaves it behind. So does a `Backup` that names its archive but not the bucket setting, as one recorded by a controller older than this behaviour does; it is released without an Event.
- On `backup.useSystemBucket: true`, deleting the Cozystack `Backup` deletes its archive through the sidecar and the `Backup` stays until that delete finished. When the ClickHouse application is already gone or no longer uses the system bucket, the platform's system bucket is no longer the one the `Backup` records its archive in (also when it changes while the delete runs), or the archive is named without its BackupJob's UID (a backup still running when the controller was upgraded, whose name another run of the same second may share), the `Backup` is released with an `ArtifactNotDeleted` Warning Event naming the archive left in the bucket; a delete that fails is retried, after a wait that starts at 30 seconds and doubles with each failure up to 30 minutes, and each failure is reported as an `ArtifactCleanupFailed` Warning Event; a cleanup Job a ResourceQuota refuses is reported the same way, and the `Backup` stays while the quota refuses the Job, unless the annotation below releases it; the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation releases it without creating another cleanup Job; a cleanup Pod that already exists can still start a delete until it is removed, and a delete the sidecar already accepted still runs to the end. A `Backup` taken before the archive name was recorded, or by a strategy that does not use `.ArchiveName`, does not name its archive and leaves it behind. So does a `Backup` that names its archive but not the bucket setting, as one recorded by a controller older than this behaviour does; it is released without an Event.
- On the tenant's own bucket the archive's lifecycle stays the tenant's: deleting the `Backup` leaves it, and `POST /backup/delete/remote/<name>` on the sidecar (port 7171, basic auth from the `<release>-backup-api-auth` Secret) deletes one by hand.
@@ -21,6 +21,7 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
@@ -565,6 +566,101 @@ func TestCleanupAltinityBackup_FailedJobBacksOff(t *testing.T) {
}
}
// Recording the failure updates the Backup, which starts the next reconcile
// at once, and the Job cache can still hold the failed Job the controller has
// just deleted. That Job is counted once: seen again, it is deleted without a
// second Event and without doubling the wait.
func TestCleanupAltinityBackup_CountsAFailedJobOnce(t *testing.T) {
backup := altinityCleanupBackup("ch-bk")
retryAt := time.Now().Add(altinityCleanupRetryBase).UTC().Format(time.RFC3339)
backup.Annotations = map[string]string{
altinityCleanupFailuresAnnotation: "1",
altinityCleanupRetryAfterAnnotation: retryAt,
altinityCleanupFailedJobAnnotation: "failed-job-uid",
}
failed := ownCleanupJob(backup)
failed.UID = "failed-job-uid"
failed.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded"}}
c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), failed)...)
rec := record.NewFakeRecorder(10)
r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec}
res, err := r.cleanupOnDelete(context.Background(), backup)
if err != nil {
t.Fatalf("cleanupOnDelete: %v", err)
}
if res.RequeueAfter <= 0 || res.RequeueAfter > altinityCleanupRetryBase {
t.Errorf("RequeueAfter = %s, want what is left of the wait already set", res.RequeueAfter)
}
got := &backupsv1alpha1.Backup{}
if err := c.Get(context.Background(), client.ObjectKeyFromObject(backup), got); err != nil {
t.Fatalf("get Backup: %v", err)
}
if f := got.Annotations[altinityCleanupFailuresAnnotation]; f != "1" {
t.Errorf("failures = %q, want the one failure counted once", f)
}
if at := got.Annotations[altinityCleanupRetryAfterAnnotation]; at != retryAt {
t.Errorf("retry-after = %q, want the one already set, %q", at, retryAt)
}
if len(rec.Events) != 0 {
t.Errorf("unexpected event %q for a failure already reported", <-rec.Events)
}
if left := listJobs(t, c); len(left) != 0 {
t.Errorf("expected the failed Job collected, %d left", len(left))
}
}
// A counted Job seen again after its wait has run out still holds the Backup:
// releasing it there would drop the finalizer with the archive undeleted.
func TestCleanupAltinityBackup_KeepsTheBackupWhenACountedJobOutlivesItsWait(t *testing.T) {
backup := altinityCleanupBackup("ch-bk")
backup.Annotations = map[string]string{
altinityCleanupFailuresAnnotation: "1",
altinityCleanupRetryAfterAnnotation: time.Now().Add(-time.Minute).UTC().Format(time.RFC3339),
altinityCleanupFailedJobAnnotation: "failed-job-uid",
}
failed := ownCleanupJob(backup)
failed.UID = "failed-job-uid"
failed.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded"}}
c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), failed)...)
r := &BackupReconciler{Client: c, Scheme: s, Recorder: record.NewFakeRecorder(10)}
res, err := r.cleanupOnDelete(context.Background(), backup)
if err != nil {
t.Fatalf("cleanupOnDelete: %v", err)
}
if res.RequeueAfter <= 0 {
t.Errorf("RequeueAfter = %s: the Backup must stay until a delete succeeds", res.RequeueAfter)
}
}
// A new failed Job, under the same name, is counted even when an earlier one
// was: its UID is not the one recorded.
func TestCleanupAltinityBackup_CountsANewFailedJob(t *testing.T) {
backup := altinityCleanupBackup("ch-bk")
backup.Annotations = map[string]string{
altinityCleanupFailuresAnnotation: "1",
altinityCleanupFailedJobAnnotation: "earlier-job-uid",
}
failed := ownCleanupJob(backup)
failed.UID = "new-job-uid"
failed.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded"}}
c, s := newAltinityCleanupClient(append(altinityCleanupFixtures(backup), failed)...)
rec := record.NewFakeRecorder(10)
r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec}
if _, err := r.cleanupOnDelete(context.Background(), backup); err != nil {
t.Fatalf("cleanupOnDelete: %v", err)
}
got := &backupsv1alpha1.Backup{}
if err := c.Get(context.Background(), client.ObjectKeyFromObject(backup), got); err != nil {
t.Fatalf("get Backup: %v", err)
}
if f, j := got.Annotations[altinityCleanupFailuresAnnotation], got.Annotations[altinityCleanupFailedJobAnnotation]; f != "2" || j != "new-job-uid" {
t.Errorf("failures = %q, counted Job = %q; want 2 and new-job-uid", f, j)
}
if len(rec.Events) != 1 {
t.Errorf("events = %d, want one for the new failure", len(rec.Events))
}
}
// The wait is recorded before the failed Job is deleted, so a delete that
// fails leaves the Backup waiting rather than free to start the next Job at
// once.
@@ -1374,6 +1470,9 @@ func TestCleanupAltinityBackup_ReleasesWhenTheJobIsRefused(t *testing.T) {
for name, refuse := range map[string]error{
"invalid": apierrors.NewInvalid(batchv1.SchemeGroupVersion.WithKind("Job").GroupKind(), "ch-bk-cleanup", nil),
"forbidden": apierrors.NewForbidden(batchv1.Resource("jobs"), "ch-bk-cleanup", errors.New("service account cannot create jobs")),
// Only a Forbidden is a quota refusal, whatever an Invalid's text says.
"invalid naming a quota": apierrors.NewInvalid(batchv1.SchemeGroupVersion.WithKind("Job").GroupKind(), "ch-bk-cleanup",
field.ErrorList{field.Invalid(field.NewPath("metadata", "name"), "ch-bk-cleanup", "exceeded quota: jobs-quota")}),
} {
t.Run(name, func(t *testing.T) {
backup := altinityCleanupBackup("ch-bk")
@@ -1404,6 +1503,44 @@ func TestCleanupAltinityBackup_ReleasesWhenTheJobIsRefused(t *testing.T) {
}
}
// A namespace ResourceQuota on Jobs refuses the cleanup Job with Forbidden while
// the quota is used up, or before its usage is known. That clears once other
// Jobs go or the quota controller has computed the usage, and releasing the
// Backup on it would leave the archive for good, so the Backup is held and the
// create retried. The messages are the ones the ResourceQuota admission plugin
// of k8s.io/apiserver returns.
func TestCleanupAltinityBackup_RetriesAJobRefusedByAQuota(t *testing.T) {
for name, msg := range map[string]string{
"quota used up": "exceeded quota: jobs-quota, requested: count/jobs.batch=1, used: count/jobs.batch=5, limited: count/jobs.batch=5",
"quota usage unknown": "status unknown for quota: jobs-quota, resources: count/jobs.batch",
} {
t.Run(name, func(t *testing.T) {
backup := altinityCleanupBackup("ch-bk")
c, s := newAltinityCleanupClientWith(interceptor.Funcs{
Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
if _, ok := obj.(*batchv1.Job); ok {
return apierrors.NewForbidden(batchv1.Resource("jobs"), "ch-bk-cleanup", errors.New(msg))
}
return c.Create(ctx, obj, opts...)
},
}, altinityCleanupFixtures(backup)...)
rec := record.NewFakeRecorder(10)
r := &BackupReconciler{Client: c, Scheme: s, Recorder: rec}
if _, err := r.cleanupOnDelete(context.Background(), backup); err == nil {
t.Fatal("a cleanup Job refused by a quota must go back to the work queue with the Backup held, not release it")
}
// The Backup stays terminating, so the refusal is named on it
// rather than only in the controller log.
if len(rec.Events) == 0 {
t.Fatal("a cleanup Job refused by a quota must surface as a Warning Event")
}
if ev := <-rec.Events; !strings.Contains(ev, "Warning ArtifactCleanupFailed") || !strings.Contains(ev, "quota") || strings.Contains(ev, "ArtifactNotDeleted") {
t.Errorf("event %q must be an ArtifactCleanupFailed Warning naming the quota", ev)
}
})
}
}
// Any other Create error is transient and goes back to the work queue with the
// Backup held.
func TestCleanupAltinityBackup_RetriesATransientCreateError(t *testing.T) {
@@ -75,9 +75,11 @@ const (
// The cleanup Job that failed is deleted to make room for the next one,
// so the count of failed attempts and the time the next may start are
// kept on the Backup.
// kept on the Backup, with the UID of the Job last counted, so that one
// still served from the cache is not counted twice.
altinityCleanupFailuresAnnotation = "altinity.strategy.backups.cozystack.io/cleanup-failures"
altinityCleanupRetryAfterAnnotation = "altinity.strategy.backups.cozystack.io/cleanup-retry-after"
altinityCleanupFailedJobAnnotation = "altinity.strategy.backups.cozystack.io/cleanup-failed-job"
// altinityCleanupRetryBase is the wait after the first failed cleanup
// Job; it doubles with each further failure up to altinityCleanupRetryMax.
@@ -1157,8 +1159,11 @@ func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *ba
rendered.Spec,
fmt.Sprintf("chi-clickhouse-%s-clickhouse-0-0.%s.svc", release, backup.Namespace), authSecret, archive)
if cerr := r.Create(ctx, desired); cerr != nil && !apierrors.IsAlreadyExists(cerr) {
// ResourceQuota also returns Forbidden. Once a Job slot frees up the same cleanup can run.
if apierrors.IsForbidden(cerr) && strings.Contains(cerr.Error(), "exceeded quota: ") {
if altinityQuotaRefusal(cerr) {
if r.Recorder != nil {
r.Recorder.Eventf(backup, corev1.EventTypeWarning, "ArtifactCleanupFailed",
"cleanup Job %s for archive %s was refused by a ResourceQuota (%v); retrying", jobKey.Name, archive, cerr)
}
return ctrl.Result{}, cerr
}
if apierrors.IsForbidden(cerr) || apierrors.IsInvalid(cerr) {
@@ -1210,6 +1215,19 @@ func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *ba
logger.Debug("Altinity archive deleted", "backup", backup.Name, "archive", archive)
return ctrl.Result{}, nil
case batchv1.JobFailed:
// Recording a failure updates the Backup, which starts the next
// reconcile while the Job cache may still hold the Job just deleted;
// a failure already counted is not counted or reported again.
if job.UID != "" && backup.Annotations[altinityCleanupFailedJobAnnotation] == string(job.UID) {
if derr := r.deleteAltinityCleanupJob(ctx, job); derr != nil {
return ctrl.Result{}, derr
}
wait := altinityCleanupRetryWait(ctx, backup, time.Now())
if wait <= 0 {
wait = altinityPollInterval
}
return ctrl.Result{RequeueAfter: wait}, nil
}
failures := altinityCleanupFailures(ctx, backup) + 1
delay := altinityCleanupRetryDelay(failures)
logger.Debug("Altinity cleanup Job failed; retrying", "backup", backup.Name, "job", job.Name, "failures", failures, "delay", delay)
@@ -1220,7 +1238,7 @@ func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *ba
"cleanup Job %s did not delete archive %s (%s: %s); retrying in %s", job.Name, archive, c.Reason, c.Message, delay)
}
// Recorded before the Job goes: should the delete below fail, the next
// reconcile counts this failure again and waits longer, rather than
// reconcile finds this Job counted and keeps waiting, rather than
// starting the next Job at once.
base := backup.DeepCopy()
if backup.Annotations == nil {
@@ -1228,6 +1246,7 @@ func (r *BackupReconciler) cleanupAltinityBackup(ctx context.Context, backup *ba
}
backup.Annotations[altinityCleanupFailuresAnnotation] = strconv.Itoa(failures)
backup.Annotations[altinityCleanupRetryAfterAnnotation] = time.Now().Add(delay).UTC().Format(time.RFC3339)
backup.Annotations[altinityCleanupFailedJobAnnotation] = string(job.UID)
if perr := r.Patch(ctx, backup, client.MergeFrom(base)); perr != nil {
return ctrl.Result{}, perr
}
@@ -1271,6 +1290,19 @@ func (r *BackupReconciler) altinityAppOnSystemBucket(ctx context.Context, backup
return app, v, true, nil
}
// altinityQuotaRefusal tells the Forbidden a namespace ResourceQuota returns
// while it is used up or its usage is not yet known, by the messages of the
// ResourceQuota admission plugin in k8s.io/apiserver. It clears once other
// Jobs go or the quota controller has computed the usage, so the create is
// retried instead of the Backup being released.
func altinityQuotaRefusal(err error) bool {
if !apierrors.IsForbidden(err) {
return false
}
msg := err.Error()
return strings.Contains(msg, "exceeded quota:") || strings.Contains(msg, "status unknown for quota:")
}
// altinitySystemBucket reads the bucket the projected credentials name in the
// namespace, the one the sidecar of a system-bucket application reads. It is
// empty when no credentials are projected there or they name no bucket.