From fac87c8b7f263ef1c9e087b57eebdee5382ce16d Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Mon, 17 Feb 2025 15:26:24 +0100
Subject: [PATCH v20250217 2/6] WIP: don't use work_mem to size buffers

---
 src/backend/access/gin/gininsert.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/src/backend/access/gin/gininsert.c b/src/backend/access/gin/gininsert.c
index 2a44482b4be..34f88d16473 100644
--- a/src/backend/access/gin/gininsert.c
+++ b/src/backend/access/gin/gininsert.c
@@ -145,6 +145,7 @@ typedef struct
 	MemoryContext funcCtx;
 	BuildAccumulator accum;
 	ItemPointerData tid;
+	int				work_mem;
 
 	/* FIXME likely duplicate with indtuples */
 	double		bs_numtuples;
@@ -576,7 +577,7 @@ ginBuildCallbackParallel(Relation index, ItemPointer tid, Datum *values,
 	 * maintenance_work_mem. It's weird to use work_mem here, in a clearly
 	 * maintenance command.
 	 */
-	if (buildstate->accum.allocatedMemory >= (Size) work_mem * 1024L)
+	if (buildstate->accum.allocatedMemory >= buildstate->work_mem * 1024L)
 		ginFlushBuildState(buildstate, index);
 
 	MemoryContextSwitchTo(oldCtx);
@@ -1766,14 +1767,19 @@ _gin_parallel_scan_and_build(GinBuildState *state,
 
 	/* Begin "partial" tuplesort */
 	state->bs_sortstate = tuplesort_begin_index_gin(heap, index,
-													sortmem, coordinate,
+													(sortmem / 2),
+													coordinate,
 													TUPLESORT_NONE);
 
 	/* Local per-worker sort of raw-data */
 	state->bs_worker_sort = tuplesort_begin_index_gin(heap, index,
-													  sortmem, NULL,
+													  (sortmem / 2),
+													  NULL,
 													  TUPLESORT_NONE);
 
+	/* remember how much space is allowed for the accumulated entries */
+	state->work_mem = (sortmem / 2);
+
 	/* Join parallel scan */
 	indexInfo = BuildIndexInfo(index);
 	indexInfo->ii_Concurrent = ginshared->isconcurrent;
-- 
2.48.1

