Skip to content

Commit 9a2f8b4

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 86392e8 commit 9a2f8b4

File tree

7 files changed

+134
-15
lines changed

7 files changed

+134
-15
lines changed

contrib/test_decoding/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
99
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
1010
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
1111
twophase_snapshot slot_creation_error catalog_change_snapshot \
12-
skip_snapshot_restore
12+
skip_snapshot_restore invalidation_distrubution
1313

1414
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
1515
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', '4', '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+

contrib/test_decoding/meson.build

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ tests += {
6363
'twophase_snapshot',
6464
'slot_creation_error',
6565
'skip_snapshot_restore',
66+
'invalidation_distrubution',
6667
],
6768
'regress_args': [
6869
'--temp-config', files('logical.conf'),
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', '4', '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
@@ -5283,3 +5283,26 @@ ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
52835283
*cmax = ent->cmax;
52845284
return true;
52855285
}
5286+
5287+
/*
5288+
* Count invalidation messages of specified transaction.
5289+
*
5290+
* Returns number of messages, and msgs is set to the pointer of the linked
5291+
* list for the messages.
5292+
*/
5293+
uint32
5294+
ReorderBufferGetInvalidations(ReorderBuffer *rb, TransactionId xid,
5295+
SharedInvalidationMessage **msgs)
5296+
{
5297+
ReorderBufferTXN *txn;
5298+
5299+
txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
5300+
false);
5301+
5302+
if (txn == NULL)
5303+
return 0;
5304+
5305+
*msgs = txn->invalidations;
5306+
5307+
return txn->ninvalidations;
5308+
}

src/backend/replication/logical/snapbuild.c

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

289289
static void SnapBuildSnapIncRefcount(Snapshot snap);
290290

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

293293
static inline bool SnapBuildXidHasCatalogChanges(SnapBuild *builder, TransactionId xid,
294294
uint32 xinfo);
@@ -845,23 +845,24 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
845845
}
846846

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

861861
/*
862862
* Iterate through all toplevel transactions. This can include
863863
* subtransactions which we just don't yet know to be that, but that's
864-
* fine, they will just get an unnecessary snapshot queued.
864+
* fine, they will just get an unnecessary snapshot and invalidations
865+
* queued.
865866
*/
866867
dlist_foreach(txn_i, &builder->reorder->toplevel_by_lsn)
867868
{
@@ -874,6 +875,14 @@ SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
874875
* transaction which in turn implies we don't yet need a snapshot at
875876
* all. We'll add a snapshot when the first change gets queued.
876877
*
878+
* Similarly, we don't need to add invalidations to a transaction whose
879+
* base snapshot is not yet set. Once a base snapshot is built, it will
880+
* include the xids of committed transactions that have modified the
881+
* catalog, thus reflecting the new catalog contents. The existing
882+
* catalog cache will have already been invalidated after processing
883+
* the invalidations in the transaction that modified catalogs,
884+
* ensuring that a fresh cache is constructed during decoding.
885+
*
877886
* NB: This works correctly even for subtransactions because
878887
* ReorderBufferAssignChild() takes care to transfer the base snapshot
879888
* to the top-level transaction, and while iterating the changequeue
@@ -883,13 +892,13 @@ SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
883892
continue;
884893

885894
/*
886-
* We don't need to add snapshot to prepared transactions as they
887-
* should not see the new catalog contents.
895+
* We don't need to add snapshot or invalidations to prepared
896+
* transactions as they should not see the new catalog contents.
888897
*/
889898
if (rbtxn_prepared(txn) || rbtxn_skip_prepared(txn))
890899
continue;
891900

892-
elog(DEBUG2, "adding a new snapshot to %u at %X/%X",
901+
elog(DEBUG2, "adding a new snapshot and invalidations to %u at %X/%X",
893902
txn->xid, LSN_FORMAT_ARGS(lsn));
894903

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

@@ -1170,8 +1206,11 @@ SnapBuildCommitTxn(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid,
11701206
/* refcount of the snapshot builder for the new snapshot */
11711207
SnapBuildSnapIncRefcount(builder->snapshot);
11721208

1173-
/* add a new catalog snapshot to all currently running transactions */
1174-
SnapBuildDistributeNewCatalogSnapshot(builder, lsn);
1209+
/*
1210+
* Add a new catalog snapshot and invalidations messages to all
1211+
* currently running transactions.
1212+
*/
1213+
SnapBuildDistributeSnapshotAndInval(builder, lsn, xid);
11751214
}
11761215
}
11771216

src/include/replication/reorderbuffer.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -748,6 +748,10 @@ extern TransactionId *ReorderBufferGetCatalogChangesXacts(ReorderBuffer *rb);
748748

749749
extern void ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr);
750750

751+
extern uint32 ReorderBufferGetInvalidations(ReorderBuffer *rb,
752+
TransactionId xid,
753+
SharedInvalidationMessage **msgs);
754+
751755
extern void StartupReorderBuffer(void);
752756

753757
#endif

0 commit comments

Comments
 (0)