Skip to content

Do not use the trivial count optimization when the aggregate argument contains arrayJoin - #115227

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-115123-trivial-count-array-join-argument
Aug 19, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-115123-trivial-count-array-join-argument

Conversation

@groeneai

@groeneai groeneai commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #115123

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 default optimize_trivial_count_query = 1. The stored row count was returned instead of the number of array elements, and on file() and url() the query returned 0. Closes #115123.

Description

Requested by @ PedroTadim on the issue ("the fix for this seems small. Can you do it?"); reported by @ konsta-danyliuk.

applyTrivialCountIfPossible replaces the whole table read with the stored row counter. It checks that the aggregate is count by type, then never inspects count's argument. arrayJoin multiplies rows above the source read, so the aggregate observes sum(length(arr)) rows rather than totalRows(), and the expansion is dropped along with the read. Measured on 3 rows / 6 elements: count(arrayJoin(A)) returned 3 instead of 6.

The fix refuses the optimization when the argument contains arrayJoin, using the same hasFunctionNode(..., "arrayJoin") guard six sibling optimizations already use for this property. The guard sits before select_query_info.optimize_trivial_count = true: for file(), url() and object storage totalRows() is nullopt, so the function returns false, but the flag has already been written and those storages count in read(), so they returned 0. Placing the guard after the flag write fixes MergeTree while leaving file() at 0, so the test asserts the file() 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 tagged no-old-analyzer.

Not bundled: rewriting count(arrayJoin(A)) to sum(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.

case base patched
count(arrayJoin(A)) on MergeTree 3 6
count(unnest(A)) (alias) 3 6
count(arrayJoin(A) + 1), arrayJoin(arrayMap(...)) (nested) 3 6
count(arrayJoin(arrayJoin([A,B]))) 3 11
count(arrayJoin(A)) on file() / url() 0 6
count(arrayJoin(M)) Map / (T) Array(Tuple) 3 5
count(arrayJoin(LC)) Array(LowCardinality) 3 7
count(arrayJoin(A)) via remote() 3 6
count(arrayJoin(A)) ReplacingMergeTree FINAL 6 6

Object storage reads the same flag at StorageObjectStorage.cpp:720, so it takes the file()/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 JOIN as a clause, countIf(arrayJoin(...)), count(DISTINCT arrayJoin(...)), the
sparsity-filter sibling, and a count() whose unrelated subquery contains arrayJoin (both
visitors stop at nested query nodes).

Controls: rejecting any non-empty argument list flips count(n) off the optimization; moving the
guard below the flag write fails the file() arm alone.

Every stateless test referencing optimize_trivial_count was run. The only failures need a dataset
or a listener this sandbox cannot provide (test.hits, 127.0.0.2:9000) and fail identically on
unpatched master.


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

Version info

  • Merged into: 26.8.1.1681 (included in 26.8 and later)
  • Backported to: 26.7.5.3, 26.6.4.4, 26.5.8.6, 26.3.21.6, 25.8.31.12

groeneai and others added 4 commits August 17, 2026 14:42
… 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds, 0 unresolved findings)

An independent reviewer read the resulting code cold, without the implementer's evidence, then a
second model re-reviewed the full scope. Findings and verdicts below.

Round 4 (this round): 0 gate findings. My own cold review raised 2 candidate findings and
withdrew both on re-measurement; they are recorded rather than deleted, because each is a trap
worth naming.

# Finding Verdict
⚠️ Test number 04743 is also claimed by two of my other open PRs 💡 Withdrawn. Not enforced and not a defect: master has 3831 distinct 5-digit prefixes and all 3831 already carry more than one distinct basename (00001_count_hits + 00001_select_1). The runner keys on the full basename; check_style.py's only number check flags gaps >= 100. The real hazard is a same-basename clash, which this is not.
❌ Reference line 38 (FUNCTION_IS_SPECIAL) appeared not to match the patched binary 💡 Withdrawn. The liveness matrix omits a column its own header declares, so that cell was measured on two binaries that predate the last commit. Re-measured on the committed head: the arm does throw Code: 129, so line 38 is the arm that commit turns green. Confirmed from source independently: the old analyzer lowers arrayJoin by a raw name comparison (ActionsVisitor.cpp:1002), so an unnormalized alias is never lowered and reaches FunctionArrayJoin::executeImpl, which throws. The exception is pre-existing.

