Skip to content

Fix NOT_FOUND_COLUMN_IN_BLOCK and wrong results when a GROUP BY key LIKE is a branch of an OR chain - #125894

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-or-like-chain-group-by-key
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-or-like-chain-group-by-key

Conversation

@groeneai

@groeneai groeneai commented Oct 14, 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, and wrong results with ROLLUP, for an OR of LIKE/ILIKE conditions that are themselves GROUP BY keys: optimize_or_like_chain no longer merges such a condition into multiSearchAny/multiMatchAny, which needs the condition's argument after aggregation.

Description

On 26.8.21.12, SELECT (s LIKE '%1%') OR (s LIKE '%2%') OR (s LIKE '%3%') OR (s LIKE '%4%') AS e, count() FROM (SELECT toString(number % 6) AS s FROM numbers(12)) GROUP BY s LIKE '%1%', s LIKE '%2%', s LIKE '%3%', s LIKE '%4%' throws NOT_FOUND_COLUMN_IN_BLOCK, and with GROUP BY ROLLUP(s, s LIKE '%1%') such an OR returns a wrong value on the rows where s LIKE '%1%' is rolled up.

The s LIKE '%1%' in the projection is the GROUP BY key and is read from the aggregation result. ConvertOrLikeChainPass runs later, groups it with the other branches by s and rewrites them into multiSearchAny(s, [...]), which needs s after aggregation.

Each query level now records, before any rewrite and by pointer, its like/ilike/match nodes equal to a key (or to its Nullable copy under group_by_use_nulls), and the pass keeps those branches as written. Other branches are still merged; a LIKE that is itself a key is no longer merged anywhere in its query level.

The new test fails on master (15 statements NOT_FOUND_COLUMN_IN_BLOCK, 6 wrong values) and passes 50/50 with randomized settings; 33 of the 34 tests that mention optimize_or_like_chain pass (the other needs the s3_cache storage policy, absent in my local setup). EXPLAIN QUERY TREE of a 255-branch OR with 101 keys: 0.082 s before, 0.091 s after.

Same class, with the same per-query collection of key nodes, in other passes: #125828, #125846. Not #124480 (one OR alias reused by several clauses): this reproduces with enable_identifier_resolve_cache = 0.


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

groeneai and others added 3 commits October 14, 2026 17:12
`ConvertOrLikeChainPass` groups the `like`/`ilike`/`match` branches of an
`or` by their left-hand side and merges a large enough group into
`multiSearchAny` / `multiSearchAnyCaseInsensitiveUTF8` / `multiMatchAny`.
It did so also for branches that are `GROUP BY` keys. After aggregation
such a branch is read from the key column, so the merged call asks for the
key's argument, which either does not exist (`NOT_FOUND_COLUMN_IN_BLOCK`)
or is another key with a different rollup (wrong results under `ROLLUP`,
`CUBE`, `GROUPING SETS`, and `group_by_use_nulls`).

Each query level now collects, before any rewrite, the `like`/`ilike`/
`match` nodes equal to one of its keys (or to its `Nullable` copy under
`group_by_use_nulls` with a modifier), by pointer, and the collection loop
keeps such a branch as written. Pointers keep identifying a key after the
pass rewrites a chain nested in the key's own argument in place.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… rewrite

When every branch of an `or` is a pattern branch and a group is rewritten,
the pass replaces the chain by `and(<clone of the rewritten or>,
indexHint(<original branches>))`, and the visitor continues into the clone.
A `GROUP BY` key nested in a left-hand side of that chain (for example
`toString(<OR of key LIKEs>) LIKE ...`) is then reached only as a copy that
is not in the per-query set of key nodes, so it was merged again and read
`s` after aggregation (`NOT_FOUND_COLUMN_IN_BLOCK`, or a wrong result under
`ROLLUP`). Right after the clone, a lockstep walk of the original and the
copy (`clone()` keeps the children layout) adds the copy of every key node
to the set; a chain nested deeper is mapped again at its own clone site.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The two new statements cover the ListNode flattening of the key collection and its Nullable shape under group_by_use_nulls.

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 over 2 rounds: an independent model (engine: codex; 0 findings in both rounds) plus my own cold review (4 findings in round 0, none in round 1).

# Sev Finding Verdict Evidence / action
1 ⚠️ The GROUPING SETS branch of the key collection (flattening of each set, Nullable shape under group_by_use_nulls) had no test row AGREE, fixed two GROUPING SETS statements added to 05402 (plain and group_by_use_nulls); both fail NOT_FOUND_COLUMN_IN_BLOCK on master and equal the optimize_or_like_chain = 0 output with the fix
2 💡 The same per-query key collection exists in #125828 and #125846 AGREE, noted one site in this PR; reuse needs unmerged code; the description names the relationship
3 💡 match keys are kept although match branches are never merged DISAGREE not a defect: a group with a raw match() regexp always keeps its branches
4 💡 A WHERE chain whose branch equals a key loses the rewrite AGREE, noted results unchanged, rare shape, stated in the description

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

Session id: cron:clickhouse-review-self-slot-58:20261014-220600

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [97a6886]

Summary: ✅


AI Review

Summary

Reviewed #125894 at 97a688671f80bd864a4908c00ac1afbd02f8faf9, including the current source, complete diff, commit history, and all prior discussion. The change preserves LIKE/ILIKE branches that are GROUP BY keys instead of merging them into expressions that require unavailable arguments after aggregation or recompute rolled-up keys incorrectly. No actionable findings.

Missing context / blind spots
  • ⚠️ Current-head functional CI was still pending when reviewed, and no local compiled binary was available. Runtime validation relies on the author's reported results and the added regression coverage; completed CI from an earlier revision does not establish the current head's test status.
Final Verdict

Status: ✅ Approve

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Default settings, no randomization: the GROUP BY s LIKE '%1%', ... query from the description throws NOT_FOUND_COLUMN_IN_BLOCK every time on master, 26.7, 26.8 and 26.9; the ROLLUP(s, s LIKE '%1%') form returns 8 13 instead of 7 13.
b Root cause explained? Yes. A LIKE branch that is a GROUP BY key is read from the aggregation result; ConvertOrLikeChainPass merged it into multiSearchAny(s, ...), which needs s after aggregation. The indexHint wrap of a chain clones the rewritten OR and the visitor continues into the clone, so keys nested in its left-hand sides were reached as copies.
c Fix matches root cause? Yes. The merge site gets the missing precondition (a key branch is kept as written), with keys classified by pointer at query entry and their copies added at the clone site. No planner-side guard.
d Test intent preserved / new tests added? New test 05402_optimize_or_like_chain_group_by_key: 15 statements fail NOT_FOUND_COLUMN_IN_BLOCK and 6 return wrong values on master, including two GROUPING SETS statements (plain and group_by_use_nulls); 5 EXPLAIN QUERY TREE counts check that the other branches are still rewritten.
e Both directions demonstrated? Yes. Through tests/clickhouse-test: FAIL (return code 10) on a master build, OK on the fix build; 50/50 randomized runs OK, with the optimize_or_like_chain limit checked in system.query_log plus a negative control.
f Fix is general across code paths? Yes. One merge site feeds all three targets (multiSearchAny, multiSearchAnyCaseInsensitiveUTF8, multiMatchAny) and the indexHint wrap; all three node copies the pass makes were checked. Other passes with the same class: #125828, #125846.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. LIKE, ILIKE, prefix patterns, Nullable(String), LowCardinality(String), group_by_use_nulls, plain/ROLLUP/CUBE/GROUPING SETS, HAVING, aliases with identifier cache 0 and 1, keys nested one and two levels inside a rewritten chain.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only queries that failed or returned wrong values change. A LIKE that is itself a key is no longer merged in its query level (results unchanged).
i Invariants and contracts preserved? Yes. The per-query set is pushed and popped for every QUERY node, holds owning pointers, and the clone mapping relies on clone() keeping the children layout, asserted with chassert.

Session id: cron:clickhouse-impl-self-slot-57:20261014-194500

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

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @yakov-olkhovskiy, could you review this and add the can be tested label? I cannot add it at the moment, so CI has not run. ConvertOrLikeChainPass merged an OR branch that is itself a GROUP BY key LIKE into multiSearchAny(s, ...), which needs s after aggregation; the pass now keeps such branches as written.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 14, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3725870

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) / 05346_distributed_insert_connection_buffers_freed_by_same_query flaky, not from this PR: 10 of 10 reruns passed; it failed on 8 other PRs and on master since 2026-10-14; the tested tree of this run predates the test fix #125909 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #125909 (mine, merged)

CIDB has no other FAIL or ERROR row from the finished run on this head.

Session id: cron:our-pr-ci-monitor:20261015-230015

groeneai and others added 2 commits November 18, 2026 14:51
…roup-by-key

Resolve the conflict with ClickHouse#129177 in ConvertOrLikeChainPass.cpp. Master now
collects the rewrites in leaveImpl and applies them in applyRewrites after the
whole visit, so:

- the GROUP BY key set is still pushed in enterImpl of each QueryNode and
  popped in its leaveImpl, and the OR collection loop in leaveImpl keeps a
  key branch as written;
- addCopiesOfNodes is dropped: it tracked the copies made by the indexHint
  wrap's node->clone(), which the visitor used to descend into. The clone now
  happens in applyRewrites, after the visit, so the visitor only ever sees the
  original nodes, which collectGroupByKeyPatternNodes records.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every chain of GROUP BY key branches in the test was exactly at the default
rewrite threshold (4 substrings, 10 patterns), so a fix that kept only one
key branch out of the rewrite left the others below the threshold and the
test still passed. With both thresholds at 1, a key branch that is not kept
out is rewritten and the statement fails.

Measured with a build that keeps only the first GROUP BY key out: the old
test caught it in 3 statements (the group_by_use_nulls ones), the new one in
15. The fix and master give the same output as before, so the reference is
unchanged.

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

clickhouse-gh Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 97a688671 with master f63ca4f78 (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.

Object file sizes

3 object files changed (+28.56 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Passes/ConvertOrLikeChainPass.cpp.o 176.49 KiB 205.05 KiB +28.55 KiB (+16.18%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline.

Job report

This branch has not been deployed

No deployments
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants