Repository navigation
Push expressions of String columns below window functions in the query plan - #126558
yakov-olkhovskiy wants to merge 13 commits into
Conversation
…y plan
With the analyzer, the projection is computed after the window functions, so
the `Window` step buffers the columns it reads. For
`SELECT toUInt64OrZero(splitByString('@', s)[2]), count() OVER () FROM t` the
window step buffers 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.
Add the query plan optimization `pushDownExpressionsBelowWindow` (setting
`query_plan_push_down_expressions_below_window`, enabled by default). It moves
the largest expressions of the `Expression` step above `Window` steps that read
a single `String` / `FixedString` column and have a fixed-size result not larger
than the smallest value of the column below the `Window` steps and the
`Sorting` steps for them. Like `pushDownVolumeReducingFunctions`, it is applied
only if nothing else reads the column after the window functions and the column
does not share memory with another column. Expressions that are executed lazily,
stateful, block-dependent or with side effects are not moved, nor are expressions
below a `LIMIT`, which may need them only for some rows. It is a second pass
optimization because it needs the steps above, and so that `liftUpFunctions`
does not move the expressions back above the window sorting.
Co-authored-by: yakov <[email protected]>
|
|
|
Workflow [PR], commit [e5a08fd] Summary: ❌
AI ReviewSummaryThe PR moves compact expressions below window functions to reduce buffered memory. One storage-representation gap remains: a join can introduce lazy replication despite preserving its header, so the default-enabled rewrite increases memory and can make previously successful queries fail. Findings
CREATE TABLE j (k UInt64) ENGINE = Join(ALL, INNER, k);
INSERT INTO j SELECT 0 FROM numbers(10000);
SELECT k, cityHash64(s), count() OVER ()
FROM
(
SELECT k, s
FROM
(
SELECT number % 2 AS k, toString(number) AS s
FROM numbers(500)
) AS a
ALL INNER JOIN j USING (k)
)
FORMAT Null
SETTINGS enable_lazy_columns_replication = 1,
max_threads = 1, max_block_size = 100,
max_memory_usage = 75000000;Tests
Final Verdict
|
- `typeid_cast` does not match the classes derived from `ISourceStep`, so no read
step was accepted as a source of separate columns. Use `dynamic_cast`.
- The outer `WHERE` of the original query is merged with the projection into the
`Filter` step above the `Window` step. A `Filter` keeps the same rows on
both sides of the window step, so its expressions are moved too.
- When an intermediate result is read by something else (`v` in `v > 0`), the
largest expressions can not replace the column, so the lowest ones are tried.
- Two columns can share memory only through functions that may return an argument
as is: with the same type up to `Nullable` / `LowCardinality`, or of a
composite argument. Follow only those instead of all the arguments, so that
`concat('p@', toString(number))` is not considered to share memory with
`number % 3`.
- The `Sorting` steps for windows have `PARTITION BY` descriptions, and a
`Window` step only adds columns, so both are passed through.
Co-authored-by: yakov <[email protected]>
The test checks that the window step does not buffer the column read only by the expression (the query fails with `MEMORY_LIMIT_EXCEEDED` with the optimization disabled), that the expression is computed below the `Window` and `Sorting` steps in the plan, also on the initiator of a distributed query, and that it stays after the window functions when the column is still read, the results are larger, the column may share memory with another one, or with a fixed-size grouping key, `LIMIT`, `QUALIFY`, lazily executed arguments, block-dependent functions, side effects and `arrayJoin`. Co-authored-by: yakov <[email protected]>
…rayJoin or for borrowed columns Address the review of #126558: - `LIMIT BY` with constant keys stops reading after the first rows, so the projection was computed for rows it does not read. `LIMIT BY` and `DISTINCT` with a limit hint now prevent the rewrite like `LIMIT`. - In one step an `arrayJoin` is executed after the actions that do not depend on it, so merging the pushed expressions into an expression with `arrayJoin` computed them for the rows an empty array removes. The pushed step is kept separate in this case. - A `Memory` table (and other sources like materialized CTEs or prepared sources) returns columns that it keeps in memory, so removing them from the window input does not free memory, while the results are buffered in addition. Only the reads that create new columns are accepted as sources now. Co-authored-by: yakov <[email protected]>
Address the review of #126558 (#126558 (comment)): with `group_by_overflow_mode = 'break'` and `max_rows_to_group_by`, an aggregation stops reading before all rows are read, as does `DISTINCT` with `distinct_overflow_mode = 'break'`, so the projection after the window functions was computed for rows it does not reach. These settings are not visible in the plan, so the optimization is disabled if any of the `group_by`, `distinct`, `sort`, `result`, `set` or `join` overflow modes is `break` with its limit set. Co-authored-by: yakov <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes38 object files changed (+152.26 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units154 translation units recompiled, 1386 s compile time in total, 97 of them have a recent master baseline. Translation units without a recent master baseline:
|
…essions Address the review of #126558: - `INTERSECT` with an empty side stops reading the other side after the first block, so the projection was computed for rows it does not read. Many steps can stop reading early (also a `JOIN` with an empty side or a `Filter` with a constant condition), so instead of listing them, only the steps known to read all rows are accepted above the window functions, up to an aggregation. - A `MergeTree` part that lacks a column added later fills it with its default expression, which can return another column as is (`t String DEFAULT s`), and the `PREWHERE` and row policy actions can compute columns from the read ones. A `MergeTree` column is now accepted only if it has no default expression, no other read column has a default expression that reads it, and no output of those actions is computed from it as is. The `File` and object storage reads, which can also fill missing columns with defaults, are not accepted anymore. Co-authored-by: yakov <[email protected]>
…or window expressions Address the review of #126558: - The overflow modes can be set only for a subquery, so the settings of the query do not show them. The `Aggregating`, `MergingAggregated`, `Distinct` and `Sorting` steps above the window functions are now checked for their own limits with `overflow_mode = 'break'`, and the set-building steps, whose limits are not known in the plan, are not accepted above them. - The default expressions of a `MergeTree` table are followed transitively (`v String DEFAULT u`, `u String DEFAULT s`), including the columns that are not read. - `getMaximumSizeOfValueInMemory` does not bound the memory of every type with a maximum size of value: `LowCardinality` keeps indexes and a dictionary, `Variant` keeps discriminators and offsets. Only the results represented by numbers or `FixedString` (also `Nullable`) are moved. - The previous value of `query_plan_push_down_expressions_below_window` in the settings history is now `true`: the rewrite does not change the results, and the old query analysis computed such expressions before the window functions too, so `compatibility` with an older version, like `compatibility = '24.0'` of the original report, does not disable it. Co-authored-by: yakov <[email protected]>
…ssions_below_window The previous value in the settings history is `false` again, as for other new settings, so `compatibility` with versions before 26.11 disables the optimization. Co-authored-by: yakov <[email protected]>
…ty results Address the review of #126558: - `LowCardinality(UInt64)` is represented by a number as its dictionary type, so `toLowCardinality(reinterpretAsUInt64(s))` was moved, although it keeps indexes and a dictionary. `LowCardinality` results are rejected explicitly. - A `MergeTree` part can store a `String` column in a sparse serialization, and it is read and buffered as a sparse column, which takes much less than its offset per row, while `cityHash64(s)` of it is a full column. A `MergeTree` column is accepted only if no part to read has a custom serialization of it. The reads from other servers can return sparse columns too, and their parts are not known, so they are not accepted anymore. Co-authored-by: yakov <[email protected]>
…on the fly Address the review of #126558: - A function keeps its result sparse if it maps the default value to the default value, so `toFixedString(s, 8)` of a sparse column is sparse too, although it is not the same column. The sparseness is now checked separately from the memory sharing, following all inputs of the expressions to the reads, and a step that is not known is assumed to return sparse columns. - The mutations and patches applied on the fly can make a column the same as another one (`UPDATE t = s` with `apply_mutations_on_fly = 1`). A `MergeTree` read is not accepted if one of its columns is changed on the fly. Co-authored-by: yakov <[email protected]>
…n infos as possibly sparse `mayBeSparse` looked up the column in the serialization infos of the parts by its query name and considered a missing entry as dense. Subcolumns (`t.s`) and columns renamed by a pending `RENAME COLUMN` are not found there, so a sparse column could be pushed below `Window`. Related: #126558 (comment) Co-authored-by: yakov <[email protected]>
| else if (can_replace_column(input, lowest_candidates)) | ||
| replacing_candidates = &lowest_candidates; | ||
|
|
||
| if (!replacing_candidates || !hasOwnMemory(*bottom_node, column_name) || mayBeSparse(*bottom_node, column_name)) |
There was a problem hiding this comment.
[P2] Include lazy replication in the input storage bound
mayBeSparse does not detect ColumnReplicated. A lower Expression containing arrayJoin can lazily replicate s, but the provenance walk follows only its explicit expression dependencies and accepts it here. WindowTransform retains the replicated pass-through column, whereas cityHash64 produces a dense UInt64 column. Consequently, the eight-byte lower bound per logical String row does not hold, and this rewrite increases buffered memory.
This reproduces with the fast-test binary for head b556b5f5:
SELECT cityHash64(s), count() OVER ()
FROM
(
SELECT toString(number) AS s, arrayJoin(range(10000)) AS a
FROM numbers(500)
)
FORMAT Null
SETTINGS query_plan_lower_array_join_function = 0,
enable_lazy_columns_replication = 1,
max_threads = 1, max_block_size = 100,
max_memory_usage = 100000000;The query succeeds with query_plan_push_down_expressions_below_window = 0 and raises MEMORY_LIMIT_EXCEEDED with it enabled. Without the cap, peak memory is 89.63 MiB disabled versus 115.37 MiB enabled. EXPLAIN confirms that cityHash64 moves below Window into a separate step after the expression containing arrayJoin.
Track lazy replication alongside sparse storage, or conservatively reject this provenance through an Expression / Filter containing arrayJoin, and add a focused stateless regression.
There was a problem hiding this comment.
Fixed in ceb7877. The sparse check is renamed to mayBeSparseOrReplicated. When the column comes from an Expression or Filter step whose DAG has an arrayJoin, the column is now treated as possibly lazily replicated. This is conservative: with enable_lazy_columns_replication, the arrayJoin action replicates all columns of the block, not only the ones computed from it, so the DAG is rejected as a whole. The other sources of ColumnReplicated, ArrayJoinStep and joins, were already not accepted by hasOwnMemory.
For your query, cityHash64 now stays above Window. Peak memory is the same with the setting enabled and disabled (98.23 MiB on my machine). I added the plan check to 05407_window_functions_push_down_expressions_below_window as a regression. I didn't add a memory-limit check, because the baseline on my machine is already above 100000000, so a fixed limit would be fragile.
There was a problem hiding this comment.
The arrayJoin case is fixed, but the claimed exclusion of joins still has a gap on head e5a08fd8. At src/Processors/QueryPlan/Optimizations/pushDownExpressionsBelowWindow.cpp:458-460, mayBeSparseOrReplicated passes through any single-input step with equal input/output headers; hasOwnMemory does the same at lines 374-376. A FilledJoinStep over a Join engine table satisfies both checks when the join key is retained. It can still return ColumnReplicated: src/Interpreters/HashJoin/HashJoinResult.cpp:189-205 lazily replicates the left columns.
This reproduces with the current-head fast-test binary:
CREATE TABLE j (k UInt64) ENGINE = Join(ALL, INNER, k);
INSERT INTO j SELECT 0 FROM numbers(10000);
SELECT k, cityHash64(s), count() OVER ()
FROM
(
SELECT k, s
FROM
(
SELECT number % 2 AS k, toString(number) AS s
FROM numbers(500)
) AS a
ALL INNER JOIN j USING (k)
)
FORMAT Null
SETTINGS enable_lazy_columns_replication = 1,
max_threads = 1, max_block_size = 100,
max_memory_usage = 75000000;The final query succeeds with query_plan_push_down_expressions_below_window = 0 and raises MEMORY_LIMIT_EXCEEDED in WindowTransform with it enabled. Without the cap, peak memory is 61.10 MiB disabled versus 76.56 MiB enabled; EXPLAIN confirms that only the enabled plan moves cityHash64 below Window.
Reject FilledJoinStep in the representation check, or restrict the generic traversal to steps proven to preserve the column representation. Please add this stateless case with the join key retained, since removing the key changes the headers and hides the gap.
With `enable_lazy_columns_replication`, an `arrayJoin` in expression actions replaces all columns of the block by `ColumnReplicated`, which can take less than the offset of a `String` per row. Moving an expression of such a column below `Window` made the buffered rows larger. Related: #126558 (comment) Co-authored-by: yakov <[email protected]>
…rt-circuit evaluation disabled The same fix as in #126880: a `Filter` applies the arguments of an `and` condition one after another even with `short_circuit_function_evaluation = 'disable'`, so `s != 'x' AND toUInt64(s) > 0` computed in an `Expression` step below the window functions threw on `'x'`. Related: #126880 (comment) Co-authored-by: yakov <[email protected]>
Related: https://github.com/ClickHouse/clickhouse-private/issues/78134
Related: #126882
Related: #126880
Alternative to #126062: the same fix as a query plan optimization instead of a change of the planner.
The minimal fix is split into #126880. This PR is the source of truth for the follow-up PRs that make the optimization never worse than the current analyzer, tracked in #126882.
With the analyzer, the projection is computed after the window functions, so the
Windowstep buffers the columns it reads. ForSELECT toUInt64OrZero(splitByString('@', c2)[2]) AS v, count() OVER () AS n FROM t1, the window step buffers theStringcolumnc2instead of aUInt64. The old query analysis computed such expressions before the window functions, and since 26.9 it cannot be selected.Peak memory with
clickhouse local --max_threads 1, on 10 million rows of 160-byte strings:SELECT count() FROM (SELECT DISTINCT toUInt64OrZero(splitByString('@', c2)[2]) AS v, count() OVER () AS n FROM ...) WHERE v > 0(the original report)... count() OVER (PARTITION BY k) ...(no external sorting)This adds the optimization
pushDownExpressionsBelowWindow(settingquery_plan_push_down_expressions_below_window, enabled by default). It generalizes the existingpushDownVolumeReducingFunctions, which moveslength,lengthUTF8,emptyandnotEmptybelowSortingandFiltersteps, to the window case.It looks at the
ExpressionorFilterstep directly above aWindowstep. It moves the expressions that read a singleString/FixedStringcolumn and whose result is stored in a fixed size not larger than the smallest value of the column (the 8-byte offset of aString,NforFixedString(N)). Only results represented by numbers (integers, floats, dates, decimals, enums,UUID, IPs) orFixedString, alsoNullable, are moved. Types likeLowCardinality(also of numbers) orVarianthave a maximum size of value but also store indexes, dictionaries, discriminators or offsets.The moved expressions go below the chain of
Windowsteps and theSortingsteps for them, and are merged into theExpressionstep there. The plan rewrite is the same as inpushDownVolumeReducingFunctions:ActionsDAG::splitof the parent, and a new step whose first part is computed below. AFilterkeeps the same rows on both sides of the window functions, so the outerWHERE v > 0of the original query, merged with the projection, does not prevent it.The expressions are moved only if this cannot make the buffered rows larger or change the results:
Nothing else reads the column after the window functions: other nodes and outputs of the parent DAG, the window function arguments, and the
PARTITION BY/ORDER BYcolumns of the windows and sortings. Several expressions of one column are moved together, only if the sum of their result sizes fits. The largest expressions are tried first (toUInt8(length(s))), then the lowest, when an intermediate result is read by something else (vinv > 0).Removing the column actually frees memory:
Nullable/LowCardinality, or a composite one, like with an identityCAST,toNullable,assumeNotNull,tupleElementor an alias. Following such functions through the steps below (Expression,Filter,Window,Union, header-preserving steps), the column must have no common node with another column.MergeTreeornumbers, or from aggregation. Others are not accepted:Memorytable, a materialized CTE or a prepared source keep their columns;Fileor object storage read can fill missing columns with defaults;MergeTreeread, the column must have no default expression, and no other read column may have a default expression reading it, also through other columns, including the ones that are not read. A part that lacks a column added later fills it with the default, which can return another column as is, liket String DEFAULT s, orv String DEFAULT uwithu String DEFAULT s. No output of thePREWHEREor row policy actions may be computed from it as is either, and no column of the read may be changed by a mutation or patch applied on the fly (UPDATE t = swithapply_mutations_on_fly = 1).toFixedString(s, 8)), so all inputs of the expressions below are followed to the reads, and everyMergeTreepart to read must have serialization info showing the default serialization for them. Subcolumns, virtual columns, and tables with pending metadata mutations (such as an unfinishedRENAME COLUMN) are treated as possibly sparse. Withenable_lazy_columns_replication, anarrayJoinreplicates all the columns of the block lazily, so a column from anExpressionorFilterstep with anarrayJoinis not accepted.No function in the expression is stateful (
runningDifference), non-deterministic in the scope of the query (blockSize,rand), or has side effects (sleepEachRow). The window and sorting steps change the order of rows and their blocks.The expression is not executed lazily as an argument of a short-circuit function (
if,multiIf,and,or). Otherwise it would be executed for all rows, and for example throw. Withshort_circuit_function_evaluation = 'disable', anandcondition of theFilteris not moved either, because theFilterapplies its arguments one after another. The pushed step is not merged into an expression witharrayJoin, which executes the actions that do not depend on it first, for the rows it then removes.All steps above the window functions read all rows, up to an aggregation. Many steps can stop reading early, and then the projection may be needed only for some rows:
LIMIT, alsoLIMIT BYwith constant keys,LIMIT AFTER/UNTIL,DISTINCT ... LIMITandORDER BY ... LIMIT;INTERSECT/EXCEPTor aJOINwith an empty side;Filterwith a constant condition;DISTINCTor sorting withoverflow_mode = 'break'and a limit, also set only for a subquery. These limits are checked in the steps.So only the steps known to read all rows are accepted:
Expression,Filterwith a non-constant condition,SortingandDistinctwithout a limit,Window,Union,ArrayJoin,Offset,Extremes,FillingandCreatingSets. The steps building a set are not accepted, because the limits of a set are not visible in the plan. This includes the steps of an outer query, because the whole plan is visible.The optimization is also disabled if one of the
group_by,distinct,sort,result,setorjoinoverflow modes of the query isbreakwith its limit set.With
QUALIFY, the projection is a separate step above theFilterand is not changed, and anarrayJoinin the parent prevents the rewrite.As for other new settings, its previous value in the settings history is
false, socompatibilitywith a version before 26.11 disables the optimization.It is a second pass optimization:
LIMIT.liftUpFunctions(tryExecuteFunctionsAfterSorting), which moves expressions aboveSortingsteps, runs only in the first pass. So the expressions can also be moved below theSortingsteps for the windows without being moved back.optimizeReadInOrderandoptimizeWindowPerPartition, and the moved expressions are merged into theExpressionstep below the window sorting, so those see the same shape of the plan.make_distributed_plan.Testing: the new test
05407_window_functions_push_down_expressions_below_window:MEMORY_LIMIT_EXCEEDEDwith the setting disabled) and the results for all the cases above.All 307 stateless tests that use window functions or
QUALIFYpass locally with the test cluster configs, and so do the tests of settings documentation and history. The original query over aMergeTreetable withmax_memory_usage = 1e9peaks at 252 MiB, while it fails with the optimization disabled.Unrelated CI failures:
03821_drop_workload_during_query_raceinStateless tests (arm_binary, sequential)has failed on master and on dozens of PRs every day since 2026-10-16.Stress test (arm_asan_ubsan)on 697029e could not restart the server because of a disk left by the test05331_table_disk_single_writer. The same failure happened on five other PRs between 2026-10-17 and 2026-10-19.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: an expression of a
StringorFixedStringcolumn with a small fixed-size result, such astoUInt64OrZero(splitByString('@', s)[2])orlength(s), is now computed before the window functions if nothing else reads the column after them, so the window functions buffer the result instead of the column. Controlled by the new settingquery_plan_push_down_expressions_below_window.Workflow [PR]
Sync PR [sync-upstream/pr/126558]