Skip to content

Bound the expansion of WITH alias propagation - #118756

Closed
nickitat wants to merge 9 commits into
masterfrom
bound-with-alias-propagation
Closed

nickitat wants to merge 9 commits into
masterfrom
bound-with-alias-propagation

Conversation

@nickitat

@nickitat nickitat commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

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):

Old-analyzer queries with enable_global_with_statement=1 now fail with TOO_BIG_AST instead of exhausting memory when recursive WITH alias propagation expands the AST.


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

With the old analyzer, `ApplyWithAliasVisitor` makes an outer `WITH` alias visible
to a nested subquery by cloning the alias into that subquery's own `WITH` list, and
then recurses with the alias still in scope. An alias whose subquery contains a
further `SELECT` is therefore expanded again at every level, so `k` such aliases
nested `d` levels deep produce `k ^ d` nodes. Only `checkStackSize` guarded this;
nothing bounded the size.

`EXPLAIN` supplies the extra `SELECT` level, which is what makes the growth
compound - `(SELECT count() FROM numbers(10))` repeated three times is harmless
because a table function has no nested `SELECT`, while
`(SELECT count() FROM (EXPLAIN PLAN SELECT 1))` repeated three times took the
server from 379 MiB to 60 GB in a minute and then off the machine.

Bound the expansion the way `QueryNormalizer` already bounds alias substitution:
check `max_expanded_ast_elements` before cloning an alias, so an alias that has
already grown is never materialised again, and once more after injecting into a
select. The pathological query now fails with `TOO_BIG_AST` in well under a second
instead of exhausting memory; queries below the limit are unaffected.

This is old-analyzer only: all three callers sit behind
`enable_global_with_statement` in the old interpreters, and the new analyzer does
not clone aliases per subquery.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b42a7e2]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
05078_with_alias_propagation_ast_size FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 8, 2026
Style check: the analyzer has been the default since 24.3, so `new analyzer` is
rejected in favour of `the analyzer`. Reword the comment and the label the test
prints, and update the reference to match.

Verified the check's own pattern no longer matches any file this branch touches,
and that the test still passes 15 runs with settings randomization and 10 without.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 8, 2026
The earlier message blamed `EXPLAIN` for supplying an extra `SELECT` level. That is
wrong. Plain nesting does not compound at all: `(SELECT count() FROM (SELECT 1))`
repeated eight times is fine, at any depth tried. What the exploding shapes have in
common is that the aliased subquery is *interpreted as a fresh query* - `view()`
compounds exactly like `EXPLAIN PLAN`, `EXPLAIN SYNTAX` and `EXPLAIN PIPELINE`,
while `EXPLAIN AST`, which only prints the parsed tree and interprets nothing, does
not. So this was never specific to `EXPLAIN`.

Reword the comment accordingly and cover both ends in the test: `view()` must be
rejected the same way, and `EXPLAIN AST` must keep working.

The bound is unchanged - it is a limit on the result, not on the cause. Stopping the
expansion itself would be the better fix, and the analyzer avoids the problem by
resolving aliases through scopes instead of cloning them into every subquery. An
attempt to stop the re-application by interpreting a view's inner query as a
subquery did not work: the expansion survives it, so the site that re-applies the
propagation is elsewhere and still unidentified.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
Review finding: the per-select checks bound each subtree at the moment it is
expanded, but a select is checked before its own descendants are expanded, and the
nodes injected into those descendants are never counted against the root. The
setting is documented as the maximum size of the query syntax tree *after* expansion
of aliases, so nothing was enforcing what it promises: sibling subqueries can each
stay under the limit while the tree they belong to ends up over it.

Check the result once in the public entry point, after propagation returns. The
per-clone checks stay: they stop an already-grown alias from being materialised
again, which is what keeps the expansion from running away in the first place, and
they fail before the memory is spent rather than after.

The wrapper moves to the .cpp because the header only forward-declares `IAST`.

Honest note on the evidence: I could not construct a query whose outcome this
changes. Probing the boundary with `k` sibling aliases gives the same answer with
and without it - succeed up to `k = 9`, `TOO_BIG_AST` from `k = 10` - because in
every shape tried a per-select check trips first. It is kept because it costs one
walk of the finished tree and makes the bound mean what the setting documents, not
because a case for it was demonstrated.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
Comment thread src/Storages/StorageDistributed.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 8, 2026
Review finding: the parallel distributed INSERT ... SELECT fast paths read the bound
from the outer context, but they run before the source SELECT's interpreter applies
its `SETTINGS`. The parser's push-down onto the INSERT does not close the gap: it
merges only `ASTSetQuery::changes`, so `DEFAULT` resets in `default_settings` are
dropped, and it deliberately does not overwrite a setting the INSERT already carries.

Reproduced end to end against a `Distributed` table over a `ReplicatedMergeTree`:

    INSERT INTO d SETTINGS parallel_distributed_insert_select = 2,
                           max_expanded_ast_elements = 200
    WITH ... SELECT ... SETTINGS max_expanded_ast_elements = 100000000000

is rejected with `TOO_BIG_AST. Maximum: 200` although the source asked for a larger
bound, which the ordinary path honours.

Resolve both settings this path depends on from a context that has the source
SELECT's own `SETTINGS` applied, the way `InterpreterSelectQuery::initSettings` does.
Note this also changes how `enable_global_with_statement` is resolved here: it was
read from the same stale context before this branch touched these lines, so the two
now agree with the ordinary path instead of only one of them.

The test asserts only that the INSERT is accepted. Reading the rows back raced with
the distributed insert becoming visible and failed 3 of 15 runs under settings
randomization, and the row count is not what this is about.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
Comment thread src/Storages/StorageDistributed.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b42a7e26a with master b75d29e7d (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

12 object files changed (+34.74 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Planner/Utils.cpp.o 278.30 KiB 306.51 KiB +28.21 KiB (+10.14%)

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

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

Job report

nickitat and others added 2 commits September 8, 2026 16:44
Both parallel distributed `INSERT ... SELECT` fast paths now build a
`select_context` with the source SELECT's own `SETTINGS` applied, but they
went on to construct `JoinedTables` from the untouched outer context. One
helper therefore resolved one half of the same source SELECT under fresh
settings and the other half under stale ones. `getLeftTableStorage` can
interpret a table-function source - `view` re-enters the old interpreter
through `TableFunctionView::getActualTableStructure` - so it must not read
settings the source SELECT has overridden.

This is a consistency fix, not a behaviour fix. Sweeping
`max_expanded_ast_elements` from 3 to 50 over

  INSERT INTO <replicated> SETTINGS parallel_distributed_insert_select = 1,
    max_expanded_ast_elements = X
  SELECT * FROM view(...) SETTINGS max_expanded_ast_elements = 100000

gives identical thresholds with the fast path on and off, because on the
ordinary path the source's table function is already resolved under the
INSERT's context as well. No reachable divergence was found; the point is
that the two lines of the same helper no longer disagree about which
context describes the source.

`InterpreterSelectQuery` uses `getSubqueryContext` here, but that helper is
file-local, and it also zeroes `max_result_rows`/`max_result_bytes`, clears
`implicit_table_at_top_level` and disables `extremes` - semantics these
paths have never had.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
Passing `select_context` instead of `local_context` cannot affect how a
table-function source is resolved. `JoinedTables::getLeftTableStorage`
executes one through `context->getQueryContext()`, and the `Context` copy
constructor carries the parent's `query_context` over unchanged, so the
copy resolves table functions exactly where its parent did. Nothing on
this path calls `makeQueryContext`. The remaining branches of
`getLeftTableStorage` - `resolveStorageID` and `getViewSource` - read no
settings, and `tablesCount` reads none either, so the previous commit
changed nothing while claiming in a comment that it did.

This is also what the earlier measurement was showing: sweeping
`max_expanded_ast_elements` over a `view()` source gave identical
thresholds with the fast path on and off, because both resolve the table
function under the query context, and for an `INSERT ... SELECT` the query
context holds the INSERT's settings - `InterpreterSetQuery::applySettingsFromQuery`
applies only `ASTInsertQuery::settings_ast` and does not descend into the
source SELECT.

Making the source's settings visible there would mean giving the copy its
own query context, which is a different behaviour from the ordinary path,
not a closer match to it, and it would drop the `table_function_results`
cache entry that the real execution reuses. Left as is, with a comment so
the next reader does not repeat the attempt.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
Comment thread src/Storages/StorageDistributed.cpp Resolved
The two parallel distributed `INSERT ... SELECT` fast paths run the old
interpreter's `ApplyWithAliasVisitor` whenever `enable_global_with_statement`
is set, whatever the analyzer setting is. That is how it has always been,
but bounding that call made the fast path reject queries every other path
accepts:

  INSERT INTO <distributed> SETTINGS parallel_distributed_insert_select = 2,
    enable_analyzer = 1, max_expanded_ast_elements = 100
  WITH (SELECT count() FROM (SELECT 1)) AS e1, ... AS e2, ... AS e3
  SELECT e1 + e2 + e3

  fast path OFF, analyzer = 1   accepted
  fast path ON,  analyzer = 1   TOO_BIG_AST     <- introduced by the bound
  plain SELECT,  analyzer = 1   accepted

The compounding the bound guards against comes from `InterpreterSelectQuery`
re-running the propagation over an AST that already carries the injected
aliases. The analyzer never does that, so on that path the visitor makes a
single linear pass: a bound there can only produce false positives, never
catch a blowup. Pass no bound when the analyzer is on, which restores the
previous behaviour exactly and leaves the bound where the blowup exists.

Gating the visitor itself on the analyzer, rather than just the bound, would
stop propagating aliases into the AST that the distributed write then ships -
a behaviour change on the default path, and not what this change is about.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Sep 8, 2026
@nickitat
nickitat marked this pull request as ready for review September 9, 2026 16:47
@nickitat
nickitat requested a review from Algunenano September 9, 2026 16:48
@nickitat

Copy link
Copy Markdown
Member Author

Bugfix won't succeed, because it constantly dies trying to run the problematic query on the master version:

2026-09-14T12:38:40.9842645Z [2026-09-14 12:38:40] [ 3946.393364] 
2026-09-14T12:38:40.9843455Z                       oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/docker/761c9521b7c0bfb8e72596751865500d01e9dd39852991b89b69d6c6143d6f79,task=clickhouse-serv,pid=3362,uid=0
2026-09-14T12:38:40.9844536Z [2026-09-14 12:38:40] [ 3946.394196] Out of memory: Killed process 3362 (clickhouse-serv) total-vm:38685664556kB, anon-rss:61829360kB, file-rss:252kB, 
2026-09-14T12:38:40.9845174Z                       shmem-rss:0kB, UID:0 pgtables:151524kB oom_score_adj:0
2026-09-14T12:38:40.9845700Z [2026-09-14 12:38:40] [ 3950.638445] oom_reaper: reaped process 3362 (clickhouse-serv), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

@Algunenano Algunenano self-assigned this Sep 15, 2026
nickitat added a commit that referenced this pull request Sep 15, 2026
Bugfix validation runs the PR's new test against the master-HEAD binary, which
by construction still has the bug. When the bug is unbounded memory growth, that
run is a runaway by design - and the loop that swaps build types dropped the cap
for the one non-sanitizer type, reverting to the default
`max_server_memory_usage_to_ram_ratio`. The install stage already documents what
that costs: the host OOM-kills the server before any query reaches
`MEMORY_LIMIT_EXCEEDED`, and the runner dies with it.

The job then reports `ERROR`, which `new_tests_check.py` counts as no signal, so
such a fix can never be validated however its test is written. This is not
specific to one PR: any fix for memory exhaustion hits it.

Cap every build type here instead. The server refuses the allocation, the test
fails cleanly, and `invert_bugfix_validation_status` reads that failure as the
reproduction it is. `reset_memory_ratio` existed only for the branch removed
here and is dropped with it.

Seen on https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118756&sha=latest&name_0=PR
for #118756, where both per-arch
jobs ran ~20 minutes and returned `ERROR` with no test rows.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 15, 2026
@nickitat
nickitat force-pushed the bound-with-alias-propagation branch from ea3867b to b42a7e2 Compare September 15, 2026 13:18
@nickitat
nickitat enabled auto-merge September 15, 2026 13:23
@nickitat nickitat closed this Sep 15, 2026
auto-merge was automatically disabled September 15, 2026 14:37

Pull request was closed

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants