Repository navigation
Conversation
When an ARRAY JOIN column's element value is never referenced (e.g. SELECT count() FROM t ARRAY JOIN arr), only the array's length matters: ARRAY JOIN emits one row per element regardless of the values. Previously the whole arr column was read just to multiply rows. PruneArrayJoinColumnsPass already tracks whether each join expression's value is used. When an unused expression is a plain physical Array/Map column, replace it with arrayWithConstant(length(arr), 0). The per-row lengths are identical (so count(), and LEFT ARRAY JOIN over empty arrays, are unchanged), and the subsequent FunctionToSubcolumnsPass rewrites length(arr) to the lightweight arr.size0 subcolumn, so only the offsets are read from storage. arrayWithConstant is used rather than range() because range() enforces function_range_max_elements_in_block, which would turn a previously working query into an error. Gated on optimize_functions_to_subcolumns. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260717-100900 |
|
cc @KochetovNicolai @novikd — could you review this? It extends |
|
Workflow [PR], commit [9478ee7] Summary: ❌
AI ReviewSummaryThis PR introduces Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 117/129 (90.70%) · Uncovered code |
|
📊 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
|
…-JOIN rewrite The PruneArrayJoinColumnsPass change in this PR rewrites an ARRAY JOIN column whose element value is unused to arrayWithConstant(length(arr), 0), so both tests query a plan that now reads arr.size0. Data results are unchanged (03355: [1,2] rows identical; 03356: [0,1,2] rows and idx1/idx2 granule pruning identical); only the EXPLAIN QUERY TREE / EXPLAIN indexes plan shape changed. Regenerate both references. The new plan shape is gated on optimize_functions_to_subcolumns, which CI randomizes, so pin optimize_functions_to_subcolumns=1 in both tests to keep the reference deterministic. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Replace the arrayWithConstant-based approach with a dedicated analyzer pass RewriteArrayJoinCountPass that rewrites a bare count() over an ARRAY JOIN (whose element value is never used) into sum(length(e)) (LEFT ARRAY JOIN: sum(greatest(length(e), 1))) and removes the ARRAY JOIN. FunctionToSubcolumnsPass then folds length(e) into e.size0, so only offsets are read. The previous approach synthesized arrayWithConstant(length(arr), 0): it hit that function's per-block TOO_LARGE_ARRAY_SIZE cap (which plain ARRAY JOIN does not have, a correctness regression for large counts), and it fired even when the array was read elsewhere (adding a synthetic array on top of the full read). Summing lengths builds no array, so neither problem can occur. Revert the arrayWithConstant addition in PruneArrayJoinColumnsPass and the 03355/03356 test edits (projection tests, unaffected by the count-only rewrite). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-1:20260718-024748 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 4 findings across rounds; bounded: 1 full pass + 1 fix round + 1 delta recheck; final delta recheck: 0 findings).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-1:20260718-024748 |
|
cc @KochetovNicolai @novikd — the approach changed based on the review: instead of rewriting the ARRAY JOIN input to |
The analyzer is enabled by default since ClickHouse 24.3, so the various style sub-check forbids describing it as a "new analyzer". Reword the comment in 04545_count_array_join_reads_sizes.sql to "analyzer pass". Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — 53cee8dCI fully finished on this head (Config Workflow, Finish Workflow both SUCCESS; the Mergeable Check / PR reds are the rollup of the failures below). None are PR-caused: this PR's diff is a new analyzer pass (RewriteArrayJoinCountPass) for
Every line owned; none PR-caused. Session id: cron:our-pr-ci-monitor:20260718-093000 |
|
@groeneai merge the latest master in this PR |
…-count-array-join-size0
|
@Manerone Merged current master (up to 9f49403) into the branch; new head 5103f6e. No conflicts, and the diff vs master is unchanged (only the 5 files of this PR, no submodule/contrib drift). Rebuilt clean and the RewriteArrayJoinCountPass + 04545 test are intact (test green: count() over ARRAY JOIN == sum(length), LEFT == sum(greatest(length,1)), Finding-2 guard still declines when arr is read elsewhere). CI re-triggering on the new head. |
CI finish ledger — 5103f6eCI is fully finished on this head (the 2026-07-20 merge-master). Every failure below has an owner. Only one shard is genuinely red; the rest are gated aggregators reflecting it.
The 4/6 shard uploaded no report artifacts (job died at the runner layer), and CIDB shows zero query-level perf regression rows on this head. This shard-level ERROR recurs across master and 10+ unrelated PRs in the last 14 days, so it is not caused by this PR's analyzer-pass diff. The new pass + 04545 test are unchanged by the merge; all other checks (Config Workflow, Finish Workflow, Style, all Builds, functional + integration) are green. Session id: cron:our-pr-ci-monitor:20260720-223000 |
Address @Manerone review on PR ClickHouse#110844: simplify the doc comments in RewriteArrayJoinCountPass.{h,cpp} (isPlainRowCount, unaligned-array-join, bare-count, single-expression), drop the FunctionToSubcolumnsPass block from the header, and trim the test comments. Convert the section-header comments in 04545_count_array_join_reads_sizes.sql into SELECT statements so they show up in the .reference file. Comment/test-cosmetic only, no logic change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| SELECT 'Optimization: the plan must read arr.size0 and no longer contain an ARRAY JOIN step.'; | ||
| SELECT count() > 0 FROM (EXPLAIN PLAN actions = 1 SELECT count() FROM t_count_aj ARRAY JOIN arr AS value) WHERE explain ILIKE '%arr.size0%'; | ||
| SELECT count() > 0 FROM (EXPLAIN PLAN actions = 1 SELECT count() FROM t_count_aj LEFT ARRAY JOIN arr) WHERE explain ILIKE '%arr.size0%'; | ||
| SELECT count() > 0 FROM (EXPLAIN PLAN actions = 1 SELECT count() FROM t_count_aj ARRAY JOIN narr) WHERE explain ILIKE '%narr.size0%'; |
There was a problem hiding this comment.
@groeneai, what about a few nested array joins such as SELECT count() FROM t ARRAY JOIN c0 ARRAY JOIN c1? What about INNER JOIN and GROUP BY in the same query?
There was a problem hiding this comment.
All three decline: the rewrite only fires for a bare single-count() projection over an ArrayJoinNode whose input is a table (RewriteArrayJoinCountPass.cpp guards).
- Chained
ARRAY JOIN c0 ARRAY JOIN c1: the outer ARRAY JOIN input is another ArrayJoinNode, not a table, so it declines and the cartesian count is unchanged. - A regular JOIN in the query: the join-tree root is a JoinNode, so it declines.
- GROUP BY:
hasGroupBy()is rejected up front (a per-group count is not a single row count).
Added coverage for all three in c425d41, each asserting the plan keeps the ARRAY JOIN and the count equals the optimize_functions_to_subcolumns=0 result.
(Note: comma ARRAY JOIN c0, c1 in a single clause does rewrite, but only because PruneArrayJoinColumnsPass already collapses the value-unused multi-column form to one surviving expression before this pass, so the result matches master.)
There was a problem hiding this comment.
@groeneai Does the case of ARRAY JOIN c0 ARRAY JOIN c1 have the same behavior as the one being fixed in the issue, where we can avoid the costly materialization and use the lengths instead?
There was a problem hiding this comment.
Good question. Today the pass declines the chained ARRAY JOIN c0 ARRAY JOIN c1 form: it only fires for a single ARRAY JOIN directly over the table, so nested ARRAY JOINs keep the master plan (arrays materialized) and count() is correct but not optimized. EXPLAIN QUERY TREE confirms the nested ARRAY_JOIN nodes stay and count() is not rewritten.
The count is computable from lengths for this shape too, so it can be extended. For the cartesian chained form the identity is a product of sizes, one factor per keyword (a LEFT keyword swaps its factor to greatest(size0, 1)), verified on the current build:
count() FROM t ARRAY JOIN c0 ARRAY JOIN c1==sum(c0.size0 * c1.size0)... LEFT ARRAY JOIN c0 ARRAY JOIN c1==sum(greatest(c0.size0, 1) * c1.size0)... LEFT ARRAY JOIN c0 LEFT ARRAY JOIN c1==sum(greatest(c0.size0, 1) * greatest(c1.size0, 1))
Walking a chain of ARRAY JOINs and emitting the product is more than the single-ARRAY-JOIN case #110812 asks for, so I scoped this PR to that and left chained as a safe decline. I am happy to add the chained case, either in this PR or as a follow-up. Which do you prefer?
There was a problem hiding this comment.
Leave this PR as it is, create a new PR with the solution for chained ARRAY JOINs
There was a problem hiding this comment.
Will do. I'll leave this PR as is and open a separate PR for chained ARRAY JOIN support, then link it here.
Cover the count()-over-ARRAY-JOIN join-tree shapes the rewrite does not handle: chained ARRAY JOIN, a query with a regular JOIN, and a query with GROUP BY. Each must keep the ARRAY JOIN and return the same count as with optimize_functions_to_subcolumns off. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — c425d41Every failure below has an owner: a fixing PR, or a full-effort fix task. None are caused by this PR (count() over ARRAY JOIN rewrite + tests).
Session id: cron:our-pr-ci-monitor:20260724-020000 |
|
Status on the chained ARRAY JOIN follow-up: the extension is implemented and validated, but the pass only exists on this PR's branch (not yet on master), so I am holding the separate PR until this one merges. Opening it now would either not compile against master or drag this PR's commits into the diff. Once this merges I will rebase the chained delta onto master and open the standalone PR here. What the change does: it generalizes |
CI finish ledger — cab8f0fEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI is fully finished on this commit with zero failing checks. Session id: cron:our-pr-ci-monitor:20260729-043000 |
…of subcolumn optimization The rewrite validated only the declared Array/Map type of the analyzed table, but that type is authoritative only for the site that performs the read. StorageDistributed returns false from supportsOptimizationToSubcolumns() precisely because it serializes the query to shards instead of reading columns locally, so a shard can hold a different type for the same column name. Dropping the ARRAY JOIN also drops its type validation. For a Distributed table declaring arr Array(UInt64) over a shard whose arr is String, count() over ARRAY JOIN returned a number instead of raising TYPE_MISMATCH as it does without the optimization. Declining there costs nothing measurable: such a storage never folds length() into the size0 subcolumn either, so the rewrite could not pay off, and the shard re-analyzes the untouched query and applies the rewrite locally where the declared type is the one actually read. Verified with a byte-cap probe that the local MergeTree path keeps reading only offsets.
… disagree with its declared type A Merge table declares its own column list and uses it verbatim when non-empty, so a child may hold a different type for the same column name. supportsOptimizationToSubcolumns() cannot see that: it is the AND over the children and a MergeTree child answers true whatever its column types are. The rewrite therefore validated a declared Array type that the read never used, and dropping the ARRAY JOIN also dropped the type check that would have caught the mismatch, so count() over a heterogeneous Merge returned the child's own interpretation of the column instead of the declared one. Check each matched child's declared type instead of the engine, so a Merge whose children all agree keeps reading only offsets. hasChildTable stops at the first match, so the predicate asks whether a child is not provably type-identical. hasChildTable inspects direct children only, so a nested Merge could hide a mismatched grandchild and the inner level re-plans a query the ARRAY JOIN has already been removed from. Decline there rather than descend: descending needs a visited set and re-entrancy reasoning, while declining is monotone and cannot be defeated by depth or a cycle. A Merge over a Merge therefore loses the optimization even when every leaf agrees. StorageAlias and StorageTableProxy forward both the capability predicate and the read, so the checks must see the storage that executes rather than the wrapper. Buffer, View and MaterializedView are left alone: they diverge on master already for a bare sum(length(arr)) with no ARRAY JOIN, which is a FunctionToSubcolumnsPass defect rather than this rewrite's.
…ializedView These three storages declare their own column list and satisfy supportsOptimizationToSubcolumns() by forwarding it to a destination table, target table or inner query, while none of them is a transparent wrapper the pass's resolution loop unwraps. The read therefore executes against a schema the analysis never saw, and since dropping the ARRAY JOIN also drops the type check that would have caught the mismatch, the rewrite produced a silently wrong count on Buffer (0 instead of 3 on a destination declaring arr String) and a failed query on View (Code 47) and on MaterializedView (Code 10). Decline at both admission points through one shared predicate: the resolved top-level storage, and the per-child check of a Merge, where such a child whose declared type happens to match was previously admitted and let the Merge path inherit the identical exposure. The predicate uses typeid_cast on the exact type rather than isView(), which MaterializedView also answers true to and StorageProxy forwards, so the declined set cannot widen unpredictably. A Merge whose children all declare the analyzed type still reads only offsets, so the decline costs the optimization on schema-inconsistent shapes only. Also in this commit: - The per-child metadata read now fails closed on a child the current user may not SELECT. That traversal is unfiltered while execution reads only accessible children, so an inaccessible child's type would otherwise steer the plan. - The analysis-time versus execution-time Merge child race is documented beside the check. StorageMerge::canMoveConditionsToPrewhere accepts the same race in-tree, but its consequence is a failed query whereas ours is a wrong count, because a child lacking the subcolumn gets a substituted default. - The downstream fold skips index columns and returns early under FINAL, so on those shapes the ARRAY JOIN is removed while the whole column is still read. The count stays correct. Three shapes are pinned by tests so relaxing either exclusion flips exactly those rows. - The wrapper hop limit is a named constant instead of a repeated literal. The unfilled ISSUE_URL_PLACEHOLDER token is removed: the sentence that carried it described these storages as uncovered, and they are now declined. Co-Authored-By: Claude Fable 5 <[email protected]>
… declares another type
The wrapper hop loop unwraps every `StorageProxy`, but a wrapper is only transparent if its
declared columns are the ones the read executes against. `StorageTableFunctionProxy` deliberately
breaks that: it exposes cached columns and appends a converting step AFTER reading a differently
structured nested storage, and `ITableFunction::needStructureConversion` defaults to true so this
is the normal case rather than an exotic one. Resolving through it therefore handed the pass a
declared `Array(UInt64)` while the read executed against a `String`, and dropping the ARRAY JOIN
turned a working count into `NO_SUCH_COLUMN_IN_TABLE` for `arr.size0`:
CREATE TABLE tf (`arr` Array(UInt64)) AS values('arr String', '[1,2,3]');
SELECT count() FROM tf ARRAY JOIN arr; -- was Code: 16, now 3
Comparing the resolved storage's own declared type against the analyzed one closes this
structurally, so any future converting wrapper is covered without naming a type. It also settles
the `StorageAlias` arm of the same concern: `StorageAlias::tryGetTargetTable` resolves by name with
no lock and `StorageAlias::read` resolves again at execution, so the storage validated here is
provably the executed one only while its declared type still matches. A `typeid_cast` remedy was
rejected: `add_conversion` is private with no accessor, and `Analyzer/` includes
`Storages/StorageTableFunction.h` nowhere today.
The check sits after the existing `readsAgainstAnotherSchema` decline and before the `Merge`
branch, and does not replace the per-child loop: a `Merge` declares its own column list, so it
passes this check while a child can still disagree.
Also names `StorageWindowView` as a third `isView` carrier the capability check already declines.
…the optimization Two test changes. Adds a `t_caj_tfp_*` group for the converting table-function proxy. Both arms of its equality row are scalar subqueries on purpose: written as `count() = (SELECT ...) FROM ... ARRAY JOIN` the outer projection is `equals`, not `count`, so the pass declines that shape outright and the row would be green whether or not the rewrite fired. Measured on the pre-fix binary, the four mismatched rows each throw `Code: 16` and the whole group is what deleting the new type check reddens; the matching `t_caj_tfp_ok` row asserts only the answer, and `t_caj_alias_good` still optimizes, so the check is not a blanket wrapper decline. Corrects the `Distributed` comment. It claimed the shard re-analyzes the untouched query and rewrites it there. That is false: `InterpreterSelectQueryAnalyzer` routes a `SECONDARY_QUERY` to `QueryTreePassManager::runOnlyResolve`, which is `run(query_tree_node, 4)`, and this pass is registered sixth, so a shard never runs it. The row underneath queried the shard table directly, i.e. an ordinary local read that is green either way, so the comment now says plainly that it pins the local path and that a distributed query reads the whole array. Declining at the initiator remains correct, because the initiator's declared type is not the shard's.
…omments Three test and comment concerns from review. No pass logic changes: the whole RewriteArrayJoinCountPass.cpp diff here is comment-only. The narr, lcarr and m rows were written as `count() = (SELECT ...) FROM ... ARRAY JOIN`, whose outer projection is equals() rather than count(), so this pass declines the query outright and the row was green whether or not the rewrite fired. Those three types had no live value assertion anywhere else, only plan rows asserting the optimization fires. Rewritten into the scalar/scalar shape already used for the table-function-proxy group, so both arms keep a plain count() projection and the optimized arm is the query under test. Verified live by rebuilding the pass to emit empty() instead of length(): all three rows flip from 1 to 0 while the size0 plan rows stay green. Nothing in the repository observed the bytes-not-read claim that the Performance Improvement category makes: tests/performance/array_join.xml is untouched and none of its queries is eligible for this rewrite, since they all reference the joined value or read from numbers(). Added a max_bytes_to_read pass/fail pair over a dedicated fixture, in the form already in-tree at 01455_shard_leaf_max_rows_bytes_to_read. Measured 160000 read_bytes optimized against 8160000 unoptimized, so the budget has a 6x margin on one side and 8x on the other; the separation is identical for Compact and Wide parts and across index_granularity 128, 1024 and 8192, so no setting is pinned on those rows. Each arm is deterministic over 20 runs. Suppressing the rewrite makes the first row raise TOO_MANY_BYTES too, which is what makes it an oracle rather than a restatement of the control. The expected error is logged at Error level, which the test runner treats as a failure, so it is bracketed by send_logs_level as this file already does for its expected Buffer warning. Nine comment blocks ran over three lines. Trimmed by moving the rationale to the PR description and keeping the invariant at the call site: that the Merge child set is revalidated at execution with no shared snapshot, and that a missing subcolumn there is silently defaulted rather than failing the query; and that a hopped wrapper is transparent only if its declared columns are the ones the read executes against.
The Distributed row in 04545 attributed the initiator's decline to the declared-type comparison. That comparison would pass on this fixture, since both tables declare arr Array(UInt64); the decline happens earlier, at the capability check, because StorageDistributed opts out of supportsOptimizationToSubcolumns unconditionally. Attribute it there instead. In the pass, "the ARRAY JOIN still goes" reads either as "is removed" or as "goes on", i.e. the opposite meaning. Say "removed". Comments only: the edited translation unit recompiles to an identical binary. Co-Authored-By: Claude Fable 5 <[email protected]>
The comment above the resolved-declared-type check documented that a StorageAlias resolves its target by name without a lock and resolves again in read(), so the storage validated during analysis is provably the executed one only while its declared type still matches. That clause was the recorded disclosure for the Alias arm of the analysis-vs-execution race, and a later comment trim removed it, leaving only the generic transparency sentence. Restore it in three lines, in the same shape as the Merge NOTE below: name the race, point at the accepted in-tree precedent, and state that the consequence here is a wrong count rather than a failed query. Comment-only, no behaviour change.
Internal second-model reviewBefore pushing this update I ran an independent review pass over the diff with a second ❌ Blockers (all fixed in this branch)
|
| finding | verdict | resolution |
|---|---|---|
Three type-wrapper rows (Array(Nullable(String)), Array(LowCardinality(String)), Map) were written in a spelling that projects equals rather than count, which this pass declines outright, so they were green whether or not the rewrite fired. |
AGREE | Rewritten to the scalar/scalar form. Rebuilding the pass to emit empty instead of length now flips all three from 1 to 0 while the size0 plan rows stay green, so each row witnesses a wrong value on the fired path. |
The Performance Improvement contract had no in-tree oracle: tests/performance/array_join.xml contains no query eligible for this rewrite. |
AGREE | Added a max_bytes_to_read budget row, measured at 160000 read bytes optimized against 8160000 unoptimized. Deterministic over 20 runs per arm, identical for Compact and Wide parts and across index_granularity 128 / 1024 / 8192; suppressing the rewrite makes the passing arm raise TOO_MANY_BYTES too. |
A comment claimed the initiator declines a Distributed query because its declared type is not the shard's. That guard cannot fire there: the fixture is type-matched, and StorageDistributed::supportsOptimizationToSubcolumns returns false unconditionally 42 lines earlier. |
AGREE | Comment rewritten to attribute the decline to the capability check. The PR body's matching parenthetical was corrected in the same pass. |
A StorageAlias resolves its target by name with no lock and re-resolves in read, which ignores the snapshot it is handed, so the storage validated during analysis is not pinned to the one that executes. |
AGREE on the disclosure, DISAGREE on the remedy | The remedies asked for were to carry a validated snapshot or lock into execution, or to decline for top-level Alias sources. I refute a necessary step of that: this race is not this PR's to close. Trunk's own FunctionToSubcolumnsPass gates on the same predicate and does not unwrap StorageAlias (nothing in src/Analyzer, src/Planner or src/Processors does), and StorageAlias forwards both the predicate and the snapshot on master, so master already folds length(arr) into arr.size0 through an alias under the identical window. The mechanism requested does not exist in ClickHouse and is a known unbuilt storage-layer item, TODO: Store tables inside StorageSnapshot; StorageMerge::canMoveConditionsToPrewhere accepts the same analysis-versus-execution race in-tree. A blanket Alias decline is disproved by the tests that exist to prove wrapper resolution did not become one. What I did agree to is that the disclosure had regressed out of the code during a comment trim, so it is restored beside the check: it names the missing lock, the re-resolution, the in-tree precedent, and that the consequence here is a wrong count rather than a failed query, mirroring the shape already accepted for the Merge arm. |
💡 Noted, not blocking
- The restored
Aliasnote says a swapped targetmiscounts, not fails. Strictly, the
miscount is the case where the new target declares a compatibleArray; aString
target instead fails at plan time. The note therefore states the worse of the two
outcomes, which is the conservative direction for a hazard disclosure. - A nested
Mergewhose every leaf matches the analyzed type also declines. That costs the
optimization and is deliberate: descending would need re-entrancy and cycle handling,
while declining is monotone. One test row pins that cost, so adding recursion later flips
exactly one row.
Method
Every guard was mutated individually with its expected failing set written down before the
arm ran, and each arm was re-served with an assertion that SELECT buildId() equals
readelf -n after a stale server was caught making one arm read the previous binary. All
119 pre-existing reference lines are byte-identical, verified with cmp and an empty
diff | grep '^<'. Regression sweep: 242 tests selected by feature, run serially, with
every failure re-run head to head against a master build containing no such pass at all,
0 regressions. 50 randomized runs of the regression test: 50 passed, 0 failed.
Session id: cron:clickhouse-review-slot-53:20260801-233300
Pre-PR validation gate
Regression sweep: 242 tests selected by feature ( |
Master renamed the pointer accessors that return the join tree and an ARRAY JOIN's table expression: getJoinTree and getTableExpression now return a const ITableExpressionNode reference, and the QueryTreeNodePtr forms are getJoinTreeNode and getTableExpressionNode. The pass still used the pre-rename spellings, so it stopped compiling once master was merged in (four errors: two pointer-vs-reference dereferences, one .get() on a reference, and one assignment through a const reference). Switch all four sites to the Node accessors, which is what the sibling passes use (CrossToInnerJoinPass, CountDistinctPass, UniqToCountPass). The rewrite semantics are unchanged: the assignment that drops the ARRAY JOIN goes through the mutable getJoinTreeNode overload. Co-Authored-By: Claude Fable 5 <[email protected]>
|
The Master renamed the pointer-shaped join-tree accessors: Verified both directions locally against merged master: restoring the old spellings reproduces |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 117/129 (90.70%) · Uncovered code |
CI finish ledger — 3636ad3Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI is fully finished on this commit with zero failing checks: 174 check-runs, 0 incomplete, Session id: cron:our-pr-ci-monitor:20260802-063000 |
…12-count-array-join-size0
Both comments asserted a wrong-result behaviour that does not occur, and both were motivation rather than a local invariant. The first claimed a swapped Alias target "miscounts, not fails". The second claimed a Merge child lacking the subcolumn "is silently defaulted", stated as a live property of the shipped code while the guard directly below declines exactly that case. The ARRAY JOIN type check the notes compare against is raised in QueryAnalyzer.cpp (the analyzer), not at execution, and QueryAnalysisPass runs before this pass in QueryTreePassManager. So the unrewritten query resolves the column type in the same phase this pass does, and the rewrite cannot remove an execution-time check that never existed. Measured on this branch, per query so one error does not mask the rest: Alias target swapped by three concurrent RENAME loops, 250 attempts: with the optimization enabled 120 correct / 130 errors (113 of them TYPE_MISMATCH), disabled 100 correct / 150 errors. Zero miscounts in either arm, and the error mix is the same with the optimization off, so the window is a pre-existing DDL race. Merge child set churned by concurrent CREATE + INSERT + DROP of a mistyped child, 250 attempts, with the child holding '[1,2]' as String so it casts cleanly and a default-filled subcolumn would be numerically visible rather than hidden behind an error: enabled 156/27/13/4 over the values 900000/902000/904000/906000, disabled 160/19/17/4 over the same set. No value appears with the optimization enabled that does not appear with it disabled. With the mistyped child present at analysis the guard declines and both settings return the correct 902000, while the rewritten shape issued directly returns 900000. Reading arr.size0 off a String-typed column raises UNKNOWN_IDENTIFIER directly and through an Alias, so the subcolumn does not silently default there either.
|
The That shard died before praktika uploaded anything, so the check was red with no artifacts and no query rows to act on. The runner root disk filled to 100%, after which a 0-byte Job-level deaths of this shape on |
CI finish ledger - 3a77c83Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
158 success, 15 skipped, 2 failures out of 175 check-runs. Session id: cron:our-pr-ci-monitor:20260803-200000 |
|
I opened #113231, which makes a That does not mean the |
@Manerone asked for the removal of the sentence explaining why the storage check uses an exact typeid_cast rather than isView. Sweeping the whole diff for the same class of comment found six more blocks stating why a choice was made, or citing another file's internals, rather than the local invariant. Removed, and the surviving blocks reworded to state only what a reader needs at that spot: - readsAgainstAnotherSchema: dropped the typeid_cast-versus-isView rationale. - The pre-check paragraph and the three-storage decline no longer restate that the rewrite removes the ARRAY JOIN type check, which is what the pass body already shows and what the header block already explains. - The Merge block no longer names supportsOptimizationToSubcolumns's internal AND-over-children implementation, and the child predicate no longer narrates which storages are declined for which reason; the code lists them. - The access-check note keeps the invariant and drops the aside about column-level grants. - The FunctionToSubcolumnsPass note keeps what the following code does and drops the restatement of an earlier step. Comments only. Added comment lines in src go from 61 to 56 against 201 added code lines, and no added block exceeds three lines except the file-level header, which follows the convention of the neighbouring pass headers. Verified: build ID moved to 1ccf3e2ed935322b72b6e1be703507abe3f49932, and 04545_count_array_join_reads_sizes reproduces its reference byte for byte (127 of 127 lines) on a server confirmed to be running that binary.
CI finish ledger - 9478ee7Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
None of this is PR-caused. This diff reads Session id: cron:our-pr-ci-monitor:20260804-160000 Corrected 2026-08-06: the heading of this comment previously carried Two owner columns are refreshed to the fixing PRs that have since merged: #111997 for the two |
Closes: #110812
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
count()overARRAY JOIN arr, when the array's element value is not used anywhere else in the query, no longer reads the wholearrcolumn: it is rewritten to sum the array lengths, which reads only the lightweightarr.size0subcolumn whenarris not part of an index and the query is notFINAL. Controlled byoptimize_functions_to_subcolumns.Description
SELECT count() FROM t ARRAY JOIN arrproduces one row per array element, so the count depends only on the array lengths, not the values. The result was correct, but the wholearrcolumn was read just to multiply rows.A new analyzer pass
RewriteArrayJoinCountPassrewrites such acount()intosum(length(arr))(LEFT:sum(greatest(length(arr), 1))) and drops theARRAY JOIN;FunctionToSubcolumnsPassthen foldslength(arr)intoarr.size0, so only offsets are read. It fires only for a lonecount()projection with no other clause, over one physicalArray/Mapcolumn.Eligibility is decided from the analyzed declared column type, which is authoritative only where the read executes. So the rewrite declines wherever the executed schema may differ:
falsetosupportsOptimizationToSubcolumns. This coversDistributed, whose shard runs only the resolve-only passes and does not recover the optimization either.Buffer,ViewandMaterializedView, which satisfy that predicate by forwarding it to a destination, inner query or target free to declare another type.Mergewhose matched children do not all declare the analyzed type: the predicate is the AND over children and aMergeTreechild satisfies it whatever its types. A nestedMergeand an inaccessible child decline.Aliasand lazily-loaded tables forward both the predicate and the read, so they are resolved to the executing storage. A decline costs the optimization, never the answer.Measured decline table (destination/inner/target declares
arr String, wrapper declaresarr Array(UInt64); correct answer 3)Bufferover a mismatched destinationARRAY JOINkeptViewover aStringcolumnCode: 47Unknown expression identifier 'arr.size0'ARRAY JOINkeptMATERIALIZED VIEW TOa mismatched targetCode: 10Column 'arr.size0' not foundARRAY JOINkeptValidated by a stateless test asserting, per shape, the count and that the
ARRAY JOINsurvives when the rewrite declines, plus amax_bytes_to_readbudget the optimized query fits and the unoptimized one does not (160 kB against 8.16 MB read); by mutating each guard and confirming exactly the predicted rows redden; and by 50 randomized runs plus a serial A/B over 242 tests, no regression.