Skip to content

Fix race condition in primary update switchover - #11185

Open
bramhanandlingala wants to merge 28 commits into
cloudnative-pg:mainfrom
bramhanandlingala:fix-unsupervised-switchover-race
Open

bramhanandlingala wants to merge 28 commits into
cloudnative-pg:mainfrom
bramhanandlingala:fix-unsupervised-switchover-race

Conversation

@bramhanandlingala

Copy link
Copy Markdown

Fixes #11114.

What happened?

During an unsupervised primary update switchover, a race condition occurred where the new target primary was selected before the existing primary was fully shut down. Because the old primary could still accept writes during the shutdown process, those writes could be replicated to other synchronous replicas (e.g., under quorum-based synchronous replication method: any) but not the pre-selected new primary. Once the switchover was completed, a less up-to-date replica would be promoted, causing the more advanced replicas to crash-loop because they were ahead of the new primary's timeline.

How was it fixed?

To resolve this, the selection of the new primary is now delayed until after the fast shutdown of the old primary completes:

  1. Introduced a new apiv1.PendingSwitchoverMarker in cluster_types.go.
  2. In updatePrimaryPod (cluster_upgrade.go), we now verify the best candidate's WAL replay lag but assign TargetPrimary to the PendingSwitchoverMarker instead of the specific candidate's name.
  3. The instance controller sees that the TargetPrimary is not the current primary and initiates the fast shutdown.
  4. replicas.go intercepts the PendingSwitchoverMarker, waits for all WAL receivers to gracefully terminate (ensuring no more WALs are being streamed), and safely promotes the most advanced replica as the new primary via PhaseSwitchover.

armru and others added 28 commits July 6, 2026 22:49
The in-core Barman Cloud support is deprecated, so the e2e suite needs to
exercise backups through the external plugin-barman-cloud. Install the plugin
(and its cert-manager prerequisite) into cnpg-system after the operator is
deployed, on local kind/k3d engines. cert-manager is a hard prerequisite (the
plugin manifest ships its Issuer/Certificate resources) and was not installed
by the harness before; its version is renovate-tracked. Both manifests are
downloaded once to a local file, as deploy_operator_from_manifest already
does, so the apply retries do not re-fetch them.

The plugin build is selected via BARMAN_PLUGIN_VERSION:
  - release (default): the latest published release
  - main:              the current snapshot from the main branch
  - vX.Y.Z:            a specific pinned release

The selector is exposed as the 'barman_plugin' workflow_dispatch input and the
'/test barman_plugin=<v>' (alias 'bp') chatops argument; it flows through
check_commenter / test_arguments / evaluate_options and reaches the kind and
k3d e2e jobs as BARMAN_PLUGIN_VERSION. Other engines are unchanged for now.
The operator is intentionally left as the default local (PR) build, consistent
with current behaviour; it remains overridable via setup-cluster.sh -o for
manual runs.

The concrete deployed version is read back from the running deployment image,
exported as BARMAN_PLUGIN_VERSION_RESOLVED, and logged together with the
operator version in the suite's startup configuration banner.

Signed-off-by: Armando Ruocco <[email protected]>
Exercise the plugin-barman-cloud build selected for the run end to end: create
an ObjectStore backed by the shared e2e MinIO, bring up a cluster that uses
the plugin as its WAL archiver, assert the operator reports the plugin as
loaded, write a known table, take a backup through the plugin, recover it into
a new cluster via the externalClusters plugin source, and check the rows come
back.

The ObjectStore CR is created as an unstructured object since its CRD lives in
the external plugin and is not registered in the operator's scheme. The test
waits for the ContinuousArchiving condition before the backup so an archiving
problem fails clearly instead of timing out later, and switches and archives
the closing WAL after the backup: the plugin backup does not force the WAL
segment holding the backup-stop record to be archived, so a standalone restore
on an otherwise idle cluster could intermittently miss its consistent recovery
point.

A pinned BARMAN_PLUGIN_VERSION is validated with the same anchored pattern
used by deploy_operator_from_manifest so a malformed value fails fast with a
clear message instead of a confusing 404, and the barman_plugin argument of
the /test command is documented in the e2e contribute guide. The test runs
only on kind/k3d, where the plugin and the shared MinIO are installed.

Signed-off-by: Armando Ruocco <[email protected]>
A source cluster archives through plugin-barman-cloud, a backup is taken
through the plugin, and a replica cluster is bootstrapped from that backup via
the externalClusters plugin source and then streams from the source.

Added next to the in-core replica-from-backup test rather than converting it:
that test shares its source cluster with a volume-snapshot scenario, so the
in-core variant stays until the in-core Barman Cloud support is removed. Runs
on kind and k3d only.

Signed-off-by: Armando Ruocco <[email protected]>
A cluster with tablespaces archives through plugin-barman-cloud, is backed up
through the plugin, and is restored into a new cluster whose tablespaces are
recreated from the backup, verifying tablespaces survive a plugin backup and
restore round-trip.

The plugin backup does not force the WAL segment that holds the backup-stop
record to be archived, so on an otherwise idle cluster a standalone restore
fails with "WAL ends before consistent recovery point". Write data into a
tablespace before the backup, switch and archive the closing WAL afterwards,
and verify the tablespace data is present in the restored cluster.

Added next to the in-core tablespaces test, whose cluster is shared with the
owner/temporary-tablespace and volume-snapshot sub-tests, so the in-core
variant stays until the in-core Barman Cloud support is removed. Runs on kind
and k3d.

Signed-off-by: Armando Ruocco <[email protected]>
Deploy the current operator, install the Barman Cloud plugin, create a
cluster archiving through it, and upgrade the operator in place to the
prime build. After the upgrade, verify the plugin is still loaded, that
a switched WAL still reaches the object store, and that a backup taken
through the plugin completes.

The backup is taken only after the online instance manager rollout has
finished: a backup started on an instance whose manager is replaced a
moment later dies with it, and the Backup resource never leaves the
"started" phase. assertOnlineManagerRollout now takes the cluster name
and the expected number of upgrade events so both the in-core spec and
this one can use it, and lists the events in the cluster's namespace
only, so a same-named cluster elsewhere cannot distort the count.

The spec owns the operator lifecycle, so its cleanup removes the plugin
Deployment and Service while the operator is still running, then deletes
cnpg-system: the operator puts a cnpg.io/cleanupPlugin finalizer on the
plugin Service, and deleting the namespace wholesale would wedge it on
that finalizer.

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

Add plugin-barman-cloud counterparts of the in-core object-store backup
scenarios that go beyond a plain backup/restore round-trip, sharing one
plugin-archived cluster: a ScheduledBackup with the immediate option, a backup
with a prefer-standby target that is verified to run on a replica, and a
point-in-time recovery into a new cluster bootstrapped through the plugin from
an external cluster definition.

The ScheduledBackup fires on February 29th, the rarest schedule the controller
accepts, so in practice only the immediate option triggers a backup. It cannot
be an impossible date (the controller refuses schedules with no next
occurrence, including their immediate backup), and restricting day-of-week
instead would backfire, since cron ORs day-of-month with day-of-week when both
are set.

backups.Execute skipped the target verification whenever the cluster had no
in-core backup section, which is always the case for plugin-backed clusters.
Resolve the target the way the operator does, with the backup's own target
winning over the cluster default, so the prefer-standby backup is verified by
Execute itself rather than a local assertion.

Signed-off-by: Armando Ruocco <[email protected]>
Every plugin spec repeated the same three steps to prepare a namespace for
plugin-barman-cloud archiving (MinIO CA secret, credentials secret,
ObjectStore) and two of them also duplicated the check that the plugin is
reported as loaded in the cluster status. Extract the setup into
setupPluginObjectStore next to the ObjectStore builder, and the check into a
shared AssertPluginLoaded.

The replica and tablespaces specs also built their Backup programmatically and
polled only for the completed phase, while the other plugin specs go through
backups.Execute, which additionally verifies the begin/end LSN and WAL fields
and the backup target. Move the two specs to fixtures and Execute so all
plugin backups get the same assertions.

Signed-off-by: Armando Ruocco <[email protected]>
The specs were labelled "plugin", which already selects the kubectl-cnpg
plugin tests; filtering on it mixes the two groups, and the certificate
tests in that group restart the operator, which fails any spec running
alongside them. Use a dedicated plugin-barman-cloud label instead.

Signed-off-by: Armando Ruocco <[email protected]>
Route the plugin-barman-cloud installation through
`hack/setup-cluster.sh plugin-barman-cloud` so there is a single
entrypoint for all callers (run-e2e.sh, upgrade_test.go).

- Add `plugin-barman-cloud` command to setup-cluster.sh and manage.sh
- Move BARMAN_PLUGIN_VERSION to 10-config.sh where all other
  image/version constants live
- Make CERT_MANAGER_VERSION a local variable so ensure_cert_manager()
  can be called without sourcing 10-config.sh
- Fix namespace deletion wedge: delete plugin services (and their
  cnpg.io/cleanupPlugin finalizer) before tearing down cnpg-system
- Broaden renovate fileMatch to cover all scripts under
  hack/testing-tools/common/ (CSI versions were previously unmanaged)

Signed-off-by: Niccolò Fei <[email protected]>
When running hack/setup_cluster.sh in GH actions we should
pass the GITHUB_TOKEN available to each curl call made by
the script.

Signed-off-by: Niccolò Fei <[email protected]>
The plugin-barman-cloud specs were written against the MinIO test harness, which main has since replaced with RustFS under provider-neutral names. Point them at the renamed objectstore package, the objectStoreEnv shared environment and the AssertArchiveWalOnObjectStore helper.

Create the credentials secret with the object store access keys instead of the former minio/minio123 pair, so the plugin authenticates against RustFS rather than failing at backup time. Rename the plugin fixtures and their cluster names to drop the minio suffix.

Signed-off-by: Armando Ruocco <[email protected]>
The customManager regex in .github/renovate.json5 requires the
"# renovate:" comment to be immediately followed by a bare
"..._VERSION=" assignment; a preceding "local" keyword breaks the
match, so Renovate was silently never going to bump cert-manager's
pinned version. Split the local declaration from the renovate-tracked
assignment, keeping it function-local so ensure_cert_manager still
works without sourcing 10-config.sh.

Signed-off-by: Marco Nenciarini <[email protected]>
…space

The main e2e run reset cnpg-system with a bare "kubectl delete
namespace", unbounded and unaware of the cnpg.io/cleanupPlugin
finalizer a leftover plugin-barman-cloud Service can carry from the
preceding upgrade-test phase. If that Service's finalizer is ever left
uncleared, the delete blocks indefinitely instead of failing fast.
reset_operator_namespace already clears plugin Services before
deleting the namespace and bounds every wait with a timeout, so route
through it instead.

Signed-off-by: Marco Nenciarini <[email protected]>
…namespace

Deleting the cnpg.io/pluginName Service ran after "helm uninstall",
which already tears down a helm-deployed operator. With no reconciler
left to clear the cnpg.io/cleanupPlugin finalizer, the delete timed
out silently and the following namespace wait failed, aborting the
script. Move the plugin-service delete first, while the operator (helm
or manifest deployed) is still running.

Also drops the "if get ns cnpg-system" guard around the namespace
delete and wait: both are no-ops on a missing namespace already
(--ignore-not-found, and "kubectl wait --for=delete" succeeds
immediately when the resource doesn't exist), so the guard added
nothing.

Signed-off-by: Marco Nenciarini <[email protected]>
getBackupTargetPod treats an empty target the same as prefer-standby,
but Execute's switch grouped it with primary instead. Currently
unreachable (the defaulting webhook never leaves a persisted cluster's
backup target empty, and Execute's own outer guard skips the switch
entirely when nothing is set), but a latent trap if this helper is
ever called against an unpersisted Cluster object. Align the switch
with the operator's.

Signed-off-by: Marco Nenciarini <[email protected]>
The smoke test and the tablespaces test each carried their own copy
of the same explanation for why a plugin backup needs an extra WAL
switch before a standalone restore. Extract it into one helper next
to the other shared plugin-test setup in this file, so the rationale
lives in one place instead of two near-duplicate comments.

Signed-off-by: Marco Nenciarini <[email protected]>
ensure_cert_manager skipped installing whenever the cert-manager
namespace existed, regardless of whether the manifest apply that
creates it had actually completed. A namespace left over from an
interrupted prior run would make it skip straight to waiting on
Deployments that were never created. Check for the Deployment itself
so a partial install re-applies instead of requiring manual cleanup.

Signed-off-by: Marco Nenciarini <[email protected]>
_github_auth_header's return value was interpolated inline via
-H "\$(_github_auth_header)" at each curl call site. Since this file
is sourced into scripts that turn on "set -x" under DEBUG=true, the
token would appear in the traced command line. Fold it into a
_curl_github wrapper that suppresses tracing only around the curl
call itself, restoring it via a RETURN trap, and use it at all four
call sites instead of duplicating the -H flag.

Signed-off-by: Marco Nenciarini <[email protected]>
The segment holding a plugin backup's stop record can stay unarchived
until archive_timeout closes it on its own; this test's restore
happens well within that window, so it needs the explicit switch.
Written to stand on its own rather than by contrast with the in-core
tests, since those are expected to go away once in-core Barman Cloud
support is dropped.

Signed-off-by: Marco Nenciarini <[email protected]>
Signed-off-by: Bramhanand Lingala <[email protected]>
… on image resolving

Here is the title and description for the issue:

### Description
When upgrading the CloudNativePG operator from `v1.29.1` to `v1.30.0`, `Pooler` resources fail to deploy, and the operator logs show:
```
"Skipping deployment reconciliation: pgbouncer image is not resolved"
```

#### Cause
In `v1.30.0`, a new `pooler.Status.Image` field was introduced to store the resolved PgBouncer image name. However, if the Custom Resource Definitions (CRDs) are not updated in the Kubernetes cluster alongside the operator binary, the new status field schema is not registered.

Consequently, the API server strips `status.image` and `status.phase` when the operator tries to save them. On the next reconciliation loop, `pooler.Status.Image` is read as empty, causing the reconciler to skip deployment reconciliation and leave PgBouncer pods uncreated.
When a replica encounters a fatal WAL replay error (e.g. 'record with
incorrect prev-link' or 'contrecord is requested by'), PostgreSQL keeps
running and accepts connections but WAL replay is permanently stuck at the
same LSN. The instance manager had no mechanism to detect this situation,
leaving the pod as Ready and eligible for traffic and failover promotion.

This commit fixes the issue by:

1. Adding a new logpipe.IsWALReplayErrorLine() helper that detects the
   known fatal WAL replay error patterns in a log line.

2. Adding a walReplayErrorDetected atomic bool to the Instance struct,
   toggled via SetWALReplayErrorDetected() / ResetWALReplayErrorDetected()
   / HasWALReplayErrorDetected().

3. Wiring a line observer into the existing raw log pipe (via the new
   NewRawLineLogPipeWithObserver constructor) so that every PostgreSQL log
   line is scanned for the error patterns without opening the FIFO a second
   time. The flag is reset on each fresh PostgreSQL startup.

4. Failing the readiness (and startup) probe in checker.go as soon as the
   flag is set, so Kubernetes marks the pod NotReady and stops routing
   traffic to it.

5. Returning an error from fillStatusFromReplica() when the flag is set,
   so the /pg/status endpoint reports a non-nil error. The operator uses
   this to populate PostgresqlStatus.Error, which excludes the replica from
   failover candidate selection via the existing PostgresqlStatusList.Less()
   sort order (errored items sort to the bottom).

Fixes: cloudnative-pg#11134
Fixes cloudnative-pg#11114.

During an unsupervised primary update switchover, a race condition occurred where the new target primary was selected *before* the existing primary was fully shut down. Because the old primary could still accept writes during the shutdown process, those writes could be replicated to other synchronous replicas (e.g., under quorum-based synchronous replication method: any) but not the pre-selected new primary. Once the switchover was completed, a less up-to-date replica would be promoted, causing the more advanced replicas to crash-loop because they were ahead of the new primary's timeline.

To resolve this, the selection of the new primary is now delayed until *after* the fast shutdown of the old primary completes:
1. Introduced a new apiv1.PendingSwitchoverMarker in cluster_types.go.
2. In updatePrimaryPod (cluster_upgrade.go), we now verify the best candidate's WAL replay lag but assign TargetPrimary to the PendingSwitchoverMarker instead of the specific candidate's name.
3. The instance controller sees that the TargetPrimary is not the current primary and initiates the fast shutdown.
4. replicas.go intercepts the PendingSwitchoverMarker, waits for all WAL receivers to gracefully terminate (ensuring no more WALs are being streamed), and safely promotes the most advanced replica as the new primary via PhaseSwitchover.
@bramhanandlingala
bramhanandlingala requested a review from a team July 14, 2026 11:08
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 14, 2026
@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 14, 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 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]: Potential race condition in primary update switchover

5 participants