Skip to content

fix: prevent replicas from restoring old-timeline WAL segments - #10394

Closed
IgorOhrimenko wants to merge 6 commits into
cloudnative-pg:mainfrom
IgorOhrimenko:fix/validate-wal-segment-timeline
Closed

IgorOhrimenko wants to merge 6 commits into
cloudnative-pg:mainfrom
IgorOhrimenko:fix/validate-wal-segment-timeline

Conversation

@IgorOhrimenko

@IgorOhrimenko IgorOhrimenko commented Mar 31, 2026 •

Copy link
Copy Markdown

After a switchover or failover, the WAL archive (S3/object storage) still contains segments from previous timelines. When a replica restarts with existing PVC data (e.g. after a rolling restart triggered by parameter change), its restore_command can fetch old-timeline WAL segments from the archive before streaming replication reconnects to the new primary.

This causes the replica's timeline history to diverge from the current primary, resulting in either:

CrashLoopBackOff:

LOG: restored log file "00000002.history" from archive
LOG: restored log file "00000003.history" from archive
LOG: restored log file "00000001000000000000004B" from archive   ← timeline 1!
LOG: restored log file "000000010000000000000048" from archive   ← timeline 1!
LOG: entering standby mode
FATAL: requested timeline 3 is not a child of this server's history
LOG: startup process (PID 34) exited with exit code 1
LOG: database system is shut down

Stuck in "Standby (file based)" mode:

LOG: restored log file "0000000100000032000000E8" from archive   ← timeline 1!
LOG: invalid record length at 32/E80000A0: expected at least 24, got 0
LOG: fetching timeline history file for timeline 2 from primary server
FATAL: could not receive timeline history file from the primary server: ERROR:
  could not open file "pg_wal/00000002.history": No such file or directory
LOG: waiting for WAL to become available at 32/E80000B8

Root cause

validateTimelineHistoryFile() in walrestore/cmd.go validates .history files but does not check regular WAL segments. A replica can successfully download 000000010000000000000048 (timeline 1) from the archive when the primary is already on timeline 3.

Fix

Added validateWALSegmentTimeline() which rejects WAL segments whose timeline is older than the cluster's current timeline, for replica instances in established clusters. This forces PostgreSQL to fall back to streaming replication from the current primary instead of consuming stale WAL from the archive.

The check is skipped when CurrentPrimary is not set (during bootstrap or PITR recovery) to allow fetching WAL from any timeline.

Reproduction

Minimal reproducer using kind + MinIO: reproduce.sh

  1. Create a 3-instance cluster with synchronous replication and WAL archiving to MinIO
  2. Write data, take backup, write more data
  3. Change shared_buffers to trigger a rolling restart with switchover
  4. Replica restarts with existing PVC, restore_command fetches old-timeline WAL from MinIO
  5. Replica crashes or gets stuck in file-based mode

In the provided test environment (kind, single-node, local MinIO, synchronous replication), the bug reproduces consistently. In multi-node production clusters the issue is intermittent, depending on the timing between switchover completion and replica reconnection.

Without the fix: replica enters CrashLoopBackOff or Standby (file based).
With the fix: old WAL is rejected with warning log, replica uses streaming replication:

WARNING: Refusing to restore old-timeline WAL segment for replica
  walName=000000010000000000000048 walTimeline=1 clusterTimeline=3

Testing

  • Unit tests added for validateWALSegmentTimeline covering all branches
  • Verified recovery from S3 backup works correctly (PITR not broken)
  • Verified rolling restarts with switchover work without file-based or CrashLoop

Closes #4990
Related: #4188, #3344

@IgorOhrimenko
IgorOhrimenko requested a review from a team March 31, 2026 15:43
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Mar 31, 2026
@cnpg-bot cnpg-bot added backport-requested ◀️ This pull request should be backported to all supported releases release-1.25 release-1.28 labels Mar 31, 2026
@github-actions

Copy link
Copy Markdown
Contributor

