logical decoding: skip unnecessary snapshot distribution.

Started by 杨伯宇(长堂)3 months ago12 messageshackers

Thread notes

1 note#performance#moderate#enhancement
hackorum-bot#performance#moderate#enhancement
hackorum-bot
2 days ago

@global #performance #moderate #enhancement

#performance#moderate#enhancement
Jump to latest
#1杨伯宇(长堂)
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

Attachments:

t253615_1
0001-Skip-snapshot-distribution-for-catalog-commits-in-ot.patchapplication/octet-streamDownload+72-15
reproduce_spill_email.shapplication/octet-streamDownload
#2Shlok Kyal
shlok.kyal.oss@gmail.com
In reply to: 杨伯宇(长堂) (#1)
Re: logical decoding: skip unnecessary snapshot distribution.

On Mon, 31 Aug 2026 at 12:33, yangboyu <yangboyu.yby@alibaba-inc.com> wrote:

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.

Hi,

I started to review the patch. And some have doubts.
In the following code:
+ if (parsed->dbId != ctx->slot->data.database &&
+ !InvalidationsTouchSharedCatalog(parsed->nmsgs, parsed->msgs))
+ distribute = false;
We are checking parsed->msgs for any invalidation message for shared catalog.

But when we are actually distributing the invalidation, we are using:
```
if (txn->xid != xid)
{
uint32 ninvalidations;
SharedInvalidationMessage *msgs = NULL;

ninvalidations = ReorderBufferGetInvalidations(builder->reorder,
xid, &msgs);

if (ninvalidations > 0)
{
Assert(msgs != NULL);

ReorderBufferAddDistributedInvalidations(builder->reorder,
txn->xid, lsn, ninvalidations, msgs);
}
}
```

Can the invalidations returned by ReorderBufferGetInvalidations()
differ from parsed->msgs?
More specifically, can parsed->msgs miss an invalidation related to a
shared catalog, while that invalidation is present in the
ReorderBuffer? If so, InvalidationsTouchSharedCatalog() could return
false and distribute would be set to false, causing us to skip
distribution of an invalidation that is actually needed.

I actually tried a case on HEAD. Suppose S1 and S2 are two psql
sessions. And suppose we execute it in this order:
Session S1 and S2 are running on separate databases db1 and db2. And
logical replication is setup in db1.
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?

Thanks,
Shlok Kyal

#3shihao zhong
zhong950419@gmail.com
In reply to: Shlok Kyal (#2)
Re: logical decoding: skip unnecessary snapshot distribution.

Hi Boyu,

I ran your patch with your reproducer on current master and got
the same result you reported. I have about 19 MB of spill without the
patch, and 0 with it.

Also, FYI: there is another thread working on the same problem
from a different direction:

"Lazy snapshot distribution in logical decoding"
/messages/by-id/578D6ABA-FC6B-4E08-955F-3493BA6FACA1@gmail.com

That patch does not skip any snapshots; it waits to hand one out
until a transaction actually needs it. Your patch skips the work
completely when the commit came from another database. Both change
the same code, so the two threads should know about each other.

I plan to take a closer look at your patch for Sholok's case this weekend.

Thanks,
Shihao

#4shihao zhong
zhong950419@gmail.com
In reply to: shihao zhong (#3)
Re: logical decoding: skip unnecessary snapshot distribution.

Hi Boyu,

One more thing: I don't see a CommitFest entry for this patch. To
give it more visibility to reviewers and committers, I created one
and set myself as the entry owner for now, since you don't seem to
have a postgresql.org community account yet:

https://commitfest.postgresql.org/patch/7265/

When you get a chance, please register a community account and
move the ownership back(or let me know), so the credit is recorded
correctly.

Thanks,
Shihao

Show quoted text
#5杨伯宇(长堂)
yangboyu.yby@alibaba-inc.com
In reply to: Shlok Kyal (#2)
Re: logical decoding: skip unnecessary snapshot distribution.

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.
Thanks,
Boyu Yang

#6杨伯宇(长堂)
yangboyu.yby@alibaba-inc.com
In reply to: shihao zhong (#4)
回复:logical decoding: skip unnecessary snapshot distribution.

Hi shihao,

Thank you for creating the CommitFest entry. And I have moved the ownership back.

Thanks,
Boyu Yang

#7shihao zhong
zhong950419@gmail.com
In reply to: 杨伯宇(长堂) (#6)
Re: logical decoding: skip unnecessary snapshot distribution.

Hi Boyu,

Did more experiment:

Decoded output for db1 is identical, and test_decoding, subscription and
recovery all pass. The idea is sound: skipping a foreign database's
invalidations is a no-op anyway, since LocalExecuteInvalidationMessage()
already filters them by dbId.

On Shlok's question, your answer is right -- the extra messages are from
the rolled-back savepoint, and not distributing a catalog change that
never committed is harmless. parsed->msgs is the correct set to test.

Smaller things for a v2:

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.

2. The dbId test contradicts DecodeTXNNeedSkip() just below, which
treats InvalidOid as "don't assume another database".

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.

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.

Thanks,
Shihao

#8Shlok Kyal
shlok.kyal.oss@gmail.com
In reply to: 杨伯宇(长堂) (#5)
Re: logical decoding: skip unnecessary snapshot distribution.

On Wed, 9 Sept 2026 at 13:22, 杨伯宇(长堂) <yangboyu.yby@alibaba-inc.com> 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

#9杨伯宇(长堂)
yangboyu.yby@alibaba-inc.com
In reply to: shihao zhong (#7)
Re:logical decoding: skip unnecessary snapshot distribution.

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

Attachments:

t253615_9
v2-0001-logical-decoding-skip-snapshot-distribution.patchapplication/octet-streamDownload+262-10
#10杨伯宇(长堂)
yangboyu.yby@alibaba-inc.com
In reply to: Shlok Kyal (#8)
回复:logical decoding: skip unnecessary snapshot distribution.

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

#11Shlok Kyal
shlok.kyal.oss@gmail.com
In reply to: 杨伯宇(长堂) (#10)
Re: logical decoding: skip unnecessary snapshot distribution.

On Fri, 16 Oct 2026 at 09:21, yangboyu <yangboyu.yby@alibaba-inc.com> 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

Attachments:

comments.patchapplication/octet-stream; name=comments.patchDownload+66-49
#12杨伯宇(长堂)
yangboyu.yby@alibaba-inc.com
In reply to: Shlok Kyal (#11)
Re:logical decoding: skip unnecessary snapshot distribution.

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; <statement>') inline.

4. The patch requires pgperltidy runs.

Agreed and applied.

Regards,
Boyu Yang

Attachments:

t253615_12
v3-0001-logical-decoding-skip-snapshot-distribution.patchapplication/octet-streamDownload+267-10