Repository navigation
Compute projection expressions before window functions in the analyzer - #126062
yakov-olkhovskiy wants to merge 9 commits into
Conversation
With the analyzer, the window step buffered the columns read by the projection
expressions, because the whole projection was computed after the window
functions. For `SELECT toUInt64OrZero(splitByString('@', s)[2]), count() OVER ()`
the window step buffered the `String` column `s` instead of a `UInt64`, which
increased the peak memory usage about ten times compared with the old query
analysis, which computed such expressions before the window functions.
Now the largest subexpressions of the projection that do not depend on window
functions are computed in a separate step right before the window step.
Expressions with `arrayJoin`, stateful functions, subqueries or correlated
columns are not moved, nor are expressions of queries with `QUALIFY`. The step
is executed on the initiator together with the window functions, so the header
of the blocks sent by shards does not change.
Co-authored-by: yakov <[email protected]>
|
|
|
Workflow [PR], commit [b9e5109] Summary: ❌
AI ReviewSummaryThe PR reduces window-query memory by computing bounded projection expressions before Findings❌ Blockers
Final VerdictStatus: ❌ Block. Correct the remaining memory accounting and bound the planning overhead, with focused regression coverage. The previous distributed-test finding is addressed and its thread has been resolved. |
| bool depends_on_columns = false; | ||
| if (canBeComputedBeforeWindow(node, correlated_columns_set, depends_on_columns)) | ||
| { | ||
| if (depends_on_columns) | ||
| result.push_back(node); |
There was a problem hiding this comment.
[P1] Avoid unconditionally buffering expanding projection results
Column dependence does not imply that computing the expression early reduces memory. This also selects expanding expressions, making an unbounded window retain their full results instead of a small input column. On the PR's Fast Test binary:
SELECT repeat('a', 2048 + number % 2) AS s, count() OVER () AS n
FROM numbers(100000)
SETTINGS max_block_size = 1024, max_threads = 1,
max_memory_usage = 50000000
FORMAT Null;This now fails with MEMORY_LIMIT_EXCEEDED. Adding the tautological QUALIFY n > 0 keeps the projection after the window and succeeds under the same limit. The new step makes the window buffer roughly 205 MB of strings rather than 0.8 MB of numbers; previously those strings could be generated one output block at a time. Add a volume/cost guard or another default-safe way to retain expanding expressions after the window, with a focused memory regression case.
There was a problem hiding this comment.
The haveMaximumSizeOfValue check added in 123c80ec at src/Planner/PlannerExpressionAnalysis.cpp:415 still admits an expanding result: FixedString(2048) has a maximum size, even when its input strings contain one byte.
SELECT toFixedString(s, 2048) AS r, count() OVER () AS n
FROM (SELECT toString(number % 10) AS s FROM numbers(100000))
FORMAT Null
SETTINGS max_memory_usage = '50M', max_block_size = 1024, max_threads = 1;This still throws MEMORY_LIMIT_EXCEEDED on the current head's Fast Test binary. The official master binary succeeds under the same limit; adding QUALIFY n > 0 on the PR binary also succeeds. The window now retains about 205 MB of results instead of the small source strings. The guard needs to bound the actual expansion, including large FixedString and fixed-size tuples; boundedness alone does not establish a reduction.
There was a problem hiding this comment.
Addressed in 5780296 (the first part, repeat, in 123c80e). Boundedness of the result alone is no longer enough. An expression is moved only if the maximum size of its result is not larger than a lower bound of the size of the values it frees up: 8 bytes (the offset) for each distinct String, Array or Map column or aggregate result it reads, plus 1 for Nullable. LowCardinality and other types count as 0. So toUInt64OrZero(s) (8 <= 8) still moves, while toFixedString(s, 2048), repeat(...), a large tuple, or a UUID from a single string stay after the window. Your FixedString(2048) query now succeeds under 50M, and both it and the repeat case are in the test.
There was a problem hiding this comment.
The guard in 57802968 still permits the original buffering regression: src/Planner/PlannerExpressionAnalysis.cpp:440-444 credits an input even when it is retained by the projection, and credits the same input separately for each selected expression.
SELECT s, toUInt64OrZero(s), count() OVER () AS n
FROM (SELECT toString(number % 10) AS s FROM numbers(2000000))
FORMAT Null
SETTINGS max_memory_usage = '80M', max_block_size = 1024, max_threads = 1;On the current head's Fast Test binary, this throws MEMORY_LIMIT_EXCEEDED; the official master binary succeeds. Here the window must still retain s, so moving the conversion adds an eight-byte column without freeing its input.
Even when the input can be dropped, SELECT length(s), sipHash64(s), cityHash64(s), xxHash64(s), count() OVER () AS n FROM (SELECT toString(number % 10) AS s FROM numbers(1000000)) FORMAT Null SETTINGS max_memory_usage = '50M', max_block_size = 1024, max_threads = 1 fails on the PR and succeeds on master. Adding QUALIFY n > 0 on the PR also succeeds. All four results independently consume the same eight-byte input budget, producing 32 bytes per row instead of one small String.
The size guard needs to compare the complete set of retained inputs and selected outputs, crediting an input only once and only if it is actually removed from the window's input.
There was a problem hiding this comment.
Addressed in 9a1eec7. The check is no longer made per expression.
collectInputsReadAfterWindowcollects the columns and aggregate results read after the window step by anything except the candidate expressions: the projection,ORDER BY,INTERPOLATE,LIMIT BY, and the arguments andPARTITION BY/ORDER BYof the window functions, which the window step buffers anyway. Only an input not in this set is credited as freed.- Candidates that read common inputs are grouped and moved or kept together. Each freed input is credited once, and the group moves only if the sum of the maximum sizes of its results does not exceed the lower bound of the freed inputs.
Both of your queries now succeed under the same limits, as on master, and both are in the test. In the first, s is still read, so nothing is freed. In the second, 4 × 8 bytes is more than the 8 bytes freed. The original toUInt64OrZero(splitByString('@', c2)[2]) case is still moved.
There was a problem hiding this comment.
src/Planner/PlannerExpressionAnalysis.cpp:377–380 in 5bb4e168 still permits the original retained-allocation regression through an identity CAST. Resolution stops at the projection's function node, so s and CAST(s AS String) receive different input identities even though createIdentityWrapper returns the same column allocation (src/Functions/FunctionsConversion.h:6092).
SELECT s, length(t) AS h, count() OVER () AS n
FROM
(
SELECT toString(number % 10) AS s, CAST(s AS String) AS t
FROM numbers(1000000)
)
FORMAT Null
SETTINGS max_memory_usage = '48M', max_block_size = 1024,
max_threads = 1;The current head's Fast Test binary throws MEMORY_LIMIT_EXCEEDED while executing length(t). Adding QUALIFY n > 0 before FORMAT disables the new step and succeeds. Without the memory limit, the peaks are 49.64 MiB and 41.62 MiB respectively. The plan confirms that the new step buffers both s and length(t); removing t releases no string allocation. toNullable and assumeNotNull wrappers also preserve shared storage and show the same accounting gap. The budget must establish that the underlying allocation is actually freed, or decline to credit inputs whose sharing cannot be established; please cover the identity-cast case with a regression test.
There was a problem hiding this comment.
Addressed in 3e00e1b. Functions that can return their argument's memory cannot be listed, so the accounting no longer tries to prove what is freed, and it fails closed.
collectBaseColumnscollects the base columns of every value: the table columns and aggregate results it is computed from, following subquery projections (recursively) andALIAScolumn expressions.- A value is credited as freed only if none of its base columns is a base column of anything read after the window step, or of another value already credited.
- A value without base columns (for example
materialize('a')) is not credited. - Candidates with common base columns are grouped and moved or kept together.
Two values can share memory only if they are computed from a common source, so CAST(s AS String), toNullable(s) and assumeNotNull(s) are all handled: t has the same base column as s, which is still read, so nothing is credited. Your query and the toNullable and assumeNotNull variants succeed under 48M, as on master, and all three are in the test. The original case (a table column or a subquery string read by nothing else) is still moved.
There was a problem hiding this comment.
src/Planner/PlannerExpressionAnalysis.cpp:451 in 3e00e1b0 still permits the original buffering regression for an ordinary-function GROUP BY key. The recursion descends through the already-computed toUInt32(s) key and credits the original String at line 665, although aggregation has removed that string from the window's input.
SELECT sipHash64(toUInt32(s)) AS h, count() OVER () AS n
FROM (SELECT toString(number) AS s FROM numbers(2000000))
GROUP BY toUInt32(s)
FORMAT Null
SETTINGS max_threads = 1, max_block_size = 1024,
max_bytes_before_external_group_by = 1000000;On this head's Fast Test binary, EXPLAIN actions = 1, compact = 0, pretty = 0 shows that the new step replaces the four-byte UInt32 grouping key with the eight-byte UInt64 hash below Window. Adding QUALIFY 1 keeps the hash above Window and introduces no surviving filter. The measured peaks are 72.99 MiB and 65.88 MiB, respectively.
Treat available post-aggregation grouping expressions as atomic input columns, like aggregate results, and budget their actual types instead of their original arguments. Please add a regression case for this boundary.
There was a problem hiding this comment.
Addressed in b9e5109. The grouping keys (including those of GROUPING SETS) are now, like the aggregate function results, inputs of their own type.
- A projection subtree equal to a key is not descended into.
- Its credit comes from the key's type, so a fixed-size key such as
toUInt32(s)gives none. - It is its own base column when checking what is still read after the window step.
This fails closed: in a query with aggregation, an expression that reaches a column outside of the matched keys and the aggregate functions is not moved. For example, a key whose type is changed by group_by_use_nulls does not match.
Your query now keeps sipHash64 above Window, with the same peak as master (65.17 MiB here). The test checks this plan. It also checks that length of a String key (GROUP BY concat(s, 'x')) is moved, because the key itself is freed, and that both queries give the same results as master.
There was a problem hiding this comment.
The retained-allocation/expansion regression is still reproducible on b9e51096 through two remaining representations:
src/Planner/PlannerExpressionAnalysis.cpp:368–370stops lineage resolution at aUnionNode, and lines 569–571 consequently treat its output columns as independent base allocations.UNION ALLcan preserve the sharing between aliases in each branch:
SELECT s, length(t) AS h, count() OVER () AS n
FROM
(
SELECT toString(number % 10) AS s, s AS t FROM numbers(500000)
UNION ALL
SELECT toString(number % 10) AS s, s AS t FROM numbers(500000)
)
FORMAT Null
SETTINGS max_block_size = 1024, max_threads = 1,
max_memory_usage = 50000000;The current head's Fast Test binary throws MEMORY_LIMIT_EXCEEDED while executing length; adding QUALIFY n > 0 before FORMAT succeeds. Without the limit, peak memory is 52,097,439 versus 47,891,535 bytes. The plan confirms that the moved expression buffers length(t) alongside the retained s. Unknown lineage across a union therefore needs conservative treatment or per-branch sharing analysis.
- Line 511 uses
getMaximumSizeOfValueInMemoryas a bound on buffered column storage, butLowCardinality(UInt64)reports 8 while also retaining its dictionary and indexes:
SELECT toLowCardinality(toUInt64OrZero(s)), count() OVER () AS n
FROM (SELECT toString(number) AS s FROM numbers(1000000))
FORMAT Null
SETTINGS max_block_size = 1024, max_threads = 1,
max_memory_usage = 56000000;This also throws MEMORY_LIMIT_EXCEEDED on the current binary and succeeds with QUALIFY n > 0. Unrestricted peaks are 60,563,190 versus 52,052,141 bytes; both conversions move below Window. Exclude such result representations unless the budget includes their actual storage overhead. Please cover both cases with focused regression tests.
The test checks that the window step does not buffer the column read only by a projection expression (the query fails with `MEMORY_LIMIT_EXCEEDED` without the fix), that the plan computes the expression below the `Window` step, and that the results of queries with `arrayJoin`, stateful functions, `QUALIFY`, `GROUP BY`, lambdas, `IN`, `DISTINCT` and `remote` are the same as before. Co-authored-by: yakov <[email protected]>
Build profile diff (arm_release)No arm_release build profile data for commit 5bb4e16 - the build was skipped, reused from cache, or predates profile upload. |
…dow functions Address the review of #126062: - The arguments of short-circuit functions that may be executed lazily were moved before the window step when the function itself depends on a window function, so `if(count() OVER () = 0, intDiv(1, number), 0)` threw `ILLEGAL_DIVISION`. Now only the arguments that are always executed are considered, and none of the arguments of `and` and `or`. - `blockSize` and other functions that are not deterministic in the scope of the query observed the blocks before the window step. They are not moved now. - An expression whose result is larger than its input, such as `repeat`, made the window step buffer the larger values. Now an expression is moved only if it reads a column of unbounded size (`String`, `Array`, ...) and its result has a maximum size, so the buffered values can only become smaller. Co-authored-by: yakov <[email protected]>
… or if they can expand Address the review of #126062: - A result type with a maximum size can still be larger than its input, as `toFixedString(s, 2048)` of a one-byte string. Now an expression is moved only if the maximum size of its result is not larger than the smallest possible size of the values of the `String`, `Array` and `Map` columns it reads (their offsets), so the buffered values can not become larger. - With `LIMIT`, the projection after the window step may be computed only for the first blocks of the result, so moving it before the window step computed it for all rows: `SELECT toUInt64(s), count() OVER () ... LIMIT 1` threw on a row that was not returned. The expressions are not moved in queries with `LIMIT`. Co-authored-by: yakov <[email protected]>
… before it Address the review of #126062: - The size check was made for each expression separately, so an input column was credited even if it was still read after the window step (`SELECT s, toUInt64OrZero(s), count() OVER ()`), and the same input was credited for each expression that reads it (`length(s), sipHash64(s), cityHash64(s), xxHash64(s)`). Now an input is credited only if nothing else reads it after the window step (the projection, `ORDER BY`, `INTERPOLATE`, `LIMIT BY`, the arguments of the window functions), and the expressions that read common inputs are moved or kept together, comparing the sum of their result sizes with the inputs they free. - `LIMIT AFTER` and `LIMIT UNTIL` are excluded like `LIMIT`. Co-authored-by: yakov <[email protected]>
…ions before window functions Address the review of #126062: - The columns of a subquery that are aliases of each other (`SELECT s, s AS t`) were credited as separate values, and a constant column (`'a' AS t`) was credited as a `String`. Now a column of a subquery is resolved to its projection expression in the subquery, so aliases are credited once and are considered read after the window step if any of them is, and constant columns are not credited. - Functions with observable side effects (`sleepEachRow`) depend on blocks and are not moved before the window step. Co-authored-by: yakov <[email protected]>
… window step Address the review of #126062: An identity `CAST`, `toNullable` or `assumeNotNull` in a subquery returns a column that shares memory with its argument, so moving `length(t)` for `CAST(s AS String) AS t` freed nothing while `s` was still read. Such wrappers can not be listed, so now the base columns of every value are collected: the columns of tables and the aggregate results it is computed from, following subquery projections and `ALIAS` columns. A value is credited as freed only if none of its base columns is a base column of a value read after the window step or of another credited value, and a value without base columns is not credited. Co-authored-by: yakov <[email protected]>
…ibuted query Address the review of #126062 (#126062 (comment)): the existing `remote` case did not move anything, because `row_number() OVER (ORDER BY s)` keeps `s` read after the window step. The new case has a single bounded projection with `count() OVER ()`, and checks in the plan that the expression is computed in the "Projection before window functions" step above `ReadFromRemote`, whose header is still the `String` column. Co-authored-by: yakov <[email protected]>
…re window functions Address the review of #126062: after `GROUP BY toUInt32(s)`, the window step reads the `UInt32` key, but the accounting descended through the key and credited the `String` column `s`, so `sipHash64(toUInt32(s))` was moved and an eight-byte hash replaced the four-byte key in the buffer. Now the grouping keys are, like the aggregate function results, inputs of their own type, and in a query with aggregation an expression that reaches a column outside of the grouping keys and the aggregate functions (for example, a key that is not matched because of `group_by_use_nulls`) is not moved. Co-authored-by: yakov <[email protected]>
|
|
||
| QueryTreeNodePtrWithHashSet unbounded_inputs; | ||
| const auto & result_type = function_node->getResultType(); | ||
| if (canBeComputedBeforeWindow(node, correlated_columns_set, aggregation_keys, unbounded_inputs) |
There was a problem hiding this comment.
[P2] Bound repeated traversal and hashing of shared projection subtrees
Every recursive call to canBeComputedBeforeWindow converts node to QueryTreeNodeWithHash for the grouping-key lookup, which walks the entire subtree even when there are no grouping keys. When there is no unbounded input, this collector then recursively repeats the analysis for every argument; collected_nodes only deduplicates successful candidates. Nested aliases therefore incur substantial planning work even when this optimization cannot move anything.
On this head's Fast Test binary, the following one-row query records 8,372,701 QueryPlanBuildMicroseconds; adding QUALIFY 1 to skip the new pass records 187,347, with identical results:
WITH number AS a0,
sipHash64(a0, a0) AS a1, sipHash64(a1, a1) AS a2,
sipHash64(a2, a2) AS a3, sipHash64(a3, a3) AS a4,
sipHash64(a4, a4) AS a5, sipHash64(a5, a5) AS a6,
sipHash64(a6, a6) AS a7, sipHash64(a7, a7) AS a8,
sipHash64(a8, a8) AS a9, sipHash64(a9, a9) AS a10,
sipHash64(a10, a10) AS a11, sipHash64(a11, a11) AS a12,
sipHash64(a12, a12) AS a13, sipHash64(a13, a13) AS a14,
sipHash64(a14, a14) AS a15, sipHash64(a15, a15) AS a16
SELECT a16, count() OVER () AS n FROM numbers(1);Please memoize eligibility/input analysis and candidate traversal for shared nodes, avoid subtree hashing for an empty grouping-key set, and skip retained-input analysis when there are no candidates. Add a focused planning benchmark so window queries over fixed-size expressions do not acquire this overhead.
|
moving to draft until we decide if we need it and where we need it - see comment https://github.com/ClickHouse/clickhouse-private/issues/78134#issuecomment-6216346979 |
closes https://github.com/ClickHouse/clickhouse-private/issues/78134
With the analyzer, the
Windowstep buffers the columns that the projection expressions read, because the whole projection is computed after the window functions. For example, inthe window step buffers the
Stringcolumnc2instead of theUInt64result. The old query analysis computed such expressions before the window functions (appendSelectSkipWindowExpressionsinExpressionAnalyzer), so it buffered only the result. Since 26.9 the old analysis cannot be selected, so on master every such query uses the larger amount. This was found in ClickHouse Cloud and reproduced on the public 26.4.5, 26.8.28 and master builds.Peak memory of the original reproduction: 10 million rows with 160-byte strings,
SELECT count() FROM (SELECT DISTINCT toUInt64OrZero(splitByString('@', c2)[2]) AS v, count() OVER () AS n FROM t1) WHERE v > 0. All builds were run withclickhouse local --max_threads 1on the same generated data.The PR brings master to the level of the hand-written subquery. The remaining difference from 26.8 (8 bytes per buffered row, also for a bare
count() OVER ()) is the unreleasedpeer_group_indexesregression tracked in #125844, which is not related to this change.Now
analyzeWindowcollects the largest subexpressions of the projection that can be computed before the window functions and have a result of bounded size. It computes the ones worth moving in a new chain step right before the window step ("Projection before window functions"). The projection then reads their results by name, so the columns used only by them are no longer buffered.Expressions are moved only if the buffered rows cannot become larger. The accounting fails closed:
ALIAScolumn expressions. After aggregation, the grouping keys and aggregate results are inputs of their own type. An expression that reaches any other column in a query with aggregation is not moved.CAST,toNullableor an alias. "Read after the window step" covers the rest of the projection,ORDER BY,INTERPOLATE,LIMIT BY, and the arguments andPARTITION BY/ORDER BYof the window functions. Constants and values without base columns are not credited.String,ArrayorMap, plus 1 forNullable. Other types count as 0.So
toUInt64OrZero(s)orlength(s)alone move. These stay after the window:SELECT s, length(s),SELECT s, length(CAST(s AS String) AS t)(through a subquery), several 8-byte results of one string,lower(s),repeat(s, 10),toFixedString(s, 2048), a hash of a fixed-size grouping key, and expressions over fixed-size columns such asx + 1. The bound is conservative because string lengths and memory sharing are unknown at planning time: two numbers extracted from the same long string are not moved, although that would also save memory.What else is not moved before the window:
arrayJoin, because in the projection it multiplies the rows only after the window functions.rowNumberInBlock,runningDifference, ...);blockSize,blockSerializedSize,rand, ...);sleepEachRow).if(count() OVER () = 0, intDiv(1, number), 0)the branch must not run for all rows. Only the always-executed arguments are considered, such as the condition ofif, and no arguments ofand/or.QUALIFY,LIMIT,LIMIT AFTERorLIMIT UNTIL, where the projection may be computed only for some of the rows.The new step is separate from "Before WINDOW" because "Before WINDOW" may run on the shards in a distributed query. The new step runs on the initiator together with the window functions, so the header of the blocks the shards send (
--stage with_mergeable_state) is the same as before, and mixed-version clusters keep working.Testing: the new test
05401_window_functions_compute_projection_before_windowfails on master: the memory check hitsMEMORY_LIMIT_EXCEEDEDand the plan order is reversed. A distributed case overremotechecks in the plan that the expression is computed in the new step aboveReadFromRemote, whose header is still theStringcolumn. Its other cases give the same results as master: block-dependent functions, side effects, lazy branches, expandingrepeatandFixedStringresults, values still read after the window, several results of one value, subquery aliases, identityCAST/toNullable/assumeNotNullwrappers and constant columns, grouping keys,LIMIT,LIMIT UNTIL,arrayJoin,QUALIFY,GROUP BY,remote, and more. It passed 20 runs with randomized settings and gives the same output with parallel replicas. All 302 stateless tests that use window functions orQUALIFYpass locally with the test cluster configs.Unrelated CI failures:
AST fuzzer (amd_release, oracle)on the first commit. The querySELECT 1, * FROM (SELECT 2 AS x) AS a LEFT JOIN (SELECT 1, -2147483648 AS y) AS b ON y = xhas no window functions and gives the same mismatch on the official master build. Related: Non-matched RIGHT JOIN row carries the outer SELECT's constant column (not defaulted) when the join is wrapped in a subquery #10692305345_text_index_prewhere_read_step_orderinStateless tests (arm_binary, ParallelReplicas, s3 storage, parallel)on 5780296 and 9a1eec7. It has been flaky in this job on master and many PRs since 2026-10-14, and a fix is in Keep the ProfileEvents-checked reads of 05345_text_index_prewhere_read_step_order off parallel replicas #125892test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hostsinIntegration tests (arm_binary, 3/4)on 5bb4e16. The old 26.8.28 server rejects the MinIO URL byremote_url_allow_hosts. On 2026-10-16 it also failed on master and on six other PRs.Build (arm_tidy, 3/4)on 3e00e1b and 34c9bbd. All errors are insrc/Functions/tests/gtest_functions_stress.cpp, broken on master by the change ofStackTrace::tryResolveAddress, and the same build failed on many PRs at the same time. A fix is in Fix the build ofunit_tests_dbmsafter the change ofStackTrace::tryResolveAddress#126269. A localclang-tidyrun reports nothing in the files of this PR.Related: #125844
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reduce the memory usage of queries with window functions: a projection expression that does not depend on window functions and has a small fixed-size result is now computed before the window step when this frees a
String,ArrayorMapcolumn that nothing else reads, so the window step buffers the result instead of the column. For example,SELECT toUInt64OrZero(splitByString('@', s)[2]), count() OVER () FROM tbuffers aUInt64instead of theStringcolumns.Workflow [PR]
Sync PR [sync-upstream/pr/126062]