Skip to content

fix: complete a failover when the old primary's PostgreSQL is unresponsive - #11265

Closed
armru wants to merge 24 commits into
mainfrom
fix/old-primary-shutdown-bounded
Closed

armru wants to merge 24 commits into
mainfrom
fix/old-primary-shutdown-bounded

Conversation

@armru

@armru armru commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

When a primary's PostgreSQL stops responding while the node stays up, a failover never completes. There are two independent reasons for that, at opposite ends of the same sequence, and this PR removes both. Together they are the whole remedy: a deterministic stop of the old primary, and a bounded fallback for the cases that stop cannot reach.

The old primary never stands down

reconcileOldPrimary, the path that shuts a demoted primary down so it can come back as a replica, sat below the pg_isready gate in the instance reconcile loop. A frozen instance never satisfies that check, so the demotion is never requested, PostgreSQL is never asked to stop, and the instance manager goes on renewing the primary lease while the newly elected primary retries acquiring it forever. The lease's own expiry does not help: a lease that still names another holder is taken over only once its record has been observed unchanged for a full lease duration, and renewal is driven by the instance manager without consulting PostgreSQL, so a healthy instance manager keeps the lease renewed no matter how stuck its PostgreSQL is.

reconcileOldPrimary's own early exits already make it safe to call unconditionally: it does nothing unless this instance is both the current primary and no longer the cluster's target primary, and deciding that reads only the data directory, never a live connection. It now runs above the readiness gate, following the precedent of fencing, which sits above the same gate and reaches the same shutdown.

Reaching the shutdown exposed two ways it could still hang forever. The pre-shutdown CHECKPOINT ran on a fresh connection with no timeout of its own, so against an instance that accepts a connection but never completes the handshake it blocked permanently and pg_ctl was never invoked at all. The CHECKPOINT and the pg_ctl call now share one deadline, taken from the caller's timeout or pg_ctl's own 60 second default, with pg_ctl given whatever remains via -t; a CHECKPOINT that misses it is logged and abandoned. Further down, pg_ctl stop -m immediate reported failure by exit status but nothing acted on it. That exit status now sends SIGKILL to the process group of the running server, read from postmaster.pid, and that exit is what the shutdown is parked on. The signal reaches the parent process alone, because PostgreSQL calls setsid in InitPostmasterChild and every backend is therefore its own process group leader, but the backends are not left behind: WL_POSTMASTER_DEATH is registered on the wait set every backend blocks on, so each one exits itself at its next wait point. A WAL sender is prompt about it, since that is the same wait its keepalive interval times out of.

The election and the promotion never start

Before electing a new primary, and again before the elected candidate promotes itself, the operator waits for every WAL receiver to report down. A frozen primary stops serving but leaves its WAL sender processes alive, and any byte they send resets wal_receiver_timeout on the standby before the message is even parsed, so every receiver stays in the streaming state with a frozen received position and pg_stat_wal_receiver keeps returning a row. Both waits then never clear, which is the deadlock reported in #10591.

Both waits now resolve on an exact condition, with the previous time-based watermark kept only as a bound. A keepalive carries the sender's own cached position while a message carrying WAL carries the live end of the stream, so the first keepalive after a freeze pulls the reported end position back down to what the standby has already flushed. Equality between the flushed position and the reported end position is therefore an exact "nothing in flight" state, reached within one keepalive interval, not a liveness guess.

Two cases are excluded from that fast path, because either would clear a failover gate on no evidence: a standby the operator cannot reach is unknown rather than caught up, and an instance manager older than this change reports the position as empty. The grace period stays as a bound for the one case the comparison cannot settle, a primary that froze midway through sending a record, where the standby flushed only to the last complete record boundary and the sender's reported position stays permanently ahead so equality never arrives.

Why both halves are here

They are not simply complementary. Once the old primary's instance manager can be reached it stops PostgreSQL, its WAL senders exit, every receiver reports down and both waits clear unaided, so the first half is the deterministic remedy. The second half is the bound on what that cannot reach: a network partition leaving the old primary's instance manager alive but unreachable, a wedged reconcile there, a partial or failed stop, or the two halves being backported on different schedules. Those cases are real, and waiting on them without a bound is the reported deadlock, so the fallback earns its place for that reason and not because the exact comparison is unreliable.

The only API surface added is two scalars on ClusterStatus, FailoverWalReceiversWatermarkLSN and FailoverWalReceiversWatermarkTimestamp. No spec field is added and no default changes, so a cluster that tunes nothing can still wait roughly an hour on the shutdown path; what changes is that the wait is finite and ends with the lease released. .spec.switchoverDelay and .spec.smartShutdownTimeout now document that their budget covers the CHECKPOINT as well as the pg_ctl call.

Cheaper routes were explored first for the shutdown half and none reaches the same place. Stopping the lease renewal when the local PostgreSQL fails its probe gives up the split-brain guard while the old instance may still be able to resume, and the probe is documented as unreliable in both directions (#10678, #10430). Dropping the old primary from the services already happens when failover starts, and it stops replicas from reconnecting rather than ending the established streams that keep the receivers up. Terminating those streams from SQL is not available either: pg_terminate_backend cannot reach a WAL receiver, which never enters the process array, and reaching a sender needs a working connection to the instance that is not answering.

Closes #10591

@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 Jul 28, 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

@armru

armru commented Jul 28, 2026

Copy link
Copy Markdown
Member Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@cnpg-bot cnpg-bot added the ok to merge 👌 This PR can be merged label Jul 28, 2026
@armru
armru marked this pull request as ready for review July 29, 2026 08:06
@armru
armru requested a review from jsilvela as a code owner July 29, 2026 08:06
@armru
armru requested a review from a team July 29, 2026 08:06
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. bug 🐛 Something isn't working labels Jul 29, 2026
@armru armru added the no-issue label Jul 29, 2026
@armru
armru force-pushed the fix/old-primary-shutdown-bounded branch from b2a8439 to 0e47f1c Compare July 29, 2026 08:49
@armru
armru force-pushed the fix/old-primary-shutdown-bounded branch from aa92537 to 5d9f82e Compare July 29, 2026 11:04
@armru

armru commented Jul 29, 2026

Copy link
Copy Markdown
Member Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 29, 2026
@armru armru removed the no-issue label Jul 29, 2026
@armru

armru commented Jul 29, 2026

Copy link
Copy Markdown
Member Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@NiccoloFei
NiccoloFei force-pushed the fix/old-primary-shutdown-bounded branch 3 times, most recently from c89bd7c to 9cf4707 Compare August 3, 2026 12:17
armru added 2 commits August 5, 2026 12:49
…responsive

The reconcile loop only ever called reconcileOldPrimary, the code path
that shuts down a demoted primary so it can restart as a replica,
after confirming PostgreSQL was answering pg_isready. When the
primary's postmaster is frozen but its instance manager process is
still alive, that check never passes, so the demotion request was
never sent, the postmaster was never asked to stop, and the instance
manager kept renewing the primary lease forever. A newly elected
primary would then retry acquiring the lease indefinitely, with no
way for the failover to ever complete.

reconcileOldPrimary's own early exits already make it safe to call
unconditionally: it is a no-op unless this instance is both the
current primary and no longer the cluster's target primary, and that
check reads only the data directory, not a live connection. Moving
the call above the readiness gate lets the demotion, and the shutdown
it triggers, proceed regardless of whether PostgreSQL is reachable.

Signed-off-by: Armando Ruocco <[email protected]>
…timeout

Before issuing pg_ctl stop, Shutdown ran a CHECKPOINT on a fresh
connection with no timeout of its own. Against a frozen postmaster
that accepts the TCP connection but never completes the protocol
handshake, that CHECKPOINT blocked forever, so pg_ctl was never even
invoked despite already having a bounded timeout.

The CHECKPOINT and the pg_ctl call now share a single deadline: the
caller's declared options.Timeout when there is one, or 60 seconds
otherwise, which is pg_ctl's own documented default rather than an
invented number. pg_ctl is then given whatever remains of that budget
via -t, so the whole attempt can never take longer than what was
asked for. A CHECKPOINT that misses its deadline is logged and
abandoned; it is an optimisation for the shutdown that follows, never
a precondition for it.

Signed-off-by: Armando Ruocco <[email protected]>
armru and others added 22 commits August 5, 2026 12:49
pg_ctl stop -m immediate already bounds itself to 60 seconds (via
PGCTLTIMEOUT, unset in the operand image) and returns a nonzero exit
status when that expires, but nothing acted on that answer: PostgreSQL
stayed up, the instance manager never exited, and a primary lease it
held was never released. A demoted primary whose postmaster will not
stop could therefore block a failover indefinitely even after the
demotion itself became reachable.

On that exit status, TryShuttingDownFastImmediate now sends SIGKILL to
the whole process group of the postmaster read from postmaster.pid,
not just the postmaster PID itself: killing a postmaster while its
backends survive is documented by PostgreSQL as a way to corrupt
shared memory. Taking down the group is safe here because the
instance manager shares it and is about to exit anyway, and kubelet
restarts the container regardless, tearing down the PID namespace.

Signed-off-by: Armando Ruocco <[email protected]>
Their budget used to cover only the pg_ctl stop call. Now that the
pre-shutdown CHECKPOINT shares the same deadline, say so on both
fields so a user reading the API reference is not surprised by where
the time goes.

Signed-off-by: Armando Ruocco <[email protected]>
Explains, using the frozen-primary case, how a demoted primary whose
PostgreSQL will not respond still shuts down within a bounded
sequence, and what switchoverDelay and smartShutdownTimeout each cover
in that sequence. This matters because the defaults are deliberately
unchanged: a cluster that tunes nothing sees no visible difference
until it actually needs this path, so the documentation is what
reaches an operator deciding whether to tune those settings.

Signed-off-by: Armando Ruocco <[email protected]>
The comment on Shutdown claimed the attempt as a whole can never exceed the
timeout the caller asked for. That is not quite true: the remainder handed to
pg_ctl is floored at one second so it is never given a zero timeout, so when
the pre-shutdown checkpoint consumes the whole budget the attempt overshoots
it by up to a second. Say so, and say why the floor is there.

Signed-off-by: Armando Ruocco <[email protected]>
…tgreSQL

A reader reaching the failover responsiveness budget reasonably asks why the
lease does not simply expire and let the candidate take over. Spell out that
renewal is driven by the instance manager and does not depend on PostgreSQL
being responsive, so the lease protects against a lost node or a crashed
instance manager but not against an instance manager that is still healthy
next to an unresponsive PostgreSQL.

Signed-off-by: Armando Ruocco <[email protected]>
The comment stated that the instance manager shares the process group being
killed. It does not: the postmaster is started with Setpgid, so it leads a
group of its own, and that is what makes the escalation work. Were the
instance manager in that group it would be killed too and could never release
the primary lease, leaving the candidate to wait out the full lease duration.

Also say why the kill exists at all, since it reads as defensive cleanup: the
lifecycle loop is parked on the postmaster's exit channel, so that exit is
what lets the runnable return and the deferred lease release run.

Signed-off-by: Armando Ruocco <[email protected]>
The comment on killPostgresProcessGroup claimed the kill takes down
PostgreSQL and every backend, and justified that as the way to avoid the
shared memory corruption PostgreSQL warns about when a postmaster is
killed while its backends survive. The kill does not do that. PostgreSQL
calls setsid in InitPostmasterChild, so every backend, walsenders
included, is its own process group leader, and the postmaster's group
holds the postmaster alone.

Killing the postmaster is still exactly what the escalation needs: the
lifecycle loop is parked on the postmaster's exit, and the primary lease
is released only once that exit lets the runnable return. The orphaned
backends are reaped when the instance manager exits and the container is
restarted, and no postmaster runs over them in between, so describe that
instead of a reach the kill does not have.

Signed-off-by: Armando Ruocco <[email protected]>
The previous wording said the backends outlive the kill and are only
reaped when the container restarts. They do not wait that long.
PostgreSQL registers WL_POSTMASTER_DEATH on the wait set every backend
blocks on, so each backend notices the dead postmaster at its next wait
point and exits by itself, and for a walsender that is the same wait its
keepalive interval times out of. The replicas therefore lose their
streams shortly after the kill rather than at the container restart,
which matters because that is what lets the operator stop waiting for
the WAL receivers to be down.

The container restart still covers the one case that has no wait point
to reach, a backend spinning in a CPU-bound query.

Signed-off-by: Armando Ruocco <[email protected]>
…ozen primary

When a primary's node freezes together with its PostgreSQL and instance
manager processes (for example, an unresponsive kubelet plus SIGSTOP on
both processes), the postmaster stops but its walsender children keep
sending replication keepalives. On the replicas those keepalives reset
wal_receiver_timeout, so every walreceiver stays in the streaming state
indefinitely with a frozen received LSN, and pg_stat_wal_receiver keeps
reporting a row.

The failover path waited for all WAL receivers to report down before
electing a new primary, using the presence of that row as the signal.
Since the receivers never report down in this case, the cluster entered
the "Failing over" phase and stayed there, logging "Waiting for all WAL
receivers to be down to elect a new primary" indefinitely.

Add a data-plane escape to that wait. When the receivers are still up
but the maximum received LSN across them has not advanced for a grace
period and the former primary is no longer reporting its status,
proceed with the election. A stalled, keepalive-only connection is
receiving no WAL, so holding the election provides no data-safety
benefit while blocking recovery. Continued progress on the received LSN
still holds the election, so a partitioned but live primary that is
still shipping WAL is never promoted against, and the promotion stays
gated by the primary lease.

Signed-off-by: Armando Ruocco <[email protected]>
… frozen primary

After the operator elects a new primary, the candidate's instance
manager waits for its own WAL receiver to be down before promoting, so
a clean switchover doesn't discard WAL that is still streaming in. The
candidate streams from the same frozen primary, so its receiver suffers
the identical problem the election gate does: the primary's walsenders
keep sending keepalives, the receiver stays in the streaming state with
a frozen received LSN, and the wait never completes. The promotion hung
indefinitely, logging "WAL receiver is still active, waiting" once a
second.

Bound that wait by received-LSN progress. When the WAL receiver is up
but its received LSN has not advanced for a short grace period, proceed
with the promotion, since a stalled, keepalive-only connection is
receiving no WAL and there is nothing left to wait for. Continued
progress on the received LSN still holds the wait, preserving its
original purpose for a clean or slow switchover, and the promotion
remains gated by the primary lease.

Closes #10591

Signed-off-by: Armando Ruocco <[email protected]>
…ction commits

evaluateWalReceiversGate cleared the stalled-progress watermark on its
escape path before the caller committed the primary election. If the
status patch that commits the election (setPrimaryInstance) failed for
any reason, the next reconciliation would find an empty watermark,
treat it as a first observation, and restart the full grace period in
a code path whose entire purpose is to stop waiting once that period
has already elapsed. Move the clear to after the caller's election
patch succeeds, in both the non-replica and replica-cluster paths, and
leave the watermark alone in between.

Signed-off-by: Armando Ruocco <[email protected]>
…iver

The received-LSN watermark that bounds the wait for the WAL receivers to go
down skipped any standby that was not reporting an active WAL receiver. For an
instance whose status probe failed, that flag is an unset default rather than an
observation, so an unreachable standby was silently counted as a receiver that
was down and making no progress.

Exclude those standbys explicitly, on the probe error rather than on the flag,
and carry their names out of the watermark computation so the event emitted when
the wait is bypassed can list them. An unreachable standby may still be
streaming from the old primary, and that is precisely when proceeding with the
election risks stranding WAL, so it belongs in the event rather than in a log
line nobody reads. When no standby could be probed at all there is nothing to
age and the wait is held, as before.

Signed-off-by: Armando Ruocco <[email protected]>
pg_stat_wal_receiver.latest_end_lsn distinguishes a keepalive's cached
sender-side position from the live flush position carried by an actual
WAL message. Fold it into the existing wal receiver query instead of a
separate round trip, and expose it on PostgresqlStatus next to
ReceivedLsn, so callers can compare the two to tell whether anything is
still in flight between the sender and this receiver.

Signed-off-by: Armando Ruocco <[email protected]>
The WAL-receivers-down gate escapes a frozen primary by waiting out a
grace period once the received LSN stops advancing, which is a
liveness heuristic rather than proof that nothing is in flight. When
every up, reporting standby's ReceivedLsn already equals its
LatestEndLsn, the sender has nothing left to give it, so let the
election proceed immediately instead of waiting on the timer.

A standby that failed to report stays unknown and disqualifies the
fast path, same as it already does for the watermark logic, and an
empty LatestEndLsn (an older instance manager mid rolling upgrade)
never counts as equal. The watermark itself is left untouched here;
it is only cleared once the election actually commits.

Signed-off-by: Armando Ruocco <[email protected]>
Mirrors the operator-side election gate: while waiting for the WAL
receiver to go down before a promotion, if the receiver is active but
has already flushed everything its sender reported (ReceivedLsn equals
LatestEndLsn), proceed with the promotion instead of waiting out the
15 second stall grace period. An empty LatestEndLsn still falls
through to the existing grace period, never satisfies the fast path.

Also corrects a stale comment: this branch of handlePromotion runs on
every promotion, switchover as well as failover, since
CurrentPrimary is only rewritten to this pod's own name once
handlePromotion returns.

Signed-off-by: Armando Ruocco <[email protected]>
The instance reconciler now takes an event recorder, which it uses to
warn when the WAL receivers are stalled. The demotion-ordering test
built the reconciler before that parameter existed, so it no longer
compiled. Give it a fake recorder rather than a nil one, so that a path
which does emit an event records it instead of panicking.

Signed-off-by: Armando Ruocco <[email protected]>
…mary loss

Both failover gates wait for every WAL receiver to report down, and a
primary that freezes without closing its sockets leaves senders behind
that keep the receivers looking alive. Document that the waits resolve on
an exact comparison of the flushed position against the position the
sender reports, why a keepalive is what makes that comparison meaningful,
and which two cases are excluded from it. Say plainly that the grace
period is a bound for a primary that froze midway through sending a
record, not the mechanism the waits normally clear on, and repeat that
completing the failover does not recover WAL that never left the lost
primary.

Signed-off-by: Armando Ruocco <[email protected]>
Trim the primary-loss section in failover.md and the failover-budget
section in failure_modes.md to describe just the current behavior plainly.
Drop internal mechanism details and "before this fix"/"what changed" framing
that only makes sense from the point of view of this change's own history, not
to a reader of the general docs.

Signed-off-by: Niccolò Fei <[email protected]>
Signed-off-by: Niccolò Fei <[email protected]>
@NiccoloFei
NiccoloFei force-pushed the fix/old-primary-shutdown-bounded branch from da27679 to e67fd0c Compare August 5, 2026 10:49
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Aug 5, 2026
@armru armru closed this Aug 18, 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

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 lgtm This PR has been approved by a maintainer ok to merge 👌 This PR can be merged release-1.28 release-1.30 size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Failover blocked indefinitely when walsender survives on zombie node (storage failure with kernel alive)

3 participants