Skip to content

Do not push a filter conjunct below a JOIN when it would exceed max_expanded_ast_elements - #134034

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-123724-option-b-expanded-size-gate
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-123724-option-b-expanded-size-gate

Conversation

@groeneai

@groeneai groeneai commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123724
Related: #100173

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 filter or JOIN ON condition reuses a column across nested subqueries above a JOIN, e.g. SELECT b + b AS c FROM (SELECT a + a AS b FROM ...) repeated 36 times. A filter conjunct that would exceed max_expanded_ast_elements written out as a tree is now evaluated above the JOIN instead of being pushed below it, when every table read below the JOIN is a MergeTree table or a bounded numbers, numbers_mt or generate_series table function.

Description

Option B of the three alternatives requested in #123724 (option A: #134010). 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.9.9.28, a query with a non-equi JOIN ON conjunct over such a chain is OOM-killed during planning despite max_server_memory_usage.

Each level passes max_expanded_ast_elements; filter push-down composes them into one conjunct with 2^depth paths. At a JOIN, splitActionsForJOINFilterPushDown rebuilds it with names spelled out per path, and the disjunction push-down walks it per path.

A memoized isExpandedSizeAbove (counting an indexHint's own condition) keeps such a conjunct in the filter above the JOIN, like any unpushable conjunct; the others are still pushed. The disjunction push-down skips a whole filter over the limit. Only if every read below the JOIN ends without its filter (MergeTree, bounded numbers; not system.numbers).

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

Query master PR
non-equi JOIN ON conjunct: defaults, runtime filters off, push-down off OOM-killed 0.3 - 0.9 s
the same over MergeTree OOM-killed 0.7 s
a36 >= id AND id >= 5 above a JOIN (implied indexHint) OOM-killed 0.8 s
05317's query (join_use_nulls = 1) and the fuzzed one from the report OOM-killed 0.3 - 0.4 s
WHERE over numbers() or MergeTree, no JOIN OOM-killed OOM-killed

Not fixed: a composed filter reaching a read without crossing a JOIN. A read uses its filter as the complete condition (exact LIMIT push-down, exact count()), so leaving a conjunct out there gives wrong results (measured).

Price: such a conjunct no longer narrows the read below the JOIN (primary key, numbers ranges), also at sizes master still plans. Below the limit plans are unchanged (251 related tests match master); planning time is within noise.


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

groeneai and others added 2 commits November 24, 2026 05:01
…xpanded_ast_elements

Option B of the three alternatives requested in ClickHouse#123724.

The analyzer bounds an expression's size written out as a tree
(`max_expanded_ast_elements`), but nested subqueries evade it because each
level is small. Filter push-down then composes the levels into one conjunct
with O(depth) nodes and 2^depth paths. At a JOIN,
`splitActionsForJOINFilterPushDown` rebuilds it through
`buildFilterActionsDAGImpl`, which spells the names out per path, and the
disjunction push-down (`extractPartialPredicate` ->
`onlyDependsOnAvailableColumns`) walks it per path without memo. On
26.9.9.28 the non-equi JOIN query from ClickHouse#123724 is OOM-killed during planning;
without the disjunction check the same query hangs instead.

A memoized `isExpandedSizeAbove` (on `computeForNodes`) moves a conjunct over
the limit from the pushed lists to `rejected`, so it is evaluated by the
filter above the JOIN, as master does for any conjunct it cannot push; the
other conjuncts are still pushed. `tryToExtractPartialPredicate` returns
nothing when the whole filter is over the limit. The gate applies only when
every read below the JOIN ends without its filter
(`canLeaveConjunctsOutOfFilter`: MergeTree and bounded `numbers(N)`); any
other leaf, e.g. unbounded `system.numbers` or a remote read, keeps master
behaviour, because it may need the pushed bound to end.

The read side is not gated: a read uses its filter as the complete condition
for exact LIMIT push-down (`numbers`) and the exact-count projection
(MergeTree), so leaving a conjunct out of a read's filter returns wrong
results. A composed filter that reaches a read without crossing a JOIN is
therefore not fixed here.

An `indexHint` counts with the condition it holds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove three comments that narrate the new code (the settings field, the fail-closed leaf check, the gate call site).

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, 5 findings, none in the last round) plus my own review (rows 1, 3, 4 and 7).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test did not observe the disjunction push-down gate: without it, a copy of the kept conjunct is pushed below the JOIN and the test still passed AGREE, fixed the oracle checks where the conjunct is printed, above and below the Join step; a mutation removing the gate turns it red
2 ⚠️ No test or measurement covered the MergeTree opt-in AGREE, fixed MergeTree variant of the test; the 36-doubling shape over MergeTree is OOM-killed on master, 1 in 0.7 s here
3 ⚠️ The max_expanded_ast_elements doc sentence overstated the scope AGREE, fixed per conjunct, only over MergeTree / bounded numbers reads
4 💡 The description's price omitted that the read below loses the conjunct for index analysis AGREE, fixed description updated
5 ❌ An implied indexHint (from optimize_and_compare_chain) holds the composed condition in its own actions, which the size check did not count, so it was still pushed below the JOIN AGREE, fixed the size check counts an indexHint with its condition; a36 >= id AND id >= 5 above a JOIN: OOM-killed on master, 5 in 0.8 s here; test case added, a mutation that stops counting the hint turns it red
6 ⚠️ The size check's memo map is a plain std::unordered_map, not a memory-tracking container DISAGREE one entry per node of a DAG already in memory, each node several times larger than the entry; the same map type as every existing computeForNodes caller
7 💡 The doc sentence and the changelog entry named only numbers, but numbers_mt and generate_series opt in too AGREE, fixed both list all three

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

