Skip to content

Compute projection expressions before window functions in the analyzer - #126062

Draft
yakov-olkhovskiy wants to merge 9 commits into
masterfrom
cursor/analyzer-compute-projection-before-window-380d
Draft

yakov-olkhovskiy wants to merge 9 commits into
masterfrom
cursor/analyzer-compute-projection-before-window-380d

Conversation

@yakov-olkhovskiy

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

Copy link
Copy Markdown
Member

closes https://github.com/ClickHouse/clickhouse-private/issues/78134

With the analyzer, the Window step buffers the columns that the projection expressions read, because the whole projection is computed after the window functions. For example, in

SELECT toUInt64OrZero(splitByString('@', c2)[2]) AS v, count() OVER () AS n FROM t1

the window step buffers the String column c2 instead of the UInt64 result. The old query analysis computed such expressions before the window functions (appendSelectSkipWindowExpressions in ExpressionAnalyzer), 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 with clickhouse local --max_threads 1 on the same generated data.

Build old query analysis analyzer analyzer, expression moved into a subquery by hand
26.8.28.14 189 MiB 2.56 GiB 189 MiB
master (not available) 2.64 GiB 268 MiB
this PR (not available) 268 MiB 268 MiB

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 unreleased peer_group_indexes regression tracked in #125844, which is not related to this change.

Now analyzeWindow collects 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:

  • Each value an expression reads (a column, a grouping key or an aggregate result) has base columns. These are the table columns, grouping keys and aggregate results it is computed from, following subquery projections and ALIAS column 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.
  • 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 credited value. Values derived from a common source can share memory, as with an identity CAST, toNullable or an alias. "Read after the window step" covers the rest of the projection, ORDER BY, INTERPOLATE, LIMIT BY, and the arguments and PARTITION BY / ORDER BY of the window functions. Constants and values without base columns are not credited.
  • The credit is a lower bound of the size of the value: the 8-byte offset of a String, Array or Map, plus 1 for Nullable. Other types count as 0.
  • Expressions with common base columns are moved or kept together, and only if the sum of the maximum sizes of their results does not exceed the credit of the values they free.

So toUInt64OrZero(s) or length(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 as x + 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:

  • Expressions with arrayJoin, because in the projection it multiplies the rows only after the window functions.
  • Functions that depend on the order of rows or on blocks, which the window step changes:
    • stateful functions (rowNumberInBlock, runningDifference, ...);
    • functions that are not deterministic in the scope of the query (blockSize, blockSerializedSize, rand, ...);
    • functions with observable side effects (sleepEachRow).
  • Arguments of short-circuit functions that can be executed lazily, when the function itself depends on a window function. For example, in 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 of if, and no arguments of and/or.
  • Subqueries and correlated columns.
  • Constant results.
  • Anything in queries with QUALIFY, LIMIT, LIMIT AFTER or LIMIT 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_window fails on master: the memory check hits MEMORY_LIMIT_EXCEEDED and the plan order is reversed. A distributed case over remote checks in the plan that the expression is computed in the new step above ReadFromRemote, whose header is still the String column. Its other cases give the same results as master: block-dependent functions, side effects, lazy branches, expanding repeat and FixedString results, values still read after the window, several results of one value, subquery aliases, identity CAST / toNullable / assumeNotNull wrappers 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 or QUALIFY pass locally with the test cluster configs.

Unrelated CI failures:

Related: #125844

Changelog category (leave one):

  • Performance Improvement

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, Array or Map column 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 t buffers a UInt64 instead of the String column s.

Open in Web Open in Cursor 

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

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]>
@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 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9e5109]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_binary) DROPPED
Build (amd_release) DROPPED
Build (arm_release) DROPPED

AI Review

Summary

The PR reduces window-query memory by computing bounded projection expressions before Window, with reported before/after measurements and stateless coverage. Two issues remain on b9e51096: the memory budget still admits regressions, and the new analysis substantially increases planning time for nested aliases.

Findings

❌ Blockers

  • The budget does not guarantee that buffered storage stays within the freed-input credit. src/Planner/PlannerExpressionAnalysis.cpp:368 stops lineage at UnionNode, so aliases sharing storage across UNION ALL branches become independent base columns. For SELECT s, length(t), count() OVER () over two branches each projecting toString(number % 10) AS s, s AS t for 500,000 rows, the moved projection retains both the string allocation and its length. The current Fast Test binary exceeds max_memory_usage = 50000000; keeping the projection after Window with QUALIFY n > 0 succeeds. Unrestricted peaks are 52,097,439 and 47,891,535 bytes.

    Line 511 also treats a LowCardinality(UInt64) value's eight-byte maximum as a column-storage bound, omitting dictionary/index overhead. SELECT toLowCardinality(toUInt64OrZero(s)), count() OVER () AS n FROM (SELECT toString(number) AS s FROM numbers(1000000)) FORMAT Null SETTINGS max_threads = 1, max_block_size = 1024, max_memory_usage = 56000000 fails; adding QUALIFY n > 0 succeeds. Unrestricted peaks are 60,563,190 and 52,052,141 bytes. Handle unknown sharing conservatively and reject result representations without a valid storage bound; cover both cases. These are continuations of the existing memory finding, answered once with current reproductions.

⚠️ Majors

  • Ineligible projections incur repeated subtree analysis and hashing. src/Planner/PlannerExpressionAnalysis.cpp:506 repeats eligibility checks while descending through shared aliases; the grouping-key lookup hashes whole subtrees even without grouping keys. A one-row query with 16 successive aliases a_i = sipHash64(a_{i-1}, a_{i-1}), starting with a0 = number, records 8,372,701 QueryPlanBuildMicroseconds, versus 187,347 with QUALIFY 1 skipping the pass. No expression is eligible to move. Memoize analysis and traversal, avoid unnecessary hashing, return early for an empty candidate set, and add a planning benchmark.
Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 15, 2026
Comment on lines +405 to +409
bool depends_on_columns = false;
if (canBeComputedBeforeWindow(node, correlated_columns_set, depends_on_columns))
{
if (depends_on_columns)
result.push_back(node);

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.

[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.

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.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 9a1eec7. The check is no longer made per expression.

  • collectInputsReadAfterWindow collects 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 and PARTITION BY / ORDER BY of 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.

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.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  • collectBaseColumns collects the base columns of every value: the table columns and aggregate results it is computed from, following subquery projections (recursively) and ALIAS column 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.

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.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

The retained-allocation/expansion regression is still reproducible on b9e51096 through two remaining representations:

  1. src/Planner/PlannerExpressionAnalysis.cpp:368–370 stops lineage resolution at a UnionNode, and lines 569–571 consequently treat its output columns as independent base allocations. UNION ALL can 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.

  1. Line 511 uses getMaximumSizeOfValueInMemory as a bound on buffered column storage, but LowCardinality(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.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 15, 2026
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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

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]>
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review October 16, 2026 03:53
… 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]>
cursoragent and others added 2 commits October 16, 2026 08:41
…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]>
cursoragent and others added 2 commits October 16, 2026 12:28
…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)

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.

[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.

@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants