Skip to content

Estimate an array join as 100 rows per input row in join reordering - #126491

Merged
vdimir merged 4 commits into
ClickHouse:masterfrom
groeneai:join-swap-empty-array-join-input
Oct 30, 2026
Merged

vdimir merged 4 commits into
ClickHouse:masterfrom
groeneai:join-swap-empty-array-join-input

Conversation

@groeneai

@groeneai groeneai commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #126481
Related: #113336

Changelog category (leave one):

  • Performance Improvement

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

Join reordering estimates a relation with arrayJoin or ARRAY JOIN as 100 rows per input row instead of leaving its size unknown, so a hash join builds its hash table from a small or empty array join input instead of reading the other input into it. Closes #126481.

Description

On 26.8, the LEFT JOIN query of #126481 reads all 6M rows of the right table into the hash table (peak 1.3 GB), although the arrayJoin side has no rows; 26.6 built from that side.

The build side is swapped only when both sides have a row estimate. Since #98533 an ExpressionStep with arrayJoin has none, and an ArrayJoinStep (the lowered function, the default since 26.10, and ARRAY JOIN) never had one. Now both get the estimate of their input times 100, because the sizes of the arrays are unknown. A filter above the array join is not applied to the input's estimate, and the statistics of the array-joined columns are dropped.

The cost: few input rows with very large arrays are estimated too low, as on 26.6, which passed the input's count through unchanged. 2 rows with 1M-element arrays joined to a 100k-row table now build 2M rows (153 MB) instead of 100k (30 MB).

Validation (MergeTree instead of SharedMergeTree, debug build, on the PR head and merged with current master): both queries of the issue, with and without compatibility = '25.6', no longer read the right table (no JoinBuildTableRowCount), peak 6-8 MB instead of 1.3-1.75 GB, same results. The test covers both carriers with an empty input, a small input and an input estimated above the other side; with a multiplier of 1 the last two cases fail.


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

Version info

  • Merged into: 26.11.1.917-master (included in 26.11 and later)

groeneai and others added 3 commits October 17, 2026 12:03
An array join multiplies each input row by its array size, which is not
estimated, so since ClickHouse#98533 an `ExpressionStep` with `arrayJoin` gives no row
estimate, and an `ArrayJoinStep` (the lowered `arrayJoin` function and the
`ARRAY JOIN` clause) never gave one. The hash join swap needs an estimate on
both inputs, so a join with an array join input over a read that selects no
rows kept building the other, possibly huge, input.

`RelationStats` now carries `proven_empty`, set only by the read branch whose
exact range analysis selected no rows and kept by steps that cannot add rows.
An array join over such an input is estimated at 0 rows; any other array join
keeps returning no estimate, because a child row count is neither an upper
nor a lower bound and an estimated zero (a keyless aggregation, a truncated
statistics selectivity) is not emptiness.

Related: ClickHouse#126481

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A statistics estimate of 0 rows is only an estimate, so an array join over
such a read kept no estimate and the hash join kept building the other input.
Execution-time part pruning proves the read empty only when it runs: it is
off with `use_statistics_for_part_pruning = 0` (which `compatibility` below
26.4 sets) and under FINAL. The issue's LEFT JOIN query runs with the former,
its INNER JOIN query with FINAL.

When the statistics estimate of a MergeTree read is 0, the estimator now asks
the statistics part pruner whether the read's filter excludes every analyzed
part. The check shares its conditions and its per-part test with
`filterPartsByStatistics`, which is only split, not changed. It does not
depend on `use_statistics_for_part_pruning`, because it skips no part and
only feeds the join order. Under FINAL it holds only for ReplacingMergeTree,
whose FINAL picks stored rows; SummingMergeTree and the other merging modes
compute new rows. It is stricter than part pruning on stale statistics: any
pending mutation or patch part, or a part storing a filtered column with
another type than the table (a killed MODIFY COLUMN), gives no proof.

Related: ClickHouse#126481

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop comments that narrate the new code and shorten the field and function contracts to one line each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 1 finding), plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ filterPartsByStatistics still prunes by stale statistics while a RENAME COLUMN is pending or after a killed MODIFY COLUMN (MergeTreeDataSelectExecutor.cpp:841) DISAGREE Pre-existing on master: this PR moves those gates into a shared helper without changing pruning. Fencing execution pruning is the scope of the open #119337 and #117814; the new proof has its own fence (test arms pending RENAME and killed MODIFY COLUMN).
2 ⚠️ Overlap with my open #113336, which adds a RelationStats upper bound that is also 0 on an empty range selection AGREE Disclosed in the description; #113336 bounds no array join, so it does not fix #126481.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261017-133800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test on master d6c2532ef gives 0 1 (other side builds) for the five array-join arms over a proven-empty input; the issue's two queries build 6,000,000 rows into the hash table under compatibility = '25.6' and the default.
b Root cause explained? The hash-join swap needs a row estimate on both inputs. An array join input has none (since #98533 for ExpressionStep with arrayJoin, always for ArrayJoinStep), and a 0-row statistics estimate below it is not a proof of emptiness.
c Fix matches root cause? Yes. The estimator now produces 0 rows for an array join only when its input is proven empty: range analysis selected no rows, or the per-part statistics exclude every part for the read's filter. No bound, tag or setting changed.
d Test intent preserved / new tests added? New 05406_join_swap_empty_array_join_input: 15 EXPLAIN arms (ILIKE on the Join: line) and 9 result lines.
e Both directions demonstrated? Yes. 5 arms red on master and green with the fix; ten mutants (drop either carrier, accept an estimated 0, accept any FINAL, reject FINAL, gate by use_statistics_for_part_pruning, drop the mutation fence or the type check, skip the per-part check, pass the child estimate through) each redden their own case. 50/50 randomized runs green; 20/20 under DatabaseReplicated.
f Fix is general across code paths? Both carriers (arrayJoin function, lowered or not, ARRAY JOIN, LEFT ARRAY JOIN) and both producers of the proof; the proof is kept only through steps that cannot add rows. filterPartsByStatistics is split into shared helpers with unchanged behaviour (134 statistics tests unchanged).
g Fix generalizes across inputs (params/datatypes/wrappers)? MergeTree, ReplacingMergeTree FINAL (proven), SummingMergeTree FINAL (refused, it computes new rows), other merging modes refused under FINAL; use_statistics_for_part_pruning 0/1; lowering 0/1; compatibility = '25.6' and default.
h Backward compatible? (maintainer-approved exception only) Yes. Plan-only change, no setting, identical results.
i Invariants and contracts preserved? proven_empty is set only where no row can exist and fails closed on: no filter, any pending mutation or patch part, masking or row policy, FINAL of a non-Replacing engine, a part storing a filtered column with another type, a throwing per-part check. A wrong proof could cost memory, never results.

Session id: cron:clickhouse-impl-slot-4:20261017-130000

@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ec0d109]

Summary: ✅


AI Review

Summary

The PR estimates arrayJoin and ARRAY JOIN output as 100 rows per input row, allowing join reordering to choose a small or empty build side. No actionable findings. The focused regression test passes on ec0d109018b6509fb1e221c3831811470e3040d0, and the PR provides before/after memory measurements and discloses the heuristic's tradeoff for large arrays.

Final Verdict

Status: ✅ Approve

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @CurtizJ, could you review this? An array join input now gets a 0-row estimate only when range analysis or the per-part statistics prove it empty, so the hash join builds from it again (#126481), while the #98533 guard still holds for every other array join; the statistics proof reuses the filterPartsByStatistics gates.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 17, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Oct 17, 2026
@fm4v fm4v added the can be tested Allows running workflows for external contributors label Oct 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ec0d10901 with master 8ea13846e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 956f38dc4; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 035d190

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
Performance Comparison (arm_release, master_head, 6/6) / insert_statistics_uniq_v2 #5 flaky, not from this PR (it changes join-reorder row estimates, not MATERIALIZE STATISTICS): background merges leave each server with its own part layout, and the measured mutation follows the largest part, so the gap survives the restart; #4/#5 were slower on 45 other PRs and on master in the last 2 days #126505 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) / 03821_drop_workload_during_query_race flaky, not from this PR: a racing query fails with the expected INVALID_SCHEDULER_NODE after DROP WORKLOAD, and the test's line filter lets the server's stack trace through to stdout (1/60 reruns failed; 67 PRs in 7 days) #126345 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126505, #126345 (the owners of the rows above)
Sync - CH Inc sync (private, not actionable by me)

The two Config Workflow / Pre Hooks failures on this head are the earlier attempts stopped at the can be tested label; the current attempt passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261018-080006

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

Maybe let's keep current logic as is, but only use some multiplier for array join step instead of turning estimation into unknown?

Comment on lines +851 to +861
try
{
return statistics_pruner.checkPartCanMatch(estimates).can_be_true;
}
catch (const Exception &)
{
tryLogCurrentException(log, fmt::format(
"Failed to apply statistics pruning for part {}, skipping statistics pruning for this part",
part.data_part->name), LogsLevel::debug);
return true;
}

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.

Try to avoid try catch here

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.

Removed together with the statistics proof in ec0d109; the PR no longer touches MergeTreeDataSelectExecutor.

An array join made the row estimate of its relation unknown, so a hash join
never compared the sides and kept building from the other side, even when the
array join input was empty (ClickHouse#126481). Multiply the input estimate by 100
instead (the sizes of the arrays are unknown), as suggested in review.

This replaces the emptiness proof by range analysis and part statistics of
the previous commits, which is reverted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Build the hash table from an array join input whose rows are proven empty Estimate an array join as 100 rows per input row in join reordering Oct 28, 2026
@groeneai

groeneai commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

Done in ec0d109: an array join (arrayJoin in an expression, the lowered ArrayJoinStep, ARRAY JOIN) now gets the estimate of its input times 100, and the emptiness proof is gone, so the change is +21/-2 in RelationStatisticsEstimator.cpp plus the test. Both queries of #126481 no longer read the right table (6-8 MB instead of 1.3-1.75 GB).

One measured cost: 2 rows with 1M-element arrays joined to a 100k-row table now build 2M rows (153 MB) instead of 100k (30 MB), as on 26.6. Any multiplier below the real array size does that. I picked 100, the default row estimate PostgreSQL uses for unnest.

@vdimir

vdimir commented Oct 28, 2026

Copy link
Copy Markdown
Member

@groeneai make sure it fixes #126481

@vdimir vdimir self-assigned this Oct 28, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Oct 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Checked on the current head (ec0d109) and on it merged with current master, with both queries of #126481 as written there (local MergeTree/ReplacingMergeTree instead of the Shared* engines), under compatibility = '25.6' and the default. JoinBuildTableRowCount / peak memory (debug builds, so no timings):

Query master this PR
LEFT JOIN, compatibility = '25.6' 6,000,000 / 1.29 GB 0 / 8.2 MB
LEFT JOIN, default 6,000,000 / 1.62 GB 0 / 6.7 MB
INNER JOIN, compatibility = '25.6' 6,000,000 / 1.44 GB 0 / 6.5 MB
INNER JOIN, default 6,000,000 / 1.75 GB 0 / 5.9 MB

With the PR the join builds from the empty arrayJoin side and t2 is not read (SelectedRows 1,259, only t1, vs 6,001,259 on master), which is the expected behaviour in the issue. Results are identical, and the merge with master gives the same plans (6.2-8.5 MB). A non-empty variant of the LEFT JOIN query (1,318 arrayJoin rows) now also builds from those rows instead of the 6M rows of t2 (6-19 MB vs 1.34-1.62 GB).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ec0d109

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 563 of 581 runs since 2026-10-26 22:00 UTC are red, on 328 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261028-193003

remapColumnStats(stats.column_stats, expression_step->getExpression());
else
for (const auto & column : array_join_step->getColumns())
stats.column_stats.erase(column);

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.

Do we just drop all column stats and keep only the relation cardinality for the array join case? Why is that?

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.

No, only the array-joined column loses them. The other columns keep their stats: for ExpressionStep they go through remapColumnStats as usual, and for ArrayJoinStep only the columns in getColumns() are erased. Repeating rows (or dropping the ones with an empty array) can only shrink a column's NDV and value range, so those stay valid bounds.

The array-joined column is different because its input stats describe whole arrays, not elements. It can have such stats: they are inherited through CAST or a one-argument function of a column with statistics. With ExpressionStep the ARRAY_JOIN node already stops the lineage in describeActionsDAGLineageHop; ArrayJoinStep replaces the column under the same name, hence the explicit erase.

Measured on a build of this head, t1 with uniq statistics on c1 (7 distinct) and s (1000 distinct), where CAST(s, 'Array(String)') has only 10 distinct elements:

  • CAST(s, 'Array(String)') AS a, no array join: 1000 rows, columns: [a: 1000, c1: 7], so the array column claims 1000 distinct values;
  • arrayJoin(...) AS k, lowered to ArrayJoinStep, not lowered, and as ARRAY JOIN: 100000 rows, columns: [c1: 7] on this PR, unknown rows, columns: [] on master.

@vdimir
vdimir added this pull request to the merge queue Oct 30, 2026
Merged via the queue into ClickHouse:master with commit 4e3df38 Oct 30, 2026
354 of 355 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 30, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @vdimir — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The array-join filter finding (#128220) is confirmed; the fix is in #128248.

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 30, 2026
…ering

Since ClickHouse#126491 the array-join branch of `estimateReadRowsCount` estimates an
array join as 100 rows per input row. It ignored both the filter passed from
above (a `FilterStep` over the array join, e.g. with
`query_plan_fuse_filter_into_array_join = 0`) and the step's own element
filter (`ArrayJoinStep::hasElementFilter`), so a filtered array join got a
known, inflated row count and `swap_on_sizes` built the hash table from the
other, possibly much larger, input.

Like the other branches of the function do for a filter they cannot account
for, a filtered array join now has no row estimate, unless its input is
estimated at 0 rows, which a filter cannot change. An unfiltered array join
keeps the multiplier.

Closes ClickHouse#128220

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 2, 2026
Backport #126491 to 26.10: Estimate an array join as 100 rows per input row in join reordering
vdimir pushed a commit that referenced this pull request Nov 2, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.8: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #126491 is applied there, with two adaptations:
- the third argument (`for_runtime_filter_transport`) of the recursive call
  does not exist on 26.8 and is dropped;
- `toUInt64Saturating` (added by #124008, master-only) does not exist on 26.8,
  so the file gets a static copy of it with the same body.

The setting `query_plan_lower_array_join_function` does not exist on 26.8
(`arrayJoin` is never lowered to an `ArrayJoinStep` there), so the test
`05406_join_swap_array_join_estimate` drops it from four queries. Those
queries then run the `arrayJoin` expression path, with the same result,
and the reference is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vdimir pushed a commit that referenced this pull request Nov 2, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.9: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #126491 is applied there, with two adaptations:
- the third argument (`for_runtime_filter_transport`) of the recursive call
  does not exist on 26.9 and is dropped;
- `toUInt64Saturating` (added by #124008, master-only) does not exist on 26.9,
  so the file gets a static copy of it with the same body.

The test `05406_join_swap_array_join_estimate` is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Nov 2, 2026
Cherry pick #126491 to 26.8: Estimate an array join as 100 rows per input row in join reordering
robot-clickhouse added a commit that referenced this pull request Nov 2, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Nov 2, 2026
Cherry pick #126491 to 26.9: Estimate an array join as 100 rows per input row in join reordering
robot-clickhouse added a commit that referenced this pull request Nov 2, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 2, 2026
Backport #126491 to 26.8: Estimate an array join as 100 rows per input row in join reordering
clickhouse-gh Bot added a commit that referenced this pull request Nov 2, 2026
Backport #126491 to 26.9: Estimate an array join as 100 rows per input row in join reordering
alexey-milovidov pushed a commit that referenced this pull request Nov 4, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.8: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #128248 is applied there, on top of the 26.8 resolution
of #126491, with one adaptation: `ArrayJoinStep` has no element filter on
26.8 (`query_plan_fuse_filter_into_array_join` does not exist there), so
only a filter above the step leaves the row count unknown.

The test `05406_join_swap_array_join_estimate` drops the settings that do
not exist on 26.8 (`query_plan_fuse_filter_into_array_join`,
`query_plan_lower_array_join_function`), so its "element filter" and
"filter step" queries are the same query there. The reference is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 4, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.9: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #128248 is applied there, on top of the 26.9 resolution
of #126491. The hunk is the same as on master.

The test `05406_join_swap_array_join_estimate` is the same as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 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 comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

performance regression: join with an arrayJoin side no longer swaps to the small build side (26.6 -> 26.8)

7 participants