❗ By default, the pull request is configured to backport to all release branches.

  • To stop backporting this pr, remove the label: backport-requested ◀️ or add the label 'do not backport'
  • To stop backporting this pr to a certain release branch, remove the specific branch label: release-x.y

@dosubot dosubot Bot added the bug 🐛 Something isn't working label Mar 31, 2026
@IgorOhrimenko
IgorOhrimenko marked this pull request as draft March 31, 2026 15:52
@IgorOhrimenko
IgorOhrimenko force-pushed the fix/validate-wal-segment-timeline branch 2 times, most recently from ff838b3 to 7c37404 Compare March 31, 2026 16:17
@IgorOhrimenko
IgorOhrimenko marked this pull request as ready for review March 31, 2026 16:27
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Mar 31, 2026
After a switchover or failover, the WAL archive still contains segments
from previous timelines. When a replica restarts with existing PVC data,
its restore_command can fetch these old-timeline WAL segments from the
archive, causing the replica's timeline history to diverge from the
current primary.

This results in either:
- CrashLoopBackOff: "requested timeline N is not a child of this
  server's history"
- Replica stuck in "Standby (file based)" mode, unable to stream

The existing validateTimelineHistoryFile only checks .history files.
This commit adds validateWALSegmentTimeline which also rejects regular
WAL segments whose timeline is older than the cluster's current
timeline, for replicas in established clusters.

The check is skipped when CurrentPrimary is not set (during bootstrap
or PITR recovery) to allow fetching WAL from any timeline.

Closes: cloudnative-pg#4990
Signed-off-by: Igor Ohrimenko <[email protected]>
@IgorOhrimenko
IgorOhrimenko force-pushed the fix/validate-wal-segment-timeline branch from a9319d5 to e3eef93 Compare April 1, 2026 09:32
@gbartolini

Copy link
Copy Markdown
Contributor

Hi @IgorOhrimenko. What if I request a particular timeline for the recovery? I believe that we should let Postgres handle that process, not CNPG. What are your thoughts?

@IgorOhrimenko

IgorOhrimenko commented Apr 3, 2026 •

Copy link
Copy Markdown
Author

Hi @gbartolini, thanks for raising this important architectural concern.
You're absolutely right that timeline management should ideally be handled by PostgreSQL itself, not by CNPG. The restore_command should be a simple fetcher without business logic.
However, this specific issue has been blocking CNPG adoption in production for years. Many teams hesitate to deploy CNPG because replicas can crash-loop or get stuck in "standby (file based)" mode after switchovers. The problem is that PostgreSQL's recovery algorithm can fetch old-timeline WAL segments before reading the .history files that would tell it those segments are incompatible.
Our fix in CNPG is a pragmatic workaround:

  • It only applies to replicas in established clusters (not during bootstrap/PITR, not for primaries)
  • It returns ErrWALNotFound to force fallback to streaming replication
  • It prevents data divergence and crash loops that PostgreSQL would otherwise hit later

The reproduction script in this PR shows the issue occurs consistently. We've already patched our production clusters with this fix (built custom binaries/Docker images), and it solves the problem immediately.
Long-term, PostgreSQL should indeed handle this better—perhaps by checking timeline compatibility earlier or prioritizing streaming replication more aggressively after failovers. But getting changes into PostgreSQL core takes years. Meanwhile, operators need stable clusters today.
If we merge this fix, we could add a code comment like:

// TODO: Remove this validation when PostgreSQL handles old-timeline
// WAL rejection during replica recovery (see PostgreSQL issue #XYZ).

Should we open a PostgreSQL issue to track this?

@daanvinken

daanvinken commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

I agree this is more of a Postgres problem, butthis seems like a fairly pragmatic fix that could have maintained auto-recovery of the operator for us as welll in some scenarios.

@gbartolini what are your thoughts on proceeding witht his PR as-is and hoping to fix this in the future?

if cluster.Status.CurrentPrimary == "" {
return nil
}

@daanvinken daanvinken Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could there still be a race condition window here during failover (not switchover)?TargetPrimary is set to PendingFailoverMarker ("pending"), not a pod name, so this skip won't match any replica.

Additionally cluster.Status.TimelineID is still the old timeline because the new primary hasn't reported yet, it's only updated in cluster_status.go:738 when item.IsPrimary. So the comparison below passes walTimeline == clusterTimeline and the poisoned segment can get through.

Would adding a PendingFailoverMarker guard here close this? Something like:

if cluster.Status.TargetPrimary == apiv1.PendingFailoverMarker {
    return barmanRestorer.ErrWALNotFound
}

During active failover, replicas should stream from the new primary, not restore from archive. Once PendingFailoverMarker is cleared and the new primary reports its timeline, the timeline comparison below takes over.

Comment thread internal/cmd/manager/walrestore/cmd.go Outdated

segment, err := postgres.SegmentFromName(walName)
if err != nil {
contextLog.Warning("Could not parse WAL segment name",

@daanvinken daanvinken Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: If IsWALFile passed but SegmentFromName fails, that's probably a bug. Worth logging at Error instead of Warning?

Comment thread internal/cmd/manager/walrestore/cmd.go Outdated
return nil
}

if walTimeline < clusterTimeline {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validateTimelineHistoryFile above rejects future timelines (fileTimeline > clusterTimeline).

Should this also reject walTimeline > clusterTimeline for consistency? (so if walTimeline != clusterTimeline)

A replica shouldn't be restoring WAL from a timeline the cluster hasn't reached. Maybe it's too defensive, but while we're at it?

@IgorOhrimenko

Copy link
Copy Markdown
Author

@daanvinken thanks for the careful review — both points were on target.

Re: PendingFailoverMarker race (line 505) — confirmed. During an active failover TargetPrimary == "pending" and TimelineID still reports the old timeline (the new primary hasn't reported yet), so the existing skip and the walTimeline < clusterTimeline check both pass. Pushed a guard: when TargetPrimary == apiv1.PendingFailoverMarker, return ErrWALNotFound outright — replica falls back to streaming.

Re: SegmentFromName failure (line 512) — agreed, IsWALFile passing but SegmentFromName failing is an invariant violation. Bumped to Error and reworded the message to make the inconsistency explicit.

Re: rejecting walTimeline > clusterTimeline (line 525) — I'd prefer to leave this as < and not extend to !=. The same status-lag that motivates your point #1 also means a freshly promoted primary may be writing TL N+1 WAL to the archive while cluster.Status.TimelineID is still N. A replica that is genuinely catching up would legitimately fetch TL N+1 segments here. With != we'd block that valid catch-up path; with < it falls through and PG's normal recovery logic (history-file driven) handles it. The new PendingFailoverMarker guard in #1 already closes the unsafe branch of this same window.

The new code path is covered by a unit test (should reject WAL when failover is pending).

@IgorOhrimenko
IgorOhrimenko force-pushed the fix/validate-wal-segment-timeline branch 3 times, most recently from ce127c6 to 2f5000f Compare May 8, 2026 12:17
The previous timeline check could let stale WAL through during the brief
window of an active failover. In that state:

  - cluster.Status.TargetPrimary is set to the PendingFailoverMarker
    sentinel ("pending"), not a pod name, so the existing skip for
    primary/target-primary does not match.
  - cluster.Status.TimelineID still reports the old timeline because the
    newly promoted primary has not reported yet.

As a result walTimeline equals clusterTimeline and the comparison passes
even though the new primary is already on a higher timeline and the
archive may contain post-divergence WAL from the old timeline. Refuse
outright when TargetPrimary equals PendingFailoverMarker so the replica
falls back to streaming replication from the new primary.

Also: if IsWALFile passes but SegmentFromName fails, that is an invariant
violation — log at Error instead of Warning.

Signed-off-by: Igor Ohrimenko <[email protected]>
@IgorOhrimenko
IgorOhrimenko force-pushed the fix/validate-wal-segment-timeline branch from 2f5000f to c63ae45 Compare May 8, 2026 12:30
…e switchpoint

validateWALSegmentTimeline refused every WAL segment whose timeline was older
than the cluster one. That is too broad: a replica that lags behind legitimately
replays the tail of its own timeline until the point where that timeline was
abandoned, and only then follows the history onto the current one.

With the previous rule such a replica could not recover at all. Streaming fails
when the primary has already recycled the segments, and the archive was refused
here, so the instance kept restarting forever. Observed on a cluster that reached
timeline 59 through a chain of failovers: the replica needed 3C/D7 of timeline 58
while the history file records 3D/469D140 as its switchpoint, so the segment was
well before the divergence and perfectly safe to replay.

Read the switchpoint from the history file of the current timeline and refuse
only the segments starting at or after it — those are the ones written by a
demoted primary onto a branch the cluster no longer follows, which is what
the check was meant to catch. Timelines missing from the history are refused
outright; an unreadable history file lets the segment through, since stranding
a replica that cannot stream either is worse than the risk it guards against.

Signed-off-by: Igor Ohrimenko <[email protected]>
A demoted primary rejoins the cluster through pg_rewind, which reads WAL
of the timeline it is being rewound from, on both sides of the point
where that timeline diverged. Those segments are not optional: without
them pg_rewind fails, the operator retries, and the instance restarts
forever.

The old-timeline segment check applied to those requests too, so an
instance whose local WAL had already been recycled could never come
back. Skip the check when wal-restore runs with --rewind, which the
instance manager sets on the restore_command it hands to pg_rewind.

PostgreSQL replaying WAL on its own is still subject to the check.

Signed-off-by: Igor Ohrimenko <[email protected]>
@IgorOhrimenko
IgorOhrimenko requested a review from a team as a code owner October 21, 2026 22:56
@IgorOhrimenko

Copy link
Copy Markdown
Author

Closing this because I can no longer reproduce the bug.

We did hit it in production: replicas crash-looping with requested timeline N is not a child of this server's history after rolling restarts, and this patch made it go away there. I've now tried to reproduce it again, and it doesn't happen on any version I tested.

With the reproducer from the description (single-node kind, 3 instances, synchronous replication, plugin-barman-cloud, shared_buffers toggled to force a rolling restart with switchover), I ran 21 switchovers per setup and checked after each one that both replicas were back to streaming on the new timeline and the cluster was healthy:

CNPG plugin-barman-cloud reproduced
1.28.0 v0.11.0 0 / 21
1.28.1 v0.11.0 0 / 21
main (c60ac25) v0.15.0 0 / 21
1.30.1 v0.15.1 0 / 21

On top of that, I replaced the operator on one of our test environments (140 two-instance clusters, synchronous replica, plugin-barman-cloud, primaryUpdateMethod: switchover, multi-node, real S3) with vanilla 1.30.1, without in-place instance manager updates. That forced a rolling update with a switchover on every cluster. 30 of the 141 replicas went through a short archive-recovery phase during the switchover, the longest for about 2.5 minutes. All of them went back to streaming on their own, and no instance crash-looped.

Two corrections to the description:

  • The "Standby (file based)" symptom was a false positive of the reproducer. It checks the status once, mid-switchover, and exits. A few seconds later the replica fetches the new timeline history and switches to streaming.
  • Restoring a segment of an older timeline is not harmful by itself. On vanilla 1.30.1, a replica restored 000000160000000000000070 while the cluster was already on timeline 0x17, then replayed onto the new timeline without errors: the switchpoint of timeline 0x16 (0/700000A0) is inside that segment. The original version of this patch would have refused it. 89f3b60 and 668477b narrowed the check to segments past the switchpoint and skipped it for pg_rewind, after the broad check stranded lagging replicas and blocked pg_rewind in our production.

If anyone sees not a child of this server's history on a replica again, the logs of that instance and the timeline history files are what would help find the actual trigger.

@IgorOhrimenko
IgorOhrimenko deleted the fix/validate-wal-segment-timeline branch October 22, 2026 15:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-requested ◀️ This pull request should be backported to all supported releases bug 🐛 Something isn't working release-1.28 release-1.30 size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Replica does not come up: checkpoint not found in timeline

5 participants