Repository navigation
Bound the query-analysis cost of optimize_and_compare_chain (and the lambda-resolution recursion guard) - #108757
Conversation
…not tree hash) QueryAnalyzer::resolveLambda used `lambdas_in_resolve_process`, a QueryTreeNodePtrWithHashSet, as a recursion guard. QueryTreeNodeWithHash eagerly computes the full IQueryTreeNode::getTreeHash (a complete, uncached walk of the lambda body subtree) on every find/emplace/erase. For queries with many large lambdas this dominates query analysis: profiling a 173-lambda expression showed ~80% of analysis time in getTreeHash, all under resolveLambda. The guard only needs to detect re-entry into the same (original, un-cloned) lambda node; a recursive reference resolves to the same alias node, so node pointer identity is sufficient and correct. Switched the set to std::unordered_set<const IQueryTreeNode *>. This also removes a latent risk of a false "Recursive lambda" error on two structurally-identical lambda nodes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
LogicalExpressionOptimizerPass::tryOptimizeAndCompareChain groups AND-chain comparisons using QueryTreeNodePtrWithHash containers, each of which computes a full (uncached) IQueryTreeNode::getTreeHash of the operands/conjuncts. On queries with very many or very large AND-comparison chains (e.g. a SQL ray tracer whose operands are big let-expanded expressions) this hashes a large fraction of the query tree for every AND node and dominates query analysis -- a 16x16 render spends ~72s in analysis -- while typically folding nothing. Bound it by the actual hashing work: getTreeHash now accumulates the number of nodes it visits into a thread-local counter, and the visitor snapshots that counter at start and stops the optimization for the rest of the query once it has hashed more than 5M nodes. Counting inside getTreeHash measures the real cost directly, so no separate tree-size estimation is needed. Stopping early is always safe -- it only forgoes an optimization, never changes results. Effect (16x16 SQL ray-trace, default settings): analysis ~72s -> ~3s (~24x), byte-identical output. Normal queries hash only thousands of nodes, never reach the budget, and are unaffected (verified the transitive-comparison derivation still fires). The threshold could later be exposed as a setting. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [01a56fe] Summary: ✅
AI ReviewSummaryThis PR bounds Final VerdictStatus: ✅ Approve |
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes query-analysis behavior: it adds a work budget to the optimize_and_compare_chain optimization (which only matters for queries with very large AND-chains of comparisons) and reuses a lambda-resolution hash. ClickBench Q4, Q15, and Q28 have simple WHERE clauses and no lambdas, so they never hit the budget or the lambda path, and analysis time is a tiny fraction of their runtime. The flagged 15-16% improvements on Q4/Q15 and 5% on Q28 are too large to come from an analyzer micro-optimization on queries that don't exercise it, so all three were downgraded to not-sure as off-path variance. No regressions were found. clickbenchFlagged queries (3 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
The previous commit changed `lambdas_in_resolve_process` to a `std::unordered_set<const IQueryTreeNode *>` keyed by pointer identity. That is incorrect: a recursive lambda reference resolves to a *fresh clone* of the alias node (`tryResolveIdentifierFromAliases` clones the alias body), so the recursive node is only structurally equal to the one being resolved, never the same pointer. With pointer identity the guard never fires for genuine recursion, and the query instead recurses until `TOO_DEEP_RECURSION`. This regressed `02388_analyzer_recursive_lambda` and `02343_analyzer_lambdas`, where recursive `WITH`-lambdas are expected to throw `UNSUPPORTED_METHOD` (`Recursive lambda`). Restore the structural-hash guard (`QueryTreeNodePtrWithHashSet`) so recursion is detected correctly, but address the original performance problem by computing the lambda's tree hash only once per `resolveLambda` call: a single `QueryTreeNodePtrWithHash` is built and reused for the `contains`/`insert`/`erase`, instead of constructing a fresh one for each operation (which recomputed the full `getTreeHash` three times). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…olve-recursion-guard
Address review feedback from `clickhouse-gh`: the work-budget check only guarded the entry of `tryOptimizeAndCompareChain` and the DFS in `findPairs`, but the map-building phase between them inserts every comparison operand into `QueryTreeNodePtrWithHash` containers (and the existing conjuncts into a `QueryTreeNodePtrWithHashSet`), each insert computing a full `getTreeHash`. For a single very large `AND` chain that phase could hash the whole operand set before any later budget check, so the cap did not apply to exactly the "many or very large `AND`-chains" case it targets. Check the budget while collecting `greater_pairs`/`less_pairs` and `existing_conjuncts` and abort as soon as it is crossed. Aborting there is safe -- no conjunct has been appended to the `AND` yet, so the optimization is merely skipped and results are unchanged. The repeated condition is factored into a small `andCompareChainHashBudgetExceeded` helper. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…olve-recursion-guard
The `optimize_and_compare_chain` work budget was a hard-coded 5M constant, which made it impossible to exercise the budget back-off path in a fast, deterministic functional test (triggering it otherwise needs a multi-megabyte query). Expose it as the new setting `optimize_and_compare_chain_max_hash_work` (default `5000000`, `0` disables the budget), as the PR description anticipated. The visitor now reads the budget from the setting instead of the constant, and `andCompareChainHashBudgetExceeded` treats `0` as unlimited so the optimization is never stopped early in that case. Behavior is unchanged at the default. Add `04490_optimize_and_compare_chain_work_budget`: it asserts that a large `AND`-chain of comparisons returns identical results across the default budget, a budget of `1` (which forces the optimization to back off, including during operand collection), an unlimited budget, and the optimization disabled -- the budget only forgoes redundant derived predicates, never changes results. It also asserts, via `EXPLAIN QUERY TREE`, that a large budget expands the transitive chain (more `less` comparisons) than a budget of `1`, proving the budget actually controls whether the optimization fires. This addresses the `clickhouse-gh` AI review "Request changes": the budget now provably covers the map/set-building phase and there is focused, deterministic evidence for the pathological `AND`-chain case. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed updates addressing the failing Fast test and the AI review ("Request changes"):
|
…in_max_hash_work The `SettingsChangesHistory.cpp` entry for the new `optimize_and_compare_chain_max_hash_work` setting recorded `5'000'000` as both the previous and the new value. Before this setting existed the `optimize_and_compare_chain` optimization was uncapped, which this PR defines as `0` (unlimited). Recording the previous value as `5'000'000` meant `SET compatibility = '26.6'` kept the new cap instead of restoring the old behavior, so compatibility mode could still stop deriving transitive predicates for huge `AND` chains. Record the previous value as `0` so `compatibility` set to a pre-26.7 version reproduces the original uncapped behavior. Extend `04490_optimize_and_compare_chain_work_budget` with an assertion that `compatibility = '26.6'` reverts the budget to `0`. Addresses the AI review finding on `SettingsChangesHistory.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed 7074a41 addressing the AI review's only "Request changes" finding ( What changed. The history entry for the new Added that assertion to Remaining red —
None of the failure output references The sync will re-run on 7074a41 once it propagates to the sync branch; the failing jobs are flaky/infra and should clear on a rerun. |
`04490_optimize_and_compare_chain_work_budget` collided with two tests that landed on `master` after this branch's merge-base (`04490_dict_get_keys_float_signed_zero_consistency` and `04490_table_readonly_partition_commands`); `04491` is also taken on `master`. Renumber to the next free prefix `04492`. Test content is unchanged (a pure file rename). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed Why. State of the rest of the PR (head before this push,
The two red checks are pre-existing, master-wide flakes, not caused by this PR (which only touches query analysis):
No master re-merge: merge-base |
|
The fresh CI run on
This is a different red from the two flakes noted on the previous run ( Otherwise the PR is ready: AI Review is ✅ Approve, there are no unresolved review threads, and it is |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 69/72 (95.83%) · Uncovered code |
|
The parent CI workflow run on `01a56fec584` has finished, so I re-ran its only failed job — `AST fuzzer (amd_debug, targeted)` — which is now in progress (run 28473939037). That single red is the chronic master-wide AST-fuzzer flake No re-merge: merge-base |
|
Follow-up to the previous comment: the re-run of The PR is now fully green — all AST-fuzzer variants, |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Very good change.
…resolve-recursion-guard Bound the query-analysis cost of optimize_and_compare_chain (and the lambda-resolution recursion guard)
`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]>
Link to ray tracer: https://github.com/ClickHouse/RayTracer
Query analysis can be dominated by
IQueryTreeNode::getTreeHashfor queries whoseWHERE/HAVINGcontain many or very largeAND-chains of comparisons.getTreeHashis an uncached, whole-subtree walk, and two analyzer sites call it once per node over big subtrees, so the cost grows with the size of the expression tree rather than the data.This surfaced in an extreme way on a SQL ray tracer (a single
SELECTbuilt from ~30 nested lambdas andarrayFold, whose comparison operands are huge let-expanded expressions): even a 16×16 image spent ~72 s in query analysis, ~80 % of it ingetTreeHash. Profiling traced it to two places, fixed here:1.
optimize_and_compare_chain(LogicalExpressionOptimizerPass::tryOptimizeAndCompareChain). It groupsAND-chain comparisons usingQueryTreeNodePtrWithHashcontainers, each of which eagerly computes the full tree hash of the operands/conjuncts. On a scene with many largeANDvalidity checks it hashes a large fraction of the (already huge) tree for everyANDnode, while typically folding nothing. It is now bounded by a work budget measured directly in nodes hashed:getTreeHashaccumulates the number of nodes it visits into a thread-local counter, and the visitor stops the optimization for the rest of the query once it has hashed more nodes than the budget. Counting inside the hash walk measures the real cost without a separate tree-size pass. Stopping early is always safe — it only forgoes an optimization, never changes results. The budget is checked at the entry of the optimization, while collecting comparison operands and existing conjuncts (the map/set-building phase, where each insert hashes an operand), and inside the DFS, so a single very largeANDchain cannot hash its whole operand set before the cap applies. The budget is exposed as the new settingoptimize_and_compare_chain_max_hash_work(default5000000;0disables it).2.
QueryAnalyzer::resolveLambdarecursion guard. This guard (lambdas_in_resolve_process) must detect re-entry by structure, not by pointer identity: a recursive lambda reference resolves to a fresh clone of the alias node (tryResolveIdentifierFromAliasesclones the alias body), so the recursive node is only structurally equal to the one being resolved, never the same pointer. It therefore stays aQueryTreeNodePtrWithHashSet, but the original performance problem — everyfind/emplace/eraserecomputing the full tree hash of the (un-cloned) lambda body — is fixed by computing that hash only once perresolveLambdacall: a singleQueryTreeNodePtrWithHashis built and reused for thecontains/insert/erase.Effect on the ray-tracer (16×16, default settings): query analysis ~72 s → ~3 s, byte-identical output. Normal queries hash only thousands of nodes, never reach the budget, and are unaffected (verified the transitive-comparison derivation still fires, and that recursive
WITH-lambdas still throwUNSUPPORTED_METHOD).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Sped up query analysis for queries with many or very large
AND-chains of comparisons: theoptimize_and_compare_chainoptimization is now bounded by a work budget (new settingoptimize_and_compare_chain_max_hash_work) instead of hashing a large fraction of the query tree, and lambda resolution no longer recomputes lambda-body hashes for its recursion guard.