From aa99d017b04af586d74fafc67656289f85633a87 Mon Sep 17 00:00:00 2001
From: alterego655 <824662526@qq.com>
Date: Fri, 29 May 2026 10:28:57 +0800
Subject: [PATCH v1] Use outer memory context across slot sync retries

Capture the outer memory context once before the retry loop in
SyncReplicationSlots() to better better matches the actual lifetime model:
sync_retry_ctx is the per-cycle child context, while slot_names must live
in the parent/outer context across resets. Rename the oldctx to outerctx
to express the parent/child relationship more clearly.
---
 src/backend/replication/logical/slotsync.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c
index 93f41be32af..e22155b7192 100644
--- a/src/backend/replication/logical/slotsync.c
+++ b/src/backend/replication/logical/slotsync.c
@@ -2014,17 +2014,20 @@ SyncReplicationSlots(WalReceiverConn *wrconn)
 		List	   *remote_slots = NIL;
 		List	   *slot_names = NIL;	/* List of slot names to track */
 		MemoryContext sync_retry_ctx;
+		MemoryContext outerctx;
 
 		check_and_set_sync_info(MyProcPid);
 
 		validate_remote_info(wrconn);
 
+		outerctx = CurrentMemoryContext;
+
 		/*
 		 * Setup and use a per-sync-cycle memory context, which is reset every
 		 * time we loop below. This avoids having to retail freeing the memory
 		 * used in each sync cycle.
 		 */
-		sync_retry_ctx = AllocSetContextCreate(CurrentMemoryContext,
+		sync_retry_ctx = AllocSetContextCreate(outerctx,
 											   "slot sync retry context",
 											   ALLOCSET_DEFAULT_SIZES);
 
@@ -2033,7 +2036,6 @@ SyncReplicationSlots(WalReceiverConn *wrconn)
 		{
 			bool		slot_persistence_pending = false;
 			bool		some_slot_updated = false;
-			MemoryContext oldctx;
 
 			/* Check for interrupts and config changes */
 			CHECK_FOR_INTERRUPTS();
@@ -2045,7 +2047,7 @@ SyncReplicationSlots(WalReceiverConn *wrconn)
 			Assert(IsTransactionState());
 
 			MemoryContextReset(sync_retry_ctx);
-			oldctx = MemoryContextSwitchTo(sync_retry_ctx);
+			MemoryContextSwitchTo(sync_retry_ctx);
 
 			/*
 			 * Fetch remote slot info for the given slot_names. If slot_names
@@ -2067,7 +2069,7 @@ SyncReplicationSlots(WalReceiverConn *wrconn)
 			 * slot_names must survive later sync_retry_ctx resets, so copy it
 			 * in the outer context.
 			 */
-			MemoryContextSwitchTo(oldctx);
+			MemoryContextSwitchTo(outerctx);
 
 			/*
 			 * If slot_persistence_pending is true, extract slot names for
-- 
2.51.0

