Skip to content

feat: detect a stalled write path of the primary and fail over - #11804

Open
Ghost7K wants to merge 4 commits into
cloudnative-pg:mainfrom
Ghost7K:write-path-check
Open

Ghost7K wants to merge 4 commits into
cloudnative-pg:mainfrom
Ghost7K:write-path-check

Conversation

@Ghost7K

@Ghost7K Ghost7K commented Oct 30, 2026

Copy link
Copy Markdown

Closes #10678

Problem

A primary whose storage blocks every write (an EBS/volume I/O pause, a frozen filesystem) is never replaced. PostgreSQL stays up and answers read-only queries, /pg/status reports it healthy, and the pod stays ready. On top of that, its walsenders keep sending keepalives, so the replicas' WAL receivers never go down and AreWalReceiversDown would block a failover even if one were started (see also #10591).

We reproduced it by freezing the primary's data volume with fsfreeze on a two-instance cluster: nothing happened for the 5.5 minutes of the freeze, and the Cluster reported 2/2 ready the whole time.

Change

This PR adds an opt-in check under .spec.probes.liveness.writePathCheck:

Field Default
enabled false
periodSeconds 10
timeoutSeconds 30
clearAfterSuccesses 3
  • Heartbeat. The primary's instance manager runs this on its own connection:
    BEGIN; SET LOCAL synchronous_commit = local;
    SELECT pg_catalog.pg_logical_emit_message(true, 'cnpg-write-path-check', ''); COMMIT;
  • Election. The stall is reported as isWritePathStalled in /pg/status, and PostgresqlStatusList.Less sorts a stalled instance after the healthy ones. Without a healthy replica, nothing changes.
  • Lease. On a stall the primary stops renewing the primary lease through the new Runnable.StopRenewing.
    • It behaves like Yield, but the lease-age monitor (with its peer check) keeps running, so the still-running PostgreSQL stays fenced.
    • The record is not blanked, so a replica takes over after the usual LeaseDuration.
    • The polling lock calls keep the liveness watchdog beating, so the kubelet does not restart the pod because of the stall.
    • The next Acquire takes the lease back once the stall is over.
  • Demotion. The instance reconciler handles the stall before any step that writes to PGDATA. Once another instance, or the pending failover marker, is the target, the stall is latched and PostgreSQL is shut down immediately with no checkpoint. This reuses the non-blocking request and the immediateShutdownTimeout handling of the unreachable-primary demotion (fix(controller): demote an unreachable old primary immediately during failover #11347). That demotion path does not trigger on its own here, because the stalled primary still answers SELECT 1.
  • WAL receivers. While the failover is pending and the check is enabled, replicas terminate their own WAL receiver.
    • The blocked primary can't be relied upon to end its walsenders.
    • markOldPrimaryAsUnhealthy keeps the replicas off -rw, so they don't reconnect.
  • Operator requeue. The operator reconciles clusters with the check enabled at least once per periodSeconds. A stalled primary changes nothing the operator watches, so in our first test run the stall was only acted upon after an unrelated change to the Cluster.

Testing

  • Unit tests. The touched packages pass, and the lease, run, controller, writepath and postgres packages pass with -race. The new tests cover:

    • StopRenewing: the watchdog stays healthy, the monitor keeps running and can still hard-stop, and re-acquire starts no second monitor.
    • The status ordering, including the existing ordering property test.
    • Webhook validation.
    • The reconciler's replica path.
    • The operator requeue.
  • Known failure, not from this change. One test in pkg/management/postgres ("testing backup command … should fail and update cluster and backup resource") also fails on a clean checkout of main.

  • TLA+. TLC passes on the unchanged PrimaryLease model, with the same state counts as the README. A primary that stops renewing while its monitor keeps running is already a behaviour the model explores. The README now says so.

  • On a real cluster (backport of this change to 1.30.1). Two instances of PostgreSQL 16; the primary's volume was frozen for 5 minutes while a client wrote one row per second.

    Event Time after the freeze
    Stall detected ~30 s
    Failover started 47 s
    Replica promoted 48 s
    -rw writable again 111 s
    • No acknowledged commit was lost.
    • The old primary rejoined through pg_rewind after the thaw.
  • Not yet run on top of current main. The port to main is covered by unit tests only so far, and I have not added an E2E test yet. Happy to add one if this direction is acceptable.

Open points

  • Between promotion and the -rw service becoming writable, most of the time goes to the operator's status poll of the frozen pod (~31 s per poll, twice), which runs before the primary label is set. Not waiting for a stalled old primary there would cut this further. I left it out to keep the PR focused.
  • golangci-lint could not be run locally (toolchain mismatch); I'm relying on CI.

🤖 Generated with Claude Code

https://claude.ai/code/session_01891ECcbNHnJQQfWF4yA7J1

Ghost7K and others added 4 commits October 30, 2026 16:09
Add the opt-in configuration (disabled by default) of a check that
detects a primary whose write path is blocked, for example because of a
frozen or unresponsive data volume. It adds the `enabled`,
`periodSeconds` (10), `timeoutSeconds` (30) and `clearAfterSuccesses`
(3) fields, the getters with their defaults, and the validation that the
effective timeout is greater than the period.

This commit only adds the API. The check itself follows.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01891ECcbNHnJQQfWF4yA7J1
Signed-off-by: Maurice Sobiera <[email protected]>
…nstances

Add `isWritePathStalled` to the instance status reported on `/pg/status`.
A primary with a stalled write path sorts behind every healthy instance
(and before the ones with an incomplete status or fenced), so the
existing failover logic elects a replica when there is one. When no
healthy instance is left, the stalled primary stays first of the list:
no failover happens.

The generator of the `Less` property test now covers the new field.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01891ECcbNHnJQQfWF4yA7J1
Signed-off-by: Maurice Sobiera <[email protected]>
…d fail over

When `.spec.probes.liveness.writePathCheck.enabled` is true, the instance
manager of the primary runs a heartbeat on its own connection:
`BEGIN; SET LOCAL synchronous_commit = local;
SELECT pg_catalog.pg_logical_emit_message(true, 'cnpg-write-path-check', '');
COMMIT;`. It forces a local WAL flush without waiting for synchronous
standbys. A heartbeat that does not complete within `timeoutSeconds` is a
stalled write path; a heartbeat that fails with an error is not. The
stall is reported in `/pg/status` and cleared after `clearAfterSuccesses`
consecutive heartbeats.

On a stall, the primary stops renewing the primary lease with the new
`Runnable.StopRenewing`, so that a replica can take the lease over after
the usual observation window. It behaves like `Yield`, except that the
lease-age monitor keeps running: the primary is still running PostgreSQL,
and the monitor, with its peer check, stops it once it is superseded or
after the lease is about to be claimed, as for a primary that can't renew
the lease. The record is not blanked, and the polling lock calls keep the
liveness watchdog beating, so the kubelet does not restart the Pod
because of the stall. The next `Acquire` takes the lease back once the
stall is over.

The instance reconciler handles the stall before any step that writes to
PGDATA. While this instance is the target primary, the rest of the
reconciliation is skipped. Once another instance (or the pending failover
marker) is the target, the stall is latched and PostgreSQL is shut down
immediately, with no checkpoint, reusing the non-blocking request and
the `immediateShutdownTimeout` handling of the unreachable-primary
demotion. That path does not apply here, because a primary that can't
write still answers read-only queries.

While the failover is pending, replicas terminate their own WAL receiver
(only when the check is enabled). The primary can't be relied upon to end
its walsenders, as it is the instance that is blocked, and the old
primary can't be reached again through the `-rw` service, since the
operator marks it unhealthy when the failover starts. This replaces the
termination of the walsenders on the primary, which is not needed.

The operator reconciles a cluster with the check enabled at least once
per `periodSeconds`: a primary with a stalled write path changes nothing
the operator watches (the Pod stays ready and the primary lease updates
are filtered out), so without a periodic reconciliation the stall
reported by the instance manager would not be evaluated until an
unrelated change to the Cluster.

Tested on a fork based on 1.30.1, with a two-instance PostgreSQL 16
cluster, freezing the filesystem of the primary volume for 5 minutes
while a client wrote one row per second: stall detected after about
30 s, failover started at 47 s, replica promoted at 48 s, `-rw` writable
again at 111 s (the status poll of the frozen Pod by the operator timed
out about 31 s twice before the primary label was set). No acknowledged
commit was lost and the old primary rejoined through `pg_rewind`. Without
the periodic reconciliation, no failover happened until an unrelated
change of the Cluster. The code has not been run on a cluster on top of
current main, only through unit tests.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01891ECcbNHnJQQfWF4yA7J1
Signed-off-by: Maurice Sobiera <[email protected]>
Describe `spec.probes.liveness.writePathCheck`: the heartbeat, what a
stall is and is not, how the primary lease, the failover and the
demotion behave, and the limits of the check. The limits include the
interaction with the primary isolation check (a stalled primary that
can't reach one of its peers is shut down even without a replica to fail
over to) and the liveness probe restarting a Pod whose PostgreSQL ignores
the immediate shutdown after the demotion.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01891ECcbNHnJQQfWF4yA7J1
Signed-off-by: Maurice Sobiera <[email protected]>
@Ghost7K
Ghost7K requested a review from a team as a code owner October 30, 2026 16:09
@cnpg-bot cnpg-bot added backport-requested ◀️ This pull request should be backported to all supported releases release-1.28 release-1.30 labels Oct 30, 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 release-1.28 release-1.30

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: /pg/status keeps reporting healthy while primary write-path is wedged, delaying operator failover

2 participants