Repository navigation
Conversation
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.
…hash-partitioning Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
|
Workflow [PR], commit [ec1ac6c] AI ReviewSummaryThis 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 Findings❌ Blockers
Tests
Final VerdictChanges 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. |
…hash-partitioning
…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]>
`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]>
…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]>
…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]>
`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]>
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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.
…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]>
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]>
`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]>
…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]>
…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]>
…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]>
… with sorting" This reverts commit 8eb3808.
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); |
There was a problem hiding this comment.
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.
Related: #121848
Aggregate window functions over whole partitions (
PARTITION BYwithoutORDER BY, only aggregate functions) can be computed by hashing the partition keys instead of sorting, with the new settingquery_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
Windowplan 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
New setting
query_plan_window_functions_hash_partitioningcomputes aggregate window functions over whole partitions (PARTITION BYwithoutORDER BY) without sorting the input.Workflow [PR]
Sync PR [sync-upstream/pr/121865]