Repository navigation
Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache) - #108553
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-7:20260625-200200 |
|
cc @maxjustus @novikd — could you review this? It fixes the |
| IdentifierResolveResult result = it->second.result; | ||
| if (cached_original) | ||
| *cached_original = result.resolved_identifier; | ||
| result.resolved_identifier = result.resolved_identifier->clone(); |
There was a problem hiding this comment.
@groeneai the whole point of the PR was to avoid unnecessary query tree copying (it's expensive operation for complex queries with extensive alias usage). Investigate other options for a fix.
There was a problem hiding this comment.
yeah this will completely kill the performance win of the cache
|
Agreed, cloning on every hit defeats the cache. Reworking to keep the no-copy fast path and fix the real defect instead.
Guarding the append against an already-present conjunct makes the pass idempotent, so the cache can keep returning shared nodes by reference (no copying) and cache on/off produce identical trees. Pushing shortly. |
tryOptimizeAndCompareChain appended a derived transitive conjunct to the
AND with push_back and never checked whether an equal conjunct was already
present, so the optimization was not idempotent.
The identifier resolve cache (enable_identifier_resolve_cache, on by
default) can hand the same resolved expression node to several use sites
(projection, HAVING, GROUP BY key). The logical-expression optimizer
visitor does not deduplicate shared nodes, so a shared AND was visited once
per parent and accumulated the same derived conjunct on every visit
(2-arg and -> 4-arg) while a singly-referenced GROUP BY key copy stayed
3-arg. GROUP BY keys are matched against the projection by formatted name,
so the two no longer matched and the query failed with
NOT_FOUND_COLUMN_IN_BLOCK on valid queries using default settings, e.g.
SELECT a FROM numbers(2)
GROUP BY ((number >= materialize(5)) AND (0 >= number)) AS a HAVING a
The sibling rewrites (tryOptimizeAndEqualsNotEqualsChain,
tryReplaceOrEqualsChainWithIn) replace the argument list rather than
appending, so they were already idempotent; this was the only offender.
The fix tracks the conjuncts already present in the AND and appends a
derived one only when an equal conjunct is not there yet. The pass is now
idempotent, so the result is independent of node sharing and the resolve
cache keeps returning shared nodes without copying.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
701fe2d to
e73f84e
Compare
|
Pushed the reworked fix (e73f84e). The cache fast path is untouched: PR shrank from 36 files to 3 (the 30 Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-7:20260625-222100 |
|
Workflow [PR], commit [86ea111] Summary: ✅
AI ReviewSummaryThis PR fixes a default-settings analyzer regression where Final VerdictStatus: ✅ Approve |
CI finish ledger — e73f84eEvery failed check below has an owner (a fixing PR).
Not PR-caused: this PR only changes Session id: cron:our-pr-ci-monitor:20260626-033000 |
novikd
left a comment
There was a problem hiding this comment.
It seems like tryOptimizeAndCompareChain can be significantly improved, but it lays out of scope of this PR>
|
@groeneai, merge the fresh master into this branch. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 12/12 (100.00%) | Lost baseline coverage: none · Uncovered code |
c113b69
Cherry pick #108553 to 26.6: Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache)
…(fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache)
Backport #108553 to 26.6: Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache)
…ifier-resolve-cache-shared-node-108518 Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache)
`ORDER BY ALL` and `GROUP BY ALL` put the projection node itself into ORDER BY / GROUP BY, and the identifier resolve cache returns the cached node for a reused alias, so one `tupleElement(n, K)` node can be reached from several clauses. `PruneArrayJoinColumnsPass` rewrites the numeric index of such a node in place through `index_remap` on every visit, and its only "already done" check (the column type comparison) comes after the rewrite. With `n.a` pruned (remap 2 -> 1, 3 -> 2), `tupleElement(n, 3)` became 2 on the first visit and 1 on the second, so it read `n.b` while its resolved type was still `n.c`'s. Depending on which action node the planner reused, this returned the wrong subcolumn (`SELECT tupleElement(n, 2), tupleElement(n, 3) FROM t ARRAY JOIN n ORDER BY ALL` gave `n.b` twice on 26.6-26.9), threw `Unexpected return type from tupleElement` (a LOGICAL_ERROR on debug builds, found by the AST fuzzer), or `NOT_FOUND_COLUMN_IN_BLOCK` for the cached-alias shape. Record every tupleElement node the visitor has processed and skip a node it reaches again, so each node is remapped exactly once from its original index, the only index `index_remap` is defined on. This is the same per-pass idempotency shape as `ConvertOrLikeChainPass`'s `processed_nodes` and the merged fix for `tryOptimizeAndCompareChain` (ClickHouse#108553); cloning at the sharing sites was rejected there because the identifier resolve cache exists to avoid query tree copies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mizerPass With enable_identifier_resolve_cache = 1 (default since 26.6) the cached resolved node of an alias is returned by reference, so every reference to an alias (GROUP BY, ORDER BY, HAVING, WHERE, another alias) is one node, while the projection's own alias expression and each alias expression resolved for an identifier are separate copies that share the alias reference nodes inside them. The query tree is a DAG, and the planner needs both copies of an expression to be rewritten to the same name. LogicalExpressionOptimizerVisitor rewrote a node in enterImpl, before its arguments were visited, and the rewrites read the argument subtrees (the compare chain reads nested `and` arguments through the flattened view; the not-equals, OR->IN and redundant-equals rewrites read their operands). So the result depended on the path: a shared node was rewritten once per reference and the rewrites are not idempotent, a node installed into a slot was never entered, and two copies of an outer alias could be entered on opposite sides of the in-place rewrite of a shared inner alias. The GROUP BY key and the projection then differed by name and the query failed with NOT_FOUND_COLUMN_IN_BLOCK, e.g. SELECT (((s = '1') = 1) = 1) AND (n > 0) AS r FROM t GROUP BY r ORDER BY r SELECT (x AND s = '1') AS a, (n <= 3 AND n != 3 AND length(s) <= n) AS x FROM t GROUP BY x, a ORDER BY x, a The and/or/equals rewrites now run in leaveImpl, after every argument slot holds its final value, and a memo maps each visited node to its result so that every other reference is pointed at that result instead of being visited again. The result of a node then depends only on its original subtree. The JOIN ON visitor still runs in enterImpl. Independently, tryExtractCommonExpressions wrote the flattened `and` back into the original `or` argument, so the WHERE-only common-expression rewrite mutated a node shared with GROUP BY. It now reads it through a local reference. No cloning, the per-pass shape of ClickHouse#108553. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `enable_identifier_resolve_cache` (default since 26.6) every reference
to an alias resolves to the same query tree node, so in
SELECT sumIf(2, number > 1) AS r, r + 0, r + 1 FROM numbers(12)
SELECT sumIf(2, number > 1) AS r FROM numbers(12) HAVING r > 3 AND r < 15
all references share one `sumIf(2, number > 1)` node. `SumIfToCountIfPass`
rewrote the node it visited in place into `countIf(number > 1)` and wrapped
only that reference in `multiply(2, ...)`. Every later reference then saw
`countIf`, failed the `sum`/`sumIf` entry check and kept the bare `countIf`,
so it lost the factor: `r + 1` returned 11 instead of 21, and the HAVING
compared `countIf` with 15 and returned the row. The same happened for
`sum(if(cond, 0, k))` at default settings and for `sum(if(cond, k, 0))`
with `optimize_rewrite_aggregate_function_with_if = 0`.
The pass now leaves the visited node unchanged and assigns a new `countIf`
node (wrapped in `multiply` when the constant is not 1) to each reference,
like `RewriteAggregateFunctionWithIfPass` does. Every reference is rewritten
on its own visit, and the tree with the cache on is the same as with it off.
Cloning shared nodes in the cache was rejected in ClickHouse#108553, which made the
pass it fixed independent of node sharing instead.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `enable_identifier_resolve_cache` the GROUP BY key and its ORDER BY, HAVING and WHERE references are one shared node, while the projection keeps its own copy. `RegexpFunctionRewritePass` enters the shared node once per reference, and `handleExtract` removed one trailing `.*$` per visit, so for a pattern such as `(1).*$.*$` the shared node ended with `(1)` and the projection with `(1).*$`. The GROUP BY key then no longer matched the projection and the query failed with NOT_FOUND_COLUMN_IN_BLOCK. Remove all trailing unescaped `.*$` in a single visit, so a repeated visit is a no-op. The escape check is evaluated for each tail; `disablesDotAll` and `endsInsideQuotedLiteral` are evaluated once on the original pattern, which is equivalent because removing a trailing `.*$` adds or removes no `(` and no `\E`. This is the per-pass shape of ClickHouse#108553; cloning at the cache was refused there. Related: ClickHouse#122404 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #108518
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
NOT_FOUND_COLUMN_IN_BLOCKwhen a compound predicate is aliased inGROUP BYand referenced again, withenable_identifier_resolve_cacheenabled (the default). Theoptimize_and_compare_chainoptimization was not idempotent and a shared resolved node accumulated a duplicate transitive conjunct.Description
tryOptimizeAndCompareChainappended a derived transitive conjunct to theANDwithpush_backwithout checking whether an equal conjunct was already present, so the pass was not idempotent.enable_identifier_resolve_cache(on by default) can hand the same resolved expression node to several use sites (projection,HAVING,GROUP BYkey). The logical-expression optimizer visitor does not deduplicate shared nodes, so a sharedANDwas visited once per parent and accumulated the same derived conjunct on every visit (2-argand-> 4-arg), while a singly-referencedGROUP BYkey copy stayed 3-arg.GROUP BYkeys are matched against the projection by formatted name, so the two no longer matched and the query failed:The sibling rewrites (
tryOptimizeAndEqualsNotEqualsChain,tryReplaceOrEqualsChainWithIn) replace the argument list rather than appending, so they were already idempotent; this was the only offender.The fix tracks the conjuncts already present in the
ANDand appends a derived one only when an equal conjunct is not there yet. The pass is now idempotent, so the result is independent of node sharing and the resolve cache keeps returning shared nodes without copying (its fast path is preserved).optimize_and_compare_chainstill fires; the transitive conjunct is added once, and trees are identical with the cache on and off.Version info
26.7.1.116(included in26.7and later)26.6.2.8