Verified with no defect found (independent re-derivation, not acceptance of the implementer's
claims):

  • Carriers. I enumerated the 30 optimize_trivial_count sites myself before reading the plan.
    Both deciders are guarded; the sparsity-filter sibling requires an empty argument list
    (PlannerJoinTree.cpp:700) so count(arrayJoin(x)) cannot reach it; the old analyzer's
    totalRows() and totalRowsByPartitionPredicate() branches, and TreeRewriter's two
    eligibility write sites, are each covered by one guard; the LIMIT-pushdown arrayJoin guards are
    a different optimization and untouched. My list matched the plan's.
  • Guard placement. The guard must precede select_query_info.optimize_trivial_count = true,
    because file(), url() and object storage count inside read() off that flag even when this
    function later declines. A negative control that moves the guard one line later fixes MergeTree
    and leaves file() returning 0, so the test asserts the file() value.
  • The two guards' asymmetry is justified, not copy-paste drift. On the new analyzer
    FunctionNode::resolveAsFunction stores FunctionArrayJoin::getName(), so a resolved alias
    already carries the canonical name. On the old analyzer names are canonicalized only by
    FunctionNameNormalizer under normalize_function_names, which CI randomizes, so that path needs
    the canonical-name form.
  • Over-guard bound. The planner guard inspects only the single count aggregate; the old-analyzer
    guard only the select list. A mutation that destroys the optimization outright reddens exactly the
    two kept-optimization assertions and nothing else, so those assertions are live.
  • Test liveness. 15 of 38 reference lines redden on pristine master; 2 more redden only under
    that mutation. The remaining lines are settings-off mirrors and no-arrayJoin controls, which is
    what makes a future over-guard visible. An earlier round found and fixed a vacuous over-guard
    assertion (count() cannot move under the over-guard it was written to detect); the replacement
    count(n) assertion was verified to fail on the over-broad build.
  • Countable claim in the description ("six sibling optimizations already use") re-measured: exactly 6.
  • Competing PR, re-checked on a fresh clock: no PR references issue Wrong result: optimize_trivial_count_query makes count(arrayJoin(arr)) return the table's row count instead of the number of array elements #115123.

💡 Noted, not blocking: this adds a third near-identical arrayJoin AST walker alongside
hasArrayJoin and selectListHasArrayJoinFunction (a fourth canonicalizing variant lives in
RowPolicy.cpp). Consolidating would change the behaviour of unrelated call sites -- hasArrayJoin
governs column-removal semantics, not row cardinality -- so I left it. Happy to fold it in if you
would prefer one shared helper.

Rounds 1-3 findings (all resolved before this round): a missing no-old-analyzer tag; the
guard-placement / file() carrier gap; and a false old-analyzer mechanism claim in maintainer-facing
text, corrected.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1d43ecb]

Summary: ✅


AI Review

Summary

This PR narrows the planner-side trivial-count optimization so it no longer fires when the lone count aggregate argument contains arrayJoin, which would otherwise multiply rows above the source read and make totalRows() incorrect. I did not find a remaining correctness gap in the current analyzer path: the guard is placed before select_query_info.optimize_trivial_count, so the file() / url() / object-storage read-side count carrier is covered as well, ARRAY JOIN clause queries are excluded earlier by the join-tree shape, and the new stateless test exercises both the wrong-result case and the flag-placement regression. The PR discussion intentionally scoped the change away from the obsolete old-analyzer path, and the current code matches that decision. Full Praktika CI is green.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.90% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization needed. CREATE TABLE t (A Array(UInt32)) ENGINE = MergeTree ORDER BY tuple(); INSERT INTO t VALUES ([1,2,3]),([4,5]),([6]); SELECT count(arrayJoin(A)) FROM t SETTINGS optimize_trivial_count_query = 1; returns 3, correct is 6. The file()/url() variants return 0.
b Root cause explained? Yes, and it is the same root cause in two independent decision points. New analyzer: applyTrivialCountIfPossible (src/Planner/PlannerJoinTree.cpp) replaces the table read with the stored row counter, validates the aggregate is count by type, and never inspects count's argument. Old analyzer (enable_analyzer = 0): TreeRewriterResult::collectUsedColumns decides eligibility instead, and its has_array_join flag is set only by the ARRAY JOIN clause (RequiredSourceColumnsVisitor.cpp:109, reached only from ASTArrayJoin; visit(ASTFunction) handles only lambda), so the function form is invisible to it. Either way arrayJoin is row-multiplying and evaluated above the source read, so the aggregate observes sum(length(A)) rows, not totalRows(); deleting the read deletes the expansion. Confirmed by plan: = 1 gives ReadFromPreparedSource (Optimized trivial count), = 0 gives ReadFromMergeTree.
c Fix matches root cause? Yes. The optimization's own premise (rows observed == totalRows()) is false here, so the planner declines and falls back to the ordinary read, which is already correct. Not a widened bound, not a no-random-* tag, not a guard masking an upstream bug.
d Test intent preserved / new tests added? New stateless test 04743_trivial_count_array_join_argument.sh, 38 assertions: 5 buggy shapes, the same 5 with the optimization off as a control, 5 fast-path arms that must not regress, 4 plan assertions in the SELECT ... FROM (EXPLAIN ...) WHERE explain ILIKE ... form, 3 file() arms for the storages that count inside read(), and 10 old-analyzer arms (3 that reddened, 2 optimization-off controls, 1 pinning the pre-existing column-argument safety, 4 over-guard controls on both eligibility branches). The no-old-analyzer tag stays, because the plan assertions describe applyTrivialCountIfPossible; the old-analyzer arms use per-query SETTINGS enable_analyzer = 0 so they run in every CI configuration rather than only the old-analyzer jobs. Plus, for the old-analyzer half: 4 plan assertions in the same SELECT ... FROM (EXPLAIN ...) form (2 refusals, 2 positive controls on the two independent eligibility write sites), a SQL-UDF arm pinning that inlining happens before this decision, and an arm asserting the alias no longer reaches the fast path. Without those plan arms the old-analyzer half asserted values only, so an unconditionally disabled optimization would have produced byte-identical output; a mutation forcing it off now reddens exactly the 2 positive controls. No no-parallel: table, database and UDF names are per-run. No existing test was changed or weakened.
e Both directions demonstrated? Yes, per guard, each arm on a build whose id was asserted on the running server with SELECT lower(buildId()). Pristine base (a675fe71820dd23) FAILS on 15 of 38 reference lines: the values collapse to the row count 3, Optimized trivial count is still present, and the file() arm returns 0. The head before the alias fix (df1dfebb4d39dc1a) still returns a silent 3 for count(unnest([10, 20])) with normalize_function_names = 0. Fully patched (e7530c36630dddc4) PASSES all 38, 50/50 with randomization on and 4 concurrent copies. Mutation controls, each failing on a different arm: moving the planner guard below the flag write fails the file() arm alone; guarding only the old analyzer's first branch fails the partitioned arm alone; broadening to reject any non-empty argument list fails count(n); forcing the old-analyzer eligibility off unconditionally (5a4852b749fe1caa) fails exactly the 2 plan positive controls.
f Fix is general across code paths? Yes, and the second analyzer is fixed too rather than assumed safe. Storage carriers: four readers of SelectQueryInfo::optimize_trivial_count were enumerated; three are live, all covered by the planner guard because it precedes the flag write (MergeTree totalRows(), StorageFile, StorageURL, measured 0 to 6), plus StorageObjectStorage which reads the flag identically. Analyzer carriers: the old analyzer was not safe for a constant argument, so it gets its own guard. optimize_trivial_count is written for SELECT in exactly two places, both inside collectUsedColumns (the no-explicit-columns branch and the partition-predicate branch), and both were independently wrong; both are covered by one clause on the existing query-shape filter in analyzeSelect, which every SELECT eligibility decision passes through (the other collectUsedColumns call site passes is_select = false, and both writes are is_select-gated). Verified already-safe without change: the sparsity-filter sibling (refuses non-empty arguments), a column argument on the old analyzer (it makes the column required), the ARRAY JOIN clause form, countIf, count(DISTINCT ...), and WHERE/GROUP BY/HAVING. PREWHERE arrayJoin(...) is not a carrier at all: Code 182 ILLEGAL_PREWHERE. Spelling carrier: the old-analyzer clause compares the canonical name (as RowPolicy.cpp does, the only other canonicalizing site), so a registered alias is recognised with normalize_function_names either way. The new analyzer needs no equivalent change and this is by construction, not assumption: FunctionNode::resolveAsFunction stores FunctionArrayJoin::getName(), the literal arrayJoin, so resolution canonicalizes the alias; verified empirically. The sibling column-pruning caller of the literal-name helper is deliberately unchanged and measured non-regressing, since it decides which columns survive projection rather than count eligibility.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured base vs patched: Array(LowCardinality(String)) 3 to 7, Map 3 to 5, Array(Tuple) 3 to 5, Array(Nullable) unchanged at 4 (a different aggregate type, already safe), all-empty arrays 3 to 0, a constant array literal 3 to 12, nested in an expression, chained arrayJoin, inside arrayMap, the unnest alias, remote(), merge(), and ReplacingMergeTree FINAL. Over-guard direction asserted too: count(), count(*), count(1), count(n) keep the optimization, as does a count() whose unrelated scalar subquery contains arrayJoin. Spelling dimension measured across normalize_function_names 0 and 1, constant and column arguments, and both eligibility write sites (ORDER BY tuple() and PARTITION BY); normalize_function_names is randomized in CI, so every arm pins it per query.
h Backward compatible? Yes. No new setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry. The only behaviour changes are that a silently wrong count becomes correct, and that one alias spelling which returned a wrong number now throws the FUNCTION_IS_SPECIAL exception that the same spelling already throws elsewhere on master.
i Invariants and contracts preserved? Yes, both guards. The invariant is the same: the trivial-count path may fire only when the aggregate observes exactly totalRows() rows. Planner guard: an early return false before any state is mutated, so select_query_info is untouched on the refusal path, which is why it must precede the flag write; it runs after the count-by-type check, so aggregates.front() is known to be the single aggregate. Old-analyzer guard: a pure read of the query AST that only ever clears optimize_trivial_count, never sets it, so it cannot enable a path that was previously refused; it is last in a short-circuit && chain behind if (result.optimize_trivial_count), so the AST walk runs only for queries still otherwise eligible. select() is non-null there, dominated by an unconditional dereference in collectUsedColumns earlier in the same function. Scope matches the planner side: the helper stops at nested ASTSelectQuery, so an unrelated subquery containing arrayJoin keeps the fast path (measured, base and patched identical).

Session id: cron:clickhouse-impl-slot-4:20260817-215300

@groeneai

Copy link
Copy Markdown
Collaborator Author

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;

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 forget enable_analyzer = 0, it's obsolete

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.

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

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1d43ecbc4 with master 2bb9dae14 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.05 MiB 699.03 MiB -3.03 MiB (-0.43%)

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 units

7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 19, 2026
Backport #115227 to 26.7: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 19, 2026
…hen the aggregate argument contains arrayJoin
clickhouse-gh Bot added a commit that referenced this pull request Aug 19, 2026
Backport #115227 to 26.6: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
vanchaklar pushed a commit to vanchaklar/ClickHouse that referenced this pull request Aug 20, 2026
…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.
alexey-milovidov added a commit that referenced this pull request Aug 20, 2026
`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]>
vdimir added a commit that referenced this pull request Aug 20, 2026
Backport #115227 to 25.8: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
vdimir added a commit that referenced this pull request Aug 20, 2026
Backport #115227 to 26.5: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
alexey-milovidov added a commit that referenced this pull request Aug 20, 2026
Backport #115227 to 26.3: Do not use the trivial count optimization when the aggregate argument contains arrayJoin
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…mization when the aggregate argument contains arrayJoin
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…mization when the aggregate argument contains arrayJoin
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…mization when the aggregate argument contains arrayJoin
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
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]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wrong result: optimize_trivial_count_query makes count(arrayJoin(arr)) return the table's row count instead of the number of array elements

6 participants