From f9eb1d52401ff454943c3862e2c3d81442a030f0 Mon Sep 17 00:00:00 2001
From: Amit Kapila <akapila@postgresql.org>
Date: Sat, 12 Mar 2022 09:23:53 +0530
Subject: [PATCH v1 2/2] fixup: row-filter publications

When initializing the row filter, consider only publications that
actually include the relation (publish_as_relid). The publications may
include different ancestors, in which case the function would get
confused and conclude there's no row filter.
---
 src/backend/replication/pgoutput/pgoutput.c | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)

diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c
index 28b13adcd8..bc9abcf0e6 100644
--- a/src/backend/replication/pgoutput/pgoutput.c
+++ b/src/backend/replication/pgoutput/pgoutput.c
@@ -1885,8 +1885,6 @@ get_rel_sync_entry(PGOutputData *data, Relation relation)
 				entry->pubactions.pubdelete |= pub->pubactions.pubdelete;
 				entry->pubactions.pubtruncate |= pub->pubactions.pubtruncate;
 
-				rel_publications = lappend(rel_publications, pub);
-
 				/*
 				 * We want to publish the changes as the top-most ancestor
 				 * across all publications. So we need to check if the
@@ -1897,9 +1895,21 @@ get_rel_sync_entry(PGOutputData *data, Relation relation)
 				if (publish_ancestor_level > ancestor_level)
 					continue;
 
-				/* The new value is an ancestor, so let's keep it. */
-				publish_as_relid = pub_relid;
-				publish_ancestor_level = ancestor_level;
+				/*
+				 * If the new value is an ancestor, discard the list of
+				 * publications through which we replicate it.
+				 */
+				if (publish_as_relid != pub_relid)
+				{
+					list_free(rel_publications);
+					rel_publications = NIL;
+
+					publish_as_relid = pub_relid;
+					publish_ancestor_level = ancestor_level;
+				}
+
+				/* Track the publications. */
+				rel_publications = lappend(rel_publications, pub);
 			}
 		}
 
-- 
2.28.0.windows.1

