Skip to content

Rewrite correlated scalar aggregate subqueries into window functions - #121848

Open
raimannma wants to merge 47 commits into
ClickHouse:masterfrom
raimannma:correlated-scalar-aggregate-to-window
Open

raimannma wants to merge 47 commits into
ClickHouse:masterfrom
raimannma:correlated-scalar-aggregate-to-window

Conversation

@raimannma

@raimannma raimannma commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #120377
Related: #121865

A correlated scalar aggregate subquery over a table that the enclosing query also reads is rewritten by a new analyzer pass into a window function over that table, computed in a derived table before the joins of the enclosing query, so the table is read once instead of twice:

SELECT o.k, (SELECT max(v) FROM t AS s WHERE s.k = o.k) FROM t AS o WHERE o.k IN (1, 2)
-- becomes
SELECT o.k, o.m FROM (SELECT k, max(v) OVER (PARTITION BY k) AS m FROM t WHERE k IN (1, 2)) AS o WHERE o.k IN (1, 2)

The window sees exactly the rows the subquery sees for the key of each row, so any aggregate function is supported. The filter push-down does not pass a window (#125463), so the pass itself copies the deterministic conditions of the enclosing query on the keys of the windows into the derived table, where they remove whole partitions only, and rewrites only when there is such a condition: otherwise the window would read and sort the whole table, while the decorrelated plan needs memory per key only. Only comparisons and logical functions are copied, as below the window a condition runs on every row of the table. Enabled by optimize_correlated_scalar_aggregate_to_window (off by default).

An earlier revision also rewrote when a runtime join filter could restrict the window (e.g. TPC-H Q17), but such a filter does not pass the window either, so that rule was removed.

Changelog category (leave one):

  • Performance Improvement

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

New setting optimize_correlated_scalar_aggregate_to_window rewrites a correlated scalar aggregate subquery over a table that the enclosing query also reads, filtered by a condition on the correlation keys, into a window function, so the table is read once.


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

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 23, 2026
@raimannma raimannma changed the title Answer correlated scalar min/max subqueries with a partition aggregate Rewrite correlated scalar aggregate subqueries into window functions Sep 23, 2026
A correlated scalar aggregate subquery over a table that the enclosing query
also reads is rewritten by a new analyzer pass into a window function over
that table, computed in a derived table before the joins and conditions of
the enclosing query:

  ... FROM lineitem, part WHERE ... AND l_quantity < (SELECT 0.2 * avg(l_quantity) FROM lineitem WHERE l_partkey = p_partkey)
  -> ... FROM (SELECT ..., avg(l_quantity) OVER (PARTITION BY l_partkey) AS a FROM lineitem) AS lineitem, part WHERE ... AND l_quantity < 0.2 * a

The window sees exactly the rows the subquery sees for the key of each row,
so any aggregate function is supported, and runtime join filters restrict the
table below the window. It applies only if the enclosing query has a
condition that may restrict the keys, otherwise the window would read the
whole table. Enabled by `optimize_correlated_scalar_aggregate_to_window`
(off by default).

Closes: ClickHouse#120377
- Register the pass after `RemoveUnusedProjectionColumnsPass`, so that
  `runOnlyResolve` still runs the same four passes as before.
- Do not rewrite keys with a Nullable inside (e.g. `Tuple(Nullable(Int32))`):
  `=` is not true for them, but the window groups them together.
- Generate window column names that do not collide with columns of the table.
@clickhouse-gh clickhouse-gh Bot added comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 23, 2026
… materialized views

A NULL inside a `Variant` key makes `=` not true while the window groups it. A `PASTE JOIN` pairs rows
by position, which the window reorders. A materialized view replaces its source table by the inserted
block after the passes, which would also apply to the derived table. Without short-circuit evaluation
the expression over the aggregates is evaluated also for keys without matching rows.
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 24, 2026
raimannma and others added 2 commits September 24, 2026 12:19
…ggregate-to-window

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e7c4c4]

Summary: ❌

job_name test_name status info comment
La Casa Del Dolor (amd_debug) FAIL
Logical error: Directory 'A' is virtual (STID: 6611-5d35) FAIL cidb

AI Review

Summary

The PR adds the default-off experimental setting optimize_correlated_scalar_aggregate_to_window to replace eligible correlated aggregate subqueries with windows over a shared table read, copying safe predicates on the partition keys below those windows. Reviewed head 2e7c4c4a46228bbb9aba88d10a71fdf2c6aac47a. The earlier memory-safety and throwing-comparison findings are addressed. No new inline findings; the existing performance-evidence concern remains unresolved.

Findings

⚠️ Majors

  • src/Analyzer/Passes/CorrelatedScalarAggregateToWindowPass.cpp:319 — The claimed performance improvement still lacks measurements for an accepted query. The revised pass requires a safe predicate on the window keys and no longer rewrites the original TPC-H Q17 shape. The linked issue measures a different planner implementation, and the related window-hashing PR measures another optimization. The pruning assertion proves fewer granules are read, but does not establish whether avoiding a second scan outweighs sorting and window execution. Supply an interleaved setting-off/setting-on benchmark on the current implementation, recording elapsed time, rows read, peak memory, and equal results. Existing inline thread; no duplicate comment posted.
Tests
  • Local validation used the current head's fast-test binary, version 26.12.1.1: 12 successful on/off query pairs returned identical results, including shared expressions, outer windows, ARRAY JOIN, multiple targets, aggregate states, and filtered aggregates. The exact new 05857_correlated_scalar_aggregate_to_window_throwing_key_condition regression matched its reference without exceptions.
  • ⚠️ A representative before/after benchmark exercising the revised eligibility rule is still needed to substantiate the Performance Improvement claim. The full CI suite was pending at review time; local probes do not replace it.
Final Verdict

Status: ⚠️ Request changes

Provide performance evidence for a representative query that the current pass actually rewrites. No additional code defect was established in this review.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — inconclusive across 31 queries analysed

Baseline selected using StressHouse version hint 26.10.1.42127; measured build ancestry could not be verified. Measured differences are not attributed to this PR. ⚙️ Master level shift inside the baseline window (~2026-10-13 01:14:12): baseline for 1 query restricted to the checks matching the selected baseline era.

PR verdict: not_sure. 1 measured difference(s) not attributable to this PR. clickbench Q20: The measured difference cannot be attributed to this PR from the available source evidence.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 20 not_sure 220 129 -41.4% <0.0001 The measured difference cannot be attributed to this PR from the available source evidence.
⚠️ 32 not_sure 700 848 +21.2% <0.0001

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 7e4d3a13-96be-4a1c-855b-6330c8f8be0c
  • MIRAI run: f06f9a46-e07c-4386-9b2e-8bcb8312d847
  • PR check IDs:
    • clickbench_232851_1792238505
    • clickbench_232857_1792238505
    • clickbench_232872_1792238506
    • tpch_adapted_1_official_232957_1792238506
    • tpch_adapted_1_official_232986_1792238506

raimannma and others added 9 commits October 5, 2026 10:28
Upstream replaced it with `anyInTypeTree`, which also visits the root, so the
separate `isVariant` check of the root is no longer needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `ANY INNER JOIN` keeps an arbitrary one of the matching rows, so `t.v` of the
  "ANY join" case differed between runs, and between the runs with and without
  the rewrite. Do not select it; the subquery value is the same for all of them.
- Since ClickHouse#122345, a materialized view
  resolves every reference to its source table, also in a subquery, to the
  inserted block. Update the reference: the results with and without the rewrite
  are still equal.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121848&sha=e46d7ff8b9d57742d8755c72bbbc6c3d0e0b5abc&name_0=PR
PR: ClickHouse#121848

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`mayRestrictKeys` counted any condition not on the target as a restriction of
the window, assuming a runtime join filter. But that filter is on the join key,
and only a filter on the `PARTITION BY` keys is pushed below the window. Now a
condition on another table counts only when the target is joined on one of the
keys of the window.

The check also used the union of the keys of all windows on the target, so a
filter on the keys of one window made every window on it count as restricted.
Now each window is checked by itself, and the target is rewritten only when all
of them are restricted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
It enables a new query execution strategy, which must be gated as
experimental until proven safe.

ClickHouse#121848

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

The window evaluates the arguments of the aggregate for every row of the
table, also for rows with a NULL key, which the subquery skips. The guard
for such arguments applied only when the subquery had conditions, so
`sum(intDiv(10, s.v))` threw for a NULL-key row with `v = 0`. Apply it
whenever a row may have no match, and check the NULL keys before the
conditions of the subquery so that they are short-circuited.

ClickHouse#121848

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without short-circuit, `and` evaluates the conditions of the subquery also
for rows with a NULL key, which the subquery skips, so a condition like
`intDiv(10, s.v) > 0` could throw only with the rewrite.

