Skip to content

Answer sibling count() subqueries over the same tables with one scan - #120502

Open
groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:fuse-sibling-aggregate-subqueries
Open

groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:fuse-sibling-aggregate-subqueries

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Experimental Feature

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

Added experimental setting optimize_fuse_sibling_aggregate_subqueries, disabled by default. When enabled, a cross/comma join of derived tables that each count rows over the same tables and differ only in their own WHERE conjuncts is answered with one scan instead of one per branch: each branch's own conjuncts become the condition of a countIf. On TPC-DS SF1 query 88 reads 87.5% fewer rows.

Description

A cross/comma join of derived tables that aggregate the same FROM and differ only in their WHERE conjuncts reads it once per branch. Each returns one row (no GROUP BY), so one pass answers all: the shared conjuncts become the fused filter, the residuals are ORed into it, and each becomes its branch's -If condition. TPC-DS 88 and 90 have that shape.

My measurements, SF1 release build, median of 5: query 88 129 -> 38 ms on 87.5% fewer rows (eight scans become one), query 90 27 -> 17 ms on half; controls flat.

Off by default, because one shape loses: when each branch's residual is prunable by the sorting key, several narrow scans become one broad one: on 32 ordered slices of 33.5M rows, 491,552 -> 33,554,432 rows read and 32 -> 481 ms.

Scope: argument-less aggregates; with an argument the -If condition stops protecting it. Also refused, because fusion changes what a read returns or costs: unsafe conjunct shapes, sources that transform what they read, a branch with no WHERE of its own, projections (explicit or forced), modifiers, a partition-read limit, non-ALL joins. With the setting off, all 99 TPC-DS trees are byte-identical.

For the comp-query-analyzer owners: this rewrite needs read-path facts a query tree cannot observe, so the guard list is long and the losing shapes are invisible to it. Sharpest: any of nine read/join limits set at all, whatever the value, skips the whole query, and ClickHouse's own stateless test profile sets eight. Is a query-tree pass with this admissibility set what you want, or does the choice belong in the planner? I will drop it if the answer is no.

Reported and prototyped by @ snelheidai (#120375); guards, scope and measurements mine. Related: #118697, and #119259 removes the CrossJoinNode this pass matches on.

Measurements and admissibility

6 reps, first dropped, max_threads = 8:

q duration read rows peak mem
88 129 ms -> 38 ms (-70%) 23,792,128 -> 2,974,016 (-87.5%) -78%
90 27 ms -> 17 ms (-37%) 1,626,088 -> 813,044 (-50%) -62%
28, 09, 16, 83 (controls) -10%..+7% (noise) unchanged unchanged

Controls' read rows and memory are exactly unchanged while durations move -10% to +7%, so read rows are the load-bearing metric. The committed perf test measures join-side widening (210 -> 40 ms, 198 -> 30 ms, -87.5% rows each); its residual columns lie outside every sorting key, so it cannot express the access-path case above.

A branch fuses only when it has its own WHERE; its aggregates take no arguments and none already carries -If; no clause changes its cardinality; every conjunct is a comparison or connective (a shape whitelist, because IFunction::canThrow answers false for intDiv(x, -1) although it throws); every source is a TableNode whose storage returns stored values unchanged and is not bounded by a limit on how far one read may span, with no projections and no modifier; only comma, CROSS or ALL joins; no repeated table; every column physical and default-free; no additional_table_filters or row policy; expressions stateless, query-deterministic, side-effect free; siblings share snapshots; residuals touch one table; no alias override; no forced projection; and none of nine read/join/temporary-column limits set. Reading a row can itself evaluate an expression, which the tree never shows, hence the new IStorage::readsColumnsWithoutTransformations, whose base answer is false. The -If condition type is checked as the aggregate factory presents it: under data_type_default_nullable the residuals of 88 and 90 are Nullable(UInt8).

Query 28 stays out: its aggregates take arguments, and its Decimal-vs-integer bounds need proving non-throwing.


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

A cross/comma join of derived tables that each aggregate the same FROM and
differ only in their own WHERE conjuncts reads that FROM once per branch.
Every such branch is a no-GROUP BY aggregation, so it returns exactly one
row, which makes a single-pass answer possible: keep the conjuncts every
branch shares as the fused filter, OR the branches' residual conjuncts into
it, and turn each residual into the condition of an -If combinator on that
branch's aggregates. TPC-DS query 88 (eight branches over the same four-table
join) and query 90 (two branches) have exactly this shape.

The new pass runs before CrossToInnerJoinPass so the join equalities the
branches share are still top-level AND conjuncts of the fused filter when
that pass turns them into join conditions.

Scope: aggregates that take no arguments. With an argument, the -If condition
stops protecting it and it would be evaluated on rows the branch's own filter
excluded; that needs argument-safety work this change deliberately leaves out.
It is also what makes the cost argument sound, since the conditions are then
the only per-row work the fused pass adds.

Evaluation safety is decided by a shape whitelist rather than by
IFunction::canThrow. canThrow falls back to short-circuit suitability, which
answers a different question and reports a cheap throwing function as not
throwing: intDiv(x, -1) is answered false and throws. Only the logical
connectives and the comparisons, which describe their own exception
behaviour, are accepted, and the check covers every conjunct of every branch
rather than only the residuals, because fusion also moves a shared conjunct
to a position where `and` no longer defers it.

Reading a row is not free either, and none of it is visible in the query
tree: a column can carry a DEFAULT that MergeTree evaluates inside the reader
for a part that does not store it, patch parts and pending mutations rewrite
values on the way out, and additional_table_filters and row policies are
attached per table expression in the planner, after the passes have run.
Fusion moves each branch's residual inside an OR, so less can be pushed into
PREWHERE and every column is materialized for more rows than before. Hence
the new IStorage::readsColumnsWithoutTransformations, which defaults to false
so that a storage that has not proven the property keeps today's behaviour;
MergeTreeData answers it from the captured storage snapshot and from live
bookkeeping, because the snapshot omits pending mutations when
apply_mutations_on_fly and apply_patch_parts are off while the reader still
converts. It mirrors the signature, placement and snapshot handling of its
neighbour supportsTrivialCountOptimization and reuses the enumeration
MergeTree already keeps for this question.

Residual conjuncts are confined to a single table: with residuals spanning
two tables the fused filter becomes a disjunction of per-branch conjunctions,
join filter push-down can only push each side's union, and the per-branch
correlation is lost, which cost 5.2x on a 16-branch probe.

The condition type is checked the way the aggregate factory will present it,
after LowCardinality unwrapping and the Null combinator, rather than raw:
under data_type_default_nullable the residuals of query 88 and query 90 are
Nullable(UInt8), and a raw isUInt8 check would refuse them and fuse nothing.

Closes: ClickHouse#120375
Review round 1 on the pass. Nothing changes the rewrite identity, the
argument-less scope, the shape whitelist or the storage predicate; all of it is
in one blind spot: the pass decided what a branch's WHERE means and never what
the branch's read costs, nor what a table-expression modifier does to it.

The setting now defaults to false. When sibling residuals are each prunable by
the sorting key, the unfused branches prune to a few marks apiece while the
fused OR scan keeps the rows of all of them and evaluates every -If condition
over the union. Measured on 32 ordered slices of 33,554,432 rows: read rows
491,552 -> 33,554,432, SelectedMarks 60 -> 4096, median 32 ms -> 481 ms. A
query tree cannot see access paths, so the pass cannot tell that case from the
winning one; the committed perf fixture cannot express it either, because its
residual columns lie outside every sorting key and both of its shapes are full
scans in both arms.

Four new fail-closed refusals:

A branch with no WHERE of its own. Unfused it is answered from part metadata
(applyTrivialCountIfPossible needs !hasWhere() and one aggregate); fused it
gains a second aggregate and empties common_conjuncts, which also suppresses
the OR, so the kept branch ends up with no filter and its sibling's predicate
survives only inside the projection, where it prunes nothing. Refused in
isFusableBranch rather than in planFusion, so the branch's filtered siblings
still fuse with each other.

A source that carries projections. A projection is selected against the
branch's own filter and the fused OR implies none of them, which under
force_optimize_projection turns a query that answered 250 250 into
PROJECTION_NOT_USED.

Any table-expression modifier. For an absolute SAMPLE the sampled set is
derived from the branch's own key condition
(convertAbsoluteSampleSizeToRelative over getApproximateTotalRowsToRead), which
fusion replaces with the merged one. The refusal is class-wide rather than an
enumerated subset, and it makes a contract out of something that was an
accident: TableNode::setTableExpressionModifiers replaces the shared storage
snapshot with a clone, so every modifier already failed the pointer-identity
check on the captured snapshot.

Nine per-query limits, because fusion answers N independently bounded reads and
joins with one and the limits are then evaluated on the fused shape. Each was
measured to turn a succeeding query into a failing one: max_rows_to_read and
max_rows_to_read_leaf give TOO_MANY_ROWS, the byte twins TOO_MANY_BYTES,
max_columns_to_read TOO_MANY_COLUMNS, max_temporary_columns and
max_temporary_non_const_columns their own codes in a one-value window; with
max_rows_in_join and join_overflow_mode = 'break' the count silently changed
from 60 60 to 50 50. max_memory_usage, max_result_rows, max_execution_time,
max_rows_to_group_by and max_subquery_depth are excluded, with reasons.

The tests now assert the one scan rather than only the -If insertion: branch
removal is a separate step of the pass, so a regression there would have left
all eight scans in place with every previous assertion green. Arms count TABLE
expressions in EXPLAIN QUERY TREE (8 -> 1 for the eight-branch arm), and a
mutation that keeps the rewrite and skips the removal reddens exactly the new
assertion while the countIf count stays 8.

Arm 29a pins query_plan_join_swap_table. join_overflow_mode = 'break'
truncates at a block boundary and which side is built decides where, so with
that setting left at auto the arm's count is 60 or 50 independently of this
pass: 12 of 50 randomized runs disagreed, at both values of the new setting.

Also: the repointed ColumnNode keeps its alias; arm 26a's fixture gives f2.x a
value independent of g, so a dropped residual changes its answer; arms 09a/09b
gained the tree assertions that make the -OrNull path non-vacuous; the
unreachable masking-policy conjunct in readsColumnsWithoutTransformations is
gone, since the live overload already reports MaskingPolicy; and
isReproducibleBranch's comment no longer credits isDeterministicInScopeOfQuery
with admitting now(), which the analyzer folds to a ConstantNode before the
predicate can see it.

Related: ClickHouse#120375
…n force

Review round 2. Both blockers are structural siblings of round-1 blockers:
each round-1 fix closed its family up to the boundary of how the family is
spelled, and the sibling on the other side rejects valid input.

A limit on how far one read may span. checkLimits takes the query value of
max_partitions_to_read when it is .changed and the table's own otherwise, then
throws TOO_MANY_PARTITIONS when the resulting read spans more partitions than
that. Fusion reads the union of the branches' rows, so N branches that each
touch one partition become one read touching N: two branches over two
partitions answered 1 1 unfused and raised Code 565 "Current 2, max 1" fused,
for the query spelling and for the table spelling alike.

It cannot join the array of query limits that round 1 refused. It is Int64
defaulting to -1, so testing it the way that array is tested would be true by
default and would fuse nothing; and its effective value can come from the
table, which the query settings cannot show. So the rule lives where the data
lives, as a second IStorage predicate answering whether a read is bounded by
such a limit, overridden in MergeTreeData off the same effective-value rule
checkLimits uses. Its default is the refusing answer, the opposite polarity
from its neighbour, because here an unanswered question has to mean do not
fuse. The other branch of checkLimits, max_concurrent_queries with
min_marks_to_honor_max_concurrent_queries, is deliberately not refused: a
fused read genuinely is the large read that limit exists to honor, the throw
needs real concurrency, and a table with both set to 1 fuses and answers.

A forced projection. The projection refusal added in round 1 reads
hasProjections(), which is !projections.empty(), and the implicit
minmax_count projection is a separate member of the same metadata object, so a
table with no projection of its own passed it. Rewriting count() into
countIf() makes the read ineligible for that projection, which turns
force_optimize_projection into Code 584 and force_optimize_projection_name
into Code 117, from two different enforcement sites, on a query that answered
250 250. Both settings are refused; the hasProjections() refusal stays, since
it also covers the unforced explicit case where a real projection would
silently have been used. On the unfused shape neither forcing setting fires at
all: applying the projection removes the ReadFromMergeTree step, so the checks
that need one are skipped, which is why the error appears only once fused.

The rest of the forcing family was swept one setting at a time rather than assumed:
force_data_skipping_indices, force_primary_key and force_index_by_date all
keep fusing and none throws, because the fused filter keeps every branch's
residual inside an OR that KeyCondition still uses.

Without a forcing setting the same rewrite silently gives up that access path,
which no query tree can see. That is the second instance of the limitation the
setting is off for, and it is disclosed in the PR body rather than guarded,
because refusing every MergeTree source would refuse queries 88 and 90 too.

Arms 32a, 32b and 33a, 33b assert that the answers agree and that nothing
fuses, each with a control line proving the same shape fuses when nothing is
set. Arms 33a to 33c pin optimize_use_projections and
optimize_use_implicit_projections, which the test runner randomizes at 5%: with
implicit projections off it is the unfused arm that raises 584, so the arm
would otherwise have been flaky about one run in twenty.

Also: arm 07 no longer credits query determinism for admitting now(), which the
analyzer folds to a constant before that predicate can see it; the WHERE
precondition established earlier in isFusableBranch is stated with a chassert
instead of being tested a second time; and the alias preserved on a repointed
outer column is measured to be unexercised in every shape the suite covers,
rather than left looking verified.

Related: ClickHouse#120375
ReadFromMergeTree::AnalysisResult::checkLimits has two branches. The first,
already mirrored by MergeTreeData::readIsBoundedBySpanLimit, bounds the
partitions one read may span. The second takes a table-wide slot once a read
selects at least min_marks_to_honor_max_concurrent_queries marks, and
MergeTreeData::insertQueryIdOrThrowNoLock throws TOO_MANY_SIMULTANEOUS_QUERIES
when the table is already at max_concurrent_queries: it rejects, it does not
wait or queue.

Fusion raises the kept read's selected_marks, since it reads the union of the
branches' rows, so branch reads that each stay under the mark threshold become
one read that crosses it and has to take the slot. Measured on a two-partition
table whose branch reads select 5 of 10 granules, with the threshold at 6 and
one concurrent query holding the single slot: the unfused query answers, the
fused one raises Code: 202. Neither setting has a query-level twin, so only a
storage predicate can answer this; the existing one gains checkLimits' second
clause instead of a third virtual being added, which completes that function -
both of its branches now refuse.

Arms 34a and 34b cover it, 34b being the same shape on a table with neither
setting, so the refusal is shown to be the settings and not the shape. The two
clauses were mutated separately to show that neither stands in for the other.

The setting reference enumerated one losing shape, which this PR's own evidence
falsifies, so it now names all three: residuals each prunable by the sorting
key, a count() the minmax_count projection could have answered without reading
rows, and the join build side that the fused residual widens towards an
external-join spill threshold.

Arms 11b and 11c gained a table-expression count. The rewrite names the fused
aggregate after the branch's own function, so an accidentally fused
count(DISTINCT k) emits uniqExactIf and an accidentally fused avg(k) emits
avgIf, and their countIf detector could never have matched either.

The perf test's two baseline arms no longer carry the new setting: false is
already its default, and every perf client is built with
settings_is_important=True, so the reference server rejected the unknown name
outright and those arms produced no two-server comparison at all.

Related: ClickHouse#120375
…limit

AggregateFunctionFactory rejects a name longer than 1000 bytes by throwing
TOO_LARGE_STRING_SIZE rather than by answering false, and
isAggregateFunctionName is one of the three lookup entry points that do so. The
pass built its candidate name and handed it straight to that predicate, so a
branch aggregate whose own name is at most 1000 bytes but over 998 produced a
candidate over the limit and the probe threw out of the analyzer: the query
failed with Code: 131 where it answered with the setting off. Such a name is
reachable in the pass's real scope, since combinator suffixes nest and an
argument-less suffixed aggregate is admitted. countState plus 110 OrDefault
suffixes is 1000 bytes, resolvable, and returns AggregateFunction(count).

The limit is now a public constant of the factory instead of a file-local one,
so the pass refuses on the same number the factory enforces. The factory's
throw is deliberately unchanged: its other callers rely on it to reject
over-long names in user SQL. The refusal sits before the probe, in the same
idiom as the condition-type pre-check below it, and nothing in the tree has
been mutated at that point, so returning an empty plan abandons the attempt for
free.

Arm 35 covers it, comparing finalized states rather than type names so that it
fails on a wrong count as well as on a wrong shape. One suffix shorter the
candidate name is inside the limit and the same shape fuses, so the boundary
and not the suffix family is what decides.

Arm 34's fixture no longer sets max_concurrent_queries to the minimum. The
guard reads only whether that setting and
min_marks_to_honor_max_concurrent_queries are both set, so the magnitude is
free to the guard, but it does bind the fixture's own reads:
insertQueryIdOrThrowNoLock throws rather than waiting, and the ParallelReplicas
test flavor routes one query through three replicas of the same server, each
presenting a distinct query_id. At 100 the guard still fires and the arm's
verdict is unchanged.

Arm 09b asserted nothing. aggregate_functions_null_for_empty appends OrNull
only when a function does not already return a default for an only-null input,
and count is registered as one that does, so the arm's reference lines were
byte-identical to the arm above it. It now covers an argument-less aggregate
carrying a combinator suffix, whose NULL for an empty branch survives the
rewrite as countOrNullIf, and it counts table expressions because a countIf
detector cannot see that name.

Related: ClickHouse#120375
FunctionComparison::canThrow answers false for a comparison of two operands of
exactly the same type, because such values are compared by IColumn::compareAt,
which reads them as they are stored. Variant, Dynamic and JSON are excluded
from that rule, since a comparison of those dispatches on the type held by each
individual row. The exclusion tests the top level only, and a tuple comparison
does not go through compareAt: it builds and executes a comparison for every
element, so a Tuple(Dynamic) passes canThrow and then raises NO_COMMON_TYPE on
a row whose two elements have no supertype.

isTotalOnEveryRow trusted canThrow beyond what it claims. Fusion evaluates a
branch's conjuncts on rows that branch's own filter excluded, so a query that
answered with the setting off failed with Code: 386 once it was on: valid input
rejected. The pass now mirrors the comparison's own three-way exclusion list at
any nesting depth, using IDataType::forEachChild, and applies it at both places
the predicate accepts a value: a function's argument types, and a bare column's
own type, which no later check would have type-tested. canThrow itself is left
alone, since its other callers rely on its current answer.

Arm 03d covers it with two Tuple(Dynamic) columns, one row whose elements are
equal integers and one whose elements are a String and an integer. The table is
partitioned on the branch key so that part selection, and not filter push-down,
keeps the throwing row out of the unfused branch's read: with the row in the
same part, moving the comparison to PREWHERE evaluates it on every row and the
unfused query throws as well, which would have made the arm depend on the plan
the randomizer draws. The fused filter's OR keeps both partitions, so the fused
query still reaches the row. The arm sweeps all three
short_circuit_function_evaluation values because force_enable defers the
residual and would answer even if the pass wrongly fused.

The test also sets the nine read and join limits the pass refuses on to zero.
tests/config/install.sh links users.d/limits.yaml for every functional job, and
that profile puts eight of them in the default profile, so the pass returned on
the first non-zero one and every arm asserting a rewrite asserted one that
could not happen in any CI flavor: 25 reference lines were wrong, including the
control that was meant to show the limit family refusing for the right reason.
Arms 29a to 29c keep their own limits in query-level SETTINGS, which override
the session-level SET, so each still tests the limit it names.

The setting's reference now names all nine limits and states that any non-zero
value skips the rewrite for the whole query, which is not derivable from the
guard list it documented before.

The factory constant's comment no longer claims that every lookup below it
throws: getDocumentation and the inherited alias probes do not check the
length. What matters to the pass is that an over-long name is answered by a
throw rather than by "not an aggregate function", and that is what it says now.

A column-source check on each branch's aggregates is removed. Every admitted
aggregate is argument-less, a FunctionNode's children are its parameters,
arguments and window, aggregate parameters are constants and the window child
is null here, so the check visited no column and could not fail. The
cloneAndReplace above it stays: the node is mutated in place further down and
an abandoned attempt must leave the sibling branch untouched.

Related: ClickHouse#120375
The setting's description enumerates the nine query limits precisely because
refusing on "set at all, whatever the value" is surprising: a user who set a
safety net otherwise gets nothing and has nothing to read. Two refusals of
exactly that class are per table and were undocumented: an effective non-zero
max_partitions_to_read, which is the query setting when it is set and the
table's own MergeTree setting otherwise, and a table that sets both
max_concurrent_queries and min_marks_to_honor_max_concurrent_queries to
non-zero values.

Both are reached through IStorage::readIsBoundedBySpanLimit, which mirrors
ReadFromMergeTree::AnalysisResult::checkLimits. The fused read spans the union
of the partitions and the marks the branches read, so each of those bounds is
evaluated against that union instead of against the per-branch reads, which is
the same reason the nine query limits give. Arms 32 to 34 already cover the
behaviour; only the description was behind it.

The trailing DROP block of 05218 also gains dyn: the leading block creates and
drops 23 fixtures while the trailing one named 22. The runner drops the
per-test database either way, so this is consistency rather than a leak.

Related: ClickHouse#120375
Delete the blocks that narrate the rewrite's own design and its refuted alternatives, keep the ones stating a non-obvious property of an existing entity, and shorten the survivors.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 7 rounds, 42 findings, 41 AGREEd and 1 refused with evidence; one AGREEd major left unfixed at the bounce cap and described below

Before publishing, an independent cold review plus a second-model gate re-review the tree, and every
finding is adjudicated against the code rather than against the author's account of it.
Bounce cap reached at round 6: published as-is; residual findings listed below.
Round 7 reviewed the tree and could not send it back, so one of its findings is a major that is NOT fixed here.

Blockers that were real bugs, all fixed before this reached you

❌ Tuple(Dynamic) defeated the totality check: comparison excludes Variant/Dynamic/JSON at the top level only, while a tuple comparison builds one per element, so (42) vs (42) and ('x') vs (42) answered 1 1 off and Code: 386 NO_COMMON_TYPE on. The refusal is recursive over the compared types now.

❌ The new test could not have passed in CI: every functional job installs tests/config/users.d/limits.yaml, which sets eight of the nine per-query limits the pass refuses on, so 22 assertions would have contradicted the reference on the first run. Cleared at file scope, verified on a server carrying that profile.

❌ AggregateFunctionFactory::isAggregateFunctionName throws TOO_LARGE_STRING_SIZE above 1000 bytes rather than answering false, so appending If gave Code: 131 on a query that succeeded off. Length is checked before the probe, and that was the last throwing call in the admissibility path.

❌ The mark-gated table concurrency limit sat outside the storage predicate: checkLimits takes a table-wide slot once a read selects min_marks_to_honor_max_concurrent_queries marks and throws at the limit rather than waiting, measured as Code: 202. My own earlier note had called it throttling, so that verdict was reversed.

❌ max_partitions_to_read escaped the guard covering nine query-level limits because it is Int64, defaults to -1 and can be carried by the table: TOO_MANY_PARTITIONS on a query that succeeded.

❌ The projection refusal covered explicit projections only, while the implicit minmax_count projection is a separate member of the same metadata object every MergeTree table carries: PROJECTION_NOT_USED once count() became countIf().

The one refusal, and one acceptance whose residual stands

⚠️ Refused with evidence: the external-join spill thresholds. Every failing arm of the probe ran grace_hash_join_max_buckets = 1 against a default of 1024 ("Too many grace hash join buckets (2 > 1)"), so the fused side was 512x inside the default; max_bytes_ratio_before_external_join defaults to 0.5, so the proposed test would refuse every multi-table branch, which is exactly queries 88 and 90. The join limits that do reject are already refused; the cost half is documented in the setting.

⚠️ Accepted, half fixed: the performance fixture's fused arms name a setting the reference server does not have, so each is a one-server measurement. Round 3 moved the baseline arms across both servers; the fused arms cannot, and the alternative is not measuring the rewrite at all. A partial query is failing-eligible on run-time variance, which is worth knowing as a diagnosis.

Round 7's finding, unfixed, and the best evidence yet for the question in the description

⚠️ cross_to_inner_join_rewrite = 2 is not refused, so with that setting a query that raised INCORRECT_QUERY returns a result instead. That value forces the rewrite of all comma joins, and CrossToInnerJoinPass::checkNotRewritten throws when a comma gap has no equi-join condition; this pass runs immediately before it and, when a group fuses, leaves the surviving branch alone, so that pass bails at its CROSS_JOIN guard and never reaches the throw:

SET cross_to_inner_join_rewrite = 2;
SELECT a, b FROM (SELECT count() AS a FROM t WHERE v > 10 AND k = 300) AS x,
                 (SELECT count() AS b FROM t WHERE v > 10 AND k = 500) AS y
WHERE a + b > 0;   -- INCORRECT_QUERY at = 0, returns `1 1` at = 1

The direction is only ever error to success, never the reverse: no wrong results, and with the setting off by default no configuration in use today changes. It is the same contract class this pass already refuses for force_optimize_projection, it is the only such consumer running directly after this pass, and no arm covers it. Unfixed because round 7 is past the internal bounce cap; the guard would be one clause, and whether that clause should exist is what I am asking below.

💡 Also round 7, benign: isTotalOnEveryRow's contract is broader than its comment claimed. A conjunct the analyzer folded to a constant is skipped without descending, so it never meets the shape whitelist and reports no table dependency to the single-table residual guard; both are sound, because such a fold is type-driven and hence row-independent. The clone keeps a source expression pointing at the fused-away branch, whose weak column source then expires; nothing that changes an answer reads it.

The standing residual, and the reason for the question in the description

⚠️ Five rounds each found a new member of one class: a bound or an access path whose outcome depends on how much a single read covers. Nothing proves that list complete, and the pass cannot see the read path by construction. Hence the setting is off by default (off, the pass returns at its first statement and all 99 TPC-DS query trees are byte-identical), and I would rather have the layer question answered than assume the enumeration is closed. I deliberately added no guard, ProfileEvent or log line for it: the remedy is a ruling, not more scaffolding.

⚠️ readsColumnsWithoutTransformations delegates to getColumnDefaultnessStatsUnavailableReason, which was written for another question (whether a part's recorded num_defaults can be trusted). Every reason it enumerates is a read-time transformation, so the answer is right today, but nothing ties the two questions together.

Noted, not blocking

💡 The setting's description misstates one of its own restrictions, and this is the item I would have bounced had a round been left, because it is the text a user reads to decide: the confinement to comparisons over "a single one of those tables" applies to the residual conjuncts only, while the shared conjuncts are cloned with no source restriction and routinely span every table, which is exactly the join equalities query 88 depends on.

💡 One of the two new IStorage predicates has a base default unreachable behind the other, fail-safe in both directions. Four refusals have no arm (PREWHERE in a branch, a branch-level SETTINGS clause, WITH TOTALS, a non-MergeTree source reaching the base false); all fail closed. enable_shared_storage_snapshot_in_query = 0 also disables the rewrite and is not in the setting's text; the default is true and both directions are asserted.

💡 Earlier rounds' nits, all fixed: a comment claiming every factory lookup throws for an over-long name; a guard that could not fail while its comment described what it could not see; refusal arms asserting only the substring countIf; an arm crediting query-determinism for admitting now() when the analyzer folds it first; a hasWhere() precondition tested twice; a fixture bound by the limit it was written to test; an arm advertising aggregate_functions_null_for_empty coverage that count cannot exercise.

💡 Round 1's other consequences were structural: a branch with no WHERE of its own lost a metadata-only answer and took its siblings' filters out of the reader's reach (refused outright now), and an indexed-residual shape measured ~13x slower fused (0.0335 s to 0.4365 s, 61 to 4096 marks), which is why the setting ships off by default and why the perf fixture's inability to express that case is stated rather than glossed.

@clickhouse-gh clickhouse-gh Bot closed this Sep 17, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6ce7073]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, sequential, 1/2) FAIL
05239_workload_drop_memory_reservation_in_use FAIL cidb
AST fuzzer (amd_release, oracle) FAIL
Segmentation fault (STID: 2844-39f8) FAIL cidb
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
long_primary_key #2 FAIL dashboard

AI Review

Summary

The PR adds optimize_fuse_sibling_aggregate_subqueries, an experimental setting disabled by default that combines eligible sibling aggregate subqueries into one scan using conditional aggregates. Review of head 6ce707350e38f162124e90adf0a2cb70c5d0e100 found no new actionable issues. Earlier findings are addressed or covered by documented tradeoffs appropriate to the experimental setting; no further inline comments or thread changes are needed.

Missing context / blind spots
  • ⚠️ Review was static: no local compiled clickhouse binary was available to rerun the regression tests. Current-head functional CI results would provide independent execution evidence.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Setting-keyed rather than flaky: EXPLAIN QUERY TREE of all 99 TPC-DS queries at optimize_fuse_sibling_aggregate_subqueries 0 and 1, plus 35 numbered arms (163 asserted lines) at both values on a server carrying ClickHouse's own stateless profile (tests/config/users.d/limits.yaml); 50 randomized runs, 50 passed, 0 errors.
b Root cause explained? Nothing recognises that the sibling QueryNodes read the same tables, so each is planned and executed on its own; each is a no-GROUP BY aggregation returning one row, so count() over the rows branch i kept equals countIf(residual_i) over the union of all branches' rows.
c Fix matches root cause? The rewrite implements that identity, and every admissibility guard is a refusal rather than a widened bound or a symptom check. The one shape that loses, sibling residuals the sorting key can prune independently (491,552 -> 33,554,432 read rows), is why the setting defaults to off instead of the pass guessing.
d Test intent preserved / new tests added? Nothing existing was weakened. New 05218_fuse_sibling_aggregate_subqueries: 35 arms, each asserting both the answer and the query tree, and counting table expressions, so branch removal alone can redden the suite (mutation keeping the -If rewrite and skipping the removal moves the table count 1 -> 8). One vacuous arm was replaced, not kept, and the perf shapes were confirmed to fuse before their timings were trusted.
e Both directions demonstrated? With the change: q88 gains 8 -If, q90 gains 2, the other 97 trees byte-identical. Each guard reverted alone, on a rebuilt binary whose Build-ID is asserted to differ from the pristine one, reddens a named arm: Code: 153, 161, 565, 584, 117, 202, 386 and 131, plus 25 reference lines flipping when the limits SET is removed on a server carrying the CI profile. Two guards are stated as fail-closed with no answer-changing shape found rather than claimed as repairs.
f Fix is general across code paths? The pass is the only new decision site, and both places the totality predicate judges a type are covered. The read-path question is answered by two new IStorage predicates whose defaults keep today's behaviour for every storage that has not proven the property; MergeTreeData overrides them from the captured snapshot and from live bookkeeping, and mirrors both branches of ReadFromMergeTree::AnalysisResult::checkLimits.
g Fix generalizes across inputs? Arms cover Nullable, LowCardinality, NULL conditions, Decimal at equal and unequal scale, Enum, String, Variant/Dynamic/JSON at any nesting depth, empty branches, branches with no WHERE, 2, 3 and 8 branches, one- and two-table joins, FINAL, absolute and relative SAMPLE, projections, ARRAY JOIN, aggregates with and without arguments, a suffixed name at the factory's length limit, and the settings matrix. The modifier and projection guards are class-wide predicates, not enumerated subsets.
h Backward compatible? New setting only, off by default, with its SettingsChangesHistory.cpp row in the current 26.9 block; = 0 reproduces the previous behaviour exactly, measured as byte-identical query trees for all 99 TPC-DS queries. No existing default changed.
i Invariants and contracts preserved? Aggregate states stay per-branch, the fused subquery still returns exactly one row, shared conjuncts keep their membership of the top-level AND, residuals stay within one table, and nothing in the tree is mutated until every check has passed, since planFusion abandons an attempt by returning an empty optional. ClickHouse's own post-pass tree validator passes, and it is what caught a column-source defect during the mutation sweep, fixed in this diff.

Session id: cron:clickhouse-impl-slot-4:20260917-011600

Master rolled 26.9 -> 26.10 after this branch declared
optimize_fuse_sibling_aggregate_subqueries, which left the record in a block
that is now historical. The settings_changes_history style leg reads the
current version from cmake/autogenerated_versions.txt and demands the record
under that block, so the Style check went red on the published head.

Move the single entry from the 26.9 block into the 26.10 block, keeping the
name, both values and the reason text identical, and without leaving a second
copy behind: an older block keeps entries only for backports, and the file
header warns against duplicate keys.
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 17, 2026
`cross_to_inner_join_rewrite = 2` asks for a comma join with no equi-join
condition in WHERE to be rejected with INCORRECT_QUERY, and
CrossToInnerJoinPass reaches that check only while the query's join tree is
still a CROSS_JOIN. FuseSiblingAggregateSubqueriesPass runs immediately before
it and, when every branch of the join fuses into one, replaces the join tree
with the surviving branch, so the rejection never happens:

  SELECT a, b
  FROM (SELECT count() AS a FROM t WHERE v > 10 AND k = 300) AS x,
       (SELECT count() AS b FROM t WHERE v > 10 AND k = 500) AS y
  WHERE a + b > 0
  SETTINGS cross_to_inner_join_rewrite = 2

raised INCORRECT_QUERY at optimize_fuse_sibling_aggregate_subqueries = 0 and
returned `1 1` at 1.

Refuse the fusion for a comma join whenever that value forces the rejection.
This is the shape of the existing force_optimize_projection refusal: a setting
that turns a lost access path into an error is checked before the tree is
changed. An explicit CROSS JOIN is never force-rejected, so it still fuses.

The refusal is keyed on the setting's value and on the comma, not on whether
the rejection would fire for this particular WHERE; deciding the latter would
mean replaying CrossToInnerJoinPass's equi-condition analysis inside this pass.

Also correct the setting's description: only the conjuncts a branch does not
share with its siblings are confined to a single table, which is what the
TPC-DS q88 shape depends on.
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6ce707350 with master 11d1ea9b2 (stripped binary size, per-symbol sizes and ThinLTO time; 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

299 object files changed (+428.17 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Passes/FuseSiblingAggregateSubqueriesPass.cpp.o new 231.42 KiB +231.42 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

909 translation units recompiled, 7039 s compile time in total, 908 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Analyzer/Passes/FuseSiblingAggregateSubqueriesPass.cpp: 5.3 s

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 88cb10f6-1c4c-47f9-81d4-f3368a1ee71e
  • MIRAI run: 6f1653b7-927b-4a36-8939-81d124fcb912
  • PR check IDs:
    • clickbench_2068498_1790496899
    • clickbench_2068504_1790496899
    • clickbench_2068509_1790496899
    • tpch_adapted_1_official_2068516_1790496899
    • tpch_adapted_1_official_2068526_1790496899
    • tpch_adapted_1_official_2069060_1790496921

groeneai and others added 3 commits September 17, 2026 09:19
The setting documents the widened build side of a multi-table branch as a cost:
"Spilling is a graceful fallback rather than an error, but it costs." At the edge it
is an error. A grace hash join doubles its bucket count as its build side grows and
raises LIMIT_EXCEEDED rather than pass grace_hash_join_max_buckets, so eight branches
that each build 1000 right rows answer while the fused OR that builds 8000 does not:

  optimize_fuse_sibling_aggregate_subqueries = 0
    -> 1000 1000 1000 1000 1000 1000 1000 1000
  optimize_fuse_sibling_aggregate_subqueries = 1
    -> Code: 290, Too many grace hash join buckets (2 > 1) ... (LIMIT_EXCEEDED)

with every other setting equal. That is arm 37.

Only the auto-conversion path reaches it. GraceHashJoin::rehashBuckets runs when
hasMemoryOverflow says so, and that has three disjuncts: the plan-level spill
scheduler, max_rows_in_join / max_bytes_in_join, and the threshold SpillingHashJoin
passes when it converts a hash join. Standalone instances pass 0 for that threshold,
so an explicit join_algorithm = 'grace_hash' can only get there through the two limits
the pass already refuses on. Measured: that shape does not rehash even at
grace_hash_join_max_buckets = 1, and the pass refuses to fuse as soon as either limit
is set.

No bail-out for the remaining path. Its carrier max_bytes_ratio_before_external_join
defaults to 0.5, so a refusal keyed on it would refuse every multi-table branch, which
is where this setting wins: TPC-DS q88 reads 87.5% fewer rows precisely because eight
scans of the same four-table join become one. The bound is narrow as well. Fusing N
branches costs at most ceil(log2(N)) extra bucket doublings, so the unfused query has
to be using more than grace_hash_join_max_buckets / N buckets already, which is 512 of
the default 1024 for two branches.
The flaky check runs one changed test in nproc-1 copies at once, so a test's own
cost is multiplied by that concurrency. 05218_fuse_sibling_aggregate_subqueries
takes 1.69 s locally (median of 20 randomized runs, debug build) and 156 s per run
in Stateless tests (amd_asan_ubsan, flaky check), where 5 of 50 runs crossed the
180 s per-run limit and failed with "Test runs too long (> 180s)".

What costs is the number of statements, not any one arm: the file's 324 queries
share 878 ms of server CPU and the largest single query is 47 ms. So arms 23 to 37
move verbatim to 05218_fuse_sibling_aggregate_subqueries_2.sql, each file creating
only the tables its own arms read. The two halves measure 0.79 s and 0.88 s
(median of 50 randomized runs each, 0 failures), which projects to 73 s and 81 s
in that job, and to 93 s and 104 s for a run as slow as the slowest one it
measured.

Three fixture inserts also drop their inline VALUES for the values() table
function: an insert with inline data costs ~57 ms of client round trips, measured,
where the same rows through values() cost ~3 ms. dyn keeps VALUES, because
values() casts tuple(42) to Tuple(Dynamic) storing UInt8 where the inline path
stores UInt64, and arm 03d is about how those element types dispatch per row.

No arm, assertion or fixture row changes. The two references concatenate to the
previous one byte for byte, and the 254 non-blank arm lines are identical in
sequence.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c4e0908

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 2/6) / test_storage_nats/test_nats_jet_stream.py (18 of 1221) whole-file cascade inside the vendored NATS client, unreachable from this diff, which touches the analyzer, the aggregate function factory and MergeTree metadata but no NATS or networking code: one real failure in test_nats_restore_failed_connection_without_losses_on_write (:1146, query_with_retry), then 17 teardown failures at :177 (DROP DATABASE IF EXISTS test SYNC), every one of them Code: 210 ... Connection refused (172.16.2.3:9000), so the server stopped accepting connections mid-module. That is the libuv-adapter reconnect-versus-close race, fixed by ClickHouse/nats.c#5 (mine, merged 2026-09-13 as cb4edba96601), which the contrib/nats-io pin on master (3e3a3f10) is still 4 commits behind #120202 (external, open), which pins contrib/nats-io to b88704df: 1 commit ahead of cb4edba96601 and 0 behind it, so it delivers that fix
Mergeable Check, PR praktika rollups of the row above, no independent failure of their own #120202 (external, open)

Session id: cron:our-pr-ci-monitor:20260919-110331

alexey-milovidov and others added 5 commits September 26, 2026 23:23
…ate-subqueries

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]>
…ss check

`MergeTreeData::getColumnDefaultnessStatsUnavailableReason(query_context,
mutations_snapshot)` was removed by ClickHouse#116365, which had no caller for it on
master; `readsColumnsWithoutTransformations` was its only caller, so the merge
of master broke the build (`Fast test`, `Build (arm_tidy)`).

Its checks are inlined: refuse on an active transaction, and on patch parts,
data mutations or alter mutations in the captured snapshot. The transaction
check stays unconditional. The remaining live check now skips it for storages
that support transactions, so calling that one alone would make the pass fuse
inside a transaction on a plain MergeTree, which it refused before. The pass's
admissibility is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The setting's description said that the conjuncts a branch does not share with
its siblings must all read a single one of the tables, which reads as a rule
per branch. The pass collects the tables of every branch's residual conjuncts
into one set and refuses when it holds more than one, so a group where one
branch filters on `f1` and another on `f2` is not fused. That shape does keep
its answers when fused, but the fused disjunction spans two tables and cannot
be pushed into either table's read, so it is refused on cost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`max_partitions_to_read` defaults to `-1`, and the pass refuses only a positive
effective value, so the setting's description now says positive rather than
non-zero, which read as if the default disabled the rewrite.

The refusal of residual conjuncts over different tables was explained as a
loss of per-branch correlation. Each branch keeps its whole residual both as
its `-If` condition and as one disjunct of the fused filter, so the answers do
not change; the limit is on cost, because an `OR` over conjuncts of different
tables can only filter joined rows. The comment and the arm 26 label now say
that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Branches were fused whatever the strictness of the joins in their FROM. For
ANY, SEMI, ANTI and ASOF the rows a join returns depend on which rows reach it,
and PASTE pairs rows by position. Fusion widens the filter pushed below a
branch's join to the disjunction of every branch's condition, so such a join
can pick a row that satisfies only another branch's condition.

For `l INNER ANY JOIN r ON l.k = r.k` with two `r` rows for one key, one per
branch filter (`WHERE r.f = 1` and `WHERE r.f = 2`), the two branches answered
`1 1` with the setting off and `1 0` with it on. The same happened for a plain
`JOIN` under `join_default_strictness = 'ANY'`.

A branch is now fused only when every join in its FROM has ALL strictness and
is not PASTE, and the setting's description says so. ALL joins still fuse and keep their answers, and the TPC-DS query
trees that change are still exactly those of queries 88 and 90.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
…tting

The setting was declared with the production tier, but the rewrite is a new
execution strategy whose admissibility rules are not known to be complete: a
query tree cannot see every read-path fact that fusion changes, and the
setting's own description lists admitted shapes that turn a successful query
into an exception (a fused grace hash join that needs more buckets than
`grace_hash_join_max_buckets`). That is what the experimental tier is for, so
the setting is now `EXPERIMENTAL`, declared the same way as
`analyzer_inline_views`.

Nothing changes in the default configuration. A server that sets
`allow_feature_tier` to 1 or higher now refuses to enable it with `READONLY`,
as it does for every other experimental setting. The default stays `false`, as
`03413_experimental_settings_cannot_be_enabled_by_default` requires, and the
history record is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 22, 2026 03:49
Master replaced the recursive `IDataType::forEachChild` with index-based
child enumeration and the walkers in `DataTypes/TypeTree.h`.
`typeDispatchesPerRow` now uses `anyInTypeTree`, which visits the root and
every nested type in pre-order, the same set the old
`check(type); type.forEachChild(check)` visited.

The current version is now 26.11, so the history record of the new setting
`optimize_fuse_sibling_aggregate_subqueries` moves from 26.10 to 26.11; the
setting did not exist in 26.10.

Also drop a test comment's pointer to `evidence.md`, which is not in the
repository.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6ce7073

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) / Segmentation fault (STID: 2844-39f8) crash, not from this PR: the fuzzed query (a mutant of 04204_crosstab_variant_merge run with make_distributed_plan = 1) segfaults with the same stack in CrossTabCountsState::merge on a master build, without the new pass #119401 (mine, open; the fix for this stack is being added to it)
Stateless tests (arm_asan_ubsan, azure, sequential, 1/2) / 05239_workload_drop_memory_reservation_in_use flaky, not from this PR: KILL QUERY ... SYNC got NOTHING_TO_KILL because DROP WORKLOAD had already failed the query; it passed 3 of 3 reruns and fails the same way on master #127158 (mine, open)
Performance Comparison (arm_release, master_head, 4/6) / long_primary_key #2 perf noise, not from this PR (its new pass is off by default): +25.2% (0.409 s to 0.513 s) against the performance reference build of 11d1ea9b25dd; the same query was reported slower on 13 other PRs in the last 24 hours a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above #119401, #127158 and the fix task above (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-103003

@groeneai

Copy link
Copy Markdown
Collaborator Author

Update to the Performance Comparison (arm_release, master_head, 4/6) / long_primary_key #2 row of the ledger above: the PR build and the reference run the same primary key analysis (216001 marks), and this query's speed follows the build's layout (performance reference builds of master went from about 0.31 s to 0.41 s at d879e48 while official builds of the same commits stayed at 0.31 s), so it is not this diff. How the gate should treat such rows is now a question for the dashboard owner: #122350 (comment)

zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Nov 19, 2026
Add the setting `optimize_merge_scalar_subqueries` (enabled by default). With the analyzer it merges uncorrelated `count`, `sum`, `avg`, `min` and `max` scalar subqueries in the `SELECT` list over the same local `MergeTree` or `Memory` table into one shared scan, implemented as a batch scalar-cache evaluation in `QueryAnalyzer::evaluateScalarSubqueryIfNeeded`.

- Group candidates by shared key/partition conjuncts so partition and primary-key pruning are preserved, and avoid merging variable-width payload columns across distinct `WHERE` filters so `PREWHERE` granule skipping is retained. Non-shared conditions are applied through the `-If` combinator.
- Preserve outward query contracts including `_subquery_N` projection names, `CREATE VIEW` column metadata, `ConstantNode` folding, temporary-table shadowing, `StorageAlias` targets, `INTERSECT` trailing `SETTINGS`, and `*nullIn` set operations. Enforce table and column `SELECT` grants and row policies.
- Resolve `SELECT`-list siblings once per enclosing query and bucket them by group key, so analysis stays linear in the number of subqueries that cannot be merged.
- Skip merging in only-analyze mode, where `SELECT`-list subqueries must not be executed; when `max_columns_to_read`, `max_temporary_columns` or `max_temporary_non_const_columns` is set, since the merged scan reads the columns of all subqueries in one read step; and when `additional_table_filters` is set, since those filters are keyed by table alias. Restrict decimal comparisons to equal scales, because rescaling can overflow on rows outside a subquery's own filter.

Closes: ClickHouse#120443
Related: ClickHouse#120375
Related: ClickHouse#120502

Add one functional test covering result and outward-contract preservation, access control, and differential checks that every merged query returns the same results and types as with `optimize_merge_scalar_subqueries = 0`, plus a performance test.
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Nov 19, 2026
Add the setting `optimize_merge_scalar_subqueries` (enabled by default). With the analyzer it merges uncorrelated `count`, `sum`, `avg`, `min` and `max` scalar subqueries in the `SELECT` list over the same local `MergeTree` or `Memory` table into one shared scan, implemented as a batch scalar-cache evaluation in `QueryAnalyzer::evaluateScalarSubqueryIfNeeded`.

- Group candidates by shared key/partition conjuncts so partition and primary-key pruning are preserved, and avoid merging variable-width payload columns across distinct `WHERE` filters so `PREWHERE` granule skipping is retained. Non-shared conditions are applied through the `-If` combinator.
- Preserve outward query contracts including `_subquery_N` projection names, `CREATE VIEW` column metadata, `ConstantNode` folding, temporary-table shadowing, `StorageAlias` targets, `INTERSECT` trailing `SETTINGS`, and `*nullIn` set operations. Enforce table and column `SELECT` grants and row policies.
- Resolve `SELECT`-list siblings once per enclosing query and bucket them by group key, so analysis stays linear in the number of subqueries that cannot be merged.
- Skip merging in only-analyze mode, where `SELECT`-list subqueries must not be executed; when `max_columns_to_read`, `max_temporary_columns` or `max_temporary_non_const_columns` is set, since the merged scan reads the columns of all subqueries in one read step; and when `additional_table_filters` is set, since those filters are keyed by table alias. Restrict decimal comparisons to equal scales, because rescaling can overflow on rows outside a subquery's own filter.

Closes: ClickHouse#120443
Related: ClickHouse#120375
Related: ClickHouse#120502

Add one functional test covering result and outward-contract preservation, access control, and differential checks that every merged query returns the same results and types as with `optimize_merge_scalar_subqueries = 0`, plus a performance test.

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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-experimental Experimental Feature pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sibling aggregate subqueries over the same tables are answered with one scan each instead of one scan total

2 participants