Session id: cron:clickhouse-review-slot-9:20261124-050300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The #123724 non-equi JOIN ON query at default settings is OOM-killed on master every run (rc 137 after 39 s in a 16 GiB scope with a 12 GiB cap); the fix returns 1 in 0.3 s. The 05317 query with join_use_nulls = 1 and the fuzzed query from the Stress test report behave the same way.
b Root cause explained? Filter push-down composes nested levels into one conjunct with 2^depth paths. At the JOIN, splitActionsForJOINFilterPushDown rebuilds it with names spelled out per path (memory), and the disjunction push-down walks it per path without memo (CPU).
c Fix matches root cause? Yes for the JOIN path: a conjunct larger than max_expanded_ast_elements written out is not handed to those per-path consumers and stays in the filter above the JOIN, where master keeps any conjunct it cannot push.
d Test intent preserved / new tests added? New 05873_join_filter_too_big_to_expand: EXPLAIN actions = 1 checks that the oversized conjunct is printed above the JOIN at limit 1000 and below it at the default limit, over numbers(N), over a MergeTree table and for an implied indexHint that holds the composed condition, while id < 10 is still pushed (exactly 20 rows read); an unbounded system.numbers case must still get the bound. Removing the split check, the disjunction check, the MergeTree opt-in or the indexHint count each fails it.
e Both directions demonstrated? Yes: the repro queries (OOM-killed on master, sub-second on the fix, also with a MergeTree table below the JOIN) and the test (fails on master only on the three limit-1000 plan-check lines; passes 50/50 randomized runs and the parallel replicas settings on the fix).
f Fix is general across code paths? All three conjunct lists of the split (left, right, both streams) and the disjunction push-down (removing that check brings back a hang on the same query). Not covered: a composed filter that reaches a read without crossing a JOIN (applyFilters, KeyCondition, PREWHERE), where leaving a conjunct out of the read's filter returns wrong results; stated in the PR.
g Fix generalizes across inputs (params/datatypes/wrappers)? Counts nodes, including the condition an indexHint holds, so it is type-independent. Checked with integer and boolean or chains, Nullable keys (join_use_nulls = 1), runtime-filter conjuncts and non-equi conjuncts. Limit 0 and the maximum value disable the check; the count saturates.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting and no default change. Below the limit plans are unchanged: 251 related stateless tests give the same results as master. Only the max_expanded_ast_elements description gains a sentence.
i Invariants and contracts preserved? A kept conjunct is evaluated by the filter above the JOIN, and each read below gets a filter equal to the filter step over it, so exact LIMIT push-down and exact count() are unaffected (results identical to master). New ExtraSettings member and initializer are last.

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

@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2c428ac]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_prometheus_protocols/test_compliance.py::test_promql_extended_support FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR uses max_expanded_ast_elements to retain oversized filter conjuncts above a JOIN over bounded sources. The fix leaves an exponential AND traversal in the same split routine, so a small nested query can still exhaust server memory.

Findings

❌ Blockers

  • src/Interpreters/ActionsDAG.cpp:4117: The per-conjunct gate does not bound atom enumeration. Inline finding. Starting from the test's bounded join, project val < 4 AS c0, double it through nested c1 = c0 AND c0, through c36, and filter with WHERE c36 AND id < 10. Expression merging and removeAliasesForFilter expose a shared and DAG. getConjunctionNodes checks its small leaf predicates, but the unconditional extractConjunctionAtoms at line 4215 enumerates every path and attempts to store 2^36 leaf pointers, requiring 512 GiB before vector growth overhead. Make this traversal operate on distinct DAG nodes while preserving order. Retaining the whole chain also requires bounding the analogous walk in trySplitSingleAndFilter in src/Processors/QueryPlan/FilterStep.cpp:392.
Tests
  • ⚠️ Add a focused regression for the shared AND chain above a bounded-source JOIN, proving planning remains bounded. The existing 05873_join_filter_too_big_to_expand passes in Fast test, but does not exercise this atom-enumeration path. The finding follows from tracing the current code; the proposed SQL variant was not executed because this review job has no ClickHouse binary.
Final Verdict

Status: ❌ Block

Bound the remaining shared AND traversal and add regression coverage.

@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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Nov 24, 2026
{
std::erase_if(conjunctions.allowed, [&](const Node * conjunct)
{
if (!isExpandedSizeAbove(conjunct, max_expanded_conjunct_size))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Blocker] The size gate still leaves an exponential traversal inside splitActionsForJOINFilterPushDown: the unconditional extractConjunctionAtoms(predicate) below (line 4215) walks shared and nodes once per path, without a visited set.

For example, adapt the new test's bounded numbers join to project val < 4 AS c0, then nest SELECT id, c0 AND c0 AS c1, SELECT id, c1 AND c1 AS c2, and so on, finishing with WHERE c36 AND id < 10. After expression merging and removeAliasesForFilter, getConjunctionNodes finds only the small leaf predicates, so every check here passes. Atom collection then attempts to materialize 2^36 copies of the same leaf in a plain std::vector (512 GiB of pointers alone), despite the default max_expanded_ast_elements. This leaves the same server OOM risk on a bounded-source JOIN.

Make atom collection operate on distinct DAG nodes while preserving predicate order, and add a regression for an AND doubling chain. If the solution instead retains the whole chain above the join, also account for the per-path walk in trySplitSingleAndFilter in FilterStep.cpp; keeping it above the join alone does not make that consumer bounded.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Measured on this head and on master alike (depth 36 is memcg-OOM-killed after about 30 s; the first walk to blow up is the per-atom loop in filterResultForNotMatchedRows), this is extractConjunctionAtoms enumerating a shared and once per path, a separate defect from the conjunct size this PR gates that none of the three #123724 alternatives targets. I'll fix it in its own PR, so the fix applies whichever alternative is merged.

@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2c428acc6 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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2c428ac

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, targeted) / test_prometheus_protocols/test_compliance.py::test_promql_extended_support crash, not related to this diff: the node died mid-test (TRUNCATE TABLE got connection refused), and its stderr.log has the UBSan abort AsynchronousMetrics.cpp:854:25: runtime error: unsigned integer overflow: 7708 - 7709 (the /proc/stat iowait counter stepped back; the wrap is fatal since the UBSan unsigned-overflow check was enabled on master on 2026-11-23). The only failure of 1766 in the job a fix task is created (investigating at full effort, fixing-PR link to follow here)
Finish Workflow / Post Hooks (can_be_merged.py --review-threads) one blocking review thread is unresolved (the bot [Blocker] on ActionsDAG.cpp, answered in the thread) PR-caused by design and owned by this PR (#134034): the resolution is addressing the blocking review thread(s)

Mergeable Check and PR are the praktika rollups of these two rows. The other CIDB FAIL rows on this head are Config Workflow / Pre Hooks of the two runs before the can be tested label. CH Inc sync is green.

Session id: cron:our-pr-ci-monitor:20261124-090025

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AsynchronousMetrics UBSan abort that killed the node in test_prometheus_protocols/test_compliance.py::test_promql_extended_support (Integration tests (amd_asan_ubsan, db disk, targeted)): #134097

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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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