Skip to content

fix(slots): cleanup orphaned failover logical slots after switchover - #9998

Open
jmealo wants to merge 11 commits into
cloudnative-pg:mainfrom
jmealo:dev/9969
Open

jmealo wants to merge 11 commits into
cloudnative-pg:mainfrom
jmealo:dev/9969

Conversation

@jmealo

@jmealo jmealo commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When using PostgreSQL 17's sync_replication_slots with CNPG's synchronizeLogicalDecoding feature, failover-enabled logical slots are synced from the primary to replicas with synced=true. However, after a switchover, the demoted primary retains its locally-created slots with synced=false, which prevents the sync worker from recreating them properly.

This PR adds automatic cleanup of orphaned failover slots on replicas when synchronizeLogicalDecoding is enabled:

  • Slots are dropped only when ALL criteria are met:

    • synced=false (locally created, not from sync worker)
    • failover=true (meant to be managed by sync_replication_slots)
    • active=false (no consumer connected)
  • External subscription slots (failover=false) are explicitly preserved

Changes

  1. Infrastructure layer (internal/management/controller/slots/infrastructure/):

    • Add LogicalReplicationSlot struct with Synced and Failover fields for PG17+
    • Add ListLogicalSlotsWithSyncStatus() to query logical slots with synced/failover columns
    • Add DeleteLogicalSlot() to drop logical slots by name
  2. Reconciler (internal/management/controller/slots/reconciler/):

    • Add cleanupOrphanedLogicalSlots() to identify and remove orphaned failover slots
    • Integrate cleanup into the replication slot reconciliation loop (runs on PG17+ replicas only)
  3. API helpers (api/v1/):

    • Add GetSynchronizeLogicalDecoding() helper function
  4. E2E test (tests/e2e/):

    • Add comprehensive test that creates a failover slot, performs switchover, and verifies cleanup

Test plan

  • Unit tests for ListLogicalSlotsWithSyncStatus()
  • Unit tests for DeleteLogicalSlot()
  • Unit tests for cleanupOrphanedLogicalSlots() covering:
    • Only drops orphan slots (synced=false AND failover=true AND active=false)
    • Does NOT drop external subscription slots (failover=false)
    • Does NOT drop synced slots (synced=true)
    • Does NOT run on primary
    • Does NOT run when synchronizeLogicalDecoding is disabled
    • Does NOT run on PG16 and earlier
  • E2E test validates slot cleanup after switchover
  • E2E test confirms failure without fix (main branch), success with fix (this branch)

Fixes: #9969

Assisted by: Claude Opus 4.5

@jmealo
jmealo requested a review from a team February 16, 2026 16:02
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Feb 16, 2026
@cnpg-bot cnpg-bot added backport-requested ◀️ This pull request should be backported to all supported releases release-1.25 release-1.28 labels Feb 16, 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

@dosubot dosubot Bot added bug 🐛 Something isn't working E2E tests E2E tests tickets for easy triage on release process labels Feb 16, 2026
@jmealo
jmealo force-pushed the dev/9969 branch 4 times, most recently from bf6b0b7 to 9202a88 Compare February 16, 2026 16:40
@gbartolini gbartolini added this to the 1.29.0 milestone Feb 17, 2026
@gbartolini

Copy link
Copy Markdown
Contributor

For maintainers' attention to evaluate inclusion in 1.29.0.

@zo-ataccama

Copy link
Copy Markdown

Hello, what about this one guys? It is quite annoying bug and it would be good if you get to that review as this is open very long time now.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 11, 2026
@jmealo

jmealo commented May 11, 2026

Copy link
Copy Markdown
Contributor Author

@mnencia Any changes needed here? If the comments are too verbose I can move them out of the source and into the PR.

@gbartolini gbartolini removed this from the 1.29.0 milestone May 29, 2026
@MathCharton

Copy link
Copy Markdown

✅ Fix validated on a test CNPG cluster — orphaned failover slot cleanup works across all failover scenarios

Environment

  • Operator: CNPG v1.29.1 (with this fix commit) · PostgreSQL: 17.10
  • Failover_slot: PG17 native sync_replication_slots + CNPG synchronizeLogicalDecoding (migrated off the pg_failover_slots extension)
  • CDC: Debezium — logical slot debezium (pgoutput, publication dbz_publication)
  • Cluster: 2 instances

Scope & limitations ⚠️

  • Run on an empty test database, no traffic — no live/production testing.
  • Validates slot state handling during failover (orphan cleanup + re-sync), not data-loss guarantees of the native mechanism under load.

TL;DR

The orphaned-slot bug is reproduced and fixed, and the fix holds across every scenario tested (planned switchovers, pod deletion, full standby rebuild, hard primary kill). In all cases the debezium slot returns to failover=t / synced=t on the standby, with no manual pg_drop_replication_slot.

The bug & the fix (FIRST switchover)

After the FIRST switchover, the demoted primary kept its local debezium slot (synced=false), blocking sync:

  1. ERROR 55000: exiting from slot synchronization because same name slot
    "debezium" already exists on the standby ← the bug
  2. cleanupOrphanedLogicalSlots: Dropping orphaned logical slot debezium ← THE FIX
  3. Debezium reconnects to new primary → CDC resumes on its own
  4. (catch-up window: "could not synchronize ... could lead to data loss" — LOG, expected)
  5. LOG: newly created replication slot "debezium" is sync-ready now ← success

✅ Before the fix this required a manual slot drop on the standby; now it's handled automatically.

Test matrix

# Scenario Action Result
1 Planned switchover x3 (TL 3 to 5) kubectl cnpg promote Orphan auto-dropped on First switchover; no 55000 recurrence on second and third switchover
2 Delete standby pod (PVC kept) delete pod <standby> Recreated, slot resynced
3 Delete standby pod + PVCs (from scratch) delete pvc … && delete pod Rebuilt via pg_basebackup, slot resynced, never invalidated
4 Unplanned failover (hard kill primary) delete pod <primary> --grace-period=0 --force Auto-promotion (TL 5 to 6), old node rejoined, slot sync-ready, CDC resumed

Unplanned failover - timeline (test 4)

T+0:00 hard kill of primary
T+1:30 detection window (transient connect errors, anti-split-brain) — expected
T+1:33 new primary auto-promoted (timeline 5→6)
T+1:42 CDC paused ~8s, then resumed (see note 2 below)
T+2:42 old node rejoined as standby → "newly created replication slot is sync-ready now"

Final state both sides: failover=t, synced=t, invalidation_reason empty. No 55000 error, no manual action.

2 behaviors worth knowing (not bugs)

  1. Deleting a PVC reprovisions the instance with a new ordinal (e.g. pg17-2 → pg17-3). Expected CNPG behavior.
  2. On an unplanned failover, CDC pauses briefly (~8s here) while synchronized_standby_slots still references the killed node's slot (WARNING 55000 … does not have active_pid). This is PG17's native data-loss-safety guard; it clears once the standby rejoins. If the killed node never returned, logical replication would stay paused until CNPG reconciles synchronized_standby_slots.

Verdict

Without fix (main) With fix (this branch)
Orphan slot on demoted primary ❌ Blocks sync (synced=false) ✅ Auto-dropped
Manual intervention ❌ Manual slot drop ✅ None
CDC after failover - ✅ Resumes on its own
Across switchovers / pod delete / PVC rebuild / hard kill - ✅ Consistently failover=t / synced=t
Raw log evidence (key lines)

Bug condition — orphaned slot blocks sync on demoted primary

{"record":{"error_severity":"ERROR","sql_state_code":"55000","message":"exiting from slot synchronization because same name slot \"debezium\" already exists on the standby","backend_type":"slotsync worker"}}

THE FIX — orphan auto-dropped

{"logger":"cleanupOrphanedLogicalSlots","msg":"Dropping orphaned logical slot","slotName":"debezium"}

Catch-up window (LOG, not ERROR — PG17 data-loss-safety guard)

{"record":{"error_severity":"LOG","message":"could not synchronize replication slot \"debezium\"","detail":"Synchronization could lead to data loss, because the remote slot needs WAL at LSN ... but the standby has ..."}}

Success — slot resynced on standby

{"record":{"error_severity":"LOG","message":"newly created replication slot \"debezium\" is sync-ready now","backend_type":"slotsync worker"}}

Unplanned failover — CDC pause while synchronized_standby_slots points at the killed node

{"record":{"error_severity":"WARNING","sql_state_code":"55000","message":"replication slot \"_cnpg_bar1928_test_pg17_1\" specified in parameter \"synchronized_standby_slots\" does not have active_pid","detail":"Logical replication is waiting on the standby ..."}}
</details>

@jmealo

jmealo commented Jun 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for testing!

@thomasboussekey

Copy link
Copy Markdown
Contributor

Hello @ardentperf,

@MathCharton, my colleague, has tested and validated this PR, did you manage to test it on your side?

@LAV73

LAV73 commented Nov 10, 2026

Copy link
Copy Markdown

Hi everyone! 👋

Our team is also hit by this bug, so we're really looking forward to this fix. Big thanks to @jmealo and @armru for driving this forward and for the thorough testing! It's awesome to see the progress here.

Could you please share if there is an estimated release version or milestone where we can expect this to land?

Thank you for all your hard work! 🚀

@armru

armru commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

@jmealo I pushed a few commits on top. The cleanup now runs in the slot
replicator instead of the instance reconciliation, so a slot held by a client
no longer triggers a requeue every second, and the api/v1 and configuration
changes are gone. Tested on KIND with PostgreSQL 17 and 18: the former primary
gets its slots back, synced, 5 to 10 seconds after it becomes ready.

The slots are lost only when both of these happen:

  1. the demoted instance is the one that created them, and this is its first
    demotion since then;
  2. that instance is promoted again within those 5 to 10 seconds, by a
    switchover back or because the new primary fails.

After the first resync a slot stays synced and is never dropped again. The
original version had the same limit, and PostgreSQL leaves no alternative to
dropping them.

I'd like to hear from the other maintainers whether this side effect is
acceptable.

@armru

armru commented Nov 10, 2026

Copy link
Copy Markdown
Member

/test

@github-actions

Copy link
Copy Markdown
Contributor

@jmealo

jmealo commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

@armru thanks for that. We're at a place in CNPG where the remaining work is difficult to reason about in isolation; so we must be careful. Interested in what the other mantainers think 🤔 .

If I can reproduce this quickly; I'm okay layering it on top of my #11868 deployment and testing it on AKS.

I'm in the middle of a migration and may not respond right away; but, I'll do my best.

@armru

armru commented Nov 12, 2026

Copy link
Copy Markdown
Member

A correction to my previous comment: the window is not 5 to 10 seconds.

The former primary gets its slots back within seconds, but PostgreSQL keeps
them temporary until their client has consumed from the new primary, and a
promotion drops the temporary slots. With an active client that took 20
seconds on KIND; a slot whose client is not consuming stays temporary, and
promoting the former primary again loses it.

I also pushed four commits: the slots are now left in place when
sync_replication_slots is off and in a replica cluster, where nothing would
recreate them, and the documentation describes the window above.

I'd still like to hear from the other maintainers whether this is acceptable.

@armru

armru commented Nov 12, 2026

Copy link
Copy Markdown
Member

/test

@github-actions

Copy link
Copy Markdown
Contributor

@jmealo

jmealo commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

@armru I'll try to test your latest commits on AKS. Thanks for pushing through on this. 🙏

@MathCharton

Copy link
Copy Markdown

✅ Re-validated with latest commits (36f448d) on EKS — slot replicator cleanup & new guards work across all scenarios

Following @armru's commits moving the cleanup into the slot replicator and adding the sync_replication_slots = off, pg_is_in_recovery(), and replica-cluster guards, we rebuilt the operator from 36f448d and ran an extended test matrix on a real AWS EKS cluster.

Environment

  • Operator: CNPG build at 36f448d · PostgreSQL: 17.10 (2 instances, AWS EKS)
  • Failover slot config: PG17 native sync_replication_slots: on + CNPG synchronizeLogicalDecoding: true (replicationSlots.updateInterval: 10)
  • CDC: Live Debezium Server 2.21 (pgoutput, publication dbz_publication, logical slot debezium with failover=true)

1. Core failover & recovery matrix

# Scenario Action Result
0 Baseline before patching operator (1.30.1) Switchover ❌ Reproduces #9969: ERROR 55000: exiting from slot synchronization because same name slot "debezium" already exists on the standby every 10s
1 Planned switchover x3 (TL 2 → 5) kubectl cnpg promote ✅ 1st demotion of each node: orphan dropped within 191–420ms (Dropping orphaned failover slot), recreated as temporary=t, then promoted to persistent (temporary=f, sync-ready). Subsequent switchovers: synced stays true across promotions → 0 55000 errors, 0 drops, 0 temporary=true window
2 Delete standby pod (PVC kept) delete pod <standby> ✅ Pod recreated in 26s, slot stays failover=t, synced=t, temporary=f
3 Delete standby pod + PVCs (full rebuild) delete pvc … && delete pod ✅ Rebuilt via pg_basebackup, slot resynced and sync-ready (temporary=f) in 51s
4 Unplanned failover (hard kill primary) delete pod <primary> --grace-period=0 --force ✅ Auto-promoted after failoverDelay (90s, TL 5 → 6); CDC paused 14.1s on synchronized_standby_slots until old primary rejoined, then Debezium resumed automatically (0 connector restarts across the entire campaign)

2. Validation of the new commits & edge cases (7124343 → 36f448d)

# Test Commit(s) Observation
5 temporary=true window duration with a live Debezium client ff12db8, 2861768 On the first demotion of the node that originally created the slot, the slot stayed temporary=t for 91s–121s on an idle database (time for Debezium to reconnect + flush LSN/advance catalog_xmin + PostgreSQL slotsync worker 30s backoff cycle), then became persistent (temporary=f). On all subsequent switchovers, synced remained t and it never went through temporary=t again.
6 Idle failover=true slot with no active client 2861768, 36f448d Created test_orphan_on_hardkill (failover=true, no consumer) alongside debezium (active Debezium consumer). After failover, debezium transitioned temporary=t → f automatically once Debezium consumed from the new primary, whereas test_orphan_on_hardkill stayed temporary=t (could not synchronize replication slot) until manually advanced on the primary — confirming the documented limitation.
7 sync_replication_slots = off guard (pg_failover_slots compatibility) c65b11a With sync_replication_slots = off and synchronizeLogicalDecoding = true, a demoted primary holding test_sync_off_keep2 (failover=t, synced=f, active=f) kept the slot untouched across 9+ slot replicator cycles (>90s). As soon as sync_replication_slots was reloaded back to on, instance-manager dropped it on the next cycle (Dropping orphaned failover slot: test_sync_off_keep2).
8 External logical slot preservation (failover = false) 7124343 Created test_external_sub_slot (failover=false) alongside test_orphan_slot (failover=true) on the primary and triggered a switchover: test_orphan_slot (failover=t, synced=f) was dropped and resynced (synced=t), while test_external_sub_slot (failover=f, synced=f) was preserved untouched.
Raw log evidence

1st demotion — orphan slot dropped by slot replicator & resynced (pg17-2 and pg17-1)

2026-11-13T14:55:49.132889558Z  postgres          ERROR 55000: exiting from slot synchronization because same name slot "debezium" already exists on the standby
2026-11-13T14:55:49.323980472Z  instance-manager  Dropping orphaned failover slot: debezium
2026-11-13T14:55:59.360101277Z  postgres          LOG: could not synchronize replication slot "debezium" (detail: Synchronization could lead to data loss, because the remote slot needs WAL at LSN 9/ED055C08 and catalog xmin 450394, but the standby has LSN 9/EE000028 and catalog xmin 450421.)
2026-11-13T14:57:20.481603813Z  postgres          LOG: newly created replication slot "debezium" is sync-ready now

3rd switchover (both nodes already synced=t) — zero 55000 errors, zero drops

         node         | slot_name | slot_type | active | failover | synced | temporary | restart_lsn | confirmed_flush_lsn 
----------------------+-----------+-----------+--------+----------+--------+-----------+-------------+---------------------
 pg17-1 (new primary) | debezium  | logical   | t      | t        | t      | f         | 9/EE0339D8  | 9/EE0339D8
 pg17-2 (standby)     | debezium  | logical   | f      | t        | t      | f         | 9/EE0339D8  | 9/EE0339D8

Unplanned failover — 14.1s synchronized_standby_slots guard until standby rejoins, then automatic Debezium recovery

2026-11-13T15:05:17.984322920Z  postgres  LOG: parameter "synchronized_standby_slots" changed to "_cnpg_bar1928_test_pg17_1"
2026-11-13T15:05:28.252997443Z  postgres  WARNING 55000: replication slot "_cnpg_bar1928_test_pg17_1" specified in parameter "synchronized_standby_slots" does not have active_pid
...
2026-11-13T15:05:42.385503372Z  postgres  LOG: duration: 14132.794 ms  statement: SELECT pg_replication_slot_advance('debezium', '9/F104BB10')

sync_replication_slots = off guard (c65b11a) & failover = false preservation (7124343)

# With sync_replication_slots = off: slot is kept across 9+ replicator cycles (>90s)
# Once sync_replication_slots is reloaded to 'on':
2026-11-13T15:45:36.642817630Z  instance-manager  Dropping orphaned failover slot: test_sync_off_keep2

# External logical slot (failover=false) preserved while orphaned failover=true slot is dropped:
       slot_name        | slot_type | active | failover | synced | temporary 
------------------------+-----------+--------+----------+--------+-----------
 debezium               | logical   | f      | t        | t      | f
 test_external_sub_slot | logical   | f      | f        | f      | f

@leonardoce

Copy link
Copy Markdown
Contributor

I tested it manually on PG16 and PG17, it worked beautifully. I just fixed some little nits.

@leonardoce

Copy link
Copy Markdown
Contributor

/test

@github-actions

Copy link
Copy Markdown
Contributor

jmealo and others added 11 commits November 24, 2026 14:58
When using PostgreSQL 17's sync_replication_slots with CNPG's
synchronizeLogicalDecoding feature, failover-enabled logical slots
are synced from primary to replicas with synced=true. However, after
a switchover, the demoted primary retains its locally-created slots
with synced=false, which blocks the sync worker from recreating them.

This change adds automatic cleanup of orphaned failover slots on
replicas when synchronizeLogicalDecoding is enabled:

- Add ListLogicalSlotsWithSyncStatus() to query logical slots with
  synced/failover columns (PG17+ only)
- Add DeleteLogicalSlot() to drop logical slots by name
- Add cleanupOrphanedLogicalSlots() to identify and remove slots
  that are synced=false AND failover=true AND active=false
- Integrate cleanup into the replication slot reconciliation loop

Safety: Only drops slots that meet ALL criteria:
- synced=false (locally created, not from sync worker)
- failover=true (meant to be managed by sync_replication_slots)
- active=false (no consumer connected)

External subscription slots (failover=false) are explicitly preserved.

Fixes: cloudnative-pg#9969

Signed-off-by: Jeff Mealo <[email protected]>
Assisted-By: Claude Opus 4.5 <[email protected]>
Follow-up hardening for the cleanup added earlier in this PR:

- Gate the drop on pg_is_in_recovery() (new IsInRecovery) so it never runs
  on a node PostgreSQL still considers a primary.
- Treat an active or failed drop as transient (requeue), matching the
  physical-slot path, instead of a fatal reconcile error.
- Fix the e2e test to assert the real synced/failover columns and the
  post-cleanup re-sync.

Signed-off-by: Jeff Mealo <[email protected]>
Assisted-By: Claude Opus 4.8 <[email protected]>
The test used the e2e assert helpers that moved to tests/internal/asserts,
so the e2e package no longer compiled. Rewrite it with the current helpers
and trim it to what reproduces the issue: a failover slot created on the
primary of a two instance cluster, synchronized to the replica before a
switchover. The former primary must then synchronize the slot from the new
primary, which only happens once its own copy is dropped.

Signed-off-by: Armando Ruocco <[email protected]>
A standby can only hold a failover slot that is not synced if it created
it while it was a primary: PostgreSQL refuses to enable failover on a slot
during recovery, except in the slot sync worker, which marks its slots as
synced. The query listing the slots to drop can then select exactly those
slots, and check pg_is_in_recovery() in the same statement, replacing the
recovery check, the Go filtering and the dedicated slot type.

The drop reuses the existing Delete and follows dropReplicationSlots: an
active slot is retried after a second, and a failed drop no longer stops
the other slots and is returned to the reconciliation loop, which retries
it with a backoff, as happens for the physical slots.

The cleanup now runs where the standby path already ends, and reads the
SynchronizeLogicalDecoding field directly, as the HA slots are known to be
enabled there: the new API helper is no longer needed.

Signed-off-by: Armando Ruocco <[email protected]>
Explain why the operator drops, on the replicas, the failover slots that
are not marked as synced, and when a slot in use is dropped.

Signed-off-by: Armando Ruocco <[email protected]>
Dropping the orphaned failover slots from the instance reconciliation
added a new path to it: a requeue every second while a client used one
of them, which also skipped the steps that follow the slot
reconciliation.

The slot replicator already runs on every replica, on its own timer,
and already drops the physical slots a former primary leaves behind.
The cleanup now runs there: it skips the slots in use, and a later run
drops them once their client disconnects.

Signed-off-by: Armando Ruocco <[email protected]>
With pg_failover_slots on PostgreSQL 17 or later, sync_replication_slots is
off and no slot sync worker runs. The extension keeps using the failover
slots a former primary created, so nothing needs them dropped: dropping one
only made the extension create it again, ahead of the position its client
still needs.

The query listing the orphaned failover slots now returns none when
sync_replication_slots is off.

Signed-off-by: Armando Ruocco <[email protected]>
PostgreSQL keeps a recreated slot temporary until the slot on the primary
has advanced past the position reserved on the replica, and drops the
temporary slots on promotion. A slot without a client consuming from the new
primary stays temporary, and promoting the former primary again loses it.

Signed-off-by: Armando Ruocco <[email protected]>
PostgreSQL synchronizes the slots only from a primary. In a replica cluster
the instances follow the designated primary, which is a standby: after a
switchover of the designated primary, the former one lost its failover slots
and the slot sync worker could not recreate them, as it stopped with "cannot
synchronize replication slots from a standby server".

The slots are now dropped only when the instance this replica follows is
not in recovery.

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

The slot of the test has no client. PostgreSQL keeps its copy on the replica
temporary while the slot on the primary is behind the replica, which is the
case when a transaction runs on the primary before the replica creates the
copy: the test would then wait in vain, and a new cluster runs such
transactions about a minute after the primary starts.

The test now advances the slot on the primary while it waits.

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Leonardo Cecchi <[email protected]>
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 E2E tests E2E tests tickets for easy triage on release process ok to merge 👌 This PR can be merged 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]: Orphaned logical replication slots on demoted primary cause WAL accumulation after switchover