v1-0001-Parallel-query-Use-TopTransactionContext-for-Rein.patch

application/x-patch

Filename: v1-0001-Parallel-query-Use-TopTransactionContext-for-Rein.patch
Type: application/x-patch
Part: 0
Message: Parallel query: Use TopTransactionContext for ReinitializeParallelDSM()
From 83641b878d8732b5eec4614acf1f9df79d29be0f Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Mon, 8 Dec 2025 10:39:35 +0530
Subject: [PATCH v1] Parallel query: Use TopTransactionContext for
 ReinitializeParallelDSM()

When reinitializing the dynamic shared memory (DSM) segment for a
parallel context in ReinitializeParallelDSM(), we failed to switch to
the long-lived TopTransactionContext for necessary memory allocations.
This deviates from the established pattern used in InitializeParallelDSM().
Allocations were instead made in the current, potentially short-lived
memory context.

This exact issue could to a potential server crash (segmentation fault)
when a pointer allocated in the short-lived context was prematurely freed.
Subsequent cleanup in DestroyParallelContext() could resulted in a
use-after-free error.

This commit fixes the breakage by ensuring that memory for the
parallel context is always correctly allocated in TopTransactionContext
during reinitialization.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Co-authored-by: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
Reviewed-by:
Discussion:
---
 src/backend/access/transam/parallel.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/backend/access/transam/parallel.c b/src/backend/access/transam/parallel.c
index 94db1ec3012..5e6d21969e1 100644
--- a/src/backend/access/transam/parallel.c
+++ b/src/backend/access/transam/parallel.c
@@ -507,8 +507,12 @@ InitializeParallelDSM(ParallelContext *pcxt)
 void
 ReinitializeParallelDSM(ParallelContext *pcxt)
 {
+	MemoryContext oldcontext;
 	FixedParallelState *fps;
 
+	/* We might be running in a very short-lived memory context. */
+	oldcontext = MemoryContextSwitchTo(TopTransactionContext);
+
 	/* Wait for any old workers to exit. */
 	if (pcxt->nworkers_launched > 0)
 	{
@@ -546,6 +550,9 @@ ReinitializeParallelDSM(ParallelContext *pcxt)
 			pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
 		}
 	}
+
+	/* Restore previous memory context. */
+	MemoryContextSwitchTo(oldcontext);
 }
 
 /*
-- 
2.43.0