Skip to content

Resolve ALIAS columns lazily in the analyzer - #123926

Merged
alexey-milovidov merged 4 commits into
masterfrom
analyzer-lazy-alias-column-resolution
Oct 9, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
analyzer-lazy-alias-column-resolution

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Since the bucketed schema of system.metric_log became the default, every query over metric_log became several times slower. The test 03540_system_dashboards went from about 110 seconds to 300-600 seconds and began to time out in Stateless tests (amd_tsan, s3 storage, sequential, 1/2): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=3ead9595c864fca894685b3d6290c45187fd4332&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20sequential%2C%201%2F2%29

There were two reasons:

  • The analyzer built and resolved the expressions of all ALIAS columns of a table (about 2000 for metric_log) on the first lookup of any column. Now the expression of an ALIAS column is built and resolved only when this column is used (AnalysisTableExpressionData::tryGetColumnNode).
  • The serialization of Enum hashed all values of the Enum on every request, and the Enum16 key of the metrics map has thousands of values, requested per part and per block while reading. Now the hash is calculated once in the constructor of DataTypeEnum.

Locally, a query reading one metric from system.metric_log takes 8 ms instead of 91 ms (the same as with the wide schema), and all queries of system.dashboards take 21.8 s instead of 53 s (16.4 s with the wide schema).

Related: #118318

Changelog category (leave one):

  • Performance Improvement

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

Faster analysis of queries to tables with many ALIAS columns, such as system.metric_log: the expression of an ALIAS column is analyzed only if the query uses this column.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1905-master (included in 26.10 and later)

The analyzer built and resolved the expressions of all `ALIAS` columns of a
table on the first lookup of any column. Since the `bucketed` schema of
`system.metric_log` became the default (it has about 2000 `ALIAS` columns),
every query over `metric_log` spent most of its time in the analysis, and
`03540_system_dashboards` began to time out.

Now the expression of an `ALIAS` column is built and resolved on the first
request of this column (`AnalysisTableExpressionData::tryGetColumnNode`).

Also calculate the hash of the serialization of `Enum` once, in the
constructor of `DataTypeEnum`, instead of on every request of the
serialization. The `Enum16` key of the `metrics` map in `metric_log` has
thousands of values, and the serialization is requested per part and per
block while reading.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=3ead9595c864fca894685b3d6290c45187fd4332&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20sequential%2C%201%2F2%29

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

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c9d8b9f]

Summary: ✅


AI Review

Summary

This PR defers analysis of table ALIAS expressions until a query actually uses the column, adds the matcher fast-path so EXCEPT and REPLACE do not force discarded ALIAS columns to resolve, and caches the Enum serialization hash per DataTypeEnum instance. I reviewed the current diff, the prior inline discussion, and the updated tests; the remaining code paths that still read getColumnNodeMap only depend on names and types, the matcher fix addresses the earlier EXCEPT/REPLACE hole, and the PR body includes concrete before/after measurements for the claimed speedup. I did not find an unresolved contract violation or a new high-impact risk in the current state of the PR.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit c9d8b9f.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 95/99 (95.96%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 864e80ab-af33-426b-bbea-8cc6b7dfe473
  • MIRAI run: 7dd057b7-eb40-4cf5-89dd-f1e88e6299ff
  • PR check IDs:
    • clickbench_60298_1791314471
    • clickbench_60312_1791314470
    • clickbench_60318_1791314472
    • tpch_adapted_1_official_60324_1791314471
    • tpch_adapted_1_official_60335_1791314471
    • tpch_adapted_1_official_60370_1791314471

alexey-milovidov and others added 2 commits October 5, 2026 22:57
…esolution

The analyzer now resolves the expression of an `ALIAS` column only when the
query uses this column, so a query over `t_alias` that does not read the
dictionary alias no longer falls back to local execution; it distributes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123926&sha=dd088d1afb6b33972a58670e59722cb1269c9ed7&name_0=PR&name_1=Integration%20tests%20%28amd_llvm_coverage%2C%202%2F8%29
PR: #123926

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c9d8b9fe3 with master d91a05305 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of eb03aea3a; 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

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

Job report

…or `REPLACE`

`getMatchedColumnNodesWithNames` resolved every matched column, so
`SELECT * EXCEPT (alias_column)` or `SELECT * REPLACE (1 AS alias_column)`
still analyzed the expression of the ALIAS column, although the projection
discards or substitutes it. Now a column that `resolveMatcher` will remove by
`EXCEPT` or substitute by `REPLACE` (with no `APPLY` before them) gets a plain
`ColumnNode` instead of `AnalysisTableExpressionData::tryGetColumnNode`.

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit 7b2c484 Oct 9, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the analyzer-lazy-alias-column-resolution branch October 9, 2026 04:12
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
alexey-milovidov added a commit to niyue/ClickHouse that referenced this pull request Oct 9, 2026
Resolve the conflict in `QueryAnalyzer::initializeTableExpressionData`:
master (ClickHouse#123926) builds `ALIAS` column expressions lazily in the
`alias_column_resolver`, so the column matcher expansion and the late cycle
check of this PR moved there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
ClickHouse#123926 resolves the expression of each ALIAS column lazily, in its own
scope, on the first lookup of that column, so a later-declared ALIAS
column is no longer resolved in the scope of the column that reads it.
That fixes the wrong values this PR was fixing, and the source change of
this PR is dropped in favor of the master version. The test still covers
the case: it fails on master with the `src/Analyzer` part of ClickHouse#123926
reverted and passes on master.

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

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 31, 2026
…projection alias

With analyzer_compatibility_join_using_top_level_identifier = 1,
try_resolve_identifier_from_query_projection copies the
AnalysisTableExpressionData of the left table expression. When the column
map already exists (an earlier USING key such as `id` built it), the copy
shares the ColumnNodes but owns a separate unresolved_alias_columns set.
The ALIAS column is then resolved through the copy, and resolved again
through the original: the second call replaces the resolved expression
with a fresh unresolved one, and getResultType() throws
"Function node with name 'multiply' is not resolved" (UNSUPPORTED_METHOD).

The populator creates ALIAS column nodes without an expression and the
resolver is the only code that sets one, so resolve only nodes that have
no expression yet. The per-object set still decides whether this object
has requested the column.

Regression from ClickHouse#123926; master only.

Closes ClickHouse#124842

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim pushed a commit to ylw510/ClickHouse that referenced this pull request Nov 6, 2026
…expression is resolved

An ALIAS column whose expression reads the column itself through a
subcolumn, e.g. `c0 Nullable(IPv6) ALIAS c0.null`, made a SELECT of it run
until the server was killed. On 26.10 such a column is accepted by CREATE
and ALTER; older releases reach it through ATTACH and table function
structures (format, remote). It was found by La Casa Del Dolor on master:
a read through clusterAllReplicas of a refreshable materialized view with
such a column OOM-killed the server.

ALIAS expressions are resolved lazily (ClickHouse#123926): tryGetColumnNode erases
the column from unresolved_alias_columns and calls the resolver, which
sets the node's expression and resolves it against the same table data.
Resolving `c0.null` calls tryGetSubcolumnInfo -> tryGetColumnNode("c0"),
which no longer finds the column unresolved and returns the node that is
being resolved; wrapExpressionNodeInSubcolumn then makes
getSubcolumn(<c0 node>, 'null') part of that node's own expression. The
query tree is cyclic, and validateTreeSize, an iterative DFS that
memoizes a node only after its children, grows its stack without bound.
Analysis is not cancellable, so max_execution_time, max_memory_usage,
max_server_memory_usage and KILL QUERY do not stop it. A direct cycle
(`c0 ALIAS c0`) overflows the stack in a recursive walker instead
(TOO_DEEP_RECURSION).

The resolver now pushes the column name to
AnalysisTableExpressionData::alias_columns_in_resolution before building
the expression and pops it on scope exit, and tryGetColumnNode throws
CYCLIC_ALIASES with the chain when a requested column is in that list.
The resolver captures the original data, which is also the alias
resolution data of every re-entrant lookup, so the check also works when
a copy of the data started the resolution (the JOIN USING projection
alias path); that is why it precedes the unresolved_alias_columns branch.
Every cycle (through subcolumns, other ALIAS columns, functions) comes
back through this lookup, so tables, Merge, remote/cluster*, format,
materialized views and stored definitions are all covered.

The definition-time check for such columns is ClickHouse#124850.

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

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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.

3 participants