logical decoding: skip unnecessary snapshot distribution.

Поиск
Список
Период
Сортировка
Искать

logical decoding: skip unnecessary snapshot distribution.

От:
"yangboyu" <yangboyu.yby@alibaba-inc.com>
Дата:
Вложения:
Hi hackers,

I recently hit a disk bloat issue caused by logical decoding:
(1) A cluster has two databases, db1 and db2.  There is a single
    logical replication slot on db1 while db2 holds plenty of tables.
(2) A long-running transaction sits open in db2, pinning the xmin of
    the historic snapshots during decoding.
(3) db2's tables get ANALYZEd -- manual run over all tables.
    Each analyzed table commits separately and writes pg_statistic,
    pg_statistic_ext and pg_class row, so every such commit is a
    catalog-changing commit carrying invalidation messages.
(4) Every one of these commits makes the decoding session of db1's
    slot rebuild its historic snapshot and distribute it to every
    in-progress transaction in its reorder buffer -- including db2's
    long transaction, whose changes the slot will never decode however.
    Since xmin is pinned, the distributed snapshot's xip array grows,
    the snapshot handed out by the k-th ANALYZE commit is O(k) in size,
    and with the total spill files grow O(k^2), even though the slot's
    own database is completely idle.

Note that a decoding session is connected to a single database and can only
reads that database's catalogs plus the shared catalogs, so changes on other
databases' catalog doesn't need a snapshot rebuild and distribution. The
attached patch exploits this: in DecodeCommit(), if the committing
transaction's dbId differs from the slot's database and none of the
commit record's invalidation messages touches a shared catalog, it skips
both the snapshot rebuild and the distribution.

Correctness relies on that, every write to a shared catalog
produces invalidation messages, SHAREDINVALSNAPSHOT_ID or
SHAREDINVALRELCACHE_ID.

Repro/measurement (script attached): one test_decoding slot on db1;
3000 tables created in db2; a long transaction open in db2; then a
single ANALYZE over all of db2's tables, which commits each table
separately (logical_decoding_work_mem = 64kB); finally decode the WAL
with the slot.  spill_bytes from pg_stat_replication_slots for db1's
slot:
    master          ~19 MB
    patched         0

So the slot of an idle database is completely unaffected by another
database's ANALYZE traffic or other operations that can generate
invalidation messages, while decoding of its own database's
catalog changes is unchanged.

Any feedback is appreciated.

Regards,
Boyu Yang


Re: logical decoding: skip unnecessary snapshot distribution.

От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Wed, 9 Sept 2026 at 13:22, 杨伯宇(长堂)  wrote:
>
> Hi Shlok,
> Thanks for your review.
> > S1: BEGIN;
> > S1: INSERT INTO t1 VALUES(11);
> > S2: BEGIN;
> > S2: ALTER TABLE t2 RENAME TO t2_new;
> > S2: SAVEPOINT s1;
> > S2: ALTER ROLE role1 RENAME TO role1_new;
> > S2 ROLLBACK TO SAVEPOINT s1;
> > S2: COMMIT;
> >
> > Now I debugged DecodeCommit for transaction in S2,
> > It displayed parsed->nmsg = 10.
> > Now I continued debugging and in 'SnapBuildDistributeSnapshotAndInval', we have:
> > ninvalidations = ReorderBufferGetInvalidations(builder->reorder, xid, &msgs);
> > Here, invalidations = 13.
> > The first 10 invalidation messages in msgs were the same as
> > parsed->msgs, but there were 3 additional messages. These additional
> > messages had dbId = 0, indicating shared-catalog invalidations (I
> > assume it is due to ALTER ROLE command).
> >
> > With the patch, InvalidationsTouchSharedCatalog(parsed->nmsgs,
> > parsed->msgs) would therefore see only the first 10 messages, return
> > false, and distribute would be set to false. The 3 shared-catalog
> > invalidations returned by ReorderBufferGetInvalidations() would
> > consequently not be distributed.
> > Is this expected behavior? Thoughts?
> Yes, it's expected.
> parsed->msgs comes from the COMMIT WAL record, which carries only the
> invalidation messages that survive to commit. When a subtransaction
> aborts, AtEOSubXact_Inval(false) drops its messages instead of
> propagating them to the parent. That is why parsed->nmsgs is 10.
> ReorderBufferGetInvalidations(), on the other hand, returns the
> accumulated set of the top-level transaction. While decoding an
> XLOG_XACT_INVALIDATIONS record, its messages are merged into the
> top-level transaction's invalidation array (rbtxn_get_toptxn() in
> ReorderBufferAddInvalidations()), and that merge is irreversible: when
> the subtransaction's abort record is later decoded,
> ReorderBufferAbort() only cleans up the subtransaction's own reorder
> buffer entry and cannot retract the messages already merged into the
> top-level one. That is why it returns 13.
> So, not distributing the invalidations of an aborted subxact
> causes no correctness issue in this patch, because those catalog
> changes were never committed.

Hi Boyu,
Thanks for the detailed explanation. The explanation makes sense to me.

I have one more doubt:
For a SHAREDINVALRELCACHE_ID message, dbId == InvalidOid and
relId == InvalidOid mean "invalidate the whole relcache".  They do not mean
that a shared relation changed.  CacheInvalidateRelcacheAll() creates this
message for publication DDL, such as ALTER PUBLICATION ... SET ALL TABLES.

InvalidationsTouchSharedCatalog() returns true for this message.  Therefore,
for a commit from another database, 'distribute' stays true and the snapshot
and invalidations are still distributed.

Since this message alone does not mean that a shared catalog changed, should
we ignore it when deciding whether to distribute changes from another
database?

Thanks,
Shlok Kyal


Re:logical decoding: skip unnecessary snapshot distribution.

От:
"杨伯宇(长堂)" <yangboyu.yby@alibaba-inc.com>
Дата:
Вложения:
Hi shihao,
    
Thanks for the review. Attached is v2 of the patch.
    
> 1. InvalidationsTouchSharedCatalog() should switch on msg->id with a
>    default: elog(ERROR, ...).  A new message type would otherwise be
>    silently treated as "not shared".  The SHAREDINVALSMGR_ID branch is
>    dead code.
    
Yes, I choose a if-else style which follows the LocalExecuteInvalidationMessage().
    
> 2. The dbId test contradicts DecodeTXNNeedSkip() just below, which
>    treats InvalidOid as "don't assume another database".
    
Yes, (dbId == InvalidOid) is now excluded.
    
> 3. "distribute" controls both the rebuild and the distribution; please
>    rename or split it, and put the justification in a comment rather
>    than only in the commit message.
    
"distribute" is renamed to "catalog_changes_relevant" to express the exact
meaning. Also, the code to "build a historic snapshot" in SnapBuildCommitTxn()
is now fully controlled by catalog_changes_relevant. I think this is clearer way.
    
> 4. Tests: a TAP test with two databases doing shared-catalog DDL in db2
>    while a transaction is in progress in db1, plus Shlok's savepoint
>    case.
    
A new test is added.
    
Regards,
Boyu Yang

回复:logical decoding: skip unnecessary snapshot distribution.

От:
"yangboyu" <yangboyu.yby@alibaba-inc.com>
Дата:

Hi Shlok, 
> For a SHAREDINVALRELCACHE_ID message, dbId == InvalidOid and
> relId == InvalidOid mean "invalidate the whole relcache".  They do not mean
> that a shared relation changed.  CacheInvalidateRelcacheAll() creates this
> message for publication DDL, such as ALTER PUBLICATION ... SET ALL TABLES.
> 
> InvalidationsTouchSharedCatalog() returns true for this message.  Therefore,
> for a commit from another database, 'distribute' stays true and the snapshot
> and invalidations are still distributed.
> 
> Since this message alone does not mean that a shared catalog changed, should
> we ignore it when deciding whether to distribute changes from another
> database?
    
Your observation is right. And in my idea, it's better to be conservative here.
    
Considering the meaning of CacheInvalidateRelcacheAll(), all relcaches contain
the relcaches of shared relations, such as pg_database. So such invalidation
message should be sent to all backends. While for publication DDLs, as there
is not a "CacheInvalidateLocalRelcacheAll()", CacheInvalidateRelcacheAll() is a
reasonable way to invalidate all local tables' relcache.
    
Although publication ddls are now the only caller of CacheInvalidateRelcacheAll(),
I think it's more reasonable to regard it as a shared catalog change. And
LocalExecuteInvalidationMessage() is also in the same way.
    
Regards,
Boyu Yang

Re: logical decoding: skip unnecessary snapshot distribution.

От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
Вложения:
On Fri, 16 Oct 2026 at 09:21, yangboyu  wrote:
>
>
> Hi Shlok,
> > For a SHAREDINVALRELCACHE_ID message, dbId == InvalidOid and
> > relId == InvalidOid mean "invalidate the whole relcache".  They do not mean
> > that a shared relation changed.  CacheInvalidateRelcacheAll() creates this
> > message for publication DDL, such as ALTER PUBLICATION ... SET ALL TABLES.
> >
> > InvalidationsTouchSharedCatalog() returns true for this message.  Therefore,
> > for a commit from another database, 'distribute' stays true and the snapshot
> > and invalidations are still distributed.
> >
> > Since this message alone does not mean that a shared catalog changed, should
> > we ignore it when deciding whether to distribute changes from another
> > database?
>
> Your observation is right. And in my idea, it's better to be conservative here.
>
> Considering the meaning of CacheInvalidateRelcacheAll(), all relcaches contain
> the relcaches of shared relations, such as pg_database. So such invalidation
> message should be sent to all backends. While for publication DDLs, as there
> is not a "CacheInvalidateLocalRelcacheAll()", CacheInvalidateRelcacheAll() is a
> reasonable way to invalidate all local tables' relcache.
>
> Although publication ddls are now the only caller of CacheInvalidateRelcacheAll(),
> I think it's more reasonable to regard it as a shared catalog change. And
> LocalExecuteInvalidationMessage() is also in the same way.
>
Hi Boyu,

I agree with you. I reviewed the v2 patch. Here are some comments:

1. I think we can improve the debug message in:
+ elog(DEBUG1,
+ "transaction %u committed in database %u %s catalog changes relevant",
+ xid, parsed->dbId,
+ catalog_changes_relevant ? "has" : "does not have");
Maybe we can change "catalog changes relevant" to relevant catalog changes"?

2. In the 002_two_databases.pl, we can club multiple commands:
+$node->safe_psql('db2', 'CREATE TABLE t2(a int)');
+$node->safe_psql('db2', 'CREATE ROLE regress_role1');
+$node->safe_psql('db2', 'CREATE PUBLICATION pub0 FOR ALL TABLES');
like:
$node->safe_psql(
'db2', qq[
CREATE TABLE t2(a int);
CREATE ROLE regress_role1;
CREATE PUBLICATION pub0 FOR ALL TABLES;
]);
There are multiple places we can do the same.

3. Multiple test use the similar statement:
+my $session1 = $node->background_psql('db1', on_error_stop => 1);
+$session1->query_safe('BEGIN');
+$session1->query_safe('INSERT INTO t1 VALUES (1)');
Maybe we can create a common function for it?

4. The patch requires pgperltidy runs.

I have made changes for the above changes. If you agree feel free to
include the change.

Thanks,
Shlok Kyal

Re:logical decoding: skip unnecessary snapshot distribution.

От:
"yangboyu" <yangboyu.yby@alibaba-inc.com>
Дата:
Вложения:
Hi Shlok,
    
Thanks very much for the review; the patch is very helpful.
Attached is v3 of the patch 
    
> 1. I think we can improve the debug message in:
> + elog(DEBUG1,
> + "transaction %u committed in database %u %s catalog changes relevant",
> + xid, parsed->dbId,
> + catalog_changes_relevant ? "has" : "does not have");
> Maybe we can change "catalog changes relevant" to relevant
> catalog changes"?
    
Agreed and applied.  The message now reads "has relevant catalog
changes" or "does not have relevant catalog changes"
    

> 2. In the 002_two_databases.pl, we can club multiple commands:
> +$node->safe_psql('db2', 'CREATE TABLE t2(a int)');
> +$node->safe_psql('db2', 'CREATE ROLE regress_role1');
> +$node->safe_psql('db2', 'CREATE PUBLICATION pub0 FOR ALL TABLES');
> like:
> $node->safe_psql(
> 'db2', qq[
> CREATE TABLE t2(a int);
> CREATE ROLE regress_role1;
> CREATE PUBLICATION pub0 FOR ALL TABLES;
> ]);
> There are multiple places we can do the same.
    
Agreed and applied.  The setup statements are grouped into one
safe_psql() call per database.
    
    
> 3. Multiple test use the similar statement:
> +my $session1 = $node->background_psql('db1', on_error_stop => 1);
> +$session1->query_safe('BEGIN');
> +$session1->query_safe('INSERT INTO t1 VALUES (1)');
> Maybe we can create a common function for it?
    
I would rather keep BEGIN at the call site. In most tests, BEGIN marks
where concurrency control starts. And a common function saves little
code. Following the existing tests and your second advice, I send
query_safe('BEGIN; ') inline.
    
    
> 4. The patch requires pgperltidy runs.
    
Agreed and applied.
    
    
Regards,
Boyu Yang
FAQ