Skip to content

[Bug]: Finalizer blocks namespace deletion when operator and operand in same namespace #10535

Description

@maxlengdell

Is there an existing issue already for this bug?

  • I have searched for an existing issue, and could not find anything. I believe this is a new bug.

I have read the troubleshooting guide

  • I have read the troubleshooting guide and I think this is a new bug.

I am running a supported version of CloudNativePG

  • I have read the troubleshooting guide and I think this is a new bug.

Contact Details

[email protected]

Version

1.29 (latest patch)

What version of Kubernetes are you using?

1.35

What is your Kubernetes environment?

Self-managed: kind (evaluation)

How did you install the operator?

Helm

What happened?

CloudNativePG Operator adds finalizers to Plugin Service, Database, Subscription and Publication CR. If these are deployed in the same namespace as the operator, when a kubectl delete namespace <namespace> is invoked, resources could be left stuck with namespace deletion pending. The finalizer is blocking the deletion, but since the operator is also deleted it may not have time to remove the finalizers before termination.

Since the plugin must be deployed in the same namespace as the operator, this race condition is somewhat unavoidable.
The CRD based resource finalizers can be discussed as a separate PR whether that's a bug or not

Issue can be reproduced by:

Installing operator

helm install cnpg https://github.com/cloudnative-pg/charts/releases/download/cloudnative-pg-v0.28.0/cloudnative-pg-0.28.0.tgz -n <TEST_NAMESPACE> --set config.clusterWide=false

Create cluster

cat <<EOF | kubectl apply -n <TEST_NAMESPACE> -f -
# Example of PostgreSQL cluster
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: cluster-example
spec:
  instances: 3
  storage:
    size: 1Gi
EOF

Create Database CR

cat <<EOF | kubectl apply  -n <TEST_NAMESPACE> -f -
# Example of PostgreSQL cluster
apiVersion: postgresql.cnpg.io/v1
kind: Database
metadata:
  name: app-db
spec:
  cluster:
    name: cluster-example
  name: app
  owner: app
  schemas:
    - name: data
      owner: app
EOF

If you want to inspect the finalizer
kubectl get database -n finalizer -o jsonpath='{range .items[*]}{.metadata.name}: {.metadata.finalizers}{"\n"}{end}'

Delete namespace

kubectl delete namespace <TEST_NAMESPACE>
namespace deletion is now stuck.

kubectl describe namespace <TEST_NAMESPACE>

Name:         <TEST_NAMESPACE>
Labels:       kubernetes.io/metadata.name=finalizer
Annotations:  <none>
Status:       Terminating
Conditions:
  Type                                         Status  LastTransitionTime               Reason                Message
  ----                                         ------  ------------------               ------                -------
  NamespaceDeletionDiscoveryFailure            False   Thu, 23 Apr 2026 14:08:14 +0200  ResourcesDiscovered   All resources successfully discovered
  NamespaceDeletionGroupVersionParsingFailure  False   Thu, 23 Apr 2026 14:08:14 +0200  ParsedGroupVersions   All legacy kube types successfully parsed
  NamespaceDeletionContentFailure              False   Thu, 23 Apr 2026 14:08:14 +0200  ContentDeleted        All content successfully deleted, may be waiting on finalization
  NamespaceContentRemaining                    True    Thu, 23 Apr 2026 14:08:22 +0200  SomeResourcesRemain   Some resources are remaining: databases.postgresql.cnpg.io has 1 resource instances
  NamespaceFinalizersRemaining                 True    Thu, 23 Apr 2026 14:08:22 +0200  SomeFinalizersRemain  Some content in the namespace has finalizers remaining: cnpg.io/deleteDatabase in 1 resource instances

Cluster resource

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: cluster-example
spec:
  instances: 3
  storage:
    size: 1Gi

Relevant log output

{"level":"info","ts":"2026-04-23T12:08:14.7511441Z","msg":"Stopping and waiting for non leader election runnables"}
{"level":"info","ts":"2026-04-23T12:08:14.752751053Z","msg":"Stopping and waiting for leader election runnables"}
{"level":"info","ts":"2026-04-23T12:08:14.752795589Z","msg":"Shutdown signal received, waiting for all workers to finish","controller":"cluster","controllerGroup":"postgresql.cnpg.io","controllerKind":"Cluster"}
{"level":"info","ts":"2026-04-23T12:08:14.752805809Z","msg":"Shutdown signal received, waiting for all workers to finish","controller":"pooler","controllerGroup":"postgresql.cnpg.io","controllerKind":"Pooler"}
{"level":"info","ts":"2026-04-23T12:08:14.752812511Z","msg":"Shutdown signal received, waiting for all workers to finish","controller":"plugin","controllerGroup":"","controllerKind":"Service"}
{"level":"info","ts":"2026-04-23T12:08:14.752817434Z","msg":"Shutdown signal received, waiting for all workers to finish","controller":"backup","controllerGroup":"postgresql.cnpg.io","controllerKind":"Backup"}
{"level":"info","ts":"2026-04-23T12:08:14.752822343Z","msg":"Shutdown signal received, waiting for all workers to finish","controller":"scheduled-backup","controllerGroup":"postgresql.cnpg.io","controllerKind":"ScheduledBackup"}
{"level":"info","ts":"2026-04-23T12:08:14.752851356Z","msg":"All workers finished","controller":"backup","controllerGroup":"postgresql.cnpg.io","controllerKind":"Backup"}
{"level":"info","ts":"2026-04-23T12:08:14.753193796Z","msg":"All workers finished","controller":"pooler","controllerGroup":"postgresql.cnpg.io","controllerKind":"Pooler"}
{"level":"info","ts":"2026-04-23T12:08:14.753316669Z","msg":"All workers finished","controller":"scheduled-backup","controllerGroup":"postgresql.cnpg.io","controllerKind":"ScheduledBackup"}
{"level":"info","ts":"2026-04-23T12:08:14.755176034Z","msg":"All workers finished","controller":"plugin","controllerGroup":"","controllerKind":"Service"}
{"level":"info","ts":"2026-04-23T12:08:14.751137579Z","msg":"Stopping and waiting for warmup runnables"}
{"level":"error","ts":"2026-04-23T12:08:14.779362398Z","msg":"Reconciler error","controller":"cluster","controllerGroup":"postgresql.cnpg.io","controllerKind":"Cluster","Cluster":{"name":"cluster-example","namespace":"finalizer"},"namespace":"finalizer","name":"cluster-example","reconcileID":"6c1c1017-a88a-4f4a-ab1c-7130956f8d86","error":"cannot reconcile required plugins: context canceled","stacktrace":"sigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller[...]).reconcileHandler\n\tpkg/mod/sigs.k8s.io/[email protected]/pkg/internal/controller/controller.go:495\nsigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller[...]).processNextWorkItem\n\tpkg/mod/sigs.k8s.io/[email protected]/pkg/internal/controller/controller.go:438\nsigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller[...]).Start.func1.1\n\tpkg/mod/sigs.k8s.io/[email protected]/pkg/internal/controller/controller.go:313"}
{"level":"info","ts":"2026-04-23T12:08:14.800383441Z","msg":"All workers finished","controller":"cluster","controllerGroup":"postgresql.cnpg.io","controllerKind":"Cluster"}
{"level":"info","ts":"2026-04-23T12:08:14.80044489Z","msg":"Stopping and waiting for caches"}
{"level":"info","ts":"2026-04-23T12:08:14.809943355Z","msg":"Stopping and waiting for webhooks"}
{"level":"info","ts":"2026-04-23T12:08:14.810851666Z","logger":"controller-runtime.webhook","msg":"Shutting down webhook server with timeout of 1 minute"}
{"level":"info","ts":"2026-04-23T12:08:14.811019537Z","msg":"Stopping and waiting for HTTP servers"}
{"level":"info","ts":"2026-04-23T12:08:14.81104744Z","logger":"controller-runtime.metrics","msg":"Shutting down metrics server with timeout of 1 minute"}
{"level":"info","ts":"2026-04-23T12:08:14.816212465Z","msg":"Wait completed, proceeding to shutdown the manager"}
{"level":"error","ts":"2026-04-23T12:08:14.856473876Z","msg":"error received after stop sequence was engaged","error":"leader election lost","stacktrace":"sigs.k8s.io/controller-runtime/pkg/manager.(*controllerManager).engageStopProcedure.func1\n\tpkg/mod/sigs.k8s.io/[email protected]/pkg/manager/internal.go:533"}

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. dosubot commented on Apr 23, 2026

    @dosubot

    @maxlengdell This is a legitimate race condition that has been investigated before. Two related bugs were identified and fixed in the main branch:

    1. Variable shadowing in error handling — In internal/controller/cluster_controller.go, errors from notifyDeletionToOwnedResources() (which removes Database finalizers) were logged but not returned due to variable shadowing. This meant the reconciliation loop saw "success" and didn't requeue, leaving finalizers orphaned. Fixed in PR #9431 (merged December 2025).

    2. Exponential backoff delaying finalizer removal — When a Cluster had a DeletionTimestamp, the controller continued normal reconciliation instead of immediately entering the deletion path. This caused failures trying to create resources in a terminating namespace, triggering exponential backoff that delayed finalizer removal significantly. Fixed in PR #9555 (merged December 2025).

    Both fixes are in the main branch but may not yet be in the 1.28 patch release you're running. You can check the release notes for your specific patch version.

    Immediate workaround — Manually remove the stuck finalizer:

    kubectl patch database app-db -n <TEST_NAMESPACE> -p '{"metadata":{"finalizers":[]}}' --type=merge

    It's also worth noting that running the operator in the same namespace as managed resources (namespaced mode) has additional architectural challenges around webhook management that are still being worked on [1] [2].

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

    Leave Feedback Ask Dosu about cloudnative-pg Share Dosu with your team

  2. maxlengdell commented on Apr 23, 2026

    @maxlengdell
    ContributorAuthor

    Hi @dosu, neither of these fixes address the race condition unfortunately. One solution to this would be to not add finalizers to database resources deployed with databaseReclaimPolicy: retain. I presume similar behavior is in place for the plugin finalizer as well.

  3. dosubot commented on Apr 23, 2026

    @dosubot

    @maxlengdell You raise a fair point. Looking at the code, the finalizer is indeed added unconditionally to all Database resources regardless of the databaseReclaimPolicy setting [1]. When the policy is retain (which is the default), the finalizer's deletion handler simply returns early without dropping the database and then removes the finalizer [2]. So for retain databases, the finalizer effectively does nothing useful during deletion — it just needs the operator to be alive to remove itself.

    The same pattern applies to Publication and Subscription resources, which also unconditionally add finalizers via the same generic finalizerReconciler[T] [3] [4].

    Your suggestion to skip adding the finalizer when databaseReclaimPolicy: retain makes sense as a way to avoid this race condition — there's no actual cleanup work to do in that case. The PRs I mentioned earlier (#9431, #9555) improved error handling and deletion path timing, but as you noted, they don't fundamentally address the race where the operator pod is terminated before it can process the finalizer removal during namespace deletion.

    This seems like it would be a straightforward change in the finalizerReconciler to conditionally add the finalizer only when the reclaim policy is delete. The maintainers would be the right people to weigh in on whether there are other reasons the finalizer is needed for retain resources (e.g., logging, status updates) that I might not be seeing.

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

    Leave Feedback Ask Dosu about cloudnative-pg Share Dosu with your team

  4. added a commit that references this issue on Apr 30, 2026
    22831ba
  5. maxlengdell commented on Jun 18, 2026

    @maxlengdell
    ContributorAuthor

    CNPG Finalizers

    Finalizer Value Resource Controller Purpose
    Database cnpg.io/deleteDatabase Database CR Instance manager (runs inside PG pod) Ensures the PostgreSQL database is dropped before the CR is deleted
    Publication cnpg.io/deletePublication Publication CR Instance manager (runs inside PG pod) Ensures the PostgreSQL publication is dropped before the CR is deleted
    Subscription cnpg.io/deleteSubscription Subscription CR Instance manager (runs inside PG pod) Ensures the PostgreSQL subscription is dropped before the CR is deleted
    Plugin cnpg.io/cleanupPlugin Service (plugin service) Operator (plugin controller) Ensures the plugin is deregistered from the in-memory connection pool before its Service is deleted

    The first 3 finalizers does not need to be added if ReclaimPolicy: retain.

    The plugin finalizer needs to be addressed differently.

  6. added
    bug 🐛
    and removed on Jun 21, 2026
  7. added a commit that references this issue on Jul 21, 2026
    843b4df
  8. added 2 commits that reference this issue on Jul 21, 2026
    e4224d3
    aeb27c6
  9. mnencia commented on Jul 23, 2026

    @mnencia
    Member

    Reopening this pr as it is solved only for a CNPG-I plugin in the same namespace of the operator.

  10. github-actions commented on Oct 2, 2026

    @github-actions
    Contributor

    This issue is stale because it has been open for 60 days with no activity.

  11. maxlengdell commented on Oct 7, 2026

    @maxlengdell
    ContributorAuthor

    Not stale, the finalizer on the CRD-backed objects are still an issue for us 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug 🐛triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions