Skip to content

fix: reserve hash aggregate group table growth before it happens - #27645

Draft
adriangb wants to merge 8 commits into
apache:mainfrom
adriangb:agg-reserve-before-group-growth
Draft

adriangb wants to merge 8 commits into
apache:mainfrom
adriangb:agg-reserve-before-group-growth

Conversation

@adriangb

@adriangb adriangb commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

  • No issue is filed yet. I can file one before this leaves draft.

Rationale for this change

A high-cardinality GROUP BY can use far more memory than its memory limit, and under a hard memory cap the process gets OOM-killed.

The hash aggregate streams reserve memory for their group table only after they aggregate a batch. When a batch makes the group hash table grow, hashbrown allocates the new table before it frees the old one, so the heap briefly holds both. The pool never sees that peak. The stream spills afterwards, but the memory is already allocated. With several partitions growing at once, the process goes well past the pool limit.

MRE in stock datafusion-cli (Linux, 8 partitions, --memory-limit 2g, FairSpillPool):

SET datafusion.execution.target_partitions = 8;
SELECT count(*) FROM (SELECT value % 20000000 AS k, count(*) AS c
  FROM generate_series(1, 40000000) GROUP BY k);
sudo systemd-run --scope -p MemoryMax=1200M -p MemorySwapMax=0 --uid=$(id -u) \
  /usr/bin/time -v datafusion-cli --memory-limit 2g --mem-pool-type fair -q -f q1.sql
MemoryMax main this PR
none OK, max RSS 1465 MB OK, max RSS 1067 MB
1300M killed (SIGKILL) OK
1200M killed (SIGKILL) OK
1100M killed (SIGKILL) OK

With a counting allocator, the heap peak of this query on main is about 1.9× the pool's tracked peak (1016 MB against 530 MB). With this PR, it is about 0.95×.

What changes are included in this PR?

Read the PR commit by commit. Each commit builds and passes tests on its own, except commit 5. Commit 5 fails the call-sequence snapshots, and commit 6 updates them.

# Commit Kind
1 e3980c8 move CountingAllocator from sqllogictest to datafusion_execution::memory_pool::counting_allocator mechanical move. The module is #[doc(hidden)] and for internal use only.
2 a01c6a8 add ThreadPeak, an exact per-thread peak, to that allocator test helper
3 62d8dbb split aggregate_batch into evaluate_batch and aggregate_evaluated refactor, no behavior change
4 ab4ae31 GroupValues::max_intern_growth and max_intern_growth_for, and the growth bounds in growth.rs new API, no callers yet
5 9bbfe97 the Partial, PartialReduce, Final and Single streams reserve memory_size() + growth before each batch the fix and its regression test
6 085314e update the aggregate_memory_call_sequence snapshots mechanical

In commit 5, a stream that the pool refuses spills or emits early first. After the batch, it shrinks the reservation to the actual size, as before. If spilling is disabled, a refused pre-check does not fail the query. The check after the batch decides.

Review tip: start with group_values/growth.rs, which has the model and its ASCII diagram, then AggregateHashTable::max_evaluated_growth, then the four stream call sites.

Not covered:

  • Accumulator growth: GroupsAccumulator does not report its capacity.
  • The value buffers of GroupValuesRows and GroupValuesColumn. Only their hash tables are bounded.
  • The clustered streams.
  • The legacy GroupedHashAggregateStream.

What is the testing strategy for this PR?

  • growth.rs unit tests compare the bound with the measured old + new allocation sizes while a table and a Vec grow. The bound is exact where hashbrown uses SSE2 groups, and at most 16 bytes high elsewhere.
  • intern_growth_for_existing_keys_is_zero fills a table to capacity. Existing keys give a bound of 0, and one new key gives exactly one doubling.
  • The new integration test reservation_covers_group_table_growth counts heap per thread and checks that the pool peak covers the doubling. On main it fails: heap peak 2004319 bytes against a reserved peak of 1572976 bytes.
  • The aggregate_memory_call_sequence snapshots gain the pre-batch try_grow and shrink calls. spills_twice_then_replays needs 40 KB instead of 39 KB to keep its two spills.

Performance: no criterion benches yet. In the worst case, where every batch sits within one batch of a table doubling (1 partition, 29.4 M groups), wall time is 4.1 s against 3.7 to 3.8 s on main. On the MRE above, wall time is unchanged. I will run the aggregate benches before this leaves draft.

Are there any user-facing changes?

Queries with a high-cardinality GROUP BY stay closer to the memory limit. They may spill slightly earlier.

GroupValues is a public trait. It gains max_intern_growth and max_intern_growth_for, both with default implementations, so this is not a breaking change.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the physical-plan Changes to the physical-plan crate label Nov 21, 2026
adriangb and others added 6 commits November 22, 2026 17:43
The aggregate peak memory test in datafusion-physical-plan needs a counting
global allocator. The only one lives in datafusion-sqllogictest, which other
crates cannot depend on. This commit moves it, unchanged, to
`datafusion_execution::memory_pool::counting_allocator`, next to the drift
tracker that consumes its count. The module is `#[doc(hidden)]` and is marked
for internal use only, per the API health policy.

This is a mechanical move. sqllogictest re-exports the same items.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A test that checks a memory reservation against real allocations needs the
peak of one thread, exact to the byte. The process-wide count flushes per
thread only every 256 KB, and tests that run in parallel mix in it.

This commit adds an exact per-thread live count and peak, and `ThreadPeak`
to read them. A realloc raises the peak as a copy, because the new block is
live before the old block is freed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A stream that reserves a batch's peak memory before it aggregates needs the
evaluated group keys first, so that it can bound the growth from the keys.
`aggregate_batch` evaluates and aggregates in one call, so a stream has no
point in between.

This commit replaces `aggregate_batch` on the four hash tables with
`aggregate_evaluated`, and makes the streams call `evaluate_batch` first.
It changes no behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A growing hashbrown table or `Vec` allocates its new storage before it frees
the old storage, so for a moment both are live. A stream that reserves only
after `GroupValues::intern` never shows this peak to the memory pool.

This commit adds `hash_table_growth` and `vec_growth`, which simulate the
growth steps and return the largest number of bytes above the current
allocation. It adds `GroupValues::max_intern_growth` and
`GroupValues::max_intern_growth_for`, with implementations for the primitive,
row and column group values. The primitive implementation counts only the
keys that the table does not store yet, so a batch of existing keys reserves
no growth. The tests check each bound against the measured peak.

Nothing calls the new methods yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The hash aggregate streams call `intern` and then `try_resize`. When the
group hash table grows, it holds the old and the new table at the same time,
so the memory pool never sees the peak. With 8 partitions and a 2 GB fair
pool, the heap peak was 1.9 times the tracked peak.

Each stream now evaluates a batch, reserves `max_evaluated_growth` above the
table's size, and only then aggregates. When the reservation fails, the
stream does what it does after a batch today: Final and Single spill, and
Partial and PartialReduce emit early. The spill headroom (one `u32` per new
group) is part of the reservation.

The new test runs 4 batches of distinct keys in Single and Partial modes.
It checks the per-thread heap peak against the pool's peak reservation.
Without this fix it fails with a heap peak of 2004319 bytes against
1572976 reserved bytes.

The call-sequence snapshots change because of this commit. The next commit
updates them on their own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The streams now reserve a batch's growth before they aggregate it. So the
recorded sequences gain a `try_grow` before each batch, and a refusal can
come one call earlier. `spills_twice_then_replays` needs a limit of 40000
bytes instead of 39000 to still spill twice.

This is a mechanical snapshot update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@adriangb
adriangb force-pushed the agg-reserve-before-group-growth branch from 3f9552a to 085314e Compare November 23, 2026 15:12
@github-actions github-actions Bot added sqllogictest SQL Logic Tests (.slt) execution Related to the execution crate labels Nov 23, 2026
…reserve-before-group-growth

# Conflicts:
#	datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs
#	datafusion/physical-plan/src/aggregates/group_values/row.rs
#	datafusion/physical-plan/src/aggregates/group_values/single_group_by/primitive.rs
# Conflicts:
#	datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

execution Related to the execution crate physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant