Skip to content

Read arr.size0 for count() over ARRAY JOIN - #110844

Closed
groeneai wants to merge 24 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-110812-count-array-join-size0
Closed

groeneai wants to merge 24 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-110812-count-array-join-size0

Conversation

@groeneai

@groeneai groeneai commented Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #110812

Changelog category (leave one):

  • Performance Improvement

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

count() over ARRAY JOIN arr, when the array's element value is not used anywhere else in the query, no longer reads the whole arr column: it is rewritten to sum the array lengths, which reads only the lightweight arr.size0 subcolumn when arr is not part of an index and the query is not FINAL. Controlled by optimize_functions_to_subcolumns.

Description

SELECT count() FROM t ARRAY JOIN arr produces one row per array element, so the count depends only on the array lengths, not the values. The result was correct, but the whole arr column was read just to multiply rows.

A new analyzer pass RewriteArrayJoinCountPass rewrites such a count() into sum(length(arr)) (LEFT: sum(greatest(length(arr), 1))) and drops the ARRAY JOIN; FunctionToSubcolumnsPass then folds length(arr) into arr.size0, so only offsets are read. It fires only for a lone count() projection with no other clause, over one physical Array/Map column.

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:

  • a storage answering false to supportsOptimizationToSubcolumns. This covers Distributed, whose shard runs only the resolve-only passes and does not recover the optimization either.
  • Buffer, View and MaterializedView, which satisfy that predicate by forwarding it to a destination, inner query or target free to declare another type.
  • a Merge whose matched children do not all declare the analyzed type: the predicate is the AND over children and a MergeTree child satisfies it whatever its types. A nested Merge and an inaccessible child decline.

Alias and 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 declares arr Array(UInt64); correct answer 3)
shape before the decline with the decline
Buffer over a mismatched destination count = 0 (silently wrong) count = 3, ARRAY JOIN kept
View over a String column Code: 47 Unknown expression identifier 'arr.size0' count = 3, ARRAY JOIN kept
MATERIALIZED VIEW TO a mismatched target Code: 10 Column 'arr.size0' not found count = 3, ARRAY JOIN kept
the same three with matching types count 3, optimized count 3, optimization given up

Validated by a stateless test asserting, per shape, the count and that the ARRAY JOIN survives when the rewrite declines, plus a max_bytes_to_read budget 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.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's exact query SELECT count() FROM t ARRAY JOIN values reads the full values column on master; EXPLAIN PLAN actions=1 deterministically shows Output: values (not values.size0).
b Root cause explained? ARRAY JOIN emits one row per array element regardless of the element values, so count() (and any query not referencing the element value) needs only each array's length. The planner still read the whole arr column to multiply rows; the read was never narrowed to the .size0 subcolumn even though the value is unused.
c Fix matches root cause? Yes. In PruneArrayJoinColumnsPass (which already tracks whether each join expression's value is used), an unused physical Array/Map join column is rewritten to arrayWithConstant(length(arr), 0); FunctionToSubcolumnsPass then rewrites length(arr) to arr.size0, so storage reads only the offsets. Directly targets the "value unused → read only size" mechanism.
d Test intent preserved / new tests added? New test 04545_count_array_join_reads_sizes asserts (via SELECT ... FROM (EXPLAIN PLAN actions=1 ...) WHERE explain ILIKE '%arr.size0%') that the optimized read fires, that counts are unchanged, and that it does NOT fire when the value is used or the setting is off. No existing test weakened.
e Both directions demonstrated? Yes. On pristine master the 5 optimization assertions return 0 (full array read) → test FAILS; with the fix all return 1 → test PASSES. Correctness lines return 1 in both (result was always correct — a missed optimization, not a bug). 20/20 passes with randomization.
f Fix is general across code paths? Applies to every ARRAY JOIN whose element value is unreferenced (count, or SELECT of non-element columns), for Array and Map (nested-Array) columns. Not a single-call-site patch; it hooks the existing usage-analysis in the one pass that owns ARRAY JOIN column pruning.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified count == sum(length(arr)) for Array(UInt64), Array(Nullable(String)), Array(LowCardinality(String)), and Map, and == sum(greatest(length,1)) for LEFT ARRAY JOIN (incl. empty arrays). Guards require the .size0 subcolumn to exist in storage and skip when a real column shadows the subcolumn name.
h Backward compatible? Yes. Gated on optimize_functions_to_subcolumns (default on); with it off, behavior is unchanged (verified). arrayWithConstant deliberately chosen over range() because range() enforces function_range_max_elements_in_block and would turn a previously working query into ARGUMENT_OUT_OF_BOUND. No format/setting-default change.
i Invariants and contracts preserved? The rewritten expression is a valid ARRAY JOIN expression producing arrays of identical per-row length, so row multiplication and block structure are preserved. Only fires for !enable_unaligned_array_join (existing pass guard) and plain physical Array/Map columns with a real table source; computed expressions, non-table sources, and array literals are left untouched (verified no crash / correct results).

Session id: cron:clickhouse-worker-slot-4:20260717-100900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd — could you review this? It extends PruneArrayJoinColumnsPass: when an ARRAY JOIN column's element value is unused (e.g. count() FROM t ARRAY JOIN arr), the join expression is rewritten to arrayWithConstant(length(arr), 0) so FunctionToSubcolumnsPass reads only arr.size0 instead of the full array. Gated on optimize_functions_to_subcolumns; arrayWithConstant avoids range()'s element-count limit. Fixes #110812.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9478ee7]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
Test script failed FAIL cidb
Stress test (arm_debug) FAIL
Logical error: ColumnBLOB should be converted to a regular column before usage (STID: 3059-3663) FAIL cidb, issue
Stress test (arm_asan_ubsan) FAIL
Logical error: ColumnBLOB should be converted to a regular column before usage (STID: 3059-3284) FAIL cidb
Stress test (arm_tsan) FAIL
Test script failed FAIL cidb

AI Review

Summary

This PR introduces RewriteArrayJoinCountPass, rewriting a bare count() over a single eligible ARRAY JOIN into an aggregate over array lengths so FunctionToSubcolumnsPass can read *.size0 instead of the full array payload. I reviewed the current diff together with the full thread history and the latest code state, including the wrapper-storage decline logic, empty_result_for_aggregation_by_empty_set, and the regression coverage in 04545_count_array_join_reads_sizes; I did not find a remaining correctness or evidence gap that warrants a new review comment.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 117/129 (90.70%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 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: 93c1b4b9-ffee-4976-876a-1e04112ec651
  • MIRAI run: 6851c461-8fc1-4a02-8855-a7c49f486a76
  • PR check IDs:
    • clickbench_1643060_1785851138
    • clickbench_1643073_1785851138
    • clickbench_1643080_1785851138
    • tpch_adapted_1_official_1643088_1785851138
    • tpch_adapted_1_official_1643114_1785851139
    • tpch_adapted_1_official_1643128_1785851138

…-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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 70000 x 20000-elem Array(UInt8), SELECT count() ... ARRAY JOIN arr SETTINGS optimize_functions_to_subcolumns=1, max_block_size=1000000, max_threads=1. On the prior arrayWithConstant build it throws TOO_LARGE_ARRAY_SIZE every run.
b Root cause explained? Yes. count() over ARRAY JOIN = number of exploded elements = sum of array lengths. The previous mechanism synthesized a placeholder arrayWithConstant(length(arr),0) to reach the length->size0 fold; that array is materialized at runtime and enforces a per-block 1e9-element cap plain ARRAY JOIN never had (regression), and it fires even when arr is read elsewhere (so the fold does not apply and a synthetic array is added on top of the full read). The count depends only on lengths, so no array should be built.
c Fix matches root cause? Yes. New RewriteArrayJoinCountPass rewrites the aggregate count() -> sum(length(e)) (LEFT: sum(greatest(length(e),1))) and drops the ARRAY JOIN. No array is materialized. The arrayWithConstant addition to PruneArrayJoinColumnsPass (source of both regressions) is fully reverted to master.
d Test intent preserved / new tests added? Yes. 04545 keeps INNER/LEFT/Array/Map/Nullable/LowCardinality correctness (count()==sum(length)); adds count(*)/count(1), count(NULL) semantics, output-name preservation, Finding-2 no-regression cases (array read elsewhere -> rewrite declines, no arrayWithConstant), plan-shape guard (sum( present, arrayWithConstant absent), backward-compat off. 03355/03356 reverted to master.
e Both directions demonstrated? Yes. Before (arrayWithConstant, Build ID 0446a06...) throws TOO_LARGE_ARRAY_SIZE; after (Build ID 80304f6...) returns 1400000000 == sum(length). 50/50 correctness stability run passed.
f Fix is general across code paths? Yes for the reported class (count() over ARRAY JOIN): INNER + LEFT, Array + Map, Nullable/LowCardinality, count()/count(*)/count(1), nested subqueries. The only mechanism that synthesized an array was the reverted arrayWithConstant addition; no sibling path does this. The projection-generalization (element unused in a non-count projection) is deliberately out of scope.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified across Array(UInt64), Array(Nullable(String)), Array(LowCardinality(String)), Map; empty arrays (LEFT greatest path); large arrays (cap); count(NULL)/count(NULL::Nullable(UInt64))/count(CAST(NULL AS Nullable(String))) (rewrite declines, returns 0 as baseline); computed ARRAY JOIN expr and JOIN+ARRAY JOIN (both decline). The test asserts the optimization FIRES (EXPLAIN size0) AND does NOT fire where it must not.
h Backward compatible? Yes. Gated behind the existing optimize_functions_to_subcolumns (default on); off -> no rewrite. No setting-default / on-disk / wire / protocol / metadata change. count() results identical in every case.
i Invariants and contracts preserved? Yes. Fires only for a single bare count() projection over a single ARRAY JOIN directly over a table with exactly one surviving plain-physical-column join expression and no other clause. projection_columns untouched, so output name+type are preserved (verified via DESCRIBE: count()/UInt64, alias preserved). New nodes are fully resolved (debug ValidationChecker passed). LEFT semantics (empty array -> 1 row) preserved via greatest(length,1); WHERE on base columns preserved.

Session id: cron:clickhouse-author-slot-1:20260718-024748

@groeneai

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ❌ count(NULL) / typed nullable-NULL constant treated as a plain row count, changing the result from 0 to the element count AGREE — fixed @ 58c61b2 Confirmed count(NULL::Nullable(UInt64))/count(CAST(NULL AS Nullable(String))) returned 200 with the rewrite vs 0 baseline. isPlainRowCount now rejects any constant arg whose value isNull() (mirrors NormalizeCountVariantsPass); added regression cases.
2 ⚠️ Test does not pin enable_unaligned_array_join, but the pass declines under it, so EXPLAIN assertions are randomization-dependent AGREE — fixed @ 58c61b2 Added SET enable_unaligned_array_join = 0 to the test setup.
3 ⚠️ Large-array INSERT could hit the 1e9 cap during INSERT before the tested SELECT AGREE — superseded Verified the INSERT does not hit it (arrayWithConstant with a constant length arg takes a cap-free fast path). Superseded by finding 4 (whole heavy fixture removed).
4 ⚠️ The 1e9-element regression fixture is unreasonably resource-intensive for a routine stateless test AGREE — fixed @ 58c61b2 The cap-trip inherently needs ~1e9 elements in one read block (~1.3 GB transient). Removed the heavy fixture; replaced with lightweight plan-shape assertions (plan must aggregate with sum( and must NOT contain arrayWithConstant), which structurally guarantees no placeholder array is materialized. Test now 0.53s / 465 MB peak (was 2.5 GB). The large before/after reproduction is retained as external evidence.

Severity: ❌ blocker / ⚠️ major / 💡 nit. All findings AGREEd and fixed; the bounded delta recheck returned 0 findings.

Session id: cron:clickhouse-author-slot-1:20260718-024748

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd — the approach changed based on the review: instead of rewriting the ARRAY JOIN input to arrayWithConstant(length(arr), 0), a new analyzer pass RewriteArrayJoinCountPass now rewrites the count() aggregate to sum(length(arr)) and drops the ARRAY JOIN. This removes the TOO_LARGE_ARRAY_SIZE regression (no array is materialized) and cannot fire when the array is read elsewhere. The arrayWithConstant change to PruneArrayJoinColumnsPass is reverted. Ready for another look.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 53cee8d

CI 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 count() over ARRAY JOIN, plus its regression test; it touches no stress/quota/replicated-DB code.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Received signal 8 (STID 4141-5867) crash (quota zero-length-interval SIGFPE, duration.h division-by-zero) #110846 (external, open)
Stress test (amd_asan_ubsan) / UndefinedBehaviorSanitizer division by zero (STID 4141-5b13) UB (same quota zero-length-interval family, duration.h:460 division-by-zero) #110846 (external, open)
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (Replicated-DB DDL-recovery race, 91 master hits/30d) #110030 (ours, open)
Sync - CH Inc sync (private, not actionable)

Every line owned; none PR-caused.

Session id: cron:our-pr-ci-monitor:20260718-093000

@Manerone

Copy link
Copy Markdown
Contributor

@groeneai merge the latest master in this PR

@groeneai

Copy link
Copy Markdown
Collaborator Author

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5103f6e

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

Check / test Reason Owner / fixing PR
Performance Comparison (amd_release, master_head, 4/6) infra (shard job-level ERROR — no artifacts uploaded; not a query regression) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Mergeable Check gated aggregator (reflects the perf shard) clears when the perf shard is green
PR gated aggregator (reflects the perf shard) clears when the perf shard is green

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

Manerone
Manerone previously approved these changes Jul 21, 2026
@Manerone
Manerone dismissed their stale review July 23, 2026 11:06

Reviewing it again

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%';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Leave this PR as it is, create a new PR with the solution for chained ARRAY JOINs

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c425d41

Every 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).

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (139 master, 665 unrelated PRs, 14d) #111029 (external, open)
Upgrade check (amd_release) / New settings are not reflected in settings changes history trunk regression (join_runtime_filter_min_probe_rows in 26.7 section, not 26.8) #111671 (ours, open)
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history trunk regression (same as above) #111671 (ours, open)

Session id: cron:our-pr-ci-monitor:20260724-020000

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 RewriteArrayJoinCountPass to a run of ARRAY JOIN keywords. A chain is a cartesian product, so count() becomes sum() over the product of the per-keyword size0 lengths, with each LEFT keyword's factor wrapped in greatest(size0, 1). It also declines when empty_result_for_aggregation_by_empty_set is set (an all-empty ARRAY JOIN yields an empty result, which the rewrite must preserve). Single ARRAY JOIN stays on the same code path unchanged. Tests cover INNER/LEFT combinations, three keywords, Nullable/LowCardinality/Map elements, and the decline cases.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — cab8f0f

Every failure below has an owner: a fixing PR (ours 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
— no failed checks on this commit —

CI is fully finished on this commit with zero failing checks.

Session id: cron:our-pr-ci-monitor:20260729-043000

groeneai and others added 8 commits August 1, 2026 08:50
…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.
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Before pushing this update I ran an independent review pass over the diff with a second
model, then adjudicated each finding against the code. Six rounds of findings were raised
across the branch; this comment records the ones that changed the code and the ones I
declined, with the evidence for each.

❌ Blockers (all fixed in this branch)

finding verdict what changed
Eligibility was decided from the analyzed declared column type, but a Buffer, View or MATERIALIZED VIEW ... TO satisfies supportsOptimizationToSubcolumns by forwarding it to a destination, inner query or target free to declare another type. Dropping the ARRAY JOIN also drops the type check that caught the mismatch, so count() returned 0 on a mismatched Buffer and failed with Code: 47 / Code: 10 on the view shapes. AGREE The rewrite declines on those three by exact typeid_cast, deliberately not isView (which MaterializedView and WindowView also answer true to and StorageProxy forwards, so the declined set cannot widen unpredictably).
StorageMerge::supportsOptimizationToSubcolumns is the AND over children and a MergeTree child answers true whatever its column types are, so the predicate is blind to per-child type heterogeneity while a Merge uses its own declared column list verbatim. A Merge declaring arr Array(UInt64) over children Array(UInt64) and String returned 3 instead of 6. AGREE Per-child sweep comparing each matched child's declared type against the analyzed one, keyed on the actual types rather than on the engine, so a Merge whose children all agree keeps reading only offsets. A blanket engine decline was measured to destroy that payoff and rejected.
A wrapper the resolution loop unwraps is transparent only if its declared columns are the ones the read executes against, and StorageTableFunctionProxy deliberately breaks that: it exposes cached columns and appends a conversion after reading a differently structured nested storage. CREATE TABLE tf (arr Array(UInt64)) AS values('arr String', '[1,2,3]') turned a correct answer into Code: 16 for arr.size0. AGREE Closed structurally, by comparing the resolved storage's own declared type against the analyzed one, so a future converting wrapper is covered without naming a type. Naming it was rejected: add_conversion is private with no accessor and Analyzer/ includes StorageTableFunction.h nowhere.
The per-child traversal is unfiltered, while execution reads only children the querying user may SELECT, so a type the reader cannot see could steer the plan. AGREE The sweep fails closed on a child the user may not SELECT, and on null metadata, an unresolvable wrapper, or an exhausted hop bound.
A non-LEFT ARRAY JOIN over only-empty arrays leaves the aggregation with no input, which empty_result_for_aggregation_by_empty_set must answer with an empty result rather than 0; sum over the base rows cannot reproduce that. AGREE Declines for the whole setting on the non-LEFT shape. Pinned by rows asserting an empty result and that the ARRAY JOIN survives, not merely that arr.size0 is absent.

⚠️ Majors

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 Alias note says a swapped target miscounts, not fails. Strictly, the
    miscount is the case where the new target declares a compatible Array; a String
    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 Merge whose 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

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# question answer
a Deterministic repro? Yes, four of them, none probabilistic. A Merge declaring arr Array(UInt64) over children arr Array(UInt64) and arr String holding '[4,5,6]': SELECT count() FROM mh ARRAY JOIN arr returned 3 instead of 6. A Buffer declaring arr Array(UInt64) over a destination declaring arr String: returned 0 instead of 3. The same shape as a View failed with Code: 47, and as a MATERIALIZED VIEW ... TO with Code: 10. And a converting table-function proxy, CREATE TABLE tf (arr Array(UInt64)) AS values('arr String', '[1,2,3]'), turned a correct answer into Code: 16 NO_SUCH_COLUMN_IN_TABLE for arr.size0.
b Root cause explained? Eligibility was decided from the analyzed table's declared column type, then the ARRAY JOIN was dropped, which also drops its type check. StorageMerge::supportsOptimizationToSubcolumns is the AND over children and a MergeTree child answers true whatever its types are, so it cannot see per-child heterogeneity, and a Merge uses its own declared column list verbatim. Buffer, View and MaterializedView reach the same guard from the other direction: they satisfy it by FORWARDING it to a destination, target table or inner query whose schema the analysis never saw. And a wrapper the resolution loop unwraps is only transparent if its declared columns are the ones the read executes against: StorageTableFunctionProxy deliberately breaks that, exposing cached columns and appending a converting step AFTER reading a differently structured nested storage, with ITableFunction::needStructureConversion defaulting to true.
c Fix matches root cause? Yes, and at the layer where the wrong decision is made rather than at the crash site. For Merge it reads each matched child's declared type rather than keying on the engine, so a Merge whose children all agree keeps reading only offsets; a blanket wrapper decline was measured to destroy that payoff and was rejected. The three self-declaring storages are declined by exact typeid_cast, deliberately not isView, which MaterializedView and WindowView also answer true to and StorageProxy forwards, so the declined set cannot widen unpredictably. The converting-wrapper hole is closed structurally, by comparing the resolved storage's own declared type against the analyzed one, so any future converting wrapper is covered without naming a type. Naming the type was rejected: add_conversion is private with no accessor, and Analyzer/ includes Storages/StorageTableFunction.h nowhere.
d Test intent preserved / new tests? All 119 pre-existing reference lines are byte-identical, verified with cmp and with an empty diff | grep '^<' rather than by eye, and no assertion was weakened; the file grew to 127 lines by additions-only hunks. The last two of those lines are a byte-budget oracle for the performance claim, since nothing in the repository previously observed it: tests/performance/array_join.xml is untouched and none of its queries is eligible for this rewrite, because they all reference the joined value or read from numbers. It runs the same query under one max_bytes_to_read budget with and without optimize_functions_to_subcolumns, measured at 160000 read bytes against 8160000, so the budget has a 6x margin on one side and 8x on the other; each arm is deterministic over 20 runs, the separation is identical for Compact and Wide parts and across index_granularity 128, 1024 and 8192, and suppressing the rewrite makes the passing arm raise TOO_MANY_BYTES too. The plan-shape rows are paired deliberately: asserting only that arr.size0 is absent is satisfiable by a pass that drops the ARRAY JOIN and lets the subcolumn pass decline, so every decline row also asserts the ARRAY JOIN survives. Each declined carrier additionally carries a must-not-regress row where the types MATCH, so a decline cannot silently become "always decline on this engine" without a row moving. The new group's equality rows use two scalar subqueries after measuring that the alternative spelling, count() = (SELECT ...) FROM ... ARRAY JOIN, projects equals rather than count and is therefore declined by this pass outright, which would make such a row green whether or not the rewrite fired. The same measurement was then applied to the three rows for Array(Nullable(String)), Array(LowCardinality(String)) and Map(String, UInt64), which had that vacuous spelling and no live value assertion elsewhere; they now use the scalar/scalar form, and rebuilding the pass to emit empty instead of length flips all three from 1 to 0 while the size0 plan rows stay green, so each row demonstrably witnesses a wrong value on the fired path.
e Both directions demonstrated? Yes. Every cell measured on the fixed build and on the pre-fix build rebuilt from the same tree, plus one mutation per shipped guard with its failing set predicted in writing before the arm ran. Deleting the three-type decline reproduces count() = 0 on Buffer and the Code: 47 and Code: 10 failures. Deleting only the per-child copy reddens exactly the two Merge-over-Buffer plan rows. Deleting only the access check reddens exactly the restricted-user plan rows. Deleting the resolved-type check reddens exactly the four mismatched proxy rows, by exception rather than by flipping to 0, which was the written prediction; because that exception truncates the run, the must-not-regress set was measured separately with a 38-cell probe suite, 38 of 38 cells joined and 0 moved. Each arm was re-served with an assertion that SELECT buildId() equals readelf -n, after a stale server was caught silently making one arm read the previous binary, and the restore arm reproduced the shipping Build ID exactly.
f General across code paths? All three StorageProxy subclasses were enumerated from the source and dispositioned individually: the converting one is now caught by declared-type comparison, the lazy table proxy forwards its metadata to the nested storage so declared equals executed, and the URL scheme dispatch forwards the capability bit to a backend returning false and so is declined earlier, verified live. Both admission points share one predicate rather than two copies that could drift: the resolved top-level storage, and the per-child check, where a Buffer or MaterializedView child whose declared type matches would otherwise let the Merge path inherit the identical exposure. The same edit also covers StorageAlias, which resolves its target by name without a lock and resolves again in read. Also closed: Distributed, a heterogeneous Merge, a nested Merge, and a Merge over a Distributed.
g General across inputs? A Map column and LEFT ARRAY JOIN both assert, since the guards sit above the left branch and above any type-specific handling. Nullable and LowCardinality element rows are covered. Every declined carrier has both a mismatched and a matching row, so the matrix is carrier by declared-type-agreement rather than one example per engine. Empty arrays, an entirely empty table, and count(*), count(1) and count(NULL) are pinned. An array column in a skip index, an array column in the primary key, and FINAL over ReplacingMergeTree are pinned too, because the downstream fold has its own exclusions there. The Nullable, LowCardinality and Map rows now assert the returned value and not only that the optimization fires, which is the half that was missing.
h Backward compatible? No setting, default, format or on-disk change, so no SettingsChangesHistory.cpp entry is due. Every check only ever declines and adds no rewrite path, so a previously correct query keeps its behaviour and a declined one returns to master's plan.
i Invariants and contracts preserved? The pass's stated invariant, that the analyzed declared type is the type the read executes against, is now enforced at every admission point instead of some of them. The new check is a read-only metadata comparison on the pointer the wrapper loop already materialized, so it takes no lock, mutates nothing, and adds no second materialization; on failure it returns before any tree edit, leaving the query tree exactly as found. All the checks run after every cheap structural check, so the metadata reads happen on a tiny fraction of queries. Null metadata, an unresolvable wrapper, and a child the current user may not SELECT all fail closed. The wrapper loop is bounded by a named constant, and exhausting the bound declines rather than falling through. The Merge child set is validated at analysis time while execution re-enumerates it, a race this PR does not close but does document in code beside the check, including that its consequence is a wrong count rather than a failed query.

Regression sweep: 242 tests selected by feature (ARRAY JOIN, optimize_functions_to_subcolumns, .size0), run serially on this branch and, for every failure, head to head against a master build that does not contain this pass at all. 0 regressions: 244 verdicts, 224 green, and all 20 failures fail identically on that pass-free control. Of those 20, 7 require the stateful dataset, 4 require a real multi-shard cluster, 1 requires an s3_cache storage policy, and 8 are pre-existing on master for unrelated reasons; the first 12 cannot pass on a single bare server on any binary, so for them the evidence is only that this branch and master behave alike. 50 randomized runs of the regression test: 50 passed, 0 failed.

groeneai and others added 2 commits August 2, 2026 01:38
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]>
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

The Fast test build break on 09c842c1 was base drift, now fixed in 3636ad3b.

Master renamed the pointer-shaped join-tree accessors: getJoinTree and getTableExpression now
return a const ITableExpressionNode &, and the QueryTreeNodePtr forms are getJoinTreeNode and
getTableExpressionNode. The pass predated that rename, so all four compile errors were the same
drift. I merged current master and switched the four sites to the Node accessors, matching the
sibling passes (CrossToInnerJoinPass, CountDistinctPass, UniqToCountPass). The rewrite
semantics are unchanged: the assignment that drops the ARRAY JOIN goes through the mutable
getJoinTreeNode overload rather than dropping the assignment.

Verified both directions locally against merged master: restoring the old spellings reproduces
exactly the four reported errors at :109, :119, :139 and :266, and the new form compiles
clean and 04545 matches its reference byte-for-byte.

@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 117/129 (90.70%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3636ad3

Every failure below has an owner: a fixing PR (ours 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
— no failed checks on this commit —

CI is fully finished on this commit with zero failing checks: 174 check-runs, 0 incomplete,
159 success and 15 skipped, Config Workflow and Finish Workflow both green. CIDB agrees,
with 0 FAIL/ERROR rows across 161 checks for this commit.

Session id: cron:our-pr-ci-monitor:20260802-063000

Manerone
Manerone previously approved these changes Aug 3, 2026
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.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

The Performance Comparison (amd_release, master_head, 4/6) row in my CI finish ledger above promised a fixing-PR link. Posting it: #112145, merged 2026-07-28.

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 ci-checks.tsv made performance_tests.py raise StopIteration out of main() ahead of the upload step. #112145 cuts the disk usage (it dumps only the system.trace_log columns the report reads and drops an unused intermediate file) and turns the truncated-file case into a reported warning instead of an uncaught exception, so a shard under disk pressure now uploads its logs and names the problem.

Job-level deaths of this shape on master_head shards went from a peak of 38 per week in mid-July to 0 in the current week (CIDB, 45 days). Part of that recovery predates the merge and is runner-side capacity, so I am not claiming this PR removed the disk pressure itself; it removes the silent-death masking.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3a77c83

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_debug) / Logical error: ColumnBLOB should be converted to a regular column before usage (STID 3059-3663) Trunk bug, not caused by this branch: a local-shard plan in a distributed query marshals its blocks, so a ColumnBLOB reaches a regular consumer. Breadth over 30 d: 68 rows / 44 PRs / 6 master rows #111997 (mine, open)
AST fuzzer (amd_debug, targeted) / Logical error: ColumnBLOB should be converted to a regular column before usage (STID 3059-3663) Same defect, same STID, second job #111997 (mine, open)
Build (arm_release) / Post Hooks CI harness: build_profile_hook.py telemetry upload fails in prepare-time-trace.sh (No connection). Job-level check_status = success (the hook carries allow_failure), so the build itself is green. Breadth over 7 d: 1712 rows / 368 PRs / 1193 master rows a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

158 success, 15 skipped, 2 failures out of 175 check-runs. Finish Workflow succeeded.

Session id: cron:our-pr-ci-monitor:20260803-200000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

I opened #113231, which makes a Buffer over a mismatched destination read a subcolumn from the converted parent instead of defaulting it, so the first row of the decline table above becomes correct at the source.

That does not mean the Buffer decline here can simply be dropped once it merges. Two carriers survive it: a Buffer whose destination is Distributed still has no post-read conversion point, so #113231 refuses there rather than fixing it, and View/MaterializedView are untouched (#112975 covers the Merge half). Relaxing the predicate would need a per-destination check, not a blanket re-enable.

@Manerone
Manerone dismissed their stale review August 4, 2026 09:14

Code is getting too specific

@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.
@groeneai

groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9478ee7

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
Stress test (arm_asan_ubsan) / ColumnBLOB should be converted to a regular column before usage (STID 3059-3284) trunk logical error, 171 rows / 105 unrelated PRs / 16 master in 14d #111997 (mine, merged 2026-08-04)
Stress test (arm_debug) / same signature (STID 3059-3663) same trunk family #111997 (mine, merged 2026-08-04)
Stress test (arm_release) / Test script failed (job exit 1, no crash signature) trunk harness failure, 58 rows / 56 unrelated PRs / 3 master in 14d #113248 (mine, open)
Stress test (arm_tsan) / Test script failed same harness family #113248 (mine, open)
Build (arm_release) / Post Hooks build-profile telemetry INSERT fails against the internal LogCluster endpoint; the check itself is success and non-gating #113409 (external, merged 2026-08-06)

None of this is PR-caused. This diff reads arr.size0 for count() over ARRAY JOIN; the
ColumnBLOB aborts are the trunk block-marshalling unwrap gap, and the two Test script failed
rows are the stress harness aborting its own fault-injection verification query.

Session id: cron:our-pr-ci-monitor:20260804-160000


Corrected 2026-08-06: the heading of this comment previously carried 9478ee7032539b2f0c0e0e4dd0f2eb0e60d9dc42, which is not a commit in this repository (gh api commits/<sha> returns 422). It matched only this head's first 12 characters, so it was a 12-character prefix with an invented tail rather than a real hash. The heading now carries the real head. That hash doubles as this ledger's idempotency key, so the wrong value made this head read as never ledgered.

Two owner columns are refreshed to the fixing PRs that have since merged: #111997 for the two ColumnBLOB rows, and #113409 for the build-profile telemetry row, which is the retry that actually landed for that failure. The two Test script failed rows still resolve to #113248, re-checked open today.

@Manerone Manerone closed this Aug 10, 2026
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 pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

count() (and other array-element-independent queries) over ARRAY JOIN reads the whole array instead of the size0 subcolumn

3 participants