From 5128a396c400801a317fa5043d62d559850f0548 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas.vondra@postgresql.org>
Date: Fri, 11 Mar 2022 02:23:25 +0100
Subject: [PATCH 2/3] 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 | 26 +++++++++++++++++----
 1 file changed, 21 insertions(+), 5 deletions(-)

diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c
index 104432fb3a6..abfef4e447c 100644
--- a/src/backend/replication/pgoutput/pgoutput.c
+++ b/src/backend/replication/pgoutput/pgoutput.c
@@ -1890,8 +1890,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
@@ -1902,9 +1900,27 @@ 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 we found an ancestor higher up in the tree, discard
+				 * the list of publications through which we replicate it,
+				 * and use the new ancestor.
+				 */
+				if (publish_ancestor_level < ancestor_level)
+				{
+					publish_as_relid = pub_relid;
+					publish_ancestor_level = ancestor_level;
+
+					/* reset the publication list for this relation */
+					rel_publications = NIL;
+				}
+				else
+				{
+					/* Same ancestor leve, has to be the same OID. */
+					Assert(publish_as_relid == pub_relid);
+				}
+
+				/* Track this publications. */
+				rel_publications = lappend(rel_publications, pub);
 			}
 		}
 
-- 
2.34.1

