Skip to content

Commit 0434033

Browse files
author
Amit Kapila
committed
Fix data loss in logical replication.
Data loss can happen when the DDLs like ALTER PUBLICATION ... ADD TABLE ... or ALTER TYPE ... that don't take a strong lock on table happens concurrently to DMLs on the tables involved in the DDL. This happens because logical decoding doesn't distribute invalidations to concurrent transactions and those transactions use stale cache data to decode the changes. The problem becomes bigger because we keep using the stale cache even after those in-progress transactions are finished and skip the changes required to be sent to the client. This commit fixes the issue by distributing invalidation messages from catalog-modifying transactions to all concurrent in-progress transactions. This allows the necessary rebuild of the catalog cache when decoding new changes after concurrent DDL. We observed performance regression primarily during frequent execution of *publication DDL* statements that modify the published tables. The regression is minor or nearly nonexistent for DDLs that do not affect the published tables or occur infrequently, making this a worthwhile cost to resolve a longstanding data loss issue. An alternative approach considered was to take a strong lock on each affected table during publication modification. However, this would only address issues related to publication DDLs (but not the ALTER TYPE ...) and require locking every relation in the database for publications created as FOR ALL TABLES, which is impractical. The bug exists in all supported branches, but we are backpatching till 14. The fix for 13 requires somewhat bigger changes than this fix, so the fix for that branch is still under discussion. Reported-by: hubert depesz lubaczewski <depesz@depesz.com> Reported-by: Tomas Vondra <tomas.vondra@enterprisedb.com> Author: Shlok Kyal <shlok.kyal.oss@gmail.com> Author: Hayato Kuroda <kuroda.hayato@fujitsu.com> Reviewed-by: Zhijie Hou <houzj.fnst@fujitsu.com> Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com> Reviewed-by: Amit Kapila <amit.kapila16@gmail.com> Tested-by: Benoit Lobréau <benoit.lobreau@dalibo.com> Backpatch-through: 14 Discussion: https://postgr.es/m/de52b282-1166-1180-45a2-8d8917ca74c6@enterprisedb.com Discussion: https://postgr.es/m/CAD21AoAenVqiMjpN-PvGHL1N9DWnHSq673bfgr6phmBUzx=kLQ@mail.gmail.com
1 parent 115f45e commit 0434033

File tree

6 files changed

+134
-15
lines changed

6 files changed

+134
-15
lines changed

contrib/test_decoding/Makefile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
88
spill slot truncate stream stats twophase twophase_stream
99
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
1010
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
11-
twophase_snapshot catalog_change_snapshot skip_snapshot_restore
11+
twophase_snapshot catalog_change_snapshot skip_snapshot_restore \
12+
invalidation_distrubution
1213

1314
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
1415
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
Parsed test spec with 2 sessions
2+
3+
starting permutation: s1_insert_tbl1 s1_begin s1_insert_tbl1 s2_alter_pub_add_tbl s1_commit s1_insert_tbl1 s2_get_binary_changes
4+
step s1_insert_tbl1: INSERT INTO tbl1 (val1, val2) VALUES (1, 1);
5+
step s1_begin: BEGIN;
6+
step s1_insert_tbl1: INSERT INTO tbl1 (val1, val2) VALUES (1, 1);
7+
step s2_alter_pub_add_tbl: ALTER PUBLICATION pub ADD TABLE tbl1;
8+
step s1_commit: COMMIT;
9+
step s1_insert_tbl1: INSERT INTO tbl1 (val1, val2) VALUES (1, 1);
10+
step s2_get_binary_changes: SELECT count(data) FROM pg_logical_slot_get_binary_changes('isolation_slot', NULL, NULL, 'proto_version', '2', 'publication_names', 'pub') WHERE get_byte(data, 0) = 73;
11+
count
12+
-----
13+
1
14+
(1 row)
15+
16+
?column?
17+
--------
18+
stop
19+
(1 row)
20+
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Test that catalog cache invalidation messages are distributed to ongoing
2+
# transactions, ensuring they can access the updated catalog content after
3+
# processing these messages.
4+
setup
5+
{
6+
SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'pgoutput');
7+
CREATE TABLE tbl1(val1 integer, val2 integer);
8+
CREATE PUBLICATION pub;
9+
}
10+
11+
teardown
12+
{
13+
DROP TABLE tbl1;
14+
DROP PUBLICATION pub;
15+
SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
16+
}
17+
18+
session "s1"
19+
setup { SET synchronous_commit=on; }
20+
21+
step "s1_begin" { BEGIN; }
22+
step "s1_insert_tbl1" { INSERT INTO tbl1 (val1, val2) VALUES (1, 1); }
23+
step "s1_commit" { COMMIT; }
24+
25+
session "s2"
26+
setup { SET synchronous_commit=on; }
27+
28+
step "s2_alter_pub_add_tbl" { ALTER PUBLICATION pub ADD TABLE tbl1; }
29+
step "s2_get_binary_changes" { SELECT count(data) FROM pg_logical_slot_get_binary_changes('isolation_slot', NULL, NULL, 'proto_version', '2', 'publication_names', 'pub') WHERE get_byte(data, 0) = 73; }
30+
31+
# Expect to get one insert change. LOGICAL_REP_MSG_INSERT = 'I'
32+
permutation "s1_insert_tbl1" "s1_begin" "s1_insert_tbl1" "s2_alter_pub_add_tbl" "s1_commit" "s1_insert_tbl1" "s2_get_binary_changes"

src/backend/replication/logical/reorderbuffer.c

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5196,3 +5196,26 @@ ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
51965196
*cmax = ent->cmax;
51975197
return true;
51985198
}
5199+
5200+
/*
5201+
* Count invalidation messages of specified transaction.
5202+
*
5203+
* Returns number of messages, and msgs is set to the pointer of the linked
5204+
* list for the messages.
5205+
*/
5206+
uint32
5207+
ReorderBufferGetInvalidations(ReorderBuffer *rb, TransactionId xid,
5208+
SharedInvalidationMessage **msgs)
5209+
{
5210+
ReorderBufferTXN *txn;
5211+
5212+
txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
5213+
false);
5214+
5215+
if (txn == NULL)
5216+
return 0;
5217+
5218+
*msgs = txn->invalidations;
5219+
5220+
return txn->ninvalidations;
5221+
}

src/backend/replication/logical/snapbuild.c

Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ static void SnapBuildFreeSnapshot(Snapshot snap);
290290

291291
static void SnapBuildSnapIncRefcount(Snapshot snap);
292292

293-
static void SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn);
293+
static void SnapBuildDistributeSnapshotAndInval(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid);
294294

295295
/* xlog reading helper functions for SnapBuildProcessRunningXacts */
296296
static bool SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running);
@@ -843,23 +843,24 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
843843
}
844844

845845
/*
846-
* Add a new Snapshot to all transactions we're decoding that currently are
847-
* in-progress so they can see new catalog contents made by the transaction
848-
* that just committed. This is necessary because those in-progress
849-
* transactions will use the new catalog's contents from here on (at the very
850-
* least everything they do needs to be compatible with newer catalog
851-
* contents).
846+
* Add a new Snapshot and invalidation messages to all transactions we're
847+
* decoding that currently are in-progress so they can see new catalog contents
848+
* made by the transaction that just committed. This is necessary because those
849+
* in-progress transactions will use the new catalog's contents from here on
850+
* (at the very least everything they do needs to be compatible with newer
851+
* catalog contents).
852852
*/
853853
static void
854-
SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
854+
SnapBuildDistributeSnapshotAndInval(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid)
855855
{
856856
dlist_iter txn_i;
857857
ReorderBufferTXN *txn;
858858

859859
/*
860860
* Iterate through all toplevel transactions. This can include
861861
* subtransactions which we just don't yet know to be that, but that's
862-
* fine, they will just get an unnecessary snapshot queued.
862+
* fine, they will just get an unnecessary snapshot and invalidations
863+
* queued.
863864
*/
864865
dlist_foreach(txn_i, &builder->reorder->toplevel_by_lsn)
865866
{
@@ -872,6 +873,14 @@ SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
872873
* transaction which in turn implies we don't yet need a snapshot at
873874
* all. We'll add a snapshot when the first change gets queued.
874875
*
876+
* Similarly, we don't need to add invalidations to a transaction whose
877+
* base snapshot is not yet set. Once a base snapshot is built, it will
878+
* include the xids of committed transactions that have modified the
879+
* catalog, thus reflecting the new catalog contents. The existing
880+
* catalog cache will have already been invalidated after processing
881+
* the invalidations in the transaction that modified catalogs,
882+
* ensuring that a fresh cache is constructed during decoding.
883+
*
875884
* NB: This works correctly even for subtransactions because
876885
* ReorderBufferAssignChild() takes care to transfer the base snapshot
877886
* to the top-level transaction, and while iterating the changequeue
@@ -881,13 +890,13 @@ SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
881890
continue;
882891

883892
/*
884-
* We don't need to add snapshot to prepared transactions as they
885-
* should not see the new catalog contents.
893+
* We don't need to add snapshot or invalidations to prepared
894+
* transactions as they should not see the new catalog contents.
886895
*/
887896
if (rbtxn_prepared(txn) || rbtxn_skip_prepared(txn))
888897
continue;
889898

890-
elog(DEBUG2, "adding a new snapshot to %u at %X/%X",
899+
elog(DEBUG2, "adding a new snapshot and invalidations to %u at %X/%X",
891900
txn->xid, LSN_FORMAT_ARGS(lsn));
892901

893902
/*
@@ -897,6 +906,33 @@ SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
897906
SnapBuildSnapIncRefcount(builder->snapshot);
898907
ReorderBufferAddSnapshot(builder->reorder, txn->xid, lsn,
899908
builder->snapshot);
909+
910+
/*
911+
* Add invalidation messages to the reorder buffer of in-progress
912+
* transactions except the current committed transaction, for which we
913+
* will execute invalidations at the end.
914+
*
915+
* It is required, otherwise, we will end up using the stale catcache
916+
* contents built by the current transaction even after its decoding,
917+
* which should have been invalidated due to concurrent catalog
918+
* changing transaction.
919+
*/
920+
if (txn->xid != xid)
921+
{
922+
uint32 ninvalidations;
923+
SharedInvalidationMessage *msgs = NULL;
924+
925+
ninvalidations = ReorderBufferGetInvalidations(builder->reorder,
926+
xid, &msgs);
927+
928+
if (ninvalidations > 0)
929+
{
930+
Assert(msgs != NULL);
931+
932+
ReorderBufferAddInvalidations(builder->reorder, txn->xid, lsn,
933+
ninvalidations, msgs);
934+
}
935+
}
900936
}
901937
}
902938

@@ -1175,8 +1211,11 @@ SnapBuildCommitTxn(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid,
11751211
/* refcount of the snapshot builder for the new snapshot */
11761212
SnapBuildSnapIncRefcount(builder->snapshot);
11771213

1178-
/* add a new catalog snapshot to all currently running transactions */
1179-
SnapBuildDistributeNewCatalogSnapshot(builder, lsn);
1214+
/*
1215+
* Add a new catalog snapshot and invalidations messages to all
1216+
* currently running transactions.
1217+
*/
1218+
SnapBuildDistributeSnapshotAndInval(builder, lsn, xid);
11801219
}
11811220
}
11821221

src/include/replication/reorderbuffer.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -676,6 +676,10 @@ TransactionId ReorderBufferGetOldestXmin(ReorderBuffer *rb);
676676

677677
void ReorderBufferSetRestartPoint(ReorderBuffer *, XLogRecPtr ptr);
678678

679+
uint32 ReorderBufferGetInvalidations(ReorderBuffer *rb,
680+
TransactionId xid,
681+
SharedInvalidationMessage **msgs);
682+
679683
void StartupReorderBuffer(void);
680684

681685
#endif

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy