public inbox for [email protected]
help / color / mirror / Atom feedFrom: Zhijie Hou (Fujitsu) <[email protected]>
To: shveta malik <[email protected]>
Cc: Hayato Kuroda (Fujitsu) <[email protected]>
Cc: PostgreSQL Hackers <[email protected]>
Cc: Tomas Vondra <[email protected]>
Cc: Dilip Kumar <[email protected]>
Cc: Andrei Lepikhov <[email protected]>
Cc: wenhui qiu <[email protected]>
Cc: Amit Kapila <[email protected]>
Subject: RE: Parallel Apply
Date: Thu, 4 Jun 2026 06:58:31 +0000
Message-ID: <TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com> (raw)
In-Reply-To: <CAJpy0uByjHr2mEDPPghzvtRkQt__BnqALs5fgkSwa5DALT=Q6w@mail.gmail.com>
References: <CAJpy0uDCxK2wiM-uMYSMKkrp+pYOHxE5ns4ihFvht=JmytVJ3A@mail.gmail.com>
<CAJpy0uByjHr2mEDPPghzvtRkQt__BnqALs5fgkSwa5DALT=Q6w@mail.gmail.com>
On Wednesday, May 13, 2026 5:32 PM shveta malik <[email protected]> wrote:
>
> On Wed, May 13, 2026 at 10:54 AM shveta malik <[email protected]>
> wrote:
> >
> >
> > Please find a few comments for patch003 mostly:
Thanks for the comments!
> >
> > 1)
> > * depended on by other transactions. Entries are of type
> ParallelizedTxnEntry.
> > *
> > * dshash is used to enable dynamic shared memory allocation based on
> > the number
> > - * of transactions being applied in parallel.
> > + * of transactions being applied in parallel. Entries are of type
> > ParallelizedTxnEntry.
> > */
> > static dsa_area *parallel_apply_dsa_area = NULL; static dshash_table
> > *parallelized_txns = NULL;
> >
> > 'Entries are of type ParallelizedTxnEntry' repeated twice in this comment.
Removed.
> >
> >
> > 2)
> > cleanup_committed_replica_identity_entries:
> >
> > + if (!skipped_write && !XLogRecPtrIsValid(pos->local_end))
> > + continue;
> >
> > Perhaps a comment will help to indicate above checks means a txn not
> > yet finished.
Added.
> >
> > 3)
> > Can you please clarify the scope, life-span of entries in
> > parallelized_txns vs ParallelApplyTxnHash. Both have remote-xid field.
> > So at any point of time, do both tables will have same number of
> > entries or if entries in one has bigger life-span/scope as compared to
> > other? It will be good to briefly mention these atop the hash-tables.
Added comments for it atop of these hash tables.
> >
> > 4)
> > +/*
> > + * Hash table storing replica identity values for changes being
> > +applied in
> > + * parallel, along with the last transaction that modified each row.
> > ...
> > +static replica_identity_hash *replica_identity_table = NULL;
> >
> > Regarding 'along with the last transaction that modified each row', is
> > 'remote_xid' in ReplicaIdentityEntry is the last transaction that
> > modified this row or the one which is currently modifying it?
It could be either, depending on whether the transaction is still running or
has already finished. In this version, I've changed it to be the "latest"
transaction.
> >
> > 5)
> > Since we have added comments for rest for the fields for below
> > existing structure, do you think we can update comment for 'xid' as
> > well to say it is remote-one. It does not mention it anywhere in
> > comment.
> >
> > typedef struct ParallelApplyWorkerEntry { TransactionId xid; /* Hash
> > key -- must be first */
> >
Added.
> >
> > 6)
> > 003' commit message says about RI table entry:
> >
> > Entries are deleted when transactions committed by parallel workers
> > are gathered, or the number of entries exceeds the limit.
> > --
> > I don't understand what do we mean by "when transactions committed by
> > parallel workers are gathered". Can we please make it more
> > clear/elaborate.
> >
I modified this to be consistent with some detailed comments in the patch.
> > ~~
> >
> > Reviewing further.
> >
>
> Few more on 003:
>
>
> 7)
> I find check_and_record_ri_dependency() difficult to understand.
>
> a)
> As an example, this part:
>
> + /*
> + * Return if no entry exists, or if the current transaction was the
> + last one
> + * to modify the key.
> + */
> + if (!rientry || TransactionIdEquals(rientry->remote_xid,
> + new_depended_xid)) return;
>
> IMO, the second check makes sense if new_depended_xid is valid. If so, why
> don't we make it part of previous 'if
> (TransactionIdIsValid(new_depended_xid))' logic. If 'found' was true, we can
> check it inside that if-block and 'return' from there instead of proceeding
> further.
>
> Once we make above change, we can even move below logic inside previous
> 'if (TransactionIdIsValid(new_depended_xid))' block, as it looks strange that in
> previous if-block we are assigning InvalidTransactionId to 'rientry-
> >remote_xid' while we have valid new_depended_xid available there.
>
> + /*
> + * Update the new depended xid into the entry if valid, the new xid
> + could
> + * be invalid if the transaction will be applied by the leader itself
> + * which means all the changes will be committed before processing next
> + * transaction, so no need to be depended on.
> + */
> + if (TransactionIdIsValid(new_depended_xid))
> + rientry->remote_xid = new_depended_xid;
Right. The original code was written that way to save a few lines,
but I agree it's harder to understand. I've refactored this part to
make each section clearer.
>
>
> b)
> Also this part is not clear:
>
> + /*
> + * Return if RI key is NULL or is explicitly marked unchanged. The key
> + * value could be NULL in the new tuple of a update opertaion which
> + * means the RI key is not updated.
> + */
> + if (original_data->colstatus[i] == LOGICALREP_COLUMN_NULL ||
> + original_data->colstatus[i] == LOGICALREP_COLUMN_UNCHANGED)
> return;
>
> Why do have we 'return' here when one of the columns is NULL or
> unchanged? What happens to rest of the RI columns? Which scenario may hit
> this? It needs more comments to explain the scenario.
After testing, I found that the handling for unchanged toasted columns was
incorrect. When the RI key includes two columns and only the non-toasted column
is changed, the toasted column is not included in the new tuple of an UPDATE
change. This means we cannot obtain the complete RI key value to check for
dependencies when handling the new change. I fixed this by copying the toasted
value from the old tuple to the new one before dependency checking.
>
>
> 8)
> check_and_record_ri_dependency() has this comment and logic around
> invalid remote_xid:
>
> + /*
> + * Remove the entry if the transaction has been committed and no new
> + * dependency needs to be added.
> + */
> + else if (!TransactionIdIsValid(rientry->remote_xid))
> + {
> + free_replica_identity_key(rientry->keydata);
> + replica_identity_delete_item(replica_identity_table, rientry); }
>
> While find_all_dependencies_on_rel() has this assert:
> + Assert(TransactionIdIsValid(rientry->remote_xid));
>
> The first logic says that we may have Invalid remote_xid in existing entry in
> replica_identity_table while second logic has a sanity check while iterating
> the same hash-table that all entries must have valid remote_xid. Is the Assert
> correct? We might have Invalid remote_xid if txn is committed (done in
> check_and_append_xid_dependency).
It's correct. The remote_xid could be invalid only before being stored
in the table. The check_and_append_xid_dependency function wasn't very clear
about this, but after refactoring, I hope it's easier to understand now.
Here is the V19 patch set which addressed all the comments above.
Best Regards,
Hou zj
Attachments:
[application/octet-stream] v19-0001-Introduce-a-shared-hash-table-to-store-paralleli.patch (9.2K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/2-v19-0001-Introduce-a-shared-hash-table-to-store-paralleli.patch)
download | inline diff:
From 5a201d629e9520e0f3ad1f28155589c62227addc Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Wed, 27 May 2026 11:31:35 +0800
Subject: [PATCH v19 1/3] Introduce a shared hash table to store parallelized
transactions
This commit introduces a shared hash table for tracking parallelized
transactions. The hash table uses transaction IDs as keys; no values are stored.
The hash entries are inserted with a remote XID when the leader bypasses remote
transactions to parallel apply workers. Entries are deleted when parallel
workers are committed to corresponding transactions.
Any worker can use this hash table to check whether a transaction is still
in progress:
- If an entry exists, the transaction is still in progress.
- If no entry exists, the transaction has committed.
Later patches will use this hash table to support dependency waiting and
commit order preservation. When transaction A depends on transaction B
(or must commit after B), the worker will wait for transaction B's entry
to be removed before committing transaction A.
Author: Zhijie Hou <[email protected]>
Author: Hayato Kuroda <[email protected]>
---
.../replication/logical/applyparallelworker.c | 90 ++++++++++++++++++-
.../utils/activity/wait_event_names.txt | 1 +
src/include/replication/worker_internal.h | 9 ++
src/include/storage/lwlocklist.h | 1 +
src/tools/pgindent/typedefs.list | 1 +
5 files changed, 101 insertions(+), 1 deletion(-)
diff --git a/src/backend/replication/logical/applyparallelworker.c b/src/backend/replication/logical/applyparallelworker.c
index 012d55e9d3d..109d85c7cdf 100644
--- a/src/backend/replication/logical/applyparallelworker.c
+++ b/src/backend/replication/logical/applyparallelworker.c
@@ -221,12 +221,38 @@ typedef struct ParallelApplyWorkerEntry
ParallelApplyWorkerInfo *winfo;
} ParallelApplyWorkerEntry;
+/* An entry in the parallelized_txns shared hash table */
+typedef struct ParallelizedTxnEntry
+{
+ TransactionId xid; /* Hash key, remote transaction ID */
+} ParallelizedTxnEntry;
+
/*
* A hash table used to cache the state of streaming transactions being applied
- * by the parallel apply workers.
+ * by the parallel apply workers. Entries are of type ParallelApplyWorkerEntry.
*/
static HTAB *ParallelApplyTxnHash = NULL;
+/*
+ * A hash table used to track the parallelized remote transactions that could be
+ * depended on by other transactions. Entries are of type ParallelizedTxnEntry.
+ *
+ * dshash is used to enable dynamic shared memory allocation based on the number
+ * of transactions being applied in parallel.
+ */
+static dsa_area *parallel_apply_dsa_area = NULL;
+static dshash_table *parallelized_txns = NULL;
+
+/* parameters for the parallelized_txns shared hash table */
+static const dshash_parameters dsh_params = {
+ sizeof(TransactionId),
+ sizeof(ParallelizedTxnEntry),
+ dshash_memcmp,
+ dshash_memhash,
+ dshash_memcpy,
+ LWTRANCHE_PARALLEL_APPLY_DSA
+};
+
/*
* A list (pool) of active parallel apply workers. The information for
* the new worker is added to the list after successfully launching it. The
@@ -260,6 +286,8 @@ static List *subxactlist = NIL;
static void pa_free_worker_info(ParallelApplyWorkerInfo *winfo);
static ParallelTransState pa_get_xact_state(ParallelApplyWorkerShared *wshared);
static PartialFileSetState pa_get_fileset_state(void);
+static void pa_attach_parallelized_txn_hash(dsa_handle *pa_dsa_handle,
+ dshash_table_handle *pa_dshash_handle);
/*
* Returns true if it is OK to start a parallel apply worker, false otherwise.
@@ -337,6 +365,15 @@ pa_setup_dsm(ParallelApplyWorkerInfo *winfo)
shm_mq *mq;
Size queue_size = DSM_QUEUE_SIZE;
Size error_queue_size = DSM_ERROR_QUEUE_SIZE;
+ dsa_handle parallel_apply_dsa_handle;
+ dshash_table_handle parallelized_txns_handle;
+
+ pa_attach_parallelized_txn_hash(¶llel_apply_dsa_handle,
+ ¶llelized_txns_handle);
+
+ if (parallel_apply_dsa_handle == DSA_HANDLE_INVALID ||
+ parallelized_txns_handle == DSHASH_HANDLE_INVALID)
+ return false;
/*
* Estimate how much shared memory we need.
@@ -372,6 +409,8 @@ pa_setup_dsm(ParallelApplyWorkerInfo *winfo)
pg_atomic_init_u32(&(shared->pending_stream_count), 0);
shared->last_commit_end = InvalidXLogRecPtr;
shared->fileset_state = FS_EMPTY;
+ shared->parallel_apply_dsa_handle = parallel_apply_dsa_handle;
+ shared->parallelized_txns_handle = parallelized_txns_handle;
shm_toc_insert(toc, PARALLEL_APPLY_KEY_SHARED, shared);
@@ -876,6 +915,8 @@ ParallelApplyWorkerMain(Datum main_arg)
shm_mq *mq;
shm_mq_handle *mqh;
shm_mq_handle *error_mqh;
+ dsa_handle pa_dsa_handle;
+ dshash_table_handle pa_dshash_handle;
ReplOriginId originid;
int worker_slot = DatumGetInt32(main_arg);
char originname[NAMEDATALEN];
@@ -962,6 +1003,8 @@ ParallelApplyWorkerMain(Datum main_arg)
InitializingApplyWorker = false;
+ pa_attach_parallelized_txn_hash(&pa_dsa_handle, &pa_dshash_handle);
+
/* Setup replication origin tracking. */
StartTransactionCommand();
ReplicationOriginNameForLogicalRep(MySubscription->oid, InvalidOid,
@@ -1656,3 +1699,48 @@ pa_xact_finish(ParallelApplyWorkerInfo *winfo, XLogRecPtr remote_lsn)
pa_free_worker(winfo);
}
+
+/*
+ * Attach to the shared hash table for parallelized transactions.
+ */
+static void
+pa_attach_parallelized_txn_hash(dsa_handle *pa_dsa_handle,
+ dshash_table_handle *pa_dshash_handle)
+{
+ MemoryContext oldctx;
+
+ if (parallelized_txns)
+ {
+ Assert(parallel_apply_dsa_area);
+ *pa_dsa_handle = dsa_get_handle(parallel_apply_dsa_area);
+ *pa_dshash_handle = dshash_get_hash_table_handle(parallelized_txns);
+ return;
+ }
+
+ /* Be sure any local memory allocated by DSA routines is persistent. */
+ oldctx = MemoryContextSwitchTo(ApplyContext);
+
+ if (am_leader_apply_worker())
+ {
+ /* Initialize dynamic shared hash table for parallelized transactions */
+ parallel_apply_dsa_area = dsa_create(LWTRANCHE_PARALLEL_APPLY_DSA);
+ dsa_pin(parallel_apply_dsa_area);
+ dsa_pin_mapping(parallel_apply_dsa_area);
+ parallelized_txns = dshash_create(parallel_apply_dsa_area, &dsh_params, NULL);
+
+ /* Store handles in shared memory for other backends to use. */
+ *pa_dsa_handle = dsa_get_handle(parallel_apply_dsa_area);
+ *pa_dshash_handle = dshash_get_hash_table_handle(parallelized_txns);
+ }
+ else if (am_parallel_apply_worker())
+ {
+ /* Attach to existing dynamic shared hash table. */
+ parallel_apply_dsa_area = dsa_attach(MyParallelShared->parallel_apply_dsa_handle);
+ dsa_pin_mapping(parallel_apply_dsa_area);
+ parallelized_txns = dshash_attach(parallel_apply_dsa_area, &dsh_params,
+ MyParallelShared->parallelized_txns_handle,
+ NULL);
+ }
+
+ MemoryContextSwitchTo(oldctx);
+}
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 560659f9568..1339c33262f 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -417,6 +417,7 @@ XactSLRU "Waiting to access the transaction status SLRU cache."
ParallelVacuumDSA "Waiting for parallel vacuum dynamic shared memory allocation."
AioUringCompletion "Waiting for another process to complete IO via io_uring."
ShmemIndex "Waiting to find or allocate space in shared memory."
+ParallelApplyDSA "Waiting for parallel apply dynamic shared memory allocation."
# No "ABI_compatibility" region here as WaitEventLWLock has its own C code.
diff --git a/src/include/replication/worker_internal.h b/src/include/replication/worker_internal.h
index 745b7d9e969..e60e0c3d6d7 100644
--- a/src/include/replication/worker_internal.h
+++ b/src/include/replication/worker_internal.h
@@ -15,6 +15,7 @@
#include "access/xlogdefs.h"
#include "catalog/pg_subscription.h"
#include "datatype/timestamp.h"
+#include "lib/dshash.h"
#include "miscadmin.h"
#include "replication/logicalrelation.h"
#include "replication/walreceiver.h"
@@ -196,6 +197,14 @@ typedef struct ParallelApplyWorkerShared
*/
PartialFileSetState fileset_state;
FileSet fileset;
+
+ /*
+ * DSA handle for parallel apply workers, along with the handle for the
+ * shared hash table allocated under it. The hash table stores parallelized
+ * transaction information.
+ */
+ dsa_handle parallel_apply_dsa_handle;
+ dshash_table_handle parallelized_txns_handle;
} ParallelApplyWorkerShared;
/*
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index d7eb648bd27..c5f2921b703 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -140,3 +140,4 @@ PG_LWLOCKTRANCHE(XACT_SLRU, XactSLRU)
PG_LWLOCKTRANCHE(PARALLEL_VACUUM_DSA, ParallelVacuumDSA)
PG_LWLOCKTRANCHE(AIO_URING_COMPLETION, AioUringCompletion)
PG_LWLOCKTRANCHE(SHMEM_INDEX, ShmemIndex)
+PG_LWLOCKTRANCHE(PARALLEL_APPLY_DSA, ParallelApplyDSA)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 8cf40c87043..fabda17d739 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2162,6 +2162,7 @@ ParallelHashJoinBatch
ParallelHashJoinBatchAccessor
ParallelHashJoinState
ParallelIndexScanDesc
+ParallelizedTxnEntry
ParallelSlot
ParallelSlotArray
ParallelSlotResultHandler
--
2.43.0
[application/octet-stream] v19-0010-Support-serializing-changes-to-disk-when-the-sen.patch (16.3K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/3-v19-0010-Support-serializing-changes-to-disk-when-the-sen.patch)
download | inline diff:
From 16ec166f61eddfdeb142af40a9cbc0938adcbe25 Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Thu, 30 Apr 2026 16:52:41 +0800
Subject: [PATCH v19 10/10] Support serializing changes to disk when the send
buffer is full
This commit adds support for the leader apply worker to serialize changes to
disk when the send buffer to parallel apply workers becomes full. If a parallel
apply worker cannot send changes to the leader due to a send timeout, it
switches to serialization mode and writes the remaining changes of the remote
transaction to a file. The parallel apply worker later reads and applies the
serialized changes once it has caught up.
---
.../replication/logical/applyparallelworker.c | 52 ++++-
src/backend/replication/logical/worker.c | 184 +++++++++++++-----
src/test/subscription/t/050_parallel_apply.pl | 30 +++
3 files changed, 209 insertions(+), 57 deletions(-)
diff --git a/src/backend/replication/logical/applyparallelworker.c b/src/backend/replication/logical/applyparallelworker.c
index 7ced261445c..17cd52394f6 100644
--- a/src/backend/replication/logical/applyparallelworker.c
+++ b/src/backend/replication/logical/applyparallelworker.c
@@ -976,6 +976,38 @@ pa_get_last_commit_end(TransactionId xid, bool delete_entry, bool *skipped_write
return entry->local_end;
}
+/*
+ * Wait for the remote transaction associated with the specified remote xid to
+ * complete.
+ */
+static void
+pa_wait_for_transaction(TransactionId wait_for_xid)
+{
+ if (!am_leader_apply_worker())
+ return;
+
+ if (!TransactionIdIsValid(wait_for_xid))
+ return;
+
+ elog(DEBUG1, "plan to wait for remote_xid %u to finish",
+ wait_for_xid);
+
+ for (;;)
+ {
+ if (pa_transaction_committed(wait_for_xid))
+ break;
+
+ pa_lock_transaction(wait_for_xid, AccessShareLock);
+ pa_unlock_transaction(wait_for_xid, AccessShareLock);
+
+ /* An interrupt may have occurred while we were waiting. */
+ CHECK_FOR_INTERRUPTS();
+ }
+
+ elog(DEBUG1, "finished wait for remote_xid %u to finish",
+ wait_for_xid);
+}
+
/*
* Interrupt handler for main loop of parallel apply worker.
*/
@@ -1595,6 +1627,7 @@ pa_send_data(ParallelApplyWorkerInfo *winfo, Size nbytes, const void *data)
void
pa_distribute_schema_changes_to_workers(LogicalRepRelation *rel)
{
+ List *workers_stopped = NIL;
StringInfoData out;
/* Only leader apply workers can distribute schema changes */
@@ -1631,13 +1664,22 @@ pa_distribute_schema_changes_to_workers(LogicalRepRelation *rel)
continue;
/*
- * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
- * buffer becomes full.
+ * Distribution to this worker failed due to a sending timeout. Wait
+ * for the worker to complete its transaction and then stop it. This
+ * is consistent with the handling of workers in serialize mode (see
+ * pa_free_worker() for details).
*/
- ereport(ERROR,
- errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("could not send data to the logical replication parallel apply worker for subscription"));
+ pa_wait_for_transaction(winfo->shared->xid);
+
+ pa_get_last_commit_end(winfo->shared->xid, false, NULL);
+
+ logicalrep_pa_worker_stop(winfo);
+
+ workers_stopped = lappend(workers_stopped, winfo);
}
+
+ foreach_ptr(ParallelApplyWorkerInfo, winfo, workers_stopped)
+ pa_free_worker_info(winfo);
}
/*
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index 6f8d83c6b7b..40ad922b9fc 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -733,9 +733,9 @@ static void set_wal_receiver_timeout(void);
static void on_exit_clear_xact_state(int code, Datum arg);
-static void send_internal_dependencies(ParallelApplyWorkerInfo *winfo,
+static bool send_internal_dependencies(ParallelApplyWorkerInfo *winfo,
List *depends_on_xids);
-static void build_dependency_with_last_committed_txn(ParallelApplyWorkerInfo *winfo);
+static bool build_dependency_with_last_committed_txn(ParallelApplyWorkerInfo *winfo);
/*
* Compute the hash value for entries in the replica_identity_table.
@@ -1931,6 +1931,9 @@ handle_parallelized_transaction(LogicalRepMsgType action, StringInfo s)
ParallelApplyWorkerInfo *winfo;
TransApplyAction apply_action;
+ /* Save the message before it is consumed. */
+ StringInfoData original_msg = *s;
+
/*
* Dependency checking for non-streaming transactions is only required in
* the leader apply worker during a remote transaction.
@@ -1951,6 +1954,12 @@ handle_parallelized_transaction(LogicalRepMsgType action, StringInfo s)
handle_dependency_on_change(action, s, remote_xid, winfo);
+ /*
+ * Re-fetch the latest apply action as it might have been changed during
+ * dependency check.
+ */
+ apply_action = get_transaction_apply_action(remote_xid, &winfo);
+
switch (apply_action)
{
case TRANS_LEADER_SEND_TO_PARALLEL:
@@ -1962,13 +1971,18 @@ handle_parallelized_transaction(LogicalRepMsgType action, StringInfo s)
action != LOGICAL_REP_MSG_TYPE);
/*
- * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
- * buffer becomes full.
+ * Switch to serialize mode when we are not able to send the
+ * change to parallel apply worker.
*/
- ereport(ERROR,
- errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("could not send data to the logical replication parallel apply worker"));
- return false; /* silence compiler warning */
+ pa_switch_to_partial_serialize(winfo, false);
+
+ pg_fallthrough;
+ case TRANS_LEADER_PARTIAL_SERIALIZE:
+ stream_write_change(action, &original_msg);
+
+ /* Same reason as TRANS_LEADER_SEND_TO_PARALLEL case. */
+ return (action != LOGICAL_REP_MSG_RELATION &&
+ action != LOGICAL_REP_MSG_TYPE);
default:
elog(ERROR, "unexpected apply action: %d", (int) apply_action);
@@ -2340,6 +2354,9 @@ apply_handle_begin(StringInfo s)
ParallelApplyWorkerInfo *winfo;
TransApplyAction apply_action;
+ /* Save the message before it is consumed. */
+ StringInfoData original_msg = *s;
+
/* There must not be an active streaming transaction. */
Assert(!TransactionIdIsValid(stream_xid));
@@ -2373,12 +2390,19 @@ apply_handle_begin(StringInfo s)
}
/*
- * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
- * buffer becomes full.
+ * Switch to serialize mode when we are not able to send the
+ * change to parallel apply worker.
*/
- ereport(ERROR,
- errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("could not send data to the logical replication parallel apply worker"));
+ pa_switch_to_partial_serialize(winfo, true);
+
+ pg_fallthrough;
+ case TRANS_LEADER_PARTIAL_SERIALIZE:
+ Assert(winfo);
+
+ stream_write_change(LOGICAL_REP_MSG_BEGIN, &original_msg);
+
+ /* Cache the parallel apply worker for this transaction. */
+ pa_set_stream_apply_worker(winfo);
break;
case TRANS_PARALLEL_APPLY:
@@ -2400,7 +2424,7 @@ apply_handle_begin(StringInfo s)
/*
* Send an INTERNAL_DEPENDENCY message to a parallel apply worker.
*/
-static void
+static bool
send_internal_dependencies(ParallelApplyWorkerInfo *winfo, List *depends_on_xids)
{
StringInfoData dependencies;
@@ -2414,14 +2438,22 @@ send_internal_dependencies(ParallelApplyWorkerInfo *winfo, List *depends_on_xids
foreach_xid(xid, depends_on_xids)
pq_sendint32(&dependencies, xid);
+ if (!winfo->serialize_changes)
+ {
+ if (pa_send_data(winfo, dependencies.len, dependencies.data))
+ return true;
+
+ pa_switch_to_partial_serialize(winfo, true);
+ }
+
/*
- * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
- * buffer becomes full.
+ * Skip writing the first internal message flag because
+ * stream_write_change() accepts it as the argument.
*/
- if (!pa_send_data(winfo, dependencies.len, dependencies.data))
- ereport(ERROR,
- errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("could not send data to the logical replication parallel apply worker"));
+ dependencies.cursor++;
+ stream_write_change(LOGICAL_REP_MSG_INTERNAL_MESSAGE, &dependencies);
+
+ return false;
}
/*
@@ -2431,14 +2463,14 @@ send_internal_dependencies(ParallelApplyWorkerInfo *winfo, List *depends_on_xids
* instructing it to wait for the last committed transaction to finish before
* committing its own, thereby preserving commit order.
*/
-static void
+static bool
build_dependency_with_last_committed_txn(ParallelApplyWorkerInfo *winfo)
{
/* Skip if transactions have not been applied yet */
if (!TransactionIdIsValid(last_parallelized_remote_xid))
- return;
+ return true;
- send_internal_dependencies(winfo, list_make1_xid(last_parallelized_remote_xid));
+ return send_internal_dependencies(winfo, list_make1_xid(last_parallelized_remote_xid));
}
/*
@@ -2453,6 +2485,9 @@ apply_handle_commit(StringInfo s)
ParallelApplyWorkerInfo *winfo;
TransApplyAction apply_action;
+ /* Save the message before it is consumed. */
+ StringInfoData original_msg = *s;
+
logicalrep_read_commit(s, &commit_data);
if (commit_data.commit_lsn != remote_final_lsn)
@@ -2496,11 +2531,11 @@ apply_handle_commit(StringInfo s)
/*
* Build a dependency between this transaction and the lastly
- * committed transaction to preserve the commit order.
+ * committed transaction to preserve the commit order. Then try to
+ * send a COMMIT message if succeeded.
*/
- build_dependency_with_last_committed_txn(winfo);
-
- if (pa_send_data(winfo, s->len, s->data))
+ if (build_dependency_with_last_committed_txn(winfo) &&
+ pa_send_data(winfo, s->len, s->data))
{
/* Cache the remote_xid */
last_parallelized_remote_xid = remote_xid;
@@ -2511,12 +2546,29 @@ apply_handle_commit(StringInfo s)
}
/*
- * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
- * buffer becomes full.
+ * Switch to serialize mode when we are not able to send the
+ * change to parallel apply worker.
*/
- ereport(ERROR,
- errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("could not send data to the logical replication parallel apply worker"));
+ pa_switch_to_partial_serialize(winfo, true);
+
+ pg_fallthrough;
+ case TRANS_LEADER_PARTIAL_SERIALIZE:
+ Assert(winfo);
+
+ /*
+ * Build a dependency with the last committed transaction if not
+ * already done.
+ */
+ if (apply_action != TRANS_LEADER_SEND_TO_PARALLEL)
+ build_dependency_with_last_committed_txn(winfo);
+
+ stream_open_and_write_change(remote_xid, LOGICAL_REP_MSG_COMMIT,
+ &original_msg);
+
+ pa_set_fileset_state(winfo->shared, FS_SERIALIZE_DONE);
+
+ /* Finish processing the transaction. */
+ pa_xact_finish(winfo, commit_data.end_lsn);
break;
case TRANS_PARALLEL_APPLY:
@@ -2569,6 +2621,9 @@ apply_handle_begin_prepare(StringInfo s)
ParallelApplyWorkerInfo *winfo;
TransApplyAction apply_action;
+ /* Save the message before it is consumed. */
+ StringInfoData original_msg = *s;
+
/* Tablesync should never receive prepare. */
if (am_tablesync_worker())
ereport(ERROR,
@@ -2608,12 +2663,19 @@ apply_handle_begin_prepare(StringInfo s)
}
/*
- * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
- * buffer becomes full.
+ * Switch to serialize mode when we are not able to send the
+ * change to parallel apply worker.
*/
- ereport(ERROR,
- errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("could not send data to the logical replication parallel apply worker"));
+ pa_switch_to_partial_serialize(winfo, true);
+
+ pg_fallthrough;
+ case TRANS_LEADER_PARTIAL_SERIALIZE:
+ Assert(winfo);
+
+ stream_write_change(LOGICAL_REP_MSG_BEGIN_PREPARE, &original_msg);
+
+ /* Cache the parallel apply worker for this transaction. */
+ pa_set_stream_apply_worker(winfo);
break;
case TRANS_PARALLEL_APPLY:
@@ -2679,6 +2741,9 @@ apply_handle_prepare(StringInfo s)
ParallelApplyWorkerInfo *winfo;
TransApplyAction apply_action;
+ /* Save the message before it is consumed. */
+ StringInfoData original_msg = *s;
+
logicalrep_read_prepare(s, &prepare_data);
if (prepare_data.prepare_lsn != remote_final_lsn)
@@ -2748,11 +2813,11 @@ apply_handle_prepare(StringInfo s)
/*
* Build a dependency between this transaction and the lastly
- * committed transaction to preserve the commit order.
+ * committed transaction to preserve the commit order. Then try to
+ * send a COMMIT message if succeeded.
*/
- build_dependency_with_last_committed_txn(winfo);
-
- if (pa_send_data(winfo, s->len, s->data))
+ if (build_dependency_with_last_committed_txn(winfo) &&
+ pa_send_data(winfo, s->len, s->data))
{
/* Cache the remote_xid */
last_parallelized_remote_xid = remote_xid;
@@ -2763,12 +2828,29 @@ apply_handle_prepare(StringInfo s)
}
/*
- * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
- * buffer becomes full.
+ * Switch to serialize mode when we are not able to send the
+ * change to parallel apply worker.
*/
- ereport(ERROR,
- errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("could not send data to the logical replication parallel apply worker"));
+ pa_switch_to_partial_serialize(winfo, true);
+ pg_fallthrough;
+
+ case TRANS_LEADER_PARTIAL_SERIALIZE:
+ Assert(winfo);
+
+ /*
+ * Build a dependency with the last committed transaction if not
+ * already done.
+ */
+ if (apply_action != TRANS_LEADER_SEND_TO_PARALLEL)
+ build_dependency_with_last_committed_txn(winfo);
+
+ stream_open_and_write_change(remote_xid, LOGICAL_REP_MSG_PREPARE,
+ &original_msg);
+
+ pa_set_fileset_state(winfo->shared, FS_SERIALIZE_DONE);
+
+ /* Finish processing the transaction. */
+ pa_xact_finish(winfo, prepare_data.end_lsn);
break;
case TRANS_PARALLEL_APPLY:
@@ -3043,9 +3125,8 @@ apply_handle_stream_prepare(StringInfo s)
* Build a dependency between this transaction and the lastly
* committed transaction to preserve the commit order.
*/
- build_dependency_with_last_committed_txn(winfo);
-
- if (pa_send_data(winfo, s->len, s->data))
+ if (build_dependency_with_last_committed_txn(winfo) &&
+ pa_send_data(winfo, s->len, s->data))
{
/* Finish processing the streaming transaction. */
pa_xact_finish(winfo, prepare_data.end_lsn);
@@ -3923,9 +4004,8 @@ apply_handle_stream_commit(StringInfo s)
* Build a dependency between this transaction and the lastly
* committed transaction to preserve the commit order.
*/
- build_dependency_with_last_committed_txn(winfo);
-
- if (pa_send_data(winfo, s->len, s->data))
+ if (build_dependency_with_last_committed_txn(winfo) &&
+ pa_send_data(winfo, s->len, s->data))
{
/* Finish processing the streaming transaction. */
pa_xact_finish(winfo, commit_data.end_lsn);
diff --git a/src/test/subscription/t/050_parallel_apply.pl b/src/test/subscription/t/050_parallel_apply.pl
index 896244a42fd..bd51d98d885 100644
--- a/src/test/subscription/t/050_parallel_apply.pl
+++ b/src/test/subscription/t/050_parallel_apply.pl
@@ -417,4 +417,34 @@ $node_subscriber->safe_psql('postgres', qq[
$node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset);
+# Cleanup
+$node_publisher->safe_psql('postgres', "DELETE FROM regress_tab;");
+$node_publisher->wait_for_catchup('regress_sub');
+
+# Force the leader apply worker to serialize changes to disk
+$node_subscriber->append_conf('postgresql.conf',
+ "debug_logical_replication_streaming = immediate");
+$node_subscriber->reload;
+
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (generate_series(1, 10), 'test');");
+
+$node_publisher->wait_for_catchup('regress_sub');
+
+# Reset to buffered mode so that subsequent tests send changes via shared
+# memory.
+$node_subscriber->append_conf('postgresql.conf',
+ "debug_logical_replication_streaming = buffered");
+$node_subscriber->reload;
+
+# Verify that changes have been serialized
+$node_subscriber->wait_for_log(
+ qr/LOG: ( [A-Z0-9]+:)? logical replication apply worker will serialize the remaining changes of remote transaction \d+ to a file/,
+ $offset);
+
+# Verify that the parallel apply worker can restore serialized changes correctly
+$result =
+ $node_subscriber->safe_psql('postgres', "SELECT count(1) FROM regress_tab");
+is ($result, 10, 'inserts are replicated to subscriber');
+
done_testing();
--
2.43.0
[application/octet-stream] v19-0009-Support-dependency-tracking-via-foreign-keys.patch (17.0K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/4-v19-0009-Support-dependency-tracking-via-foreign-keys.patch)
download | inline diff:
From c05f0b4a0b18feb4d71a01690572fedcbd4f1406 Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Thu, 4 Jun 2026 13:29:18 +0800
Subject: [PATCH v19 09/10] Support dependency tracking via foreign keys
Logical replication's parallel apply mechanism did not account for foreign-key
dependencies. This can cause a failure because the reference column may be
committed before the referenced column.
This patch extends the parallel apply's dependency tracking to account for
foreign keys in the subscriber table. One assumption here is that referenced
columns can be registered to the identity hash table.
The leader apply worker checks to determine whether values in referencing
columns have already been registered or not, and regards that there is a
dependency if found.
---
src/backend/replication/logical/relation.c | 185 ++++++++++++++++++
src/backend/replication/logical/worker.c | 145 ++++++++++++++
src/include/replication/logicalrelation.h | 11 ++
src/test/subscription/t/050_parallel_apply.pl | 53 ++++-
4 files changed, 391 insertions(+), 3 deletions(-)
diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index 6665f5c0cc9..83602dcd4cf 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -21,6 +21,7 @@
#include "access/genam.h"
#include "access/table.h"
#include "catalog/namespace.h"
+#include "catalog/pg_constraint.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_subscription_rel.h"
#include "commands/trigger.h"
@@ -143,6 +144,21 @@ free_local_unique_indexes(LogicalRepRelMapEntry *entry)
entry->local_unique_indexes = NIL;
}
+/*
+ * Release foreign key list
+ */
+static void
+free_local_fkeys(LogicalRepRelMapEntry *entry)
+{
+ Assert(am_leader_apply_worker());
+
+ foreach_ptr(LogicalRepSubscriberFK, fkinfo, entry->local_fkeys)
+ bms_free(fkinfo->conkeys);
+
+ list_free_deep(entry->local_fkeys);
+ entry->local_fkeys = NIL;
+}
+
/*
* Free the entry of a relation map cache.
*/
@@ -173,6 +189,9 @@ logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
if (entry->local_unique_indexes != NIL)
free_local_unique_indexes(entry);
+
+ if (entry->local_fkeys != NIL)
+ free_local_fkeys(entry);
}
/*
@@ -499,6 +518,171 @@ collect_local_indexes(LogicalRepRelMapEntry *entry)
list_free(idxlist);
}
+/*
+ * Search a relmap entry by local relation OID.
+ */
+static LogicalRepRelMapEntry *
+logicalrep_get_relentry_by_local_oid(Oid localreloid)
+{
+ HASH_SEQ_STATUS status;
+ LogicalRepRelMapEntry *entry = NULL;
+
+ if (LogicalRepRelMap == NULL)
+ return NULL;
+
+ /*
+ * Each entry must be checked individually. Because the key of
+ * LogicalRepRelMap is the "remote" relid but we only have the local one.
+ *
+ * Note: This iteration ignores relations that have not yet been
+ * registered in LogicalRepRelMap. It is OK because such relations have
+ * not been modified yet since the subscriber started receiving changes.
+ */
+ hash_seq_init(&status, LogicalRepRelMap);
+ while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
+ {
+ if (entry->localreloid == localreloid)
+ {
+ hash_seq_term(&status);
+ return entry;
+ }
+ }
+
+ return NULL;
+}
+
+/*
+ * Return true if the FK constraint is always deferred.
+ */
+static bool
+foreign_key_is_always_deferred(Oid conoid)
+{
+ HeapTuple tup;
+ Form_pg_constraint con;
+ bool deferred;
+
+ tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(conoid));
+ if (!HeapTupleIsValid(tup))
+ elog(ERROR, "cache lookup failed for foreign key %u", conoid);
+
+ con = (Form_pg_constraint) GETSTRUCT(tup);
+ deferred = con->condeferrable && con->condeferred;
+ ReleaseSysCache(tup);
+
+ return deferred;
+}
+
+/*
+ * Collect all local foreign keys that can be used for dependency tracking.
+ */
+static void
+collect_local_fkeys(LogicalRepRelMapEntry *entry)
+{
+ List *fkeys;
+
+ if (entry->local_fkeys != NIL)
+ free_local_fkeys(entry);
+
+ entry->local_fkeys_collected = true;
+
+ /*
+ * Get the list of foreign keys for the relation.
+ *
+ * XXX: Apart from RelationGetIndexList(), the returned list is a part of
+ * relcache and must be copied before doing anything. See comments atop
+ * RelationGetFKeyList().
+ */
+ fkeys = copyObject(RelationGetFKeyList(entry->localrel));
+
+ /* Quick exit if there are no foreign keys */
+ if (fkeys == NIL)
+ return;
+
+ foreach_ptr(ForeignKeyCacheInfo, fk, fkeys)
+ {
+ LogicalRepRelMapEntry *refentry;
+ Bitmapset *fkkeys = NULL;
+ bool suitable = true;
+
+ /*
+ * Skip NOT ENFORCED constraints because they won't be checked at any
+ * times.
+ */
+ if (!fk->conenforced)
+ continue;
+
+ /*
+ * Skip if the foreign key constraint is always deferred. The commit
+ * ordering is always preserved thus the constraint can be checked in
+ * correct order.
+ */
+ if (foreign_key_is_always_deferred(fk->conoid))
+ continue;
+
+ /* Find the referenced relation by the local OID */
+ refentry = logicalrep_get_relentry_by_local_oid(fk->confrelid);
+
+ /*
+ * Skip if the referenced relation is not the target of this
+ * subscription.
+ */
+ if (!refentry)
+ continue;
+
+ /* Seek each attributes and add to a Bitmap */
+ for (int i = 0; i < fk->nkeys; i++)
+ {
+ AttrNumber localcol = fk->conkey[i];
+ int remotecol =
+ entry->attrmap->attnums[AttrNumberGetAttrOffset(localcol)];
+
+ /* Skip if the column does not exist on publisher node */
+ if (remotecol < 0)
+ {
+ suitable = false;
+ break;
+ }
+
+ /*
+ * XXX: What if the FK column is specified with different order?
+ * E.g., there is a table (a, b) and other table refers like
+ * REFERENCES (b, a). Will it work correctly?
+ */
+ fkkeys = bms_add_member(fkkeys, remotecol);
+ }
+
+ /*
+ * One of the columns does not exist on the publisher side, skip such
+ * a constraint.
+ */
+ if (!suitable)
+ {
+ if (fkkeys)
+ bms_free(fkkeys);
+
+ continue;
+ }
+
+ if (fkkeys)
+ {
+ MemoryContext oldctx;
+ LogicalRepSubscriberFK *fkinfo;
+
+ oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
+ fkinfo = palloc(sizeof(LogicalRepSubscriberFK));
+ fkinfo->conoid = fk->conoid;
+ fkinfo->ref_remoteid = refentry->remoterel.remoteid;
+ fkinfo->conkeys = bms_copy(fkkeys);
+
+ bms_free(fkkeys);
+ entry->local_fkeys = lappend(entry->local_fkeys, fkinfo);
+ MemoryContextSwitchTo(oldctx);
+ }
+ }
+
+ list_free_deep(fkeys);
+}
+
/*
* Check all local triggers for the relation to see the parallelizability.
*
@@ -715,6 +899,7 @@ logicalrep_rel_load(LogicalRepRelMapEntry *entry, LogicalRepRelId remoteid,
{
entry->parallel_safe = LOGICALREP_PARALLEL_UNKNOWN;
collect_local_indexes(entry);
+ collect_local_fkeys(entry);
check_defined_triggers(entry);
}
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index a212bc6013d..6f8d83c6b7b 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -1205,6 +1205,138 @@ check_and_record_local_key_dependency(Oid relid,
}
}
+/*
+ * Lookup-only dependency check by key. Does not register/update entries.
+ */
+static void
+find_dependencies_by_key(ReplicaIdentityKey *key,
+ TransactionId new_depended_xid,
+ List **depends_on_xids)
+{
+ ReplicaIdentityEntry *rientry;
+ MemoryContext oldctx;
+
+ Assert(replica_identity_table);
+
+ oldctx = MemoryContextSwitchTo(ApplyContext);
+
+ rientry = replica_identity_lookup(replica_identity_table, key);
+ free_replica_identity_key(key);
+
+ MemoryContextSwitchTo(oldctx);
+
+ /*
+ * Return if no entry exists, or if the current transaction was the last one
+ * to modify the key.
+ */
+ if (!rientry || TransactionIdEquals(rientry->remote_xid, new_depended_xid))
+ return;
+
+ /*
+ * Clean up committed entries while on it.
+ */
+ if (pa_transaction_committed(rientry->remote_xid))
+ {
+ free_replica_identity_key(rientry->keydata);
+ replica_identity_delete_item(replica_identity_table, rientry);
+ return;
+ }
+
+ check_and_append_xid_dependency(&rientry->remote_xid, depends_on_xids);
+}
+
+/*
+ * Check for dependencies on preceding transactions that modify the referenced
+ * unique key of foreign keys.
+ */
+static void
+check_and_record_fkey_dependency(Oid relid,
+ LogicalRepTupleData *original_data,
+ TransactionId new_depended_xid,
+ List **depends_on_xids)
+{
+ LogicalRepRelMapEntry *relentry;
+ LogicalRepTupleData *ridata;
+ ReplicaIdentityKey *rikey;
+ MemoryContext oldctx;
+
+ Assert(depends_on_xids);
+
+ relentry = logicalrep_get_relentry(relid);
+
+ Assert(relentry);
+
+ /*
+ * We have already checked the local unique indexes and also gathered the
+ * FK info at that time.
+ *
+ * XXX: Should we check and load again?
+ */
+ Assert(relentry->local_fkeys_collected);
+
+ foreach_ptr(LogicalRepSubscriberFK, fkinfo, relentry->local_fkeys)
+ {
+ int columns = bms_num_members(fkinfo->conkeys);
+ bool suitable = true;
+
+ Assert(columns);
+
+ for (int i = 0; i < original_data->ncols; i++)
+ {
+ if (!bms_is_member(i, fkinfo->conkeys))
+ continue;
+
+ /* Skip if the column is NULL or not changed */
+ if (original_data->colstatus[i] == LOGICALREP_COLUMN_NULL ||
+ original_data->colstatus[i] == LOGICALREP_COLUMN_UNCHANGED)
+ {
+ suitable = false;
+ break;
+ }
+ }
+
+ if (!suitable)
+ continue;
+
+ oldctx = MemoryContextSwitchTo(ApplyContext);
+
+ /* Allocate space for replica identity values */
+ ridata = palloc0_object(LogicalRepTupleData);
+ ridata->colvalues = palloc0_array(StringInfoData, columns);
+ ridata->colstatus = palloc0_array(char, columns);
+ ridata->ncols = columns;
+
+ for (int i_original = 0, i_key = 0; i_original < original_data->ncols; i_original++)
+ {
+ StringInfo original_colvalue;
+
+ if (!bms_is_member(i_original, fkinfo->conkeys))
+ continue;
+
+ original_colvalue = &original_data->colvalues[i_original];
+ initStringInfoExt(&ridata->colvalues[i_key], original_colvalue->len + 1);
+ appendStringInfoString(&ridata->colvalues[i_key], original_colvalue->data);
+
+ ridata->colstatus[i_key] = original_data->colstatus[i_original];
+ i_key++;
+ }
+
+ rikey = palloc0_object(ReplicaIdentityKey);
+ rikey->relid = fkinfo->ref_remoteid;
+
+ /*
+ * XXX: use LOGICALREP_KEY_LOCAL_UNIQUE to compare with local unique
+ * indexes.
+ */
+ rikey->kind = LOGICALREP_KEY_LOCAL_UNIQUE;
+ rikey->data = ridata;
+
+ MemoryContextSwitchTo(oldctx);
+
+ find_dependencies_by_key(rikey, new_depended_xid, depends_on_xids);
+ }
+}
+
/*
* Check for preceding transactions (other than current one 'new_depended_xid')
* that involve insert, delete, or update operations on the specified table, and
@@ -1402,6 +1534,9 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
check_and_record_local_key_dependency(relid, &newtup,
new_depended_xid,
&depends_on_xids);
+ check_and_record_fkey_dependency(relid, &newtup,
+ new_depended_xid,
+ &depends_on_xids);
check_dependency_for_parallel_safety(relid, new_depended_xid,
&depends_on_xids);
break;
@@ -1419,6 +1554,10 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
new_depended_xid,
&depends_on_xids);
+ check_and_record_fkey_dependency(relid, &oldtup,
+ new_depended_xid,
+ &depends_on_xids);
+
check_dependency_for_parallel_safety(relid, new_depended_xid,
&depends_on_xids);
@@ -1437,6 +1576,9 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
check_and_record_local_key_dependency(relid, &newtup,
new_depended_xid,
&depends_on_xids);
+ check_and_record_fkey_dependency(relid, &newtup,
+ new_depended_xid,
+ &depends_on_xids);
check_dependency_for_parallel_safety(relid, new_depended_xid,
&depends_on_xids);
break;
@@ -1448,6 +1590,9 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
check_and_record_local_key_dependency(relid, &oldtup,
new_depended_xid,
&depends_on_xids);
+ check_and_record_fkey_dependency(relid, &oldtup,
+ new_depended_xid,
+ &depends_on_xids);
check_dependency_for_parallel_safety(relid, new_depended_xid,
&depends_on_xids);
break;
diff --git a/src/include/replication/logicalrelation.h b/src/include/replication/logicalrelation.h
index 241c4dda13c..ff25cd3ce4f 100644
--- a/src/include/replication/logicalrelation.h
+++ b/src/include/replication/logicalrelation.h
@@ -22,6 +22,13 @@ typedef struct LogicalRepSubscriberIdx
Bitmapset *indexkeys; /* Bitmap of key columns *on remote* */
} LogicalRepSubscriberIdx;
+typedef struct LogicalRepSubscriberFK
+{
+ Oid conoid; /* OID of the FK constraint */
+ LogicalRepRelId ref_remoteid; /* referenced remote relid */
+ Bitmapset *conkeys; /* Bitmap of key columns *on remote* */
+} LogicalRepSubscriberFK;
+
typedef struct LogicalRepRelMapEntry
{
LogicalRepRelation remoterel; /* key is remoterel.remoteid */
@@ -56,6 +63,10 @@ typedef struct LogicalRepRelMapEntry
List *local_unique_indexes;
bool local_unique_indexes_collected;
+ /* Local foreign keys. Used for dependency tracking */
+ List *local_fkeys;
+ bool local_fkeys_collected;
+
/*
* Whether the relation can be applied in parallel or not. It is
* distinglish whether defined triggers are the immutable or not.
diff --git a/src/test/subscription/t/050_parallel_apply.pl b/src/test/subscription/t/050_parallel_apply.pl
index ae539f84639..896244a42fd 100644
--- a/src/test/subscription/t/050_parallel_apply.pl
+++ b/src/test/subscription/t/050_parallel_apply.pl
@@ -33,6 +33,8 @@ $node_publisher->safe_psql(
CREATE UNIQUE INDEX tab_toast_ri_index on tab_toast (a, b);
ALTER TABLE tab_toast REPLICA IDENTITY USING INDEX tab_toast_ri_index;
INSERT INTO tab_toast(a, b) VALUES(repeat('1234567890', 200), '1234567890');
+
+ CREATE TABLE regress_tab_fk (id int PRIMARY KEY, fk int);
));
$node_publisher->safe_psql('postgres',
"INSERT INTO regress_tab VALUES (generate_series(1, 10), 'test');");
@@ -71,6 +73,8 @@ $node_subscriber->safe_psql(
ALTER TABLE tab_toast ALTER COLUMN a SET STORAGE EXTERNAL;
CREATE UNIQUE INDEX tab_toast_ri_index on tab_toast (a, b);
ALTER TABLE tab_toast REPLICA IDENTITY USING INDEX tab_toast_ri_index;
+
+ CREATE TABLE regress_tab_fk (id int PRIMARY KEY, fk int REFERENCES regress_tab (id));
));
$node_subscriber->safe_psql('postgres',
"CREATE SUBSCRIPTION regress_sub CONNECTION '$publisher_connstr' PUBLICATION regress_pub;");
@@ -315,8 +319,8 @@ $h->query_safe("COMMIT;");
# subscriber during parallel apply.
##################################################
-# Truncate the data for upcoming tests
-$node_publisher->safe_psql('postgres', "TRUNCATE TABLE regress_tab;");
+# delete the data for upcoming tests
+$node_publisher->safe_psql('postgres', "DELETE FROM regress_tab;");
$node_publisher->wait_for_catchup('regress_sub');
# Define an unique index on subscriber
@@ -367,7 +371,50 @@ $node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset
# Cleanup
$node_subscriber->safe_psql('postgres', "DROP INDEX regress_tab_value_idx;");
-$node_publisher->safe_psql('postgres', "TRUNCATE TABLE regress_tab;");
+$node_publisher->safe_psql('postgres', "DELETE FROM regress_tab;");
+$node_publisher->wait_for_catchup('regress_sub');
+
+##################################################
+# Test that the dependency tracking works correctly for local foreign key on
+# subscriber during parallel apply.
+##################################################
+
+# Insert an initial tuple
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (1, 'initial tuple');");
$node_publisher->wait_for_catchup('regress_sub');
+# Attach an injection_point. Parallel workers would wait before the commit
+$node_subscriber->safe_psql('postgres',
+ "SELECT injection_points_attach('parallel-worker-before-commit','wait');"
+);
+
+# Insert a tuple on publisher. Parallel worker would wait at the injection
+# point
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (2, 'tmp');");
+
+# Wait until the parallel worker enters the injection point.
+$node_subscriber->wait_for_event('logical replication parallel worker',
+ 'parallel-worker-before-commit');
+
+$offset = -s $node_subscriber->logfile;
+
+# Insert tuples on publisher again. This transaction waits for referring tuple
+# is committed.
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab_fk VALUES (1, 1);");
+
+# Verify the parallel worker waits for the transaction
+$str = $node_subscriber->wait_for_log(qr/wait for depended xid ([1-9][0-9]+)/, $offset);
+$xid = $str =~ /wait for depended xid ([1-9][0-9]+)/;
+
+# Wakeup the parallel worker
+$node_subscriber->safe_psql('postgres', qq[
+ SELECT injection_points_detach('parallel-worker-before-commit');
+ SELECT injection_points_wakeup('parallel-worker-before-commit');
+]);
+
+$node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset);
+
done_testing();
--
2.43.0
[application/octet-stream] v19-0008-Support-dependency-tracking-via-local-unique-ind.patch (24.0K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/5-v19-0008-Support-dependency-tracking-via-local-unique-ind.patch)
download | inline diff:
From 2cb151a82e8c33fe8d9ff2c8d83208a90df85c9f Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Thu, 4 Jun 2026 13:23:55 +0800
Subject: [PATCH v19 08/10] Support dependency tracking via local unique
indexes
Currently, logical replication's parallel apply mechanism tracks dependencies
primarily based on the REPLICA IDENTITY defined on the publisher table.
However, local subscriber tables might have additional unique indexes that
could effectively serve as dependency keys, even if they don't correspond to
the publisher's REPLICA IDENTITY. Failing to track these additional unique
keys can lead to incorrect data and/or deadlocks during parallel application.
This patch extends the parallel apply's dependency tracking to consider
local unique indexes on the subscriber table. This is achieved by extending
the existing Replica Identity hash table to also store dependency information
based on these local unique indexes.
The LogicalRepRelMapEntry structure is extended to store details about these
local unique indexes. This information is collected and cached when
dependency checking is first performed for a remote transaction on a given
relation. This collection process requires to be in a transaction to access
system catalog information.
---
src/backend/replication/logical/relation.c | 161 ++++++++++-
src/backend/replication/logical/worker.c | 252 ++++++++++++++----
src/backend/storage/lmgr/deadlock.c | 1 -
src/include/replication/logicalrelation.h | 14 +
src/test/subscription/t/050_parallel_apply.pl | 60 +++++
src/tools/pgindent/typedefs.list | 2 +
6 files changed, 439 insertions(+), 51 deletions(-)
diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index eeb85f8cc5d..6665f5c0cc9 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -128,6 +128,21 @@ logicalrep_relmap_init(void)
(Datum) 0);
}
+/*
+ * Release local index list
+ */
+static void
+free_local_unique_indexes(LogicalRepRelMapEntry *entry)
+{
+ Assert(am_leader_apply_worker());
+
+ foreach_ptr(LogicalRepSubscriberIdx, idxinfo, entry->local_unique_indexes)
+ bms_free(idxinfo->indexkeys);
+
+ list_free_deep(entry->local_unique_indexes);
+ entry->local_unique_indexes = NIL;
+}
+
/*
* Free the entry of a relation map cache.
*/
@@ -155,6 +170,9 @@ logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
if (entry->attrmap)
free_attrmap(entry->attrmap);
+
+ if (entry->local_unique_indexes != NIL)
+ free_local_unique_indexes(entry);
}
/*
@@ -361,6 +379,126 @@ logicalrep_rel_mark_updatable(LogicalRepRelMapEntry *entry)
}
}
+/*
+ * Collect all local unique indexes that can be used for dependency tracking.
+ */
+static void
+collect_local_indexes(LogicalRepRelMapEntry *entry)
+{
+ List *idxlist;
+
+ if (entry->local_unique_indexes != NIL)
+ free_local_unique_indexes(entry);
+
+ entry->local_unique_indexes_collected = true;
+
+ idxlist = RelationGetIndexList(entry->localrel);
+
+ /* Quick exit if there are no indexes */
+ if (idxlist == NIL)
+ return;
+
+ /* Iterate indexes to list all usable indexes */
+ foreach_oid(idxoid, idxlist)
+ {
+ Relation idxrel;
+ int indnkeys;
+ AttrMap *attrmap;
+ Bitmapset *indexkeys = NULL;
+ bool suitable = true;
+
+ idxrel = index_open(idxoid, AccessShareLock);
+
+ /*
+ * Check whether the index can be used for the dependency tracking.
+ *
+ * For simplification, the same condition as REPLICA IDENTITY FULL,
+ * plus it must be a unique index.
+ */
+ if (!(idxrel->rd_index->indisunique &&
+ IsIndexUsableForReplicaIdentityFull(idxrel, entry->attrmap)))
+ {
+ index_close(idxrel, AccessShareLock);
+ continue;
+ }
+
+ indnkeys = idxrel->rd_index->indnkeyatts;
+ attrmap = entry->attrmap;
+
+ Assert(indnkeys);
+
+ /* Seek each attributes and add to a Bitmap */
+ for (int i = 0; i < indnkeys; i++)
+ {
+ AttrNumber localcol = idxrel->rd_index->indkey.values[i];
+ AttrNumber remotecol;
+
+ /*
+ * XXX: Mark a relation as parallel-unsafe if it has expression
+ * indexes because we cannot compute the hash value for the
+ * dependency tracking. For safety, transactions that modify such
+ * tables can wait for applications till the lastly dispatched
+ * transaction is committed.
+ */
+ if (!AttributeNumberIsValid(localcol))
+ {
+ entry->parallel_safe = LOGICALREP_PARALLEL_RESTRICTED;
+ suitable = false;
+ break;
+ }
+
+ remotecol = attrmap->attnums[AttrNumberGetAttrOffset(localcol)];
+
+ /*
+ * Skip if the column does not exist on publisher node. In this
+ * case the replicated tuples always have NULL or default value.
+ */
+ if (remotecol < 0)
+ {
+ suitable = false;
+ break;
+ }
+
+ /* Checks are passed, remember the attribute */
+ indexkeys = bms_add_member(indexkeys, remotecol);
+ }
+
+ index_close(idxrel, AccessShareLock);
+
+ /*
+ * Skip using the index if it is not suitable. This can happen if 1)
+ * one of the columns does not exist on the publisher side, or 2)
+ * there is an expression column.
+ */
+ if (!suitable)
+ {
+ if (indexkeys)
+ bms_free(indexkeys);
+
+ continue;
+ }
+
+ /* This index is usable, store on memory */
+ if (indexkeys)
+ {
+ MemoryContext oldctx;
+ LogicalRepSubscriberIdx *idxinfo;
+
+ oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
+ idxinfo = palloc(sizeof(LogicalRepSubscriberIdx));
+ idxinfo->indexoid = idxoid;
+ idxinfo->indexkeys = bms_copy(indexkeys);
+ entry->local_unique_indexes =
+ lappend(entry->local_unique_indexes, idxinfo);
+
+ pfree(indexkeys);
+ MemoryContextSwitchTo(oldctx);
+ }
+ }
+
+ list_free(idxlist);
+}
+
/*
* Check all local triggers for the relation to see the parallelizability.
*
@@ -370,7 +508,16 @@ logicalrep_rel_mark_updatable(LogicalRepRelMapEntry *entry)
static void
check_defined_triggers(LogicalRepRelMapEntry *entry)
{
- TriggerDesc *trigdesc = entry->localrel->trigdesc;
+ TriggerDesc *trigdesc;
+
+ /*
+ * Skip if the parallelizability has already been checked. Possilble if
+ * the relation has expression indexes.
+ */
+ if (entry->parallel_safe != LOGICALREP_PARALLEL_UNKNOWN)
+ return;
+
+ trigdesc = entry->localrel->trigdesc;
/* Quick exit if triffer is not defined */
if (trigdesc == NULL)
@@ -411,7 +558,7 @@ check_defined_triggers(LogicalRepRelMapEntry *entry)
* If the key is given, the corresponding entry is first searched in the hash
* table and processed as in the above case. At the end, logical replication is
* closed.
- */
+ */
void
logicalrep_rel_load(LogicalRepRelMapEntry *entry, LogicalRepRelId remoteid,
LOCKMODE lockmode)
@@ -565,7 +712,11 @@ logicalrep_rel_load(LogicalRepRelMapEntry *entry, LogicalRepRelId remoteid,
* tracking.
*/
if (am_leader_apply_worker())
+ {
+ entry->parallel_safe = LOGICALREP_PARALLEL_UNKNOWN;
+ collect_local_indexes(entry);
check_defined_triggers(entry);
+ }
entry->localrelvalid = true;
}
@@ -867,6 +1018,12 @@ logicalrep_partition_open(LogicalRepRelMapEntry *root,
entry->localindexoid = FindLogicalRepLocalIndex(partrel, remoterel,
entry->attrmap);
+ /*
+ * TODO: Parallel apply does not support the parallel apply for now. Just
+ * mark local indexes are collected.
+ */
+ entry->local_unique_indexes_collected = true;
+
entry->localrelvalid = true;
return entry;
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index de665b8d4b3..a212bc6013d 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -578,10 +578,20 @@ typedef struct ApplySubXactData
static ApplySubXactData subxact_data = {0, 0, InvalidTransactionId, NULL};
+/*
+ * Type of key used for dependency tracking.
+ */
+typedef enum LogicalRepKeyKind
+{
+ LOGICALREP_KEY_REPLICA_IDENTITY,
+ LOGICALREP_KEY_LOCAL_UNIQUE
+} LogicalRepKeyKind;
+
/* Hash table key for replica_identity_table */
typedef struct ReplicaIdentityKey
{
Oid relid;
+ LogicalRepKeyKind kind;
LogicalRepTupleData *data;
} ReplicaIdentityKey;
@@ -760,7 +770,8 @@ static bool
hash_replica_identity_compare(ReplicaIdentityKey *a, ReplicaIdentityKey *b)
{
if (a->relid != b->relid ||
- a->data->ncols != b->data->ncols)
+ a->data->ncols != b->data->ncols ||
+ a->kind != b->kind)
return false;
for (int i = 0; i < a->data->ncols; i++)
@@ -768,6 +779,9 @@ hash_replica_identity_compare(ReplicaIdentityKey *a, ReplicaIdentityKey *b)
if (a->data->colstatus[i] != b->data->colstatus[i])
return false;
+ if (a->data->colstatus[i] == LOGICALREP_COLUMN_NULL)
+ continue;
+
if (a->data->colvalues[i].len != b->data->colvalues[i].len)
return false;
@@ -895,6 +909,89 @@ check_and_append_xid_dependency(TransactionId *xid, List **depends_on_xids)
*depends_on_xids = lappend_xid(*depends_on_xids, *xid);
}
+/*
+ * Common function for checking dependency by using the key. Used by both
+ * check_and_record_ri_dependency and check_and_record_local_key_dependency.
+ */
+static void
+check_and_record_key_dependency(ReplicaIdentityKey *key,
+ TransactionId new_depended_xid,
+ List **depends_on_xids)
+{
+ ReplicaIdentityEntry *rientry;
+ bool found = false;
+
+ /*
+ * The new xid could be invalid if the transaction will be applied by the
+ * leader itself which means all the changes will be committed before
+ * processing next transaction. In this case, we only need to check for
+ * dependencies on preceding transactions, there is no need to record a new
+ * dependency for subsequent transactions to wait on.
+ */
+ if (!TransactionIdIsValid(new_depended_xid))
+ {
+ rientry = replica_identity_lookup(replica_identity_table, key);
+ free_replica_identity_key(key);
+
+ /* No dependency detected */
+ if (!rientry)
+ return;
+
+ elog(DEBUG1,
+ key->kind == LOGICALREP_KEY_REPLICA_IDENTITY ?
+ "found conflicting replica identity change from %u" :
+ "found conflicting local unique change from %u",
+ rientry->remote_xid);
+
+ Assert(TransactionIdIsValid(rientry->remote_xid));
+ check_and_append_xid_dependency(&rientry->remote_xid, depends_on_xids);
+
+ /*
+ * Remove the entry if the remote transaction has been committed locally
+ * and no new dependency needs to be added.
+ */
+ if (!TransactionIdIsValid(rientry->remote_xid))
+ {
+ free_replica_identity_key(rientry->keydata);
+ replica_identity_delete_item(replica_identity_table, rientry);
+ }
+
+ return;
+ }
+
+ /* Record a new dependency for subsequent transactions to wait on */
+ rientry = replica_identity_insert(replica_identity_table, key,
+ &found);
+
+ /*
+ * Release the key built to search the entry, if the entry already exists.
+ */
+ if (found)
+ {
+ Assert(TransactionIdIsValid(rientry->remote_xid));
+
+ elog(DEBUG1,
+ key->kind == LOGICALREP_KEY_REPLICA_IDENTITY ?
+ "found conflicting replica identity change from %u" :
+ "found conflicting local unique change from %u",
+ rientry->remote_xid);
+
+ free_replica_identity_key(key);
+
+ /*
+ * Return if the current transaction was the last one to modify the
+ * key.
+ */
+ if (TransactionIdEquals(rientry->remote_xid, new_depended_xid))
+ return;
+
+ check_and_append_xid_dependency(&rientry->remote_xid, depends_on_xids);
+ }
+
+ /* Update the new depended xid into the entry */
+ rientry->remote_xid = new_depended_xid;
+}
+
/*
* Check for dependencies on preceding transactions that modify the same key.
* Returns the dependent transactions in 'depends_on_xids'.
@@ -911,10 +1008,8 @@ check_and_record_ri_dependency(Oid relid, LogicalRepTupleData *original_data,
LogicalRepRelMapEntry *relentry;
LogicalRepTupleData *ridata;
ReplicaIdentityKey *rikey;
- ReplicaIdentityEntry *rientry;
MemoryContext oldctx;
int n_ri;
- bool found = false;
Assert(depends_on_xids);
@@ -993,73 +1088,121 @@ check_and_record_ri_dependency(Oid relid, LogicalRepTupleData *original_data,
rikey = palloc0_object(ReplicaIdentityKey);
rikey->relid = relid;
+ rikey->kind = LOGICALREP_KEY_REPLICA_IDENTITY;
rikey->data = ridata;
MemoryContextSwitchTo(oldctx);
+ check_and_record_key_dependency(rikey, new_depended_xid, depends_on_xids);
+}
+
+/*
+ * Mostly same as check_and_record_ri_dependency() but for local unique indexes.
+ */
+static void
+check_and_record_local_key_dependency(Oid relid,
+ LogicalRepTupleData *original_data,
+ TransactionId new_depended_xid,
+ List **depends_on_xids)
+{
+ LogicalRepRelMapEntry *relentry;
+ LogicalRepTupleData *ridata;
+ ReplicaIdentityKey *rikey;
+ MemoryContext oldctx;
+
+ Assert(depends_on_xids);
+
+ /* Search for existing entry */
+ relentry = logicalrep_get_relentry(relid);
+
+ Assert(relentry);
/*
- * The new xid could be invalid if the transaction will be applied by the
- * leader itself which means all the changes will be committed before
- * processing next transaction. In this case, we only need to check for
- * dependencies on preceding transactions, there is no need to record a new
- * dependency for subsequent transactions to wait on.
+ * Gather information for local indexes if not yet. We require to be in a
+ * transaction state because system catalogs are read.
*/
- if (!TransactionIdIsValid(new_depended_xid))
+ if (!relentry->local_unique_indexes_collected)
{
- rientry = replica_identity_lookup(replica_identity_table, rikey);
- free_replica_identity_key(rikey);
-
- /* No dependency detected */
- if (!rientry)
- return;
+ bool needs_start = !IsTransactionOrTransactionBlock();
- elog(DEBUG1, "found conflicting replica identity change from %u",
- rientry->remote_xid);
+ if (needs_start)
+ StartTransactionCommand();
- Assert(TransactionIdIsValid(rientry->remote_xid));
- check_and_append_xid_dependency(&rientry->remote_xid, depends_on_xids);
+ logicalrep_rel_load(NULL, relid, AccessShareLock);
/*
- * Remove the entry if the remote transaction has been committed locally
- * and no new dependency needs to be added.
+ * Close the transaction if we start here. We must not abort because
+ * it would release all session-level locks, such as the stream lock,
+ * and break the deadlock detection mechanism between LA and PA. The
+ * outcome is the same regardless of the end status, since the
+ * transaction did not modify any tuples.
*/
- if (!TransactionIdIsValid(rientry->remote_xid))
+ if (needs_start)
+ CommitTransactionCommand();
+
+ Assert(relentry->local_unique_indexes_collected);
+ }
+
+ foreach_ptr(LogicalRepSubscriberIdx, idxinfo, relentry->local_unique_indexes)
+ {
+ int columns = bms_num_members(idxinfo->indexkeys);
+ bool suitable = true;
+
+ Assert(columns);
+
+ for (int i = 0; i < original_data->ncols; i++)
{
- free_replica_identity_key(rientry->keydata);
- replica_identity_delete_item(replica_identity_table, rientry);
+ if (!bms_is_member(i, idxinfo->indexkeys))
+ continue;
+
+ /*
+ * Skip if the column is not changed.
+ *
+ * XXX: NULL is allowed.
+ */
+ if (original_data->colstatus[i] == LOGICALREP_COLUMN_UNCHANGED)
+ {
+ suitable = false;
+ break;
+ }
}
- return;
- }
+ if (!suitable)
+ continue;
- /* Record a new dependency for subsequent transactions to wait on */
- rientry = replica_identity_insert(replica_identity_table, rikey,
- &found);
+ oldctx = MemoryContextSwitchTo(ApplyContext);
- /*
- * Release the key built to search the entry, if the entry already exists.
- */
- if (found)
- {
- Assert(TransactionIdIsValid(rientry->remote_xid));
+ /* Allocate space for replica identity values */
+ ridata = palloc0_object(LogicalRepTupleData);
+ ridata->colvalues = palloc0_array(StringInfoData, columns);
+ ridata->colstatus = palloc0_array(char, columns);
+ ridata->ncols = columns;
- elog(DEBUG1, "found conflicting replica identity change from %u",
- rientry->remote_xid);
+ for (int i_original = 0, i_key = 0; i_original < original_data->ncols; i_original++)
+ {
+ if (!bms_is_member(i_original, idxinfo->indexkeys))
+ continue;
- free_replica_identity_key(rikey);
+ if (original_data->colstatus[i_original] != LOGICALREP_COLUMN_NULL)
+ {
+ StringInfo original_colvalue = &original_data->colvalues[i_original];
- /*
- * Return if the current transaction was the last one to modify the
- * key.
- */
- if (TransactionIdEquals(rientry->remote_xid, new_depended_xid))
- return;
+ initStringInfoExt(&ridata->colvalues[i_key], original_colvalue->len + 1);
+ appendStringInfoString(&ridata->colvalues[i_key], original_colvalue->data);
+ }
- check_and_append_xid_dependency(&rientry->remote_xid, depends_on_xids);
- }
+ ridata->colstatus[i_key] = original_data->colstatus[i_original];
+ i_key++;
+ }
- /* Update the new depended xid into the entry */
- rientry->remote_xid = new_depended_xid;
+ rikey = palloc0_object(ReplicaIdentityKey);
+ rikey->relid = relid;
+ rikey->kind = LOGICALREP_KEY_LOCAL_UNIQUE;
+ rikey->data = ridata;
+
+ MemoryContextSwitchTo(oldctx);
+
+ check_and_record_key_dependency(rikey, new_depended_xid, depends_on_xids);
+ }
}
/*
@@ -1256,6 +1399,9 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
relid = logicalrep_read_insert(&change, &newtup);
check_and_record_ri_dependency(relid, &newtup, new_depended_xid,
&depends_on_xids);
+ check_and_record_local_key_dependency(relid, &newtup,
+ new_depended_xid,
+ &depends_on_xids);
check_dependency_for_parallel_safety(relid, new_depended_xid,
&depends_on_xids);
break;
@@ -1269,6 +1415,10 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
check_and_record_ri_dependency(relid, &oldtup, new_depended_xid,
&depends_on_xids);
+ check_and_record_local_key_dependency(relid, &oldtup,
+ new_depended_xid,
+ &depends_on_xids);
+
check_dependency_for_parallel_safety(relid, new_depended_xid,
&depends_on_xids);
@@ -1284,6 +1434,9 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
check_and_record_ri_dependency(relid, &newtup, new_depended_xid,
&depends_on_xids);
+ check_and_record_local_key_dependency(relid, &newtup,
+ new_depended_xid,
+ &depends_on_xids);
check_dependency_for_parallel_safety(relid, new_depended_xid,
&depends_on_xids);
break;
@@ -1292,6 +1445,9 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
relid = logicalrep_read_delete(&change, &oldtup);
check_and_record_ri_dependency(relid, &oldtup, new_depended_xid,
&depends_on_xids);
+ check_and_record_local_key_dependency(relid, &oldtup,
+ new_depended_xid,
+ &depends_on_xids);
check_dependency_for_parallel_safety(relid, new_depended_xid,
&depends_on_xids);
break;
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..31bbfcf1971 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -33,7 +33,6 @@
#include "storage/procnumber.h"
#include "utils/memutils.h"
-
/*
* One edge in the waits-for graph.
*
diff --git a/src/include/replication/logicalrelation.h b/src/include/replication/logicalrelation.h
index b1079d3f2fa..241c4dda13c 100644
--- a/src/include/replication/logicalrelation.h
+++ b/src/include/replication/logicalrelation.h
@@ -16,6 +16,12 @@
#include "catalog/index.h"
#include "replication/logicalproto.h"
+typedef struct LogicalRepSubscriberIdx
+{
+ Oid indexoid; /* OID of the local key */
+ Bitmapset *indexkeys; /* Bitmap of key columns *on remote* */
+} LogicalRepSubscriberIdx;
+
typedef struct LogicalRepRelMapEntry
{
LogicalRepRelation remoterel; /* key is remoterel.remoteid */
@@ -46,6 +52,10 @@ typedef struct LogicalRepRelMapEntry
*/
TransactionId last_depended_xid;
+ /* Local unique indexes. Used for dependency tracking */
+ List *local_unique_indexes;
+ bool local_unique_indexes_collected;
+
/*
* Whether the relation can be applied in parallel or not. It is
* distinglish whether defined triggers are the immutable or not.
@@ -57,6 +67,10 @@ typedef struct LogicalRepRelMapEntry
* Note that we do not check the user-defined constraints here. PostgreSQL
* has already assumed that CHECK constraints' conditions are immutable and
* here follows the rule.
+ *
+ * XXX: Additonally, this can be false if the relation has expression
+ * indexes. Because we cannot compute the hash value for the dependency
+ * tracking.
*/
char parallel_safe;
} LogicalRepRelMapEntry;
diff --git a/src/test/subscription/t/050_parallel_apply.pl b/src/test/subscription/t/050_parallel_apply.pl
index 04441ca1cd0..ae539f84639 100644
--- a/src/test/subscription/t/050_parallel_apply.pl
+++ b/src/test/subscription/t/050_parallel_apply.pl
@@ -310,4 +310,64 @@ $node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset
$h->query_safe("COMMIT;");
+##################################################
+# Test that the dependency tracking works correctly for local unique indexes on
+# subscriber during parallel apply.
+##################################################
+
+# Truncate the data for upcoming tests
+$node_publisher->safe_psql('postgres', "TRUNCATE TABLE regress_tab;");
+$node_publisher->wait_for_catchup('regress_sub');
+
+# Define an unique index on subscriber
+$node_subscriber->safe_psql('postgres',
+ "CREATE INDEX ON regress_tab (value);");
+
+# Attach an injection_point. Parallel workers would wait before the commit
+$node_subscriber->safe_psql('postgres',
+ "SELECT injection_points_attach('parallel-worker-before-commit','wait');"
+);
+
+# Insert a tuple on publisher. Parallel worker would wait at the injection
+# point
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (1, 'would conflict');");
+
+# Wait until the parallel worker enters the injection point.
+$node_subscriber->wait_for_event('logical replication parallel worker',
+ 'parallel-worker-before-commit');
+
+$offset = -s $node_subscriber->logfile;
+
+# Insert tuples on publisher again. This transaction is would wait because all
+# parallel workers wait till the previously launched worker commits.
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (2, 'would not conflict');");
+
+# Verify the parallel worker waits for the transaction
+$str = $node_subscriber->wait_for_log(qr/wait for depended xid ([1-9][0-9]+)/, $offset);
+$xid = $str =~ /wait for depended xid ([1-9][0-9]+)/;
+
+# Insert a conflicting tuple on publisher. Leader worker would detect the conflict
+# and wait for the transaction to commit.
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (3, 'would conflict');");
+
+# Verify the parallel worker waits for the same transaction
+$node_subscriber->wait_for_log(qr/wait for depended xid $xid/, $offset);
+
+# Wakeup the parallel worker
+$node_subscriber->safe_psql('postgres', qq[
+ SELECT injection_points_detach('parallel-worker-before-commit');
+ SELECT injection_points_wakeup('parallel-worker-before-commit');
+]);
+
+# Verify the streamed transaction can be applied
+$node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset);
+
+# Cleanup
+$node_subscriber->safe_psql('postgres', "DROP INDEX regress_tab_value_idx;");
+$node_publisher->safe_psql('postgres', "TRUNCATE TABLE regress_tab;");
+$node_publisher->wait_for_catchup('regress_sub');
+
done_testing();
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index db8bb4e1e43..34c9592e3e5 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1701,6 +1701,7 @@ LogicalRepBeginData
LogicalRepCommitData
LogicalRepCommitPreparedTxnData
LogicalRepCtxStruct
+LogicalRepKeyKind
LogicalRepMsgType
LogicalRepPartMapEntry
LogicalRepPreparedTxnData
@@ -1710,6 +1711,7 @@ LogicalRepRelation
LogicalRepRollbackPreparedTxnData
LogicalRepSequenceInfo
LogicalRepStreamAbortData
+LogicalRepSubscriberIdx
LogicalRepTupleData
LogicalRepTyp
LogicalRepWorker
--
2.43.0
[application/octet-stream] v19-0006-Track-dependencies-for-streamed-transactions.patch (10.1K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/6-v19-0006-Track-dependencies-for-streamed-transactions.patch)
download | inline diff:
From 8a90e8b7c18ce6b65785530e6321065e84858c3c Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Tue, 21 Apr 2026 15:16:59 +0800
Subject: [PATCH v19 06/10] Track dependencies for streamed transactions
This commit allows tracking dependencies of streamed transactions.
Regarding the streaming=on case, dependency tracking is enabled while applying
spooled changes from files.
In the streaming=parallel case, dependency tracking is performed when the leader
sends changes to parallel workers. Apart from non-streamed transactions, the
leader waits for parallel workers till the assigned transactions are finished at
COMMIT/PREPARE/ABORT; thus, the XID of streamed transactions is not cached as
the lastly handled one. Also, streamed transactions are not recorded as
parallelized transactions because upcoming workers do not have to wait for them.
---
.../replication/logical/applyparallelworker.c | 8 ++-
src/backend/replication/logical/worker.c | 64 +++++++++++++++----
src/include/replication/worker_internal.h | 1 -
src/test/subscription/t/050_parallel_apply.pl | 50 +++++++++++++++
4 files changed, 107 insertions(+), 16 deletions(-)
diff --git a/src/backend/replication/logical/applyparallelworker.c b/src/backend/replication/logical/applyparallelworker.c
index 103db18a25b..7ced261445c 100644
--- a/src/backend/replication/logical/applyparallelworker.c
+++ b/src/backend/replication/logical/applyparallelworker.c
@@ -165,7 +165,9 @@
* key) as another ongoing transaction (see handle_dependency_on_change for
* details). If so, the leader sends a list of dependent transaction IDs to the
* parallel worker, indicating that the parallel apply worker must wait for
- * these transactions to commit before proceeding.
+ * these transactions to commit before proceeding. If transactions are streamed
+ * but leader deciedes not to assign parallel apply workers, dependencies are
+ * verified when the transaction is committed.
*
* Tracking dependencies is necessary even when commit order is preserved.
* Consider two transactions: TX-1 (INSERT row 1) and TX-2 (DELETE row 1). If
@@ -1855,6 +1857,10 @@ pa_stream_abort(LogicalRepStreamAbortData *abort_data)
TransactionId xid = abort_data->xid;
TransactionId subxid = abort_data->subxid;
+ /* Streamed transactions won't be registered */
+ Assert(!dshash_find(parallelized_txns, &xid, false) &&
+ !dshash_find(parallelized_txns, &subxid, false));
+
/*
* Update origin state so we can restart streaming from correct position
* in case of crash.
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index 5535841c409..ff1c7142f18 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -1290,8 +1290,6 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
*/
if (winfo == NULL)
{
- Assert(!TransactionIdIsValid(new_depended_xid));
-
foreach_xid(xid, depends_on_xids)
pa_wait_for_depended_transaction(xid);
}
@@ -1498,13 +1496,22 @@ handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
case TRANS_LEADER_SEND_TO_PARALLEL:
Assert(winfo);
+ /*
+ * Pass InvalidTransactionId to skip dependency recording for this
+ * change. Streaming transactions are assumed not to conflict with
+ * other transactions, so subsequent transactions do not need to
+ * wait for them to finish.
+ */
+ handle_dependency_on_change(action, s, InvalidTransactionId, winfo);
+
/*
* XXX The publisher side doesn't always send relation/type update
* messages after the streaming transaction, so also update the
* relation/type in leader apply worker. See function
* cleanup_rel_sync_cache.
*/
- if (pa_send_data(winfo, s->len, s->data))
+ if (!winfo->serialize_changes &&
+ pa_send_data(winfo, s->len, s->data))
return (action != LOGICAL_REP_MSG_RELATION &&
action != LOGICAL_REP_MSG_TYPE);
@@ -2635,6 +2642,13 @@ apply_handle_stream_prepare(StringInfo s)
apply_spooled_messages(MyLogicalRepWorker->stream_fileset,
prepare_data.xid, prepare_data.prepare_lsn);
+ /* Wait until the last transaction finishes */
+ if (TransactionIdIsValid(last_parallelized_remote_xid))
+ {
+ pa_wait_for_depended_transaction(last_parallelized_remote_xid);
+ last_parallelized_remote_xid = InvalidTransactionId;
+ }
+
/* Mark the transaction as prepared. */
apply_handle_prepare_internal(&prepare_data);
@@ -2658,6 +2672,12 @@ apply_handle_stream_prepare(StringInfo s)
case TRANS_LEADER_SEND_TO_PARALLEL:
Assert(winfo);
+ /*
+ * Build a dependency between this transaction and the lastly
+ * committed transaction to preserve the commit order.
+ */
+ build_dependency_with_last_committed_txn(winfo);
+
if (pa_send_data(winfo, s->len, s->data))
{
/* Finish processing the streaming transaction. */
@@ -2724,6 +2744,11 @@ apply_handle_stream_prepare(StringInfo s)
pgstat_report_stat(false);
+ /*
+ * No need to update the last_parallelized_remote_xid here because leader
+ * worker always wait until streamed transactions finish.
+ */
+
/*
* Process any tables that are being synchronized in parallel, as well as
* any newly added tables or sequences.
@@ -2837,17 +2862,8 @@ apply_handle_stream_start(StringInfo s)
set_apply_error_context_xact(stream_xid, InvalidXLogRecPtr);
- /*
- * Try to allocate a worker for the streaming transaction.
- *
- * TODO: Support assigning streaming transactions to parallel apply workers
- * even when non-streaming transactions are running and better dependency
- * handling between streaming and non-streaming transactions.
- */
- if (first_segment &&
- am_leader_apply_worker() &&
- (!TransactionIdIsValid(last_parallelized_remote_xid) ||
- pa_transaction_committed(last_parallelized_remote_xid)))
+ /* Try to allocate a worker for the streaming transaction. */
+ if (first_segment)
pa_allocate_worker(stream_xid, true);
apply_action = get_transaction_apply_action(stream_xid, &winfo);
@@ -3511,6 +3527,13 @@ apply_handle_stream_commit(StringInfo s)
apply_spooled_messages(MyLogicalRepWorker->stream_fileset, xid,
commit_data.commit_lsn);
+ /* Wait until the last transaction finishes */
+ if (TransactionIdIsValid(last_parallelized_remote_xid))
+ {
+ pa_wait_for_depended_transaction(last_parallelized_remote_xid);
+ last_parallelized_remote_xid = InvalidTransactionId;
+ }
+
apply_handle_commit_internal(&commit_data);
/* Unlink the files with serialized changes and subxact info. */
@@ -3522,6 +3545,19 @@ apply_handle_stream_commit(StringInfo s)
case TRANS_LEADER_SEND_TO_PARALLEL:
Assert(winfo);
+ /*
+ * Apart from non-streaming case, no need to mark this transaction
+ * as parallelized. Because the leader waits until the streamed
+ * transaction is committed thus commit ordering is always
+ * preserved.
+ */
+
+ /*
+ * Build a dependency between this transaction and the lastly
+ * committed transaction to preserve the commit order.
+ */
+ build_dependency_with_last_committed_txn(winfo);
+
if (pa_send_data(winfo, s->len, s->data))
{
/* Finish processing the streaming transaction. */
diff --git a/src/include/replication/worker_internal.h b/src/include/replication/worker_internal.h
index 02a165ccc0d..3dde899f465 100644
--- a/src/include/replication/worker_internal.h
+++ b/src/include/replication/worker_internal.h
@@ -370,7 +370,6 @@ extern void pa_switch_to_partial_serialize(ParallelApplyWorkerInfo *winfo,
extern void pa_set_xact_state(ParallelApplyWorkerShared *wshared,
ParallelTransState xact_state);
extern void pa_set_stream_apply_worker(ParallelApplyWorkerInfo *winfo);
-
extern void pa_start_subtrans(TransactionId current_xid,
TransactionId top_xid);
extern void pa_reset_subtrans(void);
diff --git a/src/test/subscription/t/050_parallel_apply.pl b/src/test/subscription/t/050_parallel_apply.pl
index a7bbc8e59c9..04441ca1cd0 100644
--- a/src/test/subscription/t/050_parallel_apply.pl
+++ b/src/test/subscription/t/050_parallel_apply.pl
@@ -260,4 +260,54 @@ $node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset
$node_publisher->safe_psql('postgres', "COMMIT PREPARED 'regress_prepare';");
$node_publisher->wait_for_catchup('regress_sub');
+##################################################
+# Test that streaming transactions respect commit order preservation when
+# non-streaming transactions are being applied in parallel workers.
+##################################################
+
+$node_publisher->append_conf('postgresql.conf',
+ "logical_decoding_work_mem = 64kB");
+$node_publisher->reload;
+# Run a query to make sure that the reload has taken effect.
+$node_publisher->safe_psql('postgres', "SELECT 1");
+
+# Attach the injection_point again
+$node_subscriber->safe_psql('postgres',
+ "SELECT injection_points_attach('parallel-worker-before-commit','wait');"
+);
+
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (generate_series(71, 80), 'test');");
+
+# Wait until the parallel worker enters the injection point.
+$node_subscriber->wait_for_event('logical replication parallel worker',
+ 'parallel-worker-before-commit');
+
+# Run a transaction which would be streamed
+my $h = $node_publisher->background_psql('postgres', on_error_stop => 0);
+
+$offset = -s $node_subscriber->logfile;
+
+$h->query_safe(
+ q{
+BEGIN;
+UPDATE regress_tab SET value = 'streamed-updated' WHERE id BETWEEN 71 AND 80;
+INSERT INTO regress_tab VALUES (generate_series(100, 5100), 'streamed');
+});
+
+# Verify the parallel worker waits for the transaction
+$str = $node_subscriber->wait_for_log(qr/wait for depended xid ([1-9][0-9]+)/, $offset);
+$xid = $str =~ /wait for depended xid ([1-9][0-9]+)/;
+
+# Wakeup the parallel worker
+$node_subscriber->safe_psql('postgres', qq[
+ SELECT injection_points_detach('parallel-worker-before-commit');
+ SELECT injection_points_wakeup('parallel-worker-before-commit');
+]);
+
+# Verify the streamed transaction can be applied
+$node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset);
+
+$h->query_safe("COMMIT;");
+
done_testing();
--
2.43.0
[application/octet-stream] v19-0007-Wait-applying-transaction-if-one-of-user-defined.patch (11.9K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/7-v19-0007-Wait-applying-transaction-if-one-of-user-defined.patch)
download | inline diff:
From 54da67ce47be72d81b2b7fcbd2cf8370b4853927 Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Thu, 4 Jun 2026 10:26:14 +0800
Subject: [PATCH v19 07/10] Wait applying transaction if one of user-defined
triggers is immutable
Since many parallel workers apply transactions, triggers for relations can also
be fired in parallel, which may obtain unexpected results. To make it safe,
parallel apply workers wait for the previously dispatched transaction before
applying changes to the relation that has mutable triggers.
---
src/backend/replication/logical/relation.c | 123 ++++++++++++++++++---
src/backend/replication/logical/worker.c | 66 +++++++++++
src/include/replication/logicalrelation.h | 20 ++++
3 files changed, 195 insertions(+), 14 deletions(-)
diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index e1ce183dfd3..eeb85f8cc5d 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -21,7 +21,9 @@
#include "access/genam.h"
#include "access/table.h"
#include "catalog/namespace.h"
+#include "catalog/pg_proc.h"
#include "catalog/pg_subscription_rel.h"
+#include "commands/trigger.h"
#include "executor/executor.h"
#include "nodes/makefuncs.h"
#include "replication/logicalrelation.h"
@@ -160,6 +162,10 @@ logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
*
* Called when new relation mapping is sent by the publisher to update
* our expected view of incoming data from said publisher.
+ *
+ * Note that we do not check the user-defined constraints here. PostgreSQL has
+ * already assumed that CHECK constraints' conditions are immutable and here
+ * follows the rule.
*/
void
logicalrep_relmap_update(LogicalRepRelation *remoterel)
@@ -209,6 +215,8 @@ logicalrep_relmap_update(LogicalRepRelation *remoterel)
(remoterel->relkind == 0) ? RELKIND_RELATION : remoterel->relkind;
entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
+
+ entry->parallel_safe = LOGICALREP_PARALLEL_UNKNOWN;
MemoryContextSwitchTo(oldctx);
}
@@ -354,27 +362,79 @@ logicalrep_rel_mark_updatable(LogicalRepRelMapEntry *entry)
}
/*
- * Open the local relation associated with the remote one.
+ * Check all local triggers for the relation to see the parallelizability.
*
- * Rebuilds the Relcache mapping if it was invalidated by local DDL.
+ * We regard relations as applicable in parallel if all triggers are immutable.
+ * Result is directly set to LogicalRepRelMapEntry::parallel_safe.
*/
-LogicalRepRelMapEntry *
-logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
+static void
+check_defined_triggers(LogicalRepRelMapEntry *entry)
+{
+ TriggerDesc *trigdesc = entry->localrel->trigdesc;
+
+ /* Quick exit if triffer is not defined */
+ if (trigdesc == NULL)
+ {
+ entry->parallel_safe = LOGICALREP_PARALLEL_SAFE;
+ return;
+ }
+
+ /* Seek triggers one by one to see the volatility */
+ for (int i = 0; i < trigdesc->numtriggers; i++)
+ {
+ Trigger *trigger = &trigdesc->triggers[i];
+
+ Assert(OidIsValid(trigger->tgfoid));
+
+ /* Skip if the trigger is not enabled for logical replication */
+ if (trigger->tgenabled == TRIGGER_DISABLED ||
+ trigger->tgenabled == TRIGGER_FIRES_ON_ORIGIN)
+ continue;
+
+ /* Check the volatility of the trigger. Exit if it is not immutable */
+ if (func_volatile(trigger->tgfoid) != PROVOLATILE_IMMUTABLE)
+ {
+ entry->parallel_safe = LOGICALREP_PARALLEL_RESTRICTED;
+ return;
+ }
+ }
+
+ /* All triggers are immutable, set as parallel safe */
+ entry->parallel_safe = LOGICALREP_PARALLEL_SAFE;
+}
+
+/*
+ * Actual workhorse for logicalrep_rel_open().
+ *
+ * Caller must specify *either* entry or key. If the entry is specified, its
+ * attributes are filled and returned. The logical relation is kept opening.
+ * If the key is given, the corresponding entry is first searched in the hash
+ * table and processed as in the above case. At the end, logical replication is
+ * closed.
+ */
+void
+logicalrep_rel_load(LogicalRepRelMapEntry *entry, LogicalRepRelId remoteid,
+ LOCKMODE lockmode)
{
- LogicalRepRelMapEntry *entry;
- bool found;
LogicalRepRelation *remoterel;
- if (LogicalRepRelMap == NULL)
- logicalrep_relmap_init();
+ Assert((entry && !remoteid) || (!entry && remoteid));
- /* Search for existing entry. */
- entry = hash_search(LogicalRepRelMap, &remoteid,
- HASH_FIND, &found);
+ if (!entry)
+ {
+ bool found;
- if (!found)
- elog(ERROR, "no relation map entry for remote relation ID %u",
- remoteid);
+ if (LogicalRepRelMap == NULL)
+ logicalrep_relmap_init();
+
+ /* Search for existing entry. */
+ entry = hash_search(LogicalRepRelMap, &remoteid,
+ HASH_FIND, &found);
+
+ if (!found)
+ elog(ERROR, "no relation map entry for remote relation ID %u",
+ remoteid);
+ }
remoterel = &entry->remoterel;
@@ -500,6 +560,13 @@ logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
entry->localindexoid = FindLogicalRepLocalIndex(entry->localrel, remoterel,
entry->attrmap);
+ /*
+ * Leader must also collect all local unique indexes for dependency
+ * tracking.
+ */
+ if (am_leader_apply_worker())
+ check_defined_triggers(entry);
+
entry->localrelvalid = true;
}
@@ -508,6 +575,34 @@ logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
entry->localreloid,
&entry->statelsn);
+ if (remoteid)
+ logicalrep_rel_close(entry, lockmode);
+}
+
+/*
+ * Open the local relation associated with the remote one.
+ *
+ * Rebuilds the Relcache mapping if it was invalidated by local DDL.
+ */
+LogicalRepRelMapEntry *
+logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
+{
+ LogicalRepRelMapEntry *entry;
+ bool found;
+
+ if (LogicalRepRelMap == NULL)
+ logicalrep_relmap_init();
+
+ /* Search for existing entry. */
+ entry = hash_search(LogicalRepRelMap, &remoteid,
+ HASH_FIND, &found);
+
+ if (!found)
+ elog(ERROR, "no relation map entry for remote relation ID %u",
+ remoteid);
+
+ logicalrep_rel_load(entry, 0, lockmode);
+
return entry;
}
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index ff1c7142f18..de665b8d4b3 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -1138,6 +1138,58 @@ check_and_record_rel_dependency(LogicalRepRelId relid,
relentry->last_depended_xid = new_depended_xid;
}
+/*
+ * Check the parallelizability of applying changes for the relation.
+ * Append the lastly dispatched transaction in in 'depends_on_xids' if the
+ * relation is parallel unsafe.
+ */
+static void
+check_dependency_for_parallel_safety(LogicalRepRelId relid,
+ TransactionId new_depended_xid,
+ List **depends_on_xids)
+{
+ LogicalRepRelMapEntry *relentry;
+
+ /* Quick exit if no transactions have been dispatched */
+ if (!TransactionIdIsValid(last_parallelized_remote_xid))
+ return;
+
+ relentry = logicalrep_get_relentry(relid);
+
+ /*
+ * Gather information for local triggres if not yet. We require to be in a
+ * transaction state because system catalogs are read.
+ */
+ if (relentry->parallel_safe == LOGICALREP_PARALLEL_UNKNOWN)
+ {
+ bool needs_start = !IsTransactionOrTransactionBlock();
+
+ if (needs_start)
+ StartTransactionCommand();
+
+ logicalrep_rel_load(NULL, relid, AccessShareLock);
+
+ /*
+ * Close the transaction if we start here. We must not abort because
+ * it would release all session-level locks, such as the stream lock,
+ * and break the deadlock detection mechanism between LA and PA. The
+ * outcome is the same regardless of the end status, since the
+ * transaction did not modify any tuples.
+ */
+ if (needs_start)
+ CommitTransactionCommand();
+
+ Assert(relentry->parallel_safe != LOGICALREP_PARALLEL_UNKNOWN);
+ }
+
+ /* Do nothing for parallel safe relations */
+ if (relentry->parallel_safe == LOGICALREP_PARALLEL_SAFE)
+ return;
+
+ check_and_append_xid_dependency(&last_parallelized_remote_xid,
+ depends_on_xids);
+}
+
/*
* Check dependencies related to the current change by determining if the
* modification impacts the same row or table as another ongoing transaction. If
@@ -1204,6 +1256,8 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
relid = logicalrep_read_insert(&change, &newtup);
check_and_record_ri_dependency(relid, &newtup, new_depended_xid,
&depends_on_xids);
+ check_dependency_for_parallel_safety(relid, new_depended_xid,
+ &depends_on_xids);
break;
case LOGICAL_REP_MSG_UPDATE:
@@ -1215,6 +1269,9 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
check_and_record_ri_dependency(relid, &oldtup, new_depended_xid,
&depends_on_xids);
+ check_dependency_for_parallel_safety(relid, new_depended_xid,
+ &depends_on_xids);
+
/*
* Copy unchanged column values from the old tuple to the new
* tuple for replica identity dependency checking. See
@@ -1227,12 +1284,16 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
check_and_record_ri_dependency(relid, &newtup, new_depended_xid,
&depends_on_xids);
+ check_dependency_for_parallel_safety(relid, new_depended_xid,
+ &depends_on_xids);
break;
case LOGICAL_REP_MSG_DELETE:
relid = logicalrep_read_delete(&change, &oldtup);
check_and_record_ri_dependency(relid, &oldtup, new_depended_xid,
&depends_on_xids);
+ check_dependency_for_parallel_safety(relid, new_depended_xid,
+ &depends_on_xids);
break;
case LOGICAL_REP_MSG_TRUNCATE:
@@ -1245,9 +1306,14 @@ handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
* modified the same table.
*/
foreach_int(truncated_relid, remote_relids)
+ {
check_and_record_rel_dependency(truncated_relid,
new_depended_xid,
&depends_on_xids);
+ check_dependency_for_parallel_safety(truncated_relid,
+ new_depended_xid,
+ &depends_on_xids);
+ }
break;
diff --git a/src/include/replication/logicalrelation.h b/src/include/replication/logicalrelation.h
index cd852337165..b1079d3f2fa 100644
--- a/src/include/replication/logicalrelation.h
+++ b/src/include/replication/logicalrelation.h
@@ -45,6 +45,20 @@ typedef struct LogicalRepRelMapEntry
* applying (see check_dependency_on_rel).
*/
TransactionId last_depended_xid;
+
+ /*
+ * Whether the relation can be applied in parallel or not. It is
+ * distinglish whether defined triggers are the immutable or not.
+ *
+ * Theoretically, we can determine the parallelizability for each type of
+ * replication messages, INSERT/UPDATE/DELETE/TRUNCATE. But it is not done
+ * yet to reduce the number of attributes.
+ *
+ * Note that we do not check the user-defined constraints here. PostgreSQL
+ * has already assumed that CHECK constraints' conditions are immutable and
+ * here follows the rule.
+ */
+ char parallel_safe;
} LogicalRepRelMapEntry;
extern void logicalrep_relmap_update(LogicalRepRelation *remoterel);
@@ -52,6 +66,8 @@ extern void logicalrep_partmap_reset_relmap(LogicalRepRelation *remoterel);
extern LogicalRepRelMapEntry *logicalrep_rel_open(LogicalRepRelId remoteid,
LOCKMODE lockmode);
+extern void logicalrep_rel_load(LogicalRepRelMapEntry *entry,
+ LogicalRepRelId remoteid, LOCKMODE lockmode);
extern LogicalRepRelMapEntry *logicalrep_partition_open(LogicalRepRelMapEntry *root,
Relation partrel, AttrMap *map);
extern void logicalrep_rel_close(LogicalRepRelMapEntry *rel,
@@ -62,4 +78,8 @@ extern int logicalrep_get_num_rels(void);
extern void logicalrep_write_all_rels(StringInfo out);
extern LogicalRepRelMapEntry *logicalrep_get_relentry(LogicalRepRelId remoteid);
+#define LOGICALREP_PARALLEL_SAFE 's'
+#define LOGICALREP_PARALLEL_RESTRICTED 'r'
+#define LOGICALREP_PARALLEL_UNKNOWN 'u'
+
#endif /* LOGICALRELATION_H */
--
2.43.0
[application/octet-stream] v19-0005-support-2PC.patch (13.4K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/8-v19-0005-support-2PC.patch)
download | inline diff:
From 1e1ec4d6e43ef8ce1a4bf9aade573b681a590fce Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Thu, 4 Jun 2026 13:15:14 +0800
Subject: [PATCH v19 05/10] support 2PC
This patch allows the PREPARE transaction to be applied in parallel. Parallel
apply workers are assigned to a transaction when BEGIN_PREPARE is received. This
part and the dependency-waiting mechanism are the same as a normal transaction.
A parallel worker can be freed after it handles a PREPARE message. The prepared
transaction can be deleted from parallelized_txns at that time; the upcoming
transactions will wait until then.
The leader apply worker resolves COMMIT PREPARED/ROLLBACK PREPARED. Since it can
be serialized automatically, it does not add the transaction to parallelized_txns.
---
src/backend/replication/logical/worker.c | 218 +++++++++++++++---
src/test/subscription/t/050_parallel_apply.pl | 64 ++++-
2 files changed, 253 insertions(+), 29 deletions(-)
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index faf7a50bf25..5535841c409 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -806,6 +806,14 @@ delete_replica_identity_entries_for_txns(List *committed_xids)
if (!committed_xids)
return;
+ /*
+ * Skip if the replica_identity_table is not initialized yet. This can
+ * happen if the empty transaction was replicated and a parallel apply
+ * worker was launched. See comments in apply_handle_prepare().
+ */
+ if (!replica_identity_table)
+ return;
+
replica_identity_start_iterate(replica_identity_table, &i);
while ((rientry = replica_identity_iterate(replica_identity_table, &i)) != NULL)
{
@@ -2184,6 +2192,8 @@ static void
apply_handle_begin_prepare(StringInfo s)
{
LogicalRepPreparedTxnData begin_data;
+ ParallelApplyWorkerInfo *winfo;
+ TransApplyAction apply_action;
/* Tablesync should never receive prepare. */
if (am_tablesync_worker())
@@ -2195,12 +2205,54 @@ apply_handle_begin_prepare(StringInfo s)
Assert(!TransactionIdIsValid(stream_xid));
logicalrep_read_begin_prepare(s, &begin_data);
- set_apply_error_context_xact(begin_data.xid, begin_data.prepare_lsn);
+
+ remote_xid = begin_data.xid;
+
+ set_apply_error_context_xact(remote_xid, begin_data.prepare_lsn);
remote_final_lsn = begin_data.prepare_lsn;
maybe_start_skipping_changes(begin_data.prepare_lsn);
+ pa_allocate_worker(remote_xid, false);
+
+ apply_action = get_transaction_apply_action(remote_xid, &winfo);
+
+ elog(DEBUG1, "new remote_xid %u", remote_xid);
+ switch (apply_action)
+ {
+ case TRANS_LEADER_APPLY:
+ break;
+
+ case TRANS_LEADER_SEND_TO_PARALLEL:
+ Assert(winfo);
+
+ if (pa_send_data(winfo, s->len, s->data))
+ {
+ pa_set_stream_apply_worker(winfo);
+ break;
+ }
+
+ /*
+ * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
+ * buffer becomes full.
+ */
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("could not send data to the logical replication parallel apply worker"));
+ break;
+
+ case TRANS_PARALLEL_APPLY:
+ /* Hold the lock until the end of the transaction. */
+ pa_lock_transaction(MyParallelShared->xid, AccessExclusiveLock);
+ pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_STARTED);
+ break;
+
+ default:
+ elog(ERROR, "unexpected apply action: %d", (int) apply_action);
+ break;
+ }
+
in_remote_transaction = true;
pgstat_report_activity(STATE_RUNNING, NULL);
@@ -2250,6 +2302,8 @@ static void
apply_handle_prepare(StringInfo s)
{
LogicalRepPreparedTxnData prepare_data;
+ ParallelApplyWorkerInfo *winfo;
+ TransApplyAction apply_action;
logicalrep_read_prepare(s, &prepare_data);
@@ -2260,36 +2314,131 @@ apply_handle_prepare(StringInfo s)
LSN_FORMAT_ARGS(prepare_data.prepare_lsn),
LSN_FORMAT_ARGS(remote_final_lsn))));
- /*
- * Unlike commit, here, we always prepare the transaction even though no
- * change has happened in this transaction or all changes are skipped. It
- * is done this way because at commit prepared time, we won't know whether
- * we have skipped preparing a transaction because of those reasons.
- *
- * XXX, We can optimize such that at commit prepared time, we first check
- * whether we have prepared the transaction or not but that doesn't seem
- * worthwhile because such cases shouldn't be common.
- */
- begin_replication_step();
+ apply_action = get_transaction_apply_action(remote_xid, &winfo);
- apply_handle_prepare_internal(&prepare_data);
+ switch (apply_action)
+ {
+ case TRANS_LEADER_APPLY:
- end_replication_step();
- CommitTransactionCommand();
- pgstat_report_stat(false);
+ /*
+ * Unlike commit, here, we always prepare the transaction even
+ * though no change has happened in this transaction or all
+ * changes are skipped. It is done this way because at commit
+ * prepared time, we won't know whether we have skipped preparing
+ * a transaction because of those reasons.
+ *
+ * XXX, We can optimize such that at commit prepared time, we
+ * first check whether we have prepared the transaction or not but
+ * that doesn't seem worthwhile because such cases shouldn't be
+ * common.
+ */
+ begin_replication_step();
- /*
- * It is okay not to set the local_end LSN for the prepare because we
- * always flush the prepare record. So, we can send the acknowledgment of
- * the remote_end LSN as soon as prepare is finished.
- *
- * XXX For the sake of consistency with commit, we could have set it with
- * the LSN of prepare but as of now we don't track that value similar to
- * XactLastCommitEnd, and adding it for this purpose doesn't seems worth
- * it.
- */
- store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr,
- InvalidTransactionId);
+ /* Wait until the last transaction finishes */
+ if (TransactionIdIsValid(last_parallelized_remote_xid))
+ {
+ pa_wait_for_depended_transaction(last_parallelized_remote_xid);
+ last_parallelized_remote_xid = InvalidTransactionId;
+ }
+
+ apply_handle_prepare_internal(&prepare_data);
+
+ end_replication_step();
+ CommitTransactionCommand();
+ pgstat_report_stat(false);
+
+ /*
+ * It is okay not to set the local_end LSN for the prepare because
+ * we always flush the prepare record. So, we can send the
+ * acknowledgment of the remote_end LSN as soon as prepare is
+ * finished.
+ *
+ * XXX For the sake of consistency with commit, we could have set
+ * it with the LSN of prepare but as of now we don't track that
+ * value similar to XactLastCommitEnd, and adding it for this
+ * purpose doesn't seems worth it.
+ */
+ store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr,
+ InvalidTransactionId);
+
+ break;
+
+ case TRANS_LEADER_SEND_TO_PARALLEL:
+ Assert(winfo);
+
+ /*
+ * Mark this transaction as parallelized. This ensures that
+ * upcoming transactions wait until this transaction is committed.
+ */
+ pa_add_parallelized_transaction(remote_xid);
+
+ /*
+ * Build a dependency between this transaction and the lastly
+ * committed transaction to preserve the commit order.
+ */
+ build_dependency_with_last_committed_txn(winfo);
+
+ if (pa_send_data(winfo, s->len, s->data))
+ {
+ /* Cache the remote_xid */
+ last_parallelized_remote_xid = remote_xid;
+
+ /* Finish processing the transaction. */
+ pa_xact_finish(winfo, prepare_data.end_lsn);
+ break;
+ }
+
+ /*
+ * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
+ * buffer becomes full.
+ */
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("could not send data to the logical replication parallel apply worker"));
+ break;
+
+ case TRANS_PARALLEL_APPLY:
+
+ /*
+ * If the parallel apply worker is applying spooled messages then
+ * close the file before committing.
+ */
+ if (stream_fd)
+ stream_close_file();
+
+ begin_replication_step();
+
+ INJECTION_POINT("parallel-worker-before-prepare", NULL);
+
+ /* Mark the transaction as prepared. */
+ apply_handle_prepare_internal(&prepare_data);
+
+ end_replication_step();
+
+ CommitTransactionCommand();
+ pgstat_report_stat(false);
+
+ store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr,
+ InvalidTransactionId);
+
+ /*
+ * It is okay not to set the local_end LSN for the prepare because
+ * we always flush the prepare record. See apply_handle_prepare.
+ */
+ MyParallelShared->last_commit_end = InvalidXLogRecPtr;
+ pa_commit_transaction();
+
+ pa_unlock_transaction(MyParallelShared->xid, AccessExclusiveLock);
+
+ pa_reset_subtrans();
+ break;
+
+ default:
+ elog(ERROR, "unexpected apply action: %d", (int) apply_action);
+ break;
+ }
+
+ remote_xid = InvalidTransactionId;
in_remote_transaction = false;
@@ -2337,6 +2486,12 @@ apply_handle_commit_prepared(StringInfo s)
/* There is no transaction when COMMIT PREPARED is called */
begin_replication_step();
+ if (TransactionIdIsValid(last_parallelized_remote_xid))
+ {
+ pa_wait_for_depended_transaction(last_parallelized_remote_xid);
+ last_parallelized_remote_xid = InvalidTransactionId;
+ }
+
/*
* Update origin state so we can restart streaming from correct position
* in case of crash.
@@ -2405,6 +2560,13 @@ apply_handle_rollback_prepared(StringInfo s)
/* There is no transaction when ABORT/ROLLBACK PREPARED is called */
begin_replication_step();
+
+ if (TransactionIdIsValid(last_parallelized_remote_xid))
+ {
+ pa_wait_for_depended_transaction(last_parallelized_remote_xid);
+ last_parallelized_remote_xid = InvalidTransactionId;
+ }
+
FinishPreparedTransaction(gid, false);
end_replication_step();
CommitTransactionCommand();
diff --git a/src/test/subscription/t/050_parallel_apply.pl b/src/test/subscription/t/050_parallel_apply.pl
index 14121b23f23..a7bbc8e59c9 100644
--- a/src/test/subscription/t/050_parallel_apply.pl
+++ b/src/test/subscription/t/050_parallel_apply.pl
@@ -19,6 +19,8 @@ if ($ENV{enable_injection_points} ne 'yes')
# Initialize publisher node
my $node_publisher = PostgreSQL::Test::Cluster->new('publisher');
$node_publisher->init(allows_streaming => 'logical');
+$node_publisher->append_conf('postgresql.conf',
+ "max_prepared_transactions = 10");
$node_publisher->start;
# Create tables and insert initial data
@@ -44,7 +46,8 @@ my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
$node_subscriber->init;
$node_subscriber->append_conf('postgresql.conf', "log_min_messages = debug1");
$node_subscriber->append_conf('postgresql.conf',
- "max_logical_replication_workers = 10");
+ "max_logical_replication_workers = 10
+ max_prepared_transactions = 10");
$node_subscriber->start;
# Check if the extension injection_points is available, as it may be
@@ -198,4 +201,63 @@ $result =
$node_subscriber->safe_psql('postgres', "SELECT count(1) FROM tab_toast");
is ($result, 0, 'changes are replicated to subscriber');
+##################################################
+# Test that the prepared transaction can be applied in a parallel apply worker,
+# and that the commit order preservation work correctly.
+##################################################
+
+$node_subscriber->safe_psql('postgres',
+ "ALTER SUBSCRIPTION regress_sub DISABLE;");
+$node_subscriber->poll_query_until('postgres',
+ "SELECT count(*) = 0 FROM pg_stat_activity WHERE backend_type = 'logical replication apply worker'"
+);
+$node_subscriber->safe_psql(
+ 'postgres', "
+ ALTER SUBSCRIPTION regress_sub SET (two_phase = on);
+ ALTER SUBSCRIPTION regress_sub ENABLE;");
+
+$result = $node_subscriber->safe_psql('postgres',
+ "SELECT count(1) FROM pg_stat_activity WHERE backend_type = 'logical replication parallel worker'");
+is($result, '0', "no parallel apply workers exist after restart");
+
+# Attach an injection_point. Parallel workers would wait before the prepare
+$node_subscriber->safe_psql('postgres',
+ "SELECT injection_points_attach('parallel-worker-before-prepare','wait');"
+);
+
+# PREPARE a transaction on publisher. It would be handled by a parallel apply
+# worker.
+$node_publisher->safe_psql('postgres', qq[
+ BEGIN;
+ INSERT INTO regress_tab VALUES (generate_series(51, 60), 'prepare');
+ PREPARE TRANSACTION 'regress_prepare';
+]);
+
+# Wait until the parallel worker enters the injection point.
+$node_subscriber->wait_for_event('logical replication parallel worker',
+ 'parallel-worker-before-prepare');
+
+$offset = -s $node_subscriber->logfile;
+
+# Insert tuples on publisher again. This transaction waits for the prepared
+# transaction
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (generate_series(61, 70), 'test');");
+
+# Verify the parallel worker waits for the transaction
+$str = $node_subscriber->wait_for_log(qr/wait for depended xid ([1-9][0-9]+)/, $offset);
+$xid = $str =~ /wait for depended xid ([1-9][0-9]+)/;
+
+# Wakeup the parallel worker
+$node_subscriber->safe_psql('postgres', qq[
+ SELECT injection_points_detach('parallel-worker-before-prepare');
+ SELECT injection_points_wakeup('parallel-worker-before-prepare');
+]);
+
+$node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset);
+
+# COMMIT the prepared transaction. It is always handled by the leader
+$node_publisher->safe_psql('postgres', "COMMIT PREPARED 'regress_prepare';");
+$node_publisher->wait_for_catchup('regress_sub');
+
done_testing();
--
2.43.0
[application/octet-stream] v19-0004-Parallel-apply-non-streaming-transactions.patch (61.6K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/9-v19-0004-Parallel-apply-non-streaming-transactions.patch)
download | inline diff:
From 960841845f58c6b1e3dc93b6337d2e7ca285918f Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Thu, 4 Jun 2026 10:20:44 +0800
Subject: [PATCH v19 04/10] Parallel apply non-streaming transactions
--
Basic design
--
The leader worker assigns each non-streaming transaction to a parallel apply
worker. Before dispatching changes to a parallel worker, the leader verifies if
the current modification affects the same row (identitied by replica identity
key) as another ongoing transaction. If so, the leader sends a list of dependent
transaction IDs to the parallel worker, indicating that the parallel apply
worker must wait for these transactions to commit before proceeding.
The leader preserves publisher commit order for all transactions by instructing
the parallel worker to wait for the last transaction to commit before committing
the current transaction. (Note that the leader itself does not wait the
parallelized transaction to be committed unless partial serialization mode is
active, where the parallel apply worker can no longer be reused.) See the
"commit order" and "worker interaction" sections below for details.
Tracking dependencies is necessary even when commit order is preserved.
Consider two transactions: TX-1 (INSERT row 1) and TX-2 (DELETE row 1). If
both are allowed to apply in parallel, TX-2's DELETE could be applied before
TX-1's INSERT, resulting in a delete_missing conflict.
Each parallel apply worker records the local end LSN of the transaction it
applies in shared memory. Subsequently, the leader gathers these local end LSNs
and logs them in the local 'lsn_mapping' for verifying whether they have been
flushed to disk (following the logic in get_flush_position()).
If no parallel apply worker is available, the leader will apply the transaction
independently.
For further details, please refer to the following:
--
dedendency tracking
--
The leader maintains a local hash table, using the remote change's replica
identity column values and relid as keys, with remote transaction IDs as values.
Before sending changes to the parallel apply worker, the leader computes a hash
using RI key values and the relid of the current change to search the hash
table. If an existing entry is found, the leader first updates the hash entry
with the receiving remote xid then tells the parallel worker to wait for it.
If the remote relation lacks a replica identity (RI), it indicates that only
INSERT can be replicated for this table. In such cases, the leader skips
dependency checks, allowing the parallel apply worker to proceed with applying
changes without delay. This is because the only potential conflict could happen
is related to the local unique key or foreign key, which that is yet to be
implemented.
In cases of TRUNCATE or remote schema changes affecting the entire table, the
leader retrieves all remote xids touching the same table (via sequential scans
of the hash table) and tells the parallel worker to wait for those transactions
to commit.
Hash entries are cleaned up once the transaction corresponding to the remote xid
in the entry has been committed. Clean-up typically occurs when collecting the
flush position of each transaction, but is forced if the hash table exceeds a
set threshold.
--
dedendency waiting
--
If a transaction is relied upon by others, the leader adds its xid to a shared
hash table. The shared hash table entry is cleared by the parallel apply worker
upon completing the transaction. Workers needing to wait for a transaction check
the shared hash table entry; if present, they lock the transaction ID (using
pa_lock_transaction). If absent, it indicates the transaction has been
committed, negating the need to wait.
--
commit order
--
We preserve publisher commit order for all transactions for two reasons:
1) User-visible consistency
Out-of-order commits can expose states on the subscriber that were never visible
on the publisher.
For example, suppose a user updates table A and then updates table B on the
publisher. If the subscriber commits those transactions out of order, a query
that sees the latest row in B might still see stale data in A. Although eventual
consistency would still be reached, that behavior may be unacceptable for some
users. In the future, we could provide a GUC to allow out-of-order commits for
users who prefer higher parallelism.
2) Replication progress tracking
We currently track replication progress using transaction commit LSNs. With
out-of-order commits, this becomes ambiguous after failures.
For example, if TX-2 is applied before TX-1 and replication stops due to an
error, we cannot reliably determine whether TX-1 was applied before restart.
As a result, transactions that were already committed on the subscriber may
be replayed.
--
worker interaction
--
After sending the COMMIT message for a transaction, the leader apply worker
does not wait for the parallel apply worker to finish applying that
transaction. Instead, it sends a PA_MSG_XACT_DEPENDENCY message to
the parallel apply worker, instructing it to wait for the last transaction to
commit. This allows the leader to remain busy receiving and dispatching
changes to more parallel apply workers, enabling greater parallelism in
transaction application.
Author: Zhijie Hou <[email protected]>
Author: Hayato Kuroda <[email protected]>
---
.../replication/logical/applyparallelworker.c | 348 +++++++++++++++--
src/backend/replication/logical/proto.c | 38 ++
src/backend/replication/logical/relation.c | 31 ++
src/backend/replication/logical/worker.c | 358 ++++++++++++++++--
src/include/replication/logicalproto.h | 2 +
src/include/replication/logicalrelation.h | 2 +
src/include/replication/worker_internal.h | 10 +-
src/test/subscription/meson.build | 2 +-
src/test/subscription/t/001_rep_changes.pl | 2 +
src/test/subscription/t/010_truncate.pl | 2 +-
src/test/subscription/t/015_stream.pl | 8 +-
src/test/subscription/t/026_stats.pl | 1 +
src/test/subscription/t/027_nosuperuser.pl | 1 +
src/test/subscription/t/050_parallel_apply.pl | 201 ++++++++++
src/tools/pgindent/typedefs.list | 2 +
15 files changed, 929 insertions(+), 79 deletions(-)
create mode 100644 src/test/subscription/t/050_parallel_apply.pl
diff --git a/src/backend/replication/logical/applyparallelworker.c b/src/backend/replication/logical/applyparallelworker.c
index 8c81b61b052..103db18a25b 100644
--- a/src/backend/replication/logical/applyparallelworker.c
+++ b/src/backend/replication/logical/applyparallelworker.c
@@ -14,6 +14,9 @@
* ParallelApplyWorkerInfo which is required so the leader worker and parallel
* apply workers can communicate with each other.
*
+ * Streaming transactions
+ * ======================
+ *
* The parallel apply workers are assigned (if available) as soon as xact's
* first stream is received for subscriptions that have set their 'streaming'
* option as parallel. The leader apply worker will send changes to this new
@@ -36,12 +39,9 @@
* its information is added to the ParallelApplyWorkerPool. Once the worker
* finishes applying the transaction, it is marked as available for re-use.
* Now, before starting a new worker to apply the streaming transaction, we
- * check the list for any available worker. Note that we retain a maximum of
- * half the max_parallel_apply_workers_per_subscription workers in the pool and
- * after that, we simply exit the worker after applying the transaction.
- *
- * XXX This worker pool threshold is arbitrary and we can provide a GUC
- * variable for this in the future if required.
+ * check the list for any available worker. We do not stop workers in the pool
+ * unless partial of the changes of the transaction are serialized due to a send
+ * timeout.
*
* The leader apply worker will create a separate dynamic shared memory segment
* when each parallel apply worker starts. The reason for this design is that
@@ -152,6 +152,75 @@
* session-level locks because both locks could be acquired outside the
* transaction, and the stream lock in the leader needs to persist across
* transaction boundaries i.e. until the end of the streaming transaction.
+ *
+ * Non-streaming transactions
+ * ======================
+ * The handling is similar to streaming transactions, but including few
+ * differences:
+ *
+ * Transaction dependency
+ * ----------------------
+ * Before dispatching changes to a parallel worker, the leader verifies if the
+ * current modification affects the same row (identitied by replica identity
+ * key) as another ongoing transaction (see handle_dependency_on_change for
+ * details). If so, the leader sends a list of dependent transaction IDs to the
+ * parallel worker, indicating that the parallel apply worker must wait for
+ * these transactions to commit before proceeding.
+ *
+ * Tracking dependencies is necessary even when commit order is preserved.
+ * Consider two transactions: TX-1 (INSERT row 1) and TX-2 (DELETE row 1). If
+ * both are allowed to apply in parallel, TX-2's DELETE could be applied before
+ * TX-1's INSERT, resulting in a delete_missing conflict.
+ *
+ * Commit order
+ * ------------
+ * We preserve publisher commit order for all transactions for two reasons:
+ *
+ * 1) User-visible consistency
+ *
+ * Out-of-order commits can expose states on the subscriber that were never
+ * visible on the publisher.
+ *
+ * For example, suppose a user updates table A and then updates table B on the
+ * publisher. If the subscriber commits those transactions out of order, a
+ * query that sees the latest row in B might still see stale data in A.
+ * Although eventual consistency would still be reached, that behavior may be
+ * unacceptable for some users. In the future, we could provide a subscription
+ * option to allow out-of-order commits for users who prefer higher parallelism.
+ *
+ * 2) Replication progress tracking
+ *
+ * We currently track replication progress using the last transaction's commit
+ * LSNs. With out-of-order commits, this becomes ambiguous after failures.
+ *
+ * For example, if TX-2 is applied before TX-1 and replication stops due to an
+ * error, we cannot reliably determine whether TX-1 was applied before restart.
+ * As a result, transactions that were already committed on the subscriber may
+ * be replayed.
+ *
+ * Worker interaction
+ * ------------
+ * After sending the COMMIT message for a transaction, the leader apply worker
+ * does not wait for the parallel apply worker to finish applying that
+ * transaction. Instead, it sends a PA_MSG_XACT_DEPENDENCY message to
+ * the parallel apply worker, instructing it to wait for the last transaction to
+ * commit. This allows the leader to remain busy receiving and dispatching
+ * changes to more parallel apply workers, enabling greater parallelism in
+ * transaction application.
+ *
+ * Locking considerations
+ * ----------------------
+ * When handling a PA_MSG_RELMAP message, the worker attempts
+ * to acquire the transaction lock of the depended transaction and releases it
+ * immediately after acquisition (see pa_wait_for_depended_transaction). This
+ * allows deadlock detection when one worker (either leader or parallel apply
+ * worker) is waiting for a dependency on a transaction being applied by another
+ * worker, while that other worker is also blocked by a lock held by the first
+ * worker.
+ *
+ * The lock graph for the above example will look as follows: Worker_1 (waiting
+ * for depended transaction to finish) -> Worker_2 (waiting to acquire a
+ * relation lock) -> Worker_1
*-------------------------------------------------------------------------
*/
@@ -307,6 +376,7 @@ static ParallelTransState pa_get_xact_state(ParallelApplyWorkerShared *wshared);
static PartialFileSetState pa_get_fileset_state(void);
static void pa_attach_parallelized_txn_hash(dsa_handle *pa_dsa_handle,
dshash_table_handle *pa_dshash_handle);
+static void write_internal_relation(StringInfo s, LogicalRepRelation *rel);
/*
* Returns true if it is OK to start a parallel apply worker, false otherwise.
@@ -424,6 +494,7 @@ pa_setup_dsm(ParallelApplyWorkerInfo *winfo)
shared = shm_toc_allocate(toc, sizeof(ParallelApplyWorkerShared));
SpinLockInit(&shared->mutex);
+ shared->xid = InvalidTransactionId;
shared->xact_state = PARALLEL_TRANS_UNKNOWN;
pg_atomic_init_u32(&(shared->pending_stream_count), 0);
shared->last_commit_end = InvalidXLogRecPtr;
@@ -467,6 +538,8 @@ pa_launch_parallel_worker(void)
MemoryContext oldcontext;
bool launched;
ParallelApplyWorkerInfo *winfo;
+ dsa_handle pa_dsa_handle;
+ dshash_table_handle pa_dshash_handle;
ListCell *lc;
/* Try to get an available parallel apply worker from the worker pool. */
@@ -476,8 +549,36 @@ pa_launch_parallel_worker(void)
if (!winfo->in_use)
return winfo;
+
+ /*
+ * The leader does not explicitly free workers that handle non-streaming
+ * transactions, so we check whether the transaction has committed, and
+ * if so, reuse the worker.
+ */
+ if (!winfo->stream_txn &&
+ pa_get_xact_state(winfo->shared) == PARALLEL_TRANS_FINISHED)
+ {
+ /*
+ * Save the local commit LSN of the last transaction applied by
+ * this worker before reusing it for another transaction. This WAL
+ * position is crucial for determining the flush position in
+ * responses to the publisher (see get_flush_position()).
+ */
+ (void) pa_get_last_commit_end(winfo->shared->xid, false, NULL);
+ return winfo;
+ }
}
+ pa_attach_parallelized_txn_hash(&pa_dsa_handle, &pa_dshash_handle);
+
+ /*
+ * Return if the number of parallel apply workers has reached the maximum
+ * limit.
+ */
+ if (list_length(ParallelApplyWorkerPool) ==
+ max_parallel_apply_workers_per_subscription)
+ return NULL;
+
/*
* Start a new parallel apply worker.
*
@@ -505,18 +606,50 @@ pa_launch_parallel_worker(void)
dsm_segment_handle(winfo->dsm_seg),
false);
- if (launched)
- {
- ParallelApplyWorkerPool = lappend(ParallelApplyWorkerPool, winfo);
- }
- else
+ if (!launched)
{
+ MemoryContextSwitchTo(oldcontext);
pa_free_worker_info(winfo);
- winfo = NULL;
+ return NULL;
}
+ ParallelApplyWorkerPool = lappend(ParallelApplyWorkerPool, winfo);
+
MemoryContextSwitchTo(oldcontext);
+ /*
+ * Send all existing remote relation information to the parallel apply
+ * worker. This allows the parallel worker to initialize the
+ * LogicalRepRelMapEntry locally before applying remote changes. This is
+ * needed since the walsender does not send remote relation information
+ * with every transaction.
+ */
+ if (logicalrep_get_num_rels())
+ {
+ StringInfoData out;
+ shm_mq_result result;
+
+ initStringInfo(&out);
+
+ write_internal_relation(&out, NULL);
+
+ /*
+ * Send relation information synchronously rather than using
+ * non-blocking send (pa_send_data). This avoids the need to serialize
+ * the data, which would add complexity for the parallel apply worker to
+ * deserialize outside of transaction application.
+ *
+ * This is safe from deadlocks because a newly started worker does not
+ * hold any strong locks when processing relation information.
+ */
+ result = shm_mq_send(winfo->mq_handle, out.len, out.data, false, true);
+
+ if (result != SHM_MQ_SUCCESS)
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("could not send remote relation information to the logical replication parallel apply worker"));
+ }
+
return winfo;
}
@@ -621,25 +754,27 @@ pa_free_worker(ParallelApplyWorkerInfo *winfo)
{
Assert(!am_parallel_apply_worker());
Assert(winfo->in_use);
- Assert(pa_get_xact_state(winfo->shared) == PARALLEL_TRANS_FINISHED);
+ Assert(!winfo->stream_txn ||
+ pa_get_xact_state(winfo->shared) == PARALLEL_TRANS_FINISHED);
if (!hash_search(ParallelApplyTxnHash, &winfo->shared->xid, HASH_REMOVE, NULL))
elog(ERROR, "hash table corrupted");
/*
- * Stop the worker if there are enough workers in the pool.
+ * XXX we stop the worker if the leader apply worker serialize part of the
+ * transaction data due to a send timeout. This is because the message could
+ * be partially written to the queue and there is no way to clean the queue
+ * other than resending the message until it succeeds. Instead of trying to
+ * send the data which anyway would have been serialized and then letting
+ * the parallel apply worker deal with the spurious message, we stop the
+ * worker.
*
- * XXX Additionally, we also stop the worker if the leader apply worker
- * serialize part of the transaction data due to a send timeout. This is
- * because the message could be partially written to the queue and there
- * is no way to clean the queue other than resending the message until it
- * succeeds. Instead of trying to send the data which anyway would have
- * been serialized and then letting the parallel apply worker deal with
- * the spurious message, we stop the worker.
+ * For other cases, we do not stop workers once started. All transactions
+ * (whether streamed or not) are assigned to parallel apply workers, so
+ * restarting workers frequently would only increase CPU overhead and slow
+ * down the leader's ability to dispatch changes to workers.
*/
- if (winfo->serialize_changes ||
- list_length(ParallelApplyWorkerPool) >
- (max_parallel_apply_workers_per_subscription / 2))
+ if (winfo->serialize_changes)
{
logicalrep_pa_worker_stop(winfo);
pa_free_worker_info(winfo);
@@ -772,15 +907,17 @@ pa_process_spooled_messages_if_required(void)
/*
* Get the local end LSN for a transaction applied by a parallel apply worker.
*
+ * Set delete_entry to true if you intend to remove the transaction from the
+ * ParallelApplyTxnHash after collecting its LSN. Otherwise, the local end LSN
+ * is copied from shared memory into the local entry of ParallelApplyTxnHash for
+ * later collection by the leader.
+ *
* If the parallel apply worker did not write any changes during the transaction
* application due to situations like update/delete_missing or a before trigger,
* the *skipped_write will be set to true.
- *
- * Once the LSN is retrieved, the transaction entry is removed from
- * ParallelApplyTxnHash.
*/
XLogRecPtr
-pa_get_last_commit_end(TransactionId xid, bool *skipped_write)
+pa_get_last_commit_end(TransactionId xid, bool delete_entry, bool *skipped_write)
{
bool found;
ParallelApplyWorkerEntry *entry;
@@ -806,7 +943,8 @@ pa_get_last_commit_end(TransactionId xid, bool *skipped_write)
winfo = entry->winfo;
if (winfo == NULL)
{
- if (!hash_search(ParallelApplyTxnHash, &xid, HASH_REMOVE, NULL))
+ if (delete_entry &&
+ !hash_search(ParallelApplyTxnHash, &xid, HASH_REMOVE, NULL))
elog(ERROR, "hash table corrupted");
if (skipped_write)
@@ -829,7 +967,8 @@ pa_get_last_commit_end(TransactionId xid, bool *skipped_write)
elog(DEBUG1, "store local commit %X/%X end to txn entry: %u",
LSN_FORMAT_ARGS(entry->local_end), xid);
- if (!hash_search(ParallelApplyTxnHash, &xid, HASH_REMOVE, NULL))
+ if (delete_entry &&
+ !hash_search(ParallelApplyTxnHash, &xid, HASH_REMOVE, NULL))
elog(ERROR, "hash table corrupted");
return entry->local_end;
@@ -1082,6 +1221,9 @@ pa_shutdown(int code, Datum arg)
INVALID_PROC_NUMBER);
dsm_detach((dsm_segment *) DatumGetPointer(arg));
+
+ if (parallel_apply_dsa_area)
+ dsa_detach(parallel_apply_dsa_area);
}
/*
@@ -1393,7 +1535,6 @@ pa_send_data(ParallelApplyWorkerInfo *winfo, Size nbytes, const void *data)
shm_mq_result result;
TimestampTz startTime = 0;
- Assert(!IsTransactionState());
Assert(!winfo->serialize_changes);
/*
@@ -1445,6 +1586,58 @@ pa_send_data(ParallelApplyWorkerInfo *winfo, Size nbytes, const void *data)
}
}
+/*
+ * Distribute remote relation information to all active parallel apply workers
+ * that require it.
+ */
+void
+pa_distribute_schema_changes_to_workers(LogicalRepRelation *rel)
+{
+ StringInfoData out;
+
+ /* Only leader apply workers can distribute schema changes */
+ if (!am_leader_apply_worker())
+ return;
+
+ /* Quick exit if there are no parallel apply workers */
+ if (!ParallelApplyWorkerPool)
+ return;
+
+ initStringInfo(&out);
+
+ write_internal_relation(&out, rel);
+
+ foreach_ptr(ParallelApplyWorkerInfo, winfo, ParallelApplyWorkerPool)
+ {
+ /*
+ * Skip the worker responsible for the current transaction, as the
+ * relation information has already been sent to it.
+ */
+ if (winfo == stream_apply_worker)
+ continue;
+
+ /*
+ * Skip the worker that is in serialize mode, as they will soon stop
+ * once they finish applying the transaction.
+ */
+ if (winfo->serialize_changes)
+ continue;
+
+ elog(DEBUG1, "distributing schema changes to pa workers");
+
+ if (pa_send_data(winfo, out.len, out.data))
+ continue;
+
+ /*
+ * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
+ * buffer becomes full.
+ */
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("could not send data to the logical replication parallel apply worker for subscription"));
+ }
+}
+
/*
* Switch to PARTIAL_SERIALIZE mode for the current transaction -- this means
* that the current data and any subsequent data for this transaction will be
@@ -1861,25 +2054,41 @@ pa_decr_and_wait_stream_block(void)
void
pa_xact_finish(ParallelApplyWorkerInfo *winfo, XLogRecPtr remote_lsn)
{
+ XLogRecPtr local_lsn = InvalidXLogRecPtr;
+ TransactionId pa_remote_xid = winfo->shared->xid;
+
Assert(am_leader_apply_worker());
/*
- * Unlock the shared object lock so that parallel apply worker can
- * continue to receive and apply changes.
+ * Unlock the shared object lock taken for streaming transactions so that
+ * parallel apply worker can continue to receive and apply changes.
*/
- pa_unlock_stream(winfo->shared->xid, AccessExclusiveLock);
+ if (winfo->stream_txn)
+ pa_unlock_stream(winfo->shared->xid, AccessExclusiveLock);
/*
- * Wait for that worker to finish. This is necessary to maintain commit
- * order which avoids failures due to transaction dependencies and
- * deadlocks.
+ * Wait for that worker for streaming transaction to finish. This is
+ * necessary to maintain commit order which avoids failures due to
+ * transaction dependencies and deadlocks.
+ *
+ * For transactions in partial seralize mode, wait for stop as well as the
+ * worker is anyway cannot be reused anymore (see pa_free_worker() for
+ * details).
*/
- pa_wait_for_xact_finish(winfo);
+ if (winfo->serialize_changes || winfo->stream_txn)
+ {
+ pa_wait_for_xact_finish(winfo);
+
+ local_lsn = winfo->shared->last_commit_end;
+ pa_remote_xid = InvalidTransactionId;
+
+ pa_free_worker(winfo);
+ }
if (XLogRecPtrIsValid(remote_lsn))
- store_flush_position(remote_lsn, winfo->shared->last_commit_end);
+ store_flush_position(remote_lsn, local_lsn, pa_remote_xid);
- pa_free_worker(winfo);
+ pa_set_stream_apply_worker(NULL);
}
/*
@@ -2013,3 +2222,62 @@ pa_wait_for_depended_transaction(TransactionId xid)
elog(DEBUG1, "finish waiting for depended xid %u", xid);
}
+
+/*
+ * Mark the transaction state as finished and remove the shared hash entry.
+ */
+void
+pa_commit_transaction(void)
+{
+ TransactionId xid = MyParallelShared->xid;
+
+ SpinLockAcquire(&MyParallelShared->mutex);
+ MyParallelShared->xact_state = PARALLEL_TRANS_FINISHED;
+ SpinLockRelease(&MyParallelShared->mutex);
+
+ dshash_delete_key(parallelized_txns, &xid);
+ elog(DEBUG1, "xid %u committed", xid);
+}
+
+/*
+ * Write internal relation description to the output stream.
+ */
+static void
+write_internal_relation(StringInfo s, LogicalRepRelation *rel)
+{
+ pq_sendbyte(s, LOGICAL_REP_MSG_INTERNAL_MESSAGE);
+ pq_sendbyte(s, PA_MSG_RELMAP);
+
+ if (rel)
+ {
+ pq_sendint(s, 1, 4);
+ logicalrep_write_internal_rel(s, rel);
+ }
+ else
+ {
+ pq_sendint(s, logicalrep_get_num_rels(), 4);
+ logicalrep_write_all_rels(s);
+ }
+}
+
+/*
+ * Register a transaction to the shared hash table.
+ *
+ * This function is called by the leader during the commit phase of non-streamed
+ * transactions. The parallel apply worker that applies the transaction will
+ * remove it from the hash table upon completion.
+ */
+void
+pa_add_parallelized_transaction(TransactionId xid)
+{
+ bool found;
+ ParallelizedTxnEntry *txn_entry;
+
+ Assert(parallelized_txns);
+ Assert(TransactionIdIsValid(xid));
+ Assert(am_leader_apply_worker());
+
+ txn_entry = dshash_find_or_insert(parallelized_txns, &xid, &found);
+
+ dshash_release_lock(parallelized_txns, txn_entry);
+}
diff --git a/src/backend/replication/logical/proto.c b/src/backend/replication/logical/proto.c
index a0cac05cdcd..eb1a846ce0c 100644
--- a/src/backend/replication/logical/proto.c
+++ b/src/backend/replication/logical/proto.c
@@ -691,6 +691,44 @@ logicalrep_write_rel(StringInfo out, TransactionId xid, Relation rel,
logicalrep_write_attrs(out, rel, columns, include_gencols_type);
}
+/*
+ * Write internal relation description to the output stream.
+ */
+void
+logicalrep_write_internal_rel(StringInfo out, LogicalRepRelation *rel)
+{
+ pq_sendint32(out, rel->remoteid);
+
+ /* Write relation name */
+ pq_sendstring(out, rel->nspname);
+ pq_sendstring(out, rel->relname);
+
+ /* Write the replica identity. */
+ pq_sendbyte(out, rel->replident);
+
+ /* Write attribute description */
+ pq_sendint16(out, rel->natts);
+
+ for (int i = 0; i < rel->natts; i++)
+ {
+ uint8 flags = 0;
+
+ if (bms_is_member(i, rel->attkeys))
+ flags |= LOGICALREP_IS_REPLICA_IDENTITY;
+
+ pq_sendbyte(out, flags);
+
+ /* attribute name */
+ pq_sendstring(out, rel->attnames[i]);
+
+ /* attribute type id */
+ pq_sendint32(out, rel->atttyps[i]);
+
+ /* ignore attribute mode for now */
+ pq_sendint32(out, 0);
+ }
+}
+
/*
* Read the relation info from stream and return as LogicalRepRelation.
*/
diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index ab6313eb1bc..e1ce183dfd3 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -961,6 +961,37 @@ FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
return InvalidOid;
}
+/*
+ * Get the number of entries in the LogicalRepRelMap.
+ */
+int
+logicalrep_get_num_rels(void)
+{
+ if (LogicalRepRelMap == NULL)
+ return 0;
+
+ return hash_get_num_entries(LogicalRepRelMap);
+}
+
+/*
+ * Write all the remote relation information from the LogicalRepRelMapEntry to
+ * the output stream.
+ */
+void
+logicalrep_write_all_rels(StringInfo out)
+{
+ LogicalRepRelMapEntry *entry;
+ HASH_SEQ_STATUS status;
+
+ if (LogicalRepRelMap == NULL)
+ return;
+
+ hash_seq_init(&status, LogicalRepRelMap);
+
+ while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
+ logicalrep_write_internal_rel(out, &entry->remoterel);
+}
+
/*
* Get the LogicalRepRelMapEntry corresponding to the given relid without
* opening the local relation.
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index ee69f07f715..faf7a50bf25 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -290,6 +290,7 @@
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/guc.h"
+#include "utils/injection_point.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
@@ -514,6 +515,8 @@ static List *on_commit_wakeup_workers_subids = NIL;
bool in_remote_transaction = false;
static XLogRecPtr remote_final_lsn = InvalidXLogRecPtr;
+static TransactionId remote_xid = InvalidTransactionId;
+static TransactionId last_parallelized_remote_xid = InvalidTransactionId;
/* fields valid only when processing streamed transaction */
static bool in_streamed_transaction = false;
@@ -722,6 +725,7 @@ static void on_exit_clear_xact_state(int code, Datum arg);
static void send_internal_dependencies(ParallelApplyWorkerInfo *winfo,
List *depends_on_xids);
+static void build_dependency_with_last_committed_txn(ParallelApplyWorkerInfo *winfo);
/*
* Compute the hash value for entries in the replica_identity_table.
@@ -837,7 +841,7 @@ cleanup_committed_replica_identity_entries(void)
XLogRecPtrIsValid(pos->local_end))
continue;
- pos->local_end = pa_get_last_commit_end(pos->pa_remote_xid,
+ pos->local_end = pa_get_last_commit_end(pos->pa_remote_xid, false,
&skipped_write);
elog(DEBUG1,
@@ -1441,14 +1445,14 @@ handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
TransApplyAction apply_action;
StringInfoData original_msg;
+ if (!in_streamed_transaction)
+ return false;
+
apply_action = get_transaction_apply_action(stream_xid, &winfo);
/* not in streaming mode */
if (apply_action == TRANS_LEADER_APPLY)
- {
- handle_dependency_on_change(action, s, InvalidTransactionId, winfo);
return false;
- }
Assert(TransactionIdIsValid(stream_xid));
@@ -1523,6 +1527,73 @@ handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
}
}
+/*
+ * Handle non-streaming transactions when parallel apply is in use.
+ *
+ * This function runs only in the leader apply worker while processing a remote
+ * transaction. It checks whether the current change has dependencies on
+ * preceding parallelized transactions and decides whether to send the change to
+ * a parallel apply worker.
+ *
+ * Returns true if the change has been dispatched to a parallel worker,
+ * indicating the leader does not need to apply it directly. Returns false
+ * otherwise.
+ *
+ * Exception: If the message being processed is LOGICAL_REP_MSG_RELATION or
+ * LOGICAL_REP_MSG_TYPE, return false even if the message needs to be sent to a
+ * parallel apply worker.
+ */
+static bool
+handle_parallelized_transaction(LogicalRepMsgType action, StringInfo s)
+{
+ ParallelApplyWorkerInfo *winfo;
+ TransApplyAction apply_action;
+
+ /*
+ * Dependency checking for non-streaming transactions is only required in
+ * the leader apply worker during a remote transaction.
+ */
+ if (!in_remote_transaction || !am_leader_apply_worker())
+ return false;
+
+ apply_action = get_transaction_apply_action(remote_xid, &winfo);
+
+ /* not assigned to parallel apply worker, apply in leader */
+ if (apply_action == TRANS_LEADER_APPLY)
+ {
+ handle_dependency_on_change(action, s, InvalidTransactionId, winfo);
+ return false;
+ }
+
+ Assert(TransactionIdIsValid(remote_xid));
+
+ handle_dependency_on_change(action, s, remote_xid, winfo);
+
+ switch (apply_action)
+ {
+ case TRANS_LEADER_SEND_TO_PARALLEL:
+ Assert(winfo);
+
+ /* Always update relation and type cache in leader apply worker */
+ if (pa_send_data(winfo, s->len, s->data))
+ return (action != LOGICAL_REP_MSG_RELATION &&
+ action != LOGICAL_REP_MSG_TYPE);
+
+ /*
+ * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
+ * buffer becomes full.
+ */
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("could not send data to the logical replication parallel apply worker"));
+ return false; /* silence compiler warning */
+
+ default:
+ elog(ERROR, "unexpected apply action: %d", (int) apply_action);
+ return false; /* silence compiler warning */
+ }
+}
+
/*
* Executor state preparation for evaluation of constraint expressions,
* indexes and triggers for the specified relation.
@@ -1884,17 +1955,61 @@ static void
apply_handle_begin(StringInfo s)
{
LogicalRepBeginData begin_data;
+ ParallelApplyWorkerInfo *winfo;
+ TransApplyAction apply_action;
/* There must not be an active streaming transaction. */
Assert(!TransactionIdIsValid(stream_xid));
logicalrep_read_begin(s, &begin_data);
- set_apply_error_context_xact(begin_data.xid, begin_data.final_lsn);
+
+ remote_xid = begin_data.xid;
+
+ set_apply_error_context_xact(remote_xid, begin_data.final_lsn);
remote_final_lsn = begin_data.final_lsn;
maybe_start_skipping_changes(begin_data.final_lsn);
+ pa_allocate_worker(remote_xid, false);
+
+ apply_action = get_transaction_apply_action(remote_xid, &winfo);
+
+ elog(DEBUG1, "new remote_xid %u", remote_xid);
+ switch (apply_action)
+ {
+ case TRANS_LEADER_APPLY:
+ break;
+
+ case TRANS_LEADER_SEND_TO_PARALLEL:
+ Assert(winfo);
+
+ if (pa_send_data(winfo, s->len, s->data))
+ {
+ pa_set_stream_apply_worker(winfo);
+ break;
+ }
+
+ /*
+ * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
+ * buffer becomes full.
+ */
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("could not send data to the logical replication parallel apply worker"));
+ break;
+
+ case TRANS_PARALLEL_APPLY:
+ /* Hold the lock until the end of the transaction. */
+ pa_lock_transaction(MyParallelShared->xid, AccessExclusiveLock);
+ pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_STARTED);
+ break;
+
+ default:
+ elog(ERROR, "unexpected apply action: %d", (int) apply_action);
+ break;
+ }
+
in_remote_transaction = true;
pgstat_report_activity(STATE_RUNNING, NULL);
@@ -1917,12 +2032,33 @@ send_internal_dependencies(ParallelApplyWorkerInfo *winfo, List *depends_on_xids
foreach_xid(xid, depends_on_xids)
pq_sendint32(&dependencies, xid);
- if (pa_send_data(winfo, dependencies.len, dependencies.data))
+ /*
+ * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
+ * buffer becomes full.
+ */
+ if (!pa_send_data(winfo, dependencies.len, dependencies.data))
ereport(ERROR,
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("could not send data to the logical replication parallel apply worker"));
}
+/*
+ * Make a dependency between this and the lastly committed transaction.
+ *
+ * Sends an INTERNAL_DEPENDENCY message to the parallel apply worker,
+ * instructing it to wait for the last committed transaction to finish before
+ * committing its own, thereby preserving commit order.
+ */
+static void
+build_dependency_with_last_committed_txn(ParallelApplyWorkerInfo *winfo)
+{
+ /* Skip if transactions have not been applied yet */
+ if (!TransactionIdIsValid(last_parallelized_remote_xid))
+ return;
+
+ send_internal_dependencies(winfo, list_make1_xid(last_parallelized_remote_xid));
+}
+
/*
* Handle COMMIT message.
*
@@ -1932,6 +2068,8 @@ static void
apply_handle_commit(StringInfo s)
{
LogicalRepCommitData commit_data;
+ ParallelApplyWorkerInfo *winfo;
+ TransApplyAction apply_action;
logicalrep_read_commit(s, &commit_data);
@@ -1942,7 +2080,92 @@ apply_handle_commit(StringInfo s)
LSN_FORMAT_ARGS(commit_data.commit_lsn),
LSN_FORMAT_ARGS(remote_final_lsn))));
- apply_handle_commit_internal(&commit_data);
+ apply_action = get_transaction_apply_action(remote_xid, &winfo);
+
+ switch (apply_action)
+ {
+ case TRANS_LEADER_APPLY:
+
+ /*
+ * Apart from parallelized transactions, we do not have to
+ * register this transaction to parallelized_txns. The commit
+ * ordering is always preserved.
+ */
+
+ /* Wait until the last transaction finishes */
+ if (TransactionIdIsValid(last_parallelized_remote_xid))
+ {
+ pa_wait_for_depended_transaction(last_parallelized_remote_xid);
+ last_parallelized_remote_xid = InvalidTransactionId;
+ }
+
+ apply_handle_commit_internal(&commit_data);
+
+ break;
+
+ case TRANS_LEADER_SEND_TO_PARALLEL:
+ Assert(winfo);
+
+ /*
+ * Mark this transaction as parallelized. This ensures that
+ * upcoming transactions wait until this transaction is committed.
+ */
+ pa_add_parallelized_transaction(remote_xid);
+
+ /*
+ * Build a dependency between this transaction and the lastly
+ * committed transaction to preserve the commit order.
+ */
+ build_dependency_with_last_committed_txn(winfo);
+
+ if (pa_send_data(winfo, s->len, s->data))
+ {
+ /* Cache the remote_xid */
+ last_parallelized_remote_xid = remote_xid;
+
+ /* Finish processing the transaction. */
+ pa_xact_finish(winfo, commit_data.end_lsn);
+ break;
+ }
+
+ /*
+ * TODO: Support switching to PARTIAL_SERIALIZE mode when the send
+ * buffer becomes full.
+ */
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("could not send data to the logical replication parallel apply worker"));
+ break;
+
+ case TRANS_PARALLEL_APPLY:
+
+ /*
+ * If the parallel apply worker is applying spooled messages then
+ * close the file before committing.
+ */
+ if (stream_fd)
+ stream_close_file();
+
+ INJECTION_POINT("parallel-worker-before-commit", NULL);
+
+ apply_handle_commit_internal(&commit_data);
+
+ MyParallelShared->last_commit_end = XactLastCommitEnd;
+
+ pa_commit_transaction();
+
+ pa_unlock_transaction(remote_xid, AccessExclusiveLock);
+ break;
+
+ default:
+ elog(ERROR, "unexpected apply action: %d", (int) apply_action);
+ break;
+ }
+
+ remote_xid = InvalidTransactionId;
+ in_remote_transaction = false;
+
+ elog(DEBUG1, "reset remote_xid %u", remote_xid);
/*
* Process any tables that are being synchronized in parallel, as well as
@@ -2065,7 +2288,8 @@ apply_handle_prepare(StringInfo s)
* XactLastCommitEnd, and adding it for this purpose doesn't seems worth
* it.
*/
- store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr);
+ store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr,
+ InvalidTransactionId);
in_remote_transaction = false;
@@ -2125,7 +2349,8 @@ apply_handle_commit_prepared(StringInfo s)
CommitTransactionCommand();
pgstat_report_stat(false);
- store_flush_position(prepare_data.end_lsn, XactLastCommitEnd);
+ store_flush_position(prepare_data.end_lsn, XactLastCommitEnd,
+ InvalidTransactionId);
in_remote_transaction = false;
/*
@@ -2194,7 +2419,8 @@ apply_handle_rollback_prepared(StringInfo s)
* transaction because we always flush the WAL record for it. See
* apply_handle_prepare.
*/
- store_flush_position(rollback_data.rollback_end_lsn, InvalidXLogRecPtr);
+ store_flush_position(rollback_data.rollback_end_lsn, InvalidXLogRecPtr,
+ InvalidTransactionId);
in_remote_transaction = false;
/*
@@ -2256,7 +2482,8 @@ apply_handle_stream_prepare(StringInfo s)
* It is okay not to set the local_end LSN for the prepare because
* we always flush the prepare record. See apply_handle_prepare.
*/
- store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr);
+ store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr,
+ InvalidTransactionId);
in_remote_transaction = false;
@@ -2448,8 +2675,17 @@ apply_handle_stream_start(StringInfo s)
set_apply_error_context_xact(stream_xid, InvalidXLogRecPtr);
- /* Try to allocate a worker for the streaming transaction. */
- if (first_segment)
+ /*
+ * Try to allocate a worker for the streaming transaction.
+ *
+ * TODO: Support assigning streaming transactions to parallel apply workers
+ * even when non-streaming transactions are running and better dependency
+ * handling between streaming and non-streaming transactions.
+ */
+ if (first_segment &&
+ am_leader_apply_worker() &&
+ (!TransactionIdIsValid(last_parallelized_remote_xid) ||
+ pa_transaction_committed(last_parallelized_remote_xid)))
pa_allocate_worker(stream_xid, true);
apply_action = get_transaction_apply_action(stream_xid, &winfo);
@@ -2964,8 +3200,7 @@ apply_spooled_messages(FileSet *stream_fileset, TransactionId xid,
int fileno;
pgoff_t offset;
- if (!am_parallel_apply_worker())
- maybe_start_skipping_changes(lsn);
+ maybe_start_skipping_changes(lsn);
/* Make sure we have an open transaction */
begin_replication_step();
@@ -3235,7 +3470,8 @@ apply_handle_commit_internal(LogicalRepCommitData *commit_data)
pgstat_report_stat(false);
- store_flush_position(commit_data->end_lsn, XactLastCommitEnd);
+ store_flush_position(commit_data->end_lsn, XactLastCommitEnd,
+ InvalidTransactionId);
}
else
{
@@ -3260,7 +3496,8 @@ apply_handle_relation(StringInfo s)
{
LogicalRepRelation *rel;
- if (handle_streamed_transaction(LOGICAL_REP_MSG_RELATION, s))
+ if (handle_parallelized_transaction(LOGICAL_REP_MSG_RELATION, s) ||
+ handle_streamed_transaction(LOGICAL_REP_MSG_RELATION, s))
return;
rel = logicalrep_read_rel(s);
@@ -3268,6 +3505,8 @@ apply_handle_relation(StringInfo s)
/* Also reset all entries in the partition map that refer to remoterel. */
logicalrep_partmap_reset_relmap(rel);
+
+ pa_distribute_schema_changes_to_workers(rel);
}
/*
@@ -3283,7 +3522,8 @@ apply_handle_type(StringInfo s)
{
LogicalRepTyp typ;
- if (handle_streamed_transaction(LOGICAL_REP_MSG_TYPE, s))
+ if (handle_parallelized_transaction(LOGICAL_REP_MSG_TYPE, s) ||
+ handle_streamed_transaction(LOGICAL_REP_MSG_TYPE, s))
return;
logicalrep_read_typ(s, &typ);
@@ -3343,6 +3583,7 @@ apply_handle_insert(StringInfo s)
* streamed transactions.
*/
if (is_skipping_changes() ||
+ handle_parallelized_transaction(LOGICAL_REP_MSG_INSERT, s) ||
handle_streamed_transaction(LOGICAL_REP_MSG_INSERT, s))
return;
@@ -3503,6 +3744,7 @@ apply_handle_update(StringInfo s)
* streamed transactions.
*/
if (is_skipping_changes() ||
+ handle_parallelized_transaction(LOGICAL_REP_MSG_UPDATE, s) ||
handle_streamed_transaction(LOGICAL_REP_MSG_UPDATE, s))
return;
@@ -3727,6 +3969,7 @@ apply_handle_delete(StringInfo s)
* streamed transactions.
*/
if (is_skipping_changes() ||
+ handle_parallelized_transaction(LOGICAL_REP_MSG_DELETE, s) ||
handle_streamed_transaction(LOGICAL_REP_MSG_DELETE, s))
return;
@@ -4363,6 +4606,7 @@ apply_handle_truncate(StringInfo s)
* streamed transactions.
*/
if (is_skipping_changes() ||
+ handle_parallelized_transaction(LOGICAL_REP_MSG_TRUNCATE, s) ||
handle_streamed_transaction(LOGICAL_REP_MSG_TRUNCATE, s))
return;
@@ -4593,6 +4837,10 @@ apply_dispatch(StringInfo s)
* check which entries on it are already locally flushed. Those we can report
* as having been flushed.
*
+ * For non-streaming transactions managed by a parallel apply worker, we will
+ * get the local commit end from the shared parallel apply worker info once the
+ * transaction has been committed by the worker.
+ *
* The have_pending_txes is true if there are outstanding transactions that
* need to be flushed.
*/
@@ -4602,6 +4850,7 @@ get_flush_position(XLogRecPtr *write, XLogRecPtr *flush,
{
dlist_mutable_iter iter;
XLogRecPtr local_flush = GetFlushRecPtr(NULL);
+ List *committed_pa_xid = NIL;
*write = InvalidXLogRecPtr;
*flush = InvalidXLogRecPtr;
@@ -4611,6 +4860,40 @@ get_flush_position(XLogRecPtr *write, XLogRecPtr *flush,
FlushPosition *pos =
dlist_container(FlushPosition, node, iter.cur);
+ /*
+ * If the transaction was assigned to a parallel apply worker, attempt
+ * to retrieve its commit end LSN from that worker.
+ */
+ if (TransactionIdIsValid(pos->pa_remote_xid) &&
+ !XLogRecPtrIsValid(pos->local_end))
+ {
+ bool skipped_write;
+
+ pos->local_end = pa_get_last_commit_end(pos->pa_remote_xid, true,
+ &skipped_write);
+
+ elog(DEBUG1,
+ "got commit end from parallel apply worker, "
+ "txn: %u, remote_end %X/%X, local_end %X/%X",
+ pos->pa_remote_xid, LSN_FORMAT_ARGS(pos->remote_end),
+ LSN_FORMAT_ARGS(pos->local_end));
+
+ /*
+ * Break the loop if the worker has not finished applying the
+ * transaction. There's no need to check subsequent transactions,
+ * as they must commit after the current transaction being
+ * examined and thus won't have their commit end available yet.
+ */
+ if (!skipped_write && XLogRecPtrIsInvalid(pos->local_end))
+ break;
+
+ committed_pa_xid = lappend_xid(committed_pa_xid, pos->pa_remote_xid);
+ }
+
+ /*
+ * Worker has finished applying or the transaction was applied in the
+ * leader apply worker.
+ */
*write = pos->remote_end;
if (pos->local_end <= local_flush)
@@ -4619,29 +4902,22 @@ get_flush_position(XLogRecPtr *write, XLogRecPtr *flush,
dlist_delete(iter.cur);
pfree(pos);
}
- else
- {
- /*
- * Don't want to uselessly iterate over the rest of the list which
- * could potentially be long. Instead get the last element and
- * grab the write position from there.
- */
- pos = dlist_tail_element(FlushPosition, node,
- &lsn_mapping);
- *write = pos->remote_end;
- *have_pending_txes = true;
- return;
- }
}
*have_pending_txes = !dlist_is_empty(&lsn_mapping);
+
+ delete_replica_identity_entries_for_txns(committed_pa_xid);
}
/*
* Store current remote/local lsn pair in the tracking list.
+ *
+ * pa_remote_xid should be a valid transaction ID only when the transaction was
+ * assigned to a parallel apply worker; otherwise, pass InvalidTransactionId.
*/
void
-store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn)
+store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn,
+ TransactionId pa_remote_xid)
{
FlushPosition *flushpos;
@@ -4659,7 +4935,7 @@ store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn)
flushpos = palloc_object(FlushPosition);
flushpos->local_end = local_lsn;
flushpos->remote_end = remote_lsn;
- flushpos->pa_remote_xid = InvalidTransactionId;
+ flushpos->pa_remote_xid = pa_remote_xid;
dlist_push_tail(&lsn_mapping, &flushpos->node);
MemoryContextSwitchTo(ApplyMessageContext);
@@ -6784,6 +7060,22 @@ static void
maybe_start_skipping_changes(XLogRecPtr finish_lsn)
{
Assert(!is_skipping_changes());
+
+ /*
+ * For streaming transactions applied in a parallel apply worker, the remote
+ * end LSN is unknown, so skipping is not possible. For non-streaming
+ * transactions, the leader determines whether to skip the transaction. If
+ * skipping is needed, the leader simply does not send the transaction to a
+ * parallel apply worker.
+ */
+ if (am_parallel_apply_worker())
+ return;
+
+ /*
+ * These assertions apply only to leader apply and table sync workers.
+ * Parallel workers may apply spooled BEGIN or STREAM_START messages, which
+ * can set these flags to true.
+ */
Assert(!in_remote_transaction);
Assert(!in_streamed_transaction);
diff --git a/src/include/replication/logicalproto.h b/src/include/replication/logicalproto.h
index cb0a8f440c0..d9f375295de 100644
--- a/src/include/replication/logicalproto.h
+++ b/src/include/replication/logicalproto.h
@@ -259,6 +259,8 @@ extern void logicalrep_write_message(StringInfo out, TransactionId xid, XLogRecP
extern void logicalrep_write_rel(StringInfo out, TransactionId xid,
Relation rel, Bitmapset *columns,
PublishGencolsType include_gencols_type);
+extern void logicalrep_write_internal_rel(StringInfo out,
+ LogicalRepRelation *rel);
extern LogicalRepRelation *logicalrep_read_rel(StringInfo in);
extern void logicalrep_write_typ(StringInfo out, TransactionId xid,
Oid typoid);
diff --git a/src/include/replication/logicalrelation.h b/src/include/replication/logicalrelation.h
index 09890cef8d4..cd852337165 100644
--- a/src/include/replication/logicalrelation.h
+++ b/src/include/replication/logicalrelation.h
@@ -58,6 +58,8 @@ extern void logicalrep_rel_close(LogicalRepRelMapEntry *rel,
LOCKMODE lockmode);
extern bool IsIndexUsableForReplicaIdentityFull(Relation idxrel, AttrMap *attrmap);
extern Oid GetRelationIdentityOrPK(Relation rel);
+extern int logicalrep_get_num_rels(void);
+extern void logicalrep_write_all_rels(StringInfo out);
extern LogicalRepRelMapEntry *logicalrep_get_relentry(LogicalRepRelId remoteid);
#endif /* LOGICALRELATION_H */
diff --git a/src/include/replication/worker_internal.h b/src/include/replication/worker_internal.h
index 3c88d9e1027..02a165ccc0d 100644
--- a/src/include/replication/worker_internal.h
+++ b/src/include/replication/worker_internal.h
@@ -345,7 +345,8 @@ extern void SetupApplyOrSyncWorker(int worker_slot);
extern void DisableSubscriptionAndExit(void);
-extern void store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn);
+extern void store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn,
+ TransactionId pa_remote_xid);
/* Function for apply error callback */
extern void apply_error_callback(void *arg);
@@ -354,13 +355,15 @@ extern void set_apply_error_context_origin(char *originname);
/* Parallel apply worker setup and interactions */
extern void pa_allocate_worker(TransactionId xid, bool stream_txn);
extern ParallelApplyWorkerInfo *pa_find_worker(TransactionId xid);
-extern XLogRecPtr pa_get_last_commit_end(TransactionId xid, bool *skipped_write);
+extern XLogRecPtr pa_get_last_commit_end(TransactionId xid, bool delete_entry,
+ bool *skipped_write);
extern void pa_detach_all_error_mq(void);
extern void apply_handle_internal_message(StringInfo s);
extern bool pa_send_data(ParallelApplyWorkerInfo *winfo, Size nbytes,
const void *data);
+extern void pa_distribute_schema_changes_to_workers(LogicalRepRelation *rel);
extern void pa_switch_to_partial_serialize(ParallelApplyWorkerInfo *winfo,
bool stream_locked);
@@ -386,8 +389,9 @@ extern void pa_decr_and_wait_stream_block(void);
extern void pa_xact_finish(ParallelApplyWorkerInfo *winfo,
XLogRecPtr remote_lsn);
extern bool pa_transaction_committed(TransactionId xid);
-
+extern void pa_commit_transaction(void);
extern void pa_wait_for_depended_transaction(TransactionId xid);
+extern void pa_add_parallelized_transaction(TransactionId xid);
#define isParallelApplyWorker(worker) ((worker)->in_use && \
(worker)->type == WORKERTYPE_PARALLEL_APPLY)
diff --git a/src/test/subscription/meson.build b/src/test/subscription/meson.build
index fdc04d91f41..48ae698e786 100644
--- a/src/test/subscription/meson.build
+++ b/src/test/subscription/meson.build
@@ -48,7 +48,7 @@ tests += {
't/036_sequences.pl',
't/037_except.pl',
't/038_walsnd_shutdown_timeout.pl',
- 't/039_row_filter_toast_ri.pl',
+ 't/050_parallel_apply.pl',
't/100_bugs.pl',
],
},
diff --git a/src/test/subscription/t/001_rep_changes.pl b/src/test/subscription/t/001_rep_changes.pl
index 7d41715ed81..c863b430bec 100644
--- a/src/test/subscription/t/001_rep_changes.pl
+++ b/src/test/subscription/t/001_rep_changes.pl
@@ -16,6 +16,8 @@ $node_publisher->start;
# Create subscriber node
my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
$node_subscriber->init;
+$node_subscriber->append_conf('postgresql.conf',
+ "max_logical_replication_workers = 10");
$node_subscriber->start;
# Create some preexisting content on publisher
diff --git a/src/test/subscription/t/010_truncate.pl b/src/test/subscription/t/010_truncate.pl
index 945505d0239..e15a6bb2a03 100644
--- a/src/test/subscription/t/010_truncate.pl
+++ b/src/test/subscription/t/010_truncate.pl
@@ -17,7 +17,7 @@ $node_publisher->start;
my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
$node_subscriber->init;
$node_subscriber->append_conf('postgresql.conf',
- qq(max_logical_replication_workers = 6));
+ qq(max_logical_replication_workers = 7));
$node_subscriber->start;
my $publisher_connstr = $node_publisher->connstr . ' dbname=postgres';
diff --git a/src/test/subscription/t/015_stream.pl b/src/test/subscription/t/015_stream.pl
index ac96bc3f009..705bc83f5ea 100644
--- a/src/test/subscription/t/015_stream.pl
+++ b/src/test/subscription/t/015_stream.pl
@@ -232,6 +232,12 @@ $node_subscriber->wait_for_log(
$node_publisher->safe_psql('postgres', "INSERT INTO test_tab_2 values(1)");
+# FIXME: Currently, non-streaming transactions are applied in parallel by
+# default. So, the first transaction is handled by a parallel apply worker. To
+# trigger the deadlock, initiate an more transaction to be applied by the
+# leader.
+$node_publisher->safe_psql('postgres', "INSERT INTO test_tab_2 values(1)");
+
$h->query_safe('COMMIT');
$h->quit;
@@ -247,7 +253,7 @@ $node_publisher->wait_for_catchup($appname);
$result =
$node_subscriber->safe_psql('postgres', "SELECT count(*) FROM test_tab_2");
-is($result, qq(5001), 'data replicated to subscriber after dropping index');
+is($result, qq(5002), 'data replicated to subscriber after dropping index');
# Clean up test data from the environment.
$node_publisher->safe_psql('postgres', "TRUNCATE TABLE test_tab_2");
diff --git a/src/test/subscription/t/026_stats.pl b/src/test/subscription/t/026_stats.pl
index 5d457060a02..911005bde20 100644
--- a/src/test/subscription/t/026_stats.pl
+++ b/src/test/subscription/t/026_stats.pl
@@ -16,6 +16,7 @@ $node_publisher->start;
# Create subscriber node.
my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
$node_subscriber->init;
+$node_subscriber->append_conf('postgresql.conf', "max_logical_replication_workers = 10");
$node_subscriber->start;
diff --git a/src/test/subscription/t/027_nosuperuser.pl b/src/test/subscription/t/027_nosuperuser.pl
index 322f5b4cc6a..fdfc44ac729 100644
--- a/src/test/subscription/t/027_nosuperuser.pl
+++ b/src/test/subscription/t/027_nosuperuser.pl
@@ -86,6 +86,7 @@ $node_publisher = PostgreSQL::Test::Cluster->new('publisher');
$node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
$node_publisher->init(allows_streaming => 'logical');
$node_subscriber->init;
+$node_subscriber->append_conf('postgresql.conf', "max_logical_replication_workers = 10");
$node_publisher->start;
$node_subscriber->start;
$publisher_connstr = $node_publisher->connstr . ' dbname=postgres';
diff --git a/src/test/subscription/t/050_parallel_apply.pl b/src/test/subscription/t/050_parallel_apply.pl
new file mode 100644
index 00000000000..14121b23f23
--- /dev/null
+++ b/src/test/subscription/t/050_parallel_apply.pl
@@ -0,0 +1,201 @@
+
+# Copyright (c) 2025, PostgreSQL Global Development Group
+
+# This test verifies that a non-streamed transaction can launch a parallel apply
+# worker, and that dependency tracking and commit order preservation work
+# correctly during parallel apply.
+
+use strict;
+use warnings;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+# Initialize publisher node
+my $node_publisher = PostgreSQL::Test::Cluster->new('publisher');
+$node_publisher->init(allows_streaming => 'logical');
+$node_publisher->start;
+
+# Create tables and insert initial data
+$node_publisher->safe_psql(
+ 'postgres', qq(
+ CREATE TABLE regress_tab (id int PRIMARY KEY, value text);
+
+ CREATE TABLE tab_toast (a text NOT NULL, b text NOT NULL);
+ ALTER TABLE tab_toast ALTER COLUMN a SET STORAGE EXTERNAL;
+ CREATE UNIQUE INDEX tab_toast_ri_index on tab_toast (a, b);
+ ALTER TABLE tab_toast REPLICA IDENTITY USING INDEX tab_toast_ri_index;
+ INSERT INTO tab_toast(a, b) VALUES(repeat('1234567890', 200), '1234567890');
+));
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (generate_series(1, 10), 'test');");
+
+# Create a publication
+$node_publisher->safe_psql('postgres',
+ "CREATE PUBLICATION regress_pub FOR ALL TABLES;");
+
+# Initialize subscriber node
+my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
+$node_subscriber->init;
+$node_subscriber->append_conf('postgresql.conf', "log_min_messages = debug1");
+$node_subscriber->append_conf('postgresql.conf',
+ "max_logical_replication_workers = 10");
+$node_subscriber->start;
+
+# Check if the extension injection_points is available, as it may be
+# possible that this script is run with installcheck, where the module
+# would not be installed by default.
+if (!$node_subscriber->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+
+$node_subscriber->safe_psql('postgres', 'CREATE EXTENSION injection_points;');
+
+# Create a subscription
+my $publisher_connstr = $node_publisher->connstr . ' dbname=postgres';
+
+$node_subscriber->safe_psql(
+ 'postgres', qq(
+ CREATE TABLE regress_tab (id int PRIMARY KEY, value text);
+
+ CREATE TABLE tab_toast (a text NOT NULL, b text NOT NULL);
+ ALTER TABLE tab_toast ALTER COLUMN a SET STORAGE EXTERNAL;
+ CREATE UNIQUE INDEX tab_toast_ri_index on tab_toast (a, b);
+ ALTER TABLE tab_toast REPLICA IDENTITY USING INDEX tab_toast_ri_index;
+));
+$node_subscriber->safe_psql('postgres',
+ "CREATE SUBSCRIPTION regress_sub CONNECTION '$publisher_connstr' PUBLICATION regress_pub;");
+
+# Wait for initial table sync to finish
+$node_subscriber->wait_for_subscription_sync($node_publisher, 'regress_sub');
+
+##################################################
+# Test that a non-streamed transaction can be applied in a parallel apply worker
+##################################################
+
+# Insert tuples on publisher
+#
+# XXX This may not enough to launch a parallel apply worker, because
+# table_states_not_ready is not discarded yet.
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (generate_series(11, 20), 'test');");
+$node_publisher->wait_for_catchup('regress_sub');
+
+# Insert tuples again
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (generate_series(21, 30), 'test');");
+$node_publisher->wait_for_catchup('regress_sub');
+
+# Verify the parallel apply worker is launched
+my $result = $node_subscriber->safe_psql('postgres',
+ "SELECT count(1) FROM pg_stat_activity WHERE backend_type = 'logical replication parallel worker'");
+is($result, '1', "parallel apply worker is launched by a non-streamed transaction");
+
+##################################################
+# Test that the basic replica identity dependency tracking and commit order
+# preservation work correctly during parallel apply.
+##################################################
+
+# Attach an injection_point. Parallel workers would wait before the commit
+$node_subscriber->safe_psql('postgres',
+ "SELECT injection_points_attach('parallel-worker-before-commit','wait');"
+);
+
+# Insert tuples on publisher
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (generate_series(31, 40), 'test');");
+
+# Wait until the parallel worker enters the injection point.
+$node_subscriber->wait_for_event('logical replication parallel worker',
+ 'parallel-worker-before-commit');
+
+my $offset = -s $node_subscriber->logfile;
+
+# Insert tuples on publisher again. This transaction is independent from the
+# previous one, but the parallel worker would wait till it finishes
+$node_publisher->safe_psql('postgres',
+ "INSERT INTO regress_tab VALUES (generate_series(41, 50), 'test');");
+
+# Verify the parallel worker waits for the transaction
+my $str = $node_subscriber->wait_for_log(qr/wait for depended xid ([1-9][0-9]+)/, $offset);
+my $xid = $str =~ /wait for depended xid ([1-9][0-9]+)/;
+
+# Update tuples which have not been applied yet on subscriber because the
+# parallel worker stops at the injection point. Newly assigned worker also
+# waits for the same transactions as above.
+$node_publisher->safe_psql('postgres',
+ "UPDATE regress_tab SET value = 'updated' WHERE id BETWEEN 31 AND 35;");
+
+# Verify the dependency is detected for the update
+$node_subscriber->wait_for_log(qr/found conflicting replica identity change from $xid/, $offset);
+
+# Verify the parallel worker waits for the same transaction
+$node_subscriber->wait_for_log(qr/wait for depended xid $xid/, $offset);
+
+# Wakeup the parallel worker. We detach first no to stop other parallel workers
+$node_subscriber->safe_psql('postgres', qq[
+ SELECT injection_points_detach('parallel-worker-before-commit');
+ SELECT injection_points_wakeup('parallel-worker-before-commit');
+]);
+
+# Verify the parallel worker wakes up
+$node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset);
+
+$result =
+ $node_subscriber->safe_psql('postgres', "SELECT count(1) FROM regress_tab");
+is ($result, 50, 'inserts are replicated to subscriber');
+
+$result =
+ $node_subscriber->safe_psql('postgres',
+ "SELECT count(1) FROM regress_tab WHERE value = 'updated'");
+is ($result, 5, 'updates are also replicated to subscriber');
+
+##################################################
+# Test that the dependency tracking works correctly for unchanged toasted RI
+# columns.
+##################################################
+
+# Attach an injection_point. Parallel workers would wait before the commit
+$node_subscriber->safe_psql('postgres',
+ "SELECT injection_points_attach('parallel-worker-before-commit','wait');"
+);
+
+# Update one replica identity column but keep toasted column unchanged
+$node_publisher->safe_psql('postgres',
+ "UPDATE tab_toast SET b = '1';");
+
+# Wait until the parallel worker enters the injection point.
+$node_subscriber->wait_for_event('logical replication parallel worker',
+ 'parallel-worker-before-commit');
+
+# Delete the updated row.
+$node_publisher->safe_psql('postgres',
+ "DELETE FROM tab_toast WHERE b = '1';");
+
+# Verify the dependency is detected for the delete
+$str = $node_subscriber->wait_for_log(qr/found conflicting replica identity change from ([1-9][0-9]+)/, $offset);
+$xid = $str =~ /found conflicting replica identity change from ([1-9][0-9]+)/;
+
+# Verify the parallel worker waits for the same transaction
+$node_subscriber->wait_for_log(qr/wait for depended xid $xid/, $offset);
+
+# Wakeup the parallel worker. We detach first no to stop other parallel workers
+$node_subscriber->safe_psql('postgres', qq[
+ SELECT injection_points_detach('parallel-worker-before-commit');
+ SELECT injection_points_wakeup('parallel-worker-before-commit');
+]);
+
+# Verify the parallel worker wakes up
+$node_subscriber->wait_for_log(qr/finish waiting for depended xid $xid/, $offset);
+
+$result =
+ $node_subscriber->safe_psql('postgres', "SELECT count(1) FROM tab_toast");
+is ($result, 0, 'changes are replicated to subscriber');
+
+done_testing();
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 07d246bd957..db8bb4e1e43 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2162,6 +2162,7 @@ ParallelHashGrowth
ParallelHashJoinBatch
ParallelHashJoinBatchAccessor
ParallelHashJoinState
+ParallelizedTxnEntry
ParallelIndexScanDesc
ParallelizedTxnEntry
ParallelSlot
@@ -4257,6 +4258,7 @@ rendezvousHashEntry
rep
replace_rte_variables_callback
replace_rte_variables_context
+replica_identity_hash
report_error_fn
ret_type
rewind_source
--
2.43.0
[application/octet-stream] v19-0002-Introduce-internal-messages-to-track-dependencie.patch (12.7K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/10-v19-0002-Introduce-internal-messages-to-track-dependencie.patch)
download | inline diff:
From baaa11fcd78973709c41c898ad22484d09ab4718 Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Wed, 29 Apr 2026 16:41:44 +0800
Subject: [PATCH v19 2/3] Introduce internal messages to track dependencies
This patch introduces a new set of internal worker message types (see
PAWorkerMsgType). These types of messages are generated by a leader worker
and sent to parallel apply workers based on the needs. For now, two types of
messages exist: PA_MSG_XACT_DEPENDENCY and PA_MSG_RELMAP.
PA_MSG_XACT_DEPENDENCY ensures that dependent transactions are
committed in the correct order. It has a list of transaction IDs that parallel
workers must wait for. This type of message is generated when the leader
detects a dependency between the current and other transactions, or just before
the COMMIT message. The latter one is used to preserve the commit ordering
between the publisher and the subscriber.
PA_MSG_RELMAP is used to synchronize the remote relation
information between the leader and parallel workers. It has a list of relations
that the leader already knows, and parallel workers also update the relmap in
response to the message. This type of message is generated when the leader
allocates a new parallel worker to the transaction, or when the publisher sends
additional RELATION messages. This synchronization is necessary for parallel
apply workers to map local replication target relations to their remote
counterparts during change application. Since the walsender does not send remote
relation information with every transaction, the parallel apply worker may not
have up-to-date relation info unless synchronized by the leader.
In the logical replication protocol, the above messages are encapsulated within
the LOGICAL_REP_MSG_INTERNAL_MESSAGE type. Later patches will use a uniform
format (LOGICAL_REP_MSG_INTERNAL_MESSAGE + PAWorkerMsgType + internal data) for
sending to parallel apply workers or serializing to disk.
Author: Zhijie Hou <[email protected]>
Author: Hayato Kuroda <[email protected]>
---
.../replication/logical/applyparallelworker.c | 187 ++++++++++++++++--
src/backend/replication/logical/proto.c | 2 +
src/backend/replication/logical/worker.c | 4 +
src/include/replication/logicalproto.h | 8 +
src/include/replication/worker_internal.h | 17 ++
src/tools/pgindent/typedefs.list | 1 +
6 files changed, 202 insertions(+), 17 deletions(-)
diff --git a/src/backend/replication/logical/applyparallelworker.c b/src/backend/replication/logical/applyparallelworker.c
index 109d85c7cdf..5f622bbe558 100644
--- a/src/backend/replication/logical/applyparallelworker.c
+++ b/src/backend/replication/logical/applyparallelworker.c
@@ -772,6 +772,73 @@ ProcessParallelApplyInterrupts(void)
}
}
+/*
+ * Handle internal dependency information.
+ *
+ * Wait for all transactions listed in the message to commit.
+ */
+static void
+apply_handle_internal_dependency(StringInfo s)
+{
+ int nxids = pq_getmsgint(s, 4);
+
+ for (int i = 0; i < nxids; i++)
+ {
+ TransactionId xid = pq_getmsgint(s, 4);
+
+ pa_wait_for_depended_transaction(xid);
+ }
+}
+
+/*
+ * Handle internal relation information.
+ *
+ * Update all relation details in the relation map cache.
+ */
+static void
+apply_handle_internal_relation(StringInfo s)
+{
+ int nrels = pq_getmsgint(s, 4);
+
+ for (int i = 0; i < nrels; i++)
+ {
+ LogicalRepRelation *rel = logicalrep_read_rel(s);
+
+ logicalrep_relmap_update(rel);
+
+ /* Also reset all entries in the partition map that refer to remoterel. */
+ logicalrep_partmap_reset_relmap(rel);
+
+ elog(DEBUG1, "parallel apply worker init relmap for %s",
+ rel->relname);
+ }
+}
+
+/*
+ * Handle an internal message generated by the leader apply worker.
+ */
+void
+apply_handle_internal_message(StringInfo s)
+{
+ PAWorkerMsgType action = pq_getmsgbyte(s);
+
+ Assert(am_parallel_apply_worker());
+
+ switch (action)
+ {
+ case PA_MSG_XACT_DEPENDENCY:
+ apply_handle_internal_dependency(s);
+ break;
+ case PA_MSG_RELMAP:
+ apply_handle_internal_relation(s);
+ break;
+ default:
+ ereport(ERROR,
+ (errcode(ERRCODE_PROTOCOL_VIOLATION),
+ errmsg("invalid worker internal message type \"??? (%d)\"", action)));
+ }
+}
+
/* Parallel apply worker main loop. */
static void
LogicalParallelApplyLoop(shm_mq_handle *mqh)
@@ -780,6 +847,14 @@ LogicalParallelApplyLoop(shm_mq_handle *mqh)
ErrorContextCallback errcallback;
MemoryContext oldcxt = CurrentMemoryContext;
+ /*
+ * Ensure LOGICAL_REP_MSG_INTERNAL_MESSAGE does not conflict with
+ * PqReplMsg_WALData ('d'), as parallel apply workers may receive both types
+ * of messages.
+ */
+ StaticAssertDecl(LOGICAL_REP_MSG_INTERNAL_MESSAGE != PqReplMsg_WALData,
+ "LOGICAL_REP_MSG_INTERNAL_MESSAGE conflicts with PqReplMsg_WALData");
+
/*
* Init the ApplyMessageContext which we clean up after each replication
* protocol message.
@@ -818,26 +893,46 @@ LogicalParallelApplyLoop(shm_mq_handle *mqh)
initReadOnlyStringInfo(&s, data, len);
- /*
- * The first byte of messages sent from leader apply worker to
- * parallel apply workers can only be PqReplMsg_WALData.
- */
c = pq_getmsgbyte(&s);
- if (c != PqReplMsg_WALData)
- elog(ERROR, "unexpected message \"%c\"", c);
- /*
- * Ignore statistics fields that have been updated by the leader
- * apply worker.
- *
- * XXX We can avoid sending the statistics fields from the leader
- * apply worker but for that, it needs to rebuild the entire
- * message by removing these fields which could be more work than
- * simply ignoring these fields in the parallel apply worker.
- */
- s.cursor += SIZE_STATS_MESSAGE;
+ if (c == PqReplMsg_WALData)
+ {
+ /*
+ * Ignore statistics fields that have been updated by the
+ * leader apply worker.
+ *
+ * XXX We can avoid sending the statistics fields from the
+ * leader apply worker but for that, it needs to rebuild the
+ * entire message by removing these fields which could be more
+ * work than simply ignoring these fields in the parallel apply
+ * worker.
+ */
+ s.cursor += SIZE_STATS_MESSAGE;
+
+ apply_dispatch(&s);
+ }
+ else if (c == LOGICAL_REP_MSG_INTERNAL_MESSAGE)
+ {
+ /*
+ * Rewind the cursor so that apply_dispatch can re-read the
+ * first byte (LOGICAL_REP_MSG_INTERNAL_MESSAGE) to correctly
+ * handle the internal message. Alternatively, we could call
+ * apply_handle_internal_message directly, but using
+ * apply_dispatch uniformly across all message types is cleaner
+ * and more consistent.
+ */
+ s.cursor--;
- apply_dispatch(&s);
+ apply_dispatch(&s);
+ }
+ else
+ {
+ /*
+ * The first byte of messages sent from leader apply worker to
+ * parallel apply workers can only be 'w' or 'i'.
+ */
+ elog(ERROR, "unexpected message \"%c\"", c);
+ }
}
else if (shmq_res == SHM_MQ_WOULD_BLOCK)
{
@@ -1744,3 +1839,61 @@ pa_attach_parallelized_txn_hash(dsa_handle *pa_dsa_handle,
MemoryContextSwitchTo(oldctx);
}
+
+/*
+ * Wait for the given remote transaction to finish applying by a parallel apply
+ * worker.
+ *
+ * Both leader and parallel apply workers can call this function to wait for a
+ * parallelized transaction to finish.
+ */
+void
+pa_wait_for_depended_transaction(TransactionId xid)
+{
+ ParallelizedTxnEntry *txn_entry;
+
+ /*
+ * Quick exit if parallelized_txns has not been initialized yet. This can
+ * happen when the leader worker calls this function before any parallel
+ * apply workers have been launched.
+ */
+ if (!parallelized_txns)
+ return;
+
+ elog(DEBUG1, "wait for depended xid %u", xid);
+
+ for (;;)
+ {
+ txn_entry = dshash_find(parallelized_txns, &xid, false);
+
+ /* The entry is removed only if the transaction is committed */
+ if (txn_entry == NULL)
+ break;
+
+ dshash_release_lock(parallelized_txns, txn_entry);
+
+ /*
+ * Wait for the parallel apply worker processing the given remote
+ * transaction to finish applying and release its lock.
+ */
+ pa_lock_transaction(xid, AccessShareLock);
+ pa_unlock_transaction(xid, AccessShareLock);
+
+ CHECK_FOR_INTERRUPTS();
+
+ /*
+ * Acquiring the lock successfully does not guarantee we can proceed.
+ * The worker may have errored out and released the lock while leaving
+ * its shared hash entry intact, or it may not have acquired the lock
+ * yet because it hasn't processed the BEGIN message. In either case, we
+ * must continue waiting in the loop until the parallel apply worker
+ * finishes applying the transaction, or until the leader notifies us of
+ * a failure and restarts all workers.
+ *
+ * The above race window is small and infrequent, so no WaitLatch is
+ * added.
+ */
+ }
+
+ elog(DEBUG1, "finish waiting for depended xid %u", xid);
+}
diff --git a/src/backend/replication/logical/proto.c b/src/backend/replication/logical/proto.c
index 86ad97cd937..a0cac05cdcd 100644
--- a/src/backend/replication/logical/proto.c
+++ b/src/backend/replication/logical/proto.c
@@ -1253,6 +1253,8 @@ logicalrep_message_type(LogicalRepMsgType action)
return "STREAM ABORT";
case LOGICAL_REP_MSG_STREAM_PREPARE:
return "STREAM PREPARE";
+ case LOGICAL_REP_MSG_INTERNAL_MESSAGE:
+ return "INTERNAL MESSAGE";
}
/*
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index a3f2406ed83..6599d563306 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -3890,6 +3890,10 @@ apply_dispatch(StringInfo s)
apply_handle_stream_prepare(s);
break;
+ case LOGICAL_REP_MSG_INTERNAL_MESSAGE:
+ apply_handle_internal_message(s);
+ break;
+
default:
ereport(ERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
diff --git a/src/include/replication/logicalproto.h b/src/include/replication/logicalproto.h
index 058a955e20c..cb0a8f440c0 100644
--- a/src/include/replication/logicalproto.h
+++ b/src/include/replication/logicalproto.h
@@ -53,6 +53,13 @@
* in logical replication protocol, which uses a single byte to identify a
* message type. Hence the values should be single-byte wide and preferably
* human-readable characters.
+ *
+ * LOGICAL_REP_MSG_INTERNAL_MESSAGE ('i') is reserved for internal messages (see
+ * PAWorkerMsgType for sub-message types) sent from the leader apply
+ * worker to parallel apply workers. Centralizing this definition here allows
+ * all message types to be handled together and avoids the maintenance burden of
+ * ensuring sub-message types do not conflict with regular LogicalRepMsgType
+ * values.
*/
typedef enum LogicalRepMsgType
{
@@ -75,6 +82,7 @@ typedef enum LogicalRepMsgType
LOGICAL_REP_MSG_STREAM_COMMIT = 'c',
LOGICAL_REP_MSG_STREAM_ABORT = 'A',
LOGICAL_REP_MSG_STREAM_PREPARE = 'p',
+ LOGICAL_REP_MSG_INTERNAL_MESSAGE = 'i',
} LogicalRepMsgType;
/*
diff --git a/src/include/replication/worker_internal.h b/src/include/replication/worker_internal.h
index e60e0c3d6d7..43dcae43a62 100644
--- a/src/include/replication/worker_internal.h
+++ b/src/include/replication/worker_internal.h
@@ -242,6 +242,19 @@ typedef struct ParallelApplyWorkerInfo
ParallelApplyWorkerShared *shared;
} ParallelApplyWorkerInfo;
+/*
+ * Parallel apply worker internal message types.
+ *
+ * These types of messages are generated by the leader apply worker and sent to
+ * the parallel apply worker, encapsulated within the
+ * LOGICAL_REP_MSG_INTERNAL_MESSAGE type.
+ */
+typedef enum PAWorkerMsgType
+{
+ PA_MSG_XACT_DEPENDENCY = 'd',
+ PA_MSG_RELMAP = 'r',
+} PAWorkerMsgType;
+
/* Main memory context for apply worker. Permanent during worker lifetime. */
extern PGDLLIMPORT MemoryContext ApplyContext;
@@ -341,6 +354,8 @@ extern void pa_allocate_worker(TransactionId xid);
extern ParallelApplyWorkerInfo *pa_find_worker(TransactionId xid);
extern void pa_detach_all_error_mq(void);
+extern void apply_handle_internal_message(StringInfo s);
+
extern bool pa_send_data(ParallelApplyWorkerInfo *winfo, Size nbytes,
const void *data);
extern void pa_switch_to_partial_serialize(ParallelApplyWorkerInfo *winfo,
@@ -368,6 +383,8 @@ extern void pa_decr_and_wait_stream_block(void);
extern void pa_xact_finish(ParallelApplyWorkerInfo *winfo,
XLogRecPtr remote_lsn);
+extern void pa_wait_for_depended_transaction(TransactionId xid);
+
#define isParallelApplyWorker(worker) ((worker)->in_use && \
(worker)->type == WORKERTYPE_PARALLEL_APPLY)
#define isTableSyncWorker(worker) ((worker)->in_use && \
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index fabda17d739..c00c34652fe 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1926,6 +1926,7 @@ OverridingKind
PACE_HEADER
PACL
PATH
+PAWorkerMsgType
PCtxtHandle
PERL_CONTEXT
PERL_SI
--
2.43.0
[application/octet-stream] v19-0003-Introduce-a-local-hash-table-to-store-replica-id.patch (34.7K, ../TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com/11-v19-0003-Introduce-a-local-hash-table-to-store-replica-id.patch)
download | inline diff:
From 7288605c496764047ce0fc550ddd32c28bd4a08d Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Thu, 30 Apr 2026 13:28:40 +0800
Subject: [PATCH v19 3/3] Introduce a local hash table to store replica
identities
This local hash table on the leader is used for detecting dependencies between
transactions.
The hash contains the Replica Identity (RI) as a key and the remote XID that
modified the corresponding tuple. The hash entries are inserted when the leader
finds an RI from a replication message, and are removed in the
following cases:
1) When handling a subsequent change that modifies the same row, and the
stored transaction has already committed.
2) When collecting flush progress of remote transactions, and the stored
transaction is found to have committed.
3) When the number of entries exceeds REPLICA_IDENTITY_CLEANUP_THRESHOLD
and the stored transaction has already committed.
When the leader sends replication changes to parallel workers, it checks whether
aother transaction has already used the RI associated with the change. If so,
the leader marks the current transaction as dependent on that transaction and
notifies parallel workers via PA_MSG_XACT_DEPENDENCY to wait for that
transaction to finish.
Author: Zhijie Hou <[email protected]>
Author: Hayato Kuroda <[email protected]>
---
.../replication/logical/applyparallelworker.c | 131 +++-
src/backend/replication/logical/relation.c | 24 +
src/backend/replication/logical/worker.c | 688 +++++++++++++++++-
src/include/replication/logicalrelation.h | 9 +
src/include/replication/worker_internal.h | 6 +-
src/test/subscription/meson.build | 1 +
src/tools/pgindent/typedefs.list | 3 +
7 files changed, 857 insertions(+), 5 deletions(-)
diff --git a/src/backend/replication/logical/applyparallelworker.c b/src/backend/replication/logical/applyparallelworker.c
index 5f622bbe558..ff4d6028ddc 100644
--- a/src/backend/replication/logical/applyparallelworker.c
+++ b/src/backend/replication/logical/applyparallelworker.c
@@ -213,12 +213,32 @@
#define PARALLEL_APPLY_LOCK_XACT 1
/*
- * Hash table entry to map xid to the parallel apply worker state.
+ * Hash table entry of ParallelApplyTxnHash to map xid to the parallel apply
+ * worker state.
*/
typedef struct ParallelApplyWorkerEntry
{
- TransactionId xid; /* Hash key -- must be first */
+ TransactionId xid; /* Remote transaction ID (hash key) ---
+ * must be first */
+
+ /*
+ * The parallel apply worker assigned for applying the transaction. It is
+ * NULL if the worker has already finished the transaction and the leader
+ * has collected its local end LSN.
+ */
ParallelApplyWorkerInfo *winfo;
+
+ /*
+ * The local end LSN of this transaction applied by the parallel apply
+ * worker.
+ *
+ * The leader will initialize this value by reading the last_commit_end from
+ * the parallel apply worker shared memory before reusing the worker for
+ * another transaction (see pa_get_last_commit_end). An invalid value
+ * indicates the worker has not finished applying the transaction or there
+ * is no change applied by the worker for this transaction.
+ */
+ XLogRecPtr local_end;
} ParallelApplyWorkerEntry;
/* An entry in the parallelized_txns shared hash table */
@@ -230,6 +250,10 @@ typedef struct ParallelizedTxnEntry
/*
* A hash table used to cache the state of streaming transactions being applied
* by the parallel apply workers. Entries are of type ParallelApplyWorkerEntry.
+ *
+ * The leader apply worker adds an entry when a transaction starts being
+ * applied, and removes it after collecting the transaction's local end LSN from
+ * the parallel worker.
*/
static HTAB *ParallelApplyTxnHash = NULL;
@@ -237,6 +261,10 @@ static HTAB *ParallelApplyTxnHash = NULL;
* A hash table used to track the parallelized remote transactions that could be
* depended on by other transactions. Entries are of type ParallelizedTxnEntry.
*
+ * The leader apply worker adds an entry before sending the COMMIT record of a
+ * transaction to a parallel apply worker. The entry is removed by that worker
+ * immediately after committing the transaction.
+ *
* dshash is used to enable dynamic shared memory allocation based on the number
* of transactions being applied in parallel.
*/
@@ -510,7 +538,7 @@ pa_launch_parallel_worker(void)
* streaming changes.
*/
void
-pa_allocate_worker(TransactionId xid)
+pa_allocate_worker(TransactionId xid, bool stream_txn)
{
bool found;
ParallelApplyWorkerInfo *winfo = NULL;
@@ -551,7 +579,9 @@ pa_allocate_worker(TransactionId xid)
winfo->in_use = true;
winfo->serialize_changes = false;
+ winfo->stream_txn = stream_txn;
entry->winfo = winfo;
+ entry->local_end = InvalidXLogRecPtr;
}
/*
@@ -748,6 +778,72 @@ pa_process_spooled_messages_if_required(void)
return true;
}
+/*
+ * Get the local end LSN for a transaction applied by a parallel apply worker.
+ *
+ * If the parallel apply worker did not write any changes during the transaction
+ * application due to situations like update/delete_missing or a before trigger,
+ * the *skipped_write will be set to true.
+ *
+ * Once the LSN is retrieved, the transaction entry is removed from
+ * ParallelApplyTxnHash.
+ */
+XLogRecPtr
+pa_get_last_commit_end(TransactionId xid, bool *skipped_write)
+{
+ bool found;
+ ParallelApplyWorkerEntry *entry;
+ ParallelApplyWorkerInfo *winfo;
+
+ Assert(TransactionIdIsValid(xid));
+ Assert(ParallelApplyTxnHash);
+
+ if (skipped_write)
+ *skipped_write = false;
+
+ /* Find an entry for the requested transaction. */
+ entry = hash_search(ParallelApplyTxnHash, &xid, HASH_FIND, &found);
+
+ if (!found)
+ return InvalidXLogRecPtr;
+
+ /*
+ * If worker info is NULL, it indicates that the worker has already
+ * finished handling the transaction. Consequently, the local end LSN has
+ * already been collected and saved in entry->local_end.
+ */
+ winfo = entry->winfo;
+ if (winfo == NULL)
+ {
+ if (!hash_search(ParallelApplyTxnHash, &xid, HASH_REMOVE, NULL))
+ elog(ERROR, "hash table corrupted");
+
+ if (skipped_write)
+ *skipped_write = XLogRecPtrIsInvalid(entry->local_end);
+
+ return entry->local_end;
+ }
+
+ /* Return InvalidXLogRecPtr if the transaction is still in progress */
+ if (pa_get_xact_state(winfo->shared) != PARALLEL_TRANS_FINISHED)
+ return InvalidXLogRecPtr;
+
+ /* Collect the local end LSN from the worker's shared memory area */
+ entry->local_end = winfo->shared->last_commit_end;
+ entry->winfo = NULL;
+
+ if (skipped_write)
+ *skipped_write = XLogRecPtrIsInvalid(entry->local_end);
+
+ elog(DEBUG1, "store local commit %X/%X end to txn entry: %u",
+ LSN_FORMAT_ARGS(entry->local_end), xid);
+
+ if (!hash_search(ParallelApplyTxnHash, &xid, HASH_REMOVE, NULL))
+ elog(ERROR, "hash table corrupted");
+
+ return entry->local_end;
+}
+
/*
* Interrupt handler for main loop of parallel apply worker.
*/
@@ -1795,6 +1891,35 @@ pa_xact_finish(ParallelApplyWorkerInfo *winfo, XLogRecPtr remote_lsn)
pa_free_worker(winfo);
}
+/*
+ * Check if the given transaction has been committed. This can only be used by
+ * the leader apply worker.
+ *
+ * Returns true if the transaction is committed, false if it is still being
+ * applied in parallel.
+ */
+bool
+pa_transaction_committed(TransactionId xid)
+{
+ bool found;
+ ParallelApplyWorkerEntry *entry;
+
+ Assert(am_leader_apply_worker());
+ Assert(TransactionIdIsValid(xid));
+ Assert(ParallelApplyTxnHash);
+
+ /* Find an entry for the requested transaction */
+ entry = hash_search(ParallelApplyTxnHash, &xid, HASH_FIND, &found);
+
+ if (!found)
+ return true;
+
+ if (!entry->winfo)
+ return true;
+
+ return pa_get_xact_state(entry->winfo->shared) == PARALLEL_TRANS_FINISHED;
+}
+
/*
* Attach to the shared hash table for parallelized transactions.
*/
diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index 0b1d80b5b0f..ab6313eb1bc 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -960,3 +960,27 @@ FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
return InvalidOid;
}
+
+/*
+ * Get the LogicalRepRelMapEntry corresponding to the given relid without
+ * opening the local relation.
+ */
+LogicalRepRelMapEntry *
+logicalrep_get_relentry(LogicalRepRelId remoteid)
+{
+ LogicalRepRelMapEntry *entry;
+ bool found;
+
+ if (LogicalRepRelMap == NULL)
+ logicalrep_relmap_init();
+
+ /* Search for existing entry. */
+ entry = hash_search(LogicalRepRelMap, (void *) &remoteid,
+ HASH_FIND, &found);
+
+ if (!found)
+ elog(DEBUG1, "no relation map entry for remote relation ID %u",
+ remoteid);
+
+ return entry;
+}
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index 6599d563306..eea870ca282 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -303,11 +303,35 @@
#define NAPTIME_PER_CYCLE 1000 /* max sleep time between cycles (1s) */
+/*
+ * Struct for tracking the progress of flushing the transaction received from
+ * the publisher.
+ *
+ * A list of these structs (lsn_mapping) is maintained in the apply worker, each
+ * representing a transaction that is being flushed. The entries are removed
+ * from the list when the transaction is fully flushed (see get_flush_position).
+ */
typedef struct FlushPosition
{
dlist_node node;
+
+ /*
+ * The end of commit record applied by the worker, and the corresponding end
+ * of commit record on the publisher.
+ *
+ * For transactions assigned to a parallel apply worker, the local_end is
+ * not immediately available. The leader will update the local_end when it
+ * confirms that the parallel apply worker has finished applying the
+ * transaction (see the usage of pa_get_last_commit_end).
+ */
XLogRecPtr local_end;
XLogRecPtr remote_end;
+
+ /*
+ * The remote transaction ID. This should be set to a valid ID only when the
+ * transaction is assigned to a parallel apply worker.
+ */
+ TransactionId pa_remote_xid;
} FlushPosition;
static dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping);
@@ -476,6 +500,8 @@ ErrorContextCallback *apply_error_context_stack = NULL;
MemoryContext ApplyMessageContext = NULL;
MemoryContext ApplyContext = NULL;
+static MemoryContext ParallelApplyContext = NULL;
+
/* per stream context for streaming transactions */
static MemoryContext LogicalStreamingContext = NULL;
@@ -549,6 +575,65 @@ typedef struct ApplySubXactData
static ApplySubXactData subxact_data = {0, 0, InvalidTransactionId, NULL};
+/* Hash table key for replica_identity_table */
+typedef struct ReplicaIdentityKey
+{
+ Oid relid;
+ LogicalRepTupleData *data;
+} ReplicaIdentityKey;
+
+/* Hash table entry in replica_identity_table */
+typedef struct ReplicaIdentityEntry
+{
+ ReplicaIdentityKey *keydata;
+ TransactionId remote_xid;
+
+ /* needed for simplehash */
+ uint32 hash;
+ char status;
+} ReplicaIdentityEntry;
+
+#include "common/hashfn.h"
+
+static uint32 hash_replica_identity(ReplicaIdentityKey *key);
+static bool hash_replica_identity_compare(ReplicaIdentityKey *a,
+ ReplicaIdentityKey *b);
+
+/* Define parameters for replica identity hash table code generation. */
+#define SH_PREFIX replica_identity
+#define SH_ELEMENT_TYPE ReplicaIdentityEntry
+#define SH_KEY_TYPE ReplicaIdentityKey *
+#define SH_KEY keydata
+#define SH_HASH_KEY(tb, key) hash_replica_identity(key)
+#define SH_EQUAL(tb, a, b) hash_replica_identity_compare(a, b)
+#define SH_STORE_HASH
+#define SH_GET_HASH(tb, a) (a)->hash
+#define SH_SCOPE static inline
+#define SH_DECLARE
+#define SH_DEFINE
+#include "lib/simplehash.h"
+
+#define REPLICA_IDENTITY_INITIAL_SIZE 128
+#define REPLICA_IDENTITY_CLEANUP_THRESHOLD 1024
+
+/*
+ * Hash table storing replica identity values for changes being applied in
+ * parallel, along with the latest transaction that modified each row.
+ *
+ * Entries are removed in the following cases:
+ *
+ * 1) When handling a subsequent change that modifies the same row, and the
+ * stored transaction has already committed.
+ * 2) When collecting flush progress of remote transactions, and the stored
+ * transaction is found to have committed.
+ * 3) When the number of entries exceeds REPLICA_IDENTITY_CLEANUP_THRESHOLD
+ * and the stored transaction has already committed.
+ *
+ * We use simplehash for its efficiency (see comments atop of simplehash.h), as
+ * this hash table is accessed for every change in a transaction.
+ */
+static replica_identity_hash *replica_identity_table = NULL;
+
static inline void subxact_filename(char *path, Oid subid, TransactionId xid);
static inline void changes_filename(char *path, Oid subid, TransactionId xid);
@@ -636,6 +721,580 @@ static void set_wal_receiver_timeout(void);
static void on_exit_clear_xact_state(int code, Datum arg);
+static void send_internal_dependencies(ParallelApplyWorkerInfo *winfo,
+ List *depends_on_xids);
+
+/*
+ * Compute the hash value for entries in the replica_identity_table.
+ */
+static uint32
+hash_replica_identity(ReplicaIdentityKey *key)
+{
+ int i;
+ uint32 hashkey = 0;
+
+ hashkey = hash_combine(hashkey, hash_uint32(key->relid));
+
+ for (i = 0; i < key->data->ncols; i++)
+ {
+ uint32 hkey;
+
+ if (key->data->colstatus[i] == LOGICALREP_COLUMN_NULL)
+ continue;
+
+ hkey = hash_any((const unsigned char *) key->data->colvalues[i].data,
+ key->data->colvalues[i].len);
+ hashkey = hash_combine(hashkey, hkey);
+ }
+
+ return hashkey;
+}
+
+/*
+ * Compare two entries in the replica_identity_table.
+ */
+static bool
+hash_replica_identity_compare(ReplicaIdentityKey *a, ReplicaIdentityKey *b)
+{
+ if (a->relid != b->relid ||
+ a->data->ncols != b->data->ncols)
+ return false;
+
+ for (int i = 0; i < a->data->ncols; i++)
+ {
+ if (a->data->colstatus[i] != b->data->colstatus[i])
+ return false;
+
+ if (a->data->colvalues[i].len != b->data->colvalues[i].len)
+ return false;
+
+ if (strcmp(a->data->colvalues[i].data, b->data->colvalues[i].data))
+ return false;
+
+ elog(DEBUG1, "conflicting key %s", a->data->colvalues[i].data);
+ }
+
+ return true;
+}
+
+/*
+ * Free resources associated with a replica identity key.
+ */
+static void
+free_replica_identity_key(ReplicaIdentityKey *key)
+{
+ Assert(key);
+
+ pfree(key->data->colvalues);
+ pfree(key->data->colstatus);
+ pfree(key->data);
+ pfree(key);
+}
+
+/*
+ * Clean up hash table entries associated with the given transaction IDs.
+ */
+static void
+delete_replica_identity_entries_for_txns(List *committed_xids)
+{
+ replica_identity_iterator i;
+ ReplicaIdentityEntry *rientry;
+
+ if (!committed_xids)
+ return;
+
+ replica_identity_start_iterate(replica_identity_table, &i);
+ while ((rientry = replica_identity_iterate(replica_identity_table, &i)) != NULL)
+ {
+ if (!list_member_xid(committed_xids, rientry->remote_xid))
+ continue;
+
+ /* Clean up the hash entry for committed transaction */
+ free_replica_identity_key(rientry->keydata);
+ replica_identity_delete_item(replica_identity_table, rientry);
+ }
+}
+
+/*
+ * Check committed transactions and clean up corresponding entries in the hash
+ * table.
+ *
+ * Also update the local_end for transactions assigned to parallel apply workers
+ * if not already set.
+ */
+static void
+cleanup_committed_replica_identity_entries(void)
+{
+ dlist_mutable_iter iter;
+ List *committed_xids = NIL;
+
+ dlist_foreach_modify(iter, &lsn_mapping)
+ {
+ FlushPosition *pos =
+ dlist_container(FlushPosition, node, iter.cur);
+ bool skipped_write;
+
+ /*
+ * Skip if the transaction was not assigned to a parallel worker, or if
+ * we have already collected its local end LSN.
+ */
+ if (!TransactionIdIsValid(pos->pa_remote_xid) ||
+ XLogRecPtrIsValid(pos->local_end))
+ continue;
+
+ pos->local_end = pa_get_last_commit_end(pos->pa_remote_xid,
+ &skipped_write);
+
+ elog(DEBUG1,
+ "got commit end from parallel apply worker, "
+ "txn: %u, remote_end %X/%X, local_end %X/%X",
+ pos->pa_remote_xid, LSN_FORMAT_ARGS(pos->remote_end),
+ LSN_FORMAT_ARGS(pos->local_end));
+
+ /* Skip if the transaction is still being applied */
+ if (!skipped_write && !XLogRecPtrIsValid(pos->local_end))
+ continue;
+
+ committed_xids = lappend_xid(committed_xids, pos->pa_remote_xid);
+ }
+
+ /* cleanup the entries for committed transactions */
+ delete_replica_identity_entries_for_txns(committed_xids);
+}
+
+/*
+ * Append the given transaction ID to the dependency list if it is not already
+ * present.
+ *
+ * If the transaction has already committed, the ID is reset to
+ * InvalidTransactionId and nothing is appended.
+ */
+static void
+check_and_append_xid_dependency(TransactionId *xid, List **depends_on_xids)
+{
+ Assert(xid && TransactionIdIsValid(*xid));
+
+ if (list_member_xid(*depends_on_xids, *xid))
+ return;
+
+ /*
+ * Return and reset the xid if the transaction has been committed.
+ */
+ if (pa_transaction_committed(*xid))
+ {
+ *xid = InvalidTransactionId;
+ return;
+ }
+
+ *depends_on_xids = lappend_xid(*depends_on_xids, *xid);
+}
+
+/*
+ * Check for dependencies on preceding transactions that modify the same key.
+ * Returns the dependent transactions in 'depends_on_xids'.
+ *
+ * Additionally, if new_depended_xid is valid, record it as a dependency for the
+ * replica identity key modification, allowing subsequent transactions that
+ * modify the same key to be dependent on it.
+ */
+static void
+check_and_record_ri_dependency(Oid relid, LogicalRepTupleData *original_data,
+ TransactionId new_depended_xid,
+ List **depends_on_xids)
+{
+ LogicalRepRelMapEntry *relentry;
+ LogicalRepTupleData *ridata;
+ ReplicaIdentityKey *rikey;
+ ReplicaIdentityEntry *rientry;
+ MemoryContext oldctx;
+ int n_ri;
+ bool found = false;
+
+ Assert(depends_on_xids);
+
+ /* Search for existing entry */
+ relentry = logicalrep_get_relentry(relid);
+
+ Assert(relentry);
+
+ /*
+ * First check whether any previous transaction (other than the current one)
+ * has affected the whole table e.g., truncate or schema change from
+ * publisher.
+ */
+ if (TransactionIdIsValid(relentry->last_depended_xid) &&
+ !TransactionIdEquals(relentry->last_depended_xid, new_depended_xid))
+ check_and_append_xid_dependency(&relentry->last_depended_xid, depends_on_xids);
+
+ n_ri = bms_num_members(relentry->remoterel.attkeys);
+
+ /*
+ * Return if there are no replica identity columns, indicating that the
+ * remote relation has neither a replica identity key nor is marked as
+ * replica identity full.
+ */
+ if (!n_ri)
+ return;
+
+ /* Check if the RI key value of the tuple is invalid */
+ for (int i = 0; i < original_data->ncols; i++)
+ {
+ if (!bms_is_member(i, relentry->remoterel.attkeys))
+ continue;
+
+ /*
+ * NULL in the new tuple means the replica identity key hasn't changed,
+ * so no new dependency needs to be recorded. The dependency should have
+ * been recorded when processing the old tuple.
+ */
+ if (original_data->colstatus[i] == LOGICALREP_COLUMN_NULL)
+ return;
+
+ /*
+ * LOGICALREP_COLUMN_UNCHANGED only indicates that a TOAST column in the
+ * replica identity key hasn't changed. However, other columns may have
+ * changed, so we still need to check the dependency for this column.
+ *
+ * Before calling this function, unchanged TOAST column values should
+ * have been copied from the old tuple to the new tuple. So, we should
+ * see the complete replica identity key value in original_data and
+ * correctly check the dependency.
+ */
+ Assert(original_data->colstatus[i] != LOGICALREP_COLUMN_UNCHANGED ||
+ original_data->colvalues[i].len > 0);
+ }
+
+ oldctx = MemoryContextSwitchTo(ApplyContext);
+
+ /* Allocate space for replica identity values */
+ ridata = palloc0_object(LogicalRepTupleData);
+ ridata->colvalues = palloc0_array(StringInfoData, n_ri);
+ ridata->colstatus = palloc0_array(char, n_ri);
+ ridata->ncols = n_ri;
+
+ for (int i_original = 0, i_ri = 0; i_original < original_data->ncols; i_original++)
+ {
+ StringInfo original_colvalue = &original_data->colvalues[i_original];
+
+ if (!bms_is_member(i_original, relentry->remoterel.attkeys))
+ continue;
+
+ initStringInfoExt(&ridata->colvalues[i_ri], original_colvalue->len + 1);
+ appendStringInfoString(&ridata->colvalues[i_ri], original_colvalue->data);
+ ridata->colstatus[i_ri] = original_data->colstatus[i_original];
+ i_ri++;
+ }
+
+ rikey = palloc0_object(ReplicaIdentityKey);
+ rikey->relid = relid;
+ rikey->data = ridata;
+
+ MemoryContextSwitchTo(oldctx);
+
+ /*
+ * The new xid could be invalid if the transaction will be applied by the
+ * leader itself which means all the changes will be committed before
+ * processing next transaction. In this case, we only need to check for
+ * dependencies on preceding transactions, there is no need to record a new
+ * dependency for subsequent transactions to wait on.
+ */
+ if (!TransactionIdIsValid(new_depended_xid))
+ {
+ rientry = replica_identity_lookup(replica_identity_table, rikey);
+ free_replica_identity_key(rikey);
+
+ /* No dependency detected */
+ if (!rientry)
+ return;
+
+ elog(DEBUG1, "found conflicting replica identity change from %u",
+ rientry->remote_xid);
+
+ Assert(TransactionIdIsValid(rientry->remote_xid));
+ check_and_append_xid_dependency(&rientry->remote_xid, depends_on_xids);
+
+ /*
+ * Remove the entry if the remote transaction has been committed locally
+ * and no new dependency needs to be added.
+ */
+ if (!TransactionIdIsValid(rientry->remote_xid))
+ {
+ free_replica_identity_key(rientry->keydata);
+ replica_identity_delete_item(replica_identity_table, rientry);
+ }
+
+ return;
+ }
+
+ /* Record a new dependency for subsequent transactions to wait on */
+ rientry = replica_identity_insert(replica_identity_table, rikey,
+ &found);
+
+ /*
+ * Release the key built to search the entry, if the entry already exists.
+ */
+ if (found)
+ {
+ Assert(TransactionIdIsValid(rientry->remote_xid));
+
+ elog(DEBUG1, "found conflicting replica identity change from %u",
+ rientry->remote_xid);
+
+ free_replica_identity_key(rikey);
+
+ /*
+ * Return if the current transaction was the last one to modify the
+ * key.
+ */
+ if (TransactionIdEquals(rientry->remote_xid, new_depended_xid))
+ return;
+
+ check_and_append_xid_dependency(&rientry->remote_xid, depends_on_xids);
+ }
+
+ /* Update the new depended xid into the entry */
+ rientry->remote_xid = new_depended_xid;
+}
+
+/*
+ * Check for preceding transactions (other than current one 'new_depended_xid')
+ * that involve insert, delete, or update operations on the specified table, and
+ * return them in 'depends_on_xids'.
+ */
+static void
+find_all_dependencies_on_rel(LogicalRepRelId relid, TransactionId new_depended_xid,
+ List **depends_on_xids)
+{
+ replica_identity_iterator i;
+ ReplicaIdentityEntry *rientry;
+
+ Assert(depends_on_xids);
+
+ replica_identity_start_iterate(replica_identity_table, &i);
+ while ((rientry = replica_identity_iterate(replica_identity_table, &i)) != NULL)
+ {
+ Assert(TransactionIdIsValid(rientry->remote_xid));
+
+ if (rientry->keydata->relid != relid)
+ continue;
+
+ /* Skip self-dependency */
+ if (TransactionIdEquals(rientry->remote_xid, new_depended_xid))
+ continue;
+
+ /* Clean up the hash entry for committed transaction while on it */
+ if (pa_transaction_committed(rientry->remote_xid))
+ {
+ free_replica_identity_key(rientry->keydata);
+ replica_identity_delete_item(replica_identity_table, rientry);
+
+ continue;
+ }
+
+ check_and_append_xid_dependency(&rientry->remote_xid, depends_on_xids);
+ }
+}
+
+/*
+ * Check for any preceding transactions that affect the given table and returns
+ * them in 'depends_on_xids'.
+ *
+ * Additionally, if new_depended_xid is valid, record it as a table-level
+ * dependency, allowing subsequent transactions that modify the same table to be
+ * dependent on it.
+ */
+static void
+check_and_record_rel_dependency(LogicalRepRelId relid,
+ TransactionId new_depended_xid,
+ List **depends_on_xids)
+{
+ LogicalRepRelMapEntry *relentry;
+
+ Assert(depends_on_xids);
+
+ find_all_dependencies_on_rel(relid, new_depended_xid, depends_on_xids);
+
+ /* Search for existing entry */
+ relentry = logicalrep_get_relentry(relid);
+
+ /*
+ * Return if no entry exists, or if no transaction has affected the whole
+ * table, or if the current transaction was the last one to modify it.
+ */
+ if (!relentry ||
+ !TransactionIdIsValid(relentry->last_depended_xid) ||
+ TransactionIdEquals(relentry->last_depended_xid, new_depended_xid))
+ return;
+
+ check_and_append_xid_dependency(&relentry->last_depended_xid, depends_on_xids);
+
+ if (TransactionIdIsValid(new_depended_xid))
+ relentry->last_depended_xid = new_depended_xid;
+}
+
+/*
+ * Check dependencies related to the current change by determining if the
+ * modification impacts the same row or table as another ongoing transaction. If
+ * needed, instruct parallel apply workers to wait for these preceding
+ * transactions to complete.
+ *
+ * Simultaneously, if the current change will be dispatched to a parallel apply
+ * worker (indicated by a valid new_depended_xid and a non-NULL winfo), track
+ * the dependency for the current change to ensure that subsequent transactions
+ * address this dependency.
+ */
+static void
+handle_dependency_on_change(LogicalRepMsgType action, StringInfo s,
+ TransactionId new_depended_xid,
+ ParallelApplyWorkerInfo *winfo)
+{
+ LogicalRepRelId relid;
+ LogicalRepTupleData oldtup;
+ LogicalRepTupleData newtup;
+ LogicalRepRelation *rel;
+ List *depends_on_xids = NIL;
+ List *remote_relids;
+ bool has_oldtup = false;
+ bool cascade = false;
+ bool restart_seqs = false;
+
+ /*
+ * Parse the consume data using a local copy instead of directly consuming
+ * the given remote change as the caller may also read the data from the
+ * remote message.
+ */
+ StringInfoData change = *s;
+
+ /* Only the leader checks dependencies and schedules the parallel apply */
+ if (!am_leader_apply_worker())
+ return;
+
+ if (!ParallelApplyContext)
+ {
+ Assert(!replica_identity_table);
+
+ /*
+ * Create a permanent memory context for dependency information that
+ * persists across transactions. Using a dedicated context makes memory
+ * consumption more visible and easier to track, especially when
+ * handling a large number of change entries for transactions being
+ * applied in parallel.
+ */
+ ParallelApplyContext = AllocSetContextCreate(ApplyContext,
+ "ParallelApplyContext",
+ ALLOCSET_DEFAULT_SIZES);
+
+ replica_identity_table = replica_identity_create(ParallelApplyContext,
+ REPLICA_IDENTITY_INITIAL_SIZE,
+ NULL);
+ }
+
+ if (replica_identity_table->members >= REPLICA_IDENTITY_CLEANUP_THRESHOLD)
+ cleanup_committed_replica_identity_entries();
+
+ switch (action)
+ {
+ case LOGICAL_REP_MSG_INSERT:
+ relid = logicalrep_read_insert(&change, &newtup);
+ check_and_record_ri_dependency(relid, &newtup, new_depended_xid,
+ &depends_on_xids);
+ break;
+
+ case LOGICAL_REP_MSG_UPDATE:
+ relid = logicalrep_read_update(&change, &has_oldtup, &oldtup,
+ &newtup);
+
+ if (has_oldtup)
+ {
+ check_and_record_ri_dependency(relid, &oldtup, new_depended_xid,
+ &depends_on_xids);
+
+ /*
+ * Copy unchanged column values from the old tuple to the new
+ * tuple for replica identity dependency checking. See
+ * check_and_record_ri_dependency() for details.
+ */
+ for (int i = 0; i < oldtup.ncols; i++)
+ if (newtup.colstatus[i] == LOGICALREP_COLUMN_UNCHANGED)
+ newtup.colvalues[i] = oldtup.colvalues[i];
+ }
+
+ check_and_record_ri_dependency(relid, &newtup, new_depended_xid,
+ &depends_on_xids);
+ break;
+
+ case LOGICAL_REP_MSG_DELETE:
+ relid = logicalrep_read_delete(&change, &oldtup);
+ check_and_record_ri_dependency(relid, &oldtup, new_depended_xid,
+ &depends_on_xids);
+ break;
+
+ case LOGICAL_REP_MSG_TRUNCATE:
+ remote_relids = logicalrep_read_truncate(&change, &cascade,
+ &restart_seqs);
+
+ /*
+ * Truncate affects all rows in a table, so the current
+ * transaction should wait for all preceding transactions that
+ * modified the same table.
+ */
+ foreach_int(truncated_relid, remote_relids)
+ check_and_record_rel_dependency(truncated_relid,
+ new_depended_xid,
+ &depends_on_xids);
+
+ break;
+
+ case LOGICAL_REP_MSG_RELATION:
+ rel = logicalrep_read_rel(&change);
+
+ /*
+ * The replica identity key could be changed, making existing
+ * entries in the replica identity invalid. In this case, parallel
+ * apply is not allowed on this specific table until all running
+ * transactions that modified it have finished.
+ */
+ check_and_record_rel_dependency(rel->remoteid, new_depended_xid,
+ &depends_on_xids);
+ break;
+
+ case LOGICAL_REP_MSG_TYPE:
+ case LOGICAL_REP_MSG_MESSAGE:
+
+ /*
+ * Type updates accompany relation updates, so dependencies have
+ * already been checked during relation updates. Logical messages
+ * do not conflict with any changes, so they can be ignored.
+ */
+ break;
+
+ default:
+ Assert(false);
+ break;
+ }
+
+ /* Return early if the current change has no dependencies. */
+ if (!depends_on_xids)
+ return;
+
+ /*
+ * If the leader applies the transaction itself, start waiting for
+ * transactions that the current change depends on to finish. Otherwise,
+ * instruct the parallel apply worker to wait for them.
+ */
+ if (winfo == NULL)
+ {
+ Assert(!TransactionIdIsValid(new_depended_xid));
+
+ foreach_xid(xid, depends_on_xids)
+ pa_wait_for_depended_transaction(xid);
+ }
+ else
+ {
+ send_internal_dependencies(winfo, depends_on_xids);
+ }
+}
+
/*
* Form the origin name for the subscription.
*
@@ -792,7 +1451,10 @@ handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
/* not in streaming mode */
if (apply_action == TRANS_LEADER_APPLY)
+ {
+ handle_dependency_on_change(action, s, InvalidTransactionId, winfo);
return false;
+ }
Assert(TransactionIdIsValid(stream_xid));
@@ -1244,6 +1906,29 @@ apply_handle_begin(StringInfo s)
pgstat_report_activity(STATE_RUNNING, NULL);
}
+/*
+ * Send an INTERNAL_DEPENDENCY message to a parallel apply worker.
+ */
+static void
+send_internal_dependencies(ParallelApplyWorkerInfo *winfo, List *depends_on_xids)
+{
+ StringInfoData dependencies;
+
+ initStringInfo(&dependencies);
+
+ pq_sendbyte(&dependencies, LOGICAL_REP_MSG_INTERNAL_MESSAGE);
+ pq_sendbyte(&dependencies, PA_MSG_XACT_DEPENDENCY);
+ pq_sendint32(&dependencies, list_length(depends_on_xids));
+
+ foreach_xid(xid, depends_on_xids)
+ pq_sendint32(&dependencies, xid);
+
+ if (pa_send_data(winfo, dependencies.len, dependencies.data))
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("could not send data to the logical replication parallel apply worker"));
+}
+
/*
* Handle COMMIT message.
*
@@ -1771,7 +2456,7 @@ apply_handle_stream_start(StringInfo s)
/* Try to allocate a worker for the streaming transaction. */
if (first_segment)
- pa_allocate_worker(stream_xid);
+ pa_allocate_worker(stream_xid, true);
apply_action = get_transaction_apply_action(stream_xid, &winfo);
@@ -3980,6 +4665,7 @@ store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn)
flushpos = palloc_object(FlushPosition);
flushpos->local_end = local_lsn;
flushpos->remote_end = remote_lsn;
+ flushpos->pa_remote_xid = InvalidTransactionId;
dlist_push_tail(&lsn_mapping, &flushpos->node);
MemoryContextSwitchTo(ApplyMessageContext);
diff --git a/src/include/replication/logicalrelation.h b/src/include/replication/logicalrelation.h
index efe0f9d6031..09890cef8d4 100644
--- a/src/include/replication/logicalrelation.h
+++ b/src/include/replication/logicalrelation.h
@@ -37,6 +37,14 @@ typedef struct LogicalRepRelMapEntry
/* Sync state. */
char state;
XLogRecPtr statelsn;
+
+ /*
+ * The last remote transaction that modified the relation's schema or
+ * truncated the relation. Used in dependency tracking to ensure subsequent
+ * transactions modifying the same table wait for this transaction to finish
+ * applying (see check_dependency_on_rel).
+ */
+ TransactionId last_depended_xid;
} LogicalRepRelMapEntry;
extern void logicalrep_relmap_update(LogicalRepRelation *remoterel);
@@ -50,5 +58,6 @@ extern void logicalrep_rel_close(LogicalRepRelMapEntry *rel,
LOCKMODE lockmode);
extern bool IsIndexUsableForReplicaIdentityFull(Relation idxrel, AttrMap *attrmap);
extern Oid GetRelationIdentityOrPK(Relation rel);
+extern LogicalRepRelMapEntry *logicalrep_get_relentry(LogicalRepRelId remoteid);
#endif /* LOGICALRELATION_H */
diff --git a/src/include/replication/worker_internal.h b/src/include/replication/worker_internal.h
index 43dcae43a62..3c88d9e1027 100644
--- a/src/include/replication/worker_internal.h
+++ b/src/include/replication/worker_internal.h
@@ -239,6 +239,8 @@ typedef struct ParallelApplyWorkerInfo
*/
bool in_use;
+ bool stream_txn;
+
ParallelApplyWorkerShared *shared;
} ParallelApplyWorkerInfo;
@@ -350,8 +352,9 @@ extern void apply_error_callback(void *arg);
extern void set_apply_error_context_origin(char *originname);
/* Parallel apply worker setup and interactions */
-extern void pa_allocate_worker(TransactionId xid);
+extern void pa_allocate_worker(TransactionId xid, bool stream_txn);
extern ParallelApplyWorkerInfo *pa_find_worker(TransactionId xid);
+extern XLogRecPtr pa_get_last_commit_end(TransactionId xid, bool *skipped_write);
extern void pa_detach_all_error_mq(void);
extern void apply_handle_internal_message(StringInfo s);
@@ -382,6 +385,7 @@ extern void pa_decr_and_wait_stream_block(void);
extern void pa_xact_finish(ParallelApplyWorkerInfo *winfo,
XLogRecPtr remote_lsn);
+extern bool pa_transaction_committed(TransactionId xid);
extern void pa_wait_for_depended_transaction(TransactionId xid);
diff --git a/src/test/subscription/meson.build b/src/test/subscription/meson.build
index e71e95c6297..fdc04d91f41 100644
--- a/src/test/subscription/meson.build
+++ b/src/test/subscription/meson.build
@@ -48,6 +48,7 @@ tests += {
't/036_sequences.pl',
't/037_except.pl',
't/038_walsnd_shutdown_timeout.pl',
+ 't/039_row_filter_toast_ri.pl',
't/100_bugs.pl',
],
},
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index c00c34652fe..07d246bd957 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2669,6 +2669,8 @@ ReplOriginXactState
ReplaceVarsFromTargetList_context
ReplaceVarsNoMatchOption
ReplaceWrapOption
+ReplicaIdentityEntry
+ReplicaIdentityKey
ReplicaIdentityStmt
ReplicationKind
ReplicationSlot
@@ -2680,6 +2682,7 @@ ReplicationSlotPersistentData
ReplicationState
ReplicationStateCtl
ReplicationStateOnDisk
+replica_identity_hash
ResTarget
ReservoirState
ReservoirStateData
--
2.43.0
view thread (7+ messages) latest in thread
reply
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: [email protected]
Cc: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]
Subject: RE: Parallel Apply
In-Reply-To: <TY4PR01MB17718A4AB7F564C8DB0D6F7DC94102@TY4PR01MB17718.jpnprd01.prod.outlook.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox