Skip to content

fix: Mark replicas unhealthy on stalled WAL replay error loops - #11135

Open
ardentperf wants to merge 2 commits into
cloudnative-pg:mainfrom
ardentperf:pr-detect-broken-replica
Open

ardentperf wants to merge 2 commits into
cloudnative-pg:mainfrom
ardentperf:pr-detect-broken-replica

Conversation

@ardentperf

@ardentperf ardentperf commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

This change detects replicas stuck in repeated unrecoverable WAL replay errors and marks the instance unhealthy using existing CNPG health paths.

Reproducer: https://github.com/ardentperf/bug-repro-wal-restore

important: if someone went into a pod and manually executed pg_rewind to recover, current PR design would still require a pod restart to clear the flag allowing CNPG to mark it healthy

The patch intentionally avoids automatic remediation. It does not delete pods, recreate PVCs, fence instances, or mark the Cluster unrecoverable. It only makes the broken replica stop looking healthy.

Main changes:

  • Adds an instance statusError field.
    • A non-empty value causes GetStatus() and therefore /pg/status to fail.
    • The operator records the failed /pg/status call as a status collection error.
    • Existing target selection already avoids instances with status collection errors.
    • This is process-local state and is cleared by restarting the affected Pod.
  • Adds a log monitor path for CSV log records.
    • LogPipe now accepts a RecordWriter, and a new MultiRecordWriter fans each parsed log record out to every configured RecordWriter.
    • The instance manager builds a MultiRecordWriter holding the WAL replay detector alongside the normal log writer, so multiple independent detectors can observe records without chaining.
    • The WAL replay detector is a pure observer — it inspects records in memory and no longer forwards them itself (delivery is handled by the MultiRecordWriter).
  • Adds WAL replay loop detection.
    • Tracks repeated matching WAL replay errors at the same LSN.
    • Requires 3 repeated matches within the configured window.
    • Skips primaries.
    • On detection, sets canCheckReadiness=false and sets the instance status error.

Behavior after detection:

  • readiness fails, so Kubernetes removes the replica from service endpoints
  • /pg/status fails with a clear message
  • normal cluster failover target selection avoids the instance through existing status-error handling
  • logs remain the primary visibility mechanism for the detailed condition

This PR deliberately does not add Cluster phase reporting for this condition. A follow-up feature could add a generic mechanism for instance-manager detected faults that require user action to be surfaced in Cluster status, but that is kept out of this minimal fix.

Tests run:

go test ./internal/cmd/manager/instance/run ./pkg/management/postgres ./pkg/management/postgres/logpipe ./pkg/postgres ./internal/controller

Fixes #11134

Detect replicas stuck in repeated unrecoverable WAL replay errors and
marks the instance unhealthy using existing CNPG health paths. Adds an
instance `statusError` field and adds a log monitor path for CSV log
records that detects unrecoverable WAL replay loops.

Signed-off-by: Jeremy Schneider <[email protected]>
@ardentperf
ardentperf requested a review from a team July 6, 2026 18:51
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. bug 🐛 Something isn't working release-1.28 release-1.29 release-1.30 labels Jul 6, 2026
@cnpg-bot cnpg-bot added the backport-requested ◀️ This pull request should be backported to all supported releases label Jul 6, 2026
@github-actions

github-actions Bot commented Jul 6, 2026

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

to support multiple detectors, base this on a multirecordwriter now.
this is a better direction than chaining writers.

Signed-off-by: Jeremy Schneider <[email protected]>
ardentperf-agent Bot added a commit to ardentperf/cloudnative-pg that referenced this pull request Jul 6, 2026
Signed copy of cloudnative-pg#11135, used as a prerequisite
for the startup-probe WAL replay progress detector.

Signed-off-by: ardentperf-agent[bot] <265149240+ardentperf-agent[bot]@users.noreply.github.com>
@armru

armru commented Jul 7, 2026

Copy link
Copy Markdown
Member

The PR looks good to me, and I like the same-LSN repetition idea: from
what I can tell from the PostgreSQL sources, these messages only show up
when a WAL source keeps serving actual bad bytes, and the benign
end-of-WAL repeats seem to be suppressed to DEBUG1, so I don't think
they can reach the threshold. There are a few points I'd like to
discuss though.

1. I think the detector should also check where the message comes
from.
If I'm reading it right, any CSV record whose message matches
would count, regardless of which backend emitted it, so for example
three RAISE EXCEPTION 'contrecord is requested by 0/5A000028' from a
connected user would mark the replica unhealthy (pg_walinspect seems
able to produce the same text inside its error messages too). Since the
genuine loop messages should only come from the startup process, and
LoggingRecord already parses backend_type (PG 13+), wouldn't a
BackendType == "startup" check close this?

2. Have you considered clearing statusError when the postmaster
restarts in place?
The instance manager re-enables canCheckReadiness
at every postmaster session start (lifecycle/run.go), so after an
in-place restart (config change, unfencing) the two signals seem to
diverge: the pod becomes ready again and rejoins the -ro service while
/pg/status keeps failing. Clearing the error at that same point feels
more consistent to me, and I think it would also address the pg_rewind
caveat from your description: a still-broken replica should re-trip
within seconds, while a fixed one recovers without deleting the pod.

3. I'm a bit worried about the fencing interaction. The early
return in GetStatus is above the MightBeUnavailable masking defer,
so if someone fences the broken replica (which I'd expect to be a common
reaction) I believe /pg/status would keep hard-failing instead of
reporting as expected-down, leaving cluster reconciliation blocked.
Would moving the check below the defer, or clearing the error on
fencing, make sense?

Two smaller things:

  • If the replica stays permanently not-ready, I believe reconcilePods
    stops at its "waiting for pods to be ready" gates, so scale changes
    and rolling updates would freeze until someone intervenes (failover
    and switchover should still work). Maybe that's the right trade-off
    for a replica that needs human attention, but I'd call it out in the
    PR body.
  • The messages are translated under a non-English lc_messages, so
    detection would silently turn off there; probably fine, but worth a
    comment (backend_type is never translated, so the check from point 1
    should be safe). Also, having the actual LSN in the status error
    message would help debugging.

The MultiRecordWriter change looks good to me.

@ardentperf

Copy link
Copy Markdown
Contributor Author

thanks for the review and feedback

(pg_walinspect seems able to produce the same text inside its error messages too). Since the genuine loop messages should only come from the startup process, and LoggingRecord already parses backend_type (PG 13+), wouldn't a BackendType == "startup" check close this?

good catch on pg_walinspect. i think responding to an explicit RAISE EXCEPTION might be useful for testing (unlikely someone does that accidentally) - but while unlikely, i think pg_walinspect could happen while someone was debugging. i'll work on an update to filter on BackendType

2. Have you considered clearing statusError when the postmaster restarts in place? ... Clearing the error at that same point feels more consistent to me, and I think it would also address the pg_rewind caveat from your description

i agree this makes sense. i think that resetting the state with in-place postmaster restarts will be intuitive for users.

early return in GetStatus is above the MightBeUnavailable masking defer, so if someone fences the broken replica (which I'd expect to be a common reaction) I believe /pg/status would keep hard-failing instead of reporting as expected-down, leaving cluster reconciliation blocked. Would moving the check below the defer, or clearing the error on fencing, make sense?

random comment: MightBeUnavailable seems like an odd name to me for fencing :)

i hadn't fully thought through the interaction with fencing after the instance gets into an unrecoverable state. this is helpful.

i think the error should be left in place when an instance is fenced; i haven't traced all the code yet but i'm thinking masked errors might still be visible? but i do think it would make sense to clear the error on un-fencing, if that won't already happen. if instances can be un-fenced without any in-place postmaster restart the it might be worth an extra line of code to do this explicitly.

  • If the replica stays permanently not-ready, I believe reconcilePods
    stops at its "waiting for pods to be ready" gates, so scale changes
    and rolling updates would freeze until someone intervenes (failover
    and switchover should still work). Maybe that's the right trade-off
    for a replica that needs human attention, but I'd call it out in the
    PR body.

actually i dont think this is the right tradeoff - but i think this should be a separate PR. IMO we should think more broadly about "how should reconciliation work with pods that aren't ready"

  • The messages are translated under a non-English lc_messages, so
    detection would silently turn off there; probably fine, but worth a
    comment (backend_type is never translated, so the check from point 1
    should be safe). Also, having the actual LSN in the status error
    message would help debugging.

i originally had LSN in the message, during an early draft, and removed it from the message bc that seemed a little more consistent with other messages to me :) happy to add it back in, that works for me

i'll work on a new revision of this patch. thanks again for reviewing!!

@ardentperf

Copy link
Copy Markdown
Contributor Author

nb. i will also address linter feedback in the PR

mnencia added a commit that referenced this pull request Jul 17, 2026
…11152)

When a PostgreSQL instance has to replay a large amount of WAL before
reaching consistency (for example a standby restarting after a crash, as
reported in #11024), `pg_isready` reports that the server is alive but
rejecting connections until recovery completes. The startup probe
treated that state as a failure, so when recovery outlasted `startDelay`
the kubelet killed the pod. Every restart threw away the replay progress
and the instance could never catch up, looping forever.

With the default `pg_isready` strategy, the startup probe now considers
a server that is alive but rejecting connections as already started up:

- The liveness probe will not restart it, because it returns OK
unconditionally for a non-primary instance.
- The readiness probe keeps failing on a server that rejects
connections, so a recovering instance stays out of the ready endpoints
of the services and is not eligible for promotion until it accepts
connections.

The `query` and `streaming` startup strategies are unchanged: they
require PostgreSQL to accept connections by design, and the
documentation now points out that `startDelay` must account for recovery
time when using them.

One trade-off worth noting: the startup probe was previously the only
mechanism that restarted a pod whose PostgreSQL was permanently stuck
while rejecting connections, even though in the #11024 scenario those
restarts were exactly what prevented recovery from completing. With this
change such an instance is reported as started and left to continue
attempting recovery, with no automatic restart if it never completes. A
specific form of this, repeated WAL-replay error loops, is proposed in
#11135, which does not cover a replica silently stalled with no matching
errors.

This was verified on a kind cluster by reproducing the scenario from the
issue: a two-instance cluster with `startDelay: 10`, one-second probe
periods, and `checkpoint_timeout: 5h` so that the standby takes no
restartpoints. After writing about 4.7GiB of WAL and deleting the
standby pod, the instance came back in `shut down in recovery`, the
first startup probe reported it as started, the pod stayed not ready
while replaying (readiness failing with HTTP 500), and it became ready
about 40 seconds later with zero container restarts. The same
configuration on the previous build restarted the pod every 10 seconds.

Unit tests cover the new startup checker and the probe runner selection,
which previously had no coverage.

Thanks to Jeremy Schneider for reporting this issue and providing a
detailed analysis of the failure.

Closes #11024

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Leonardo Cecchi <[email protected]>
Co-authored-by: Jeremy Schneider <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>
cnpg-bot pushed a commit that referenced this pull request Jul 17, 2026
…11152)

When a PostgreSQL instance has to replay a large amount of WAL before
reaching consistency (for example a standby restarting after a crash, as
reported in #11024), `pg_isready` reports that the server is alive but
rejecting connections until recovery completes. The startup probe
treated that state as a failure, so when recovery outlasted `startDelay`
the kubelet killed the pod. Every restart threw away the replay progress
and the instance could never catch up, looping forever.

With the default `pg_isready` strategy, the startup probe now considers
a server that is alive but rejecting connections as already started up:

- The liveness probe will not restart it, because it returns OK
unconditionally for a non-primary instance.
- The readiness probe keeps failing on a server that rejects
connections, so a recovering instance stays out of the ready endpoints
of the services and is not eligible for promotion until it accepts
connections.

The `query` and `streaming` startup strategies are unchanged: they
require PostgreSQL to accept connections by design, and the
documentation now points out that `startDelay` must account for recovery
time when using them.

One trade-off worth noting: the startup probe was previously the only
mechanism that restarted a pod whose PostgreSQL was permanently stuck
while rejecting connections, even though in the #11024 scenario those
restarts were exactly what prevented recovery from completing. With this
change such an instance is reported as started and left to continue
attempting recovery, with no automatic restart if it never completes. A
specific form of this, repeated WAL-replay error loops, is proposed in
#11135, which does not cover a replica silently stalled with no matching
errors.

This was verified on a kind cluster by reproducing the scenario from the
issue: a two-instance cluster with `startDelay: 10`, one-second probe
periods, and `checkpoint_timeout: 5h` so that the standby takes no
restartpoints. After writing about 4.7GiB of WAL and deleting the
standby pod, the instance came back in `shut down in recovery`, the
first startup probe reported it as started, the pod stayed not ready
while replaying (readiness failing with HTTP 500), and it became ready
about 40 seconds later with zero container restarts. The same
configuration on the previous build restarted the pod every 10 seconds.

Unit tests cover the new startup checker and the probe runner selection,
which previously had no coverage.

Thanks to Jeremy Schneider for reporting this issue and providing a
detailed analysis of the failure.

Closes #11024

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Leonardo Cecchi <[email protected]>
Co-authored-by: Jeremy Schneider <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>
(cherry picked from commit 268dcfd)
cnpg-bot pushed a commit that referenced this pull request Jul 17, 2026
…11152)

When a PostgreSQL instance has to replay a large amount of WAL before
reaching consistency (for example a standby restarting after a crash, as
reported in #11024), `pg_isready` reports that the server is alive but
rejecting connections until recovery completes. The startup probe
treated that state as a failure, so when recovery outlasted `startDelay`
the kubelet killed the pod. Every restart threw away the replay progress
and the instance could never catch up, looping forever.

With the default `pg_isready` strategy, the startup probe now considers
a server that is alive but rejecting connections as already started up:

- The liveness probe will not restart it, because it returns OK
unconditionally for a non-primary instance.
- The readiness probe keeps failing on a server that rejects
connections, so a recovering instance stays out of the ready endpoints
of the services and is not eligible for promotion until it accepts
connections.

The `query` and `streaming` startup strategies are unchanged: they
require PostgreSQL to accept connections by design, and the
documentation now points out that `startDelay` must account for recovery
time when using them.

One trade-off worth noting: the startup probe was previously the only
mechanism that restarted a pod whose PostgreSQL was permanently stuck
while rejecting connections, even though in the #11024 scenario those
restarts were exactly what prevented recovery from completing. With this
change such an instance is reported as started and left to continue
attempting recovery, with no automatic restart if it never completes. A
specific form of this, repeated WAL-replay error loops, is proposed in
#11135, which does not cover a replica silently stalled with no matching
errors.

This was verified on a kind cluster by reproducing the scenario from the
issue: a two-instance cluster with `startDelay: 10`, one-second probe
periods, and `checkpoint_timeout: 5h` so that the standby takes no
restartpoints. After writing about 4.7GiB of WAL and deleting the
standby pod, the instance came back in `shut down in recovery`, the
first startup probe reported it as started, the pod stayed not ready
while replaying (readiness failing with HTTP 500), and it became ready
about 40 seconds later with zero container restarts. The same
configuration on the previous build restarted the pod every 10 seconds.

Unit tests cover the new startup checker and the probe runner selection,
which previously had no coverage.

Thanks to Jeremy Schneider for reporting this issue and providing a
detailed analysis of the failure.

Closes #11024

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Leonardo Cecchi <[email protected]>
Co-authored-by: Jeremy Schneider <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>
(cherry picked from commit 268dcfd)
cnpg-bot pushed a commit that referenced this pull request Jul 17, 2026
…11152)

When a PostgreSQL instance has to replay a large amount of WAL before
reaching consistency (for example a standby restarting after a crash, as
reported in #11024), `pg_isready` reports that the server is alive but
rejecting connections until recovery completes. The startup probe
treated that state as a failure, so when recovery outlasted `startDelay`
the kubelet killed the pod. Every restart threw away the replay progress
and the instance could never catch up, looping forever.

With the default `pg_isready` strategy, the startup probe now considers
a server that is alive but rejecting connections as already started up:

- The liveness probe will not restart it, because it returns OK
unconditionally for a non-primary instance.
- The readiness probe keeps failing on a server that rejects
connections, so a recovering instance stays out of the ready endpoints
of the services and is not eligible for promotion until it accepts
connections.

The `query` and `streaming` startup strategies are unchanged: they
require PostgreSQL to accept connections by design, and the
documentation now points out that `startDelay` must account for recovery
time when using them.

One trade-off worth noting: the startup probe was previously the only
mechanism that restarted a pod whose PostgreSQL was permanently stuck
while rejecting connections, even though in the #11024 scenario those
restarts were exactly what prevented recovery from completing. With this
change such an instance is reported as started and left to continue
attempting recovery, with no automatic restart if it never completes. A
specific form of this, repeated WAL-replay error loops, is proposed in
#11135, which does not cover a replica silently stalled with no matching
errors.

This was verified on a kind cluster by reproducing the scenario from the
issue: a two-instance cluster with `startDelay: 10`, one-second probe
periods, and `checkpoint_timeout: 5h` so that the standby takes no
restartpoints. After writing about 4.7GiB of WAL and deleting the
standby pod, the instance came back in `shut down in recovery`, the
first startup probe reported it as started, the pod stayed not ready
while replaying (readiness failing with HTTP 500), and it became ready
about 40 seconds later with zero container restarts. The same
configuration on the previous build restarted the pod every 10 seconds.

Unit tests cover the new startup checker and the probe runner selection,
which previously had no coverage.

Thanks to Jeremy Schneider for reporting this issue and providing a
detailed analysis of the failure.

Closes #11024

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Leonardo Cecchi <[email protected]>
Co-authored-by: Jeremy Schneider <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>
(cherry picked from commit 268dcfd)
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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Replica can remain healthy after unrecoverable WAL replay loop

4 participants