Skip to content

Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache) - #108553

Merged
novikd merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/analyzer-identifier-resolve-cache-shared-node-108518
Jun 26, 2026
Merged

novikd merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/analyzer-identifier-resolve-cache-shared-node-108518

Conversation

@groeneai

@groeneai groeneai commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #108518

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):

Fix NOT_FOUND_COLUMN_IN_BLOCK when a compound predicate is aliased in GROUP BY and referenced again, with enable_identifier_resolve_cache enabled (the default). The optimize_and_compare_chain optimization was not idempotent and a shared resolved node accumulated a duplicate transitive conjunct.

Description

tryOptimizeAndCompareChain appended a derived transitive conjunct to the AND with push_back without 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 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:

SELECT a FROM numbers(2)
GROUP BY ((number >= materialize(5)) AND (0 >= number)) AS a HAVING a;
-- Code: 10. NOT_FOUND_COLUMN_IN_BLOCK

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 (its fast path is preserved). optimize_and_compare_chain still fires; the transitive conjunct is added once, and trees are identical with the cache on and off.

Version info

  • Merged into: 26.7.1.116 (included in 26.7 and later)
  • Backported to: 26.6.2.8

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT a FROM numbers(2) GROUP BY ((number >= materialize(5)) AND (0 >= number)) AS a HAVING a fails 100% with defaults (enable_analyzer=1, enable_identifier_resolve_cache=1); passes with enable_identifier_resolve_cache=0 or the old analyzer.
b Root cause explained? The cache returned a resolved alias node by shared reference when its subtree had no QUERY/UNION. LogicalExpressionOptimizer mutates the tree in place, injecting a transitive conjunct into the shared AND at one use site (2-arg becomes 3-arg). GROUP BY keys match the projection by formatted name, so the desynced AND no longer matched -> NOT_FOUND_COLUMN_IN_BLOCK.
c Fix matches root cause? Yes. The non-cached path clones the alias body per use site; the cache violated that. findCachedIdentifier now always clones, so no node is shared and no in-place mutation can desync use sites. Targets the mechanism, not the symptom.
d Test intent preserved / new tests added? New test 04341_analyzer_identifier_cache_shared_expression_mutation covers the repro family. 04299 rewritten to assert the corrected (cache-transparent) behavior instead of node sharing. No assertion weakened.
e Both directions demonstrated? Yes. Repro fails on master (Build ID ed4daf4...), passes after the fix (Build ID 706858c2...); confirmed cache on/off now produce byte-identical resolved trees.
f Fix is general across code paths? Yes. Single shared mechanism (findCachedIdentifier); the fix subsumes the prior subquery-only clone branch. No sibling cache path left unfixed.
g Fix generalizes across inputs? Verified across AND/OR chains, three-way AND, triple-referenced alias, Nullable, LowCardinality, and the original LOGICAL_ERROR fuzzer form (STID 0250-20a8). All pass.
h Backward compatible? Yes. Restores prior correct behavior for a regression from #88043 (on shipped defaults). No setting default, on-disk, or wire format change.
i Invariants and contracts preserved? Yes. Matches the non-cached resolution invariant (independent subtree per use site). Projection names (stored keyed by node pointer) are copied from original to clone so the cache stays transparent; existing node_to_remove_aliases registration for distributed re-analysis is preserved. All 77 EXPLAIN QUERY TREE tests pass (only 3 pre-existing env-only failures, identical on master); affected EXPLAIN references are id-normalized-identical.

Session id: cron:clickhouse-worker-slot-7:20260625-200200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @maxjustus @novikd — could you review this? It fixes the enable_identifier_resolve_cache (default on) returning a resolved alias node by shared reference, which LogicalExpressionOptimizer then mutates in place, desyncing the other use sites (a GROUP BY alias AND gains a transitive conjunct at one site -> NOT_FOUND_COLUMN_IN_BLOCK, #108518). The fix makes findCachedIdentifier always clone (matching the non-cached path) and copies projection names onto the clone so the cache stays transparent.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 25, 2026
@clickhouse-gh clickhouse-gh Bot closed this Jun 25, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Jun 25, 2026
IdentifierResolveResult result = it->second.result;
if (cached_original)
*cached_original = result.resolved_identifier;
result.resolved_identifier = result.resolved_identifier->clone();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah this will completely kill the performance win of the cache

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, cloning on every hit defeats the cache. Reworking to keep the no-copy fast path and fix the real defect instead.

tryOptimizeAndCompareChain is not idempotent: it appends a derived transitive conjunct with push_back (LogicalExpressionOptimizerPass.cpp:1249) without checking whether that conjunct is already present. A node the resolve cache shares between use sites is visited once per parent by the non-deduplicating InDepthQueryTreeVisitor, so it accumulates the conjunct twice (2-arg and -> 4-arg) while the singly-referenced GROUP BY key stays 3-arg; the two no longer match by formatted name, hence NOT_FOUND_COLUMN_IN_BLOCK. The sibling rewrites (tryOptimizeAndEqualsNotEqualsChain, tryReplaceOrEqualsChainWithIn) replace the argument list instead of appending, so they are already idempotent; this one was the lone offender.

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]>
@groeneai
groeneai force-pushed the fix/analyzer-identifier-resolve-cache-shared-node-108518 branch from 701fe2d to e73f84e Compare June 25, 2026 23:14
@groeneai groeneai changed the title Fix analyzer identifier resolve cache sharing a mutated expression node Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache) Jun 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed the reworked fix (e73f84e). The cache fast path is untouched: findCachedIdentifier still returns shared nodes by reference, no cloning. The real defect was that tryOptimizeAndCompareChain appended a transitive conjunct without a presence check, so a cache-shared AND (visited once per parent by the non-deduplicating optimizer visitor) accumulated the conjunct twice while a singly-referenced GROUP BY copy stayed 3-arg. Guarding the append makes the pass idempotent; cache on/off now produce identical trees and optimize_and_compare_chain still fires.

PR shrank from 36 files to 3 (the 30 EXPLAIN QUERY TREE reference regenerations are gone, since the tree no longer changes shape).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT a FROM numbers(2) GROUP BY ((number >= materialize(5)) AND (0 >= number)) AS a HAVING a on defaults -> Code: 10 NOT_FOUND_COLUMN_IN_BLOCK.
b Root cause explained? tryOptimizeAndCompareChain appends a derived transitive conjunct with push_back and never checks for an equal one, so it is not idempotent. The resolve cache hands the same AND node to projection + HAVING; the optimizer visitor does not dedup shared nodes, so it is visited once per parent and accumulates the conjunct twice (2-arg -> 4-arg) while the singly-referenced GROUP BY key copy stays 3-arg. GROUP BY keys match the projection by formatted name -> 4 != 3 -> NOT_FOUND.
c Fix matches root cause? Yes. Track conjuncts already present in the AND; append a derived one only if an equal one is not there. Targets the non-idempotency directly; no cloning, cache fast path preserved.
d Test intent preserved / new tests added? New regression test 04341_analyzer_identifier_cache_shared_expression_mutation covers the repro plus AND/OR/3-way/Nullable variants and an EXPLAIN QUERY TREE idempotency assertion (cache on == cache off). No existing test weakened; the 30 reference regenerations from the prior approach are reverted because the tree shape is unchanged.
e Both directions demonstrated? Yes. Fails (Code: 10) on the base build; passes on the fixed build (Build ID b34c7564). 50/50 with full randomization.
f Fix is general across code paths? Yes. The two sibling rewrites (tryOptimizeAndEqualsNotEqualsChain, tryReplaceOrEqualsChainWithIn) already replace the argument list rather than appending, so they are idempotent; tryOptimizeAndCompareChain was the only push_back offender.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified empty/correct for UInt64, Nullable(UInt64), LowCardinality(String), LowCardinality(Nullable), Float64; AND, OR, 3-way AND, alias projected twice; group-selecting case returns the expected row. optimize_and_compare_chain still injects the transitive conjunct (verified present, once).
h Backward compatible? Yes. Restores pre-#88043 behavior on default settings; no setting, format, or default change.
i Invariants and contracts preserved? Yes. The pass now produces the same AND regardless of node sharing, so block structure (projection vs GROUP BY key name match) holds on all use sites. The cache contract (return resolved nodes, by reference, no copy) is unchanged.

Session id: cron:clickhouse-worker-slot-7:20260625-222100

@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [86ea111]

Summary: ✅


AI Review

Summary

This PR fixes a default-settings analyzer regression where tryOptimizeAndCompareChain could append the same derived conjunct multiple times to a cache-shared AND, making projection/HAVING and GROUP BY copies format differently and causing NOT_FOUND_COLUMN_IN_BLOCK. The current change deduplicates generated conjuncts with query-tree semantic hash/equality while preserving the identifier resolve cache fast path, and the added stateless test covers the reported repro plus nearby shared-expression cases.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e73f84e

Every failed check below has an owner (a fixing PR). Mergeable Check / PR are aggregators that only reflect the rows below.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, s3 storage, parallel, 1/2) / ThreadSanitizer data race (STID 3667-3bd3) + Server died + 02920_alter_column_of_projections TSAN data race on MemoryReservation release at query finish (trunk); Server-died and 02920 are collateral of that crash #108391 (external, merged 2026-06-25) — this build predates the fix; picked up on next rebase
Stress test (amd_debug) / Hung check failed, possible deadlock found deadlock, chronic shutdown/teardown family (not PR-caused) #101680 / #105905 (ours, open)
Stress test (arm_tsan) / Logical error: Not-ready Set is passed as the second argument (STID 0250-41a5) chronic "Not-ready Set" trunk bug #102192 (external, open)

Not PR-caused: this PR only changes src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp (+12/-1) plus an analyzer regression test; none of these stress/TSAN failures are in that path.

Session id: cron:our-pr-ci-monitor:20260626-033000

@novikd novikd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like tryOptimizeAndCompareChain can be significantly improved, but it lays out of scope of this PR>

@novikd

novikd commented Jun 26, 2026

Copy link
Copy Markdown
Member

@groeneai, merge the fresh master into this branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@novikd done — merged fresh master (de06571c8d4) into the branch; new head 86ea111874a. Diff unchanged (3 files, +75/-1). This also picks up #108391 (merged), clearing the TSAN MemoryReservation ledger line. CI re-running.

@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 12/12 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@novikd
novikd added this pull request to the merge queue Jun 26, 2026
Merged via the queue into ClickHouse:master with commit c113b69 Jun 26, 2026
490 of 493 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 Jun 26, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 27, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 27, 2026
Cherry pick #108553 to 26.6: Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache)
robot-clickhouse added a commit that referenced this pull request Jun 27, 2026
…(fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache)
@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 Jun 28, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jun 28, 2026
Backport #108553 to 26.6: Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ifier-resolve-cache-shared-node-108518

Make tryOptimizeAndCompareChain idempotent (fix NOT_FOUND_COLUMN_IN_BLOCK with identifier resolve cache)
alexey-milovidov pushed a commit to hinata34/ClickHouse that referenced this pull request Oct 4, 2026
`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]>
tsenart pushed a commit to perfloop-oss/ClickHouse that referenced this pull request Nov 14, 2026
…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]>
grantholly-clickhouse pushed a commit to il9ue/ClickHouse that referenced this pull request Nov 16, 2026
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]>
grantholly-clickhouse pushed a commit to il9ue/ClickHouse that referenced this pull request Nov 16, 2026
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]>
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 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.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Analyzer: enable_identifier_resolve_cache shares a mutated expression node, breaking compound GROUP BY alias (NOT_FOUND_COLUMN_IN_BLOCK)

7 participants