From 5bec3fb3533cd25e5d89f3355b8f1598e6967e9b Mon Sep 17 00:00:00 2001
From: Masahiko Sawada <sawada.mshk@gmail.com>
Date: Thu, 24 Nov 2022 16:58:44 +0900
Subject: [PATCH] Reset InitialRunningXacts array when freeing SnapBuild.

After finishing the decoding, it frees the decoding context but we
forgot to reset NInitialRunningXacts and InitialRunningXacts
array. So, the next time when starting decoding in the same session
where we don't restore any serialized snapshot, we ended up using the
unreset array.

An oversight in 272248a0c1b18a82c4266e0dc3b526d4d2637de3, so backpatch
to 11.

Reported-by: Maxim Orlov
Author: Masahiko Sawada
Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/CACG=ezZoz_KG+Ryh9MrU_g5e0HiVoHocEvqFF=NRrhrwKmEQJQ@mail.gmail.com
Backpatch-through: v11
---
 src/backend/replication/logical/snapbuild.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index cdf4aa01e9..d2fe2d222e 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -343,6 +343,9 @@ AllocateSnapshotBuilder(ReorderBuffer *reorder,
 
 	MemoryContextSwitchTo(oldcontext);
 
+	/* Make sure the initial running transactions array is empty */
+	Assert(InitialRunningXacts == NULL && NInitialRunningXacts == 0);
+
 	return builder;
 }
 
@@ -363,6 +366,10 @@ FreeSnapshotBuilder(SnapBuild *builder)
 
 	/* other resources are deallocated via memory context reset */
 	MemoryContextDelete(context);
+
+	/* InitialRunningXacts is freed along with the context */
+	InitialRunningXacts = NULL;
+	NInitialRunningXacts = 0;
 }
 
 /*
-- 
2.31.1

