Unify parallel worker handling for index builds and instrumentation

Started by Lukas Fittl6 months ago7 messageshackers
Jump to latest
#1Lukas Fittl
lukas@fittl.com

Hi,

Whilst working on the stack-based instrumentation patch, I noticed
that there is a lot of duplication of parallel worker code, and in
particular parallel index build code, when it comes to how it sets up
shared memory, and how metadata information is fed back to/from the
leader.

My initial focus was around instrumentation, but I think there is a
bigger duplication issue that needs a refactoring in regards to
parallel index builds in particular. See attached a draft patch
series, that does the following:

0001: Use the new Instrumentation struct to handle WAL and Buffer usage together

0002: New helpers to estimate/store Instrumentation struct in shared memory

0003: New helpers to handle query text for parallel workers

0004: Introduces shared parallel index build helper functions

Of these, 0004 is where I have the most uncertainty personally (what's
a good abstraction here?), but wanted to share this to spark a
conversation on how we could improve this.

I could imagine an alternate design where we refactor more generally
how parallel workers get handled for any maintenance commands (i.e.
also including parallel vacuum), but that would reduce how much code
duplication we can avoid for index builds.

Thoughts?

Thanks,
Lukas

--
Lukas Fittl

Attachments:

t139799_1
v1-0001-instrumentation-Use-Instrumentation-struct-for-pa.patchapplication/octet-stream; name=v1-0001-instrumentation-Use-Instrumentation-struct-for-pa.patchDownload+114-180
v1-0003-Unify-parallel-worker-handling-for-query-text.patchapplication/octet-stream; name=v1-0003-Unify-parallel-worker-handling-for-query-text.patchDownload+60-96
v1-0002-Unify-parallel-worker-handling-for-instrumentatio.patchapplication/octet-stream; name=v1-0002-Unify-parallel-worker-handling-for-instrumentatio.patchDownload+58-94
v1-0004-Unify-parallel-index-build-infrastructure.patchapplication/octet-stream; name=v1-0004-Unify-parallel-index-build-infrastructure.patchDownload+465-475
#2Sami Imseih
samimseih@gmail.com
In reply to: Lukas Fittl (#1)
Re: Unify parallel worker handling for index builds and instrumentation

Hi,

Whilst working on the stack-based instrumentation patch, I noticed
that there is a lot of duplication of parallel worker code, and in
particular parallel index build code, when it comes to how it sets up
shared memory, and how metadata information is fed back to/from the
leader.

+1, Thanks for the patches!

My initial focus was around instrumentation, but I think there is a
bigger duplication issue that needs a refactoring in regards to
parallel index builds in particular.

Yes, looks like it.

I reviewed you proposed patch set and here are my findings.

0001: Use the new Instrumentation struct to handle WAL and Buffer usage together

This one is a straightforward refactor. Only comment is to remove the bare block

-       InstrEndParallelQuery(&buffer_usage[ParallelWorkerNumber],
-
&wal_usage[ParallelWorkerNumber]);
+       {
+               Instrumentation *worker_instr;
+
+               worker_instr = shm_toc_lookup(toc,
PARALLEL_KEY_INSTRUMENTATION, false);
+               InstrEndParallelQuery(&worker_instr[ParallelWorkerNumber]);
+       }

0002: New helpers to estimate/store Instrumentation struct in shared memory

Another straightforward refactor.

This comment

- * If there are no extensions loaded that care, we could skip this. We
- * have no way of knowing whether anyone's looking at pgWalUsage or
- * pgBufferUsage, so do it unconditionally.
- */

was removed from the several duplicate code paths that estimated space
for parallel instrumentation, but I don't think it added value anyhow,
so that is fine.

0003: New helpers to handle query text for parallel workers

+/*
+ * Restore the query text in a worker: set debug_query_string and report it as
+ * the current activity.  The key is looked up with missing_ok, so this is a
+ * no-op (leaving debug_query_string NULL) when the leader stored no text.
+ */
+void
+RestoreParallelQueryText(shm_toc *toc, uint64 key)
+{
+       debug_query_string = shm_toc_lookup(toc, key, true);
+       pgstat_report_activity(STATE_RUNNING, debug_query_string);
+}

I went back-forth on this since it combines 2 different ideas, setting
a debug_query_string and reporting activity. I think this is OK after
thinking about it a bit, and the whole point is to deduplicate code.

"no-op (leaving debug_query_string NULL) " The comment here is
not accurate. I would drop the "no-op" part since it is setting a NULL
query string. right?

0004: Introduces shared parallel index build helper functions

Of these, 0004 is where I have the most uncertainty personally (what's
a good abstraction here?), but wanted to share this to spark a
conversation on how we could improve this.

I think this is a nice deduplication as well. So I am also +1 to this.

A few things:

1/
+        * Mutable state that is maintained for exact index AMs (e.g.
nbtree), and
+        * unused for lossy AMs.

Not sure if the "loss AMs" comment is accurate. From what I can tell, GIN
does not use the havedead and brokenhotchain fields and it's not lossy.
right?

2/
+ * workers are launched; the mutable fields are maintained by the workers

nit: extra space before "launched"

3/
Per the commit message:

This also fixes an oversight in parallel GIN index builds that forgot
to pass the queryid to the parallel workers, like other AMs do.

I think this should be an independent patch, and first in the series.

I could imagine an alternate design where we refactor more generally
how parallel workers get handled for any maintenance commands (i.e.
also including parallel vacuum), but that would reduce how much code
duplication we can avoid for index builds.

Yeah, I am not sure we need to go that far in the deduplication. Parallel
Vacuum and Parallel index builds are way different in what they do.

--
Sami Imseih
Amazon Web Services (AWS)

#3Michael Paquier
michael@paquier.xyz
In reply to: Sami Imseih (#2)
Re: Unify parallel worker handling for index builds and instrumentation

On Mon, Jun 01, 2026 at 01:31:00PM -0500, Sami Imseih wrote:

0001: Use the new Instrumentation struct to handle WAL and Buffer usage together

This one is a straightforward refactor. Only comment is to remove the bare block

-       InstrEndParallelQuery(&buffer_usage[ParallelWorkerNumber],
-
&wal_usage[ParallelWorkerNumber]);
+       {
+               Instrumentation *worker_instr;
+
+               worker_instr = shm_toc_lookup(toc,
PARALLEL_KEY_INSTRUMENTATION, false);
+               InstrEndParallelQuery(&worker_instr[ParallelWorkerNumber]);
+       }

Instrumentation is a structure larger than WalUsage and BufferUsage
combined, and we don't care about all these other fields for the
parallel workers. Sure, this cuts code, but this also increases the
DSM and memory footprint.

0002 relies on 0001, so same mixed feeling regarding it.

0003: New helpers to handle query text for parallel workers

+/*
+ * Restore the query text in a worker: set debug_query_string and report it as
+ * the current activity.  The key is looked up with missing_ok, so this is a
+ * no-op (leaving debug_query_string NULL) when the leader stored no text.
+ */
+void
+RestoreParallelQueryText(shm_toc *toc, uint64 key)
+{
+       debug_query_string = shm_toc_lookup(toc, key, true);
+       pgstat_report_activity(STATE_RUNNING, debug_query_string);
+}

I went back-forth on this since it combines 2 different ideas, setting
a debug_query_string and reporting activity. I think this is OK after
thinking about it a bit, and the whole point is to deduplicate code.

"no-op (leaving debug_query_string NULL) " The comment here is
not accurate. I would drop the "no-op" part since it is setting a NULL
query string. right?

Hmm. This one looks like it has nice advantages. For one, less
specific logic related to debug_query_string in all the main callbacks
of these parallel workers, copied in three different places.

0004: Introduces shared parallel index build helper functions

Of these, 0004 is where I have the most uncertainty personally (what's
a good abstraction here?), but wanted to share this to spark a
conversation on how we could improve this.

I think this is a nice deduplication as well. So I am also +1 to this.

Less duplication with the levels of locks assigned and less
duplication regarding the levels of the snapshots retrieved makes this
approach quite beneficial in the long-term. That reads nice.
--
Michael

#4Sami Imseih
samimseih@gmail.com
In reply to: Michael Paquier (#3)
Re: Unify parallel worker handling for index builds and instrumentation

0001: Use the new Instrumentation struct to handle WAL and Buffer usage together

This one is a straightforward refactor. Only comment is to remove the bare block

-       InstrEndParallelQuery(&buffer_usage[ParallelWorkerNumber],
-
&wal_usage[ParallelWorkerNumber]);
+       {
+               Instrumentation *worker_instr;
+
+               worker_instr = shm_toc_lookup(toc,
PARALLEL_KEY_INSTRUMENTATION, false);
+               InstrEndParallelQuery(&worker_instr[ParallelWorkerNumber]);
+       }

Instrumentation is a structure larger than WalUsage and BufferUsage
combined, and we don't care about all these other fields for the
parallel workers. Sure, this cuts code, but this also increases the
DSM and memory footprint.

The difference is 192 bytes per worker; 360 bytes for Instrumentation
- 168 bytes
for removing BufferUsage and WalUsage. Even with 32 parallel workers ( probably
the extreme case ) that is ~6 KB, which is negligible compared to the code
cleanup.

gdb -batch -nx $PGHOME/bin/postgres \
-ex "print (int)sizeof(Instrumentation)" \
-ex "print (int)sizeof(BufferUsage)" \
-ex "print (int)sizeof(WalUsage)" \
-ex "ptype/o Instrumentation" \
-ex "ptype/o BufferUsage" \
-ex "ptype/o WalUsage"
$1 = 360
$2 = 128
$3 = 40

--
Sami Imseih
Amazon Web Services (AWS)

#5Lukas Fittl
lukas@fittl.com
In reply to: Sami Imseih (#4)
Re: Unify parallel worker handling for index builds and instrumentation

On Tue, Jun 2, 2026 at 4:29 PM Sami Imseih <samimseih@gmail.com> wrote:

0001: Use the new Instrumentation struct to handle WAL and Buffer usage together

This one is a straightforward refactor. Only comment is to remove the bare block

-       InstrEndParallelQuery(&buffer_usage[ParallelWorkerNumber],
-
&wal_usage[ParallelWorkerNumber]);
+       {
+               Instrumentation *worker_instr;
+
+               worker_instr = shm_toc_lookup(toc,
PARALLEL_KEY_INSTRUMENTATION, false);
+               InstrEndParallelQuery(&worker_instr[ParallelWorkerNumber]);
+       }

Instrumentation is a structure larger than WalUsage and BufferUsage
combined, and we don't care about all these other fields for the
parallel workers. Sure, this cuts code, but this also increases the
DSM and memory footprint.

The difference is 192 bytes per worker; 360 bytes for Instrumentation
- 168 bytes
for removing BufferUsage and WalUsage. Even with 32 parallel workers ( probably
the extreme case ) that is ~6 KB, which is negligible compared to the code
cleanup.

Hmm, thanks for running the numbers!

I agree its not substantial, but its also not nothing - so I see
Michael's point. I think the largest difference here is the fact that
WalUsage and BufferUsage are repeated - that is something that would
no longer be necessary once/if we go with the stack-based
instrumentation approach. When I had this patch in the other patch
series, it was after a refactoring that made the overhead much
smaller.

Maybe for now I can re-order this patch series to lead with the other
patches, and we could defer this part a bit until we have clarity what
we're doing re: stack-based instrumentation.

I'll respond on the other comments separately later this week. Thanks
to you both for the quick feedback!

Thanks,
Lukas

--
Lukas Fittl

#6Michael Paquier
michael@paquier.xyz
In reply to: Lukas Fittl (#5)
Re: Unify parallel worker handling for index builds and instrumentation

On Tue, Jun 02, 2026 at 05:38:09PM -0700, Lukas Fittl wrote:

I agree its not substantial, but its also not nothing - so I see
Michael's point. I think the largest difference here is the fact that
WalUsage and BufferUsage are repeated - that is something that would
no longer be necessary once/if we go with the stack-based
instrumentation approach. When I had this patch in the other patch
series, it was after a refactoring that made the overhead much
smaller.

Maybe for now I can re-order this patch series to lead with the other
patches, and we could defer this part a bit until we have clarity what
we're doing re: stack-based instrumentation.

Right. That hints also to a patch ordering problem to me, where the
final picture (if I got correctly) would be that we don't have the
_start fields anymore at the end in the Instrumentation data sent.
It feels confusing that we push from the leader to its workers a set
of fields that the workers have no use for.
--
Michael

#7Lukas Fittl
lukas@fittl.com
In reply to: Lukas Fittl (#5)
Re: Unify parallel worker handling for index builds and instrumentation

On Tue, Jun 2, 2026 at 5:38 PM Lukas Fittl <lukas@fittl.com> wrote:

Maybe for now I can re-order this patch series to lead with the other
patches, and we could defer this part a bit until we have clarity what
we're doing re: stack-based instrumentation.

I'll respond on the other comments separately later this week. Thanks
to you both for the quick feedback!

Well, that took a bit longer - whoops!

See attached v2:

Per prior discussion, to focus on the bigger win here, I've dropped
the original 0001 and 0002 patches for now (though thank you Sami for
reviewing) and might bring them back at a later time when some of the
instrumentation work goes in (or clearly doesn't). However, I've added
two new bug fix patches in their place:

New 0001 "Fix query ID reporting in parallel workers for GIN index
builds" - split out as Sami suggested.

New 0002 "Fix broken HOT chain handling in parallel BRIN and GIN index builds"

- I discovered this whilst thinking through how pgvector also had an
extra field that needed the ParallelIndexBuildShared mutex (see at the
end of this email) - I initially thought that both "havedead" and
"brokenhotchain" were B-tree specific, but I don't think that's
actually true - instead "brokenhotchain" / ii_BrokenHotChain is a
general purpose field that must be handled correctly by any index AM
that points at heap tuples
- This should be backpatched to 17 (parallel BRIN index builds) and 18
(parallel GIN index builds) respectively, since in my read it's an
actual bug: A transaction holding a snapshot from before the build
started could use the new BRIN/GIN index and get incorrect results

Per the discussion I've also flipped the order of the other two,
making 0003 "Unify parallel index build infrastructure", and 0004
"Unify parallel worker handling for query text".

New 0005 - "Unify parallel index build scan handling" - an additional
proposal of how we could more structurally prevent the issue that 0002
fixes by introducing a shared ParallelIndexBuildScan() helper.

I've also addressed the other minor feedback items on what are now
0003/0004, and additionally:

- Forward declare ParallelTableScanDescData in parallel_index_build.h
to avoid including access/relscan.h and storage/lockdefs.h
- Add a helper function ParallelIndexBuildAbort to deal with the abort
case in a consistent way
- Have ParallelIndexBuildCreateContext take a library_name argument,
matching CreateParallelContext, to allow extensions to use this
infrastructure more easily (see pgvector case below)
- Rework how lock modes are set, so the caller doesn't have to pass them back in
- Rework the query text logic to avoid making two strlen calls (we can
keep the pre-existing pattern with a local variable to store the
length from the estimation)

To put this to the test I've also sketched out how pgvector can update
to this infrastructure at [0]https://github.com/lfittl/pgvector/pull/1, as an example of an out-of-core index
AM that supports parallel index builds. Some notes from that:

- Because which fields are updated under the ParallelIndexBuildShared
mutex isn't configurable, pgvector has to do an additional
SpinLockAcquire/SpinLockRelease for updating its "inertia" field
before calling ParallelIndexBuildReportScanDone (which will report the
other fields) -- I don't think that in itself is a problem (and don't
have a good idea to solve it), but we kind of have the same in-core
"quirk", which is why havedead is on ParallelIndexBuildShared despite
being B-Tree specific
- pgvector didn't report back worker WAL/buffer usage, and the
ParallelIndexBuildEnd function added here now requires that, which I
think is acceptable
- pgvector also suffered from the same queryid reporting bug as GIN,
which is fixed by using the new infrastructure
- pgvector also did not report back broken HOT chains encountered
during parallel index builds

As expected, this is a net code reduction for pgvector, when ignoring
the need to have older Postgres versions supported (the shim is ~330
lines that they'd have to carry for a few years).

Thanks,
Lukas

[0]: https://github.com/lfittl/pgvector/pull/1

--
Lukas Fittl

Attachments:

t139799_7
v2-0001-Fix-query-ID-reporting-in-parallel-workers-for-GI.patchapplication/octet-stream; name=v2-0001-Fix-query-ID-reporting-in-parallel-workers-for-GI.patchDownload+7-1
v2-0005-Unify-parallel-index-build-scan-handling.patchapplication/octet-stream; name=v2-0005-Unify-parallel-index-build-scan-handling.patchDownload+210-204
v2-0002-Fix-broken-HOT-chain-handling-in-parallel-BRIN-an.patchapplication/octet-stream; name=v2-0002-Fix-broken-HOT-chain-handling-in-parallel-BRIN-an.patchDownload+47-19
v2-0004-Unify-parallel-worker-handling-for-query-text.patchapplication/octet-stream; name=v2-0004-Unify-parallel-worker-handling-for-query-text.patchDownload+77-94
v2-0003-Unify-parallel-index-build-infrastructure.patchapplication/octet-stream; name=v2-0003-Unify-parallel-index-build-infrastructure.patchDownload+520-524