Repository navigation
Do not use the trivial count optimization when the aggregate argument contains arrayJoin - #115227
Conversation
… contains arrayJoin applyTrivialCountIfPossible replaces the whole table read with the stored row counter. It validated that the aggregate is count by type and then never inspected count's argument. arrayJoin is row-multiplying and is evaluated above the source read, so the aggregate observes sum(length(arr)) rows rather than totalRows(), and replacing the read dropped the expansion. With the default optimize_trivial_count_query = 1, SELECT count(arrayJoin(arr)) returned the table row count. Refuse the optimization when the single aggregate's argument subtree contains arrayJoin, using the hasFunctionNode helper that six sibling optimizations already use for this property. unnest is an alias of arrayJoin and resolves to the canonical name in the query tree, so it is covered. The helper's visitor stops at nested QUERY/UNION nodes, so an arrayJoin confined to a subquery does not disable the optimization for the outer count. The guard precedes the select_query_info.optimize_trivial_count write. For file(), url() and object storage totalRows() is nullopt, so the function returns false and the plan is not rewritten, but those storages count inside read() and act on that flag, which made the same queries return 0. Guarding after the flag write fixes MergeTree only, and every MergeTree test still passes in that state. Measured on 3 rows holding 6 elements: count(arrayJoin(A)) 3 to 6, the unnest spelling, nesting inside a larger expression, chained arrayJoin, Map, Array(Tuple), Array(LowCardinality), a constant array literal, all-empty arrays, remote(), file() and url() all corrected. count(), count(*), count(1) and count(n) keep the optimization; the new test asserts count(n) specifically, because a guard broadened to reject any non-empty argument list leaves the zero-argument spellings unchanged and only moves that one. Closes: ClickHouse#115123
…carrier The four EXPLAIN assertions describe applyTrivialCountIfPossible, which only the new analyzer runs. On the old analyzer the count(n) arm evaluates to 0, because count(n) makes has_explicit_columns true in TreeRewriter so the branch that sets optimize_trivial_count for a bare count is skipped, and the partition branch then rejects n as a non-partition column. Both old-analyzer stateless job families run in PR CI, and they are llvm_coverage builds that force a flaky-labelled failure to OK, so the assertion was either red or silently whitewashed. Tag the test no-old-analyzer, as the in-tree siblings do. The fixture was entirely MergeTree, which does not consume select_query_info.optimize_trivial_count, so no assertion distinguished the guard's placement from one below the flag write. Convert to .sh so the test can write a data file, and assert count(arrayJoin(A)) over file(), which counts inside read() and acts on that flag. Both settings the arm depends on are pinned per query, since the runner randomizes them. Unique names come from CLICKHOUSE_TEST_UNIQUE_NAME so concurrent copies do not collide and no no-parallel tag is needed. The 19 existing reference lines are unchanged.
The old analyzer decides trivial count in TreeRewriter, not in the planner, so the planner guard added in the previous commit does not cover enable_analyzer = 0. A column argument was already safe there: arrayJoin(A) makes A a required column, so has_explicit_columns is true and the eligibility branch is skipped. A constant argument requires no column, so count(arrayJoin([10, 20])) still returned the stored row count. The has_array_join flag does not help, because it is set only for the ARRAY JOIN clause (RequiredSourceColumnsVisitor visits ASTArrayJoin; its ASTFunction case handles only lambda), never for the function form. collectUsedColumns has two eligibility branches and both were wrong the same way, the second one reachable as count(arrayJoin([n, n])) on a partitioned table. Rather than editing both, the predicate goes on the query-shape filter in analyzeSelect that every SELECT eligibility decision passes through, next to the existing GROUP BY, HAVING and FINAL disqualifiers: the flag is only ever written inside collectUsedColumns under is_select, and the path from there to the single return is straight-line. That also keeps the AST walk behind the short-circuit, so it runs only for queries that are otherwise still candidates. hasArrayJoin already exists in this translation unit and stops at nested ASTSelectQuery, matching the scope of the planner-side guard: an unrelated subquery containing arrayJoin keeps the fast path. Test arms use per-query SETTINGS enable_analyzer = 0 so they run in every CI configuration rather than only the old-analyzer jobs, and cover both branches plus over-guard controls asserting count() and count(n) still take the optimization. normalize_function_names is pinned on the unnest arm: the runner randomizes it, and with it off the alias never reaches TreeRewriter as arrayJoin.
The old analyzer decides trivial-count eligibility in TreeRewriter::analyzeSelect by matching the literal function name "arrayJoin". A registered alias such as unnest only carries the canonical name after normalize_function_names has rewritten it, so with that setting off the aggregate argument was not recognised as row-multiplying and the query returned the stored row count. The eligibility filter now compares the canonical name, following RowPolicy.cpp. Only the trivial-count filter is changed; the column-pruning caller at line 478 keeps the literal name, because that decision is about which columns survive projection and broadening it turns a shape whose correct answer exists into an exception. Declining the fast path surfaces the FUNCTION_IS_SPECIAL exception that the same query already throws on unpatched master with the optimization off, instead of a silent row count. arrayJoin is unsupported on the old analyzer with normalize_function_names = 0 independently of this optimization. The new analyzer needs no equivalent change: FunctionNode::resolveAsFunction stores FunctionArrayJoin::getName(), so resolution itself canonicalizes the alias. Test: plan arms for the old analyzer so a destroyed optimization is distinguishable from a preserved one, a SQL-UDF arm pinning that inlining happens before this decision, and an arm asserting the alias no longer reaches the fast path. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (4 rounds, 0 unresolved findings)An independent reviewer read the resulting code cold, without the implementer's evidence, then a Round 4 (this round): 0 gate findings. My own cold review raised 2 candidate findings and
Verified with no defect found (independent re-derivation, not acceptance of the implementer's
💡 Noted, not blocking: this adds a third near-identical Rounds 1-3 findings (all resolved before this round): a missing |
|
Workflow [PR], commit [1d43ecb] Summary: ✅
AI ReviewSummaryThis PR narrows the planner-side trivial-count optimization so it no longer fires when the lone Final Verdict✅ No findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260817-215300 |
|
cc @KochetovNicolai @antaljanosbenjamin, could you review this? applyTrivialCountIfPossible confirms the aggregate is count by type and then never inspects its argument, so count(arrayJoin(arr)) was served from the stored row counter with the row-multiplying expansion deleted; the guard also has to sit before select_query_info.optimize_trivial_count is set, because file() and object storage count inside read() off that flag and were returning 0. |
| SETTINGS enable_analyzer = 0, optimize_trivial_count_query = 1; | ||
| SELECT count() > 0 FROM (EXPLAIN SELECT count() FROM t_04743_old) | ||
| WHERE explain ILIKE '%Optimized trivial count%' | ||
| SETTINGS enable_analyzer = 0, optimize_trivial_count_query = 1; |
There was a problem hiding this comment.
Done in 1d43ecb.
I dropped the TreeRewriter guard along with the arms, because the two are a pair: TreeRewriterResult::optimize_trivial_count is read only by InterpreterSelectQuery, which InterpreterFactory picks only when enable_analyzer = 0, so keeping the guard would have left source on that path with no test. The analyzer fix in PlannerJoinTree is untouched. The old analyzer therefore still returns the row count for count(arrayJoin([10, 20])); say the word if you would rather have that fixed too.
The test keeps no-old-analyzer and still fails on unpatched master (5 wrong-result arms, both plan assertions, and the file() arm).
Per review, the old analyzer is obsolete, so its enable_analyzer = 0 test arms are removed. The TreeRewriter guard those arms covered is reverted with them: TreeRewriterResult::optimize_trivial_count is consumed only by InterpreterSelectQuery, which InterpreterFactory instantiates only when enable_analyzer = 0, so keeping the guard would leave source on that path with no coverage. The analyzer fix in PlannerJoinTree is unchanged. The test keeps the no-old-analyzer tag and still fails on unpatched master.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline. |
Backport #115227 to 26.7: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
…hen the aggregate argument contains arrayJoin
Backport #115227 to 26.6: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
…ches without unnest The test added by ClickHouse#115227 used `unnest`, a case-insensitive alias of `arrayJoin` registered only since 8601d0f (2026-05-16), i.e. after the 25.8 and 26.3 branch points. On those branches the analyzer throws UNKNOWN_FUNCTION before the guard under test is reached, so the backports of ClickHouse#115227 to 25.8 and 26.3 fail on the added test file while the src/Planner fix itself cherry-picks cleanly. All 19 statements of the main block are one client call, so the abort at statement 2 also skipped statements 3-19: every optimize_trivial_count_query = 0 control, the four "optimization is kept" arms and all four EXPLAIN plan assertions. Those backports therefore carried no verification of the fix they exist to port. Drop the two unnest arms from 04743 and relocate the alias coverage into 04241_alias_unnest, which is absent from exactly the branches that lack the alias. This loses nothing at the guard: FunctionNode::resolveAsFunction stores the canonical name, so hasFunctionNode(..., "arrayJoin") sees the two arms identically, and the surviving 20 reference lines are byte-identical with and without them. 04241 gains a MergeTree trivial-count arm with an optimize_trivial_count_query = 0 control. Validated on the backports' own CI build artifacts, both directions on the same binary: 25.8 and 26.3 fail before and are byte-equal to the reference after, with the 17 previously skipped assertions now executing and agreeing; 26.5, 26.6 and 26.7 stay byte-equal. On master both tests pass clickhouse-test, 200/200 over randomized and non-randomized runs. Deleting the guard reddens 7 of 04743's assertions and flips the new 04241 arm from 6 to 3, so neither file is vacuous. This does not turn the already-open backports green: each is built from the parent's frozen merge commit and ClickHouse#115227 carries pr-backports-created, so it is not re-processed.
`unnest`, a case-insensitive alias of `arrayJoin`, was registered only in 8601d0f (2026-05-16), after the 25.8 branch point. On this branch the analyzer throws `UNKNOWN_FUNCTION` at the second statement of the test's single client call, which also skipped statements 3-19: every `optimize_trivial_count_query = 0` control, the four "optimization is kept" arms and all four `EXPLAIN` plan assertions. So the backport carried no verification of the fix it exists to port. This mirrors the master change c97ca0b (#115505), which dropped the two `unnest` arms and relocated the alias coverage into `04241_alias_unnest` - a test that does not exist on this branch, precisely because the alias does not. Nothing is lost at the guard itself: `FunctionNode::resolveAsFunction` stores the canonical name, so `hasFunctionNode(..., "arrayJoin")` sees the `unnest` arms identically to the `arrayJoin` ones, and the surviving 20 reference lines are byte-identical with and without them. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115468&sha=77b6ebb9c8604d45e2db4a7111e93258704076fa&name_0=BackportPR Related: #115227 Related: #115505 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Backport #115227 to 25.8: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
Backport #115227 to 26.5: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
Backport #115227 to 26.3: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
…mization when the aggregate argument contains arrayJoin
…mization when the aggregate argument contains arrayJoin
…mization when the aggregate argument contains arrayJoin
AGG: `count(arrayJoin(arr))` with optimize_trivial_count_query=1 -> wrong. Effect in the production build a394e92: its upstream test(s) 04743_trivial_count_array_join_argument fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv). Upstream patch unchanged, with its test(s): 04743_trivial_count_array_join_argument. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #115123
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results for
SELECT count(arrayJoin(arr))with the defaultoptimize_trivial_count_query = 1. The stored row count was returned instead of the number of array elements, and onfile()andurl()the query returned0. Closes #115123.Description
Requested by @ PedroTadim on the issue ("the fix for this seems small. Can you do it?"); reported by @ konsta-danyliuk.
applyTrivialCountIfPossiblereplaces the whole table read with the stored row counter. It checks that the aggregate iscountby type, then never inspectscount's argument.arrayJoinmultiplies rows above the source read, so the aggregate observessum(length(arr))rows rather thantotalRows(), and the expansion is dropped along with the read. Measured on 3 rows / 6 elements:count(arrayJoin(A))returned3instead of6.The fix refuses the optimization when the argument contains
arrayJoin, using the samehasFunctionNode(..., "arrayJoin")guard six sibling optimizations already use for this property. The guard sits beforeselect_query_info.optimize_trivial_count = true: forfile(),url()and object storagetotalRows()isnullopt, so the function returnsfalse, but the flag has already been written and those storages count inread(), so they returned0. Placing the guard after the flag write fixes MergeTree while leavingfile()at0, so the test asserts thefile()value too.The old analyzer decides trivial count separately, in
TreeRewriter, and is affected there too. Per @ PedroTadim's review, that path is obsolete, so this PR leaves it alone: the analyzer is the only path fixed and asserted, and the test is taggedno-old-analyzer.Not bundled: rewriting
count(arrayJoin(A))tosum(A.size0)would be faster, but that is an optimization on top of a wrong-results fix.Carriers and over-guard checks (measured, base vs patched)
Fixture: 3 rows,
sum(length(A))= 6.count(arrayJoin(A))on MergeTreecount(unnest(A))(alias)count(arrayJoin(A) + 1),arrayJoin(arrayMap(...))(nested)count(arrayJoin(arrayJoin([A,B])))count(arrayJoin(A))onfile()/url()count(arrayJoin(M))Map /(T)Array(Tuple)count(arrayJoin(LC))Array(LowCardinality)count(arrayJoin(A))viaremote()count(arrayJoin(A))ReplacingMergeTree FINALObject storage reads the same flag at
StorageObjectStorage.cpp:720, so it takes thefile()/url()path; with no S3 endpoint here that row is read from the code, not measured.
Unchanged, and asserted so:
count(),count(*),count(1),count(n),count(nullable),ARRAY JOINas a clause,countIf(arrayJoin(...)),count(DISTINCT arrayJoin(...)), thesparsity-filter sibling, and a
count()whose unrelated subquery containsarrayJoin(bothvisitors stop at nested query nodes).
Controls: rejecting any non-empty argument list flips
count(n)off the optimization; moving theguard below the flag write fails the
file()arm alone.Every stateless test referencing
optimize_trivial_countwas run. The only failures need a datasetor a listener this sandbox cannot provide (
test.hits,127.0.0.2:9000) and fail identically onunpatched master.
Workflow [PR]
Sync PR [sync-upstream/pr/115227]
Version info
26.8.1.1681(included in26.8and later)26.7.5.3,26.6.4.4,26.5.8.6,26.3.21.6,25.8.31.12