Skip to content

Fix cubic complexity of planning a JOIN with a merge table - #113140

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix-merge-join-column-resolution
Aug 15, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix-merge-join-column-resolution

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

Planning a query that joins a Merge table with something else could take minutes and hundreds of megabytes of memory, and it was interruptible neither by max_execution_time nor by KILL QUERY, because all of it happens inside QueryPlan::optimize.

ReadFromMerge::createChildrenPlans builds a separate child query tree for every source table. When the Merge table takes part in a JOIN, this goes through replaceTableExpressionAndRemoveJoin, which rebuilds the projection list from the required column names. Every column there was resolved by its own QueryAnalysisPass run, and every such run rebuilt AnalysisTableExpressionData for all the columns of the Merge table. The structure of a Merge table is the union of the structures of its source tables, so the cost of planning was cubic in the number of source tables.

All the required columns are now resolved with a single QueryAnalysisPass run. For 40 tables with 20 distinct columns each, a SELECT * joined with merge goes from 18 seconds down to about a second in a release build; the results are byte-identical before and after.

This is what made the Hung check fail in a stress test: the AST fuzzer produced SELECT * FROM (SELECT number AS a FROM numbers(11)) AS t1 PASTE JOIN merge('system', '') AS t2 LIMIT 294 for 02933_paste_join.sql, and the query spent more than 16 minutes inside QueryPlan::optimize under TSan.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=dd1e53dfe2715c22d4b7e63c2459bc9eec994581&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29

Changelog category (leave one):

  • Performance Improvement

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

Fixed cubic complexity of query planning for a JOIN with a Merge table over many tables with different structures. Such queries could previously spend minutes in query planning without responding to max_execution_time or KILL QUERY.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.1462 (included in 26.8 and later)

`ReadFromMerge::createChildrenPlans` builds a separate child query tree for
every source table. When the `Merge` table takes part in a JOIN, this goes
through `replaceTableExpressionAndRemoveJoin`, which rebuilds the projection
list from the required column names. Every column there was resolved by its own
`QueryAnalysisPass` run, and every such run rebuilt `AnalysisTableExpressionData`
for all the columns of the `Merge` table. The structure of a `Merge` table is
the union of the structures of its source tables, so planning was cubic in the
number of source tables.

Resolve all the required columns with a single `QueryAnalysisPass` run instead.
For 40 tables with 20 distinct columns each, a `SELECT *` joined with `merge`
goes from 18 seconds down to about a second in a release build.

This is what made the `Hung check` fail in a stress test: the AST fuzzer
produced `SELECT * FROM (SELECT number AS a FROM numbers(11)) AS t1 PASTE JOIN
merge('system', '') AS t2 LIMIT 294`, and the query spent more than 16 minutes
inside `QueryPlan::optimize` under TSan, responding neither to
`max_execution_time` nor to the cancellation request.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=dd1e53dfe2715c22d4b7e63c2459bc9eec994581&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ecb7c27]

Summary: ✅


AI Review

Summary

This PR changes StorageMerge so JOIN planning resolves the required merge()-side columns in one QueryAnalysisPass instead of one pass per column, eliminating the cubic planning blow-up on wide Merge tables. I reviewed the current head, the existing discussion, and the added regression tests; the prior alias-resolution concern is covered by 04903_merge_join_alias_column_resolution, and I did not find a remaining correctness, compatibility, or performance-contract issue in the batched analyzer path.

Final Verdict

✅ No remaining review findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.90% +0.20%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 22/26 (84.62%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 35 queries analysed

This PR is scoped entirely to StorageMerge: it batches column resolution in replaceTableExpressionAndRemoveJoin so a JOIN against a merge() table no longer pays cubic query-planning cost. None of the flagged ClickBench (single hits table) or TPC-H (regular MergeTree joins) queries use merge() tables, so this change cannot plausibly touch any of their execution or planning paths. All six flagged improvements are therefore downgraded to not_sure as off-path deltas; the largest and cleanest ones (Q7 ×8.2 faster, Q23 ×2.3 faster) most likely reflect base-build or environment differences rather than this PR. The real effect of this fix would only show up on queries that JOIN wide merge() tables, which this benchmark set does not include.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 482 -13.4% <0.0001 This PR only changes Merge-table JOIN planning in StorageMerge; a single-table ClickBench scan never hits that path, so the -13.4% shift is off-path environment variance, not a PR effect.
⚠️ 18 not_sure 1298 1229 -5.3% <0.0001 Q18 is a single-table hits query and does not use merge() tables, so the StorageMerge planning fix cannot cause the -5.3% delta; treat it as run-to-run variance.
⚠️ 23 not_sure 167 73 ×2.3 faster <0.0001 Q23 has noisy history and runs on a single table with no merge() JOIN, so this Merge-only diff cannot produce the ×2.3 faster result; it is unrelated variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 574 70 ×8.2 faster <0.0001 join_operator: Q7 joins regular MergeTree tables, not merge() tables, so the StorageMerge column-resolution fix cannot touch it; the ×8.2 faster delta more likely reflects a base/environment difference.
⚠️ 8 not_sure 175 80 ×2.2 faster <0.0001 join_operator: Q8 also joins ordinary tables with no merge() involved, so the Merge-only planning change is off-path; the ×2.2 faster shift is not attributable to this PR.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: d8ea543e-20d4-4fdf-8ef6-74d510cc6964
  • MIRAI run: 020fbeca-8fcd-48eb-818f-741d4627d7a7
  • PR check IDs:
    • clickbench_1335721_1786775976
    • clickbench_1335727_1786775976
    • clickbench_1335739_1786775976
    • tpch_adapted_1_official_1335750_1786775976
    • tpch_adapted_1_official_1335763_1786775976
    • tpch_adapted_1_official_1335791_1786775976

@novikd novikd self-assigned this Aug 3, 2026

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

Nice catch!

alexey-milovidov and others added 2 commits August 4, 2026 11:14
The flaky check under TSan and debug builds killed the test after 180
seconds: 40 tables with 20 columns each are too heavy for sanitizer
builds even with the fix. Reduce to 20 tables with 10 columns each; the
whole test takes about half a second in a release build now, while a
cubic planning regression would still blow past the limit.

The run with the old analyzer failed with `UNKNOWN_IDENTIFIER`: the
old analyzer cannot resolve columns of a `Merge` table that are
missing from some of the source tables, so pass `--enable_analyzer 1`
explicitly for the `SELECT` queries.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113140&sha=c60ed76704e5b13d618c8784613a5f878406b5bf&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (amd_tsan) failure (logical error ColumnBLOB should be converted to a regular column before usage) is unrelated to this PR: it is the known issue #113165 (also #111945), with a fix in progress in #111997.

The remaining failures were caused by the new test and are addressed: it now uses 20 tables × 10 columns (the whole test takes ~0.5 s in a release build, so it fits the 180 s flaky-check limit in TSan/debug builds too) and passes --enable_analyzer 1 explicitly, because the old analyzer cannot resolve columns of a Merge table that are missing from some of the source tables.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both remaining CI failures on 304d237 are unrelated to this PR:

Neither fix has landed on master yet, so re-merging master would not clear these. Everything else is green; no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both CI failures on c2fe2bd are unrelated to this PR — they are the fleet-wide stress regressions caused by #113772 (PromQL materialized-CTE subqueries), affecting master and many unrelated PRs since 2026-08-10:

Re-merging master would not clear these until the fixes land. @groeneai, #114291 still has no fix PR — please provide a fix in a separate PR (or link it here if one is already in progress).

@groeneai

Copy link
Copy Markdown
Collaborator

#114291 does have a fix in progress: #113397 (open, not merged). I measured it A/B on the reproduced leak this morning: 5/5 runs leak on an ASAN build of master, 5/5 clean with that patch applied, and a 34-test materialized-CTE/PromQL run gives identical results on both arms, so I am not opening a competing PR for it.

Measurement details are on the issue: #114291 (comment)

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch: both remaining stress-test failures were the fleet-wide fallout of the PromQL topk/limitk streaming plan (LSan materialized-CTE cycle #114291 and the hung DROP TABLE prometheus check #114259), whose revert #114326 has now landed on master, so the fresh CI run should be clean. The branch builds and the test 04695_merge_join_column_resolution passes locally against the merged state.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ecb7c278f with master aef28dd26 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c8dacba9c; 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 693.40 MiB 690.38 MiB -3.02 MiB (-0.44%)

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, 26 s compile time in total, 7 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI failure on 0cb1d1e, Stress test (arm_tsan), is unrelated to this PR: it is the known fleet-wide logical error Sizes of nested column and null map of Nullable column are not equal after deserialization in MergeTreeIndexGranuleSet deserialization after a killed ALTER MODIFY COLUMN mutation — issue #114368, affecting dozens of unrelated PRs and master since 2026-08-07. The fix is open in #112484 (not merged yet), so re-merging master would not clear this red.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113140&sha=0cb1d1e1fbe2baafb9f451fd4e5f187c33a3c55e&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

Comment thread src/Storages/StorageMerge.cpp Resolved
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into master with commit e2fa47b Aug 15, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-merge-join-column-resolution branch August 15, 2026 15:37
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants