Skip to content

Compute whole-partition window aggregates without sorting - #121865

Closed
raimannma wants to merge 29 commits into
ClickHouse:masterfrom
raimannma:window-functions-hash-partitioning
Closed

raimannma wants to merge 29 commits into
ClickHouse:masterfrom
raimannma:window-functions-hash-partitioning

Conversation

@raimannma

@raimannma raimannma commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Related: #121848

Aggregate window functions over whole partitions (PARTITION BY without ORDER BY, only aggregate functions) can be computed by hashing the partition keys instead of sorting, with the new setting query_plan_window_functions_hash_partitioning (off by default). The rows are scattered by the hash of the keys, aggregated per key, and the buffered rows spill to disk under the external sort thresholds.

2-5x faster on 60M rows with up to 200k keys. With many small partitions the hash table needs much more memory than sorting (3.6 GiB vs 0.7 GiB for 15M keys), so it stays off by default. The hash mode is serialized in version 1 of the Window plan step, which needs query plan serialization version 21. As with any bump of that version, replicas below it are not used for parallel replicas during a rolling upgrade.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

New setting query_plan_window_functions_hash_partitioning computes aggregate window functions over whole partitions (PARTITION BY without ORDER BY) without sorting the input.


Workflow [PR]
Sync PR [sync-upstream/pr/121865]

New setting `query_plan_window_functions_hash_partitioning` (off by default).
A window with `PARTITION BY` and no `ORDER BY`, whose frame covers the whole
partition and whose functions are all aggregates, is computed without
sorting: `WindowStep` scatters the rows by the hash of the partition keys, and
`PartitionAggregateTransform` aggregates per key and appends the results to
the buffered rows, which spill to disk under the external sort thresholds.
`max_rows_to_sort` / `max_bytes_to_sort` apply as for the sorting it replaces.

It is not used when the window sort would also serve a later window or the
final `ORDER BY`, for keys whose equal values may have different bytes
(`keyTypeBreaksHashSharding`), or with `make_distributed_plan`. Filter and
limit pushdown, per-partition reading and stream disjointness work as for
other windows. The hash mode is serialized in version 1 of the `Window` step,
which needs query plan serialization version 21.

2-5x faster on 60M rows with up to 200k keys. With many small partitions the
hash table needs much more memory than sorting (3.6 GiB vs 0.7 GiB for 15M
keys), so it stays off by default.
…version

`max_rows_to_sort` / `max_bytes_to_sort` are checked per stream, so a
hash-partitioned window keeps its scatter and does not request per-partition
reading when they are set, like the sorting it replaces.

Describe query plan serialization version 21 in the native protocol spec.
@clickhouse-gh clickhouse-gh Bot added comp-window-functions Window function execution + frame handling (ROW_NUMBER/RANK/LAG/LEAD, frames, partitions, order). external Author is not a member of the ClickHouse organization labels Sep 24, 2026
raimannma and others added 2 commits September 24, 2026 12:19
…sh-partitioning

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Sep 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ec1ac6c]


AI Review

Summary

This PR adds an experimental hash-partitioned execution path for aggregate windows over whole partitions, with the expected planner and serialization guards and broad correctness coverage for low-cardinality keys, cancellation, spilling, and downstream partition-disjoint consumers. The remaining issue is in the spill path of PartitionAggregateTransform: once spilling is triggered, the executor stops treating one-row partitions as temporary and materializes them into persistent aggregate groups, so high-cardinality workloads can still grow roughly one state per partition and exceed the memory bound that the external-sort settings are supposed to provide.

Findings
❌ Blockers
  • [src/Processors/Transforms/PartitionAggregateTransform.cpp:400-410] The !last branch of groupDeferred eagerly installs every deferred partition into state.map. consume reaches this branch immediately before spill() (groupChunks(/*last=*/ false) at src/Processors/Transforms/PartitionAggregateTransform.cpp), so a workload dominated by one-row partitions loses the single_row_group optimization as soon as it spills. A query such as sum(x) OVER (PARTITION BY number) with a low max_bytes_before_external_sort will therefore keep one persistent state per spilled partition and can still run into the query memory limit or OOM even though spilling is enabled.
    Suggested fix: preserve deferred one-row candidates across spill batches instead of materializing them into places, or add a spill representation that can remember those candidates and allocate real groups only once a partition is proven to have multiple rows.
Tests
  • Existing stateless coverage checks spilled correctness, but it does not cover the high-cardinality spill case above. A focused regression should force spilling on mostly-one-row partitions and assert that the no-group path still survives spill batches (or at least that memory remains bounded).
Final Verdict

Changes requested. The spill path still defeats the PR's key memory optimization on exactly the high-cardinality workloads that are most likely to rely on external spilling.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 28, 2026
Comment thread src/Planner/Planner.cpp Resolved
raimannma and others added 3 commits September 28, 2026 18:12
…ow sort when it covers the final `ORDER BY`

- Include `WindowFunctions/IWindowFunction.h`, the new location of the window function interface after the merge of master.
- Fix `cppcoreguidelines-init-variables` and `performance-move-const-arg` in `PartitionAggregateTransform`.
- Do not use hash partitioning when the final `ORDER BY` is a prefix of `PARTITION BY`: the window sort already provides the query order, and hash partitioning would add a full extra sort.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/121865/34220298d05d662ca8c645905c6290cdcd61c411/pr/build_arm_tidy/build_clickhouse/build_clickhouse.log
PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Planner/Planner.cpp Resolved
`query_plan_reuse_storage_ordering_for_window_functions` lets `optimizeReadInOrder` read in the order of
the sorting key instead of sorting for a window, but that decision is made later, on the `SortingStep`.
Hash partitioning removes this step, so a query over a `MergeTree` table ordered by the partition key
would build a hash table instead of reading in order. Keep the sort whenever that optimization is enabled.

The setting is randomized by `clickhouse-test`, so the test disables it except for the new case.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
…f `PartitionAggregateTransform`

The spill was triggered only by the size of the buffered rows, but with many partitions the key arena,
the hash table and the aggregate states can take most of the memory. They cannot be spilled, but they now
count towards `max_bytes_before_external_sort`, so that the buffered rows are spilled earlier.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
raimannma and others added 4 commits September 28, 2026 21:22
…h partitioning with one thread

With a single thread the sort for a window does not scatter the input, so it checks `max_rows_to_sort`
and `max_bytes_to_sort` on every input stream and merges them afterwards. Hash partitioning merged the
streams first, so a query could fail the limits only with `query_plan_window_functions_hash_partitioning`.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…itionAggregateTransform`

Found by a local `codex review`:
- Every spill appended to one temporary file whose disk space was reserved only on the first spill, so
  later spills ignored `min_free_disk_space_for_temporary_data`. Write a file per spill, like
  `MergeSortingTransform`, each with its own reservation.
- The group of a row is stored as `UInt32`, so more than 2^32 partitions in one stream silently merged
  unrelated partitions. Throw an exception instead.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…of windows and speed up its test

Windows with equal sort descriptions came to `addWindowSteps` in an arbitrary order: they are collected
from an `unordered_map`, and `sortWindowDescriptions` used an unstable `::sort`, which shuffles in debug
builds. When a window eligible for hash partitioning came first, it used hash partitioning and the next
window added its own sort; in the other order both windows shared one sort. Now the windows that need a
sort are put first and `sortWindowDescriptions` keeps the order of equal ones, so the eligible windows
reuse that sort. The condition for hash partitioning is shared between the reordering and the planning.

`05243_window_functions_hash_partitioning` ran more than 180 seconds in the flaky check with ASan,
because it started the client three times per query. The queries are now run with two client invocations.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121865&sha=8c8dc01df51938261a416f58507f1f183a1b746d&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ntly and in a serialized query plan

`05291_window_functions_hash_partitioning_partitions_independently` checks that the scatter of a
hash-partitioned window is skipped when the table partition key is determined by the window `PARTITION BY`
columns, that it is kept otherwise and with sort limits, and that the results match sorting, also with
`DISTINCT` and other windows after it.

`05292_window_functions_hash_partitioning_serialize_query_plan` checks that a hash-partitioned `WindowStep`
shipped to a remote shard with `serialize_query_plan` is computed by `PartitionAggregateTransform` on the
shard, keeps the spill settings, and returns the same result as sorting.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
`WindowStep::deserialize` ignored the hash partitioning flag in step version 0 and any unknown flag bit, so
a received plan could build a step with another execution contract than the sender planned. Now it throws
`CORRUPTED_DATA`, like `LimitRangeStep`, `LimitByStep` and `NegativeLimitStep`.

Also explain why the limits of the hash-partitioned window force `OverflowMode::THROW`: the sorting for a
window in `addWindowSteps` does the same, because `sort_overflow_mode = 'break'` would compute the windows over
incomplete partitions.

Review: ClickHouse#121865 (comment)
PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bba9a890e with master 001b6e36e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

19 object files changed (+365.59 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/PartitionAggregateTransform.cpp.o new 290.07 KiB +290.07 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/WindowStep.cpp.o 216.53 KiB 266.95 KiB +50.42 KiB (+23.29%)
src/CMakeFiles/dbms.dir/Planner/Planner.cpp.o 776.65 KiB 792.93 KiB +16.29 KiB (+2.10%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

301 translation units recompiled, 2658 s compile time in total, 300 of them have a recent master baseline.

Job report

raimannma and others added 3 commits September 29, 2026 12:02
…ning`

It compares the sorting and the hash partitioning for aggregate window functions over whole partitions,
from 100 partitions to one for every row, with a `String` key, several keys and wide rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With many partitions, the hash partitioning was slower than sorting, down to 0.33x with a partition for
every row, because a table of all partitions takes a cache miss for most rows and grows through every size.
Now:

- Fixed-size keys are packed into an integer of up to 32 bytes, column by column, and a single `String`
  key is used as it is, instead of serializing every key.
- Up to 65536 partitions, the rows are grouped as they come. With more, the later rows are put into 256
  buckets by the hash of their key and grouped at the end one bucket at a time, in a small table that is
  reused. Their groups are created at once, in the order of the rows.
- A partition of one row takes no group: its row is aggregated when it is output, in a state that is reused.
- With a row or two in each partition, the results are taken for each row from the states instead of being
  copied from the results of the partitions; variable-size results are copied a value at a time.
- The states that own memory take the rows of a partition at once with `addBatchSinglePlace`, like in
  `WindowTransform`, when there are many rows in each of not many partitions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Use `DefaultHash` for the packed keys, which does not xor the words of a wide integer, and
`Memory::alignUp` for the layout of the states. Take the arguments of the functions in one place, destroy
the states in one place, create a single group with `createGroups`, keep the buckets of the deferred rows
outside of the templated state, and look for the rows of partitions of one row only when there are such
partitions. Copy only arrays, and not strings, a value at a time into the results, and keep the key columns
of the deferred chunks only for a `String` key, whose bytes point into them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
raimannma and others added 2 commits September 29, 2026 12:26
So that `allow_feature_tier` can forbid it while the new aggregation, buffering and spilling of the windows
is rolled out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…test

The test now has partitions grouped as the rows come and at the end in buckets, partitions of one and two rows,
`String` keys used as they are, keys packed into 16 and 32 bytes and serialized keys, states that take the rows
of a partition at once, and a result that is an array.

The results are taken for each row also with exactly two rows in each group, and the rows of partitions of one
row, which have no group, no longer count against it: with two rows in each partition it was 10% slower than
sorting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Planner/Planner.cpp Resolved
raimannma and others added 3 commits September 29, 2026 15:30
`DataTypeLowCardinality` of a number passes
`isValueUnambiguouslyRepresentedInFixedSizeContiguousMemoryRegion`, so the key
was packed as a fixed-size key, but its column stayed `ColumnLowCardinality`
and `packKeys` read it as a `ColumnFixedSizeHelper`: a segmentation fault in
the AST fuzzer, or wrong partitions. The key types and columns are now
stripped of `LowCardinality`, like the arguments of the functions.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121865&sha=bba9a890e1b97eb626257e18d56db88937a579cc&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`generate` grouped all deferred rows and made the results of all partitions
in one call, without checking `isCancelled`, so `KILL QUERY` or a client
disconnect waited until the whole phase finished (2.7 s instead of 0.26 s on
100 million partitions in an ASan build). The grouping of `groupChunks` with
`last` and the results of the partitions now stop when the query is cancelled.
The grouping as the rows come is not interrupted, as `spill` writes the groups
of all buffered chunks.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`rows_of_new_groups` was a `UInt32` count of the rows of each new partition,
only compared with one: a partition of 2^32 + 1 deferred rows wrapped around
to one and each of its rows was aggregated on its own. It is now a flag of
whether the partition has one row, which also takes a byte instead of four.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
…keep `LowCardinality` in serialized keys

A serialized plan could set the hash partitioning flag of a `WindowStep` for a
window that `canUseHashPartitioning` rejects, such as one with `ORDER BY`; it is
now rejected with `INCORRECT_DATA`.

`PartitionAggregateTransform` removed `LowCardinality` from all its keys, so
`groupDeferred` kept a materialized `String` column of every buffered chunk for a
`LowCardinality(String)` key, which was not counted towards the spill threshold.
Only the packed keys need plain columns now: the serialized keys are read from
the dictionaries.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
raimannma and others added 3 commits September 29, 2026 17:54
…hunk

`SingleRowStates` aggregated into the arena of `PartitionAggregateTransform`,
which lives until the end of the query, so an aggregate that allocates in the
arena, such as `groupArray`, kept memory for every partition of one row. They now
have an arena of their own, freed with them. For
`groupArray(n) OVER (PARTITION BY n)` over 20M rows the peak memory usage drops
from 693 MiB to 499 MiB, the same as `sum`.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…form`

The results were taken for each row from the states when the groups had two
rows or less on average, and in every chunk with a partition of one row, so a
large partition next to many partitions of one row was finalized for each of its
rows: `quantileExact(0.5)(number) OVER (PARTITION BY if(number < 50000, 0, number))`
over 100000 rows took 0.49 s instead of 0.005 s with sorting, quadratic in the
size of the partition.

Now the results are taken for each row only while no group has more than two
rows, which `aggregateChunk` tracks with a counter of up to three rows for each
group. Otherwise, the rows of partitions of one row take their results from
their states, and the other rows from the results of their groups. The query
above takes 0.007 s; the other queries of the performance test are unchanged.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e less memory

`uniqExactState(x) OVER w` is copied for each row of its partition, also with
sorting, so the partitions of tens of thousands of rows took a state of up to
1000 values for each row, and the sorting query exceeded the memory limit in CI.
The state now takes `x % 5`: the test takes 122 MiB at most.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121865&sha=b6fb696d69f31babf199ab5dc9a5a01dfdb4e65a&name_0=PR
PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Planner/Planner.cpp Resolved
raimannma and others added 3 commits September 29, 2026 19:41
…rting

`query_plan_enable_multithreading_after_window_functions` resized the streams
after the last window only with `WindowTransform`. The hash-partitioned window
kept the streams it had, which are fewer than the threads if the scatter is
skipped for partitions read independently, and uneven with skewed partitions.
It is now resized like the sorted one.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The streams after the hash-partitioned window hold whole partitions, and the
steps after it rely on that: resizing them after the last window, as the reverted
commit did, made `DISTINCT` return 80 rows instead of 10.

PR: ClickHouse#121865

Co-Authored-By: Claude Opus 5.5 <[email protected]>
{
const size_t hash = get_hash(i);
if constexpr (is_serialized<Map>)
groups[i] = emplaceGroup(state.map, ArenaKeyHolder{keys[i], arena}, hash);

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.

When consume hits the spill threshold it first calls groupChunks(/*last=*/ false), which lands here in the !last branch and eagerly installs every deferred partition into state.map. On a high-cardinality query where most partitions have one row, that turns each spill batch into another permanent places / arena entry.

The single_row_group optimization below only applies to partitions that survive deferred until last = true, so a query like sum(x) OVER (PARTITION BY number) with a low max_bytes_before_external_sort still grows roughly one persistent state per spilled partition and can hit the query memory limit or OOM despite spilling. I think this needs a spill path that preserves deferred one-row candidates across spill batches instead of materializing them into full groups, plus a regression that forces spill on mostly-one-row partitions.

@raimannma raimannma closed this Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-window-functions Window function execution + frame handling (ROW_NUMBER/RANK/LAG/LEAD, frames, partitions, order). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants