Skip to content

[Bug]: Switchover target promotes without replaying the old primary's last archived segment; another replica restores it from the archive and diverges past the fork #11715

Open

Description

@GureevLeonid

Existing issue / troubleshooting / supported version: [x] [x] [x]
Version: 1.30 (latest patch), 1.30.1 · Kubernetes: 1.35 · Environment: Other (self-managed) · Install: Helm

What happened?

Setup: 3-instance clusters, PostgreSQL 18 (18.6), WAL archiving through a CNPG-I plugin that implements the WAL service (isWALArchiver: true) and stores WAL in S3-compatible object storage. The clusters have a failover logical slot that a Debezium-style CDC client consumes (synchronizeLogicalDecoding: true). wal_sender_timeout=5s.

We ran an unsupervised rolling update (primaryUpdateMethod: switchover) over 78 clusters. Six of them ended with a replica permanently diverged from the new timeline, and CNPG still reported "Cluster in healthy state". No committed data was lost. The only WAL the broken replica had past the fork was the old primary's shutdown XLOG_SWITCH record.

Sequence (cluster A; T0 = old primary's received fast shutdown request; YY = segment, ZZ = YY+1):

  1. The shutdown checkpoint stalls. The checkpointer waits in WalSndWaitStopping() for every walsender to exit. The logical walsender cannot exit because its client never confirms flush of the trailing non-transactional WAL; its confirmed_flush_lsn stays at the last commit. The physical walsenders also stop getting standby replies once shutdown starts (we do not know why), and wal_sender_timeout reaps them at T+7.5 s. The logical walsender is reaped at T+9.5 s, and the shutdown checkpoint starts 40 ms later.
  2. Both standbys stop at the same LSN, the end of the instance manager's pre-shutdown CHECKPOINT (X/YY018E78). Neither receives the XLOG_SWITCH that ShutdownXLOG writes before the shutdown checkpoint, because their streams are already gone.
  3. The old primary archives segment YY with the XLOG_SWITCH in it, in its final archiver cycle at T+11.10 s. It shuts down at T+11.46 s. This is the only old-timeline segment it archives, and it does so before any promotion.
  4. The target promotes without that segment. Its restore_command attempt for YY started before the object existed and returned "not found" at T+10.95 s. At T+12.1 s handlePromotion() logs "applying WALs and promoting" and calls promote with no further restore attempt. PostgreSQL ends recovery at the end of the streamed WAL (redo done at X/YY018E00). Timeline N forks at X/YY018E78, before the XLOG_SWITCH.
  5. The third replica restores the old-timeline segment and passes the fork. Its stream is gone too, so it falls back to restore_command. At T+15.7 s it restores old-timeline segment YY, which contains the XLOG_SWITCH, and its recovery point moves to X/ZZ000000. That is 4.7 s before 0000000N.history exists in the archive, while status.timelineID is still N-1 and targetPrimary != currentPrimary. From then on it is diverged for good. CNPG pg_rewinds the demoted old primary, so that one is fine, but nothing rewinds or re-clones the third replica.

The race. In all 78 switchovers the target was picked by the same logic.

  • 68 clusters had no stall. The shutdown checkpoint came 0.05–0.7 s after the shutdown request, the standbys streamed the XLOG_SWITCH and the shutdown checkpoint, and there was no problem.
  • 10 clusters stalled for 4.5–9.6 s. Every one of them had a logical walsender reaped by replication timeout.
    • 6 diverged. For these, promote was decided 0.6–1.3 s after the final segment landed in the archive, and the target's last restore before promote was a miss decided between 0.15 s before and 1.2 s after the upload.
    • 4 were fine. For these, the gap was 2.7–3.4 s, so the target restored segment YY, replayed the XLOG_SWITCH and forked at X/ZZ000000. The third replica then consumed the same segment harmlessly (cluster B below).

In earlier rolling updates with primaryUpdateMethod: restart we saw the same stall, and replicas restored the same XLOG_SWITCH segment. That was harmless because no new timeline is created.

Expected behaviour

  1. Target side. Before promoting during a switchover, the target should replay all WAL the old primary produced up to its shutdown. For example, the old primary's instance manager could publish its final checkpoint LSN from pg_controldata after the clean shutdown, and the target would not promote until its replay LSN reaches it (fetching from the archive). At minimum, it should retry restore_command for the next segment on the current timeline for a bounded time before calling promote. Whether "the shutdown streamed everything" holds should be checked rather than assumed. That also applies to the precondition proposed in [Feature]: Skip archive lookups that cannot succeed when the target of a planned switchover promotes #11638.
  2. Non-target replicas. While a switchover is in progress (targetPrimary != currentPrimary, or a pending marker as in PR Fix race condition in primary update switchover #11185), wal-restore should not serve WAL segments of the old timeline. The replica should wait and stream from the new primary instead.
  3. Health. A replica that logs "forked off current database system timeline … before current recovery point" or "not in this server's history" should not count as healthy, and an unsupervised rolling update should stop. This is the [Bug]: Replica permanently stuck in wal-restore loop after failover: walreceiver never reconnects, operator reports cluster healthy, burns CPU indefinitely #10419 / [Bug]: Replica does not come up: checkpoint not found in timeline #4990 class.

Reproduction (derived from production evidence; not yet reproduced in isolation)

  1. Create a 3-instance cluster on PG 18 with wal_level=logical, wal_sender_timeout=5s, wal_receiver_timeout=5s and hot_standby_feedback=on. Set replicationSlots.highAvailability.synchronizeLogicalDecoding: true (CNPG then sets synchronized_standby_slots). Archive WAL through a CNPG-I WAL archiver plugin to object storage.
  2. Create a logical slot with failover = true (pgoutput). Attach a client that only reports flush_lsn up to the last COMMIT it received, as Debezium does. A psycopg2 LogicalReplicationConnection consumer that calls send_feedback(flush_lsn=<commit lsn>) only on commit messages is enough. A light write load is optional.
  3. Trigger a switchover. We used an unsupervised primary update; kubectl cnpg promote uses the same handlePromotion() path but is untested here.
  4. On the old primary, confirm that "checkpoint starting: shutdown" comes about wal_sender_timeout after "received fast shutdown request". Then check the non-target replica for "restored log file "…YY" from archive" followed by the fork errors. Repeat if needed: the outcome depends on 1–3 s of timing (6 of 10 stalls diverged for us).

Cluster resource (relevant parts)

spec:
  instances: 3
  imageCatalogRef: { kind: ClusterImageCatalog, major: 18 }
  primaryUpdateStrategy: unsupervised
  primaryUpdateMethod: switchover
  plugins:
    - name: <cnpg-i-wal-archiver-plugin>
      isWALArchiver: true
  replicationSlots:
    highAvailability: { enabled: true, synchronizeLogicalDecoding: true }
    synchronizeReplicas: { enabled: true }
  postgresql:
    synchronous: { method: any, number: 1, dataDurability: required }  # also seen on a cluster without synchronous
    parameters:
      wal_level: logical
      archive_timeout: 5min
      hot_standby_feedback: "on"
      sync_replication_slots: "on"
      wal_sender_timeout: 5s
      wal_receiver_timeout: 5s

Relevant log output

# Cluster A (diverged). A-1 = old primary, A-2 = target, A-3 = third replica. archive = object-store LastModified.
T-0.01  A-1 Executing CHECKPOINT command before shutdown   (checkpoint complete … redo X/YY018E00)
T+0.00  A-1 received fast shutdown request
T+7.50  A-1 terminating walsender process due to replication timeout   (application_name=A-2)
T+7.50  A-1 terminating walsender process due to replication timeout   (application_name=A-3)
T+9.51  A-1 terminating walsender process due to replication timeout   (application_name=Debezium Streaming)
T+9.56  A-1 checkpoint starting: shutdown immediate                     (XLOG_SWITCH at X/YY018E78, ckpt X/ZZ000028)
T+10.95 A-2 restore_command: <old TL>…YY not found in archive
T+11.10 archive <old TL>…YY created (old primary's final archiver cycle)
T+11.46 A-1 database system is shut down
T+11.47 A-3 record with incorrect prev-link … at X/YY018E78
T+12.11 A-2 I'm the target primary, applying WALs and promoting my instance
T+13.08 A-2 record with incorrect prev-link … at X/YY018E78 ; received promote request ; redo done at X/YY018E00
T+15.74 A-3 restored log file "<old TL>…YY" from archive
T+17.82 A-2 selected new timeline ID: N
T+19.53 A-3 unexpected pageaddr … in WAL segment <old TL>…ZZ, LSN X/ZZ000000, offset 0
T+20.43 archive 0000000N.history created
T+28.7  A-3 FATAL: could not start WAL streaming: ERROR: requested starting point X/ZZ000000 on timeline N-1 is not in this server's history
              DETAIL: This server's history forked from timeline N-1 at X/YY018E78.
T+31.4  A-3 new timeline N forked off current database system timeline N-1 before current recovery point X/ZZ000000   (loops until re-clone)

# Cluster B (stalled, survived): the target restored the segment before promote, so the fork is at the segment boundary.
T+4.42  B-2 terminating walsender process due to replication timeout   (Debezium Streaming) ; T+4.46 checkpoint starting: shutdown
T+~5.3  B-2 final segment <old TL>…YY archived
T+7.99  B-1 I'm the target primary, applying WALs and promoting my instance
T+9.14  B-1 restored log file "<old TL>…YY" from archive ; T+9.92 B-3 restored the same segment
T+11.67 B-1 unexpected pageaddr … LSN X/ZZ000000 ; received promote request ; redo done at X/YY00ADF8
T+26.1  B-3 started streaming WAL from primary at X/ZZ000000 on timeline N

Related (why these are not the same)

Workaround

  • Stop the logical client before a switchover and check that pg_stat_replication has no logical walsender. The shutdown then takes about 0.1 s and the standbys stream the XLOG_SWITCH and the shutdown checkpoint.
  • Alternatively, use primaryUpdateMethod: restart for clusters with CDC clients.
  • Recovery: re-clone the diverged replica.
  • On the PostgreSQL side, the proposed wal_sender_shutdown_timeout GUC (pgsql-hackers, not in PG 18) would bound the stall.

Activity

  1. chobostar commented on Oct 29, 2026

    @chobostar

    Re "The physical walsenders also stop getting standby replies once shutdown starts (we do not know why)": we hit
    the same thing on 1.30.0 and found the cause in our environment. Which CNI do you run, and do replicas reach the
    primary through <cluster>-rw?

    Since #10409 (in 1.29.1 and 1.30.x) the reconcile guard relabels the old primary cnpg.io/instanceRole=unhealthy
    whenever CurrentPrimary != TargetPrimary, so also at the very start of a switchover, while the old primary is
    still running CHECKPOINT and streaming. -rw loses its only backend. Replicas stream through -rw
    (primary_conninfo host=<cluster>-rw). With kube-proxy the established flows survive via conntrack. With Cilium
    kube-proxy replacement without socket LB (bpf-lb-sock=false) the VIP is translated per packet, so established
    replica connections go silent both ways and are reaped by wal_sender_timeout / wal_receiver_timeout.
    The #10409 description assumes the opposite ("does not drop TCP connections already established by a replica's
    walreceiver").

    Production, 2 days: 8 replication timeout disconnects, each ~5 s after a switchover started, all on our only
    Cilium cluster; 42 switchovers on a kube-proxy cluster with the same operator: 0. Two incidents with a permanently
    diverged replica. Reproduced on a test cluster (pgbench, kubectl cnpg promote): label changed at 13:40:32.8,
    Cilium had 0 backends for -rw by 13:40:34.4, the old primary's fast shutdown started only at 13:40:34.2, both
    ends timed out at 13:40:38.5. Hubble later showed a packet of the old connection redirected to the new backend
    and answered with RST.

    In our case the target and the other replica then raced for the shutdown checkpoint over streaming (the update
    reaches each node at a different time) rather than via the archive as in your cluster A, but the start is the same:
    the streams die before ShutdownXLOG. Keeping the old primary labelled until it has shut down during a
    switchover (applying #10409 only to failover) would remove this trigger; your target-side and health items would
    still be needed for the other paths.

  2. antoinemichea commented on Nov 3, 2026

    @antoinemichea

    We hit the same end state on 1.27.0 after a failover (not a switchover), and the diverged reader was a replica cluster that follows the object store. We're adding our timeline because the post-fork WAL came from a different path than in your report. The old primary wrote it after the operator had already decided the failover, while that primary was coming back from a crash.

    Setup

    • CloudNativePG 1.27.0, plugin-barman-cloud 0.12.0 (isWALArchiver: true), PostgreSQL 17.5, Kubernetes 1.35.2, containerd 2.3.3, cgroup v2.
    • Source cluster: 2 instances (A-1 primary, A-3 standby), asynchronous streaming, no logical slot, replicationSlots.highAvailability enabled, archive_timeout: 5min, wal_sender_timeout/wal_receiver_timeout: 5s, failoverDelay: 0.
    • Reader: a separate Cluster with replica.enabled: true, 1 instance (R-1). Its externalClusters point to the same object store through the plugin (isWALArchiver: false). It has no streaming connection to the source and only follows the archive.

    Trigger

    The cgroup OOM killer sent SIGKILL to a single backend on A-1. Because restart_after_crash is off, the postmaster exited, and the container restarted about 3 s later.

    Timeline

    T0 is the last commit on timeline N-1 (record at X/YY5880E0, ending at X/YY588110).

    T (s) Who Event
    +0.27 A-3 could not receive data from WAL stream: SSL SYSCALL error: EOF detected
    +1.36 A-3 record with incorrect prev-link … at X/YY588110: the end of the streamed WAL, which later becomes the fork point
    +3.66 A-1 Container restarted, instance manager starting
    +4.26 A-1 postmaster started, as a primary: no standby.signal, and the cluster status still names it current primary
    +5.33 operator Cannot extract Pod status … the database system is starting up
    +5.36 operator Current primary isn't healthy, initiating a failover
    +5.42 operator Failing over (newPrimary A-3)
    +5.60 A-1 Crash recovery: redo done at X/YY5880E0
    +5.62 A-1 checkpoint starting: end-of-recovery immediate wait writes CHECKPOINT_SHUTDOWN at X/YY588110
    +5.69 A-3 I'm the target primary, applying WALs and promoting my instance
    +5.76 A-1 database system is ready to accept connections, as a read-write primary on N-1
    +6.27 A-3 received promote request, redo done at X/YY5880E0
    +6.31 → +6.70 A-3 restore_command for N-1 segment YY: not found
    +6.55 A-1 This is an old primary node. Requesting a checkpoint before demotion writes CHECKPOINT_REDO, RUNNING_XACTS, CHECKPOINT_ONLINE
    +6.57 A-1 Shutting it down to get it demoted to a replica, fast shutdown; ShutdownXLOG writes XLOG_SWITCH at X/YY588258
    +6.69 → +7.36 A-1 plugin archives N-1 segment YY, which now holds the five post-fork records
    +7.40 A-3 selected new timeline ID: N
    +7.42 A-1 database system is shut down
    +8.21 A-3 server promoted
    +8.60 → +8.98 A-3 archives 0000000N.history (in the store at +8.98) and …YY.partial
    +9.06 → +9.57 R-1 Restoring WAL file N-1 segment YY: restored and replayed up to X/ZZ000000
    +10.43 operator Setting replica label A-1, Setting primary label A-3
    +20.9 A-1 pg_rewind: servers diverged at WAL location X/YY588110 on timeline N-1, rewound fine
    after that R-1 Every 5 s: new timeline N forked off current database system timeline N-1 before current recovery point X/ZZ000000, then waiting for WAL to become available at X/ZZ000018. This went on for about 14 h, while the replica cluster stayed in Cluster in healthy state

    Timeline history file: N-1 X/YY588110 no recovery target specified.

    pg_waldump on the N-1 segment that R-1 restored:

    rmgr: Transaction len (rec/tot):  46/  46, tx: …832, lsn: X/YY5880E0, desc: COMMIT …       <- last commit, also on timeline N
    rmgr: XLOG        len (rec/tot): 114/ 114, tx:    0, lsn: X/YY588110, desc: CHECKPOINT_SHUTDOWN redo X/YY588110; tli N-1; …   <- A-1 end-of-recovery
    rmgr: XLOG        len (rec/tot):  30/  30, tx:    0, lsn: X/YY588188, desc: CHECKPOINT_REDO wal_level logical
    rmgr: Standby     len (rec/tot):  50/  50, tx:    0, lsn: X/YY5881A8, desc: RUNNING_XACTS nextXid …833 latestCompletedXid …832 …
    rmgr: XLOG        len (rec/tot): 114/ 114, tx:    0, lsn: X/YY5881E0, desc: CHECKPOINT_ONLINE redo X/YY588188; tli N-1; …    <- checkpoint before demotion
    rmgr: XLOG        len (rec/tot):  24/  24, tx:    0, lsn: X/YY588258, desc: SWITCH                                         <- ShutdownXLOG
    

    No transaction follows the fork. No committed data was lost, and nothing was written on A-1 during the ~0.8 s it accepted connections.

    Differences with the original report

    1. Failover, no walsender stall. A-3 had streamed everything up to the end of the last commit, and that point is exactly the fork.
    2. The post-fork WAL did not exist when the failover was decided. The restarted old primary produced it in three steps, five records in all: the end-of-recovery checkpoint, the "checkpoint before demotion" (CHECKPOINT_REDO, RUNNING_XACTS, CHECKPOINT_ONLINE) and the shutdown XLOG_SWITCH. Its own archiver then uploaded it, 1.3 s after the operator had picked the new target.
    3. The reader is a replica cluster. It cannot see the source cluster's targetPrimary/currentPrimary, so a guard on non-target replicas (your expected behaviour 2) would not protect it. Only the writing side can.
    4. Uploading the history file first would not have been enough. 0000000N.history was in the store 86 ms before R-1's next attempt. R-1's polling cycle asks for the next segment on its current timeline before it looks for a newer history file (its log shows segment, then history, every ~5 s), so the N-1 segment won.

    What would have prevented it in our case

    • Writing side, archiving. An instance that is no longer targetPrimary could refuse to archive: wal-archive or the CNPG-I archive call returns an error, the files stay .ready, and pg_rewind discards them anyway. All of our post-fork WAL left through A-1's archiver.
    • Writing side, demotion. When a crashed primary restarts while a failover may be pending, it could stay out of read-write mode, or at least run without archiving, until the operator confirms it is still the target. And for an old primary that has been failed over, as opposed to switched over, it could skip the "checkpoint before demotion".
    • Health. A replica cluster stuck on forked off … before current recovery point should not report healthy, which matches your expected behaviour 3. We only noticed through a replication-lag alert.

    Side note: A-1 accepted connections from T+5.76 to T+6.57 s while it still carried the primary label, which the operator only changed at T+10.43. The startup probe (10 s period) most likely kept it out of the -rw endpoints, and nothing was written, but the window exists.

    Recovery: we re-created the replica cluster from a VolumeSnapshot of the rewound standby, and it picked up timeline N from the archive. The polluted N-1 segment stays in the object store. As far as we can tell, a recovery that starts once 0000000N.history exists tries the timeline N segment first, so restores are not affected.

    We can share more logs if that helps.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions