Skip to content

Fix a join planning hang for a key that reuses a column across nested subqueries - #123793

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-exponential-join-planning-shared-subexpression
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-exponential-join-planning-shared-subexpression

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123509
Related: #123432
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 join planning that never finished, and ignored max_execution_time and KILL QUERY, for a join on an expression built by nested subqueries that reuse a column (for example x + x at every level).

Description

On 26.8 and 26.9, a LEFT JOIN whose key is built by nested subqueries that each use the previous column twice never finishes planning and ignores max_execution_time and KILL QUERY; an INNER JOIN does the same with enable_join_runtime_filters = 0. CI: a stress-test variant of 05317_exponential_null_propagation hung for 3937 s (Stress test (arm_release)).

Root cause: mergeExpressions folds such projections into one ActionsDAG with O(depth) nodes but 2^depth paths, and three planning walks visited it once per path:

  • ActionsDAG::Node::updateHash / ActionsDAG::updateHash (join statistics keys during join reordering);
  • strictOnRelations / predicateNullRejectingRelations (null rejection with join_use_nulls = 1);
  • the consumed-inputs walk in buildPhysicalJoinImpl.

Change: the hash is a Merkle digest computed once per node, and the two walks keep a visited set or a per-node cache. Hash values change, but every consumer is an in-memory per-process cache key.

Validation: reverting each change alone makes its query hang again. With enable_join_runtime_filters = 0, at depth 24/25/26/27 master plans in 3.9/7.2/14.0/27.8 s and the fix in about 0.6 s. The new test times out on master and passes 50/50 with random settings. The LEFT JOIN arm runs with the default settings.

Not fixed here: with the default enable_join_runtime_filters = 1, the runtime filter on such a key is pushed down through the expression, and predicate push-down and index analysis then build names or walk it once per path too (#123724), so an INNER JOIN of this shape runs out of memory; master gets there after the hang. It is reached without a join too, so it needs its own fix; the test's INNER JOIN arms pin enable_join_runtime_filters = 0, as 05317 does.


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

… subqueries

`mergeExpressions` folds nested projections such as `a2 = a1 + a1`, `a3 = a2 + a2`, ... into one
`ActionsDAG` whose `plus` nodes have the same child twice: the DAG has O(depth) nodes but 2^depth
root-to-leaf paths. When such an expression becomes a JOIN key, several plan-time walks visited it
per path instead of per node, so planning doubled with every nesting level and never finished at
depth 36 (the AST-fuzzer variant of 05317_exponential_null_propagation hung a stress check for
3937 s, ignoring `max_execution_time` and `KILL QUERY`; planning has no cancellation points).

- `ActionsDAG::Node::updateHash` recursed into every child without a memo, and
  `ActionsDAG::updateHash` walked every path and called it at each node. Both now compute a Merkle
  digest (own fields + the 128-bit digests of the children), each node hashed once per call. The
  contract is unchanged (a structural hash; equal expressions hash equal; the runtime-filter id value
  is still skipped); only the values change. All consumers (hash-table statistics keys, join output
  keys, the query condition cache, automatic parallel replicas) are per-process and in-memory, so
  they only start cold after an upgrade. Reached from `deriveCacheKeysForNewJoin` during join
  reordering, the stack of the stress-check hang.
- `strictOnRelations` (null-rejection analysis under `join_use_nulls = 1`) recursed through every
  null-propagating function per path; it is now an iterative walk with a visited set, and
  `predicateNullRejectingRelations` caches its per-node results, as ClickHouse#123509 did for
  `collectNullPropagatingInputs` / `collectNullRejectedInputs`.
- The consumed-inputs walk in `buildPhysicalJoinImpl` pushed every child of every node; it now
  skips visited nodes. Without it the stress-check query still hangs there after the hash fix.

Each change was checked by reverting it alone: the matching query hangs again. With the default
`enable_join_runtime_filters = 1` such a join next runs out of memory in predicate push-down
(ClickHouse#123724); that family is reached without a join too and is not changed here, so the new test's
`INNER JOIN` arms pin `enable_join_runtime_filters = 0` like 05317, and the test turns off the
server-side AST fuzzer (`ast_fuzzer_runs = 0`), whose variants of these queries reach it.

Related: ClickHouse#123509
Related: ClickHouse#123432
Related: ClickHouse#123724

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

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

Pre-publication review by an independent model (engine: codex; 2 findings over 3 rounds, the last round clean) plus my own review over 3 rounds.

# Sev Finding Verdict Evidence / action
1 ⚠️ The release hang was measured at default settings, the fix only with join runtime filters off; "linear" overclaims while a non-equi ON condition still runs out of memory in filter push-down (#123724) AGREE default-settings runs on the fix; title and changelog entry narrowed (round 1)
2 ❌ The residual-condition walk in buildPhysicalJoinImpl (JoinStepLogical.cpp:1931) still visits the shared key once per path DISAGREE the same ON key = k.val AND key <= k.val shape with query_plan_filter_push_down = 0 plans in 0.53 s on this tree without a visited set in that walk; with push-down on, the stack is in buildFilterActionsDAGImpl name building (#123724), which master hits too
3 💡 Commit message says the other queries stay fast when one change is reverted AGREE reworded (round 1)
4 💡 The same hash keys the query condition cache AGREE measured (round 1)
5 ⚠️ The Stress test's server-side AST fuzzer can turn the default-settings LEFT JOIN arm into an INNER JOIN with runtime filters, which runs out of memory in filter push-down (#123724) AGREE the test sets ast_fuzzer_runs = 0 (round 2); with the Stress profile's fuzzer on, the test produces 0 fuzzed queries, while a copy without the flag produces 15
6 💡 #116781, #122966 and #117161 also edit ActionsDAG::Node::updateHash AGREE noted: textual conflict only; their changes belong in updateHashWithoutChildren
7 💡 The local regression run did not include the 02151_hash_table_sizes_stats* tests AGREE noted: the reorder-time and pre-walk join keys both come from calculateJoinStepCacheKeyContribution, so they still agree; PR CI runs them
8 💡 05317_exponential_null_propagation can still reach #123724 through a fuzzer-added WHERE in the Stress test AGREE noted: not changed here; the CI query that hung this check now returns in 0.5 s with its CI settings

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

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The CI query and three generated variants (join key = 36 nested x + x doublings on the preserved side of r LEFT JOIN l) never finish planning on master at a 90 s limit, every run. The new test times out at 120 s on a master server.
b Root cause explained? mergeExpressions builds a DAG with O(depth) nodes and 2^depth paths. ActionsDAG::Node::updateHash / ActionsDAG::updateHash (join statistics keys during reordering), strictOnRelations / predicateNullRejectingRelations (join_use_nulls = 1) and the consumed-inputs walk in buildPhysicalJoinImpl visited it once per path. Planning has no cancellation points.
c Fix matches root cause? Yes. Each walk now visits each node once: a memoized Merkle hash, a visited set, a per-node cache. No timeout, tag or bound was changed.
d Test intent preserved / new tests added? New 05320_exponential_join_planning_shared_subexpression (plain key, join_use_nulls 1, key as a join output, and a LEFT JOIN with the default settings). Its random-settings line keeps the join order limit at 3 or more, because at 0 or 1 the join is not reordered and master passes it. 05317 is unchanged and passes.
e Both directions demonstrated? Yes. Master: no result at 90 s; fix: 0.5 s. Test: master FAIL (timeout), fix OK, 50/50 with random settings. Reverting each of the three changes alone makes its query hang again; with the hash change reverted the LEFT JOIN arm alone times out too. At default settings there is no depth (20 to 26) where master returns a result and the fix does not.
f Fix is general across code paths? The hash is fixed in the shared helper, so all callers benefit (join statistics keys, query condition cache, automatic parallel replicas). I enumerated every walk on this planning path and kept only the ones a revert proves reachable. The name building in filter push-down (#123724) is a separate mechanism, also reached without a join, and is not changed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? The walks are type-blind except the null-rejection one, whose type checks are unchanged. Exercised: depth 18 to 36, non-plus functions in the chain (intDivOrZero, positiveModuloOrNull), the CI job's settings (JIT, max_threads 2, dpsize,greedy), 50 randomized runs.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change. Hash values change, but they are only in-memory per-process cache keys, so caches start cold after an upgrade.
i Invariants and contracts preserved? updateHash is still a structural hash (equal expressions hash equal) and still skips the runtime-filter id value. The per-node field hashing is unchanged. strictOnRelations returns the same set (a union over the same reachable leaves). The null-rejection control flow is unchanged.

Session id: cron:clickhouse-impl-slot-41:20261003-225500

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [02a8b79]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
05218_text_index_substreams_opened_lazily FAIL cidb

AI Review

Summary

This PR replaces the path-exploding join-planning walks over shared ActionsDAG subexpressions with memoized or visited traversals, and it adds a focused stateless regression test for the reported hang. I did not find a remaining contract violation in the changed equi-join planning paths or a PR-metadata issue that would justify new inline review comments.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

⚠️ No coverage measurement for commit 02a8b79: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_6.profdata.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 02a8b79e8 with master 37a251ffa (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

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

Job report

@groeneai

groeneai commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 652dbd4

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
Build (amd_fuzzers) / Build ClickHouse not from this PR: the clickhouse_fuzzer link fails with relocation R_X86_64_PC32 out of range in __sanitizer::StackDepot*; the same job failed on 181 PRs and 40 master runs in the last 24h #123738 (external, merged 2026-10-04 01:14Z). This workflow was created at 00:54Z, before that merge, so the fix is not in the tree that ran; a master merge to pick it up follows
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 05023_lazy_url_glob_expansion not from this PR: under parallel replicas url() goes through StorageURLCluster, and LIMIT 1 keeps whichever address a replica returns first; it failed on 8 PRs and on master in the last 24h #123815 (mine, open)
Mergeable Check, PR rollups, red only because of the rows above #123738, #123815

None of these touches join planning, and 05320_exponential_join_planning_shared_subexpression passed everywhere it ran. All 146 checks completed, Finish Workflow is green and CH Inc sync passed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261004-063241

…n-planning-shared-subexpression

Picks up ClickHouse#123738 (amd_fuzzers relocation overflow fix).

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

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 02a8b79

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, parallel) / 05218_text_index_substreams_opened_lazily flaky: selective_below_threshold flips to 0 while the answers stay right; the job's 17 reruns with the same randomized settings all pass; the same failure hit 12 other PRs and master in the last 24 h #123823 (mine, open)
Mergeable Check, PR rollups of the row above #123823 (mine, open)

Session id: cron:our-pr-ci-monitor:20261004-120236

@rschu1ze

rschu1ze commented Oct 7, 2026

Copy link
Copy Markdown
Member

Same as #123509

@rschu1ze rschu1ze closed this Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

I don't think #123509 covers this. It was merged on 2026-10-03, before I opened this PR, and changes only the walk in convertOuterJoinToInnerJoinTransitively.cpp. This PR fixes other per-path walks over the same shared x + x DAG: ActionsDAG::Node::updateHash (join-order cache keys), strictOnRelations, and the consumed-inputs walk in JoinStepLogical.

On master 516006f (26.10.1.1758, includes #123509), release build:

  • The LEFT JOIN query from the new test, at default settings, gives no result after 60 s. At 30 s its stack is 49 nested ActionsDAG::Node::updateHash frames under calculateJoinStepCacheKeyContribution. On this branch it returns in 0.5 s.
  • The fuzzed CI query with max_execution_time = 10 is still running at 60 s.

The Stress hung check has hit it 5 times since #123509 merged, every time inside Node::updateHash. That includes master, in Stress test (arm_debug) @ 7405dae0 on 2026-10-06.

Would you reopen it, or would you prefer a different shape?

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... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants