Skip to content

[Bug]: Replica cluster with primaryUpdateMethod: switchover gets stuck when WAL receiver inactive #9919

Not planned

Description

@usiegj00

[Bug]: Replica cluster with primaryUpdateMethod: switchover gets stuck when WAL receiver is temporarily inactive

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.

Related issues:

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

  • Yes

Version

1.28.0

What version of Kubernetes are you using?

1.30

What is your Kubernetes environment?

Self-managed (production)

How did you install the operator?

Helm

What happened?

Summary

A replica cluster (replica.enabled: true) with primaryUpdateMethod: switchover gets stuck in phase "Waiting for the instances to become active" when attempting to roll out pod changes (e.g., after spec changes like fsGroupChangePolicy).

The operator repeatedly logs "Pod rollout required" but never performs the rollout. The cluster remains stuck indefinitely.

Root Cause Analysis

After tracing the code, I identified the exact blocking condition in cluster_upgrade.go:

  1. The operator detects the designated primary needs rollout
  2. With switchover method, it selects the cascading replica as the switchover target
  3. At line 213, it checks if !targetInstance.IsWalReceiverActive
  4. If the WAL receiver is not active (even temporarily), it returns errLogShippingReplicaElected
  5. The phase is never updated to reflect this blocked state
  6. Result: Cluster shows stale "Waiting for instances to become active" phase

The Problematic Code Path

// cluster_upgrade.go:194-222
if cluster.Status.Instances > 1 && len(podList.Items) > 1 {
    targetInstance := podList.Items[1]  // Cascading replica for replica clusters

    if targetInstance.Pod.Name == primaryPod.Name {
        targetInstance = podList.Items[0]
    }

    // THIS CHECK BLOCKS ROLLOUT
    if !targetInstance.IsWalReceiverActive {
        contextLogger.Info(
            "chosen new primary is still not connected via streaming replication",
            ...)
        return false, errLogShippingReplicaElected  // Returns error, no phase update
    }

    // Only reached if WAL receiver is active
    return true, r.setPrimaryInstance(ctx, cluster, targetInstance.Pod.Name)
}

Why This is Problematic for Replica Clusters

For replica clusters with cascading replication:

External Source
       │
       ▼ (streaming replication)
    Pod-2 (designated primary)
       │
       ▼ (cascading replication)
    Pod-1 (cascading replica)
  1. The "switchover" semantics don't apply the same way as regular clusters
  2. There's no real "promotion" - just a change in which pod replicates from external
  3. The WAL receiver check is too strict - temporary disconnections block rollouts indefinitely
  4. The phase message is misleading - all pods ARE active, but the rollout is blocked

Phase Staleness Issue

The phase "Waiting for the instances to become active" is set earlier when allInstancesAreActive() returned false. When the pods become ready, allInstancesAreActive() returns true, and reconciliation proceeds to handleRollingUpdate. However, when blocked by errLogShippingReplicaElected:

// cluster_controller.go:1098-1103
case errors.Is(err, errLogShippingReplicaElected):
    contextLogger.Warning(
        "The primary needs to be restarted, but the chosen new primary is still " +
            "not connected via streaming replication, waiting for 5 seconds",
    )
    return ctrl.Result{RequeueAfter: 5 * time.Second}, nil  // NO PHASE UPDATE!

The phase is never updated, leaving users confused with a stale message.

Steps to Reproduce

  1. Create a replica cluster:
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: replica-test
spec:
  instances: 2
  primaryUpdateMethod: switchover
  primaryUpdateStrategy: unsupervised
  replica:
    enabled: true
    source: external-cluster
  # ... storage config
  externalClusters:
    - name: external-cluster
      connectionParameters:
        host: primary-cluster-rw
        # ...
  1. Wait for cluster to become healthy
  2. Apply a spec change that triggers pod rollout (e.g., change fsGroupChangePolicy)
  3. Observe the cluster gets stuck in "Waiting for the instances to become active"

Expected Behavior

  1. The phase should be updated to reflect the actual blocking condition
  2. For replica clusters, the rollout should work even with temporary WAL receiver disconnections
  3. The designated primary should be rollable directly (like a replica) since there's no real failover

Actual Behavior

  1. Phase shows stale "Waiting for the instances to become active"
  2. Operator logs "Pod rollout required" repeatedly
  3. No actual rollout occurs
  4. Cluster remains stuck indefinitely

Workarounds

  1. Use restart instead of switchover for replica clusters:
spec:
  primaryUpdateMethod: restart
  1. Manually delete the designated primary pod:
kubectl delete pod <cluster>-2 -n <namespace>

Diagnostic Commands

# Check if replica cluster with switchover
kubectl get cluster <name> -o jsonpath='{.spec.replica.enabled}'  # true
kubectl get cluster <name> -o jsonpath='{.spec.primaryUpdateMethod}'  # switchover

# Check WAL receiver status
kubectl exec -it <cluster>-1 -c postgres -- psql -U postgres -c \
  "SELECT pid, status, sender_host FROM pg_stat_wal_receiver;"

# Check operator logs for blocking message
kubectl logs -l app.kubernetes.io/name=cloudnative-pg -n cnpg-system | \
  grep -i "not connected via streaming"

Proposed Fix

See attached PR that:

  1. Updates the phase when blocked by errLogShippingReplicaElected
  2. Adds a metric for blocked rollouts
  3. (Optional) Considers using restart semantics for replica cluster designated primary

Cluster Resource

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: pg-b21fd85c-95b2-438d-b6e5-2308a6155695
  namespace: databases
spec:
  instances: 2
  primaryUpdateMethod: switchover
  primaryUpdateStrategy: unsupervised
  replica:
    enabled: true
    source: external-cluster
  postgresql:
    parameters:
      max_connections: "200"
  storage:
    size: 100Gi
    storageClass: premium-rwo
  # ...

Relevant Log Output

{"level":"info","ts":"...","msg":"Pod rollout required","controller":"cluster","podName":"pg-xxx-2","reason":"startup-probe differs"}
{"level":"info","ts":"...","msg":"Pod rollout required","controller":"cluster","podName":"pg-xxx-2","reason":"startup-probe differs"}
... (repeats every ~1 second)

The expected switchover log ("The primary needs to be restarted, we'll trigger a switchover") never appears.

Code of Conduct

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

Analysis Artifacts

Full code path analysis with Mermaid diagrams: CNPG-Reconciliation.md

Key Files Traced

File Line Function Description
cluster_controller.go 770 allInstancesAreActive() Gate before pod reconciliation
cluster_controller.go 1085 handleRollingUpdate Calls rollout logic
cluster_controller.go 1096 rolloutRequiredInstances Main rollout orchestration
cluster_controller.go 1098-1103 error handling Missing phase update
cluster_upgrade.go 54 rolloutRequiredInstances Pod iteration logic
cluster_upgrade.go 147 updatePrimaryPod Primary rollout logic
cluster_upgrade.go 213 WAL receiver check BLOCKING CONDITION
status.go 313-321 Less Replica cluster sorting
probes.go 559 IsWALReceiverActive Check pg_stat_wal_receiver

Activity

  1. dosubot commented on Feb 6, 2026

    @dosubot

    Hi @usiegj00! I'm Dosu and I’m helping the cloudnative-pg team.

    Your analysis is correct: this is a new bug and not tracked in any existing issue or PR. The code path in cluster_upgrade.go and cluster_controller.go confirms that when a replica cluster with primaryUpdateMethod: switchover tries to roll out the designated primary, the operator blocks rollout if the WAL receiver on the switchover target is inactive—even temporarily. When this happens, the operator returns an error but does not update the cluster phase, so the UI remains stuck on "Waiting for the instances to become active" even though all pods are healthy and ready. This leads to indefinite blocking and a misleading phase message, matching your description and code trace.

    No documentation or release notes mention this scenario, and related issues like #9885, #8602, and #5754 discuss similar symptoms but have different root causes or were closed without a fix. The workaround you described—switching to primaryUpdateMethod: restart or manually deleting the designated primary pod—is currently the only way to unblock the rollout. Your proposed fix (updating the phase and/or relaxing the WAL receiver check for replica clusters) would address the root cause and improve user experience. This behavior has not been addressed in any recent release or open PRs as of v1.28.0 and 1.28.1 [source].

    Let me know if you want a deeper dive into the code or more details on possible mitigations.

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

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

  2. usiegj00 commented on Feb 6, 2026

    @usiegj00
    Author

    Update: Pod deletion workaround did not work

    Attempted the manual pod deletion workaround on a stuck replica cluster:

    1. Deleted designated primary pod (pod-2) → Pod recreated, primary switched to pod-1, still stuck
    2. Deleted pod-1 (now primary) → Pod recreated, primary switched back to pod-2, still stuck
    3. Applied trivial spec change (startDelay: 32) → No effect

    Observations:

    • Cluster keeps flip-flopping primaries on each pod deletion
    • Events show repeated FailingOver between pods
    • All pods are Running/Ready, instancesStatus.healthy shows both pods
    • But phase never transitions to Healthy
    LAST SEEN   TYPE     REASON        MESSAGE
    24m         Normal   FailingOver   Current target primary isn't healthy, failing over from pod-2 to pod-1
    5m          Normal   FailingOver   Current target primary isn't healthy, failing over from pod-1 to pod-2
    

    Next attempt: Will try changing primaryUpdateMethod from switchover to restart to see if that resolves the stuck state.

  3. usiegj00 commented on Feb 6, 2026

    @usiegj00
    Author

    Update: Successful Fix Procedure

    After extensive testing, I found that simple pod deletion does not resolve this issue. Here's what we tried and what actually worked:

    What Didn't Work

    1. Deleting just the designated primary pod - Cluster remained stuck after pod recreation
    2. Changing primaryUpdateMethod to restart - Still stuck
    3. Scaling to 1 instance - Single instance also remained stuck
    4. Deleting individual pods and their PVCs - Stuck in "Creating a new replica" phase

    What Actually Worked

    The only fix that worked was a complete cluster rebuild:

    # 1. Delete ALL PVCs (this will delete pods too via ownerReferences)
    kubectl delete pvc -n <namespace> -l cnpg.io/cluster=<cluster-name>
    
    # 2. Reset latestGeneratedNode to allow new pod creation
    # (Required because operator refuses to create new primary when this is non-zero)
    kubectl patch cluster <cluster-name> -n <namespace>   --subresource=status --type=merge   -p '{"status":{"latestGeneratedNode":0}}'
    
    # 3. Wait for pgbasebackup rebuild from external source
    kubectl get cluster <cluster-name> -n <namespace> -w

    Why Step 2 is Critical

    After deleting all PVCs/pods, the operator logged:

    refusing to create the primary instance while the latest generated serial is not zero. 
    If you are recovering the cluster after a disaster, please cleanup the persistent volume claims 
    and restart the operator
    

    The latestGeneratedNode status field acts as a safety mechanism but must be manually reset after a disaster recovery scenario.

    Post-Fix Status

    After the rebuild completed (~15 minutes for pgbasebackup):

    NAME           AGE   INSTANCES   READY   STATUS                     PRIMARY
    my-replica     46h   2           2       Cluster in healthy state   my-replica-1
    

    Recommendation

    The workaround section in the issue should be updated to note that simple pod deletion may not work and a full rebuild may be required for severely stuck clusters.

  4. jsilvela commented on Mar 17, 2026

    @jsilvela
    Contributor

    Hi,
    I haven't tried to repro your issue yet, and I'm talking only from looking at the code, so please take my comments with a grain of salt and excuse if I miss something.

    Something that I don't get in your report is the "even temporarily" part.
    When the primary update fails, in the code you show, the error bubbles up to here

    	case errors.Is(err, errLogShippingReplicaElected):
    		contextLogger.Warning(
    			"The primary needs to be restarted, but the chosen new primary is still " +
    				"not connected via streaming replication, waiting for 5 seconds",
    		)
    		return ctrl.Result{RequeueAfter: 5 * time.Second}, nil

    in cluster_controller.go, line 1112

    What I expect there is a retry.
    Are you seeing a retry and then the same behavior repeating, or is the "Pod rollout required" happening only once?
    You say that for the replica cluster a switchover is not really a switchover, but it's not only marking an instance as the new designated primary, but setting the other instances to stream from the new designated primary.

    What's going on in the replica instances? Why are they not streaming from the designated primary? Any error logs in them?

  5. usiegj00 commented on Mar 26, 2026

    @usiegj00
    Author

    You know I tried to dig in while we had a number of instances to test in this configuration, and I really did think we had isolated this. BUT I completely agree that this code path could not be the issue. I could have walked myself into the wrong cul de sac as you can see I was updating the ticket as I tried to pin things down. I will do a better job if/when I come across this again.

  6. jsilvela commented on Apr 4, 2026

    @jsilvela
    Contributor

    Ha, the bugs get more subtle as the codebase improves.

  7. dosubot commented on Aug 17, 2026

    @dosubot

    Hi, @usiegj00. I'm Dosu, and I'm helping the cloudnative-pg team manage their backlog and am marking this issue as stale.

    Issue Summary

    • You reported that replica clusters using primaryUpdateMethod: switchover can get stuck during pod rollouts in a perpetual “Waiting for the instances to become active” state.
    • The cluster repeatedly reports “Pod rollout required” but does not advance phases.
    • An initial hypothesis pointed to the WAL-receiver check in the switchover path, but that diagnosis was questioned and additional evidence was requested.
    • You later confirmed that deleting pods or switching to restart did not resolve the issue.
    • The only recovery you found was a full rebuild: deleting all PVCs and resetting status.latestGeneratedNode to 0.

    Next Steps

    • Please let us know if this issue is still relevant on the latest version of cloudnative-pg.
    • If it is still reproducible, you can keep the discussion open by commenting here; otherwise, this issue will be automatically closed in 7 days.

    Thanks for your understanding and contribution.

  8. zerkms commented on Sep 2, 2026

    @zerkms

    I think I observe this very bug too.

    I also have a test cluster with primaryUpdateMethod: switchover (one primary and two replicas) and here is what I see in logs in the replica (db-3) that has been restarted:

    {"level":"info","ts":"2026-09-02T09:17:29.742889571Z","logger":"postgres","msg":"record","logging_pod":"db-3","record":{"log_time":"2026-09-02 09:17:29.701 UTC","user_name":"cnpg_metrics_exporter","database_name":"postgres_checker","process_id":"177","connection_from":"[local]","session_id":"6a97e9a9.b1","session_line_num":"1","session_start_time":"2026-09-02 09:17:29 UTC","transaction_id":"0","error_severity":"FATAL","sql_state_code":"57P03","message":"the database system is not yet accepting connections","detail":"Consistent recovery state has not been yet reached.","backend_type":"client backend","query_id":"0"}}
    

    It's now been lasting for 12+ hours.

    I have fixed it with removing PVC/pod and letting cnpg recreate it from the scratch.

    Coincidentally, the other replica (db-2) has been broken in the other way:

    ERROR: cannot advance replication slot to 2DB/56000000, minimum is 2DB/56000028 (SQLSTATE 55000)
    

    BUT!!! - recreating db-3 replica also fixed db-2 as well.

    CNPG version: 1.30.0

  9. github-actions commented on Nov 11, 2026

    @github-actions
    Contributor

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

  10. github-actions commented on Nov 25, 2026

    @github-actions
    Contributor

    This issue was closed because it has been inactive for 14 days since being marked as stale.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions