Skip to content

Hash each AND-chain operand once in optimize_and_compare_chain - #131361

Merged
fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:and-compare-chain-hash-operands-once
Nov 16, 2026
Merged

fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:and-compare-chain-hash-operands-once

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Query analysis is faster for queries whose AND chains of comparisons read columns of large subqueries, such as many inlined CTEs: optimize_and_compare_chain now hashes each operand once instead of on every lookup. Analysis of the query from #131134 is 2x faster with the work budget off and 1.5x faster at default settings.

Description

optimize_and_compare_chain = 1 made analysis of the query in #131134 (9 levels of inlined CTEs, each a self-join with an AND chain of comparisons) 3.5x slower.

tryOptimizeAndCompareChain keyed its maps and sets by QueryTreeNodePtr and passed raw nodes through its DFS, so every lookup recomputed getTreeHash. The hash of a column includes its source, and every operand is a column of an inlined subquery, so each lookup walked a whole subquery: 16.6M nodes hashed for a 15K-node tree.

Each operand is now hashed once per call. A lookup by an already computed key is still charged that key's hash work, and a lookup of an existing conjunct its full hash work, so optimize_and_compare_chain_max_hash_work still bounds the chain traversal. Existing conjuncts of the shape of every derived one, comparison(operand, constant), are indexed by operand and constant; other conjuncts are no longer hashed, so an AND close to the budget may now fit in it.

On the issue query (EXPLAIN QUERY TREE is byte-identical before and after at depths 1 to 8, budget off and at defaults):

  • with the budget off (compatibility before 26.7, as in the issue), median QueryAnalysisMicroseconds 697 ms -> 350 ms (chain off: 203 ms);
  • at default settings the derivation is still dropped; analysis 327 ms -> 212 ms;
  • the second workload from the issue (countIf chains over window-function and ARRAY JOIN subqueries, compatibility = '24.10'): analysis 90 ms -> 39 ms (chain off: 28 ms).

The 28 stateless tests of the optimization pass 3 randomized runs. 04492_optimize_and_compare_chain_work_budget now also checks that the budget bounds the chain traversal. The new performance test runs the issue query with the budget off and at the default: 1.39 s -> 0.71 s and 0.65 s -> 0.46 s locally.

Related: #131134
Related: #108757

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2445-master (included in 26.11 and later)
  • Backported to: 26.10.7.18

groeneai and others added 6 commits November 13, 2026 07:24
`tryOptimizeAndCompareChain` keyed every container (comparison pairs,
constants, visited set, derived-conjunct filters, existing conjuncts) by
`QueryTreeNodePtr` and passed raw nodes through the DFS, so every lookup
re-ran `getTreeHash`. The hash of a column also hashes its source, so when
the operands are columns of a large inlined subquery (many non-materialized
CTEs) each lookup walks the whole subquery: about 30 walks per chain for 5
distinct operands. On the query from ClickHouse#131134 (CTE depth 8) the visitor
hashed 16.6M nodes for a 15K-node tree.

Compute a `QueryTreeNodePtrWithHash` once per operand per call and pass the
key through the containers and the DFS (the pattern ClickHouse#108757 used for
`resolveLambda`). The existing-conjunct sets hashed every conjunct and
every candidate; a derived conjunct is always `comparison(operand,
constant)`, so index existing conjuncts of that shape by the key of their
first argument and decide with `isEqual` inside the bucket. The derived set
is unchanged.

Nodes hashed for the ClickHouse#131134 query drop from 16.6M to 3.4M, which is below
the default `optimize_and_compare_chain_max_hash_work` budget, so at
default settings the derivation now completes instead of being reverted.
With the budget off (`compatibility` before 26.7) query analysis is 2.1x
faster.

Related: ClickHouse#131134

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Hashing each operand once removed every `getTreeHash` call from the DFS of
`tryOptimizeAndCompareChain`, so `optimize_and_compare_chain_max_hash_work`
no longer bounded the traversal. Each DFS step now charges the budget the
hash work its precomputed key took, which is what the step used to pay for
looking the operand up.

Related: ClickHouse#131134

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…by operand and constant

A lookup by an operand key that `tryOptimizeAndCompareChain` already
computed is charged the hash work of that key, so
`optimize_and_compare_chain_max_hash_work` counts what it counted when
every container access re-hashed the operand. Existing conjuncts of the
shape `comparison(operand, constant)` are indexed by operand key and then
constant key, so deduplicating a derived conjunct no longer scans every
conjunct written on the same operand.

Related: ClickHouse#131134

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in work budget, as hashing the whole conjunct did.

Related: ClickHouse#131134

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rewrite the operand-key memo comment as a standalone statement (drop the reference to the previous budget accounting).

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-5)
Finding Verdict
⚠️ Reusing precomputed keys stopped charging optimize_and_compare_chain_max_hash_work, so a long chain reachable from many constants ran unbounded AGREE, fixed: a lookup by an already computed key is charged the hash work of that key, as each lookup hashed before
⚠️ A per-step charge below the old per-lookup count let queries that used to exceed the default budget keep the derivation, slower in total AGREE, fixed by the same rule; the issue query's tree at defaults is unchanged
⚠️ Deduplicating derived conjuncts scanned all conjuncts on an operand, uncharged (16x slower than before on a 1200 x 1200 chain at defaults) AGREE, fixed: conjuncts are indexed by operand and constant
⚠️ A conjunct lookup was charged 3 nodes less than hashing the whole conjunct (the comparison node and its two lists), so a chain at the budget ran longer than before AGREE, fixed: each conjunct lookup is charged those nodes
⚠️ The second workload posted on the issue was not measured AGREE, measured; result stated in the description
⚠️ Passing a raw node to the key-taking addComparisonFilter made tryOptimizeAndCompareNotEqualsChain hash the operand of a comparison it folds away (e.g. UInt8 column < 256), which it did not hash before AGREE, fixed: a raw node is hashed only when the filter map is accessed, as before
⚠️ The perf test runs with the budget off and does not assert the derivation DISAGREE: the measured query yields 512 indexHint under the test's settings; derivation correctness is covered by the existing stateless tests, and the budget path by the extended 04492
💡 The setting description says the budget counts nodes hashed by getTreeHash, while reused keys are charged without hashing DISAGREE: the charge keeps the unit the description states (what hashing on each lookup visited)
💡 tryOptimizeAndCompareNotEqualsChain still hashes its operands per lookup Out of scope: it runs whether or not optimize_and_compare_chain is enabled

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A binary search over optimize_and_compare_chain_max_hash_work for the smallest budget that keeps the full derivation gives exact per-depth counts for the issue query (depth 8: 16,599,089 before, 15,010,804 after, so the budget still drops the derivation at the default); timing medians are interleaved, n=10.
b Root cause explained? tryOptimizeAndCompareChain keyed its containers by QueryTreeNodePtr and carried raw nodes through the DFS, so every lookup recomputed getTreeHash. A column's hash includes its source, here an inlined CTE subquery, so each lookup walked a whole subquery (about 30 walks per chain for 5 distinct operands).
c Fix matches root cause? Yes. Each operand is hashed once per call; a lookup by an already computed key is charged that key's hash work, and a lookup of an existing conjunct its full hash work, so the budget keeps its meaning. Existing comparison(operand, constant) conjuncts are indexed by operand and constant. No setting or getTreeHash change. addComparisonFilter hashes a raw node only on map access, as before, so its other caller's boundary-folded comparisons are not hashed.
d Test intent preserved / new tests added? New performance test analyzer_and_compare_chain_inlined_ctes.xml (the issue query with the budget off and at the default). 04492_optimize_and_compare_chain_work_budget gains one assertion that the budget bounds the chain traversal; no existing line changed.
e Both directions demonstrated? Issue query QueryAnalysisMicroseconds median 697 ms -> 350 ms with the budget off and 327 ms -> 212 ms at defaults; the issue's second workload 90 ms -> 39 ms; perf-test query 1.39 s -> 0.71 s and 0.65 s -> 0.46 s. The new 04492 assertion fails on the first commit of this PR (no DFS charge) and passes now.
f Fix is general across code paths? Every operand-keyed container access in the function goes through the same memo. The sibling tryOptimizeAndCompareNotEqualsChain hashes once per comparison-with-constant conjunct and is not changed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Only key types change, no derivation rule. EXPLAIN QUERY TREE is byte-identical for depths 1 to 8 and for lambda-argument, subquery-column and repeated-conjunct probes, with the budget off and at defaults, identifier resolve cache on and off. The 28 stateless tests of the optimization (Nullable, LowCardinality, Variant, DateTime64, outer JOIN ON, notEquals) pass 3 of 3 randomized runs.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; results unchanged.
i Invariants and contracts preserved? Equal nodes get the same key; conjunct dedup uses the same isEqual predicate inside an operand/constant bucket. Memo entries hold strong references. Budget checks, the all-or-nothing revert and the correlated-subquery guard are unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [08460ad]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
05345_robin_hood_large_hash_tables FAIL cidb IGNORED

AI Review

Summary

The PR reduces repeated operand hashing in tryOptimizeAndCompareChain and indexes existing conjuncts by operand and constant while accounting for reused keys against optimize_and_compare_chain_max_hash_work. No actionable findings in head 08460ad704214edd57e6a791f9212eb455aa9620.

Missing context / blind spots
  • ⚠️ Tests and benchmarks were not rerun locally because this checkout has no built ClickHouse binary. Runtime evidence comes from the author's reported regression runs and before/after measurements; an independent run of 04492_optimize_and_compare_chain_work_budget and analyzer_and_compare_chain_inlined_ctes.xml would close this verification gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 08460ad70 with master d89be9791 (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.

Object file sizes

4 object files changed (+39.31 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp.o 642.35 KiB 681.67 KiB +39.32 KiB (+6.12%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.66, programs/clickhouse-keeper ×0.64 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 14.5 s +10.7 s (+281%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.5 s +5.3 s (+238%)
Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 08460ad

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) / 05345_robin_hood_large_hash_tables flaky: the last line of the Robin Hood memory check printed 0 instead of 1 (the join without enable_robin_hood_hash_for_joins must peak above 1.2 times the join with it), 9/9 reruns with the same settings passed; it failed 24 times on master and in 10 other PRs in 30 days, and this PR only changes LogicalExpressionOptimizerPass.cpp and its tests; the fix merged at 21:11Z, after this run (17:28Z), so it was not in the tested tree #131362 (external, merged)
Mergeable Check, PR praktika rollups of the row above #131362 (external, merged)

CIDB has no other FAIL or ERROR row on this head (the Config Workflow / Pre Hooks rows are the runs before the can be tested label).

Session id: cron:our-pr-ci-monitor:20261113-210012

@fm4v
fm4v added this pull request to the merge queue Nov 16, 2026
Merged via the queue into ClickHouse:master with commit c14cab4 Nov 16, 2026
604 of 608 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 16, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 17, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Nov 18, 2026
Cherry pick #131361 to 26.10: Hash each `AND`-chain operand once in `optimize_and_compare_chain`
robot-clickhouse added a commit that referenced this pull request Nov 18, 2026
robot-clickhouse added a commit that referenced this pull request Nov 18, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 19, 2026
Backport #131361 to 26.10: Hash each `AND`-chain operand once in `optimize_and_compare_chain`
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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements 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