Skip to content

Push expressions of String columns below window functions in the query plan - #126558

Draft
yakov-olkhovskiy wants to merge 13 commits into
masterfrom
cursor/plan-push-down-expressions-below-window-380d
Draft

yakov-olkhovskiy wants to merge 13 commits into
masterfrom
cursor/plan-push-down-expressions-below-window-380d

Conversation

@yakov-olkhovskiy

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

Copy link
Copy Markdown
Member

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 Window step buffers the columns it 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, and since 26.9 it cannot be selected.

Peak memory with clickhouse local --max_threads 1, on 10 million rows of 160-byte strings:

Query master this PR
SELECT count() FROM (SELECT DISTINCT toUInt64OrZero(splitByString('@', c2)[2]) AS v, count() OVER () AS n FROM ...) WHERE v > 0 (the original report) 2.64 GiB 268 MiB
... count() OVER (PARTITION BY k) ... (no external sorting) 153 MiB 138 MiB

This adds the optimization pushDownExpressionsBelowWindow (setting query_plan_push_down_expressions_below_window, enabled by default). It generalizes the existing pushDownVolumeReducingFunctions, which moves length, lengthUTF8, empty and notEmpty below Sorting and Filter steps, to the window case.

It looks at the Expression or Filter step directly above a Window step. It moves the expressions that read a single String / FixedString column and whose result is stored in a fixed size not larger than the smallest value of the column (the 8-byte offset of a String, N for FixedString(N)). Only results represented by numbers (integers, floats, dates, decimals, enums, UUID, IPs) or FixedString, also Nullable, are moved. Types like LowCardinality (also of numbers) or Variant have a maximum size of value but also store indexes, dictionaries, discriminators or offsets.

The moved expressions go below the chain of Window steps and the Sorting steps for them, and are merged into the Expression step there. The plan rewrite is the same as in pushDownVolumeReducingFunctions: ActionsDAG::split of the parent, and a new step whose first part is computed below. A Filter keeps the same rows on both sides of the window functions, so the outer WHERE v > 0 of 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 BY columns 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 (v in v > 0).

  • Removing the column actually frees memory:

    • Two columns can share memory only through functions that may return an argument as is: an argument of the same type up to Nullable / LowCardinality, or a composite one, like with an identity CAST, toNullable, assumeNotNull, tupleElement or 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.
    • The column must come from a read that creates new full columns, MergeTree or numbers, or from aggregation. Others are not accepted:
      • a Memory table, a materialized CTE or a prepared source keep their columns;
      • a File or object storage read can fill missing columns with defaults;
      • the reads from other servers and parallel replicas can return sparse columns, and their parts are not known.
    • For a MergeTree read, 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, like t String DEFAULT s, or v String DEFAULT u with u String DEFAULT s. No output of the PREWHERE or 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 = s with apply_mutations_on_fly = 1).
    • The column must not be sparse or lazily replicated. Such a column takes much less than the offset per row, while a result of it can be a full column. Functions keep their results sparse if they map the default value to the default value (toFixedString(s, 8)), so all inputs of the expressions below are followed to the reads, and every MergeTree part to read must have serialization info showing the default serialization for them. Subcolumns, virtual columns, and tables with pending metadata mutations (such as an unfinished RENAME COLUMN) are treated as possibly sparse. With enable_lazy_columns_replication, an arrayJoin replicates all the columns of the block lazily, so a column from an Expression or Filter step with an arrayJoin is 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. With short_circuit_function_evaluation = 'disable', an and condition of the Filter is not moved either, because the Filter applies its arguments one after another. The pushed step is not merged into an expression with arrayJoin, 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, also LIMIT BY with constant keys, LIMIT AFTER/UNTIL, DISTINCT ... LIMIT and ORDER BY ... LIMIT;
    • INTERSECT / EXCEPT or a JOIN with an empty side;
    • a Filter with a constant condition;
    • an aggregation, DISTINCT or sorting with overflow_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, Filter with a non-constant condition, Sorting and Distinct without a limit, Window, Union, ArrayJoin, Offset, Extremes, Filling and CreatingSets. 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, set or join overflow modes of the query is break with its limit set.

  • With QUALIFY, the projection is a separate step above the Filter and is not changed, and an arrayJoin in the parent prevents the rewrite.

As for other new settings, its previous value in the settings history is false, so compatibility with a version before 26.11 disables the optimization.

