From e77f52dac35b1d5a7af5ae7ef604c88e52f1b5d7 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas Date: Mon, 30 Nov 2026 13:52:29 +0200 Subject: [PATCH v17 1/8] Refactor PARALLEL_MESSAGE procsignal signaling When a message is sent to a shm_mq in pq_putmessage(), the sender sends a PROCSIG_PARALLEL_MESSAGE procsignal to the receiver, to notify it of the new message. However, in case of a parallel apply worker or a repack worker, we used PROCSIG_PARALLEL_APPLY_MESSAGE or PROCSIG_REPACK_MESSAGE instead. Remove those extra procsignals, always use PROCSIG_PARALLEL_MESSAGE, and move the logic to the receiving side instead to check all different kinds of incoming messages. This deduplicates the code between ProcessParallelMessages(), ProcessParallelApplyMessages(), and ProcessRepackMessages() to set up the short-lived memory context and to hold interrupts. All three kinds of workers now share one pending flag, so if reading one kind of queue throws an error, the others were not read yet. The reader catches the error, sets the flag again, and rethrows, so that a caller that catches the error (a PL/pgSQL exception block in a trigger running in a parallel apply leader that also leads a parallel query, say) still gets the remaining messages on the next CHECK_FOR_INTERRUPTS(). With separate flags, master kept the other flags set in that case. Reviewed-by: Robert Haas Reviewed-by: Greg Burd Discussion: https://postgr.es/m/0aac2b1a-ec0f-4bb6-a786-760e6cea4d1d@iki.fi --- src/backend/access/transam/parallel.c | 68 +++++++++++++++---- src/backend/commands/repack.c | 63 ++--------------- src/backend/commands/repack_worker.c | 2 +- src/backend/libpq/pqmq.c | 22 +----- .../replication/logical/applyparallelworker.c | 63 ++--------------- src/backend/storage/ipc/procsignal.c | 6 -- src/backend/tcop/postgres.c | 8 +-- src/include/access/parallel.h | 2 +- src/include/commands/repack.h | 3 - src/include/replication/logicalworker.h | 5 -- src/include/storage/procsignal.h | 2 - 11 files changed, 70 insertions(+), 174 deletions(-) diff --git a/src/backend/access/transam/parallel.c b/src/backend/access/transam/parallel.c index e0fef0e8d70..1c5ad287f45 100644 --- a/src/backend/access/transam/parallel.c +++ b/src/backend/access/transam/parallel.c @@ -26,6 +26,7 @@ #include "catalog/pg_enum.h" #include "catalog/storage.h" #include "commands/async.h" +#include "commands/repack.h" #include "commands/vacuum.h" #include "executor/execParallel.h" #include "libpq/libpq.h" @@ -34,6 +35,7 @@ #include "miscadmin.h" #include "optimizer/optimizer.h" #include "pgstat.h" +#include "replication/logicalworker.h" #include "storage/ipc.h" #include "storage/predicate.h" #include "storage/proc.h" @@ -157,7 +159,8 @@ static const struct }; /* Private functions. */ -static void ProcessParallelMessage(ParallelContext *pcxt, int i, StringInfo msg); +static void ProcessParallelContextMessages(void); +static void ProcessParallelContextMessage(ParallelContext *pcxt, int i, StringInfo msg); static void WaitForParallelWorkersToExit(ParallelContext *pcxt); static parallel_worker_main_type LookupParallelWorkerFunction(const char *libraryname, const char *funcname); static void ParallelWorkerShutdown(int code, Datum arg); @@ -1054,7 +1057,7 @@ ParallelContextActive(void) * * Note: this is called within a signal handler! All we can do is set * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke - * ProcessParallelMessages(). + * ProcessParallelMessageInterrupt(). */ void HandleParallelMessageInterrupt(void) @@ -1068,9 +1071,8 @@ HandleParallelMessageInterrupt(void) * Process any queued protocol messages received from parallel workers. */ void -ProcessParallelMessages(void) +ProcessParallelMessageInterrupt(void) { - dlist_iter iter; MemoryContext oldcontext; static MemoryContext hpm_context = NULL; @@ -1101,6 +1103,53 @@ ProcessParallelMessages(void) /* OK to process messages. Reset the flag saying there are more to do. */ ParallelMessagePending = false; + /* + * All three kinds of workers share one flag, which we just reset. If + * reading one kind of queue throws an error, the others were never read, + * and if the error is caught, nothing would bring us back here for them. + * So set the flag again on the way out; a spare call finds the queues + * empty. + */ + PG_TRY(); + { + /* Process messages from workers in a ParallelContext */ + ProcessParallelContextMessages(); + + /* Process messages from REPACK CONCURRENTLY workers */ + ProcessRepackMessages(); + + /* Process messages from replication parallel apply workers */ + ProcessParallelApplyMessages(); + } + PG_CATCH(); + { + InterruptPending = true; + ParallelMessagePending = true; + PG_RE_THROW(); + } + PG_END_TRY(); + + MemoryContextSwitchTo(oldcontext); + + /* Might as well clear the context on our way out */ + MemoryContextReset(hpm_context); + + RESUME_INTERRUPTS(); +} + +/* + * Process any incoming messages from workers in a ParallelContext: parallel + * query, parallel index builds, parallel vacuum, and anything else that uses + * this module. + * + * This is called from CHECK_FOR_INTERRUPTS(), but in a short-lived memory + * context. + */ +static void +ProcessParallelContextMessages(void) +{ + dlist_iter iter; + dlist_foreach(iter, &pcxt_list) { ParallelContext *pcxt; @@ -1134,7 +1183,7 @@ ProcessParallelMessages(void) initStringInfo(&msg); appendBinaryStringInfo(&msg, data, nbytes); - ProcessParallelMessage(pcxt, i, &msg); + ProcessParallelContextMessage(pcxt, i, &msg); pfree(msg.data); } else @@ -1144,20 +1193,13 @@ ProcessParallelMessages(void) } } } - - MemoryContextSwitchTo(oldcontext); - - /* Might as well clear the context on our way out */ - MemoryContextReset(hpm_context); - - RESUME_INTERRUPTS(); } /* * Process a single protocol message received from a single parallel worker. */ static void -ProcessParallelMessage(ParallelContext *pcxt, int i, StringInfo msg) +ProcessParallelContextMessage(ParallelContext *pcxt, int i, StringInfo msg) { char msgtype; diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index eee8b646029..b88eb52def0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -154,12 +154,6 @@ typedef struct DecodingWorker /* Pointer to currently running decoding worker. */ static DecodingWorker *decoding_worker = NULL; -/* - * Is there a message sent by a repack worker that the backend needs to - * receive? - */ -volatile sig_atomic_t RepackMessagePending = false; - static LOCKMODE RepackLockLevel(bool concurrent); static bool cluster_rel_recheck(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid userid, LOCKMODE lmode, @@ -4174,30 +4168,15 @@ DecodingWorkerFileName(char *fname, Oid relid, uint32 seq) snprintf(fname, MAXPGPATH, "%u-%u", relid, seq); } -/* - * Handle receipt of an interrupt indicating a repack worker message. - * - * Note: this is called within a signal handler! All we can do is set - * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke - * ProcessRepackMessages(). - */ -void -HandleRepackMessageInterrupt(void) -{ - InterruptPending = true; - RepackMessagePending = true; - SetLatch(MyLatch); -} - /* * Process any queued protocol messages received from the repack worker. + * + * This is called from CHECK_FOR_INTERRUPTS(), but in a short-lived memory + * context. */ void ProcessRepackMessages(void) { - MemoryContext oldcontext; - static MemoryContext hpm_context = NULL; - /* * Nothing to do if we haven't launched the worker yet or have already * terminated it. Stopping the worker detaches the error message queue @@ -4207,32 +4186,6 @@ ProcessRepackMessages(void) if (decoding_worker == NULL || decoding_worker->error_mqh == NULL) return; - /* - * This is invoked from ProcessInterrupts(), and since some of the - * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential - * for recursive calls if more signals are received while this runs. It's - * unclear that recursive entry would be safe, and it doesn't seem useful - * even if it is safe, so let's block interrupts until done. - */ - HOLD_INTERRUPTS(); - - /* - * Moreover, CurrentMemoryContext might be pointing almost anywhere. We - * don't want to risk leaking data into long-lived contexts, so let's do - * our work here in a private context that we can reset on each use. - */ - if (hpm_context == NULL) /* first time through? */ - hpm_context = AllocSetContextCreate(TopMemoryContext, - "ProcessRepackMessages", - ALLOCSET_DEFAULT_SIZES); - else - MemoryContextReset(hpm_context); - - oldcontext = MemoryContextSwitchTo(hpm_context); - - /* OK to process messages. Reset the flag saying there are more to do. */ - RepackMessagePending = false; - /* * Read messages from the worker, but stop if the error queue disappears, * which happens when a PqRepackMsg_Terminate is received; or as soon as @@ -4259,7 +4212,7 @@ ProcessRepackMessages(void) case SHM_MQ_WOULD_BLOCK: /* no more messages to process for now */ - goto out; + return; case SHM_MQ_DETACHED: @@ -4275,14 +4228,6 @@ ProcessRepackMessages(void) errhint("More details may be available in the server log.")); } } - -out: - MemoryContextSwitchTo(oldcontext); - - /* Might as well clear the context on our way out */ - MemoryContextReset(hpm_context); - - RESUME_INTERRUPTS(); } /* diff --git a/src/backend/commands/repack_worker.c b/src/backend/commands/repack_worker.c index 511dfa715ed..262be71cb5c 100644 --- a/src/backend/commands/repack_worker.c +++ b/src/backend/commands/repack_worker.c @@ -210,7 +210,7 @@ RepackWorkerShutdown(int code, Datum arg) */ dsm_detach(seg); - SendProcSignal(pid, PROCSIG_REPACK_MESSAGE, procno); + SendProcSignal(pid, PROCSIG_PARALLEL_MESSAGE, procno); } bool diff --git a/src/backend/libpq/pqmq.c b/src/backend/libpq/pqmq.c index 98e57a04ff1..1090b764de7 100644 --- a/src/backend/libpq/pqmq.c +++ b/src/backend/libpq/pqmq.c @@ -14,13 +14,11 @@ #include "postgres.h" #include "access/parallel.h" -#include "commands/repack.h" #include "libpq/libpq.h" #include "libpq/pqformat.h" #include "libpq/pqmq.h" #include "miscadmin.h" #include "pgstat.h" -#include "replication/logicalworker.h" #include "storage/latch.h" #include "storage/procsignal.h" #include "tcop/tcopprot.h" @@ -173,23 +171,9 @@ mq_putmessage(char msgtype, const char *s, size_t len) result = shm_mq_sendv(pq_mq_handle, iov, 2, true, true); if (pq_mq_parallel_leader_pid != 0) - { - if (IsLogicalParallelApplyWorker()) - SendProcSignal(pq_mq_parallel_leader_pid, - PROCSIG_PARALLEL_APPLY_MESSAGE, - pq_mq_parallel_leader_proc_number); - else if (AmRepackWorker()) - SendProcSignal(pq_mq_parallel_leader_pid, - PROCSIG_REPACK_MESSAGE, - pq_mq_parallel_leader_proc_number); - else - { - Assert(IsParallelWorker()); - SendProcSignal(pq_mq_parallel_leader_pid, - PROCSIG_PARALLEL_MESSAGE, - pq_mq_parallel_leader_proc_number); - } - } + SendProcSignal(pq_mq_parallel_leader_pid, + PROCSIG_PARALLEL_MESSAGE, + pq_mq_parallel_leader_proc_number); if (result != SHM_MQ_WOULD_BLOCK) break; diff --git a/src/backend/replication/logical/applyparallelworker.c b/src/backend/replication/logical/applyparallelworker.c index b9730de4c70..4f9a4b9e244 100644 --- a/src/backend/replication/logical/applyparallelworker.c +++ b/src/backend/replication/logical/applyparallelworker.c @@ -242,12 +242,6 @@ static List *ParallelApplyWorkerPool = NIL; */ ParallelApplyWorkerShared *MyParallelShared = NULL; -/* - * Is there a message sent by a parallel apply worker that the leader apply - * worker needs to receive? - */ -volatile sig_atomic_t ParallelApplyMessagePending = false; - /* * Cache the parallel apply worker information required for applying the * current streaming transaction. It is used to save the cost of searching the @@ -859,7 +853,7 @@ static void pa_shutdown(int code, Datum arg) { SendProcSignal(MyLogicalRepWorker->leader_pid, - PROCSIG_PARALLEL_APPLY_MESSAGE, + PROCSIG_PARALLEL_MESSAGE, INVALID_PROC_NUMBER); dsm_detach((dsm_segment *) DatumGetPointer(arg)); @@ -999,21 +993,6 @@ ParallelApplyWorkerMain(Datum main_arg) Assert(false); } -/* - * Handle receipt of an interrupt indicating a parallel apply worker message. - * - * Note: this is called within a signal handler! All we can do is set a flag - * that will cause the next CHECK_FOR_INTERRUPTS() to invoke - * ProcessParallelApplyMessages(). - */ -void -HandleParallelApplyMessageInterrupt(void) -{ - InterruptPending = true; - ParallelApplyMessagePending = true; - /* latch will be set by procsignal_sigusr1_handler */ -} - /* * Process a single protocol message received from a single parallel apply * worker. @@ -1062,40 +1041,15 @@ ProcessParallelApplyMessage(StringInfo msg) } /* - * Handle any queued protocol messages received from parallel apply workers. + * Process any queued protocol messages received from parallel apply workers. + * + * This is called from CHECK_FOR_INTERRUPTS(), but in a short-lived memory + * context. */ void ProcessParallelApplyMessages(void) { ListCell *lc; - MemoryContext oldcontext; - - static MemoryContext hpam_context = NULL; - - /* - * This is invoked from ProcessInterrupts(), and since some of the - * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential - * for recursive calls if more signals are received while this runs. It's - * unclear that recursive entry would be safe, and it doesn't seem useful - * even if it is safe, so let's block interrupts until done. - */ - HOLD_INTERRUPTS(); - - /* - * Moreover, CurrentMemoryContext might be pointing almost anywhere. We - * don't want to risk leaking data into long-lived contexts, so let's do - * our work here in a private context that we can reset on each use. - */ - if (!hpam_context) /* first time through? */ - hpam_context = AllocSetContextCreate(TopMemoryContext, - "ProcessParallelApplyMessages", - ALLOCSET_DEFAULT_SIZES); - else - MemoryContextReset(hpam_context); - - oldcontext = MemoryContextSwitchTo(hpam_context); - - ParallelApplyMessagePending = false; foreach(lc, ParallelApplyWorkerPool) { @@ -1131,13 +1085,6 @@ ProcessParallelApplyMessages(void) (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("lost connection to the logical replication parallel apply worker"))); } - - MemoryContextSwitchTo(oldcontext); - - /* Might as well clear the context on our way out */ - MemoryContextReset(hpam_context); - - RESUME_INTERRUPTS(); } /* diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c index eb0f4d6fcdf..b00e3889bcc 100644 --- a/src/backend/storage/ipc/procsignal.c +++ b/src/backend/storage/ipc/procsignal.c @@ -715,12 +715,6 @@ procsignal_sigusr1_handler(SIGNAL_ARGS) if (CheckProcSignal(PROCSIG_LOG_MEMORY_CONTEXT)) HandleLogMemoryContextInterrupt(); - if (CheckProcSignal(PROCSIG_PARALLEL_APPLY_MESSAGE)) - HandleParallelApplyMessageInterrupt(); - - if (CheckProcSignal(PROCSIG_REPACK_MESSAGE)) - HandleRepackMessageInterrupt(); - if (CheckProcSignal(PROCSIG_SLOTSYNC_MESSAGE)) HandleSlotSyncMessageInterrupt(); diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index 1361dfa5526..aed54ff8d5d 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -3716,19 +3716,13 @@ ProcessInterrupts(void) ProcessProcSignalBarrier(); if (ParallelMessagePending) - ProcessParallelMessages(); + ProcessParallelMessageInterrupt(); if (LogMemoryContextPending) ProcessLogMemoryContextInterrupt(); - if (ParallelApplyMessagePending) - ProcessParallelApplyMessages(); - if (SlotSyncShutdownPending) ProcessSlotSyncMessage(); - - if (RepackMessagePending) - ProcessRepackMessages(); } /* diff --git a/src/include/access/parallel.h b/src/include/access/parallel.h index 60f857675e0..0ed0a88d831 100644 --- a/src/include/access/parallel.h +++ b/src/include/access/parallel.h @@ -73,7 +73,7 @@ extern void DestroyParallelContext(ParallelContext *pcxt); extern bool ParallelContextActive(void); extern void HandleParallelMessageInterrupt(void); -extern void ProcessParallelMessages(void); +extern void ProcessParallelMessageInterrupt(void); extern void AtEOXact_Parallel(bool isCommit); extern void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId); extern void ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end); diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h index 45e5440a311..89e6e576bf8 100644 --- a/src/include/commands/repack.h +++ b/src/include/commands/repack.h @@ -35,8 +35,6 @@ typedef struct ClusterParams uint32 options; /* bitmask of CLUOPT_* */ } ClusterParams; -extern PGDLLIMPORT volatile sig_atomic_t RepackMessagePending; - extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel); @@ -58,7 +56,6 @@ extern void finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap, MultiXactId cutoffMulti, char newrelpersistence); -extern void HandleRepackMessageInterrupt(void); extern void ProcessRepackMessages(void); /* in repack_worker.c */ diff --git a/src/include/replication/logicalworker.h b/src/include/replication/logicalworker.h index 7d748a28da8..382269001cf 100644 --- a/src/include/replication/logicalworker.h +++ b/src/include/replication/logicalworker.h @@ -12,10 +12,6 @@ #ifndef LOGICALWORKER_H #define LOGICALWORKER_H -#include - -extern PGDLLIMPORT volatile sig_atomic_t ParallelApplyMessagePending; - extern void ApplyWorkerMain(Datum main_arg); extern void ParallelApplyWorkerMain(Datum main_arg); extern void TableSyncWorkerMain(Datum main_arg); @@ -24,7 +20,6 @@ extern void SequenceSyncWorkerMain(Datum main_arg); extern bool IsLogicalWorker(void); extern bool IsLogicalParallelApplyWorker(void); -extern void HandleParallelApplyMessageInterrupt(void); extern void ProcessParallelApplyMessages(void); extern void LogicalRepWorkersWakeupAtCommit(Oid subid); diff --git a/src/include/storage/procsignal.h b/src/include/storage/procsignal.h index aaa158bfd66..691314e26bf 100644 --- a/src/include/storage/procsignal.h +++ b/src/include/storage/procsignal.h @@ -35,9 +35,7 @@ typedef enum PROCSIG_WALSND_INIT_STOPPING, /* ask walsenders to prepare for shutdown */ PROCSIG_BARRIER, /* global barrier interrupt */ PROCSIG_LOG_MEMORY_CONTEXT, /* ask backend to log the memory contexts */ - PROCSIG_PARALLEL_APPLY_MESSAGE, /* Message from parallel apply workers */ PROCSIG_SLOTSYNC_MESSAGE, /* ask slot synchronization to stop */ - PROCSIG_REPACK_MESSAGE, /* Message from repack worker */ PROCSIG_RECOVERY_CONFLICT, /* backend is blocking recovery, check * PGPROC->pendingRecoveryConflicts for the * reason */ base-commit: 32afcc29df98b245d6c2055fd2a21e6cd2d0fd06 -- 2.54.0