Skip to content

Fix NOT_FOUND_COLUMN_IN_BLOCK when an alias of an OR chain of LIKE conditions is reused by GROUP BY and other clauses - #124480

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-or-like-chain-shared-alias
Oct 19, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-or-like-chain-shared-alias

Conversation

@groeneai

@groeneai groeneai commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixed NOT_FOUND_COLUMN_IN_BLOCK for a query that groups by an alias of an OR chain of LIKE/ILIKE conditions and reuses that alias in ORDER BY or HAVING, for example SELECT (s LIKE '%a%' OR s LIKE '%b%' OR s LIKE '%c%' OR s LIKE '%1%') AS r FROM t GROUP BY r ORDER BY r.

Description

On 26.8.2.7, SELECT (s LIKE '%a%' OR s LIKE '%b%' OR s LIKE '%c%' OR s LIKE '%1%') AS r FROM t GROUP BY r ORDER BY r fails with Code: 10 NOT_FOUND_COLUMN_IN_BLOCK on default settings (also on 26.7 and master).

With enable_identifier_resolve_cache (default since 26.6) the GROUP BY key and its ORDER BY / HAVING references are one shared or node. ConvertOrLikeChainPass rewrites that node in place into multiSearchAny(...) and then replaces only the reference it reached first with and(<rewritten or>, indexHint(<original chain>)) (the indexHint, added in #94517, keeps the LIKE conditions visible to index analysis). The other reference keeps the bare rewritten or, so the key and ORDER BY differ by name and the planner looks for __table1.s after aggregation.

The change: the pass turns the or node itself into and(<rewritten or>, indexHint(<original chain>)) in place, so every reference to a shared node sees the same expression, including references the visitor does not descend into (under indexHint). A query without a shared node gets an identical query tree (EXPLAIN QUERY TREE byte-identical with the cache off).

The new test covers 11 shapes (ORDER BY, HAVING, ILIKE, multiMatchAny, Nullable and LowCardinality haystacks, two key groups in one chain, WITH ROLLUP, a chain nested in the haystack of another, a reference under indexHint, and ORDER BY ALL with the cache off, which shares the projection node); all 11 fail on master and pass with the fix, also with random settings. The existing optimize_or_like_chain and indexHint-consuming index tests are unchanged.

Related: #122404, same class as #108553. Same issue in other passes, separate PRs: #123925, #122512, #122726.


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

Version info

  • Merged into: 26.11.1.221-master (included in 26.11 and later)

…LikeChainPass

With enable_identifier_resolve_cache the GROUP BY key and its ORDER BY /
HAVING references are one `or` node. ConvertOrLikeChainPass rewrote that
node in place and then replaced only the slot it reached first with
and(<rewritten or>, indexHint(<original chain>)); the other reference was
skipped by processed_nodes and kept the bare rewritten `or`, so the key and
ORDER BY had different names and the planner asked for the source column
after aggregation (Code 10).

Record the slot replacement and put the same `and` node at every later
reference of the replaced node in needChildVisit. The map is keyed by the
node pointer itself (not structural hash), so the projection's own copy is
not conflated with the shared node, and it keeps replaced nodes alive for
the pass. A tree without a shared node is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The result-only test stays green if the rewrite silently declines DISAGREE All 9 arms fail with Code 10 on master and again when the one recording line is deleted, so the test reddens without the fix; the only randomized knob is pinned by the limits line (negative control: 15/30 runs fail). Rewrite activity is asserted by the EXPLAIN reference of 02226_analyzer_or_like_combine.
2 💡 Relationship links as short references DISAGREE The template's relationship block is kept with full URLs, plus a visible Related: line.
3 💡 needChildVisit assigns the child slot AGREE, noted Legal (child is the parent's slot); same idiom as #123925.
4 💡 Same memo idiom in #123925 AGREE, noted The two maps record different nodes; no shared helper for now.

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

Session id: cron:clickhouse-review-self-slot-58:20261007-195400

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Each of the 9 test queries fails with Code: 10 on master in a fresh clickhouse local; the first one also fails on official 26.8.2.7 and 26.7.6.57 with default settings.
b Root cause explained? Yes. With the identifier resolve cache the GROUP BY key and its ORDER BY/HAVING references are one or node. The pass rewrites it in place (reaches every reference) and then wraps only the first reference in and(.., indexHint(..)), so the other reference keeps a different name.
c Fix matches root cause? Yes. The replacement is recorded where it is made and reused at every other reference of the same node; no guard, no clone at the cache.
d Test intent preserved / new tests added? New SQL test 05346_optimize_or_like_chain_shared_alias, 9 shapes. Deleting the one recording line makes all 9 fail again.
e Both directions demonstrated? Yes. Master build and the mutation fail 9/9, the fix passes 9/9, locally and through clickhouse-test (plain and randomized); 50/50 randomized runs pass.
f Fix is general across code paths? Yes. It is the only slot replacement in the pass; the in-place-only branch was already consistent. ORDER BY, HAVING, ROLLUP, CUBE, GROUPING SETS, WITH FILL, an extra aggregate and a nested chain all reach it. Other passes with the same issue are separate PRs.
g Fix generalizes across inputs (params/datatypes/wrappers)? String, Nullable, LowCardinality (test) and LowCardinality(Nullable) (checked by hand); LIKE, ILIKE and multiMatchAny targets; two key groups. FixedString/Enum and below-threshold chains are not rewritten.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. A query without a shared node gets a byte-identical query tree; the query text sent to shards matches the cache-off text, and an unpatched shard accepts it.
i Invariants and contracts preserved? Every reference of one node carries the same rewritten form after the pass. processed_nodes is unchanged; the map holds strong pointers, so a replaced node's address cannot be reused during the pass.

Session id: cron:clickhouse-impl-self-slot-57:20261007-191300

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c55750d]

Summary: ✅


AI Review

Summary

Reviewed #124480 at c55750daa554d1ff9b114bcf75334e4178e4b416. The change fixes NOT_FOUND_COLUMN_IN_BLOCK when an optimized OR chain is shared across query clauses by rewriting the shared node into and in place. No actionable findings remain. The new shared-alias regression test passes in the Fast test report.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 7, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f7b8cfc9-2bf2-4077-8fc9-38dcf1ddafdc
  • MIRAI run: 2c78b6ae-270f-4427-87b1-7876f18d4bd3
  • PR check IDs:
    • clickbench_771373_1791665153
    • clickbench_771379_1791665153
    • clickbench_771385_1791665153
    • tpch_adapted_1_official_771396_1791665153
    • tpch_adapted_1_official_771408_1791665153
    • tpch_adapted_1_official_771443_1791665153

@PedroTadim

PedroTadim commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

@groeneai 🕵️

The fix works: visitChildren passes each child by reference, so every reference ends up with the same and(...) node. One suggestion:

Could the shared node become the and in place, instead of being replaced? From reading the code, not run: keep auto optimized_or_clone = node->clone(); as now, then set function_node->getArguments().getNodes() to {optimized_or_clone, index_hint_node} and call function_node->resolveAsFunction(and_function_resolver). FunctionNode::resolveAsFunction also renames the node. The map and the needChildVisit change are then no longer needed. It also covers the references the visitor never reaches, which still keep the bare rewritten or:

  • a reference under an indexHint parent: needChildVisit returns before the map lookup;
  • unresolved table-function arguments;
  • a scope where optimize_or_like_chain is off.

As a bonus, the node keeps its alias, which node = and_node drops.

…nPass

As suggested in review: instead of replacing the slot with a new
and(<rewritten or>, indexHint(<original chain>)) node and replaying that
replacement at later references through a map, turn the OR node itself
into the AND. Every reference to a shared node, including ones the
visitor never reaches (under an indexHint parent), then sees the same
expression, and the map and the needChildVisit redirect are not needed.

Add two test arms: a reference under indexHint, and ORDER BY ALL with
enable_identifier_resolve_cache = 0, where ORDER BY shares the
projection node. Both fail on master with Code 10.

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

Copy link
Copy Markdown
Collaborator Author

Thanks, done in c55750d: the or node is rewritten into the and in place, and the map and the needChildVisit change are removed.

  • Reference under indexHint: new test arm SELECT (...) AS r, indexHint(r) FROM t GROUP BY r ORDER BY r. It fails on master with Code 10 and passes now (it also passed on the previous head).
  • New test arm for ORDER BY ALL with enable_identifier_resolve_cache = 0: there ORDER BY shares the projection node, and master fails the same way.
  • Unresolved table-function arguments and a scope with optimize_or_like_chain = 0: I found no query that puts a shared node there (view() arguments are analyzed as a separate query, and a correlated subquery that uses the GROUP BY alias fails with Code 48 on master even for (s = 'a') AS r), so they have no test. The in-place rewrite covers them anyway.

Queries without a shared node get the same query tree as before (EXPLAIN QUERY TREE identical).

/// Replace the original node with the AND expression
node = std::move(and_node);
/// Mark the cloned OR as processed to prevent re-visiting
processed_nodes.insert(optimized_or_clone->as<FunctionNode>());

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 are you sure no performance regressions are going to be created from this change?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I measured it with the CI release builds: this PR's merge build (579bfca2f69) against master 16add56e8d1, which differs from the merge parent only in docs and tests, so this PR is the only source difference. 30M-row MergeTree table, 16 query shapes that the pass rewrites (to multiSearchAny and to multiMatchAny): the chain in WHERE, PREWHERE or the projection, and as an alias shared by WHERE, ORDER BY, GROUP BY, HAVING and two aggregates.

  • EXPLAIN actions = 1, indexes = 1 is byte-identical to master for 11 of 16 shapes. Of the other 5, the 3 GROUP BY shapes fail on master with NOT_FOUND_COLUMN_IN_BLOCK; in the 2 WHERE r ORDER BY r shapes the sort key becomes (...) AND indexHint(), the column the WHERE filter already computes.
  • For all 16 shapes the plan is byte-identical to master's plan with enable_identifier_resolve_cache = 0, so the default now gets the plan the cache-off path always had. At execution indexHint() returns a constant 1 without evaluating the chain (FunctionIndexHint::executeImpl).
  • Median of 45 runs each, max_threads = 8, master / PR, ms:
shape multiSearchAny multiMatchAny
WHERE, not shared 147 / 153 196 / 192
WHERE r ORDER BY r 236 / 236 306 / 308
two aggregates on r 152 / 154 195 / 194
PREWHERE 174 / 175
GROUP BY r (master with the cache off) 158 / 154 198 / 201

Every pair is within 3% either way except the first, whose plan is byte-identical: two re-runs (one with the binary order swapped) read 145 / 147 and 145 / 146. Analysis of a query with 300 chains: 55 / 55 ms.

  • In this PR's Performance Comparison (arm_release) the 10 optimize_or_like_chain_hits queries are unchanged. The only slower flag is and_function #0, which has no OR (the pass returns at its first check) and was flagged slower on 218 other PRs in the last 30 days.

So I see no regression.

processed_nodes.insert(optimized_or_clone->as<FunctionNode>());

/// Rewrite the node in place to optimized_or AND indexHint(original_like_chain), as it may be shared by several references.
function_node->getArguments().getNodes() = {std::move(optimized_or_clone), std::move(index_hint_node)};

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.

@novikd maybe you can help here a little? This change is difficult for me to understand. The comment in the original code mentions indexHint, while the PR is to fix LIKE expressions?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The indexHint is part of the LIKE rewrite itself. Since #94517, optimize_or_like_chain (on by default) rewrites s LIKE '%a%' OR s LIKE '%b%' OR ... into multiSearchAny(s, ['a', 'b', ...]) AND indexHint(s LIKE '%a%' OR s LIKE '%b%' OR ...). multiSearchAny is what gets executed; indexHint keeps the original LIKE conditions visible to primary key and skip index analysis and returns a constant 1 at execution (comment in the pass).

The bug is in how that AND was attached. With enable_identifier_resolve_cache, the r in GROUP BY r ORDER BY r is one shared or node, and the old code put the new and node only into the reference it visited first. EXPLAIN QUERY TREE dump_ast = 1 on master for SELECT (s LIKE '%a%' OR s LIKE '%b%' OR s LIKE '%c%' OR s LIKE '%1%') AS r FROM t GROUP BY r ORDER BY r:

GROUP BY and((multiSearchAny(__table1.s, _CAST(['a', 'b', 'c', '1'], 'Array(String)')) OR 0), indexHint(or(__table1.s LIKE '%a%', ...)))
ORDER BY (multiSearchAny(__table1.s, _CAST(['a', 'b', 'c', '1'], 'Array(String)')) OR 0) ASC

The ORDER BY expression is no longer the GROUP BY key, so the planner tries to compute it from __table1.s after aggregation, which gives NOT_FOUND_COLUMN_IN_BLOCK. With enable_identifier_resolve_cache = 0, ORDER BY gets the full and(..., indexHint(...)) like GROUP BY, and the query works.

With this PR the shared or node itself becomes the and (your suggestion from yesterday), so SELECT, GROUP BY and ORDER BY all get ... AND indexHint(...).

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 19, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Good to merge

Merged via the queue into ClickHouse:master with commit 8c0552d Oct 19, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 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 Nov 3, 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 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #124480 to 26.10: Fix `NOT_FOUND_COLUMN_IN_BLOCK` when an alias of an `OR` chain of `LIKE` conditions is reused by `GROUP BY` and other clauses
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…ias of an `OR` chain of `LIKE` conditions is reused by `GROUP BY` and other clauses
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). groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants