Skip to content

Make the planner consumers of a filter DAG linear in its size - #134059

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/123724-option-c-linear-consumers
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/123724-option-c-linear-consumers

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. Filter push-down, index analysis, PREWHERE, JIT compilation, short-circuit analysis and partial JOIN filter push-down now process such a filter once per node instead of once per path.

Description

Option C of three alternatives requested in #123724 (comment) (A: #134010, B: #134034). 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.5.57 and 26.8.37.168, SELECT count() FROM (<36 nested SELECT a + a>) WHERE a36 <= 0 is OOM-killed during planning despite the memory limit.

The filter has few nodes but 2^36 paths. Every optimization still runs; each consumer that walked paths or concatenated child names is now linear:

  1. buildFilterActionsDAG and cloneDAGWithInversionPushDown (now memoized) generate names up to 64 KiB, then keep the source name.
  2. RPNBuilder stops a name once it exceeds every name it is compared with (KeyCondition, FINAL key check, estimator, isConditionGood), the PREWHERE log label at 64 KiB.
  3. PREWHERE analysis visits each node once; the JIT name is cut at 64 KiB plus the DAG hash.
  4. findLazyExecutedNodes: the same change as Visit each node once when finding lazily executed short-circuit arguments #133893.
  5. Partial JOIN push-down uses allReachableNodes / anyReachableNode.

Nine places in 13 files, ~300 lines; reverting any one alone turns a repro red.

Debug build, depth 36:

Query master PR
numbers(), also merge expressions off / JIT / a comparison chain OOM-killed / MEMORY_LIMIT_EXCEEDED 0.02 s, plus JIT compilation
MergeTree: key, PREWHERE + statistics, FINAL OOM-killed 0.02-0.05 s
JOIN: non-equi ON, 05317 with join_use_nulls = 1, the fuzzed query (its own ILLEGAL_DIVISION) OOM-killed 0.03-0.12 s
short-circuit AND / OR OOM-killed 0.02 s
partial JOIN push-down OR > 120 s 0.04 s

Not fixed (no repro reaches them): skip-index name lookups, text-index direct read, use_query_condition_cache_for_time_conditions = 1, Graphite / row-policy FINAL helpers, the Cascades estimator, EXPLAIN pretty (#115921), and/or over shared subtrees.

Price: names within 64 KiB and all walk results are unchanged; 1845 related stateless tests match master.


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

groeneai and others added 3 commits November 24, 2026 04:24
Nested subqueries that each double a column (`SELECT a + a AS b FROM (...)`)
compose into one filter DAG with O(depth) nodes but 2^depth root-to-leaf
paths. The DAG itself and its execution are linear; the consumers below
rebuild a name from the children's names or walk the predicate once per
path, so planning needed exponential time or memory (OOM-killed at 36
levels with default settings). Each of them now does O(nodes) work:

1. `ActionsDAG::nameForRebuiltFunction` / `MAX_GENERATED_NAME_SIZE` (64 KiB):
   a rebuilt function keeps its generated `f(children)` name unless that
   name would exceed the bound, then it takes the source node's name.
2. `buildFilterActionsDAGImpl` names rebuilt functions that way.
3. `cloneDAGWithInversionPushDown` (KeyCondition) clones each node once per
   (need_inversion, boolean_context) and names the clones the same way.
4. `RPNBuilderTreeNode::tryGetColumnName(max_size)`: KeyCondition, the FINAL
   sorting-key check, the selectivity estimator and `isConditionGood` stop
   building a name once it is longer than every name it is compared with.
5. MergeTreeWhereOptimizer: `collectColumns`, `cannotBeMoved`,
   `isExpensiveExpression`, `conditionMayThrow` and the FINAL walk visit each
   DAG node once.
6. The JIT function name (`CompileDAG::dump`) is cut at the bound, with the
   DAG hash appended to keep it unique.
7. `findLazyExecutedNodes` remembers nodes found not lazily executed; this is
   the same change as ClickHouse#133893.
8. Partial JOIN filter push-down: `onlyDependsOnAvailableColumns` and
   `dependsOnSomeColumn` use `allReachableNodes` / `anyReachableNode`.
9. The PREWHERE condition log label (`Condition::toString`) uses the bounded
   name, falling back to the DAG node's name.

Every name within the bound and every walk result is unchanged.

Related: ClickHouse#123724

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Eleven queries whose filters have 24 or 40 doublings of one column: every
memory-bound one fails with MEMORY_LIMIT_EXCEEDED on master under a 200 MB
cap, and the two partial JOIN push-down ones plan for hours there.

Related: ClickHouse#123724

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`cloneDAGWithInversionPushDown` names a comparison it rebuilds (inverted or not) like every other rebuilt function.

Related: ClickHouse#123724

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (Gate B) - adjudication
Finding Verdict
❌ cloneDAGWithInversionPushDown: comparisons (inverse_relations branch) still concatenated child names AGREE - fixed: same 64 KiB bound as the other rebuilt functions, plus a comparison-chain case in the test
⚠️ Test checks only results, not that each optimization still runs DISAGREE - the test is the master-vs-fix oracle; per-site necessity was measured by reverting each item alone
⚠️ Test should pin the settings that enable each consumer DISAGREE - results are identical under any value (50 randomized runs, 4 parallel-replicas modes); pinning only removes coverage

Re-review after the fix: no findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Manerone, could you review this? Option C for issue #123724: each planner consumer of a filter DAG (filter push-down names, index analysis, PREWHERE, JIT, short-circuit analysis, partial JOIN push-down) processes the filter once per node instead of once per path; the JIT part cuts the CompileDAG::dump name at 64 KiB and appends the DAG hash.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05874_exponential_predicate_consumers on master: the ten memory-bound queries fail with MEMORY_LIMIT_EXCEEDED under a 200 MB cap (0.7-16 s each), the two partial JOIN push-down queries do not finish in 150 s; every run. At depth 36 without a cap master is OOM-killed (clickhouse local, also official 26.10.5.57 and 26.8.37.168).
b Root cause explained? Nested subqueries that double a column give a filter DAG with O(depth) nodes and 2^depth paths. Consumers that rebuild a name from the children's names (buildFilterActionsDAG, cloneDAGWithInversionPushDown, RPNBuilder, the JIT name) or recurse per path (PREWHERE walks, findLazyExecutedNodes, partial JOIN push-down) cost 2^depth time or memory.
c Fix matches root cause? Yes. Each consumer becomes linear where it walks: per-call memos and visited sets, reuse of allReachableNodes / anyReachableNode, a 64 KiB bound for generated labels, and RPN names that stop at the longest name they are compared with. No gate, no new setting, no optimization skipped.
d Test intent preserved / new tests added? New test 05874: twelve queries (numbers(), a comparison chain, MergeTree, FINAL, JIT, merge expressions off, short-circuit, equi-key copy, non-equi ON, partial push-down OR), at most 5 nested levels. Per-site necessity: reverting any one of the nine items turns at least one repro red; the comparison-clone name is guarded by a depth-36 chain.
e Both directions demonstrated? Yes. Master: [ FAIL ] (10 x Code 241, then timeout). This PR: [ OK ] in 2.3 s, peak query memory 0.8-3.1 MiB; 50/50 randomized runs OK (20/20 after the last commit).
f Fix is general across code paths? Five KeyCondition lookups, the FINAL key check, the selectivity estimator, isConditionGood, five PREWHERE walks, the PREWHERE log label, JIT, lazy execution, partial push-down. Not reached by any repro and listed in the PR: skip-index lookups, text-index direct read, use_query_condition_cache_for_time_conditions, Graphite / row-policy FINAL helpers, the Cascades estimator, EXPLAIN pretty.
g Fix generalizes across inputs (params/datatypes/wrappers)? numbers(), + and = chains (also under NOT), MergeTree, ReplacingMergeTree FINAL, INNER / LEFT JOIN, join_use_nulls 0/1, JIT, merge expressions off, one and several PREWHERE steps, randomized settings x 50, four parallel-replicas modes x 10, a TSan-sized stack x 10.
h Backward compatible? (maintainer-approved exception only) Yes. Names within 64 KiB, RPN names within their candidates' length and every walk result are unchanged, so EXPLAIN, query condition cache keys and index/PREWHERE decisions of ordinary queries do not change: 1845 related stateless tests match master. No setting or format change.
i Invariants and contracts preserved? The clone memo returns the same node for the same (node, inversion, boolean context); tryGetColumnName returns the exact getColumnName value or nothing, which callers treat as a name not in their set; memos live for one top-level call and use memory-tracked containers.

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

@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fb3e0e5]

Summary: ✅


AI Review

Summary

The PR bounds generated expression labels and memoizes planner walks over shared filter DAGs, preventing exponential planning work for the covered query shapes. Reviewed commit fb3e0e5f2b701101729a8c58255e8a2ab3f2fe4f; no actionable findings. The new 05874_exponential_predicate_consumers regression test passes in Fast test in 1.7 seconds.

Consumers traced for the changed labels: source filtering and JOIN push-down use rebuilt output names; KeyCondition, PREWHERE analysis and selectivity estimation reconstruct expression names and reject overlong matches; LLVMFunction uses the bounded display name while compilation caching retains the full DAG hash.

Missing context / blind spots
  • ⚠️ Broader sanitizer, stateless and bugfix-validation results are not yet available for the current run. Their completed current-commit CI reports would close this validation gap. No local ClickHouse tests were run, as required by the review environment.
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 24, 2026

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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