Skip to content

Hash each node of an ActionsDAG once, fixing a planning hang in the hash table statistics key - #129184

Merged
murphy-4o merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-hash-shared-dag-nodes-once
Nov 6, 2026
Merged

murphy-4o merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-hash-shared-dag-nodes-once

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #126250
Related: #126148

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 query planning that never finished for a filter over a subexpression that is reused many times (for example x + x in 30 nested subqueries) below a JOIN or a GROUP BY with keys, while hash table statistics are collected (the default). Such a query also ignored KILL QUERY and max_execution_time.

Description

On 26.10.2.103, a SELECT with a filter over a subexpression reused at every level of 30 or more nested subqueries (x + x) below a JOIN or a GROUP BY with keys never finishes planning at default settings, and neither KILL QUERY nor max_execution_time stops it.

Since #116781 the hash table statistics key of a join or an aggregation includes ActionsDAG::getOutputIdentity of each filter below it. ActionsDAG::Node::updateHash hashed a node's own fields and then recursed into every child with no memo, so a node shared by two parents was hashed once per path: a chain of a_{i+1} = a_i + a_i has O(depth) nodes and 2^depth paths. ActionsDAG::updateHash also visited each node once per path and hashed its whole subtree at each visit.

Now each node gets a 128-bit digest of its own fields (updateOwnHash, split out by #126148), its number of children and its children's digests, computed once per node with a per-call memo. Both functions become O(nodes + edges), covering every hash caller (statistics keys, query condition cache, prewhere and top-K keys). Hash values change, equality does not, and every consumer is an in-memory key. Other per-path walks are separate code, not changed here: VirtualColumnUtils::isDeterministic, strictOnRelations and JIT expression names (#123724).

Validation (debug build):

  • The issue's queries at depth 24 / 30 / 36: base 2-3 s / >60 s / >60 s, fix under 1 s.
  • New 05359_hash_table_stats_key_shared_nodes (aggregation key) and 05359_partial_result_shared_nodes_join_filter with its collect_hash_table_stats_during_joins = 0 workaround removed (join key) time out on base and pass with the fix, 50/50 with randomized settings; both check in system.text_log that the query reached the statistics cache. A gtest covers ActionsDAG::updateHash, which neither SQL test reaches.

🤖 Generated with Claude Code


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

Version info

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

`ActionsDAG::Node::updateHash` mixed in the node's own fields and then
recursed into every child with no memo, so a node shared by two parents
was hashed once per path. A chain of `a_{i+1} = a_i + a_i` folded into
one DAG has O(depth) nodes but 2^depth paths, so hashing it was
exponential. `ActionsDAG::updateHash` was worse: it walked every edge
and called the recursive node hash at each visit.

Since `FilterStep::serialize` puts `getOutputIdentity` of the filter into
the hash table statistics key, planning a filter over 30+ nested
`x + x` aliases below a `JOIN` or a keyed `GROUP BY` never finished at
default settings, and the walk does not react to `KILL QUERY`.

Now a node's digest is SipHash128 of its own fields (`updateOwnHash`),
its number of children and its children's digests, computed once per
node by an iterative post-order walk with a per-call memo.
`Node::updateHash` mixes in the digest of the node, and
`ActionsDAG::updateHash` the number of outputs and the digest of each
output, sharing one memo. Both are O(nodes + edges).

Hash values change, equality does not: two subtrees hash equal iff their
own fields and ordered children are equal, whether a child is shared or
duplicated. Every consumer is an in-memory, per-process key (hash table
statistics, query condition cache, prewhere and top-K keys), and nothing
persists these hashes.

The `collect_hash_table_stats_during_joins = 0` pin in 05359 was the
workaround for this bug and is removed, so that test now covers the join
statistics key at depth 36. The new 05359 test covers the aggregation
statistics key, both SQL tests check in `system.text_log` that their
query reached the statistics cache, and the gtest covers
`ActionsDAG::updateHash`, which neither SQL test reaches, and that
different DAGs still hash differently.

Closes ClickHouse#126250

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (Gate B, 3 rounds)
  • ❌ AGREE, fixed: hash-test-liveness. The gtest now checks that different DAGs hash differently (an input 64 levels down, a second output); hashing only the first output or dropping the children's digests reddens it.
  • ❌ AGREE, fixed: join-random-gate. query_plan_optimize_join_order_limit = 0 (5% of randomized runs) skips the join statistics key; the join test clamps it to at least 1.
  • ❌ AGREE, fixed: stats-path-oracle. Both SQL tests check in system.text_log that their query reached the hash table statistics cache.
  • 💡 noted: the join test covers the join key while the filter sits under an optimized join; the aggregation test and the gtest cover the shared hash in every plan shape.

Final round: 0 findings.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's queries at depth 30 and 36 time out (60 s) on every run of a master debug build (re-measured on a master that contains #126148) and of the official 26.10.2.103, both arms; depth 24 takes 2.1-2.3 s on master. Stacks: nested ActionsDAG::Node::updateHash under getOutputIdentity <- FilterStep::serialize <- calculateHashTableCacheKeys, from setAggregationHashTableCacheKeys and from optimizeJoinLogical.
b Root cause explained? Yes. The nested x + x aliases fold into one DAG with O(depth) nodes and 2^depth paths. Node::updateHash recursed into each child with no memo, so a shared node was hashed once per path; ActionsDAG::updateHash also walked every edge. Since #116781 the statistics keys hash every filter below a join or aggregation through it, with no cancellation point.
c Fix matches root cause? Yes. Each node gets a Merkle digest (own fields, children count, children's digests) computed once per call, in both functions. No timeout, cancellation check or setting pin.
d Test intent preserved / new tests added? Yes. New 05359_hash_table_stats_key_shared_nodes (aggregation key); 05359_partial_result_shared_nodes_join_filter loses the collect_hash_table_stats_during_joins = 0 pin that worked around this bug, so it now covers the join key; it clamps query_plan_optimize_join_order_limit to >= 1, since 0 skips the join key. Both SQL tests also check in system.text_log that their query reached the statistics cache (existing reference lines unchanged, one line added each); gtest ActionsDAGHash for ActionsDAG::updateHash and hash equality.
e Both directions demonstrated? Yes. Both SQL tests time out on base and pass with the fix (50/50 randomized). Restoring the recursive node hash reddens both SQL tests and the gtest; restoring only the per-edge DAG walk reddens the gtest, and so does hashing only the first output or dropping the children's digests. Turning the statistics collection off reddens only the text_log line of each SQL test, and so does query_plan_optimize_join_order_limit = 0 without the clamp (8/8 such runs of 100).
f Fix is general across code paths? Yes. Fixed in the two shared functions, so every consumer inherits it: getOutputIdentity in four steps, the join-key contributions, and getHash for the query condition cache, prewhere, top-K and format filter keys. Other exponential walks on such chains (strictOnRelations, JIT names #123724) are different functions and not changed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The hash is structural and type-agnostic; the three flags are constant within a call, so a memo keyed by node is exact. The gtest checks shared vs duplicated equal children, a different function, a different child order, a different input 64 levels down and a different second output.
h Backward compatible? (maintainer-approved exception only) Yes. Hash values change, equality does not. Every consumer is an in-memory, per-process key, nothing persists them, and plan transmission uses the unchanged ActionsDAG::serialize. No setting or format change.
i Invariants and contracts preserved? Yes. Equal structures hash equal; the DAG is const and the memo local, so no concurrency change; the walk is iterative. Digests are 128-bit per node and the final 64-bit truncation is unchanged.

Session id: cron:clickhouse-impl-slot-4:20261104-052800

@groeneai

This comment was marked as resolved.

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3023892]

Summary: ✅


AI Review

Summary

The PR replaces repeated recursive hashing of shared ActionsDAG nodes with memoized 128-bit digests, fixing exponential planning time for filters below joins and keyed aggregations. No actionable findings remain.

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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 302389225 with master 7f11488e0 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4f752f7e6; 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, 19 s compile time in total, 7 of them have a recent master baseline.

Job report

…filter safe under concurrent runs

The hash table statistics cache is process-wide, and every run of the test
builds the same keys. A run that misses the cache and then finds an equal
entry stored by a concurrent run in the meantime logs nothing under its own
query_id: `HashJoin` updates the entry without a lookup and skips an equal
one. In the flaky check 7 of 300 runs printed 0 for the oracle this way.

Run the first query once more after it has finished, when its entry is
cached, and count the log rows of both runs. Locally, 64 or 96 concurrent
runs on a fresh server: 16 of 160 runs failed before, 0 of 288 after (14 of
them logged nothing for the first query and were covered by the second).
With `collect_hash_table_stats_during_joins = 0` the oracle still prints 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@murphy-4o murphy-4o self-assigned this Nov 6, 2026
@murphy-4o
murphy-4o added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit b51445e Nov 6, 2026
185 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 6, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Nov 6, 2026
Cherry pick #129184 to 26.10: Hash each node of an ActionsDAG once, fixing a planning hang in the hash table statistics key
robot-clickhouse added a commit that referenced this pull request Nov 6, 2026
…ng a planning hang in the hash table statistics key
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 6, 2026
murphy-4o pushed a commit that referenced this pull request Nov 6, 2026
…ild loop

The conflict resolution of the cherry-pick (#129668) kept the old body of
Node::updateHash as the new updateOwnHash, so:

- updateOwnHash is defined in ActionsDAG.cpp but not declared in
  ActionsDAG.h (the declaration came with #126148, which is not on 26.10),
  and the build fails with "no member named 'updateOwnHash'".
- updateOwnHash still ends with the recursion over the children, so each
  per-node digest re-hashes the whole subtree and the planning hang of
  #126250 stays.

Add the declaration as on master and remove the loop. The tree now equals
26.10 + #129184 with only the #126148 updateOwnHash split, as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 6, 2026
Backport #129184 to 26.10: Hash each node of an ActionsDAG once, fixing a planning hang in the hash table statistics key
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…ng a planning hang in the hash table statistics key
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…ild loop

The conflict resolution of the cherry-pick (#129668) kept the old body of
Node::updateHash as the new updateOwnHash, so:

- updateOwnHash is defined in ActionsDAG.cpp but not declared in
  ActionsDAG.h (the declaration came with #126148, which is not on 26.10),
  and the build fails with "no member named 'updateOwnHash'".
- updateOwnHash still ends with the recursion over the children, so each
  per-node digest re-hashes the whole subtree and the planning hang of
  #126250 stays.

Add the declaration as on master and remove the loop. The tree now equals
26.10 + #129184 with only the #126148 updateOwnHash split, as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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. 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.

getOutputIdentity hashes shared nodes per path: planning hangs at defaults

5 participants