It is a second pass optimization:

  • It needs the steps above, to see a LIMIT.
  • liftUpFunctions (tryExecuteFunctionsAfterSorting), which moves expressions above Sorting steps, runs only in the first pass. So the expressions can also be moved below the Sorting steps for the windows without being moved back.
  • It runs before optimizeReadInOrder and optimizeWindowPerPartition, and the moved expressions are merged into the Expression step below the window sorting, so those see the same shape of the plan.
  • The window functions and the new step are only on the initiator, so the blocks sent by shards do not change. For now, the reads from other servers are not accepted as sources (see above), so the rewrite applies only to local reads. It is not applied with make_distributed_plan.

Testing: the new test 05407_window_functions_push_down_expressions_below_window:

All 307 stateless tests that use window functions or QUALIFY pass locally with the test cluster configs, and so do the tests of settings documentation and history. The original query over a MergeTree table with max_memory_usage = 1e9 peaks at 252 MiB, while it fails with the optimization disabled.

Unrelated CI failures:

  • 03821_drop_workload_during_query_race in Stateless 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 test 05331_table_disk_single_writer. The same failure happened on five other PRs between 2026-10-17 and 2026-10-19.

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: an expression of a String or FixedString column with a small fixed-size result, such as toUInt64OrZero(splitByString('@', s)[2]) or length(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 setting query_plan_push_down_expressions_below_window.

Open in Web Open in Cursor 

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

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

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e5a08fd]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

The 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

⚠️ Majors

  • pushDownExpressionsBelowWindow.cpp:458-460: Equal headers do not guarantee that a step preserves column representation. Both hasOwnMemory and mayBeSparseOrReplicated accept a single-input FilledJoinStep when its join key remains in the output. An ALL INNER JOIN against a Join engine table can then return ColumnReplicated, while the pushed cityHash64 produces a dense result. On the current-head fast-test binary, the reproducer below peaks at 61.10 MiB disabled versus 76.56 MiB enabled. Under a 75,000,000-byte limit, it succeeds with query_plan_push_down_expressions_below_window = 0 and raises MEMORY_LIMIT_EXCEEDED in WindowTransform enabled. Reject FilledJoinStep in the representation check, or allow traversal only through steps proven to preserve the representation. The existing lazy-replication thread has been reopened with the evidence.
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
  • ⚠️ Add a stateless regression covering this Join engine path with the join key retained; assert that the hash stays above Window. Removing the key changes the headers and hides the gap.
Final Verdict

⚠️ Request changes — close the FilledJoinStep representation gap and add the focused regression.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 18, 2026
cursoragent and others added 2 commits October 18, 2026 04:10
- `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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e5a08fd80 with master c77196273 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c8a410bb9; 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

38 object files changed (+152.26 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/pushDownExpressionsBelowWindow.cpp.o new 144.72 KiB +144.72 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

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

Translation units without a recent master baseline:

  • src/Core/Settings.cpp: 12.5 s
  • src/Processors/QueryPlan/Optimizations/pushDownExpressionsBelowWindow.cpp: 11.2 s
  • src/Interpreters/InterpreterExplainQuery.cpp: 9.5 s
  • src/Storages/StorageBuffer.cpp: 9.5 s
  • src/Storages/PostgreSQL/MaterializedPostgreSQLConsumer.cpp: 8.3 s
  • src/Storages/StorageView.cpp: 7.9 s
  • src/Storages/IStorageCluster.cpp: 7.7 s
  • src/Storages/IStorage.cpp: 7.3 s
  • src/Processors/QueryPlan/Optimizations/convertJoinToIn.cpp: 7.3 s
  • src/Processors/QueryPlan/Optimizations/mergeFilterIntoJoinCondition.cpp: 6.9 s
  • src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp: 6.8 s
  • src/Storages/StorageExecutable.cpp: 6.6 s
  • src/Storages/TimeSeries/PrometheusRemoteReadProtocol.cpp: 6.5 s
  • src/Storages/StorageTimeSeriesSelector.cpp: 6.5 s
  • src/Interpreters/GlobalSubqueriesVisitor.cpp: 6.5 s
  • src/Processors/QueryPlan/resolveStorages.cpp: 6.2 s
  • src/Storages/System/StorageSystemUserQueryLog.cpp: 6.1 s
  • src/Interpreters/getHeaderForProcessingStage.cpp: 6.0 s
  • src/Interpreters/InterpreterDescribeQuery.cpp: 5.8 s
  • src/Interpreters/InterpreterSelectQueryAnalyzer.cpp: 5.8 s
  • ... and 8 more

Job report

…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]>
cursoragent and others added 2 commits October 19, 2026 14:38
…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]>
cursoragent and others added 2 commits October 20, 2026 01:36
…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))

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

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 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]>

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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants