Fix race between copying and dropping a replication slot

From: Zhijie Hou <houzhijie22(at)gmail(dot)com>
To: "pgsql-hackers(at)lists(dot)postgresql(dot)org" <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Cc: Masahiko Sawada <sawada(dot)mshk(at)gmail(dot)com>
Subject: Fix race between copying and dropping a replication slot
Date: 2026-11-26 14:39:40
Message-ID: 3abb64fe-d494-4960-83dc-30e48ac82729@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

(CCing Sawada-san for replication slot copying and dynamic logical
decoding.)

While looking into dynamic logical decoding toggling on PG 19+, I found
a race condition in copy_replication_slot() when the source slot is
concurrently dropped during the copy operation.

copy_replication_slot() copies the source slot in two phases: it first
reads the source slot's initial metadata, creates the destination slot
without holding the source slot, and then re-reads the source slot to
copy its latest LSN/xmin values and verify that it still exists.

However, the second-phase check does not verify the source slot's in_use
flag. Since dropping a slot only clears in_use without resetting its
persistent data, a concurrent drop of the source slot before the
destination slot reserves its resources can go undetected.

On PG 19+ with wal_level = replica, this is easy to hit because dropping
the last logical slot deactivates logical decoding, and
create_logical_replication_slot() then re-enables it for the destination
slot. Because the drop goes undetected, the copied slot is persisted
with LSNs preceding the deactivation record, causing subsequent decoding
to fail with "unexpected logical decoding status change 0".

Older branches are also affected, although there it requires a
checkpoint or VACUUM to remove WAL segments or catalog tuples referenced
by the stale restart_lsn and xmin values in that window, tripping
Assert(XLogGetLastRemovedSegno() < segno) or leaving a corrupted copied
slot.

Attached a patch to fix this by checking second_slot_contents.in_use and
ensuring MyReplicationSlot did not reuse src in the second phase. The
code fix applies back to PG 15.

--
Best Regards,
Zhijie Hou

Attachment Content-Type Size
v1-0001-Fix-race-between-copying-and-dropping-a-replicati.patch text/plain 9.0 KB

Browse pgsql-hackers by date

  From Date Subject
Next Message Jelte Fennema-Nio 2026-11-26 14:59:29 Re: postgres_fdw: Fix costing of remote sorts without remote estimates
Previous Message Heikki Linnakangas 2026-11-26 14:16:55 Re: Fix two race conditions in processing interrupts