Skip to content

fix: reserve incoming aggregate state before merging - #27129

Open
yashdotrv wants to merge 7 commits into
apache:mainfrom
yashdotrv:fix/aggregate-state-reservation
Open

yashdotrv wants to merge 7 commits into
apache:mainfrom
yashdotrv:fix/aggregate-state-reservation

Conversation

@yashdotrv

@yashdotrv yashdotrv commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Part of #26705.

Rationale for this change

SELECT median(v) FROM generate_series(1, 30000000) with 4 target partitions and a 300 MB memory limit runs past the limit (656–939 MB peak RSS in #26705): the partial aggregate releases its reservation when it emits its state, and the final aggregate reserves memory only after merging it. This PR reserves each incoming state batch before merging it, so that query now returns ResourcesExhausted.

What changes are included in this PR?

  1. Reserve incoming state batches before merging in AggregateStream, FinalHashAggregateStream, and ClusteredFinalAggregateStream.
  2. A batch is charged only when its rows reference more than 1 KiB each on average (and 64 KiB in total), so ordinary batch_size-bounded state batches are not charged.
  3. Slices of a larger partial output are charged only for the bytes their rows reference via SpilledRowSizes.
  4. Dedicated unit tests for bounded batches, shared buffer slices, Single mode raw input, non-retaining aggregates, and deduplicated views.

Are these changes tested?

Yes, with new unit tests in aggregate_stream, hash_stream, and clustered_final_stream.

@github-actions github-actions Bot added physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt) and removed sqllogictest SQL Logic Tests (.slt) labels Nov 5, 2026
@yashdotrv
yashdotrv force-pushed the fix/aggregate-state-reservation branch from 1c93e8c to 0539bfb Compare November 5, 2026 19:20
@yashdotrv
yashdotrv marked this pull request as ready for review November 5, 2026 19:21
@jayzhan211
jayzhan211 self-requested a review November 7, 2026 02:06

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yashdotrv thanks for picking this up. Please correct the description, since most of the state is still unreserved and buffer growth is not the main cause. With the ignored #26705 cases in #26728 turned on, unreserved memory grows 121-124 MB for median (122-143 MB on main) and 500-505 MB for array_agg (531-589 MB), against a 16 MB bound. At the peak 19.1 MB of 152 MB is reserved for median, about one of the four partial states; the others appear to be queued in CoalescePartitionsExec.

A follow-up is fine because that queue is outside these streams, so #26705 should stay open. The description should also say that array_agg over 1000 groups at 30-60 MB goes from passing to ResourcesExhausted, while peak RSS at 100 MB stays near 610 MB.

@yashdotrv

Copy link
Copy Markdown
Contributor Author

@jayzhan211 ty for your review, I'll work on the suggestions and get back.

@yashdotrv
yashdotrv force-pushed the fix/aggregate-state-reservation branch from 0539bfb to a7850b7 Compare November 11, 2026 11:10
@yashdotrv

Copy link
Copy Markdown
Contributor Author

@jayzhan211 Thanks again for the review and detailed pointers! I have updated the branch with the requested changes:

  1. Per-Row Charging Threshold: Replaced the fixed 64 KiB threshold with MAX_IN_FLIGHT_STATE_BYTES_PER_ROW = 1024 and MIN_CHARGED_STATE_BATCH_BYTES = 64 * 1024. Normal bounded batches remain exempt, avoiding unnecessary spills/refusals on queries with many aggregates.
  2. Soft Limit Early Break: Kept the early break for soft group limit before try_resize in FinalHashAggregateStream.
  3. Spill Logic Cleanup: Extracted the duplicate spill-and-resize logic in FinalHashAggregateStream into a shared spill_table helper.
  4. Ungrouped Aggregate Guard: Guarded the calculation of incoming state batch memory in AggregateStream strictly to AggregateInputMode::Partial.
  5. Call Sequence Tests Restored: Restored aggregate_memory_call_sequence.rs to match main without edits; all 8 snapshot tests pass.
  6. Test Coverage:
    • Updated final_aggregate_reserves_incoming_state_batch and final_hash_reserves_incoming_state_batch to use 64-row sliced batches retaining multi-megabyte underlying buffers.
    • Added clustered_final_refuses_large_state_batch.
    • Added final_hash_spills_to_admit_large_state_batch.
    • Added clustered_final_spills_to_admit_large_state_batch to test the spill retry path under GroupClusteringMode::Partial(vec![0]).
  7. PR Description: Clarified that Partial aggregate state reaches the final aggregate without a memory reservation (median, array_agg) #26705 remains open for the queued partial states in CoalescePartitionsExec.

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yashdotrv thanks for the quick turnaround; every point from the first round is addressed. One new problem remains: the charge counts the whole buffer behind a zero-copy slice, so a grouped query without a hash repartition goes from passing to ResourcesExhausted. Details and a fix are inline on incoming_state_batch_reservation_bytes. The fix changes how the new tests should build their large state batch, so I've also asked for one more test there.

@yashdotrv
yashdotrv force-pushed the fix/aggregate-state-reservation branch from b1f2c29 to b8d1065 Compare November 21, 2026 18:59
@yashdotrv

Copy link
Copy Markdown
Contributor Author

@yashdotrv thanks for the quick turnaround; every point from the first round is addressed. One new problem remains: the charge counts the whole buffer behind a zero-copy slice, so a grouped query without a hash repartition goes from passing to ResourcesExhausted. Details and a fix are inline on incoming_state_batch_reservation_bytes. The fix changes how the new tests should build their large state batch, so I've also asked for one more test there.

@jayzhan211 Thanks for catching the zero-copy buffer slicing issue and for the detailed suggestions!

I have updated the PR and rebased against the latest main:

  1. Zero-Copy Slice Buffer Accounting:

    • In incoming_state_batch_reservation_bytes, added a fast check buffer_bytes <= in_flight_bytes.
    • When buffer_bytes > in_flight_bytes, we now measure the memory actually referenced by the slice's rows using SpilledRowSizes::new(batch). Slices of larger batches (e.g., when repartition_aggregations = false) will not double-charge the shared parent buffer that the producer already tracks.
  2. Realistic Test Payloads:

    • Updated existing unit tests to use payloads that genuinely exceed the per-row threshold (e.g. ListArray with 131k elements for array_agg, and large Utf8 strings).
  3. New Test Coverage:

    • final_hash_does_not_charge_buffers_shared_by_slices: verifies that 8,192-row slices from a 1M-group batch (16 MB buffer) are not over-charged and run cleanly.
    • final_aggregate_does_not_charge_bounded_state_batch: pins the per-row rule by asserting an 8,192-row batch of two Int64 states (128 KB) in a 96 KB pool is not charged.
    • single_aggregate_does_not_charge_raw_input: verifies that ungrouped Single mode over raw input (64 rows of 16 KB strings = 1 MB in a 512 KB pool) does not charge raw input batches.

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yashdotrv thanks for adopting every point from the last round. The 500k-group query without a hash repartition now passes at 40–80 MB again, and the 30M-row median at 300 MB is still refused. Two tests no longer reach the paths they are named for; the fixes are inline.

Optional: the Rationale opens with the mechanism, so a reviewer can't see the symptom from its first paragraph, and "What changes" doesn't mention the 1 KiB/row rule, which is the part that decides which batches are charged. Something like:

SELECT median(v) FROM generate_series(1, 30000000) with 4 target partitions and a 300 MB memory limit runs past the limit (656–939 MB peak RSS in #26705): the partial aggregate releases its reservation when it emits its state, and the final aggregate reserves memory only after merging it. This PR reserves each incoming state batch before merging it, so that query now returns ResourcesExhausted.

A batch is charged only when its rows reference more than 1 KiB each on average (and 64 KiB in total), so ordinary batch_size-bounded state batches are not charged. Slices of a larger partial output are charged only for the bytes their rows reference.

yashdotrv and others added 5 commits November 24, 2026 01:25
- Charge partial-state batches only when bytes per row exceed 1 KiB and total bytes exceed 64 KiB
- Restore early break on soft group limit before table memory resize in FinalHashAggregateStream
- Extract shared spill_table helper in FinalHashAggregateStream
- Guard incoming batch memory reservation calculation to Partial input mode in AggregateStream
- Replace synthetic tests with large-buffer retaining batches to properly test state batch admission
- Add test for ClusteredFinalAggregateStream spill-and-retry on partial clustering
- Add test for FinalHashAggregateStream spill-and-retry on large state batch
- Restore aggregate_memory_call_sequence.rs to match main
… aggregate

- Measure only bytes referenced by slice rows using SpilledRowSizes when buffer exceeds in_flight_bytes
- Add unit tests for bounded state batches, shared buffer slices, and Single mode raw input
- Update test cases to use realistic state payloads
@yashdotrv
yashdotrv force-pushed the fix/aggregate-state-reservation branch from b8d1065 to 5f65736 Compare November 23, 2026 19:55
@yashdotrv

Copy link
Copy Markdown
Contributor Author

@yashdotrv thanks for adopting every point from the last round. The 500k-group query without a hash repartition now passes at 40–80 MB again, and the 30M-row median at 300 MB is still refused. Two tests no longer reach the paths they are named for; the fixes are inline.

Optional: the Rationale opens with the mechanism, so a reviewer can't see the symptom from its first paragraph, and "What changes" doesn't mention the 1 KiB/row rule, which is the part that decides which batches are charged. Something like:

SELECT median(v) FROM generate_series(1, 30000000) with 4 target partitions and a 300 MB memory limit runs past the limit (656–939 MB peak RSS in #26705): the partial aggregate releases its reservation when it emits its state, and the final aggregate reserves memory only after merging it. This PR reserves each incoming state batch before merging it, so that query now returns ResourcesExhausted.
A batch is charged only when its rows reference more than 1 KiB each on average (and 64 KiB in total), so ordinary batch_size-bounded state batches are not charged. Slices of a larger partial output are charged only for the bytes their rows reference.

@jayzhan211 Thanks for the feedback! I've pushed an update addressing all points:

  1. Adjusted spill-and-retry memory pool limits:

    • In hash_stream.rs (final_hash_spills_to_admit_large_state_batch), reduced the pool to 2400 * 1024 so the batch does not fit alongside the table and triggers the spill-and-retry path.
    • In clustered_final_stream.rs (clustered_final_spills_to_admit_large_state_batch), reduced the pool to 2300 * 1024 for the same reason.
  2. Added non-retaining aggregate test (max):

    • Added final_aggregate_reserves_state_batch_it_does_not_retain using max_udaf(), confirming that only the up-front reservation refuses the 1 MB state batch in a 512 KB pool.
  3. Added shared deduplicated views test:

    • Added final_aggregate_does_not_charge_shared_view_bytes, testing 8,192 views of a 2 KB value with deduplicated strings (130 KB buffer, 16 MB counted row-by-row) to confirm the fast check prevents over-charging.

…uplicated states

- Lower memory pool sizes in hash_stream and clustered_final_stream tests to exercise the spill-and-retry path
- Add test verifying that up-front reservation refuses state batches even for non-retaining aggregates (max)
- Add test verifying that shared Utf8View values with deduplicated strings are not over-charged
@yashdotrv
yashdotrv force-pushed the fix/aggregate-state-reservation branch from b7fb5d3 to 142a800 Compare November 25, 2026 23:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

physical-plan Changes to the physical-plan crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants