Skip to content

fix(failover): elect on the primary lease, not on WAL receivers - #11367

Closed
leonardoce wants to merge 11 commits into
cloudnative-pg:mainfrom
leonardoce:no-wal-receiver-for-coordination
Closed

leonardoce wants to merge 11 commits into
cloudnative-pg:mainfrom
leonardoce:no-wal-receiver-for-coordination

Conversation

@leonardoce

@leonardoce leonardoce commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

A failover used to wait until every WAL receiver was down before electing a new primary, and the elected replica then waited for its own receiver before it promoted. A stuck receiver stalled the failover, and the wait is redundant once the primary lease orders the promotion: the former primary releases the lease only after PostgreSQL has exited, a walsender stops only after the standbys have flushed everything it sent, and a promoting replica replays all the WAL in pg_wal.

The election now waits for the primary lease to be released, or to stay unchanged for the lease duration, so the positions it compares are final and a replica cannot end up ahead of the new primary. Replicas time the lease from the moment the failover is marked as pending, so the elected replica does not wait a second lease duration before it claims it. Only the elected replica can claim the lease, and instance managers without this change keep the old timing. A planned switchover no longer waits for the target's WAL receiver either, because the old primary's shutdown already flushes everything to the standbys.

Closes #11735


Reviewer notes

The PGDATA-corruption e2e is the spec to watch. It catches an election made before the old primary has stopped: a sibling replica ends up ahead of the new primary and never rejoins. The TLA model is unchanged, because the pending marker plays the role of the target flip it already models, and the README wording now says so.

Not covered here: a webhook check that RetryPeriod + 2 * requestTimeout stays below LeaseDuration, and a deterministic test for the election order.

@cnpg-bot cnpg-bot added backport-requested ◀️ This pull request should be backported to all supported releases release-1.28 release-1.29 release-1.30 labels Aug 24, 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

@leonardoce leonardoce added do not backport This PR must not be backported - it will be in the next minor release no-issue and removed backport-requested ◀️ This pull request should be backported to all supported releases release-1.28 release-1.29 release-1.30 labels Aug 24, 2026
@leonardoce

Copy link
Copy Markdown
Contributor Author

IMPORTANT: this requires #11347 #11350 #11357 and #11358 to be merged before a real review. They are cherry-picked here out of convenience.

@leonardoce

Copy link
Copy Markdown
Contributor Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@leonardoce

leonardoce commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

This is what happened:

  • 14:44:50.109 — Test corrupts the primary (-1) by deleting its PGDATA while postgres keeps running
  • 14:44:5x – 14:45:17 — -1's postmaster starts returning FATAL: "base/5" is not a valid data directory for new connections/backends, but its pre-existing walsender connections to -2 and -3 (established before the corruption) keep running normally — they only read WAL segment files and don't need to touch the corrupted catalog
  • 14:45:17.847 — Operator (decides the new primary: it snapshots replica status and finds -2 and -3 tied at receivedLsn = replayLsn = 0/6055A20; it picks -2 and sets cluster.Status.TargetPrimary = -2
  • 14:45:18.276 – 18.406 — -1's own instance-manager notices it's no longer TargetPrimary, requests a fast shutdown; postgres on -1 (and both its walsenders) dies
  • 14:45:18.397 / .401 — -2's and -3's walreceivers both disconnect essentially simultaneously (SSL EOF) — i.e. both were still actively streaming, at slightly different effective positions, right up to the moment -1 actually died
  • 14:45:18.563 — -1 releases the primary lease
  • 14:45:20.495 – 21.562 — -2 acquires the lease (fast path: empty holder, no 15s TTL wait needed) and promotes — ~2.6s after the original election snapshot, and ~1.9s after the lease was actually released
  • (at promotion) — -2's fork point is 0/6055A20 (its replay had only reached there) — but -3 had already received WAL up to 0/7000000 in the meantime
  • 14:45:5x → 14:51:09 (timeout) — -3 endlessly retries streaming from 0/7000000, failing forever with requested starting point 0/7000000 on timeline 1 is not in this server's history — it diverged onto WAL the new primary never had, and nothing detects/repairs this (no automatic re-clone/rewind)

So the primary lease worked correctly, but unfortunately the operator decided which replica to promote too early, without re-checking it before the promotion actually happens.

Claude was used to help wording the timeline.

@leonardoce
leonardoce force-pushed the no-wal-receiver-for-coordination branch from f1ad3f1 to 57f3b1d Compare August 25, 2026 13:07
@leonardoce

Copy link
Copy Markdown
Contributor Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@leonardoce

Copy link
Copy Markdown
Contributor Author
  • 15:52:08.88 → 15:52:23.17: 8 consecutive "Waiting for the primary lease to be released or expire" reconciles, 1 every ~2s (the RequeueAfter: 1 * time.Second from handleSwitchover's ErrPrimaryLeaseHeld branch, though logs land ~2s apart)
  • 15:52:25.26: FailoverTarget event finally fires — ~16.4s after the failover was first marked pending

It looks like the tests time budget is not enough to observe a failover. That's even more important now given that, in these conditions, we need to wait for the lease to expire.

@leonardoce

Copy link
Copy Markdown
Contributor Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@cnpg-bot cnpg-bot added the ok to merge 👌 This PR can be merged label Aug 26, 2026
@leonardoce
leonardoce marked this pull request as ready for review August 26, 2026 11:10
@leonardoce
leonardoce requested review from a team, NiccoloFei and litaocdl as code owners August 26, 2026 11:10
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. release-1.28 release-1.29 labels Aug 26, 2026
@mnencia

mnencia commented Oct 23, 2026

Copy link
Copy Markdown
Member

/test

@github-actions

Copy link
Copy Markdown
Contributor

@mnencia

mnencia commented Oct 23, 2026

Copy link
Copy Markdown
Member

@mnencia
mnencia force-pushed the no-wal-receiver-for-coordination branch 3 times, most recently from 44deb86 to b4524e2 Compare October 23, 2026 12:20
@armru

armru commented Oct 23, 2026

Copy link
Copy Markdown
Member

/test

@github-actions

Copy link
Copy Markdown
Contributor

leonardoce and others added 9 commits October 26, 2026 12:43
The controller used to snapshot replica LSNs and immediately elect a
new primary in the same reconcile pass as marking the failover
pending, even though the old primary could still be alive and
streaming for a few more seconds. That window let the LSN snapshot go
stale before the elected replica actually promoted, leaving a sibling
replica to fork onto a diverged timeline with no automatic repair.

Splits "mark pending" and "elect" into two separate reconcile passes,
deferring election until the primary lease is confirmed released or
expired, so the LSN snapshot used for the election is taken as close
as possible to the actual promotion.

Signed-off-by: Leonardo Cecchi <[email protected]>
…ivers to stop

The primary lease now guarantees only one instance can act as primary
at a time, so failovers and switchovers no longer need to stall until
every WAL receiver in the cluster reports itself down before a new
primary is chosen and promoted. This removes a source of delay and
stuck-waiting states during failover.

Signed-off-by: Leonardo Cecchi <[email protected]>
Signed-off-by: Leonardo Cecchi <[email protected]>
The gate only has to wait for the old primary, so a lease held by a
target that was never promoted no longer defers the election: that
target keeps renewing it, and the operator could never replace it. The
observer package is one function and a small map on the reconciler, and
only the deletion of the Cluster drops its state, since a changed record
restarts the window anyway.

The failover page and two comments now describe the gate instead of the
WAL receiver wait.

Assisted-by: Claude
Signed-off-by: Marco Nenciarini <[email protected]>
The gate makes the controller wait a full lease duration before it
elects a new primary, and the elected replica then started its own
observation window and waited again. The marker already tells the old
primary that it was replaced, through the peers' failsafe answers, so
the replicas now time the lease record from the marker on. Only the
elected one may claim it.

The window runs only while the Cluster names the marker or the pod
itself as target, and any other target drops it. Instance managers
without this change keep the old timing.

Assisted-by: Claude
Signed-off-by: Marco Nenciarini <[email protected]>
Marking the failover as pending returned neither an error nor an elected
primary, which handleSwitchover reads as a healthy primary: it cleared
CurrentPrimaryFailingSinceTimestamp and went on with the rest of the
reconciliation. The next pass then started the failover delay again, so a
cluster with failoverDelay set waited for it twice before the election.

The pending step now returns ErrPrimaryLeaseHeld, since the election waits
for the old primary's lease from the next pass on, and the caller requeues
without touching the delay.

Signed-off-by: Armando Ruocco <[email protected]>
… may not step down

A replica promoted as soon as it held the primary lease, trusting the old
primary to stop on its own before the lease expired. A primary running an
instance manager without the step-down never does: during an upgrade with a
supervised primary update, a primary still on 1.30.1 that loses the API
server and the operator but keeps reaching its replicas goes on accepting
writes, and the replica elected in its place promoted next to it.

The new primary now waits for its WAL receiver to stop, as it did before the
lease, unless the isolation check is enabled and the old primary reports its
target primary on /failsafe, which only an instance manager with the
step-down does. An old primary that cannot be probed is not streaming WAL to
it either, so a failover after a crash keeps the promotion the lease allows.

Signed-off-by: Armando Ruocco <[email protected]>
…ry is gone

The election compared the WAL positions of the instance status read at the
start of the reconciliation, and checked the primary lease only afterwards.
When the old primary released the lease in between, the status was read
while it was still streaming: a replica that had stopped receiving could be
elected ahead of one that went on to receive the rest of the WAL, which then
had to be rewound.

The pass that finds the old primary gone now requeues, and the next one,
whose status is read after that, elects.

Signed-off-by: Armando Ruocco <[email protected]>
…not step down

The election waited only for the primary lease to go away. An old primary
that does not stop on its own, because the isolation check is disabled or it
runs an instance manager without the step-down, outlives its lease and keeps
streaming WAL to the replicas: the operator elected on WAL positions that were
still moving, and could move the target between streaming replicas while the
elected one, holding the lease, waited for its WAL receiver and then promoted
even if it was no longer the target.

The operator now also waits for every WAL receiver to stop, as it did before
the lease, unless the isolation check is enabled and the old primary Pod was
started from the operator's own image, the only one known to step down.

Signed-off-by: Armando Ruocco <[email protected]>
@armru
armru force-pushed the no-wal-receiver-for-coordination branch from 657fa2a to ef7d5d6 Compare October 26, 2026 11:48
…Pod is gone

The operator cannot tell which instance manager a former primary runs once its
Pod is gone, so it waits for every WAL receiver to stop, as for a Pod created
by a previous operator version. Say so in the failover documentation.

Signed-off-by: Armando Ruocco <[email protected]>
@armru

armru commented Oct 26, 2026

Copy link
Copy Markdown
Member

/test

@github-actions

Copy link
Copy Markdown
Contributor

The election now has one more step in
reconcileTargetPrimaryForNonReplicaCluster, which brings its cognitive
complexity to 31 and fails gocognit (limit 30) on golangci-lint v2.15.0.
Move the marking of the failover as pending into its own method.

Signed-off-by: Armando Ruocco <[email protected]>
@mnencia

mnencia commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Closing this one. After a closer look it gains little over main. The stall it targets is already bounded: once the failover is pending the old primary gets a fast shutdown and then an immediate one, so its walsenders go away. The WAL receiver wait is also the only protection against a primary on an instance manager without the step-down (1.30 and older), so it has to stay at least during upgrades. With the waits kept, the lease gate in the controller only moves the election later, for about 360 lines of new state.

What stays open: #11778 makes the isolation check always active (closes #11777) and still needs to be discussed. Starting the lease window at the pending marker may follow later in its own small PR.

@mnencia mnencia closed this Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not backport This PR must not be backported - it will be in the next minor release no-issue ok to merge 👌 This PR can be merged size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Do not wait for WAL receivers to stop before promoting a replica

5 participants