Skip to content

Do not rebuild nested ANDs at every level in optimize_and_compare_chain - #131479

Merged
fm4v merged 1 commit into
ClickHouse:masterfrom
groeneai:and-compare-chain-flatten-without-resolve
Nov 16, 2026
Merged

fm4v merged 1 commit into
ClickHouse:masterfrom
groeneai:and-compare-chain-flatten-without-resolve

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131134
Related: #131361

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 a condition written as a deeply nested AND tree, such as ((a AND b) AND c) AND ..., when optimize_and_compare_chain is enabled (the default).

Description

With optimize_and_compare_chain, analysis of the nested-AND workload in #131134 (a left-deep WHERE ((((a AND b) AND c) AND ...) of ~105 comparisons) is 10x slower on 26.10 (23x on master here); the same conjuncts as a flat AND are not affected, and optimize_and_compare_chain_max_hash_work does not bound it.

tryOptimizeAndCompareChain runs for every and node of the tree. It read its operands through getFlattenedLogicalExpression, which recursively built and resolved (function lookup plus a signature check over all arguments) a throw-away and node at every nested level: O(k^2) argument checks per call on a depth-k subtree, ~O(n^3) for the whole chain.

The new collectFlattenedLogicalArguments collects the flattened operands without creating nodes. getFlattenedLogicalExpression uses it and builds and resolves only the top node; tryOptimizeAndCompareChain uses the list directly. The operands (same nodes, same order) are unchanged, and so is the query tree: EXPLAIN QUERY TREE and results are byte-identical between master and this PR on the #131134 workloads and on nested derivation cases.

QueryAnalysisMicroseconds, RelWithDebInfo clickhouse local, median of 7 interleaved runs:

query master this PR
nested AND, defaults 163.5 ms 47.1 ms
nested AND, compatibility = '24.10' (chain off) 7.2 ms 6.8 ms
flat AND, chain on 8.6 ms 9.1 ms
inlined CTEs from #131134, defaults 331.5 ms 333.2 ms

Together with #131361 (per-operand hashing, the inlined-CTE shape of #131134) the nested query takes 22.8 ms.

Tests: new performance test analyzer_and_compare_chain_nested_and.xml; 04032_and_comparison_filter_optimization_2 gets a case whose derivation needs a conjunct two levels deep (fails if the flattening is not recursive).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2444-master (included in 26.11 and later)
  • Backported to: 26.10.5.32

…chain`

`tryOptimizeAndCompareChain` runs for every `and` node, so a left-deep
`((a AND b) AND c) AND ...` chain of depth n gets n calls. Each call read
its operands through `getFlattenedLogicalExpression`, which recursed into
every nested same-name function and, at every level that had nested
children, built a throw-away `FunctionNode` and resolved it
(`FunctionFactory::get` plus a variadic signature check over all its
arguments). A call on a depth-k subtree did O(k^2) argument checks, the
chain ~O(n^3); `optimize_and_compare_chain_max_hash_work` counts only tree
hashing, so it never bounded this.

`collectFlattenedLogicalArguments` collects the same operands (same nodes,
same order) without creating any node. `getFlattenedLogicalExpression`
uses it and builds and resolves only the top node, which also serves
`optimize_extract_common_expressions`; the compare chain uses the list
directly. The query tree is unchanged.

The nested-AND repro from ClickHouse#131134 (~105 levels, RelWithDebInfo, median
QueryAnalysisMicroseconds of 7 interleaved runs): 163.5 ms -> 47.1 ms at
defaults, 7.2 ms with the chain off; flat AND and the inlined-CTE repro
unchanged. EXPLAIN QUERY TREE and results byte-identical master vs this
change on 13 cases.

Adds a performance test with that query, and a 04032 case whose
derivation needs a conjunct two levels deep, which fails if the
flattening stops at one level.

Closes ClickHouse#131134

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; 0 findings) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 The perf test's budget variants (0 and 5000000) run the same code path DISAGREE both are real configurations: compatibility below 26.7 sets the budget to 0, the default is 5000000; measured equal gain on both (167 -> 49 ms, 165 -> 48 ms)
2 💡 The fixed perf query (~47 ms locally) is under 0.1 s, a common source of unstable verdicts DISAGREE 7 interleaved runs spread 45.9-47.9 ms; CPU-bound analysis with no I/O

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

Session id: cron:clickhouse-review-slot-9:20261113-225700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The nested-AND query from #131134, compatibility = '24.10', optimize_and_compare_chain = 1, RelWithDebInfo clickhouse local: QueryAnalysisMicroseconds 167 ms on master vs 7 ms with the chain off, 7 of 7 interleaved runs.
b Root cause explained? tryOptimizeAndCompareChain runs for every and node; each call flattened its operands with getFlattenedLogicalExpression, which built and resolved a throw-away and node at every nested level (O(k^2) signature checks per call, ~O(n^3) per chain). The hash budget does not count this work.
c Fix matches root cause? Yes. The flattened operands are collected without creating or resolving intermediate nodes; only the top node is still built where a caller needs a node. No limit, no guard.
d Test intent preserved / new tests added? New performance test analyzer_and_compare_chain_nested_and.xml (budget 0 and 5000000). 04032_and_comparison_filter_optimization_2 extended (additions only) with a derivation that needs a conjunct two levels deep; no existing query or reference changed.
e Both directions demonstrated? Analysis 167 ms -> 49 ms (chain off: 7 ms). EXPLAIN QUERY TREE and results byte-identical master vs PR on 13 cases. The new test case passes on master and on the PR, and fails with a one-level-only or no flattening (mutations).
f Fix is general across code paths? Both consumers go through the one helper: the compare chain and optimize_extract_common_expressions (WHERE / PREWHERE / JOIN ON). tryOptimizeAndCompareNotEqualsChain reads only direct arguments; no other caller.
g Fix generalizes across inputs (params/datatypes/wrappers)? A query-tree structure change, independent of types: and and or, single-argument nested and(x), flat chains, nesting depth 25 to 105, budget 0 and default. The related stateless tests (46) pass with randomized settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default, or format change; the produced query tree is unchanged.
i Invariants and contracts preserved? Same operand nodes in the same order; getFlattenedLogicalExpression returns no node in exactly the same cases; the collected list holds strong references; the AND node is not modified while the list is read; recursion depth is the nesting depth, as before.

Session id: cron:clickhouse-impl-slot-40:20261113-214900

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e03c2b8]

Summary: ✅


AI Review

Summary

The PR speeds up analysis of deeply nested AND expressions by collecting flattened operands without constructing and resolving intermediate logical nodes. The current code preserves operand identity and order for comparison derivation and common-expression extraction. The supplied before/after measurements and focused regression coverage support the performance claim; the updated stateless test passes in CI. No actionable findings.

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 labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e03c2b869 with master 2b1bef1d3 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.61, programs/clickhouse-keeper ×0.69 (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 _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.4 s +5.2 s (+234%)
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

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Nov 14, 2026
@fm4v
fm4v added this pull request to the merge queue Nov 16, 2026
Merged via the queue into ClickHouse:master with commit fa13215 Nov 16, 2026
608 of 610 checks passed
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 16, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 16, 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 16, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 16, 2026
Backport #131479 to 26.10: Do not rebuild nested `AND`s at every level 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.

optimize_and_compare_chain=1 makes analysis of large inlined CTE trees 3.5x slower

5 participants