Repository navigation
Conversation
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.
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 belowBefore publishing, an independent cold review plus a second-model gate re-review the tree, and every Blockers that were real bugs, all fixed before this reached you ❌ ❌ The new test could not have passed in CI: every functional job installs ❌ ❌ The mark-gated table concurrency limit sat outside the storage predicate: ❌ ❌ The projection refusal covered explicit projections only, while the implicit The one refusal, and one acceptance whose residual stands
Round 7's finding, unfixed, and the best evidence yet for the question in the description
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 = 1The 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 💡 Also round 7, benign: The standing residual, and the reason for the question in the description
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 💡 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 💡 Round 1's other consequences were structural: a branch with no |
|
Workflow [PR], commit [6ce7073] Summary: ❌
AI ReviewSummaryThe PR adds Missing context / blind spots
Final VerdictStatus: ✅ Approve |
Pre-PR validation gate (click to expand)
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.
`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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes299 object files changed (+428.17 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units909 translation units recompiled, 7039 s compile time in total, 908 of them have a recent master baseline. Translation units without a recent master baseline:
|
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
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.
CI finish ledger - c4e0908Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260919-110331 |
…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]>
…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]>
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]>
CI finish ledger - 6ce7073Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261022-103003 |
|
Update to the |
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.
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.
Changelog category (leave one):
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 ownWHEREconjuncts is answered with one scan instead of one per branch: each branch's own conjuncts become the condition of acountIf. On TPC-DS SF1 query 88 reads 87.5% fewer rows.Description
A cross/comma join of derived tables that aggregate the same
FROMand differ only in theirWHEREconjuncts reads it once per branch. Each returns one row (noGROUP BY), so one pass answers all: the shared conjuncts become the fused filter, the residuals areORed into it, and each becomes its branch's-Ifcondition. TPC-DS 88 and 90 have that shape.My measurements, SF1 release build, median of 5: query 88
129 -> 38 mson 87.5% fewer rows (eight scans become one), query 9027 -> 17 mson 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,432rows read and32 -> 481 ms.Scope: argument-less aggregates; with an argument the
-Ifcondition 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 noWHEREof its own, projections (explicit or forced), modifiers, a partition-read limit, non-ALLjoins. With the setting off, all 99 TPC-DS trees are byte-identical.For the
comp-query-analyzerowners: 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
CrossJoinNodethis pass matches on.Measurements and admissibility
6 reps, first dropped,
max_threads = 8: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, becauseIFunction::canThrowanswersfalseforintDiv(x, -1)although it throws); every source is aTableNodewhose 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,CROSSorALLjoins; no repeated table; every column physical and default-free; noadditional_table_filtersor 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 newIStorage::readsColumnsWithoutTransformations, whose base answer isfalse. The-Ifcondition type is checked as the aggregate factory presents it: underdata_type_default_nullablethe residuals of 88 and 90 areNullable(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]