From 3dccd97f4db1468b37cd4d486d0253d46297b0d1 Mon Sep 17 00:00:00 2001
From: Amit Kapila <akapila@postgresql.org>
Date: Thu, 3 Dec 2020 17:21:47 +0530
Subject: [PATCH v1] Remove incorrect assertion in reorderbuffer.c.

We start recording changes in ReorderBufferTXN even before we reach
SNAPBUILD_CONSISTENT state so that if the commit is encountered after
reaching that we should be able to send the changes of the entire transaction.
Now, while recording changes if the reorder buffer memory has exceeded
logical_decoding_work_mem then we can start streaming if it is allowed and
we haven't yet streamed that data. However, we must not allow streaming to
start unless the snapshot has reached SNAPBUILD_CONSISTENT state.

In passing, improve the comments atop ReorderBufferResetTXN to mention the
case when we need to continue streaming after getting an error.
---
 src/backend/replication/logical/reorderbuffer.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 301baff244..15dc51a94d 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -1891,6 +1891,8 @@ ReorderBufferSaveTXNSnapshot(ReorderBuffer *rb, ReorderBufferTXN *txn,
  * Helper function for ReorderBufferProcessTXN to handle the concurrent
  * abort of the streaming transaction.  This resets the TXN such that it
  * can be used to stream the remaining data of transaction being processed.
+ * This can happen when the subtransaction is aborted and we still want to
+ * continue processing the main or other subtransactions data.
  */
 static void
 ReorderBufferResetTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
@@ -3461,6 +3463,10 @@ ReorderBufferCanStartStreaming(ReorderBuffer *rb)
 	LogicalDecodingContext *ctx = rb->private_data;
 	SnapBuild  *builder = ctx->snapshot_builder;
 
+	/* We can't start streaming unless a consistent state is reached. */
+	if (SnapBuildCurrentState(builder) < SNAPBUILD_CONSISTENT)
+		return false;
+
 	/*
 	 * We can't start streaming immediately even if the streaming is enabled
 	 * because we previously decoded this transaction and now just are
@@ -3468,11 +3474,7 @@ ReorderBufferCanStartStreaming(ReorderBuffer *rb)
 	 */
 	if (ReorderBufferCanStream(rb) &&
 		!SnapBuildXactNeedsSkip(builder, ctx->reader->EndRecPtr))
-	{
-		/* We must have a consistent snapshot by this time */
-		Assert(SnapBuildCurrentState(builder) == SNAPBUILD_CONSISTENT);
 		return true;
-	}
 
 	return false;
 }
-- 
2.28.0.windows.1

