Skip to content

Bound the expansion of WITH elements by max_expanded_ast_elements - #122362

Merged
alexey-milovidov merged 22 commits into
masterfrom
bound-with-expansion
Oct 14, 2026
Merged

alexey-milovidov merged 22 commits into
masterfrom
bound-with-expansion

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

The AST fuzzer on master killed the server with the OOM killer (46 GB RSS within a minute) on EXPLAIN AST optimize = 1 over a WITH list of 13 scalar subqueries: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=711f560311e8150e0898a4dad1ef6af19e8cc77a&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29

ApplyWithAliasVisitor copies every element of a WITH list into the subqueries of the elements after it, together with the copies those already carry, so the query doubles with each element. ApplyWithSubqueryVisitor then pastes a common table expression into every place that reads it, so a chain of CTEs each reading the previous one twice doubles as well. Neither visitor had a bound, and neither checks for cancellation, so the query ignored its 10 s timeout. The same happens outside EXPLAIN: CREATE VIEW with a doubling CTE chain exhausts the memory in InterpreterCreateQuery before the analyzer's own "Query tree is too big" check can run.

Both visitors now count the elements they copy and throw TOO_BIG_AST past max_expanded_ast_elements, the limit the analyzer applies to the query tree. The check runs before each copy, so the work stays proportional to the limit. Definitions replayed from metadata stay unbounded (a full ATTACH ... AS SELECT is user input, so it is bounded), so a server never refuses to start over a view it accepted before. On the fuzzer's query and on both new test cases, the release build of master runs out of an 8 GB address-space cap after 12 to 28 s; with this change they fail in 0.3 s with TOO_BIG_AST.

Related: #118756 (an earlier, closed attempt that bounded only ApplyWithAliasVisitor; this query also needs the CTE substitution bounded)

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

A WITH list whose elements refer to the preceding ones, or a chain of common table expressions that read the previous one more than once, now fails with TOO_BIG_AST past max_expanded_ast_elements instead of exhausting the server's memory in EXPLAIN AST optimize = 1, CREATE VIEW, a full ATTACH VIEW ... AS SELECT and ALTER TABLE ... MODIFY QUERY.

🤖 Generated with Claude Code


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

Version info

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

`ApplyWithAliasVisitor` copies every element of a `WITH` list into the
subqueries of the elements after it, together with the copies those carry
already, so the query doubles with each element. `ApplyWithSubqueryVisitor`
then pastes a common table expression into every place that reads it, so a
chain of CTEs each reading the previous one twice doubles as well. Neither had
a bound: the AST fuzzer's `EXPLAIN AST optimize = 1` over 13 scalar
subqueries grew the server to 46 GB RSS within a minute, ignoring the 10 s
timeout, until the OOM killer stopped it. `CREATE VIEW` with a doubling CTE
chain exhausts the memory the same way.

Count the elements both visitors copy and throw `TOO_BIG_AST` past
`max_expanded_ast_elements`, the limit the analyzer applies to the query tree.
Definitions loaded from metadata stay unbounded, so a server never refuses to
start over a view it accepted before.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=711f560311e8150e0898a4dad1ef6af19e8cc77a&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5363321]

Summary: ✅


AI Review

Summary

This PR threads max_expanded_ast_elements through the remaining WITH-expansion paths and adds focused regression coverage for SELECT, view creation and full-definition ATTACH, ALTER TABLE ... MODIFY QUERY, mutation expressions, distributed INSERT ... SELECT, and UNION propagation. I re-read the current diff together with every prior review thread and did not find an outstanding correctness, compatibility, or performance issue in the updated code.

Final Verdict

✅ No new blockers or majors. The previously reported review issues appear addressed in the current code.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 26, 2026
Comment thread src/Databases/DDLDependencyVisitor.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5363321da with master 2279aceb6 (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

23 object files changed (+8.43 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/ExpandedASTBudget.cpp.o new 29.77 KiB +29.77 KiB

719 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

29 translation units recompiled, 245 s compile time in total, 28 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 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: f0603eaa-777a-43ca-8879-8ece57537e28
  • MIRAI run: 1bc96ede-4787-403f-9011-e247abab0b74
  • PR check IDs:
    • clickbench_1176737_1791862042
    • clickbench_1176749_1791862042
    • clickbench_1176755_1791862042
    • tpch_adapted_1_official_1176761_1791862042
    • tpch_adapted_1_official_1176793_1791862042
    • tpch_adapted_1_official_1176807_1791862042

alexey-milovidov and others added 4 commits October 3, 2026 14:37
Resolved the conflict in the `Setting` declarations of `InterpreterInsertQuery.cpp` by keeping both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…xt in `DDLDependencyVisitor`

`checkTableCanBeAddedWithNoCyclicDependencies` expands the query of a materialized view to collect its
dependencies. The limit was read from the global context, so a session override of
`max_expanded_ast_elements` was ignored there. Pass the limit of the current query down instead.

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

With `enable_global_with_statement`, the `WITH` list of the first branch of a `UNION` is cloned into every
other branch, which allocates O(with_list * branches) AST nodes before any limit is checked. Count these
copies with `ExpandedASTBudget` as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the fix, cover new cases

The bugfix validation jobs ran into their 20-minute timeout: a server without the bound never finishes
expanding a chain of 30 elements. Use shorter chains with a lower `max_expanded_ast_elements`, so that the
old server finishes quickly and fails the test (it reports `BAD_ARGUMENTS` or no error instead of
`TOO_BIG_AST`). Also cover the `UNION` propagation and the dependency collection of a materialized view.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122362&sha=873da41dc76a2aa020eb86d6aec484183dbbcc6f&name_0=PR&name_1=Bugfix%20validation%20%28functional%20tests%2C%20amd64%29
#122362

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits October 5, 2026 06:40
…y `max_expanded_ast_elements`

A full user-supplied `ATTACH VIEW ... AS SELECT` runs under `LoadingStrictnessLevel::ATTACH`, so
`mode <= CREATE` left it unbounded. Use `isFreshTableDefinition`, so only replayed metadata stays
unbounded.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failures: they are unrelated to this PR and also fail elsewhere.

Provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/Interpreters/ExpandedASTBudget.cpp Resolved
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Both already have fixes:

mohammedImad10 pushed a commit to mohammedImad10/ClickHouse that referenced this pull request Oct 5, 2026
04401_http_query_parameters_not_leaked_to_logs bounded its six
system.text_log reads only by `event_time >= now() - INTERVAL 600 SECOND`,
so every read scanned the last ten minutes of the whole server's log. On
the parallel `Stateless tests (arm_binary, ParallelReplicas, s3 storage,
parallel)` server that is ~4.7M rows / ~120 MB of `message` per scan, and
with `remote_filesystem_read_method = 'read'`, `enable_filesystem_cache = 0`
and 1 MiB remote read tasks the five `message LIKE` scans took 97-222 s
each, so the test hit the 600 s timeout (ClickHouse#123752, ClickHouse#122362).

Take `toUnixTimestamp(now())` before the first request and bound all six
reads with `event_time >= toDateTime(test_start)`, as ClickHouse#123652 did for
05061. Every asserted line is logged after that point, so the reference
is unchanged; text_log is ordered by (event_date, event_time), so the
bound prunes the read to the test's own granules. Locally, with 681K rows
in the ten-minute window, a scan reads 381 rows instead of 681,982.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…st `max_expanded_ast_elements`

`ExpandedASTBudget` counted only the subtrees copied within one pass, and every pass
created its own budget, so `max_expanded_ast_elements` acted as a per-pass delta: a
large query could still receive a full limit of copies, and the alias propagation and
the common table expression substitution could each spend the whole limit.

The budget now also charges the query being expanded, on its first copy, so the limit
bounds the size of the whole expanded query. A pass that copies nothing does not walk
the query at all.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 7, 2026 07:37
…he fragments of a query

`InterpreterUpdateQuery` expands the predicate and the assignments in separate calls, and
`InterpreterAlterQuery` does the same for `MODIFY QUERY` and every mutation expression. Each call
had its own `ExpandedASTBudget`, so splitting a doubling `WITH` chain across sibling fragments let
one query grow past the limit. Now one budget, rooted at the whole query, is threaded through all
of these calls.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122362&sha=5e1f5a70f6816d5d397a77706d2e8f4316cc8e02&name_0=PR (Fast test (arm_darwin): 03312_squashing_with_low_card_mem_usage and 03826_calculate_subcolumn_size_during_merge_tree_read fail with NOT_ENOUGH_SPACE on the macOS runner, unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here. Possibly related: #113605

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

This job ran on ip-10-0-18-223: 96% used (4.1G free) at start, 98% at the end. It is the same pattern as ip-10-0-28-9 in #122086 (comment), on a second host: it grew in every job sample since 2026-09-28 (41G used then) and never dropped back to the ~43G post-reboot level, although #121990 gives macOS runners a 3-day lifetime.

The fix is #113605: it runs the free-space check before every job on macOS too, so a host this full refuses the job and reboots instead of taking it. It is waiting for review and deploy by @ leshikus. #124316 is the diagnostic that prints what fills the disk on such a host.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/122362/0ca1a4051cf860aa7dfef2f0016e68efe859ead5/pr/ast_fuzzer_amd_release_oracle/job.log (AST fuzzer (amd_release, oracle): Subquery wrap oracle mismatch on a SELECT DISTINCT with two concat of AggregateFunction(uniqTheta, String) constants under one duplicate alias res, with no WITH in the query, so it is unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here. The Stateless tests (arm_asan_ubsan, azure, sequential) failure is the job timeout, with no failed test; #123849 addresses it.

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. This is a real wrong result, not an oracle false positive, and it does not need remote(): two different AggregateFunction constants compare as equal in the query tree (ConstantNode::isEqualImpl uses IColumn::compareAt, and ColumnAggregateFunction::compareAt always returns 0), so the duplicate alias check accepts two different expressions under one alias.

SELECT * FROM (SELECT concat(initializeAggregation('groupArrayState', 'x'), toString(number)) AS r, concat(initializeAggregation('groupArrayState', 'y'), toString(number)) AS r FROM numbers(2))

returns x0 x0 / x1 x1 instead of x0 y0 / x1 y1, on master and on 26.3.42.3. With String constants the same query gets MULTIPLE_EXPRESSIONS_FOR_ALIAS. I found no open PR for it; I'll follow up here with a separate PR.

… is attached

`ExpandedASTBudget::replace` refunds the elements of the node being replaced,
assuming they belong to the counted query. The table-position substitution in
`ApplyWithSubqueryVisitor` detached `database_and_table_name` before calling it,
so when that call was the first one, the root was counted without the table name
and the table name was then refunded a second time, undercounting the expanded
AST. Call `replace` before detaching the table name.

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

Copy link
Copy Markdown
Member Author

🕵 The Build (arm_fuzzers) failure on b0f2bbc is unrelated to this PR: serialization_dynamic_fuzzer.cpp uses DeserializeBinaryBulkSettings::object_and_dynamic_read_statistics, which does not exist on master either (https://s3.amazonaws.com/clickhouse-test-reports/PRs/122362/b0f2bbc17d93e7ea9443cc6839643d24eeb2f515/pr/build_arm_fuzzers/build_clickhouse/build_clickhouse.log). It is fixed by the open #124798. The review comment about the FROM cte refund is addressed in 2762e10.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

The fix is in #124867: the analyzer constant comparison (ConstantNode::isEqualImpl) and the ActionsDAG constant deduplication now also compare the nested AggregateFunction type names and the states, so the fuzzer's query fails with MULTIPLE_EXPRESSIONS_FOR_ALIAS, as with String constants. The same root cause also made a valid filter over a quantileState(0.9) constant return no rows on 26.8 (the planner reused the quantileState(0.5) constant). That case is covered too.

alexey-milovidov and others added 2 commits October 10, 2026 01:27
# Conflicts:
#	src/Interpreters/InterpreterCreateQuery.cpp
…Visitor`

When a `SELECT` has no `WITH` clause, `ApplyWithAliasVisitor` creates a new
`ASTExpressionList` for the propagated aliases. That node is part of the
expanded query too, so it is now charged against `max_expanded_ast_elements`
together with the copies it holds.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master to resolve the conflict in InterpreterCreateQuery.cpp (two adjacent extern setting declarations; kept both). The Build (arm_tidy, 2/4) failure (FifoQueue undeclared in gtest_throttler_constraint.cpp) is unrelated and was fixed on master by be9cfb1, which this merge brings in. The bugfix-validation jobs were dropped because of that build failure.

Comment thread src/Interpreters/ExpandedASTBudget.h Resolved
alexey-milovidov and others added 2 commits October 10, 2026 20:25
… `WITH` expansion

The setting now also limits the substitution of `WITH` elements in views,
`ATTACH`, `MODIFY QUERY`, mutations, distributed `INSERT ... SELECT` and
`UNION` propagation, so mention it in the setting description (the docs
page is generated from it).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 11, 2026 18:33
… `Replicated` database

A follower replica executes a `CREATE VIEW` under `SECONDARY_CREATE`, so
`isFreshTableDefinition` returned false there and the expansion of `WITH`
elements was not bounded by `max_expanded_ast_elements`. For an ordinary view
there is no earlier bounded pass on that replica, so a doubling CTE chain could
still exhaust the memory of every follower. Keep the exemption only for a
restore from a backup and for the recovery from stored metadata.

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.

Very good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 13, 2026
Merged via the queue into master with commit 89877c1 Oct 14, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the bound-with-expansion branch October 14, 2026 00:26
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 13, 2026
…nt-subquery-loading-dependency"

This reverts commit 659cc1c, reversing
changes made to f75df10.

Conflicts resolved by removing only what ClickHouse#114923 added: the narrow
qualification pass in AddDefaultDatabaseVisitor.h is removed together with
the parts ClickHouse#114908 later added inside it; InterpreterCreateQuery.cpp keeps
the expansion bound of ClickHouse#122362 on the neighbouring call; the string overload
of qualifyDictionaryNameWithDatabase in ExternalDictionariesLoader is kept,
because the dictionary usage record of ClickHouse#121567 is built on it.
04908_constraint_subquery_loading_dependency.sh (edited by ClickHouse#124408) is
deleted with the rest of the test.

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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default 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