ClickHouse#121848

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ORDER BY ALL` shares the expressions of the projection, so the same
subquery was collected twice, and the second rewrite found the window
column where it expected the subquery: a `LOGICAL_ERROR` exception.

ClickHouse#121848

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

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2e7c4c4a4 with master 962432765 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

4 object files changed (+322.68 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Passes/CorrelatedScalarAggregateToWindowPass.cpp.o new 319.85 KiB +319.85 KiB

716 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

9 translation units recompiled, 17 s compile time in total, 8 of them have a recent master baseline.

Job report

The test started a client three times per case, about 200 times in total,
and ran longer than 180 seconds in the ASan flaky check. Send the cases in
three batches instead and split the results by a marker line.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121848&sha=ee27e24dc998101466519d9b1a35a42c881548d3&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
ClickHouse#121848

Co-Authored-By: Claude Opus 5.5 <[email protected]>
raimannma and others added 5 commits October 5, 2026 23:34
A rewrite replaces the columns of its target in the whole query, but a
target is not rewritten while a subquery of another candidate is
correlated to it, so the outer keys of the remaining candidates are not
replaced. Add a case with subqueries over each other's table keyed by the
other table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With parallel replicas, the plan with the rewrite is built on the replicas,
and `EXPLAIN` on the initiator prints it in a form without
`Window step for window`, so every case reported `rewritten 0` in the
`ParallelReplicas` job although the rewrite happened. Disable parallel
replicas only for the queries that inspect the plan; the result batches
keep running with them.

The test took 223-249 s in the debug and sanitizer flaky checks, over the
180 s limit; almost all of it was the three batches of queries running one
after another. Run them concurrently.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121848&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel)
ClickHouse#121848

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ster and independent of parallel replicas

The flaky check failed `05244_correlated_scalar_aggregate_to_window` with "Test runs too long (> 180s)":
every case was run three times (without the rewrite, with it, and its plan), and with randomized settings
each query takes up to a few seconds there. The batch without the rewrite is dropped, since the reference
already pins those results, and the cases where the subquery is not rewritten move to the new test
`05385_correlated_scalar_aggregate_to_window_not_rewritten`. The helpers move to
`correlated_scalar_aggregate_to_window.lib`, and each test creates only the tables it reads.

With parallel replicas, every case reported `rewritten 0`: the rewrite happens, but the plan describes
the window step as `Window` instead of `Window step for window ...`. The rewrite is now detected by a window
function in `EXPLAIN QUERY TREE`, which does not depend on how the plan is built and does not build it.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121848&sha=c00f81e3fe4511686b956dcaf1824d1e147680e1&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121848&sha=c00f81e3fe4511686b956dcaf1824d1e147680e1&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
ClickHouse#121848
raimannma and others added 10 commits October 13, 2026 01:40
…_window_not_rewritten`

The `self-join` and `column named like a window column` cases are rewritten, so they belong to
`05244_correlated_scalar_aggregate_to_window`.
…ed-scalar-aggregate-to-window

# Conflicts:
#	tests/queries/0_stateless/05244_correlated_scalar_aggregate_to_window.sh
…der `ie_join`

`mayRestrictKeys` lets a condition on a joined table justify the rewrite because the
runtime filter of the join carries it to the window keys. No runtime filter is built
when `ie_join` is listed first in `join_algorithm`, or from a `Join` table, a
dictionary or a key-value storage, which are looked up instead of read into a hash
table, so the window then reads the whole table.
…type or without the join order optimization

No runtime filter is built for join keys without a common supertype. Without the join
order optimization (`query_plan_optimize_join_order_limit = 0`), the join sides are not
swapped, and the target may stay on the build side. Check whether a table is already
joined on the keys before the casts of its storage, and pin
`query_plan_optimize_join_order_limit` in the tests, since it is randomized.
A single key pair without a common supertype disables the runtime filter of the whole
join, so the other keys of the join do not restrict the windows either.
`toInt64(o.k) = ku.k` disables the runtime filter of the join as well as a key pair of
columns does.
…-aggregate-to-window

Upstream changed `supportsRuntimeFilter` to also take whether `grace_hash` can run and the join strictness.
`CorrelatedScalarAggregateToWindowPass` now passes `JoinSettings::canRunGraceHash` and `JoinStrictness::All`:
it takes the restricting conditions only from the ON of `ALL` and `ANY` joins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd fewer queries per run

In the flaky check, `05244_correlated_scalar_aggregate_to_window` and
`05385_correlated_scalar_aggregate_to_window_not_rewritten` ran longer than 180 s: every
copy competes with the other copies of the same test, and each of its ~190 queries took
about a second.

Split each test in two (`05407_correlated_scalar_aggregate_to_window_shapes` and
`05408_correlated_scalar_aggregate_to_window_not_rewritten_joins`), with the tables each
one needs. Send the check of the query tree before each query in the same batch: its single
row separates the results, so the marker queries and the second client are gone. Run the
materialized view case only with the rewrite, the reference pins the answer without it.
A run now sends 46 to 68 queries instead of 188 and 196.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121848&sha=0393bf2bb0e735c5e70405b1e1bb21f97c9edc00&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29
PR: ClickHouse#121848

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n the settings history

Master is now 26.11 and the setting was not released in 26.10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-aggregate-to-window

# Conflicts:
#	src/Analyzer/QueryTreePassManager.cpp
The assignment to `current` destroys the node `column` points to, so with two keys the next iteration
read freed memory when the argument was the first outer key.
…uch a condition

The filter push-down does not pass a window any more (ClickHouse#125463), so neither a condition on the keys
nor a runtime join filter restricted the generated window, which read and sorted the whole table.
The pass now copies the deterministic conditions on the keys of the windows into the derived table,
where they remove whole partitions only, and rewrites only when there is such a condition. The rule
for conditions on tables joined on the keys, which relied on the runtime filter, is removed with its
tests; the other tests get a condition on the key, so they still check the rewritten query.
Below the window a condition runs on every row of the table, also on rows the enclosing query never
evaluates it on, so `intDiv(10, t.k) > 2` could throw `Division by zero` only with the rewrite. Only
comparisons and logical functions are copied now.
Comment on lines +293 to +295
auto key_conditions = collectKeyConditions(target, enforced, common_keys);
if (!key_conditions.empty())
rewriteTarget(query_node_ptr, *tables.at(target).slot, target_candidates, key_conditions);

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.

[Major] Measure a query that the revised rewrite still accepts

The PR is categorized as a performance improvement, but there is no before/after measurement or performance test exercising optimize_correlated_scalar_aggregate_to_window. The measurements in the linked issue concern a different planner implementation and the original TPC-H Q17 shape; the revised pass explicitly stopped rewriting that shape without an additional key predicate. The new EXPLAIN indexes = 1 assertion establishes pruning, but does not establish a net benefit from replacing aggregation with sorting and a window.

Please include an interleaved setting-off/setting-on benchmark on the current implementation for a representative accepted query, recording elapsed time, rows read, and peak memory. This would show whether removing the second scan outweighs the added window and sort for the behavior now being proposed.

raimannma and others added 2 commits November 22, 2026 18:07
…row for their types

A list of function names does not establish that a condition cannot throw:
`equals` of `Decimal(18, 0)` and `UInt64` throws `DECIMAL_OVERFLOW` for a value that
does not fit, and below the window the condition runs on rows the enclosing query
never evaluates it on. Ask the resolved function through `IFunctionBase::canThrow`
with the types and constants of its arguments; only the logical functions are
still taken by name.

Also record the setting in the history of 26.12, the current version.

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

stresshouse Bot commented Nov 22, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

No query shows a performance change caused by this PR. The only flagged row, clickbench Q28 (+6.2%, 1007.0 ms to 1069.5 ms), stays inconclusive: the two tests disagreed, and the measurements on both sides were noisy. The PR adds a query-tree pass that rewrites correlated scalar aggregate subqueries into window functions. The pass sits behind an experimental setting that is off by default, and it does nothing unless that setting is enabled. Q28 has no correlated subquery, so this PR's code cannot explain the shift.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1007 1070 +6.2% <0.0001 cpu: Q28 is a regex-heavy GROUP BY with no correlated subquery, so the new pass, which is off by default, never rewrites it. The +6.2% is borderline, and both sides were noisy.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 21408c32-770c-479a-8492-9a2c3ba3a360
  • MIRAI run: 5c646e3a-773d-4972-91e0-cf5d038c3687
  • PR check IDs:
    • clickbench_831156_1795372055
    • clickbench_831162_1795372055
    • tpch_adapted_1_official_831187_1795372055
    • tpch_adapted_1_official_831220_1795372055

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

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

2 participants