Re: Per-table resync for logical replication subscriptions
Re: Per-table resync for logical replication subscriptions
От:
Peter Smith <smithpb2250@gmail.com>
Дата:
On Wed, Jul 8, 2026 at 8:55 PM Cagri Biroglu wrote: > > here is the WIP patch for the disabled-subscription case. > It adds: > > ALTER SUBSCRIPTION name REFRESH TABLE table_name > [ WITH (copy_data = true, truncate = true) ] > ... > Open questions if this direction makes sense ,I would still like feedback on: the command spelling > (REFRESH TABLE vs RESYNC TABLE), and whether the enabled-subscription > case is worth doing as a follow-up (it needs the running apply worker to > notice and re-read the reset relation state). (My feedback only about the syntax question) As you said in the OP, this proposal is a bit like a table equivalent of "ALTER SUBSCRIPTION sub REFRESH SEQUENCES". IIRC we went through similar syntax debates when that command was being developed. Some alternatives were proposed [1] ALTER SUBSCRIPTION sub RESYNC PUBLICATION SEQUENCES; ALTER SUBSCRIPTION sub RESYNC SEQUENCES; And, then more [2] ALTER SUBSCRIPTION sub REPLICATE PUBLICATION SEQUENCES; ALTER SUBSCRIPTION sub RESYNC PPUBLICATION SEQUENCES; ALTER SUBSCRIPTION sub SYNC PUBLICATION SEQUENCES; ALTER SUBSCRIPTION sub MERGE PUBLICATION SEQUENCES; It went back and forth for a while... Finally, I proposed [3] and gave some reasons for just having: ALTER SUBSCRIPTION sub REFRESH SEQUENCES; And that's where it ended up... ~~~ If your proposal is to proceed, then IMO it would be better to continue the same pattern, avoiding introducing new keywords unless absolutely necessary. So, your v1 patch syntax "REFRESH TABLE" looked good to me. A similar reasoning to "REFRESH SEQUENCES" [3] can be used to explain it. ====== [1] https://www.postgresql.org/message-id/CALDaNm30iA_N4Dfeyp__YdLnbm9oatw_%2BVyCfNfbQmZiS_ybCw%40mail.gmail.com [2] https://www.postgresql.org/message-id/CAA4eK1JJUv2Kykb%3DJvdTzq%2BqDzkbD3m%2BYPAF6qz6Sm-qJ%2BwF8g%40mail.gmail.com [3] https://www.postgresql.org/message-id/CAHut%2BPvOmCe2fO4LPwJtROierhGLtHY%2B%2B%2Br9PXF8%3DLLQ2m%3DAXw%40mail.gmail.com Kind Regards, Peter Smith. Fujitsu Australia
Re: Per-table resync for logical replication subscriptions
От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Hi, On Wed, Jul 8, 2026 at 3:55 AM Cagri Biroglu wrote: > > here is the WIP patch for the disabled-subscription case. > It adds: > > ALTER SUBSCRIPTION name REFRESH TABLE table_name > [ WITH (copy_data = true, truncate = true) ] > > The command is subscriber-local: it resets just the named relation in > pg_subscription_rel back to the initial sync state (optionally > truncating the local copy first), so a tablesync worker re-copies that > one table on the next enable, reusing the existing tablesync machinery. > Publication membership and other tables are left untouched. As > discussed, this first version requires the subscription to be disabled. > > The tests are included in the same patch: a TAP test at > src/test/subscription/t/039_refresh_table.pl that > > - resyncs one drifted table on a two-node setup and confirms it > matches the publisher again after re-enabling; > - confirms only the targeted relation is reset (a sibling table is > left in 'r' state); > - checks the rejection cases: enabled subscription, table not in the > subscription, a sequence, truncate without copy_data, and running > inside a transaction block. > > The full src/test/subscription suite and the core regression tests pass > with the patch applied. > > Open questions if this direction makes sense ,I would still like feedback on: the command spelling > (REFRESH TABLE vs RESYNC TABLE), and whether the enabled-subscription > case is worth doing as a follow-up (it needs the running apply worker to > notice and re-read the reset relation state). REFRESH TABLE is better to me. It's more consistent with the existing commands such as REFRESH REQUENCES. I've not looked at the patch in depth yet but I have a few comments: I think it might be a good idea that the REFRESH TABLE command can take multiple tables rather than one table. --- Why does the REFRESH TABLE command require for the subscription to be disabled while REFRESH PUBLICATIONS doesn't? Regards, -- Masahiko Sawada Amazon Web Services: https://aws.amazon.com
Re: Per-table resync for logical replication subscriptions
Thanks a lot for looking at this.
Before the point-by-point: one change after getting feedback on this
from the sketch in my first mail
is that I dropped the WITH (copy_data, truncate) options. For refreshing
a table that is already subscribed, only one combination is useful, so
REFRESH TABLE now always truncates the local copy and re-copies (what
would have been copy_data = true, truncate = true). Without truncating,
the re-copy hits duplicate-key errors or doubles the rows; skipping the
copy leaves the drift in place. So neither other combination is
meaningful, and there is nothing to configure.
> REFRESH TABLE is better to me. It's more consistent with the existing
> commands such as REFRESH SEQUENCES.
Great, I've kept REFRESH TABLE.
> I think it might be a good idea that the REFRESH TABLE command can
> take multiple tables rather than one table.
Agreed. v2 makes REFRESH TABLE take a comma-separated list:
ALTER SUBSCRIPTION name REFRESH TABLE t1, t2, ...
It's all-or-nothing: every named relation is validated (part of the
subscription, not a sequence, exists) before any of them is reset, so a
bad table name aborts the whole command without touching the others. The
listed tables are also truncated together, which lets a set connected by
foreign keys be re-seeded as a unit.
One note on scope: this doesn't add resource risk over doing one table
at a time, because the re-copy is still performed by tablesync workers
that are capped by max_sync_workers_per_subscription; resetting N tables
just queues them rather than starting N copies at once.
> Why does the REFRESH TABLE command require for the subscription to be
> disabled while REFRESH PUBLICATIONS doesn't?
Good question, but I'd actually argue the disabled requirement is a
reasonable design choice here rather than a limitation to remove.
The reason the two commands differ is that REFRESH PUBLICATION only adds
*new* relations to pg_subscription_rel (in init state), whereas REFRESH
TABLE resets a relation that is already in ready state, and those hit
different caches in the apply worker:
- The set of not-ready relations is cached (table_states_not_ready in
syncutils.c) and correctly invalidated by the SUBSCRIPTIONRELMAP
syscache callback (InvalidateSyncingRelStates). So after the reset the
apply worker does notice the table is non-ready and does launch a
tablesync worker for it. That part works whether enabled or not.
- However, whether the apply worker applies incoming changes for a
relation is decided by should_apply_changes_for_rel(), which reads the
per-relation LogicalRepRelMapEntry.state. That state is only refreshed
from the catalog while it is not READY:
/* relation.c, logicalrep_rel_open() */
if (entry->state != SUBREL_STATE_READY)
entry->state = GetSubscriptionRelState(...);
For an already-ready table the entry stays READY, and the relcache
invalidation only clears localrelvalid (rebuilds the attrmap); it does
not reset entry->state. So the running apply worker keeps treating the
table as READY and keeps applying live changes to it, at the same time
as the freshly launched tablesync worker re-copies it, with no handoff
on the sync LSN. In my testing that reliably diverges the table.
For a newly added table (REFRESH PUBLICATION) there is no stale READY
entry, so the normal init -> datasync -> syncdone -> ready handoff works
without any disable.
Requiring the subscription to be disabled sidesteps this cleanly. When
you re-enable, a fresh apply worker starts and reads the reset table's
state from the catalog as init, so the same init -> datasync -> syncdone
-> ready handoff kicks in, exactly as for a newly added table. And the
disable only needs to bracket the quick catalog reset, not the re-copy
itself: REFRESH TABLE just truncates and flips the state, and after
ENABLE the tablesync worker does the (possibly long) copy while the
apply worker resumes the other tables as usual, so the pause is short
and scoped to the metadata change, not the data copy.
Supporting the enabled case would instead mean reaching into the running
apply worker to force it to drop and re-read the cached state of the
reset relation mid-flight. That is doable, but it adds moving parts and
a new invalidation path to get right, for what is a deliberate,
occasional maintenance action where briefly disabling the subscription
does no harm. So my inclination is to keep the disabled requirement here
rather than trade that simplicity away. Happy to reconsider if you think
the enabled case matters enough to justify the extra machinery or i am missing sth.
Regards,
Cagri Biroglu
RE: Per-table resync for logical replication subscriptions
Dear Cagri, Thanks for updating the patch. I read and tested your patch. Here are my comments. 01. According to the REFRESH PUBLICATION command, we must prohibit to synchronize tables if the two_phase is enabled, but REFRESH TABLE seems to bypass the restriction. Also, if there are prepared transactions done by the subscription and they modify target relations, the command would stuck forever - the apply worker won't start again. So should we have the same guard as the REFRESH PUBLICATION? 02. You have already checked the case the existence of tablesync workers, but not for the leader worker. I feel we should ensure via logicalrep_workers_find() like ALTER SUBSCRIPTION SET (two_phase). Also, we can remove the part from AlterSubscription_refresh_table(). 03. Regarding the partition table, I found the case that TRUNCATE happened but srsubstate cannot be updated. It's because ExecuteTruncate() truncates tables all child tables but AlterSubscription_refresh_table() updates tuples relid is exactly matched. Per my experiment, this can cause the issue if the different publications publish the root and child separately, and they are subscribed by the different subscription. See attached reproducer. Best regards, Hayato Kuroda FUJITSU LIMITED
RE: Per-table resync for logical replication subscriptions
От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Cagri,
Thanks for the update. I found this patch could cause an issue if two subscriptions
are modifying the same table. The scenario:
1. A tablesync worker for sub1 acquired opened a table with the RowExclusive in LogicalRepSyncTableStart().
2. User ran ALTER SUBSCRIPTION sub2 REFRESH TABLE command.
3. The backend acquired a AccessExclusive lock for pg_subscription_rel, then
tried to acquire a AccessExclusive Lock for tables. It would wait till the tablesync
worker released.
4. The tablesync worker also tried to acquire AccessShare lock for pg_subscription_rel,
but it would be blocked by the backend. It's done in
copy_table()->logicalrep_rel_open()->GetSubscriptionRelState().
5. The deadlock detector detected the wait-for graph is now circle,
thus it terminates either of them.
One idea for the fix is to acquire AccessShare locks for user-defined tables
first, then acquire the AccessExclusive lock after the CheckRefreshTableNotShared().
This avoids to acquire strong locks only if it's needed, and my reproducer can
reject by the function. Thought?
Also, below are my cosmetic comments.
01.
```
+ LOCKMODE lockmode = AccessExclusiveLock;
```
It might be matter of taste, but I feel the variable lock_mode is not needed:
the pattern is mainly used when the mode can be different based on situations.
02.
```
+static void
+CheckRefreshTableNotShared(Relation pgsubrel, Subscription *sub,
+ List *subrelids, List *relids)
```
The name CheckRefreshTableNotShared() is not suitable, because not sure the
meaning "Shared". How about CheckRefreshTableNotInOtherSubscriptions?
03.
```
+ /*
+ * Tuples reach a partition through its ancestors, so a subscription
+ * tracking any of them keeps this relation populated too. A named
+ * relation's own entry belongs to this subscription and is skipped
+ * below by the srsubid test.
+ */
+ feeders = lappend_oid(get_partition_ancestors(relid), relid);
```
get_partition_ancestors() seems to assume that the given relation has at least
one parent, but the patch does not ensure. Maybe get_rel_relispartition() or
similar functions can be used.
04.
You missed to update meson.build file.
05.
```
+$node_subscriber->append_conf('postgresql.conf',
+ "wal_retrieve_retry_interval = 1ms");
```
Can you clarify the reason why the setting is required? Can we remove if not needed?
Best regards,
Hayato Kuroda
FUJITSU LIMITED
Re: Per-table resync for logical replication subscriptions
Hello Ajin,
Thank you for the review. This needs a change outside the feature;
Thank you for the review. This needs a change outside the feature;
v7 is attached.
> 1. The header above CheckRefreshTableNotInOtherSubscriptions() has two
> sets of comments, the first one I feel is meant for
> AlterSubscription_refresh_table() which is without a header.
Right , done.
> 2.
> + /*
> + * The local copy is discarded below, so require the same privilege
> + * TRUNCATE itself would.
> + */
> + aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
> + if (aclresult != ACLCHECK_OK)
> + aclcheck_error(aclresult, get_relkind_objtype(get_rel_relkind(relid)),
> + rv->relname);
>
> rather than doing it this way, I believe you need to call
> truncate_check_rel(relid, rel->rd_rel);
> truncate_check_perms(relid, rel->rd_rel);
> truncate_check_activity(rel);
>
> else you will miss out on checking for temp tables of other backends
> and invoking InvokeObjectTruncateHook(relid) which are object access
> hooks.
Agreed. v6 does call the hook, but by hand;
v7 does it the way you describe, which also brings in the temp table check
that the hand-rolled version was still missing.
So v7 makes the three functions extern, which is no functional change on its
own, and calls them as you describe:
truncate_check_rel(relid, userrel->rd_rel);
truncate_check_activity(userrel);
for every relation that will be truncated, and
truncate_check_perms(relid, userrel->rd_rel);
for the relations actually named in the command. The privilege check stays in
the first pass, earlier than the other two, so that the command is rejected
before it escalates any lock. It is deliberately not applied to the partitions
that come along with a named partitioned table, which follows what
ExecuteTruncate() does for inheritance children:
* Inherited TRUNCATE commands perform access permission
* checks on the parent table only. So we skip checking the
* children's permissions and don't call
* truncate_check_perms() here.
*/
truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
truncate_check_activity(rel);
Two consequences are behaviour changes rather than tidying, so they are worth
naming.
Your point about other backends' temp tables was the substantive one. The
check was being applied only to the partitions the command collects, on the
argument that a temp table cannot be a partition of a permanent one; the
relations named in the command were not covered at all, which left that case
resting on an untested assumption about what can appear in
pg_subscription_rel. That is not the kind of thing to lean on.
truncate_check_activity() now covers them, and errors rather than skips, as
ExecuteTruncate() does for explicitly named relations.
truncate_check_activity() calls CheckTableNotInUse(rel, "TRUNCATE"), so that
message now says TRUNCATE rather than naming the subscription command. I
preferred that to keeping a hand-rolled copy for the sake of one string, but
say the word if you would rather it read ALTER SUBSCRIPTION ... REFRESH TABLE
and I will thread the statement name through.
Best regards,
Cagri Biroglu
> 1. The header above CheckRefreshTableNotInOtherSubscriptions() has two
> sets of comments, the first one I feel is meant for
> AlterSubscription_refresh_table() which is without a header.
Right , done.
> 2.
> + /*
> + * The local copy is discarded below, so require the same privilege
> + * TRUNCATE itself would.
> + */
> + aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
> + if (aclresult != ACLCHECK_OK)
> + aclcheck_error(aclresult, get_relkind_objtype(get_rel_relkind(relid)),
> + rv->relname);
>
> rather than doing it this way, I believe you need to call
> truncate_check_rel(relid, rel->rd_rel);
> truncate_check_perms(relid, rel->rd_rel);
> truncate_check_activity(rel);
>
> else you will miss out on checking for temp tables of other backends
> and invoking InvokeObjectTruncateHook(relid) which are object access
> hooks.
Agreed. v6 does call the hook, but by hand;
v7 does it the way you describe, which also brings in the temp table check
that the hand-rolled version was still missing.
So v7 makes the three functions extern, which is no functional change on its
own, and calls them as you describe:
truncate_check_rel(relid, userrel->rd_rel);
truncate_check_activity(userrel);
for every relation that will be truncated, and
truncate_check_perms(relid, userrel->rd_rel);
for the relations actually named in the command. The privilege check stays in
the first pass, earlier than the other two, so that the command is rejected
before it escalates any lock. It is deliberately not applied to the partitions
that come along with a named partitioned table, which follows what
ExecuteTruncate() does for inheritance children:
* Inherited TRUNCATE commands perform access permission
* checks on the parent table only. So we skip checking the
* children's permissions and don't call
* truncate_check_perms() here.
*/
truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
truncate_check_activity(rel);
Two consequences are behaviour changes rather than tidying, so they are worth
naming.
Your point about other backends' temp tables was the substantive one. The
check was being applied only to the partitions the command collects, on the
argument that a temp table cannot be a partition of a permanent one; the
relations named in the command were not covered at all, which left that case
resting on an untested assumption about what can appear in
pg_subscription_rel. That is not the kind of thing to lean on.
truncate_check_activity() now covers them, and errors rather than skips, as
ExecuteTruncate() does for explicitly named relations.
truncate_check_activity() calls CheckTableNotInUse(rel, "TRUNCATE"), so that
message now says TRUNCATE rather than naming the subscription command. I
preferred that to keeping a hand-rolled copy for the sake of one string, but
say the word if you would rather it read ALTER SUBSCRIPTION ... REFRESH TABLE
and I will thread the statement name through.
Best regards,
Cagri Biroglu
On Tue, Aug 25, 2026 at 7:52 AM Ajin Cherian <itsajin@gmail.com> wrote:
On Wed, Aug 19, 2026 at 9:10 PM Cagri Biroglu <cagri.biroglu@adyen.com> wrote:
>
> Hello Hayato,
>
> Thank you for the review, v5 is attached.
>
Hello Cagri,
Some minor comments:
1. The header above CheckRefreshTableNotInOtherSubscriptions() has two
sets of comments, the first one I feel is meant for
AlterSubscription_refresh_table() which is without a header.
2.
+ /*
+ * The local copy is discarded below, so require the same privilege
+ * TRUNCATE itself would.
+ */
+ aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
+ if (aclresult != ACLCHECK_OK)
+ aclcheck_error(aclresult, get_relkind_objtype(get_rel_relkind(relid)),
+ rv->relname);
rather than doing it this way, I believe you need to call
truncate_check_rel(relid, rel->rd_rel);
truncate_check_perms(relid, rel->rd_rel);
truncate_check_activity(rel);
else you will miss out on checking for temp tables of other backends
and invoking InvokeObjectTruncateHook(relid) which are object access
hooks.
regards,
Ajin Cherian
Fujitsu Australia
Re: Fix resource leak in FindConflictTuple() retry path
От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Thu, Sep 3, 2026 at 9:22 AM Nisha Moond wrote:
>
> Hi,
>
> As part of the AI-assisted review of the update_deleted conflict
> detection work [1], a small resource leak was identified in
> FindConflictTuple(), introduced by commit 9758174e2e5.
>
> When should_refetch_tuple() returns true i.e. when the conflicting
> tuple was modified between ExecCheckIndexConstraints() and
> table_tuple_lock(), the function retries from its retry label. On each
> pass it creates a new slot and assigns it to *conflictslot,
> overwriting the previous slot without releasing it. So every retry
> abandons one slot.
>
> The abandoned slot also holds a buffer pin. Since FindConflictTuple()
> does not pass TUPLE_LOCK_FLAG_FIND_LAST_VERSION, heapam_tuple_lock()
> falls through to ExecStorePinnedBufferHeapTuple(), which transfers the
> pin to the slot even for TM_Updated. The heap_lock_tuple() failure
> path releases the content lock but not the pin. Since the slot has a
> NULL reglist, it is not registered in estate->es_tupleTable and is
> therefore not cleaned up by ExecResetTupleTable().
>
> This is mostly harmless in practice: the slot is freed with its memory
> context, and buffer pins are released at transaction end. The usual
> conflict path also aborts the transaction with ERROR, releasing
> everything.
>
> Still, a pinned buffer cannot be evicted, and repeated retries on a
> contended unique key can accumulate pins for the lifetime of the
> transaction, so this seems worth fixing.
>
> The attached patch-001 creates the slot once before the retry loop and
> reuses it. Re-storing a tuple in the same slot releases its previous
> buffer pin, so no slot is abandoned.
>
> Reproducing the issue:
> The window is very narrow and cannot be triggered directly from SQL,
> as the concurrent UPDATE must occur between
> ExecCheckIndexConstraints() and table_tuple_lock() inside
> FindConflictTuple().
>
> I created a small, hacky TAP test (patch-002) with the help of Claude,
> which uses an injection point and elog() to reproduce the issue and
> verify slot reuse. This test is only for demonstrating the problem and
> is not intended for commit.
>
> Since this is an oversight in commit 9758174e2e5, it should be
> backpatched to PG18.
>
> Feedback on the fix and approach is welcome.
>
> [1] https://www.postgresql.org/message-id/TY4PR01MB177182F547A62FC2666EC04EC94B72%40TY4PR01MB17718.jpnprd01.prod.outlook.com
>
I agree with the idea of patch. But the patch can be improved. Before
this patch, slot creation happened after the conflict was found. Now
it happens unconditionally. So every call to FindConflictTuple() now
allocates a slot and immediately tears it down. So most of the cases
which are ocnflict-free now will do slot-allocation. I feel this can
be optimized.
Suggestion:
retry:
if (ExecCheckIndexConstraints(...))
{
if (*conflictslot)
ExecDropSingleTupleTableSlot(*conflictslot);
*conflictslot = NULL;
return false;
}
if (*conflictslot == NULL)
*conflictslot = table_slot_create(rel, NULL);
thanks
Shveta
Re: Fix resource leak in FindConflictTuple() retry path
On Thu, Sep 3, 2026 at 2:36 PM shveta malik wrote: > > On Thu, Sep 3, 2026 at 1:03 PM Hayato Kuroda (Fujitsu) > wrote: > > > > Dear Nisha, > > > > Not sure, should we release a buffer pin if should_refetch_tuple() returns true? > > I referred heapam_tuple_lock()/heap_lock_tuple(), they pin a buffer via ReadBuffer() > > and transfers to a slot via ExecStorePinnedBufferHeapTuple(). > > > > IIUC, ExecClearTuple() can release corresponding resources for the slot, so below > > fix is enough. > > > > IMO, ExecClearTuple() can resolve the problem of pinned buffers but it > still leaves the other trivial problem behind that we keep allocating > slots while one is enough, which when resued will release buffer pin > in ExecStorePinnedBufferHeapTuple() -> tts_buffer_heap_store_tuple() > implicitly. +1 > Therefore, this alone might not be a better fix. But if we want to > club it with the fix already provided by Nisha, that will help us > releasing the pin a little earlier without relying on next > table_tuple_lock() on same slot to do that implictly. That said, I > don't see ExecClearTuple() called explicitly in the two similar > functions in this file, RelationFindReplTupleByIndex() and > RelationFindReplTupleSeq(); both of which reuse a single > caller-provided slot across retries and rely purely on the implicit > release-on-restore behavior. > I also agree not to make FindConflictTuple() the only one clearing explicitly. -- Thanks, Nisha
RE: Per-table resync for logical replication subscriptions
Dear Cagri, Thanks for the patch. I have comments for v7. ``` + /* + * The relation set is now known to be fed by this subscription alone, and + * this subscription has no running workers, so nothing that replicates + * into these relations is still holding them. Take the level the + * truncate needs. + */ + foreach_oid(relid, relids) + LockRelationOid(relid, AccessExclusiveLock); ``` Here we does not acquire a lock for the root table if the publication publishes only leaves. So subscriptions can be created after CheckRefreshTableNotInOtherSubscriptions(). I considered a race condition due to this with LLM: See attached patch. Also, I found the test could fail like: ``` [14:44:37.892](0.014s) not ok 35 - only the named inheritance parent is reset [14:44:37.893](0.000s) # Failed test 'only the named inheritance parent is reset' # at /home/hayato/postgres/src/test/subscription/t/039_refresh_table.pl line 407. [14:44:37.893](0.000s) # got: 'tab_inh_c=s,tab_inh_p=i' # expected: 'tab_inh_c=r,tab_inh_p=i' ``` It tried to ensure the tab_inh_c was synchronized, right? Should accept 's' Best regards, Hayato Kuroda FUJITSU LIMITED
RE: Per-table resync for logical replication subscriptions
От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Cagri,
Thanks for updating the patch! Few comments:
01.
There seems to be a corner issue for partition handling. Existing code ensures to
lock the parittion root first then lock the children. However, if both the parent
and its child is in the pg_subscription_rel and DBA runs the command like below,
the ordering of the lock can be opposite. This situation can happen if the
schema definition is difference between the publisher and subscriber side.
ALTER SUBSCRIPTION sub REFRESH TABLE table_child, table_root;
I showed a reproducer in [1], but I think it seldom happen. We may have to
re-order relids to be the partition root first if we want to fix.
02:
```
+ /*
+ * The local copy is discarded below, so require the same privilege
+ * TRUNCATE itself would. This runs here, rather than with the other
+ * two truncate checks further down, so that the command is rejected
+ * before it escalates any lock. As in ExecuteTruncate(), the
+ * privilege is required of the relations named in the command, not of
+ * the partitions that come with them.
+ */
+ userrel = table_open(relid, NoLock);
+ truncate_check_perms(relid, userrel->rd_rel);
+ table_close(userrel, NoLock);
```
According to a comment atop objectNamesToOids(), REVOKE command only acquires the
AccessShareLock. So I think the concurrent DDL can revoke a TRUNCATE privilege
after the truncate_check_perms(). IIUC the check should be done after acquiring
the AccessExclusive.
[1]:
Setup
=====
Publisher definition:
CREATE TABLE test_p (id int);
CREATE TABLE test_c (id int);
CREATE PUBLICATION pub_p FOR TABLE test_p;
CREATE PUBLICATION pub_c FOR TABLE test_c;
Subscriber definition:
CREATE TABLE test_p (id int) PARTITION BY RANGE (id);
CREATE TABLE test_c PARTITION OF test_p FOR VALUES FROM (-100) TO (0);
CREATE SUBSCRIPTION sub CONNECTION '{pub_connstr}' PUBLICATION pub_p, pub_c;
With above setup test_p and test_c can be in the pg_subscription_rel.
```
subscriber=# \d
List of relations
Schema | Name | Type | Owner
--------+--------+-------------------+----------
public | test_c | table | postgres
public | test_p | partitioned table | postgres
(2 rows)
subscriber=# SELECT * FROM pg_subscription_rel ;
srsubid | srrelid | srsubstate | srsublsn
---------+---------+------------+------------
16390 | 16384 | r | 0/0177F038
16390 | 16387 | r | 0/0177F038
(2 rows)
```
Workload
========
0. Disable a subscription
1. Establish a connection to the subscriber
2. Attach the backend via gdb, and add a break on AlterSubscription_refresh_table
3. Run `ALTER SUBSCRIPTION sub REFRESH test_c, test_p`
4. Proceed steps on gdb and stop just after acquiring an AccessExclusiveLock for test_c.
5. Establish another connection to the subscriber
6. Run `INSERT INTO test_p VALUES (-1);`. It would wait acquiring a lock
7. detach from the first backend process.
8. Deadlock could happen between two backends.
Best regards,
Hayato Kuroda
FUJITSU LIMITED
RE: Per-table resync for logical replication subscriptions
От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Cagri,
While thinking this feature again, I had two points:
01.
Assuming the below schema definition, which only the subscriber has a partition:
```
pub - sub
tab tab
- tab_part1 // stores data from pub
- tab_part2 // stores data generated locally
```
In this case, REFRESH TABLE tab command truncate partition leaves. Data in
tab_part1 could be re-synced but tuples in tab_part2 were gone. Is it OK?
I felt several issues have been reported for the partition table, and this trend
would continue. How about separating the patch into two parts, 0001 is for normal
tables (reject for partition root) and 0002 adds the partition handling?
02.
Logical replication allowed to construct two(three)-way replication with the
subscription parameter origin=none. Can you evaluate the combination? I'm worry
because initial sync does not take care the origin of tuples.
Best regards,
Hayato Kuroda
FUJITSU LIMITED
Re: Per-table resync for logical replication subscriptions
Dear Hayato,
Thank you for both rounds. The attached v10 answers all four points. It also
carries the two fixes from your previous review, so it replaces v9.
In short:
- The tables are locked root first now, so naming a partition before its root
no longer deadlocks.
- The TRUNCATE privilege is checked again under AccessExclusiveLock.
- Truncating the partitions of a subscribed partitioned table is what a
replicated TRUNCATE already does, so nothing extra is lost. Documented.
- REFRESH TABLE now runs the origin = none copy check, for the tables it
re-seeds.
From your earlier review:
> We may have to re-order relids to be the partition root first
Done. I reproduced it without gdb, by holding the partition in a prepared
transaction:
REFRESH TABLE test_c, test_p -- has test_c, wants test_p
INSERT INTO test_p -- has test_p, wants test_c
ERROR: deadlock detected
SortRefreshTableRelations() sorts the named tables by how many partitioned
ancestors each one has, which puts every root ahead of its partitions.
Unrelated tables keep the order given. The reproducer is clean afterwards.
> IIUC the check should be done after acquiring the AccessExclusive
Right. objectNamesToOids() takes only AccessShareLock, deliberately, so the
privilege can go away after the first check. TRUNCATE is safe because its
check sits in a RangeVarGetRelidExtended() callback that is re-run with the
lock held. This command has no callback, so it repeats the check itself.
From this review:
> In this case, REFRESH TABLE tab command truncate partition leaves. Data in
> tab_part1 could be re-synced but tuples in tab_part2 were gone. Is it OK?
It is not new. I ran your schema twice:
local-only rows in tab_part2 surviving, out of 5
publisher TRUNCATE : 0
REFRESH TABLE : 0
apply_handle_truncate() expands a partitioned target the same way, so a
TRUNCATE on the publisher already empties tab_part2. The docs now say so.
> How about separating the patch into two parts, 0001 is for normal tables
> (reject for partition root) and 0002 adds the partition handling?
Rejecting partitioned roots removes only about fifty lines. It does not
remove the ancestor locking or the ancestor half of the cross-subscription
check, which are needed when a leaf is the subscribed table, as it is whenever
publish_via_partition_root is off. Both problems you found here were in that
code, so it would stay in 0001 and 0002 would add the easy part. I would
rather keep one patch, but I will split it if you prefer.
> Can you evaluate the combination? I'm worry because initial sync does not
> take care the origin of tuples.
thank you. With C -> B -> A and A on origin = none, the same
copy made CREATE SUBSCRIPTION warn and REFRESH TABLE stay silent.
check_publications_origin_tables() skips the tables a subscription already
has, because those come through WAL where origins are known, and this command
is the one thing that puts such a table back through a copy. v10 runs the
check and passes the subscription's other tables as the skip list, so it warns
for a table another subscription writes and stays quiet otherwise.
check-world passes.
Best regards,
Cagri
Thank you for both rounds. The attached v10 answers all four points. It also
carries the two fixes from your previous review, so it replaces v9.
In short:
- The tables are locked root first now, so naming a partition before its root
no longer deadlocks.
- The TRUNCATE privilege is checked again under AccessExclusiveLock.
- Truncating the partitions of a subscribed partitioned table is what a
replicated TRUNCATE already does, so nothing extra is lost. Documented.
- REFRESH TABLE now runs the origin = none copy check, for the tables it
re-seeds.
From your earlier review:
> We may have to re-order relids to be the partition root first
Done. I reproduced it without gdb, by holding the partition in a prepared
transaction:
REFRESH TABLE test_c, test_p -- has test_c, wants test_p
INSERT INTO test_p -- has test_p, wants test_c
ERROR: deadlock detected
SortRefreshTableRelations() sorts the named tables by how many partitioned
ancestors each one has, which puts every root ahead of its partitions.
Unrelated tables keep the order given. The reproducer is clean afterwards.
> IIUC the check should be done after acquiring the AccessExclusive
Right. objectNamesToOids() takes only AccessShareLock, deliberately, so the
privilege can go away after the first check. TRUNCATE is safe because its
check sits in a RangeVarGetRelidExtended() callback that is re-run with the
lock held. This command has no callback, so it repeats the check itself.
From this review:
> In this case, REFRESH TABLE tab command truncate partition leaves. Data in
> tab_part1 could be re-synced but tuples in tab_part2 were gone. Is it OK?
It is not new. I ran your schema twice:
local-only rows in tab_part2 surviving, out of 5
publisher TRUNCATE : 0
REFRESH TABLE : 0
apply_handle_truncate() expands a partitioned target the same way, so a
TRUNCATE on the publisher already empties tab_part2. The docs now say so.
> How about separating the patch into two parts, 0001 is for normal tables
> (reject for partition root) and 0002 adds the partition handling?
Rejecting partitioned roots removes only about fifty lines. It does not
remove the ancestor locking or the ancestor half of the cross-subscription
check, which are needed when a leaf is the subscribed table, as it is whenever
publish_via_partition_root is off. Both problems you found here were in that
code, so it would stay in 0001 and 0002 would add the easy part. I would
rather keep one patch, but I will split it if you prefer.
> Can you evaluate the combination? I'm worry because initial sync does not
> take care the origin of tuples.
thank you. With C -> B -> A and A on origin = none, the same
copy made CREATE SUBSCRIPTION warn and REFRESH TABLE stay silent.
check_publications_origin_tables() skips the tables a subscription already
has, because those come through WAL where origins are known, and this command
is the one thing that puts such a table back through a copy. v10 runs the
check and passes the subscription's other tables as the skip list, so it warns
for a table another subscription writes and stays quiet otherwise.
check-world passes.
Best regards,
Cagri
On Fri, Sep 25, 2026 at 11:44 AM Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com> wrote:
Dear Cagri,
While thinking this feature again, I had two points:
01.
Assuming the below schema definition, which only the subscriber has a partition:
```
pub - sub
tab tab
- tab_part1 // stores data from pub
- tab_part2 // stores data generated locally
```
In this case, REFRESH TABLE tab command truncate partition leaves. Data in
tab_part1 could be re-synced but tuples in tab_part2 were gone. Is it OK?
I felt several issues have been reported for the partition table, and this trend
would continue. How about separating the patch into two parts, 0001 is for normal
tables (reject for partition root) and 0002 adds the partition handling?
02.
Logical replication allowed to construct two(three)-way replication with the
subscription parameter origin=none. Can you evaluate the combination? I'm worry
because initial sync does not take care the origin of tuples.
Best regards,
Hayato Kuroda
FUJITSU LIMITED
Re: Per-table resync for logical replication subscriptions
Hello again ,
needed a rebase. v11 is attached.
Best regards,
Cagri
needed a rebase. v11 is attached.
Best regards,
Cagri
On Sun, Sep 27, 2026 at 10:35 PM Cagri Biroglu <cagri.biroglu@adyen.com> wrote:
Dear Hayato,
Thank you for both rounds. The attached v10 answers all four points. It also
carries the two fixes from your previous review, so it replaces v9.
In short:
- The tables are locked root first now, so naming a partition before its root
no longer deadlocks.
- The TRUNCATE privilege is checked again under AccessExclusiveLock.
- Truncating the partitions of a subscribed partitioned table is what a
replicated TRUNCATE already does, so nothing extra is lost. Documented.
- REFRESH TABLE now runs the origin = none copy check, for the tables it
re-seeds.
From your earlier review:
> We may have to re-order relids to be the partition root first
Done. I reproduced it without gdb, by holding the partition in a prepared
transaction:
REFRESH TABLE test_c, test_p -- has test_c, wants test_p
INSERT INTO test_p -- has test_p, wants test_c
ERROR: deadlock detected
SortRefreshTableRelations() sorts the named tables by how many partitioned
ancestors each one has, which puts every root ahead of its partitions.
Unrelated tables keep the order given. The reproducer is clean afterwards.
> IIUC the check should be done after acquiring the AccessExclusive
Right. objectNamesToOids() takes only AccessShareLock, deliberately, so the
privilege can go away after the first check. TRUNCATE is safe because its
check sits in a RangeVarGetRelidExtended() callback that is re-run with the
lock held. This command has no callback, so it repeats the check itself.
From this review:
> In this case, REFRESH TABLE tab command truncate partition leaves. Data in
> tab_part1 could be re-synced but tuples in tab_part2 were gone. Is it OK?
It is not new. I ran your schema twice:
local-only rows in tab_part2 surviving, out of 5
publisher TRUNCATE : 0
REFRESH TABLE : 0
apply_handle_truncate() expands a partitioned target the same way, so a
TRUNCATE on the publisher already empties tab_part2. The docs now say so.
> How about separating the patch into two parts, 0001 is for normal tables
> (reject for partition root) and 0002 adds the partition handling?
Rejecting partitioned roots removes only about fifty lines. It does not
remove the ancestor locking or the ancestor half of the cross-subscription
check, which are needed when a leaf is the subscribed table, as it is whenever
publish_via_partition_root is off. Both problems you found here were in that
code, so it would stay in 0001 and 0002 would add the easy part. I would
rather keep one patch, but I will split it if you prefer.
> Can you evaluate the combination? I'm worry because initial sync does not
> take care the origin of tuples.
thank you. With C -> B -> A and A on origin = none, the same
copy made CREATE SUBSCRIPTION warn and REFRESH TABLE stay silent.
check_publications_origin_tables() skips the tables a subscription already
has, because those come through WAL where origins are known, and this command
is the one thing that puts such a table back through a copy. v10 runs the
check and passes the subscription's other tables as the skip list, so it warns
for a table another subscription writes and stays quiet otherwise.
check-world passes.
Best regards,
CagriOn Fri, Sep 25, 2026 at 11:44 AM Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com> wrote:Dear Cagri,
While thinking this feature again, I had two points:
01.
Assuming the below schema definition, which only the subscriber has a partition:
```
pub - sub
tab tab
- tab_part1 // stores data from pub
- tab_part2 // stores data generated locally
```
In this case, REFRESH TABLE tab command truncate partition leaves. Data in
tab_part1 could be re-synced but tuples in tab_part2 were gone. Is it OK?
I felt several issues have been reported for the partition table, and this trend
would continue. How about separating the patch into two parts, 0001 is for normal
tables (reject for partition root) and 0002 adds the partition handling?
02.
Logical replication allowed to construct two(three)-way replication with the
subscription parameter origin=none. Can you evaluate the combination? I'm worry
because initial sync does not take care the origin of tuples.
Best regards,
Hayato Kuroda
FUJITSU LIMITED
RE: Per-table resync for logical replication subscriptions
От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Hi Cagri, Sorry for the late reply. I have been busy for PG19 open items. > Rejecting partitioned roots removes only about fifty lines. It does not > remove the ancestor locking or the ancestor half of the cross-subscription > check, which are needed when a leaf is the subscribed table, as it is whenever > publish_via_partition_root is off. Both problems you found here were in that > code, so it would stay in 0001 and 0002 would add the easy part. I would > rather keep one patch, but I will split it if you prefer. I still prefer the separated patch to make review easier. > thank you. With C -> B -> A and A on origin = none, the same > copy made CREATE SUBSCRIPTION warn and REFRESH TABLE stay silent. > check_publications_origin_tables() skips the tables a subscription already > has, because those come throuqgh WAL where origins are known, and this command > is the one thing that puts such a table back through a copy. v10 runs the > check and passes the subscription's other tables as the skip list, so it warns > for a table another subscription writes and stays quiet otherwise. Assuming that there is a bidirectional setup A <-> B, and REFRESH TABLE is done on node A. In this case the TRUNCATE can be replicated to the node B and table on both nodes are empty. Tuples are lost after the subscription is enabled because the copy source does not have ones anymore. Isn't it problematic? Is there a good method to fix? My primitive idea is to reject REFRESH command if the target tables are included in a publication. Below are new comments: 01. Assuming that there is a cascading replication: A->B->C and origin=any, and the publication on B does not publish TRUNCATE. If the REFRESH TABLE is done on B, the TRUNCATE cannot be replicated but the re-synced data can be replicated again, can cause the data conflict. Should we solve the issue? Rejecting the REFRESH TABLE on the intermediate node can solve the issue but may be too aggressive. 02. Assuming the normal logical replication system A->B, and the REFRESH TABLE is done while the srsubstate is still FINISHCOPY. If the command fails after dropping the replication origin and replication slot, the tablesync worker will assume the slot exists and tries to stream via the slot, it can cause the ERROR. I think we need to clarify that the REFRESH must be done again if it fails. Or should we reject the case if the table-sync is ongoing? Best regards, Hayato Kuroda FUJITSU LIMITED
Re: Per-table resync for logical replication subscriptions
Dear Hayato,
Thank you. v12 is attached.
- 0001 is plain tables, and rejects a partitioned table or a partition.
0002 adds partition support.
- The truncate now carries the subscription's own replication origin. That
is what keeps the two-way case from emptying both nodes.
- The failure after the slot drop is confirmed and documented.
> I still prefer the separated patch to make review easier.
Done.
> Isn't it problematic? Is there a good method to fix? My primitive idea is to
> reject REFRESH command if the target tables are included in a publication.
The cause is that the discard and the refill do not travel under the same
origin filter. The truncate is issued by a user backend, so it carries no
origin and nothing filters it, while the re-copy is done by a tablesync
worker, so it carries one. A subscriber using origin = none therefore takes
the first and drops the second.
v12 sets replorigin_xact_state.origin to the subscription's own origin around
ExecuteTruncateGuts(), which is the origin the apply worker would have used
had the same truncate arrived from the publisher. So the two halves travel
together: a subscriber takes both or neither.
v12 rows on B right after the command : 100
after re-enable : A 100, B 100
Indeed the primitive idea does prevent the loss, but it refuses a great deal more
Thank you. v12 is attached.
- 0001 is plain tables, and rejects a partitioned table or a partition.
0002 adds partition support.
- The truncate now carries the subscription's own replication origin. That
is what keeps the two-way case from emptying both nodes.
- The failure after the slot drop is confirmed and documented.
> I still prefer the separated patch to make review easier.
Done.
> Isn't it problematic? Is there a good method to fix? My primitive idea is to
> reject REFRESH command if the target tables are included in a publication.
The cause is that the discard and the refill do not travel under the same
origin filter. The truncate is issued by a user backend, so it carries no
origin and nothing filters it, while the re-copy is done by a tablesync
worker, so it carries one. A subscriber using origin = none therefore takes
the first and drops the second.
v12 sets replorigin_xact_state.origin to the subscription's own origin around
ExecuteTruncateGuts(), which is the origin the apply worker would have used
had the same truncate arrived from the publisher. So the two halves travel
together: a subscriber takes both or neither.
v12 rows on B right after the command : 100
after re-enable : A 100, B 100
Indeed the primitive idea does prevent the loss, but it refuses a great deal more
than it has to. "Included in a publication" holds for every table on a node that has a
FOR ALL TABLES publication, and for every table a forwarder forwards, which is
one of the topologies this is meant for. In the cascade below it would refuse
all four refreshes on B, where only one of the four was losing anything: two of
them publish no TRUNCATE at all, so nothing can cross, and the first converges
as it is.
Narrowing it to "the node I copy from is subscribed to me" would cut that
down, but it is both unreliable and incomplete: publication names are not
unique across nodes, so the match has to be made on a name the publisher
reports, and a cycle of three or more never matches at all -- with
A -> B -> C -> A the node A copies from is C, and nothing in A's catalogs
mentions C.
Tagging the truncate refuses nothing, needs no detection, and holds for any
cycle length.
> Rejecting the REFRESH TABLE on the intermediate node can solve the issue but
> may be too aggressive.
Agreed, and I think the matrix argues against it. A -> B -> C, refresh on B,
with drift introduced first so the repair restores different rows. Only two
settings matter, neither of them the command's:
B's publication C's subscription v11 C rows v12 C rows
publishes TRUNCATE origin = any 100, converged 100, converged
publishes TRUNCATE origin = none 0, LOST 100, keeps its own
withholds TRUNCATE origin = any 100, stale 100, stale
withholds TRUNCATE origin = none 100, stale 100, stale
The second row is the case you did not name, and it is the same bug as the
two-way one: the discard propagates, the refill does not. The third row is
yours; C logs conflict=insert_exists and its apply worker stops.
> I think we need to clarify that the REFRESH must be done again if it fails.
> Or should we reject the case if the table-sync is ongoing?
Confirmed, and I could fail the command there rather than reconstruct the
state. Two relations with tablesync slots, t1 parked at FINISHEDCOPY and t2
still copying. A pg_recvlogical session holds t2's slot, so the command drops
t1's slot and then waits on t2's, DROP_REPLICATION_SLOT ... WAIT waiting for an
active slot rather than failing: it is now inside its drop loop with one slot
already gone. Cutting its connection to the publisher there gives
ERROR: could not drop replication slot "pg_16400_sync_16392_..." on
publisher: FATAL: terminating connection due to administrator command
and the rollback returns t1 to FINISHEDCOPY with its slot gone, so enabling the
subscription leaves its worker at
ERROR: could not start WAL streaming: ERROR: replication slot
"pg_16400_sync_16384_..." does not exist
repeating, because tablesync.c resumes a FINISHEDCOPY relation from that slot,
reading its origin with replorigin_by_name(originname, false). Re-running the
command repairs it: state i, then r, 400001 rows on both sides. I can send the
script if you want to run it.
I have documented it rather than rejecting the mid-sync case, for two reasons.
A relation stuck mid-sync is the main thing this command is for -- a tablesync
that cannot finish is exactly what the user wants to reset -- so rejecting it
would remove the primary use. And the exposure is core's own: both
AlterSubscription_refresh() and DropSubscription() drop tablesync slots at the
very end with missing_ok = true, for the stated reason
/*
* Drop the tablesync slots associated with removed tables. This has
* to be at the end because otherwise if there is an error while doing
* the database operations we won't be able to rollback dropped slots.
*/
and this command does the same, with the slot drops last.
Best regards,
Cagri
FOR ALL TABLES publication, and for every table a forwarder forwards, which is
one of the topologies this is meant for. In the cascade below it would refuse
all four refreshes on B, where only one of the four was losing anything: two of
them publish no TRUNCATE at all, so nothing can cross, and the first converges
as it is.
Narrowing it to "the node I copy from is subscribed to me" would cut that
down, but it is both unreliable and incomplete: publication names are not
unique across nodes, so the match has to be made on a name the publisher
reports, and a cycle of three or more never matches at all -- with
A -> B -> C -> A the node A copies from is C, and nothing in A's catalogs
mentions C.
Tagging the truncate refuses nothing, needs no detection, and holds for any
cycle length.
> Rejecting the REFRESH TABLE on the intermediate node can solve the issue but
> may be too aggressive.
Agreed, and I think the matrix argues against it. A -> B -> C, refresh on B,
with drift introduced first so the repair restores different rows. Only two
settings matter, neither of them the command's:
B's publication C's subscription v11 C rows v12 C rows
publishes TRUNCATE origin = any 100, converged 100, converged
publishes TRUNCATE origin = none 0, LOST 100, keeps its own
withholds TRUNCATE origin = any 100, stale 100, stale
withholds TRUNCATE origin = none 100, stale 100, stale
The second row is the case you did not name, and it is the same bug as the
two-way one: the discard propagates, the refill does not. The third row is
yours; C logs conflict=insert_exists and its apply worker stops.
> I think we need to clarify that the REFRESH must be done again if it fails.
> Or should we reject the case if the table-sync is ongoing?
Confirmed, and I could fail the command there rather than reconstruct the
state. Two relations with tablesync slots, t1 parked at FINISHEDCOPY and t2
still copying. A pg_recvlogical session holds t2's slot, so the command drops
t1's slot and then waits on t2's, DROP_REPLICATION_SLOT ... WAIT waiting for an
active slot rather than failing: it is now inside its drop loop with one slot
already gone. Cutting its connection to the publisher there gives
ERROR: could not drop replication slot "pg_16400_sync_16392_..." on
publisher: FATAL: terminating connection due to administrator command
and the rollback returns t1 to FINISHEDCOPY with its slot gone, so enabling the
subscription leaves its worker at
ERROR: could not start WAL streaming: ERROR: replication slot
"pg_16400_sync_16384_..." does not exist
repeating, because tablesync.c resumes a FINISHEDCOPY relation from that slot,
reading its origin with replorigin_by_name(originname, false). Re-running the
command repairs it: state i, then r, 400001 rows on both sides. I can send the
script if you want to run it.
I have documented it rather than rejecting the mid-sync case, for two reasons.
A relation stuck mid-sync is the main thing this command is for -- a tablesync
that cannot finish is exactly what the user wants to reset -- so rejecting it
would remove the primary use. And the exposure is core's own: both
AlterSubscription_refresh() and DropSubscription() drop tablesync slots at the
very end with missing_ok = true, for the stated reason
/*
* Drop the tablesync slots associated with removed tables. This has
* to be at the end because otherwise if there is an error while doing
* the database operations we won't be able to rollback dropped slots.
*/
and this command does the same, with the slot drops last.
Best regards,
Cagri
On Fri, Oct 23, 2026 at 8:36 AM Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com> wrote:
Hi Cagri,
Sorry for the late reply. I have been busy for PG19 open items.
> Rejecting partitioned roots removes only about fifty lines. It does not
> remove the ancestor locking or the ancestor half of the cross-subscription
> check, which are needed when a leaf is the subscribed table, as it is whenever
> publish_via_partition_root is off. Both problems you found here were in that
> code, so it would stay in 0001 and 0002 would add the easy part. I would
> rather keep one patch, but I will split it if you prefer.
I still prefer the separated patch to make review easier.
> thank you. With C -> B -> A and A on origin = none, the same
> copy made CREATE SUBSCRIPTION warn and REFRESH TABLE stay silent.
> check_publications_origin_tables() skips the tables a subscription already
> has, because those come throuqgh WAL where origins are known, and this command
> is the one thing that puts such a table back through a copy. v10 runs the
> check and passes the subscription's other tables as the skip list, so it warns
> for a table another subscription writes and stays quiet otherwise.
Assuming that there is a bidirectional setup A <-> B, and REFRESH TABLE is done
on node A. In this case the TRUNCATE can be replicated to the node B and table
on both nodes are empty. Tuples are lost after the subscription is enabled
because the copy source does not have ones anymore. Isn't it problematic?
Is there a good method to fix?
My primitive idea is to reject REFRESH command if the target tables are included
in a publication.
Below are new comments:
01.
Assuming that there is a cascading replication: A->B->C and origin=any, and the
publication on B does not publish TRUNCATE. If the REFRESH TABLE is done on B,
the TRUNCATE cannot be replicated but the re-synced data can be replicated again,
can cause the data conflict. Should we solve the issue? Rejecting the REFRESH TABLE
on the intermediate node can solve the issue but may be too aggressive.
02.
Assuming the normal logical replication system A->B, and the REFRESH TABLE is
done while the srsubstate is still FINISHCOPY. If the command fails after dropping
the replication origin and replication slot, the tablesync worker will assume
the slot exists and tries to stream via the slot, it can cause the ERROR.
I think we need to clarify that the REFRESH must be done again if it fails.
Or should we reject the case if the table-sync is ongoing?
Best regards,
Hayato Kuroda
FUJITSU LIMITED
Re: Per-table resync for logical replication subscriptions
От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Mon, 26 Oct 2026 at 02:18, Cagri Biroglu wrote:
>
> Dear Hayato,
>
> Thank you. v12 is attached.
Hi Cagri,
I reviewed the v12-0001 patch and found a possible deadlock when ALTER
SUBSCRIPTION ... REFRESH PUBLICATION and ALTER SUBSCRIPTION ...
REFRESH TABLE run concurrently on two different subscriptions.
Steps to reproduce the issue:
1. On publisher node:
CREATE TABLE t1 (a int);
CREATE TABLE obsolete (a int);
CREATE PUBLICATION pub1 FOR TABLE t1;
CREATE PUBLICATION pub2 FOR TABLE obsolete;
2. On subscriber node:
CREATE TABLE t1 (a int);
CREATE TABLE obsolete (a int);
CREATE SUBSCRIPTION sub1 CONNECTION ... PUBLICATION pub1 WITH
(enabled = false);
CREATE SUBSCRIPTION sub2 CONNECTION ... PUBLICATION pub2;
3. After sub2 is synchronized, change pub2 on the publisher: ALTER
PUBLICATION pub2 SET TABLE t1;
4. Attach GDB to subscriber session A and add a breakpoint before this
code in AlterSubscription_refresh():
if (!rel)
rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
Then run: ALTER SUBSCRIPTION sub2 REFRESH PUBLICATION WITH (copy_data = false);
5. Attach GDB to subscriber session B and add a breakpoint before this
code in AlterSubscription_refresh_table():
foreach_oid(relid, relids)
LockRelationOid(relid, AccessExclusiveLock);
Then run: ALTER SUBSCRIPTION sub1 REFRESH TABLE t1;
Continue session B first, then session A. The sessions wait for each
other, and PostgreSQL reports a deadlock.
The deadlock happens because REFRESH PUBLICATION takes AccessShareLock
on the user table at:
"relid = RangeVarGetRelid(rv, AccessShareLock, false);"
When removing the old table, it requests AccessExclusiveLock on
pg_subscription_rel:
```
if (!rel)
rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
```
At the same time, REFRESH TABLE takes RowExclusiveLock on pg_subscription_rel:
"rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);"
It then requests AccessExclusiveLock on the user table here:
```
foreach_oid(relid, relids)
LockRelationOid(relid, AccessExclusiveLock);
```
So, REFRESH PUBLICATION command waits for lock on pg_subscription_rel
but REFRESH TABLE already have a lock on it
and REFRESH TABLE waits for lock on the user table t1 but REFRESH
PUBLICATION already have an lock on it.
Hence it leads to a deadlock.
Thanks,
Shlok Kyal
Re: Per-table resync for logical replication subscriptions
Hi Shlok ,
thank you , fixed in v13, attached.
REFRESH TABLE held pg_subscription_rel while it waited for a lock on a user
relation. It now takes every relation lock first and opens the catalogue
afterwards, which is the order AlterSubscription_refresh() already uses, so
the cycle cannot form. The lock level was not the problem: RowExclusiveLock
conflicts with the AccessExclusiveLock that command wants there just as
surely.
039 asserts it directly -- while REFRESH TABLE waits on a relation lock it
must hold no lock on pg_subscription_rel -- and then runs your two commands
concurrently in that window. Four of those five checks fail if the change is
reverted, one with "deadlock detected".
The reproduction is attached as poc_refresh_publication_deadlock.sh: your
recipe, without gdb, so it can run unattended. A prepared transaction holds a
second table named in the REFRESH TABLE, which parks the command in its first
pass exactly where your breakpoint was. Can you please confirm ?
B opens pg_subscription_rel, resolves t1, waits on t_block
A takes AccessShareLock on t1, then waits on pg_subscription_rel
X commits, releasing t_block
B asks for AccessExclusiveLock on t1, which A holds -> deadlock detected
Best regards,
Cagri Biroglu
thank you , fixed in v13, attached.
REFRESH TABLE held pg_subscription_rel while it waited for a lock on a user
relation. It now takes every relation lock first and opens the catalogue
afterwards, which is the order AlterSubscription_refresh() already uses, so
the cycle cannot form. The lock level was not the problem: RowExclusiveLock
conflicts with the AccessExclusiveLock that command wants there just as
surely.
039 asserts it directly -- while REFRESH TABLE waits on a relation lock it
must hold no lock on pg_subscription_rel -- and then runs your two commands
concurrently in that window. Four of those five checks fail if the change is
reverted, one with "deadlock detected".
The reproduction is attached as poc_refresh_publication_deadlock.sh: your
recipe, without gdb, so it can run unattended. A prepared transaction holds a
second table named in the REFRESH TABLE, which parks the command in its first
pass exactly where your breakpoint was. Can you please confirm ?
B opens pg_subscription_rel, resolves t1, waits on t_block
A takes AccessShareLock on t1, then waits on pg_subscription_rel
X commits, releasing t_block
B asks for AccessExclusiveLock on t1, which A holds -> deadlock detected
Best regards,
Cagri Biroglu
On Thu, Oct 29, 2026 at 1:32 PM Shlok Kyal <shlok.kyal.oss@gmail.com> wrote:
On Mon, 26 Oct 2026 at 02:18, Cagri Biroglu <cagri.biroglu@adyen.com> wrote:
>
> Dear Hayato,
>
> Thank you. v12 is attached.
Hi Cagri,
I reviewed the v12-0001 patch and found a possible deadlock when ALTER
SUBSCRIPTION ... REFRESH PUBLICATION and ALTER SUBSCRIPTION ...
REFRESH TABLE run concurrently on two different subscriptions.
Steps to reproduce the issue:
1. On publisher node:
CREATE TABLE t1 (a int);
CREATE TABLE obsolete (a int);
CREATE PUBLICATION pub1 FOR TABLE t1;
CREATE PUBLICATION pub2 FOR TABLE obsolete;
2. On subscriber node:
CREATE TABLE t1 (a int);
CREATE TABLE obsolete (a int);
CREATE SUBSCRIPTION sub1 CONNECTION ... PUBLICATION pub1 WITH
(enabled = false);
CREATE SUBSCRIPTION sub2 CONNECTION ... PUBLICATION pub2;
3. After sub2 is synchronized, change pub2 on the publisher: ALTER
PUBLICATION pub2 SET TABLE t1;
4. Attach GDB to subscriber session A and add a breakpoint before this
code in AlterSubscription_refresh():
if (!rel)
rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
Then run: ALTER SUBSCRIPTION sub2 REFRESH PUBLICATION WITH (copy_data = false);
5. Attach GDB to subscriber session B and add a breakpoint before this
code in AlterSubscription_refresh_table():
foreach_oid(relid, relids)
LockRelationOid(relid, AccessExclusiveLock);
Then run: ALTER SUBSCRIPTION sub1 REFRESH TABLE t1;
Continue session B first, then session A. The sessions wait for each
other, and PostgreSQL reports a deadlock.
The deadlock happens because REFRESH PUBLICATION takes AccessShareLock
on the user table at:
"relid = RangeVarGetRelid(rv, AccessShareLock, false);"
When removing the old table, it requests AccessExclusiveLock on
pg_subscription_rel:
```
if (!rel)
rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
```
At the same time, REFRESH TABLE takes RowExclusiveLock on pg_subscription_rel:
"rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);"
It then requests AccessExclusiveLock on the user table here:
```
foreach_oid(relid, relids)
LockRelationOid(relid, AccessExclusiveLock);
```
So, REFRESH PUBLICATION command waits for lock on pg_subscription_rel
but REFRESH TABLE already have a lock on it
and REFRESH TABLE waits for lock on the user table t1 but REFRESH
PUBLICATION already have an lock on it.
Hence it leads to a deadlock.
Thanks,
Shlok Kyal
Re: Per-table resync for logical replication subscriptions
От:
Song Yanli <YanliliSong@outlook.com>
Дата:
At 2026-11-02 04:05:10, "Cagri Biroglu" <cagri.biroglu@adyen.com> wrote:
>Hi Shlok ,
>
>thank you , fixed in v13, attached.
>
>REFRESH TABLE held pg_subscription_rel while it waited for a lock on a user
>relation. It now takes every relation lock first and opens the catalogue
>afterwards, which is the order AlterSubscription_refresh() already uses, so
>the cycle cannot form. The lock level was not the problem: RowExclusiveLock
>conflicts with the AccessExclusiveLock that command wants there just as
>surely.
Hi,
While reviewing the v13 patch, I found that the 039_refresh_table.pl test fails on my local machine.
It appears that case #79 behaves differently from your test results.
I believe the expected output of #79 is not guaranteed by the code logic,
but depends on the completion timing of two concurrent commands.
This is a test race condition.
I tried the following change:
move `$bg_pub->query('SELECT 1')` before `COMMIT PREPARED`
-$node_subscriber->safe_psql('postgres', "COMMIT PREPARED 'refresh_lk'");
-$bg_pub->query('SELECT 1');
-$bg_lk->query('SELECT 1');
+$bg_pub->query('SELECT 1');
+my $row_after = $node_subscriber->safe_psql('postgres',
+ "SELECT count(*) FROM pg_subscription_rel sr
+ JOIN pg_subscription s ON s.oid = sr.srsubid
+ WHERE s.subname = 'tap_sub_lk2'
+ AND sr.srrelid = 'tab_lk1'::regclass");
+diag("B1 after sync: row=$row_after");
+$node_subscriber->safe_psql('postgres', "COMMIT PREPARED 'refresh_lk'");
+$bg_lk->query('SELECT 1');
This ensures that bg_lk is only allowed to proceed after the REFRESH PUBLICATION on bg_pub has committed.
The 039_refresh_table.pl test now passes as expected.
Re: Per-table resync for logical replication subscriptions
От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Mon, 2 Nov 2026 at 01:35, Cagri Biroglu wrote:
>
> Hi Shlok ,
>
> thank you , fixed in v13, attached.
>
> REFRESH TABLE held pg_subscription_rel while it waited for a lock on a user
> relation. It now takes every relation lock first and opens the catalogue
> afterwards, which is the order AlterSubscription_refresh() already uses, so
> the cycle cannot form. The lock level was not the problem: RowExclusiveLock
> conflicts with the AccessExclusiveLock that command wants there just as
> surely.
>
> 039 asserts it directly -- while REFRESH TABLE waits on a relation lock it
> must hold no lock on pg_subscription_rel -- and then runs your two commands
> concurrently in that window. Four of those five checks fail if the change is
> reverted, one with "deadlock detected".
>
> The reproduction is attached as poc_refresh_publication_deadlock.sh: your
> recipe, without gdb, so it can run unattended. A prepared transaction holds a
> second table named in the REFRESH TABLE, which parks the command in its first
> pass exactly where your breakpoint was. Can you please confirm ?
>
> B opens pg_subscription_rel, resolves t1, waits on t_block
> A takes AccessShareLock on t1, then waits on pg_subscription_rel
> X commits, releasing t_block
> B asks for AccessExclusiveLock on t1, which A holds -> deadlock detected
Hi Cagri,
I tested and agree that poc_refresh_publication_deadlock.sh can
reproduce the issue in a deterministic way.
But I also noticed that test 039_refresh_table.pl is failing in my
local machine.
I have also confirmed that the change suggested by Song in [1]
addresses this failure.
Apart from that I have a doubt for v13-0001 patch:
Suppose we have a tablesync in a mid-sync state such as FINISHEDCOPY
or DATASYNC,
And we run ALTER SUBSCRIPTION ... REFRESH TABLE for such a table, and
due to some
reason publisher is down, the following code will drop the replication origin
corresponding to the tablesync:
+ foreach_oid(relid, originrelids)
+ {
+ ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
+ sizeof(originname));
+ replorigin_drop_by_name(originname, true, false);
+ }
But at the later stage, the REFRESH TABLE command will fail as publisher is down
and subscriber will not be able to connect to the publisher:
+ load_file("libpqwalreceiver", false);
+
+ must_use_password = sub->passwordrequired && !sub->ownersuperuser;
+ wrconn = walrcv_connect(SubscriptionConninfo(sub), true, true,
+ must_use_password, sub->name, &err);
+ if (!wrconn)
+ ereport(ERROR,
+ errcode(ERRCODE_CONNECTION_FAILURE),
+ errmsg("subscription \"%s\" could not connect to the publisher: %s",
+ sub->name, err));
+
Since the command failed, the transactional block will rollback: tablesync will
be setback to FINISHEDCOPY/DATASYNC state, the TRUNCATE command will rollback.
But the replication origin status (in pg_replication_origin_status)
will remain dropped.
Is this expected? Could this lead to any unexpected behaviour?
I am able to reproduce the scenario, but I am not able to find any
unexpected behaviour
during my testing. But I am raising the comment to be on the safe side.
[1]: https://www.postgresql.org/message-id/SE2P216MB34109622EC422B7265E5E0AABF6A2%40SE2P216MB3410.KORP216.PROD.OUTLOOK.COM
Thanks,
Shlok Kyal
Re: Per-table resync for logical replication subscriptions
От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Mon, 2 Nov 2026 at 01:35, Cagri Biroglu wrote: > > Hi Shlok , > > thank you , fixed in v13, attached. > Hi Cagri, I further reviewed the v13 patch and found that ALTER SUBSCRIPTION ... REFRESH TABLE truncates the target table by calling ExecuteTruncateGuts(). Consequently, it executes BEFORE TRUNCATE and AFTER TRUNCATE statement-level triggers on that table. For example we have trigger: CREATE TRIGGER t1_truncate_trigger AFTER TRUNCATE ON t1 FOR EACH STATEMENT EXECUTE FUNCTION log_t1_trigger(); And if t1 is part of subscription sub1, 'ALTER SUBSCRIPTION sub1 REFRESH TABLE t1;' can call the above trigger. Is this ok to allow triggers to be called when ALTER SUBSCRIPTION ... REFRESH TABLE executed? I checked if any other ALTER SUBSCRIPTION command can execute any triggers but I did not find any. I noticed that apply workers can execute row-level INSERT, UPDATE, and DELETE triggers, and statement-level TRUNCATE triggers, but only when the table is configured as ENABLE REPLICA or ENABLE ALWAYS. Should we have a similar way for the REFRESH TABLE case as well? Thanks, Shlok Kyal
Re: Per-table resync for logical replication subscriptions
On Tue, 3 Nov 2026 at 15:24, Shlok Kyal wrote: > > On Mon, 2 Nov 2026 at 01:35, Cagri Biroglu wrote: > > > > Hi Shlok , > > > > thank you , fixed in v13, attached. > > > Hi Cagri, > > I further reviewed the v13 patch and found that ALTER SUBSCRIPTION ... > REFRESH TABLE truncates the target table by calling > ExecuteTruncateGuts(). Consequently, it executes BEFORE TRUNCATE and > AFTER TRUNCATE statement-level triggers on that table. > For example we have trigger: > CREATE TRIGGER t1_truncate_trigger > AFTER TRUNCATE ON t1 > FOR EACH STATEMENT EXECUTE FUNCTION log_t1_trigger(); > > And if t1 is part of subscription sub1, 'ALTER SUBSCRIPTION sub1 > REFRESH TABLE t1;' can call the above trigger. > > Is this ok to allow triggers to be called when ALTER SUBSCRIPTION ... > REFRESH TABLE executed? > > I checked if any other ALTER SUBSCRIPTION command can execute any > triggers but I did not find any. > I noticed that apply workers can execute row-level INSERT, UPDATE, and > DELETE triggers, and statement-level TRUNCATE triggers, but only when > the table is configured as ENABLE REPLICA or ENABLE ALWAYS. > Should we have a similar way for the REFRESH TABLE case as well? > I did further testing and was able to hit an Assert. A BEFORE TRUNCATE trigger can change the session replication origin while REFRESH TABLE temporarily changes replorigin_xact_state.origin. AlterSubscription_refresh_table() saves replorigin_xact_state.origin, assigns the subscription origin while truncating and restores the saved value afterward. But, the trigger can reset the corresponding session state. Consequently, the saved origin ID is restored while session_replication_state remains NULL. During commit, replorigin_session_advance() can hit:Assert(session_replication_state != NULL); I have attached a perl test to reproduce the issue. Thanks, Shlok Kyal
Re: Per-table resync for logical replication subscriptions
Dear Shlok,
Thanks for the three reports. All are addressed in v14, attached, rebased
on current master.
A. Publisher down. The progress is in fact lost, even though nothing goes
visibly wrong straight away: v13 dropped the tablesync origin, whose
in-memory progress a rollback does not bring back, and only then failed to
connect. With the relation parked at FINISHEDCOPY, the origin's remote_lsn
went from 0/049107F0 to nothing, so catch-up would later resume from the
slot's confirmed position instead. The command now connects first, then
drops the slots, and drops the origins last, the order the tablesync worker
uses for its own. So a slot drop that fails after connecting also leaves
the origins alone, and an origin is dropped only once its relation has no
slot left to resume from. 039 checks that the progress survives both a
failed connection and a slot drop cancelled on the publisher;
poc_refresh_publisher_down_origin.sh shows the first case standalone.
B. Triggers. I kept TRUNCATE semantics: the command is run in a user's
session, and fires the triggers a TRUNCATE there would. The re-copy is made
by a tablesync worker running as replica, so a trigger that has to see both
halves can be ENABLE ALWAYS. The documentation now says so, and
poc_refresh_trigger_roles.sh shows which trigger fires for which half.
C. The crash. Thanks for the test. I found two more ways in: a FATAL while
a truncate trigger runs (pg_terminate_backend() is enough), and a trigger
whose EXCEPTION block rolls back a subtransaction. All three come from v13
setting the origin for the whole truncate, triggers included, and restoring
it afterwards. The commit and abort paths take a set origin for one
configured in the session and advance it, which fails when there is none:
a trigger has just reset it (your case), or there never was one (the other
two). The origin is now passed to ExecuteTruncateGuts() and set only while
the truncate's WAL record is inserted, so no trigger, error or abort sees
it. 039 covers your case, the other two, and a session with an origin of
its own. As a side effect, what the triggers write is no longer attributed
to the subscription's origin.
Also in v14: Song's fix to the lock-order test, and 039/040 run through
pgperltidy, which accounts for some of the noise in the test diff.
Best regards,
Cagri Biroglu
Thanks for the three reports. All are addressed in v14, attached, rebased
on current master.
A. Publisher down. The progress is in fact lost, even though nothing goes
visibly wrong straight away: v13 dropped the tablesync origin, whose
in-memory progress a rollback does not bring back, and only then failed to
connect. With the relation parked at FINISHEDCOPY, the origin's remote_lsn
went from 0/049107F0 to nothing, so catch-up would later resume from the
slot's confirmed position instead. The command now connects first, then
drops the slots, and drops the origins last, the order the tablesync worker
uses for its own. So a slot drop that fails after connecting also leaves
the origins alone, and an origin is dropped only once its relation has no
slot left to resume from. 039 checks that the progress survives both a
failed connection and a slot drop cancelled on the publisher;
poc_refresh_publisher_down_origin.sh shows the first case standalone.
B. Triggers. I kept TRUNCATE semantics: the command is run in a user's
session, and fires the triggers a TRUNCATE there would. The re-copy is made
by a tablesync worker running as replica, so a trigger that has to see both
halves can be ENABLE ALWAYS. The documentation now says so, and
poc_refresh_trigger_roles.sh shows which trigger fires for which half.
C. The crash. Thanks for the test. I found two more ways in: a FATAL while
a truncate trigger runs (pg_terminate_backend() is enough), and a trigger
whose EXCEPTION block rolls back a subtransaction. All three come from v13
setting the origin for the whole truncate, triggers included, and restoring
it afterwards. The commit and abort paths take a set origin for one
configured in the session and advance it, which fails when there is none:
a trigger has just reset it (your case), or there never was one (the other
two). The origin is now passed to ExecuteTruncateGuts() and set only while
the truncate's WAL record is inserted, so no trigger, error or abort sees
it. 039 covers your case, the other two, and a session with an origin of
its own. As a side effect, what the triggers write is no longer attributed
to the subscription's origin.
Also in v14: Song's fix to the lock-order test, and 039/040 run through
pgperltidy, which accounts for some of the noise in the test diff.
Best regards,
Cagri Biroglu
On Tue, Nov 3, 2026 at 3:37 PM Shlok Kyal <shlok.kyal.oss@gmail.com> wrote:
On Tue, 3 Nov 2026 at 15:24, Shlok Kyal <shlok.kyal.oss@gmail.com> wrote:
>
> On Mon, 2 Nov 2026 at 01:35, Cagri Biroglu <cagri.biroglu@adyen.com> wrote:
> >
> > Hi Shlok ,
> >
> > thank you , fixed in v13, attached.
> >
> Hi Cagri,
>
> I further reviewed the v13 patch and found that ALTER SUBSCRIPTION ...
> REFRESH TABLE truncates the target table by calling
> ExecuteTruncateGuts(). Consequently, it executes BEFORE TRUNCATE and
> AFTER TRUNCATE statement-level triggers on that table.
> For example we have trigger:
> CREATE TRIGGER t1_truncate_trigger
> AFTER TRUNCATE ON t1
> FOR EACH STATEMENT EXECUTE FUNCTION log_t1_trigger();
>
> And if t1 is part of subscription sub1, 'ALTER SUBSCRIPTION sub1
> REFRESH TABLE t1;' can call the above trigger.
>
> Is this ok to allow triggers to be called when ALTER SUBSCRIPTION ...
> REFRESH TABLE executed?
>
> I checked if any other ALTER SUBSCRIPTION command can execute any
> triggers but I did not find any.
> I noticed that apply workers can execute row-level INSERT, UPDATE, and
> DELETE triggers, and statement-level TRUNCATE triggers, but only when
> the table is configured as ENABLE REPLICA or ENABLE ALWAYS.
> Should we have a similar way for the REFRESH TABLE case as well?
>
I did further testing and was able to hit an Assert.
A BEFORE TRUNCATE trigger can change the session replication origin
while REFRESH TABLE temporarily changes replorigin_xact_state.origin.
AlterSubscription_refresh_table() saves replorigin_xact_state.origin,
assigns the subscription origin while truncating and restores the
saved value afterward. But, the trigger can reset the corresponding
session state. Consequently, the saved origin ID is restored while
session_replication_state remains NULL.
During commit, replorigin_session_advance() can
hit:Assert(session_replication_state != NULL);
I have attached a perl test to reproduce the issue.
Thanks,
Shlok Kyal
Re: Per-table resync for logical replication subscriptions
Hi,
Test was failing again for macos (while waiting for
the slow truncate trigger: "Timed out waiting for the truncate trigger to
start".)
That job is the only one that runs with debug_parallel_query = regress.
pg_sleep() is parallel safe, so the trigger's PERFORM pg_sleep() ran in a
parallel worker, and the session itself waited in ExecuteGather. The test
looked for the PgSleep wait event only in the session, so it never saw it.
Running 039 locally with the initdb options of that job fails the same
way, right after test 62.
Attaching v15.
Best regards,
Cagri Biroglu
Test was failing again for macos (while waiting for
the slow truncate trigger: "Timed out waiting for the truncate trigger to
start".)
That job is the only one that runs with debug_parallel_query = regress.
pg_sleep() is parallel safe, so the trigger's PERFORM pg_sleep() ran in a
parallel worker, and the session itself waited in ExecuteGather. The test
looked for the PgSleep wait event only in the session, so it never saw it.
Running 039 locally with the initdb options of that job fails the same
way, right after test 62.
Attaching v15.
Best regards,
Cagri Biroglu
On Fri, Nov 6, 2026 at 1:07 PM Cagri Biroglu <cagri.biroglu@adyen.com> wrote:
Dear Shlok,
Thanks for the three reports. All are addressed in v14, attached, rebased
on current master.
A. Publisher down. The progress is in fact lost, even though nothing goes
visibly wrong straight away: v13 dropped the tablesync origin, whose
in-memory progress a rollback does not bring back, and only then failed to
connect. With the relation parked at FINISHEDCOPY, the origin's remote_lsn
went from 0/049107F0 to nothing, so catch-up would later resume from the
slot's confirmed position instead. The command now connects first, then
drops the slots, and drops the origins last, the order the tablesync worker
uses for its own. So a slot drop that fails after connecting also leaves
the origins alone, and an origin is dropped only once its relation has no
slot left to resume from. 039 checks that the progress survives both a
failed connection and a slot drop cancelled on the publisher;
poc_refresh_publisher_down_origin.sh shows the first case standalone.
B. Triggers. I kept TRUNCATE semantics: the command is run in a user's
session, and fires the triggers a TRUNCATE there would. The re-copy is made
by a tablesync worker running as replica, so a trigger that has to see both
halves can be ENABLE ALWAYS. The documentation now says so, and
poc_refresh_trigger_roles.sh shows which trigger fires for which half.
C. The crash. Thanks for the test. I found two more ways in: a FATAL while
a truncate trigger runs (pg_terminate_backend() is enough), and a trigger
whose EXCEPTION block rolls back a subtransaction. All three come from v13
setting the origin for the whole truncate, triggers included, and restoring
it afterwards. The commit and abort paths take a set origin for one
configured in the session and advance it, which fails when there is none:
a trigger has just reset it (your case), or there never was one (the other
two). The origin is now passed to ExecuteTruncateGuts() and set only while
the truncate's WAL record is inserted, so no trigger, error or abort sees
it. 039 covers your case, the other two, and a session with an origin of
its own. As a side effect, what the triggers write is no longer attributed
to the subscription's origin.
Also in v14: Song's fix to the lock-order test, and 039/040 run through
pgperltidy, which accounts for some of the noise in the test diff.
Best regards,
Cagri BirogluOn Tue, Nov 3, 2026 at 3:37 PM Shlok Kyal <shlok.kyal.oss@gmail.com> wrote:On Tue, 3 Nov 2026 at 15:24, Shlok Kyal <shlok.kyal.oss@gmail.com> wrote:
>
> On Mon, 2 Nov 2026 at 01:35, Cagri Biroglu <cagri.biroglu@adyen.com> wrote:
> >
> > Hi Shlok ,
> >
> > thank you , fixed in v13, attached.
> >
> Hi Cagri,
>
> I further reviewed the v13 patch and found that ALTER SUBSCRIPTION ...
> REFRESH TABLE truncates the target table by calling
> ExecuteTruncateGuts(). Consequently, it executes BEFORE TRUNCATE and
> AFTER TRUNCATE statement-level triggers on that table.
> For example we have trigger:
> CREATE TRIGGER t1_truncate_trigger
> AFTER TRUNCATE ON t1
> FOR EACH STATEMENT EXECUTE FUNCTION log_t1_trigger();
>
> And if t1 is part of subscription sub1, 'ALTER SUBSCRIPTION sub1
> REFRESH TABLE t1;' can call the above trigger.
>
> Is this ok to allow triggers to be called when ALTER SUBSCRIPTION ...
> REFRESH TABLE executed?
>
> I checked if any other ALTER SUBSCRIPTION command can execute any
> triggers but I did not find any.
> I noticed that apply workers can execute row-level INSERT, UPDATE, and
> DELETE triggers, and statement-level TRUNCATE triggers, but only when
> the table is configured as ENABLE REPLICA or ENABLE ALWAYS.
> Should we have a similar way for the REFRESH TABLE case as well?
>
I did further testing and was able to hit an Assert.
A BEFORE TRUNCATE trigger can change the session replication origin
while REFRESH TABLE temporarily changes replorigin_xact_state.origin.
AlterSubscription_refresh_table() saves replorigin_xact_state.origin,
assigns the subscription origin while truncating and restores the
saved value afterward. But, the trigger can reset the corresponding
session state. Consequently, the saved origin ID is restored while
session_replication_state remains NULL.
During commit, replorigin_session_advance() can
hit:Assert(session_replication_state != NULL);
I have attached a perl test to reproduce the issue.
Thanks,
Shlok Kyal
Re: Per-table resync for logical replication subscriptions
От:
shveta malik <shveta.malik@gmail.com>
Дата:
Hi, I agree with the idea of the patch and the need for this feature. While looking at this from the angle of [1], I noticed that REFRESH TABLE only looks at the subscriber’s pg_subscription_rel; it does not check whether the named table is still published by any of the subscription’s publications. I tried v15 (with the fix from [1] applied): sync tab1 (using test given in [1]), then on the publisher ALTER PUBLICATION pub1 DROP TABLE tab1, then on the subscriber DISABLE + REFRESH TABLE tab1. The command succeeds, truncates tab1 (5 rows -> 0) and resets it to 'i'. After ENABLE, tablesync fails because the table is no longer published, so the local data is gone and won’t be copied back unless the table is published again and error raised by [1] is also not resolved. With disable_on_error = true, the subscription is disabled again, and repeating REFRESH TABLE just repeats this. Since REFRESH TABLE is a per-table refresh, I would expect it to also reconcile the table with the publications, similar to REFRESH PUBLICATION: if the named table is no longer published by any of the subscription’s publications, it should be removed from the subscription instead of being truncated and re-copied. At a minimum, the command should verify with the publisher that each named table is still published before truncating it, and error out otherwise. Thoughts? [1]: https://www.postgresql.org/message-id/CAJpy0uAWSLH-SMeH0JoqvGACv8truSfXiwFp4PCkTJE93CGigA%40mail.gmail.com (Thanks Peter for pointing me to this thread and for the off-list discussion on this.) thanks Shveta
Re: Per-table resync for logical replication subscriptions
От:
Cagri Biroglu <cagri.biroglu@adyen.com>
Дата:
Hi Shveta,
Thanks, and thanks Peter for pointing you here. Having followed [1],
I agree it is a use case: with your reproducer on master today the
table is copied whole, and once the publication is back, REFRESH
TABLE re-copies just that table with its column list and row filter.
It would also be how to copy a skipped table, if [1] later moves to a
WARNING as Peter suggested.
For the case you describe, I would keep REFRESH TABLE as it is and
rely on [1]:
- With [1], the re-seeded table ends where [1] leaves any table whose
initial sync finds it unpublished: it stays in 'd', nothing is
copied, and "with the ERROR the next retry simply syncs it" once it
is published again, as you said in [1]. If it stays unpublished,
the way out, with disable_on_error too, is the one your v4-0002
documents. I tested both on v15 with your v4.
- Removing it has the problems you gave in [1] against the worker
doing it: a table published again stays out until someone runs
REFRESH PUBLICATION, and a per-table removal is only a partial
refresh, e.g. after a publish_via_partition_root change it would
drop the partitions without adding the root.
- A check with the publisher first cannot replace [1], since the
table can be unpublished right after it, and every REFRESH TABLE
would have to connect; for ready tables under origin = any it does
not today. Done with fetch_relation_list(), it also has the
publisher open every published table, the cost fd7a25af11e took out
of tablesync: about 160 ms for a FOR ALL TABLES publication of 50k
tables here, and it waits behind an ACCESS EXCLUSIVE lock on any of
them.
REFRESH TABLE is meant for a table that is still published and
replicating but has drifted, and when to reconcile membership stays
with the user, as with REFRESH SEQUENCES. So in the next version I
would add the note REFRESH SEQUENCES has, to run REFRESH PUBLICATION
first if the publication's set of tables has changed; a table it
removes is then refused by REFRESH TABLE without being truncated.
Best regards,
Cagri Biroglu
Thanks, and thanks Peter for pointing you here. Having followed [1],
I agree it is a use case: with your reproducer on master today the
table is copied whole, and once the publication is back, REFRESH
TABLE re-copies just that table with its column list and row filter.
It would also be how to copy a skipped table, if [1] later moves to a
WARNING as Peter suggested.
For the case you describe, I would keep REFRESH TABLE as it is and
rely on [1]:
- With [1], the re-seeded table ends where [1] leaves any table whose
initial sync finds it unpublished: it stays in 'd', nothing is
copied, and "with the ERROR the next retry simply syncs it" once it
is published again, as you said in [1]. If it stays unpublished,
the way out, with disable_on_error too, is the one your v4-0002
documents. I tested both on v15 with your v4.
- Removing it has the problems you gave in [1] against the worker
doing it: a table published again stays out until someone runs
REFRESH PUBLICATION, and a per-table removal is only a partial
refresh, e.g. after a publish_via_partition_root change it would
drop the partitions without adding the root.
- A check with the publisher first cannot replace [1], since the
table can be unpublished right after it, and every REFRESH TABLE
would have to connect; for ready tables under origin = any it does
not today. Done with fetch_relation_list(), it also has the
publisher open every published table, the cost fd7a25af11e took out
of tablesync: about 160 ms for a FOR ALL TABLES publication of 50k
tables here, and it waits behind an ACCESS EXCLUSIVE lock on any of
them.
REFRESH TABLE is meant for a table that is still published and
replicating but has drifted, and when to reconcile membership stays
with the user, as with REFRESH SEQUENCES. So in the next version I
would add the note REFRESH SEQUENCES has, to run REFRESH PUBLICATION
first if the publication's set of tables has changed; a table it
removes is then refused by REFRESH TABLE without being truncated.
Best regards,
Cagri Biroglu
On Thu, Nov 19, 2026 at 5:45 AM shveta malik <shveta.malik@gmail.com> wrote:
Hi,
I agree with the idea of the patch and the need for this feature.
While looking at this from the angle of [1], I noticed that REFRESH
TABLE only looks at the subscriber’s pg_subscription_rel; it does not
check whether the named table is still published by any of the
subscription’s publications.
I tried v15 (with the fix from [1] applied): sync tab1 (using test
given in [1]), then on the publisher ALTER PUBLICATION pub1 DROP TABLE
tab1, then on the subscriber DISABLE + REFRESH TABLE tab1. The command
succeeds, truncates tab1 (5 rows -> 0) and resets it to 'i'.
After ENABLE, tablesync fails because the table is no longer
published, so the local data is gone and won’t be copied back unless
the table is published again and error raised by [1] is also not
resolved. With disable_on_error = true, the subscription is disabled
again, and repeating REFRESH TABLE just repeats this.
Since REFRESH TABLE is a per-table refresh, I would expect it to also
reconcile the table with the publications, similar to REFRESH
PUBLICATION: if the named table is no longer published by any of the
subscription’s publications, it should be removed from the
subscription instead of being truncated and re-copied. At a minimum,
the command should verify with the publisher that each named table is
still published before truncating it, and error out otherwise.
Thoughts?
[1]: https://www.postgresql.org/message-id/CAJpy0uAWSLH-SMeH0JoqvGACv8truSfXiwFp4PCkTJE93CGigA%40mail.gmail.com
(Thanks Peter for pointing me to this thread and for the off-list
discussion on this.)
thanks
Shveta
Re: Per-table resync for logical replication subscriptions
От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Sat, Nov 21, 2026 at 11:41 PM Cagri Biroglu wrote: > > Hi Shveta, > > Thanks, and thanks Peter for pointing you here. Having followed [1], > I agree it is a use case: with your reproducer on master today the > table is copied whole, and once the publication is back, REFRESH > TABLE re-copies just that table with its column list and row filter. > It would also be how to copy a skipped table, if [1] later moves to a > WARNING as Peter suggested. Agreed. > For the case you describe, I would keep REFRESH TABLE as it is and > rely on [1]: > > - With [1], the re-seeded table ends where [1] leaves any table whose > initial sync finds it unpublished: it stays in 'd', nothing is > copied, and "with the ERROR the next retry simply syncs it" once it > is published again, as you said in [1]. If it stays unpublished, > the way out, with disable_on_error too, is the one your v4-0002 > documents. I tested both on v15 with your v4. The end state is the same, but the difference lies in what happens to the data beforehand. With [1] alone, nothing is lost: the sync fails and the local rows stay. REFRESH TABLE, however, truncates them first and then hits the same error, so it turns a harmless "not published" state into data loss. The same happens independently of [1] when the table is dropped on the publisher: REFRESH TABLE truncates it, and the sync then keeps failing with "table ... not found on publisher". The error itself is right, but by the time it is raised, the subscriber's data is already lost, before the user can do anything about it. > > - Removing it has the problems you gave in [1] against the worker > doing it: a table published again stays out until someone runs > REFRESH PUBLICATION, and a per-table removal is only a partial > refresh, e.g. after a publish_via_partition_root change it would > drop the partitions without adding the root. Agreed, a per-table removal is only a partial refresh. I am fine with not doing it in REFRESH TABLE. > > - A check with the publisher first cannot replace [1], since the > table can be unpublished right after it, and every REFRESH TABLE > would have to connect; for ready tables under origin = any it does > not today. Agreed, it can't replace [1], and it is not meant to. It only avoids discarding data on a request that is already invalid when it is made; [1] remains the safety net for later changes. The connection is needed anyway; the command exists to copy the table again from the pub. If the publisher can't be reached, the table can't be refilled either, so IMO, it is better to fail before truncating. > Done with fetch_relation_list(), it also has the > publisher open every published table, the cost fd7a25af11e took out > of tablesync: about 160 ms for a FOR ALL TABLES publication of 50k > tables here, and it waits behind an ACCESS EXCLUSIVE lock on any of > them. The cost need not be that of fetch_relation_list(). The check can use the same per-table lookups as tablesync; look up the table by name, then call pg_get_publication_tables() with the publication names and the table's OID (the form added by fd7a25af11e). The check could occur just before the truncate. It can't rule out a table being unpublished right after it or before the copy at ENABLE, but that is a concurrent change on the publisher, which [1] already handles with an error. The aim is narrower: REFRESH TABLE should not discard the local data when the table is already not published at the time it is run, which is the case a user is far more likely to hit. Thoughts? > > REFRESH TABLE is meant for a table that is still published and > replicating but has drifted, and when to reconcile membership stays > with the user, as with REFRESH SEQUENCES. So in the next version I > would add the note REFRESH SEQUENCES has, to run REFRESH PUBLICATION > first if the publication's set of tables has changed; a table it > removes is then refused by REFRESH TABLE without being truncated. The note helps a user who knows the set of tables has changed, not one who doesn't, e.g. when someone else manages the publisher. Such a user, seeing the sync fail, may well run REFRESH TABLE to fix it and lose the rows. The patch already refuses a table fed by another subscription "rather than silently losing data"; IMO the same reasoning applies here. [1]: https://www.postgresql.org/message-id/CAJpy0uAWSLH-SMeH0JoqvGACv8truSfXiwFp4PCkTJE93CGigA%40mail.gmail.com ~~ Overall, my only concern is the TRUNCATE part: the command should not end up discarding the local data for an invalid request. Kindly let me know if this has already been discussed earlier in the thread, as I haven't had a chance to read it completely. thanks Shveta