Skip to content

Do not merge a filter with the expressions below it when its condition would exceed max_expanded_ast_elements - #134010

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:filter-merge-expanded-size-limit-123724-a
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:filter-merge-expanded-size-limit-123724-a

Conversation

@groeneai

@groeneai groeneai commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123724

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

Fixed an out-of-memory kill while planning a query whose nested subqueries reuse a column more than once per level, e.g. 36 nested levels of SELECT a + a AS b FROM (...) under a WHERE. Query plan optimizations no longer merge a filter with the expressions below it, and do not use it for index or projection analysis, when its condition would then exceed max_expanded_ast_elements.

Description

Option A of the three alternatives requested in #123724 (comment). Found by Stress test (amd_msan): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100173&sha=b00d774e18fa8a5be47f1f2c8fcc26290d8fc13a&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

On 26.10.2.103, SELECT count() FROM (<36 nested SELECT a + a>) WHERE a36 <= 0 is killed by the OOM killer during planning.

Each nested scope passes max_expanded_ast_elements, but merging the levels into the filter builds a 2^38-node condition, and filter push-down, index analysis and projection analysis walk it once per path; a 12 GiB max_server_memory_usage does not stop them.

A memoized getExpandedTreeSize (on visitNodesPostOrder) gates the four places that build a filter condition from the steps below it: tryMergeExpressions (Filter + Expression), tryMergeFilters, compose in optimizePrimaryKeyConditionAndLimit, and QueryDAG::build for projections.

Master vs this PR (debug, 12 GiB cap):

Query (depth 36) master PR
WHERE over numbers() OOM-killed 0.9 s
same, query_plan_merge_expressions = 0 MEMORY_LIMIT_EXCEEDED 0.8 s
over MergeTree, plain / PARTITION BY (minmax_count projection) OOM-killed 0.2 / 0.3 s
non-equi JOIN ON conjunct over the chain OOM-killed 1.0 s
the 05317 query and the fuzzed one from the report OOM-killed 0.4 - 0.8 s
implied indexHint from HAVING, pushed below GROUP BY MEMORY_LIMIT_EXCEEDED 0.2 s

JOIN filters and runtime filters reach the chain through the same Filter + Expression merge, so they stay above it. The JOIN-side compositions themselves (fix_predicate_for_join_logical_step, join graph absorption) and the read-side conjunction in applyFilters are unchanged.

Price: below the limit plans are unchanged (1192 related stateless tests match master; planning a 300-level nested WHERE takes the same time). Above it the filter stays put: no push-down, index analysis or PREWHERE for it (its small conjuncts included), no index analysis or LIMIT push-down above it, and no projection for the query.


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

groeneai and others added 3 commits November 24, 2026 00:05
…n would exceed max_expanded_ast_elements

A column that each nested subquery level builds as `x + x` from the level
below has a linear DAG but 2^depth paths. Each scope is small, so the
analyzer's `max_expanded_ast_elements` never fires, but the first plan
pass merges the levels into the filter that reads the column, and the
condition then expands to 2^(depth + 2) + 1 nodes. Filter push-down over
JOIN (`splitActionsForJOINFilterPushDown`), index analysis
(`buildFilterActionsDAG` in `applyFilters`, `cloneDAGWithInversionPushDown`)
and projection analysis (`resolveMatchedInputs`) walk it once per path,
so at depth 36 planning allocates past `max_server_memory_usage` and the
process is OOM-killed (master and 26.10.2.103; also hit by the stress
fuzzer on a 05317 variant).

Option A of the three alternatives requested in ClickHouse#123724: the places that
build a filter condition from the steps below it refuse to do so when the
result would expand beyond `max_expanded_ast_elements`:
- `tryMergeExpressions` (Filter + Expression) and `tryMergeFilters` keep
  the steps separate;
- `optimizePrimaryKeyConditionAndLimit` does not add such a composed filter
  for index analysis (the FilterStep still runs);
- `QueryDAG::build` does not build the projection DAG, so no projection is
  used for the query.
The size is computed by a memoized post-order walk
(`getExpandedTreeSize[AfterMerge]` on `visitNodesPostOrder`); the
after-merge variant binds the inputs of the second DAG to the outputs of
the first exactly as `ActionsDAG::mergeInplace` does, so nothing is merged
to measure. A limit of 0 means no limit, which keeps the default-constructed
`ExtraSettings{}` used by lazy materialization unchanged.

Below the limit plans are unchanged. The JOIN-side compositions and the
read-side conjunction of filters that were each bounded are left as they
are; the measured JOIN shapes are fixed because their join filters reach
the chain through the same Filter + Expression merge.

Related: ClickHouse#123724

Co-Authored-By: Claude Opus 5.5 <[email protected]>
05872 observed only the Filter + Expression merge check. It now also
covers, at depth 18:
- two stacked filters (`query_plan_split_filter = 0`) stay separate when
  their merged condition would exceed the limit;
- index analysis on a MergeTree table gets no condition for such a filter
  (`Condition: true` instead of `(val in [0, 0])`);
- projection analysis does not use the aggregate projection for it.
Each of these fails when its check alone is removed; all fail on master.
`query_plan_merge_filters` is pinned to 1 on the stacked-filter query,
since with 0 the filters are not merged with or without the check.

Also reword the doc line of `getExpandedTreeSize`: it counts DAG nodes,
not the analyzer's query tree nodes.

Related: ClickHouse#123724

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ze limit in the projection reject reason

With parallel replicas the initiator's plan nests the local MergeTree read
under the parallel-replicas step, or (with `parallel_replicas_local_plan = 0`)
has no local read at all, so the primary key condition and the projection
choice that the two MergeTree EXPLAINs inspect are not there. This happens
with query-based and plan-based parallel replicas alike, so both statements
set `enable_parallel_replicas = 0`.

`QueryDAG::build` now also fails when the filter condition exceeds
`max_expanded_ast_elements`, so the reject reason reported for the projection
(visible in `PROJECTION_NOT_USED` under `force_optimize_projection = 1`)
names that case too.

Related: ClickHouse#123724

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 rounds, 4 findings), plus my own review (3 nits, 1 major).

# Sev Finding Verdict Evidence / action
1 ❌ Several filters, each under the limit, are still ANDed for index and projection analysis, so the analyzed condition can exceed max_expanded_ast_elements DISAGREE The AND of k bounded filters is at most k times the limit, linear in the query; the OOM needs exponential expansion (2^38 nodes at depth 36). Measured with this PR: two filters of 262,145 nodes each, ANDed to 524,291, take 219-280 ms and 145 MiB (master 226-266 ms, 141 MiB). The setting bounds each filter's condition, as the analyzer bounds each expression.
2 ⚠️ The test only covers the Filter + Expression merge, not the index and projection analysis checks AGREE, fixed @ 8ca80e5 Cases added for tryMergeFilters, index analysis and projection analysis; each fails with its check removed.
3 💡 Header comment says the size is "as counted for max_expanded_ast_elements"; the analyzer also counts argument lists AGREE, fixed @ 8ca80e5 Comment reworded.
4 ⚠️ The new MergeTree EXPLAIN cases change under parallel replicas AGREE, fixed @ cf5e942 enable_parallel_replicas = 0 on those two statements: they fail with query-based parallel replicas too, not only plan-based.
5 💡 A filter over the limit is reported as "the steps ... cannot be rewritten onto a projection" AGREE, fixed @ cf5e942 The reason now also names max_expanded_ast_elements.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261124-014700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ, could you review this? Option A for issue 123724: query plan optimizations skip merging a filter with the expressions below it, and skip it for index and projection analysis, when its condition would exceed max_expanded_ast_elements.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 36 nested SELECT a + a levels under a WHERE: OOM-killed during planning on master and on 26.10.2.103 every run (planning only, no randomness). The new test's depth-18 EXPLAIN differs on master every run.
b Root cause explained? Each nested scope passes max_expanded_ast_elements; merging the levels into the filter (tryMergeExpressions) builds a condition that expands to 2^38 nodes, and push-down over JOIN, buildFilterActionsDAG in applyFilters, KeyCondition and projection analysis walk it once per path.
c Fix matches root cause? Yes. The oversized condition is no longer built (tryMergeExpressions, tryMergeFilters) or analyzed (optimizePrimaryKeyConditionAndLimit, QueryDAG::build). No bound widened, no tag.
d Test intent preserved / new tests added? New SQL test 05872_filter_merge_expanded_size_limit: plain EXPLAIN step names at depth 18 (kept) and 12 (merged), the query result, a max_expanded_ast_elements = 1000 case, two stacked filters, and on a MergeTree table the primary key condition and the projection choice at depth 18 (those two pin enable_parallel_replicas = 0: with parallel replicas the plan has no local read to inspect).
e Both directions demonstrated? Test fails on master and passes here (50/50 with random settings); removing any one of the four checks makes it fail. Depth-36 queries: master OOM-killed or MEMORY_LIMIT_EXCEEDED, this PR 0.2-1.0 s.
f Fix is general across code paths? All four places that compose a filter with the steps below it are gated. JOIN-side compositions and the read-side conjunction of already bounded filters are unchanged; the measured JOIN shapes are fixed anyway. Removing the projection check makes the partitioned MergeTree shape hang again.
g Fix generalizes across inputs (params/datatypes/wrappers)? The size is counted on DAG nodes, independent of types. Checked: numbers(), MergeTree, partitioned MergeTree (minmax_count projection), JOINs with join_use_nulls 0/1 and runtime filters on/off, the threshold between depth 16 and 17, the setting at 1000 and 10^12.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change; plans below the limit are unchanged (1192 related stateless tests give the same results as master).
i Invariants and contracts preserved? Each check runs before any mutation and returns "not merged" / "not used", which every caller already handles. A filter skipped for index analysis still runs, so results do not change. Sizes saturate, so the sums cannot overflow.

Session id: cron:clickhouse-impl-slot-40:20261124-003800

@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [76c8f90]

Summary: ✅


AI Review

Summary

Bounds filter expansion during expression merging, index analysis and projection matching using max_expanded_ast_elements. No remaining blocker or major findings at 76c8f903583a2704378cb79a38d03d6c24a07db3. The earlier LIMIT, query condition cache and implied indexHint findings are addressed. The focused regression 05872_filter_merge_expanded_size_limit passes in the current Fast test report.

Missing context / blind spots
  • ⚠️ The full test suite remains limited by the review-threads gate; its rerun must complete for broader validation. No local ClickHouse binary is available in this review job.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 76c8f9035 with master a1ba05231 (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

72 object files changed (+37.89 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp.o 277.00 KiB 311.43 KiB +34.43 KiB (+12.43%)

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

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

Job report

Sources take the filters they are given as all the filters below the next
step of the walk. When a filter was skipped for its size, the walk went on:

- a `LIMIT` above it still reached the source, and `numbers`, `primes` and
  `generate_series` (which push a limit only when the filter is absent or
  exactly ranged) stopped after `limit + offset` rows before the skipped
  filter ran, returning too few rows;
- `updateQueryConditionCacheForMemory` tagged the nearest `FilterStep` (the
  skipped one) with the hash of the filters above it, so its rejections were
  stored under another condition's key and later queries lost rows.

Now the walk stops there, as it does at any step it cannot see through. Only
conditions above `max_expanded_ast_elements` are affected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An `indexHint` keeps its condition in its own DAG, not in its children, and
`ActionsDAG::mergeInplace` rebinds the inputs of an implied hint to the
expressions of the DAG below. Index analysis (`buildFilterActionsDAGImpl`,
`cloneDAGWithInversionPushDown`) walks that condition, so a hint counted as one
node let the expansion through.

`HAVING a36 < max(v) AND max(v) < 5` over the 36-level `a + a` chain: with
`optimize_and_compare_chain` an implied `indexHint(a36 < 5)` is pushed below
`GROUP BY`, passes the merge check, and the read then spends 11 GiB in
`cloneDAGWithInversionPushDown` (`MEMORY_LIMIT_EXCEEDED`, as on master). With
the hint counted it takes 0.2 s over `numbers()` and MergeTree, with the same
result as master at depth 12.

`getExpandedTreeSize` now adds the expanded size of the outputs of a hint's
DAG, and `getExpandedTreeSizeAfterMerge` binds the inputs of implied hints to
the outputs of `first` by name, as `mergeInplace` does.

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

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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant