From 011ec0d4f7c690fdc2ff4f396cac435bb8d4c597 Mon Sep 17 00:00:00 2001
From: Huseyin Demir <huseyin.d3r@gmail.com>
Date: Fri, 30 Oct 2026 08:03:39 +0100
Subject: [PATCH] Log changes discarded for relations not in the subscription

When an apply worker receives a change for a relation that is not in
SUBREL_STATE_READY, should_apply_changes_for_rel() returns false and the
change is discarded with no log message, conflict or statistics counter.
That is correct while a tablesync worker is still copying the table, but
it is indistinguishable from a relation that has no pg_subscription_rel
row at all, where the discard is permanent and both the replication
origin and the publisher slot advance past the discarded rows.

Report the discard at LOG when the relation is not part of the
subscription, and at DEBUG2 for a relation that is merely not
synchronized yet.  The gate is reached once per change, so remember the
last sync state reported in the relation map entry and report a relation
once per sync state, each time that entry is built.

Author: Huseyin Demir <huseyin.d3r@gmail.com>
---
 src/backend/replication/logical/relation.c  |  2 +
 src/backend/replication/logical/worker.c    | 60 ++++++++++++++--
 src/include/replication/logicalrelation.h   | 10 +++
 src/test/subscription/t/015_stream.pl       | 39 ++++++++++
 src/test/subscription/t/024_add_drop_pub.pl | 80 +++++++++++++++++++++
 5 files changed, 187 insertions(+), 4 deletions(-)

diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index 00e3dabdbc8..f8e065d97a6 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -182,6 +182,7 @@ logicalrep_relmap_update(LogicalRepRelation *remoterel)
 		logicalrep_relmap_free_entry(entry);
 
 	memset(entry, 0, sizeof(LogicalRepRelMapEntry));
+	entry->last_unapplied_state = SUBREL_STATE_INIT_LAST_UNAPPLIED;
 
 	/* Make cached copy of the data */
 	oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
@@ -681,6 +682,7 @@ logicalrep_partition_open(LogicalRepRelMapEntry *root,
 	{
 		memset(part_entry, 0, sizeof(LogicalRepPartMapEntry));
 		part_entry->partoid = partOid;
+		entry->last_unapplied_state = SUBREL_STATE_INIT_LAST_UNAPPLIED;
 	}
 
 	/* Release the no-longer-useful attrmap, if any. */
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index 95044620e68..b98a8fd4a14 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -670,6 +670,50 @@ ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid,
 	}
 }
 
+/*
+ * Report that changes for a relation are being skipped.
+ *
+ * Logs at most once per sync state of the relation.  Called from
+ * should_apply_changes_for_rel() each time it decides not to apply a change.
+ */
+static void
+report_unapplied_change(LogicalRepRelMapEntry *rel)
+{
+	/*
+	 * This is reached once per change, so remember the last state reported in
+	 * the relation map entry and stay quiet until the state changes.
+	 */
+	if (rel->state == rel->last_unapplied_state)
+		return;
+
+	/*
+	 * A relation with no pg_subscription_rel row is not being synchronized at
+	 * all.  Its changes are discarded for as long as that holds, yet are
+	 * still acknowledged to the publisher as applied, so log at LOG;
+	 * otherwise nothing shows that they were dropped.
+	 */
+	if (rel->state == SUBREL_STATE_UNKNOWN)
+		ereport(LOG,
+				errmsg("skipping changes for relation \"%s.%s\"",
+					   rel->remoterel.nspname, rel->remoterel.relname),
+				errdetail("The published relation is not included in subscription \"%s\".",
+						  MySubscription->name),
+				errhint("If this relation should be replicated, use ALTER SUBSCRIPTION ... REFRESH PUBLICATION."));
+	else
+	{
+		/*
+		 * The relation is still being synchronized by a tablesync worker, so
+		 * skipping its changes is transient and expected.
+		 */
+		ereport(DEBUG2,
+				errmsg_internal("skipping changes for relation \"%s.%s\" in subscription \"%s\": synchronization state is \"%c\"",
+								rel->remoterel.nspname, rel->remoterel.relname,
+								MySubscription->name, rel->state));
+	}
+
+	rel->last_unapplied_state = rel->state;
+}
+
 /*
  * Should this worker apply changes for given relation.
  *
@@ -713,12 +757,20 @@ should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
 								MySubscription->name),
 						 errdetail("Cannot handle streamed replication transactions using parallel apply workers until all tables have been synchronized.")));
 
-			return rel->state == SUBREL_STATE_READY;
+			if (rel->state == SUBREL_STATE_READY)
+				return true;
+
+			report_unapplied_change(rel);
+			return false;
 
 		case WORKERTYPE_APPLY:
-			return (rel->state == SUBREL_STATE_READY ||
-					(rel->state == SUBREL_STATE_SYNCDONE &&
-					 rel->statelsn <= remote_ctx.finish_lsn));
+			if (rel->state == SUBREL_STATE_READY ||
+				(rel->state == SUBREL_STATE_SYNCDONE &&
+				 rel->statelsn <= remote_ctx.finish_lsn))
+				return true;
+
+			report_unapplied_change(rel);
+			return false;
 
 		case WORKERTYPE_SEQUENCESYNC:
 			/* Should never happen. */
diff --git a/src/include/replication/logicalrelation.h b/src/include/replication/logicalrelation.h
index 4063118d2b9..807764cd018 100644
--- a/src/include/replication/logicalrelation.h
+++ b/src/include/replication/logicalrelation.h
@@ -16,6 +16,9 @@
 #include "catalog/index.h"
 #include "replication/logicalproto.h"
 
+/* Value of last_unapplied_state before anything has been reported */
+#define SUBREL_STATE_INIT_LAST_UNAPPLIED	'?'
+
 typedef struct LogicalRepRelMapEntry
 {
 	LogicalRepRelation remoterel;	/* key is remoterel.remoteid */
@@ -40,6 +43,13 @@ typedef struct LogicalRepRelMapEntry
 
 	/* Sync state. */
 	char		state;
+
+	/*
+	 * Sync state for which report_unapplied_change() last reported, or
+	 * SUBREL_STATE_INIT_LAST_UNAPPLIED if it has not reported yet.  This must
+	 * be set whenever the entry is zeroed, as zero is SUBREL_STATE_UNKNOWN.
+	 */
+	char		last_unapplied_state;
 	XLogRecPtr	statelsn;
 } LogicalRepRelMapEntry;
 
diff --git a/src/test/subscription/t/015_stream.pl b/src/test/subscription/t/015_stream.pl
index ac96bc3f009..dc5d68c953c 100644
--- a/src/test/subscription/t/015_stream.pl
+++ b/src/test/subscription/t/015_stream.pl
@@ -201,6 +201,45 @@ $node_subscriber->safe_psql('postgres', q{SELECT 1});
 
 test_streaming($node_publisher, $node_subscriber, $appname, 1);
 
+# Verify that a parallel apply worker reports changes it does not apply.
+#
+# A table that is published but never refreshed on the subscriber has no
+# pg_subscription_rel row at all.  GetSubscriptionRelations() only returns rows
+# that exist, so such a table is invisible to AllTablesyncsReady(),
+# pa_can_start() still hands the streamed transaction to a parallel apply
+# worker, and that worker discards every change for the table.
+$node_publisher->safe_psql('postgres', "CREATE TABLE test_tab_3 (a int)");
+$node_subscriber->safe_psql('postgres', "CREATE TABLE test_tab_3 (a int)");
+$node_publisher->safe_psql('postgres',
+	"ALTER PUBLICATION tap_pub ADD TABLE test_tab_3");
+
+my $pa_offset = -s $node_subscriber->logfile;
+
+# Large enough to be streamed, given logical_decoding_work_mem = 64kB.
+$node_publisher->safe_psql('postgres',
+	"INSERT INTO test_tab_3 SELECT i FROM generate_series(1, 5000) s(i)");
+
+# The bgw_type in log_line_prefix's %b distinguishes the parallel apply worker
+# ("logical replication parallel worker") from the leader ("logical replication
+# apply worker"), so this pins the report to the parallel path specifically.
+$node_subscriber->wait_for_log(
+	qr/logical replication parallel worker\[\d+\] LOG: ( [A-Z0-9]+:)? skipping changes for relation "public\.test_tab_3"/,
+	$pa_offset);
+
+ok( $node_subscriber->log_contains(
+		qr/DETAIL: ( [A-Z0-9]+:)? The published relation is not included in subscription "tap_sub"\./,
+		$pa_offset),
+	'parallel apply worker names the relation it is not applying changes for'
+);
+
+$node_publisher->wait_for_catchup($appname);
+
+$result =
+  $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM test_tab_3");
+is($result, qq(0),
+	'parallel apply worker discards changes for a relation not in the subscription'
+);
+
 # Test that the deadlock is detected among the leader and parallel apply
 # workers.
 
diff --git a/src/test/subscription/t/024_add_drop_pub.pl b/src/test/subscription/t/024_add_drop_pub.pl
index 63adb1b464c..61c5c9ffb2c 100644
--- a/src/test/subscription/t/024_add_drop_pub.pl
+++ b/src/test/subscription/t/024_add_drop_pub.pl
@@ -135,6 +135,86 @@ is( $result, qq(1
 	'check that the incremental data is replicated after the publication is created'
 );
 
+# Verify that the apply worker reports changes it does not apply because the
+# relation is not part of the subscription.  Such changes are discarded and
+# still acknowledged to the publisher as applied, so the report is the only
+# indication that they were received at all.
+#
+# Each relation is reported once per sync state, however many changes arrive.
+$node_publisher->safe_psql('postgres', "CREATE TABLE tab_4 (a int)");
+$node_subscriber->safe_psql('postgres', "CREATE TABLE tab_4 (a int)");
+$node_publisher->safe_psql('postgres', "CREATE TABLE tab_5 (a int)");
+$node_subscriber->safe_psql('postgres', "CREATE TABLE tab_5 (a int)");
+
+# Add the tables to the publication, but do not refresh the subscription, so
+# the subscriber has no pg_subscription_rel entry for them.
+$node_publisher->safe_psql('postgres',
+	"ALTER PUBLICATION tap_pub_3 ADD TABLE tab_4, tab_5");
+
+$offset = -s $node_subscriber->logfile;
+
+$node_publisher->safe_psql('postgres',
+	"INSERT INTO tab_4 SELECT generate_series(1, 10)");
+$node_publisher->safe_psql('postgres',
+	"INSERT INTO tab_5 SELECT generate_series(1, 10)");
+
+foreach my $tab ('tab_4', 'tab_5')
+{
+	$node_subscriber->wait_for_log(
+		qr/LOG: ( [A-Z0-9]+:)? skipping changes for relation "public\.$tab"/,
+		$offset);
+}
+
+ok( $node_subscriber->log_contains(
+		qr/DETAIL: ( [A-Z0-9]+:)? The published relation is not included in subscription "tap_sub"\./,
+		$offset),
+	'relation not in the subscription is reported with the relation name');
+
+$result =
+  $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM tab_4");
+is($result, qq(0),
+	'changes for a relation not in the subscription are discarded');
+
+# Send more changes and confirm each relation is reported once, rather than
+# once per change.
+$node_publisher->safe_psql('postgres',
+	"INSERT INTO tab_4 SELECT generate_series(11, 100)");
+$node_publisher->safe_psql('postgres',
+	"INSERT INTO tab_5 SELECT generate_series(11, 100)");
+$node_publisher->wait_for_catchup('tap_sub');
+
+my $log =
+  PostgreSQL::Test::Utils::slurp_file($node_subscriber->logfile, $offset);
+foreach my $tab ('tab_4', 'tab_5')
+{
+	my $count = () = $log =~ /skipping changes for relation "public\.$tab"/g;
+	is($count, 1, "$tab is reported once rather than once per change");
+}
+
+# A restarted apply worker starts with an empty relation map, so a relation
+# that is still missing is reported again.
+$node_subscriber->safe_psql('postgres', "ALTER SUBSCRIPTION tap_sub DISABLE");
+$node_subscriber->safe_psql('postgres', "ALTER SUBSCRIPTION tap_sub ENABLE");
+$offset = -s $node_subscriber->logfile;
+$node_publisher->safe_psql('postgres', "INSERT INTO tab_4 VALUES (101)");
+$node_subscriber->wait_for_log(
+	qr/LOG: ( [A-Z0-9]+:)? skipping changes for relation "public\.tab_4"/,
+	$offset);
+
+$node_subscriber->safe_psql('postgres',
+	"ALTER SUBSCRIPTION tap_sub REFRESH PUBLICATION");
+$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub');
+
+$node_publisher->safe_psql('postgres', "INSERT INTO tab_4 VALUES (102)");
+$node_publisher->wait_for_catchup('tap_sub');
+
+# Once the relation is part of the subscription its changes are applied, and
+# the initial copy brings across the rows that were discarded earlier.
+$result = $node_subscriber->safe_psql('postgres',
+	"SELECT count(*), max(a) FROM tab_4");
+is($result, qq(102|102),
+	'changes are applied once the relation is part of the subscription');
+
 # shutdown
 $node_subscriber->stop('fast');
 $node_publisher->stop('fast');
-- 
2.54.0 (Apple Git-157)

