Repository navigation
fix: prevent replicas from restoring old-timeline WAL segments - #10394
IgorOhrimenko wants to merge 6 commits into
Conversation
|
❗ By default, the pull request is configured to backport to all release branches.
|
ff838b3 to
7c37404
Compare
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]>
a9319d5 to
e3eef93
Compare
|
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? |
|
Hi @gbartolini, thanks for raising this important architectural concern.
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. Should we open a PostgreSQL issue to track this? |
|
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 | ||
| } | ||
|
|
There was a problem hiding this comment.
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.
|
|
||
| segment, err := postgres.SegmentFromName(walName) | ||
| if err != nil { | ||
| contextLog.Warning("Could not parse WAL segment name", |
There was a problem hiding this comment.
Nit: If IsWALFile passed but SegmentFromName fails, that's probably a bug. Worth logging at Error instead of Warning?
| return nil | ||
| } | ||
|
|
||
| if walTimeline < clusterTimeline { |
There was a problem hiding this comment.
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?
|
@daanvinken thanks for the careful review — both points were on target. Re: PendingFailoverMarker race (line 505) — confirmed. During an active failover Re: SegmentFromName failure (line 512) — agreed, Re: rejecting The new code path is covered by a unit test ( |
ce127c6 to
2f5000f
Compare
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]>
2f5000f to
c63ae45
Compare
…ent-timeline Signed-off-by: Igor Ohrimenko <[email protected]>
…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]>
|
Closing this because I can no longer reproduce the bug. We did hit it in production: replicas crash-looping with With the reproducer from the description (single-node kind, 3 instances, synchronous replication, plugin-barman-cloud,
On top of that, I replaced the operator on one of our test environments (140 two-instance clusters, synchronous replica, plugin-barman-cloud, Two corrections to the description:
If anyone sees |
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_commandcan 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:
Stuck in "Standby (file based)" mode:
Root cause
validateTimelineHistoryFile()inwalrestore/cmd.govalidates.historyfiles but does not check regular WAL segments. A replica can successfully download000000010000000000000048(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
CurrentPrimaryis not set (during bootstrap or PITR recovery) to allow fetching WAL from any timeline.Reproduction
Minimal reproducer using kind + MinIO: reproduce.sh
shared_buffersto trigger a rolling restart with switchoverrestore_commandfetches old-timeline WAL from MinIOIn 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:
Testing
validateWALSegmentTimelinecovering all branchesCloses #4990
Related: #4188, #3344