Hash aggregation shows only the last execution's stats for parallel workers

Started by Tatsuya Kawata13 days ago5 messageshackers

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1Tatsuya Kawata
kawatatatsuya0913@gmail.com

Hi,

I noticed that Agg has the same issue as the one fixed for Memoize [1]/messages/by-id/CAHza6qeA-4vB355co-2yAxDMRTpEneY0rg9CD2zMLYscYvv2UA@mail.gmail.com.

When a Gather (or Gather Merge) node is rescanned, a new set of workers
is started, and they write their Agg stats into the same shared memory
slots as the previous ones. ExecEndAgg() overwrites the values, so
EXPLAIN ANALYZE shows the per-worker Batches etc. only for the last
execution.

=== Example

CREATE TABLE ag AS SELECT g % 2000 AS y FROM generate_series(1, 2000000) g;
ANALYZE ag;

SET work_mem = '64kB'; -- make the hash aggregation spill
SET parallel_leader_participation = off; -- only the worker runs the
Partial HashAggregate
SET max_parallel_workers = 1; -- so that Worker 0 runs both
executions

EXPLAIN (ANALYZE, VERBOSE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT o.z, (SELECT count(*) + o.z FROM (SELECT y, count(*) FROM ag GROUP
BY y) s)
FROM (VALUES (1), (2)) o(z);

=== Output on master

Each execution uses 5 batches (1 + 4), and Worker 0 runs the Partial
HashAggregate twice (loops=2), but Batches shows only 5:

-> Partial HashAggregate (actual rows=2000.00 loops=2)
...
Worker 0: actual rows=2000.00 loops=2
Batches: 5 Memory Usage: 161kB Disk Usage: 11048kB

=== With the patch

Batches: 9 Memory Usage: 161kB Disk Usage: 11048kB

The attached patch accumulates the values instead of overwriting them.
As for Memoize, it keeps the maximum for Memory Usage and Disk Usage.
For Batches, hash_batches_used is 1 when nothing spilled, so simply
adding the values would give 2 when a worker that didn't spill runs
twice, and Disk Usage would then be shown as if it had spilled. So the
in-memory batch is counted only once. This is the same as how master
counts it when the leader rescans the node itself.

Note that this example uses only one worker to keep the results stable,
and Worker 0 does the same work in both executions, so Memory Usage and
Disk Usage don't change with the patch. With two workers, the rows are
distributed differently in each execution, and Disk Usage then shows
the value of the last execution on master and the maximum with the
patch.

Regards,
Tatsuya Kawata

[1]: /messages/by-id/CAHza6qeA-4vB355co-2yAxDMRTpEneY0rg9CD2zMLYscYvv2UA@mail.gmail.com
/messages/by-id/CAHza6qeA-4vB355co-2yAxDMRTpEneY0rg9CD2zMLYscYvv2UA@mail.gmail.com

Attachments:

t259246_1
v1-0001-Accumulate-Agg-parallel-worker-stats-across-resca.patchapplication/octet-stream; name=v1-0001-Accumulate-Agg-parallel-worker-stats-across-resca.patchDownload+10-4
#2Prashant Chinnam
crprashant@hotmail.com
In reply to: Tatsuya Kawata (#1)
Re: Hash aggregation shows only the last execution's stats for parallel workers

Hi Tatsuya,

Thanks for the patch. I reproduced the problem and verified the
fix on current master (207b5293b8d); v1 applies cleanly and the
diffstat is exactly the advertised +10 -3 in nodeAgg.c. My
verdict is Ready for Committer. Details below.

Your analysis is right: when a Gather or Gather Merge node is
rescanned it starts a new set of workers, and each worker's
ExecEndAgg() overwrites the Agg statistics in the shared memory
slots, so EXPLAIN ANALYZE reports only the last execution's
per-worker Batches / Memory Usage / Disk Usage. Accumulating in
ExecEndAgg(), where the worker hands its stats back, is the
right layer, and the shape matches the precedent you cite: the
Memoize fix already accumulates its counters in exactly this
spot, with Max() for the peak value.

What I ran, using your reproducer's settings (work_mem = 64kB
to force spilling, parallel_leader_participation = off,
max_parallel_workers = 1 so Workers Planned: 2 but only
Worker 0 launches and runs every execution; 2,000,000-row
table, GROUP BY over 2,000 groups):

case master patched
your repro, rescanned twice 5 9
same, rescanned three times 5 13
rescanned twice, no spilling 1 1
single execution, spilling 5 5
rescanned twice, two workers 5 / 5 9 / 9

So the patched Worker 0 Batches is 9 for two executions
(5 + 5, with the in-memory batch counted once) and 13 for
three, while Memory Usage (169kB) and Disk Usage (7344kB)
are unchanged from master in these identical-execution
cases, since they keep the maximum. The two controls I cared
about most both hold: a single execution reports exactly the
same numbers as master (no double counting, because the
shared slot starts at zero), and two executions that never
spill still show Batches: 1 with no Disk Usage line, which a
naive sum would have broken (explain.c prints Disk Usage
only when Batches > 1, so summing would have produced a
phantom "Disk Usage: 0kB").

Scope checks: ExecEndAgg() is the only place that writes the
shared AggregateInstrumentation slots, and explain.c is the
only reader, so the fix covers the whole affected path. The
leader cannot have this bug (its stats are read from its own
AggState, and indeed a leader-executed HashAggregate that is
rescanned twice already shows Batches: 9 on unpatched master;
the patch makes the worker path consistent with it), and
GroupAggregate has no hash statistics to accumulate. All of
my non-parallel and leader-executed control cases produced
byte-identical Batches values before and after the patch.

Tests: I ran the full meson test suite (TAP enabled) on the
patched build: 404 ok, 0 failures, 36 skipped; core
regression 243/243 (including aggregates, select_parallel,
explain, groupingsets and partition_aggregate) and isolation
139/139. I also ran installcheck-world on a separate
autoconf build of the same patched tree (TAP enabled,
against the installed server): all 55 pg_regress suites
passed, 668 tests, zero regression.diffs, core 243/243 and
isolation 139/139 included. The TAP suites run under it
passed as well, except pg_upgrade's on the first pass:
008_extension_control_path.pl needs the test modules' .so
files, which a plain make does not build. With them built,
that suite passes standalone (9 files, 161 tests).

The patch adds no regression test, and I do not think its
absence should hold the fix up — no existing test prints
per-worker Batches, and the analogous Memoize fix shipped
without one. That said, the Batches number turns out to be
stable enough to test (it reproduced exactly in both our
environments, unlike Memory/Disk: your 161kB / 11048kB vs
my 169kB / 7344kB), so I wrote one and attached it, for you
or a committer to take or leave. It adds a case to
select_parallel that rescans a Gather over a spilling
HashAggregate with one launched worker and asserts only the
extracted Batches line: 9 with the fix, 5 without, plus a
no-spill pass that must stay at 1. With the test added, the
core regression suite passes on the patched tree; on
unpatched master it fails with exactly that one line
(Batches: 5 for the expected 9).

The patch is marked for backpatching to stable; how far back
is a committer's call, but since this only changes EXPLAIN
ANALYZE statistics reporting and not query results, it looks
safe to backpatch wherever the Memoize fix went.
I used AI assistance for the builds and test runs.

Regards,
Prashant

Attachments:

t259246_2
regression-test.patchapplication/octet-stream; name=regression-test.patchDownload+119-0
#3David Rowley
dgrowleyml@gmail.com
In reply to: Prashant Chinnam (#2)
Re: Hash aggregation shows only the last execution's stats for parallel workers

On Tue, 24 Nov 2026 at 13:10, Prashant Chinnam <crprashant@hotmail.com> wrote:

I used AI assistance for the builds and test runs.

IMO, it looks like you used AI to write the entire email and the patch too.

In future, try to consider that a human might have to read your email.
Mentioning that the git diff --stat match the git format-patch's stats
part probably isn't as useful a thing to mention as your AI might
think. From the point of view of a committer, reading emails like this
is infuriating, as we need to go over discussions to see what's
resolved and what's outstanding. IMO, all you've added to the thread
is a load of AI-generated crud that I could have had my local LLM
generate if I'd wanted to.

FWIW, the proposed test patch is ridiculous. A 100k-row table to test
the EXPLAIN output is insane.

David

#4David Rowley
dgrowleyml@gmail.com
In reply to: Tatsuya Kawata (#1)
Re: Hash aggregation shows only the last execution's stats for parallel workers

On Tue, 17 Nov 2026 at 03:17, Tatsuya Kawata
<kawatatatsuya0913@gmail.com> wrote:

When a Gather (or Gather Merge) node is rescanned, a new set of workers
is started, and they write their Agg stats into the same shared memory
slots as the previous ones. ExecEndAgg() overwrites the values, so
EXPLAIN ANALYZE shows the per-worker Batches etc. only for the last
execution.

This seems to be a duplicate of [1]/messages/by-id/CAJTYsWW5evhmWDWAgknx=GXNMJG=k4-T+d435pZpg8Lqxc=kFQ@mail.gmail.com. The patches seem to take a
different approach to how hash_batches_used is calculated.

You've got:

+        /* Workers restart on rescan; count the initial batch only once. */
+        if (si->hash_batches_used == 0)
+            si->hash_batches_used = node->hash_batches_used;
+        else
+            si->hash_batches_used += node->hash_batches_used - 1;

Whereas the other patch does:

+        si->hash_batches_used = Max(si->hash_batches_used, 1) +
+            node->hash_batches_used - 1;

Can you state the other patches version isn't correct?

David

[1]: /messages/by-id/CAJTYsWW5evhmWDWAgknx=GXNMJG=k4-T+d435pZpg8Lqxc=kFQ@mail.gmail.com

#5Tatsuya Kawata
kawatatatsuya0913@gmail.com
In reply to: David Rowley (#4)
Re: Hash aggregation shows only the last execution's stats for parallel workers

Hi David,

This seems to be a duplicate of [1].

Sorry, I missed that thread.

Can you state the other patches version isn't correct?

The version in that thread is also correct, and the two give the same
results. (Just to note, the code under "You've got" is the version in
that thread, and the one with Max() is mine.)
Actually, I first wrote this patch with if...else too, but I went with
this form because I couldn't find a similar if...else in other nodes,
and it can be written more simply without one.

Since the thread you pointed to came first, I'll withdraw this one.
Please go ahead with that thread.

Regards,
Tatsuya Kawata