BUG #19955: Parallel Hash doubles nbatch without limit under build-side skew; backend OOM-killed

From: PG Bug reporting form <noreply(at)postgresql(dot)org>
To: pgsql-bugs(at)lists(dot)postgresql(dot)org
Cc: rudi(at)babaluga(dot)com
Subject: BUG #19955: Parallel Hash doubles nbatch without limit under build-side skew; backend OOM-killed
Date: 2026-11-29 09:08:32
Message-ID: 19955-52b16ad4b4cc4347@postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

The following bug has been logged on the website:

Bug reference: 19955
Logged by: Rudi Bruchez
Email address: rudi(at)babaluga(dot)com
PostgreSQL version: 19.0
Operating system: Linux x86_64 (Debian container images, podman)
Description:

## Versions and platform

- PostgreSQL 18.6 (Debian 18.6-1.pgdg13+2) on x86_64-pc-linux-gnu, compiled
by gcc (Debian 14.2.0-19) 14.2.0, 64-bit
- PostgreSQL 18.7 (Debian 18.7-1.pgdg13+5) on x86_64-pc-linux-gnu, compiled
by gcc (Debian 14.2.0-19) 14.2.0, 64-bit
- PostgreSQL 19.0 (Debian 19.0-2.pgdg13+1) on x86_64-pc-linux-gnu, compiled
by gcc (Debian 14.2.0-19) 14.2.0, 64-bit
- Official `postgres:18.6`, `postgres:18.7` and `postgres:19.0` container
images, default configuration, run under rootless podman on Linux 7.3
(x86_64) with a 3 GB cgroup memory limit (`--memory 3g --memory-swap 3g
--shm-size 1g`).

## Summary

When the build side of a Parallel Hash Join holds one very frequent key
mixed with many distinct keys, the number of batches keeps doubling until it
is of the order of the number of distinct keys. The per-batch,
per-participant buffers are not counted against `hash_mem`, so memory grows
far beyond `work_mem * hash_mem_multiplier`. With 70,000 build rows and
`work_mem = 64kB`, the query uses more than 2.6 GB of anonymous memory and
the backend is killed by the kernel OOM killer, which takes the whole
instance through crash recovery.

The same query with a serial hash join, or with a parallel non-shared hash
(`enable_parallel_hash = off`), finishes in under 50 ms with 64 batches.

## Reproduction

```sql
-- Build side: 70,000 rows, half of them on key 1, the rest on distinct
keys.
-- Statistics are gathered before the skew is introduced, so that the
planner
-- picks this table as the build side (it believes k is unique).
DROP TABLE IF EXISTS build, probe;
CREATE TABLE build (k int, v int) WITH (autovacuum_enabled = off);
INSERT INTO build SELECT g, g FROM generate_series(1, 70000) g;
ANALYZE build;
UPDATE build SET k = 1 WHERE v % 2 = 0;
VACUUM build;
CREATE TABLE probe (k int) WITH (autovacuum_enabled = off);
INSERT INTO probe SELECT g % 70000 + 1 FROM generate_series(1, 140000) g;
ANALYZE probe;
ALTER TABLE build SET (parallel_workers = 3);
ALTER TABLE probe SET (parallel_workers = 3);

SET max_parallel_workers_per_gather = 3;
SET parallel_setup_cost = 0;
SET parallel_tuple_cost = 0;
SET work_mem = '64kB'; -- hash_mem_multiplier left at its default
(2)

-- 1. Serial hash join: finishes, small number of batches.
SET max_parallel_workers_per_gather = 0;
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM probe JOIN build USING (k);
SET max_parallel_workers_per_gather = 3;

-- 2. Parallel, non-shared hash: finishes.
SET enable_parallel_hash = off;
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM probe JOIN build USING (k);
RESET enable_parallel_hash;

-- 3. Parallel Hash: memory grows until the backend is OOM-killed.
EXPLAIN SELECT count(*) FROM probe JOIN build USING (k);
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM probe JOIN build USING (k);
```

The `UPDATE` matters for two reasons: it hides the skew from the planner
(otherwise it hashes the other side), and it rewrites the key-1 rows at the
end of the heap, so that the distinct keys are read first (see "Dependence
on physical order" below).

## Expected result

Step 3 finishes like steps 1 and 2, with a bounded number of batches, or at
worst uses memory of the same order as the serial plan. Once a batch cannot
be split because it is dominated by one key, growth should stop.

## Actual result

Steps 1 and 2, identical on 18.6 and 19.0:

```
Hash (actual time=9.101..9.102 rows=70000.00 loops=1)
Buckets: 8192 (originally 8192) Batches: 64 (originally 16) Memory
Usage: 1251kB
Execution Time: 49.825 ms -- serial, 18.6 (36.7 ms on 19.0)
Execution Time: 37.578 ms -- enable_parallel_hash = off, 3 workers,
18.6 (36.0 ms on 19.0)
```

Step 3 plan:

```
Finalize Aggregate
-> Gather
Workers Planned: 3
-> Partial Aggregate
-> Parallel Hash Join
Hash Cond: (probe.k = build.k)
-> Parallel Seq Scan on probe
-> Parallel Hash
-> Parallel Seq Scan on build
```

`EXPLAIN ANALYZE` never returns. Anonymous memory of the container cgroup
(`memory.stat`) climbs to 2,784 MB (18.6), 2,773 MB (18.7) and 2,673 MB
(19.0) within about 10 seconds, then:

```
LOG: client backend (PID 84) was terminated by signal 9: Killed
DETAIL: Failed process was running: EXPLAIN (ANALYZE, BUFFERS) SELECT
count(*) FROM probe JOIN build USING (k);
LOG: terminating any other active server processes
LOG: all server processes terminated; reinitializing
LOG: database system was not properly shut down; automatic recovery in
progress
```

Depending on which process the kernel picks, the victim is the leader or a
`background worker "parallel worker"`. Dynamic shared memory stays small (at
most 63 MB in `/dev/shm`); the growth is in backend-private memory.

With less data the query completes and shows the batch count. Same shape of
table, 50,000 build rows, `work_mem = 128kB`:

| Plan | Batches | Execution time | Peak anonymous memory |
|---|---|---|---|
| serial | 32 (originally 16) | 38 ms | negligible |
| Parallel Hash, 1 worker + leader | 16384 (originally 16) | 6.5 s | 1.2 GB
|
| Parallel Hash, 3 workers + leader | 16384 (originally 16) | 12.4 s | 1.9
GB |

`EXPLAIN ANALYZE` reports `Memory Usage: 1056kB` for these Parallel Hash
runs, which hides the real consumption. Larger inputs reproduce the OOM as
well (I tried up to 2,000,000 build rows with `work_mem = 4MB`).

## Dependence on physical order

Same contents (35,000 rows on key 1, 35,000 distinct keys), `work_mem =
64kB`, 3 workers, only the insertion order changes (statistics taken on a
unique key before `TRUNCATE` and reload):

| Physical order of the build table | 18.6 | 19.0 |
|---|---|---|
| distinct keys first, then key 1 | OOM-killed | OOM-killed |
| key 1 first, then distinct keys | 32 batches, 31 ms | 32 batches, 34 ms |
| alternating | 4096 batches, 3.5 s | 4096 batches, 3.6 s |

The serial and non-shared plans finish with 64 batches in under 65 ms for
the first order.

## Analysis

Line numbers refer to `src/backend/executor/nodeHash.c` at `REL_18_6` (19.0
in parentheses); this logic is unchanged between the two, and `nodeHash.c`,
`sharedtuplestore.c` and `buffile.c` are unchanged between `REL_18_6` and
`REL_18_7`.

In `ExecParallelHashIncreaseNumBatches`, phase `PHJ_GROW_BATCHES_DECIDE`,
growth is disabled only when some child batch received every tuple of its
parent:

```c
if (batch->ntuples == hashtable->batches[parent].shared->old_ntuples)
extreme_skew_detected = true; /* line 1398 (1423) */
...
if (extreme_skew_detected || hashtable->nbatch >= INT_MAX / 2)
pstate->growth = PHJ_GROWTH_DISABLED; /* lines 1404-1405
(1429-1430) */
else if (space_exhausted)
pstate->growth = PHJ_GROWTH_NEED_MORE_BATCHES;
```

If the batch holding the hot key also holds other keys when it overflows,
each doubling moves about half of those other keys to the sibling batch. The
hot child never receives all of its parent's tuples, so the test never
fires, while the hot key alone keeps the batch above `space_allowed`.
Doubling goes on until the hot batch contains nothing but the hot key, which
takes a number of batches of the order of the number of distinct keys. When
the hot rows are read first, the first overflowing batch contains only the
hot key, the test fires on the first split, and growth stops (the 32-batch
case above). This is the behavior described for the serial path in the
pgsql-hackers thread "Avoiding hash join batch explosions with extreme skew
and weird stats" (May 2019).

PostgreSQL 18 mitigated this for the non-parallel path (commit a1b4f289be,
"Consider BufFiles when adjusting hashjoin parameters", fixed by
b85c4700fc): `ExecHashIncreaseNumBatches` calls `ExecHashIncreaseBatchSize`
(line 1048 (1073)), which doubles `spaceAllowed` instead of `nbatch` once
the batch files would cost more than the hash table. That is why the serial
and non-shared plans stop at 64 batches here, with a `Memory Usage` above
`hash_mem`. Nothing equivalent exists on the parallel path:
`pstate->space_allowed` is set once (lines 601 and 1244 (626 and 1269)) and
never raised, and `ExecHashIncreaseBatchSize` is not called there.

The memory itself, as far as I can tell from the code, is the per-batch
state of each participant: every batch a participant writes to gets a
`SharedTuplestoreAccessor` whose first `sts_puttuple` allocates a
`STS_CHUNK_PAGES * BLCKSZ` (32 kB) write chunk (`sharedtuplestore.c`, lines
333-335) plus a `BufFile` with its 8 kB buffer. During repartitioning every
participant writes to every batch, so this is about 40 kB per batch per
participant. At 16384 batches that is about 650 MB per participant,
consistent with the 500 to 600 MB per participant measured above; the next
doubling or two exceed 3 GB with four participants.

## Related reports

- BUG #19449 (April 2026): a Parallel Hash growing to 262144 batches on
PostgreSQL 16 and later. The reduced case there was a LEFT JOIN with about
465,000 NULL keys on the build side, which commit 1811f1af98 ("Improve hash
join's handling of tuples with null join keys", PostgreSQL 19) addresses.
The case above is an inner join on a non-NULL duplicate key and still fails
on 19.0, so it seems to be a separate trigger of the same underlying growth
logic.
- Commit 98c7c7152d ("Fix extreme skew detection in Parallel Hash Join",
October 2024) is present in both versions tested; the test it fixed is the
one that does not fire here.

## Possible directions

Not tested, only listed: apply the 18 memory balancing to the parallel path
(count the per-participant accessor buffers against `space_allowed` and grow
the budget instead of `nbatch` when they dominate); relax the 100% test in
the DECIDE phase, as discussed in the 2019 thread; or stop growing when a
doubling reduces the largest batch by less than some fraction.

Browse pgsql-bugs by date

  From Date Subject
Next Message ZizhuanLiu X-MAN 2026-11-29 12:45:31 Re: BUG #19789: "expression not found in statistics object" for a boolean domain column in an MCV statistics object
Previous Message hi 2026-11-29 07:55:40 Removed left join leaves its key in the outer rel's target list