From 475e235e051f8745bd55720370ba452a121d6b95 Mon Sep 17 00:00:00 2001
From: Shlok Kyal <shlok.kyal.oss@gmail.com>
Date: Mon, 10 Mar 2025 10:53:35 +0530
Subject: [PATCH v7] Comment race condition in copy_replication_slot

After copied slot is created there can be a race condition with function
InvalidateObsoleteReplicationSlots, when the copied slot appear before
source slot in array ReplicationSlotCtl->replication_slots.

If just after slot creation, the source slot is invalidated due to
some operation. The execution of InvalidateObsoleteReplicationSlots will
wait for copy_replication_slot function to release the copied slot. Then the
source slot will be invalidated. So, the copying of source slot is successful
in this case.

The wal_status of copied slot is set to lost immediately and hence will
not have any harm.
---
 src/backend/replication/slotfuncs.c | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)

diff --git a/src/backend/replication/slotfuncs.c b/src/backend/replication/slotfuncs.c
index 16a35279037..2c710a9c180 100644
--- a/src/backend/replication/slotfuncs.c
+++ b/src/backend/replication/slotfuncs.c
@@ -756,7 +756,22 @@ copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
 		plugin = NameStr(*(PG_GETARG_NAME(3)));
 	}
 
-	/* Create new slot and acquire it */
+	/*
+	 * Create new slot and acquire it
+	 *
+	 * After slot is created there can be a race condition with function
+	 * InvalidateObsoleteReplicationSlots, when the copied slot appear before
+	 * source slot in array ReplicationSlotCtl->replication_slots.
+	 *
+	 * If just after slot creation, the source slot is invalidated due to
+	 * some operation. The execution of InvalidateObsoleteReplicationSlots will
+	 * wait for this function to release the copied slot. Then the source slot
+	 * will be invalidated. So, the copying of source slot is successful in this
+	 * case.
+	 *
+	 * The wal_status of copied slot is set to lost immediately and hence will
+	 * not have any harm.
+	 */
 	if (logical_slot)
 	{
 		/*
-- 
2.34.1

