Skip to content

Fix a planning hang when a filter over repeated subexpressions is checked against a JOIN - #125117

Merged
m-selmi merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-evaluate-partial-result-shared-nodes
Oct 16, 2026
Merged

m-selmi merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-evaluate-partial-result-shared-nodes

Conversation

@groeneai

@groeneai groeneai commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

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 a query that never finished planning, ignoring max_execution_time and KILL QUERY, when a filter over expressions that reuse the same subexpression (such as x + x across nested subqueries) is pushed down to a JOIN or checked for the ANY to SEMI/ANTI join conversion.

Description

On 26.3.33.24 LTS, as on every release line since 25.12, a WHERE over a chain of x + x aliases above an ANY LEFT JOIN never finishes planning and ignores max_execution_time and KILL QUERY. Since #123829 (in 26.8.21.10 and 26.9.13.15) the same happens for such a filter pushed down to a plain LEFT JOIN. That is the hung query in Stress test (amd_tsan) on #116577 (report, stuck for 2037 s in ActionsDAG::evaluatePartialResult <- filterResultForNotMatchedRows <- tryPushDownOverJoinStep).

Root cause: evaluatePartialResult marks a node as visited only by giving it an entry in node_to_column. A node whose arguments are unknown got no entry unless allow_unknown_function_arguments is set, so every parent walked its subtree again: O(2^depth) for a_k = a_{k-1} + a_{k-1}. The ANY-to-SEMI probe (filterResultForMatchedRows) and the always-false probe that #123829 added to filter push-down over a join both call it with no known inputs and default parameters.

Change: record such a node with a null column, which the walk already treats as unknown, so each node is visited once. Results are unchanged: a parent already received exactly that {nullptr, type, name} for a missing child.

Validation: the new test times out (60 s) on master and on this tree with the two lines reverted, and passes in 0.2 s with the fix; 50/50 randomized runs; 369 of 370 related join and filter push-down tests pass. The test pins join_use_nulls = 0, compile_expressions = 0 and collect_hash_table_stats_during_joins = 0: otherwise planning still walks the expression once per path elsewhere (#123724, the expression JIT, and since #116781 the join statistics key in ActionsDAG::Node::updateHash), which this PR does not change. It is a .sh test so that the AST fuzzer does not mutate it: an INNER JOIN in place of its LEFT JOIN reaches #123724 too.


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

Version info

  • Merged into: 26.11.1.47-master (included in 26.11 and later)

The walk used node_to_column as its only visited marker, but a node whose
arguments are not all known got no entry when allow_unknown_function_arguments
is false. Every parent then re-walked its whole subtree, so a chain like
a_k = a_{k-1} + a_{k-1} cost O(2^depth) visits.

filterResultForMatchedRows (ANY to SEMI/ANTI join conversion) and the
always-false check that tryPushDownOverJoinStep runs on every filter
push-down over a join both call it with no known inputs and the default
parameters. A filter over a doubled alias chain therefore never finished
planning and did not react to max_execution_time or KILL QUERY (seen as
"Hung check failed" in Stress test (amd_tsan) on ClickHouse#116577).

Record such a node as unknown (null column) so it is visited once. Parents
already materialise a missing child as the same {nullptr, type, name} and
treat a null column as unknown, so the results do not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 10, 2026
@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; 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test passes with filter push-down and the ANY conversion disabled, so it may not exercise the fixed walk DISAGREE CI does not randomize the push-down query 1 depends on. With the two lines reverted both queries time out at 60 s (fix: 0.58 s and 0.44 s), and query 2 also hangs on every release before #123829. Residual: query_plan_convert_any_join_to_semi_or_anti_join is randomized off in 5% of runs, when query 2 skips the ANY probe; query 1 still fails without the fix. Noted, not blocking.
2 💡 The test pins join_use_nulls = 0 and uses >=, unlike the CI row (join_use_nulls = 1, IS DISTINCT FROM) AGREE, noted The CI row's query verbatim also hangs on master and returns 2 in 0.56 s with the fix. The pin avoids the separate name blow-up of #123724.
3 💡 Test comments describe internals; the JIT naming growth is the same class as #123724, not that issue's site AGREE, noted none

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

Session id: cron:clickhouse-review-slot-8:20261010-232300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test 05359_partial_result_shared_nodes_join_filter times out on master every run, no randomized setting needed (clickhouse local --queries-file <test>: rc 124 at 60 s). The #116577 stress query verbatim does the same.
b Root cause explained? evaluatePartialResult uses node_to_column as its only visited marker; an unevaluable node got no entry when allow_unknown_function_arguments = false, so each parent re-walked its subtree: O(2^depth) for a_k = a_{k-1} + a_{k-1}. The push-down always-false probe and the ANY-to-SEMI probe call it with no known inputs.
c Fix matches root cause? Yes. The node is recorded as unknown (null column), making the walk linear at its source. No cancellation check, depth cap or caller-specific guard.
d Test intent preserved / new tests added? New .sql test with two queries: the filter push-down probe and the ANY-to-SEMI probe. No existing test changed.
e Both directions demonstrated? Master: both queries time out at 60 s; this tree with the 2 lines reverted: same; with the fix: 2 and 2 in under 0.6 s, equal to the reference from push-down off and from 26.9.7.6. Runner: FAIL (timeout) on a master server, OK 0.24 s on the fix. 50/50 randomized runs pass.
f Fix is general across code paths? One branch covers FUNCTION, ALIAS and ARRAY_JOIN nodes for every caller with allow_unknown_function_arguments = false (push-down probe, ANY-to-SEMI/ANTI probes, evaluateConjunction, mayBeTrueOnDefaultValue). Callers with true already recorded every node.
g Fix generalizes across inputs (params/datatypes/wrappers)? The defect is in the graph shape, not types. Measured with UInt64 and Nullable chains, IS DISTINCT FROM / > / >=, join_use_nulls 0/1 for the ANY query, hash / partial_merge / grace_hash joins, table swap auto/true/false.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; results are identical (a missing child was already passed to its parent as the same {nullptr, type, name}).
i Invariants and contracts preserved? Each node is processed at most once and its result equals master's. Callers use a local or discarded map; a null-column entry is already the in-tree "unknown" marker. try_emplace keeps the materialize entry written just above.

Session id: cron:clickhouse-impl-slot-7:20261010-215100

@groeneai
groeneai requested review from vdimir and yariks5s October 10, 2026 23:45
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e012146]

Summary: ✅


AI Review

Summary

PR #125117, head e012146b1aa59d67caaebbeeeac90bbed777261a, caches unknown results in ActionsDAG::evaluatePartialResult to prevent exponential traversal of shared subexpressions during join filter analysis. No actionable findings. The new stateless regression passed in 0.24 seconds in the Fast test report.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 10, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e012146b1 with master e0d54e882 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ef3bb299b; 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

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

Job report

The client AST fuzzer takes its seeds only from *.sql files. In the targeted
fuzzer run on this PR it turned the LEFT JOIN of this chain into an INNER JOIN,
so the filter is pushed into the right side of the join, and
splitActionsForJOINFilterPushDown then builds names that grow as 2^depth
(issue ClickHouse#123724): the server grew to 46 GB and was OOM-killed. The same query
does that on builds without this fix too (26.10.1.286, 26.9.7.6); on master it
hangs in evaluatePartialResult before it gets there.

Build the same two queries in a .sh test, like
05317_exponential_null_propagation.sh, so the chain is not a fuzzer seed, here
or in the master fuzzer corpus.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0965a79

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04227_materialized_cte_reused_with_in_subquery not from this PR: Code: 60 UNKNOWN_TABLE for _materialized_cte_ct_* when a reused MATERIALIZED CTE feeds an IN subquery on parallel replicas. The runner reproduces it 241/241 with the drawn optimize_move_to_prewhere = 0 and 0/196 without random settings; 6 PRs show it in 30 days #123121 (mine, open)
Mergeable Check, PR rollups, red only because of the row above #123121 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

All 164 other check runs completed and Finish Workflow is green; CH Inc sync is still pending. The AST fuzzer (amd_debug, targeted) red of the previous head is gone. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261011-073009

@m-selmi
m-selmi added this pull request to the merge queue Oct 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 15, 2026
Since ClickHouse#116781, `FilterStep::serialize` hashes the filter with
`ActionsDAG::Node::updateHash` when it builds the hash table statistics
key of the join (`calculateHashTableCacheKeys`). That hash walks the
children of every node again, so on this chain it runs once per path, and
the first query hangs in the second optimization pass on current master
even with the fix. The merge queue run on 8d3778b (master 3389afa
+ this branch) timed out on it in Fast test and in the flaky check.

That walk is a different defect from the one fixed here, so the test turns
the statistics off and checks only the push-down probe.

Measured on master 3389afa + this branch: the test passes 50/50 with
random settings and 20/20 without (at most 0.9 s); without the new setting
it times out at 60 s. On master 2cb89c8 (no fix) the test still times
out at 60 s, stuck in `filterResultForNotMatchedRows`.

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

Copy link
Copy Markdown
Collaborator Author

The merge queue run timed out on 05359_partial_result_shared_nodes_join_filter because current master gets stuck on its first query in a different place: since #116781, the hash table statistics key of the join hashes the filter with ActionsDAG::Node::updateHash, which walks it once per path (the walk #123793 changed). I pinned collect_hash_table_stats_during_joins = 0 in the test (e012146); the source change is the same.

On master 3389afa + this PR the test now passes 50/50 in under 1 s. On master without the fix it still times out, stuck in filterResultForNotMatchedRows.

@m-selmi
m-selmi added this pull request to the merge queue Oct 16, 2026
Merged via the queue into ClickHouse:master with commit 198cc17 Oct 16, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 16, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #125117 to 26.10: Fix a planning hang when a filter over repeated subexpressions is checked against a `JOIN`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…eated subexpressions is checked against a `JOIN`
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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants