Skip to content

Make planning of a Merge child with many ALIAS columns linear in their number - #134077

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:merge-many-alias-columns-linear-planning
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:merge-many-alias-columns-linear-planning

Conversation

@groeneai

@groeneai groeneai commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #114734
Related: #128155

Changelog category (leave one):

  • Performance Improvement

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

Planning a query over a Merge table or the merge table function is now linear, instead of quadratic, in the number of independent ALIAS columns it reads from a source table. For example, SELECT * FROM merge('system', 'metric_log') reads about 2,500 ALIAS columns of system.metric_log and could plan for a long time, ignoring max_execution_time.

Description

In the stress job's log export, the AST fuzzer's SELECT * FROM merge(REGEXP('(?i)SYSTEM'), 'metric_log') (and two variants) spent 64-72 min planning the system.metric_log child on amd_tsan with max_execution_time = 10: 1, 2, 3.

metric_log has about 2,480 ALIAS columns that system.all_metric_log declares MATERIALIZED, so merge() makes them ordinary and * reads all of them from metric_log as aliases. ReadFromMerge handled a child's aliases one at a time: a QueryAnalysisPass (each rebuilding the analysis data of all columns) and an actions visit per column in getModifiedQueryInfo, then another pass and an ExpressionStep per alias in convertAndFilterSourceStream. Each part is quadratic, and the time limit is only checked between children.

Both places now resolve the alias names with one QueryAnalysisPass over a list, as replaceTableExpressionAndRemoveJoin does since #113140, and one ExpressionStep computes the aliases. The JOIN path is already one pass; direct reads of many aliases are #128634.

Resolving by name also fixes a wrong result (present in 26.3-26.10): re-analyzing each inlined alias's AST let a source table's ALIAS column named __table1, the generated table alias, capture __table1.x: y UInt64 ALIAS x + 2 returned 102, not 3, through merge. The names are resolved with analyzer_compatibility_prefer_alias_over_subcolumn off, otherwise __table1.x, a subcolumn of that column, meant the column x of the table (a LOGICAL_ERROR on master).

Debug build, default server config: the three CI queries took 98-107 s (TIMEOUT_EXCEEDED) and now 1.9-3.2 s. A child with 2,500 aliases: 22.3 s -> 0.48 s, same results. Merge-related stateless tests: same results. The .sh test generates its 2,500-column tables and checks the peak memory in system.query_log (510 MB -> 36 MB).

🤖 Generated with Claude Code


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

groeneai and others added 4 commits November 24, 2026 00:57
…r number

`ReadFromMerge` handled the `ALIAS` columns a child is asked for one at a
time. `getModifiedQueryInfo` ran a separate `QueryAnalysisPass` per alias
(each one rebuilds the analysis data of all the child's columns) and a
separate `PlannerActionsVisitor` visit per column (each one indexes the
whole growing DAG). `convertAndFilterSourceStream` then ran another pass and
added a separate `ExpressionStep` per alias, a chain of N steps with growing
headers that `QueryPlan::optimize` merges one by one. All of it is quadratic
in the number of aliases, and runs inside one child iteration of
`createChildrenPlans`, where the time limit is not checked.

Since `system.metric_log` has about 2,480 `ALIAS` columns over one map and
`system.all_metric_log` declares the same columns `MATERIALIZED`, they are
ordinary columns of `merge('system', 'metric_log')`, and `*` reads all of them
from `metric_log` as aliases. The AST fuzzer's variants of that query in the
stress job's log export spent 64-72 minutes planning that child on amd_tsan
with `max_execution_time = 10`; on a debug build it takes about 100 s.

Resolve all aliases with one `QueryAnalysisPass` over a list, as
`replaceTableExpressionAndRemoveJoin` already does since ClickHouse#113140, visit the
columns once, and compute all aliases with one `ExpressionStep`. Its outputs
are assembled in one pass to be the same as one `addOrReplaceInOutputs` call
per alias, in order (every output of a name is replaced by the last alias of
that name, a new name is appended once), without rescanning the outputs for
each alias. One shared analyzer scope is safe for the aliases of one table:
`CREATE TABLE` and `ALTER` already validate all its column defaults in one
scope.

Debug build, default server config: the CI queries went from 98-107 s
(`TIMEOUT_EXCEEDED` with a 10 s limit) to 2.6-3.8 s. A child with N aliases:
N = 1000 3.65 s -> 0.15 s, N = 2000 14.2 s -> 0.31 s, N = 2500 22.3 s -> 0.40 s,
peak memory 519 MB -> 39 MB, identical results.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… plan

`convertAndFilterSourceStream` rebuilt every alias from the AST of its
inlined expression. That AST qualifies physical columns with the
generated table alias (`__table1.x`) and carries `AS <name>` for every
inlined alias, so the analyzer can bind `__table1.x` to something named
`__table1` instead of the table: with one pass over all aliases, another
alias's `AS __table1` sits in the shared scope, and with one pass per
alias (master) the child's own `__table1` column wins. Through `merge`,
a child with `__table1 Tuple(x UInt64) ALIAS tuple(100)` and
`y UInt64 ALIAS x + 2` returned 102 for `y` instead of 3 (also on
26.3, 26.8 and 26.10).

Resolve the alias names against the child table expression instead, as
`getModifiedQueryInfo` does, and inline their expressions with
`ApplyAliasColumnExpressionsVisitor`: one pass over plain identifiers,
no alias in the list, no AST round trip. `AliasData::expression` is
then unused and removed.

The regression test gains the `__table1` case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed one by one

The wide query of 05872 now runs with max_memory_usage = 150000000. Planning
the 2,500 aliases of the t_alias child one at a time peaks at 511 MB on a debug
build (minimum of 10 randomized runs), so the query fails with
MEMORY_LIMIT_EXCEEDED on such a tree (10/10 runs), while the single pass peaks
at 36 MB (maximum of 50 randomized runs, 4x below the cap). Before, the test
only caught the per-alias planning through its runtime on sanitizer builds.

t_plain is now a Memory table: as a MergeTree table, random settings made it a
Wide part in some runs, and reading its 2,500 column streams alone took up to
391 MB, which hid the planning cost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ad of capping it

05872 now runs the wide query with a fixed query_id and checks its memory_usage in
system.query_log (< 150000000), instead of running it under max_memory_usage = 150000000.
max_memory_usage is not enforced for allocations through operator new, so a tree that plans
the aliases one by one could pass the cap: without random settings the capped query on an
unfixed debug build finished with 510,736,328 bytes logged and no exception. The logged peak
is deterministic: 510-513 MB before the change and 36 MB after, in every run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds)
Finding Verdict
❌ Resolving all alias expressions in one analyzer scope lets an ALIAS column named like the table alias (__table1) capture the other aliases' __table1.x references (102 instead of 3) AGREE: aliases are now resolved by name, as in getModifiedQueryInfo; case added to the test
⚠️ The test cannot fail on an unfixed debug/release/ASan build AGREE: the test now checks the wide query's peak memory (510 MB with per-alias planning, 36 MB now)
⚠️ A max_memory_usage cap does not reliably fail the old planning: operator new allocations are tracked without being refused AGREE: the cap is replaced by a system.query_log memory_usage check, which fails the old planning in randomized and non-randomized runs
💡 The output-assembly block repeats the one in #128634 noted, not blocking: neither is on master yet

Last round: no findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy, could you review this? ReadFromMerge ran a QueryAnalysisPass, an actions visit and an ExpressionStep per ALIAS column of a child, quadratic in their number (merge('system', 'metric_log') reads about 2,500 of them and planned for minutes, ignoring max_execution_time); it now resolves all alias names against the child in one pass and computes them in one step.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Debug server, default config: SELECT * FROM merge(REGEXP('(?i)SYSTEM'), 'metric_log') FORMAT Null SETTINGS max_execution_time = 10 throws TIMEOUT_EXCEEDED after 97.8 s before the change, finishes in 2.6 s after.
b Root cause explained? Yes. all_metric_log (MATERIALIZED) and metric_log (ALIAS) make the ~2,480 metric columns ordinary in merge(), so * reads them all from metric_log as aliases; ReadFromMerge ran a QueryAnalysisPass, an actions visit and an ExpressionStep per alias, all quadratic, inside one child iteration with no time check.
c Fix matches root cause? Yes. One analysis pass, one actions visit and one step for all aliases (the #113140 technique, same file); no cancellation-check workaround.
d Test intent preserved / new tests added? Yes. New 05872_merge_many_alias_columns.sh: 2,500 aliases, an alias chain, and an ALIAS column named __table1 next to y ALIAS x + 2; no existing test changed. The test checks the wide query's peak in system.query_log (memory_usage < 150000000): 36 MB after the change, 511 MB before (t_plain is a Memory table, so the peak does not depend on the randomized part format).
e Both directions demonstrated? Yes. Synthetic child, N = 2000: 14.2 s before, 0.31 s after; the new test's wide query alone takes 236 s on an ASan build before the change. The test fails before in 10/10 randomized and 5/5 non-randomized runs on the peak-memory check, and passes after in 50/50 randomized (max 6.5 s, debug) and 5/5 non-randomized runs. The __table1 case returns y = 102 instead of 3 before (also on 26.3, 26.8, 26.10) and 3 after.
f Fix is general across code paths? Yes. Both per-alias sites in ReadFromMerge changed; the JOIN path was already one pass; the query info cache path goes through the changed code; direct reads are #128634; no other per-alias pass or step loop exists.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. String/Enum16 map keys, alias chains, lambda, String, Array aliases, subcolumns of aliases, IN sets, Distributed, row policy, PREWHERE, JSON/Variant children: same results and headers before and after (562 merge-related stateless tests, identical results on both builds).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; results unchanged except the __table1 case, which now matches a direct read of the child.
i Invariants and contracts preserved? Yes. Columns read, alias list and replacement map keep their contents and order; alias expressions come from resolving the alias names against the child, as getModifiedQueryInfo does, not from a re-analyzed AST; the step's outputs equal one addOrReplaceInOutputs per alias in order; alias columns are matched by name downstream; same LOGICAL_ERROR checks plus resolved-count checks.

Session id: cron:clickhouse-impl-slot-4:20261124-082900

@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8862281]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_msan, targeted) FAIL
test_storage_rabbitmq/test.py::test_rabbitmq_handle_error_mode_stream FAIL cidb

AI Review

Summary

The PR batches analysis and computation of a Merge child's ALIAS columns to remove quadratic planning work, and fixes name resolution when a column overlaps a generated table alias. No actionable findings at 886228104fdc941cf0617ddba8dbaa63ac201012. The description provides before/after timing and memory measurements; the current-head Fast test report confirms 05872_merge_many_alias_columns passes, covering the wide schema, dependent aliases, and name collisions with the compatibility setting enabled. Broader CI is still pending.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-storage-merge Merge table engine (logical union over tables) and related mechanics. labels Nov 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 886228104 with master 13091b141 (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

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.

Object file sizes

3 object files changed (+32.18 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.59 MiB 1.62 MiB +32.17 KiB (+1.98%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

…er_alias_over_subcolumn off

A child's required column names are resolved as identifiers in the scope of
the child's table expression, which carries the generated table alias
(`__table1`). With `analyzer_compatibility_prefer_alias_over_subcolumn = 1`
the analyzer prefers the alias-qualified reading of a multi-part identifier,
so `__table1.x`, a subcolumn of a source table's ALIAS column named
`__table1`, resolved to the column `x` of the table: `getModifiedQueryInfo`
threw the LOGICAL_ERROR "Alias column __table1.x is not resolved" (on master
too), and `convertAndFilterSourceStream` alone would have returned `x`
instead of the subcolumn. The outer query had already resolved the name as
the subcolumn, since its table alias is generated after resolution.

The stress jobs hit it with 05872's capture case and the random setting.
Both resolutions now use a copy of the context with the setting off (only
when it is on); the copy is kept alive by the child plan, since functions
resolved with it may refer to it while the plan runs. 05872 runs the
capture query with the setting as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8862281

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
Integration tests (amd_msan, targeted) / test_storage_rabbitmq/test.py::test_rabbitmq_handle_error_mode_stream not related to this diff: red on master since #133527 (2026-11-23), an idle RabbitMQ cycle drops messages for a newly created materialized view (Time limit of 60 seconds reached without any RabbitMQ consumption); #134110 reverts it #134110 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Mergeable Check and PR are the praktika rollups of the integration row. The CIDB FAIL rows of Stress test (amd_tsan) and Stress test (arm_asan_ubsan) are an OOM the job accepts (OOM error (allowed in stress tests), both jobs green).

Session id: cron:our-pr-ci-monitor:20261124-160028

This branch has not been deployed

No deployments
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-storage-merge Merge table engine (logical union over tables) and related mechanics. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant