Skip to content

Fix memory usage degradation of window functions with the analyzer - #126880

Open
yakov-olkhovskiy wants to merge 7 commits into
masterfrom
cursor/window-expressions-degradation-fix-380d
Open

yakov-olkhovskiy wants to merge 7 commits into
masterfrom
cursor/window-expressions-degradation-fix-380d

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Closes: https://github.com/ClickHouse/clickhouse-private/issues/78134
Related: #126558
Related: #126882

This fixes a memory usage degradation of the analyzer compared with the old query analysis.

With the analyzer, the projection is computed after the window functions, so the Window step buffers the columns the projection reads. For SELECT toUInt64OrZero(splitByString('@', c2)[2]) AS v, count() OVER () AS n FROM t1, the window step buffers the String column c2 instead of a UInt64. The old query analysis computed such expressions before the window functions (appendSelectSkipWindowExpressions in ExpressionAnalyzer), and since 26.9 it cannot be selected anymore.

This adds the second-pass query plan optimization pushDownExpressionsBelowWindow, with the setting query_plan_push_down_expressions_below_window (enabled by default). It looks at the Expression or Filter step directly above a Window step. A Filter with an and condition is skipped: it applies the arguments one after another and computes its other expressions only for the rows that passed the previous ones. It moves the expressions there below the Window steps, and above the lowest Sorting step for them, where the old query analysis computed them (liftUpFunctions moved them there), if all of these hold:

  • the expression reads a single String / FixedString column;
  • its result is a number or a FixedString (also Nullable) no larger than the smallest value of the column (the 8-byte offset of a String, N for FixedString(N));
  • nothing else reads the column after the window functions.

The rewrite is the same as in pushDownVolumeReducingFunctions: ActionsDAG::split of the parent, and a new step below that is merged into the Expression step there. It runs in the second pass, so that it sees the plan after the first pass moved and merged the expressions.

Unlike the old query analysis, it keeps the results of the analyzer: stateful (runningDifference), non-deterministic in the scope of the query (blockSize, rand) and side-effect (sleepEachRow) functions, arrayJoin, and lazily executed arguments of short-circuit functions are not moved. Otherwise it follows the old query analysis. The corner cases where moving an expression can use more memory or CPU than computing it after the window functions are not handled here: sparse or shared columns, a LIMIT above the window functions, and others. Computing the expressions below the window sorting as well, which would also reduce the memory of the sorting, is left for the improvements. They are tracked in #126882, and #126558 is the source of truth for the follow-up PRs, with the checks and a test for each case.

The original query over a MergeTree table of 10 million rows of about 160-byte strings, with max_threads = 1, peaks at 935 MiB (most of it the DISTINCT set) instead of 2.38 GiB. With max_memory_usage = 1e9 it fails without the optimization.

The test 05407_window_functions_push_down_expressions_below_window checks the plan, the memory usage and the results. It passed 40 runs with randomized settings, and all 307 stateless tests that use window functions or QUALIFY pass locally.

Unrelated CI failure: Stress test (amd_tsan) aborted with Received signal 6 (internal) (STID: 4362-110a) in ReplicatedMergeTreeQueue::pullLogsToQueue, after the test 05230_merge_entry_for_local_part_missing_in_zookeeper wrote a merge entry with an empty part name into ZooKeeper (Unexpected part name: for format version: 1, BAD_DATA_PART_NAME) when fault injection had failed its INSERT. The same abort happened on master and four other PRs on 2026-10-21. The fix is #127123.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix the memory usage of queries with window functions with the analyzer: an expression of a String or FixedString column with a small fixed-size result, such as toUInt64OrZero(splitByString('@', s)[2]) or length(s), is computed before the window functions again, as with the old query analysis, so the window functions buffer the result instead of the column. Controlled by the new setting query_plan_push_down_expressions_below_window.

Open in Web Open in Cursor 

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

cursoragent and others added 2 commits October 20, 2026 04:39
…query 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 ()`
it buffers the `String` column `s` instead of a `UInt64`. The old query analysis computed such
expressions before the window functions.

The new second-pass optimization `pushDownExpressionsBelowWindow` (setting
`query_plan_push_down_expressions_below_window`) moves the expressions with a small fixed-size
result of a `String` or `FixedString` column below the `Window` steps and the `Sorting` steps for
them, if nothing else reads the column after them. Stateful, non-deterministic and side-effect
functions, `arrayJoin` and lazily executed arguments are not moved, so the results are the same.

Co-authored-by: yakov <[email protected]>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cdf703d]

Summary: ✅


AI Review

Summary

Moves eligible fixed-size expressions of String and FixedString columns before window functions to reduce buffered memory, controlled by query_plan_push_down_expressions_below_window. Reviewed head cdf703d61ce8a83873744ced66225fd55a7f2e57, including all prior discussion and fixes. No unresolved or new actionable findings. The locally applicable portion of the new stateless regression matches its reference exactly; additional sparse-column and lambda probes also match with the optimization enabled and disabled. The explicitly deferred early-termination and memory tradeoffs remain tracked in #126882.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 20, 2026
…rt-circuit evaluation disabled

A `Filter` applies the arguments of an `and` condition one after another even with
`short_circuit_function_evaluation = 'disable'`, so an argument is not executed for the rows
removed by the previous ones. Computed in an `Expression` step below the window functions,
`s != 'x' AND toUInt64(s) > 0` threw on `'x'`.

Related: #126880 (comment)

Co-authored-by: yakov <[email protected]>
cursor Bot pushed a commit that referenced this pull request Oct 20, 2026
…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]>
…hort-circuit mode

With `short_circuit_function_evaluation = 'enable'`, the functions not suitable for short-circuit
evaluation, like `toBool`, are executed for all rows, so only the sequential filtering of the
`Filter` protected `toBool(s)` in `s != '' AND toBool(s)` from the empty string.

Related: #126880 (comment)

Co-authored-by: yakov <[email protected]>
…n `and` condition

Such a `Filter` applies the arguments of the condition one after another and computes the rest
of its expressions, like a merged projection with `query_plan_split_filter = 0`, only for the
rows that passed the previous arguments. Moved below the window functions, `toUInt64(s)` was
computed for all rows and threw.

Related: #126880 (comment)

Co-authored-by: yakov <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cdf703d61 with master a6c5f4ab9 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0ddba953e; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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

48 object files changed (+107.25 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/pushDownExpressionsBelowWindow.cpp.o new 101.99 KiB +101.99 KiB

719 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

155 translation units recompiled, 1363 s compile time in total, 154 of them have a recent master baseline.

Job report

…ke the old query analysis

With the old query analysis, `liftUpFunctions` moved the expressions computed before the window
functions above the sorting for them. The sorting materializes sparse columns, so functions that
see the representation, like `byteSize`, returned other values when the expressions were computed
below it.

Related: #126880 (comment)

Co-authored-by: yakov <[email protected]>
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review October 20, 2026 14:14
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 21, 2026
`03322_view_over_parameterized_view` leaves the parameterized view `test_1.v`
and an interrupted `02703_row_policy_for_database` leaks `ON test_1.* USING 1`.
A parameterized view has no columns until its parameters are given, so
`SELECT 1 FROM v` fails the access check for any user (Code 497), and a filter
naming a column fails with an unknown identifier, which dropped a valid policy.
Red on ClickHouse#126880 and ClickHouse#127094.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants