Skip to content

Enable optimize_or_like_chain by default. - #94517

Merged
alexey-milovidov merged 142 commits into
masterfrom
optimize-or-like-chain-indexhint
Jul 13, 2026
Merged

alexey-milovidov merged 142 commits into
masterfrom
optimize-or-like-chain-indexhint

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jan 18, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Enable optimize_or_like_chain by default. Closes #87779.

Version info

  • Merged into: 26.7.1.843 (included in 26.7 and later)

alexey-milovidov and others added 5 commits January 18, 2026 16:14
This change simplifies and improves the OR LIKE/ILIKE chain optimization pass:

1. Use match() with combined regex instead of multiMatchAny:
   - Transforms: x LIKE 'a%' OR x LIKE '%b'
   - Into: match(x, '(^a)|(b$)')
   - This removes the Hyperscan/Vectorscan dependency

2. Keep multiSearchAny for pure substring patterns:
   - When all patterns are %substring% form, uses faster multiSearchAny
   - Uses multiSearchAnyCaseInsensitive for ILIKE patterns

3. Add indexHint wrapping to preserve index analysis:
   - Wraps result with AND indexHint(original_expression)
   - This allows the optimization to be safely enabled by default

4. Support match() function in the chain:
   - match() patterns are used as-is (already regexp)
   - Detects (?i) prefix for case insensitivity

5. Move likePatternIsSubstring to Common library for shared use

Note: indexHint wrapping is only implemented for the new analyzer.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
The optimization now preserves index analysis by wrapping the original
expressions in indexHint(), so it's safe to enable by default.

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

clickhouse-gh Bot commented Jan 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [94db121]

Summary: ✅

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jan 18, 2026

Copilot AI left a comment

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.

Pull request overview

This PR enables the optimize_or_like_chain setting by default, which optimizes chains of OR conditions with LIKE/ILIKE/match operations. The optimization converts these chains into more efficient function calls: multiSearchAny for substring patterns or match() with combined regex patterns for other cases.

Changes:

  • Enabled optimize_or_like_chain setting by default (changed from false to true)
  • Enhanced the optimization to support match() functions and use multiSearchAny for substring patterns
  • Added indexHint() wrapping in the analyzer to preserve index analysis capability
  • Refactored implementation to extract and reuse likePatternIsSubstring helper function

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/queries/0_stateless/02226_analyzer_or_like_combine.sql Adds comprehensive test cases for new optimization scenarios including match() combinations and substring patterns
tests/queries/0_stateless/02226_analyzer_or_like_combine.reference Updates expected output for new test cases showing optimized query trees
tests/queries/0_stateless/02226_analyzer_or_like_combine.oldanalyzer.reference Updates expected output for old analyzer showing match() instead of multiMatchAny
src/Interpreters/ConvertFunctionOrLikeVisitor.h Updates documentation to describe new optimization behavior
src/Interpreters/ConvertFunctionOrLikeVisitor.cpp Implements pattern analysis and selection between multiSearchAny and match() with combined regex
src/Functions/multiMatchAny.h Removes file as multiMatchAny is no longer used in this optimization
src/Functions/MatchImpl.h Removes likePatternIsSubstring implementation (moved to likePatternToRegexp.cpp)
src/Core/SettingsChangesHistory.cpp Records the setting change in version 26.1
src/Core/Settings.cpp Changes default value to true and updates documentation
src/Common/likePatternToRegexp.h Adds declaration for likePatternIsSubstring helper function
src/Common/likePatternToRegexp.cpp Implements likePatternIsSubstring (extracted from MatchImpl.h)
src/Analyzer/Passes/ConvertOrLikeChainPass.h Updates documentation to describe new optimization behavior
src/Analyzer/Passes/ConvertOrLikeChainPass.cpp Implements analyzer pass with indexHint wrapping and pattern analysis

@rschu1ze

Copy link
Copy Markdown
Member

@alexey-milovidov Lots of other code changes sneaked in. Could you push them separately?

@shankar-iyer shankar-iyer self-assigned this Jan 20, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze, none of the other code sneaked in. All of this code is on point.

@alexey-milovidov
alexey-milovidov marked this pull request as draft January 30, 2026 03:27
alexey-milovidov and others added 3 commits March 30, 2026 03:39
`ILIKE` is UTF-8-aware but `multiSearchAnyCaseInsensitive` is ASCII-only,
which produces false negatives for non-ASCII text. Use the UTF-8 variant
`multiSearchAnyCaseInsensitiveUTF8` instead.

Also fix build after merge with master: use `make_intrusive<ASTLiteral>`
instead of `std::make_shared<ASTLiteral>` since AST children now use
`boost::intrusive_ptr`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The setting is already configured in
performance/scripts/config/users.d/perf-comparison-tweaks-users.xml.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author
Screenshot_20260713_055320

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 13, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jul 13, 2026
Merged via the queue into master with commit be50d63 Jul 13, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the optimize-or-like-chain-indexhint branch July 13, 2026 04:11
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 13, 2026
alexey-milovidov added a commit that referenced this pull request Jul 15, 2026
… master

The merge of master brought in the reworked `optimize_or_like_chain`
(#94517), which changed the semantic content of this test. Regenerate
both reference files from the merged binary so the `EXPLAIN SYNTAX`
results are single records with embedded newlines, matching the new
`single_record = 1` default. Verified with clickhouse-test against a
local server: `02226_analyzer_or_like_combine` passes with both the new
and the old analyzer.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…_chain

1. Fix correctness bug for mixed OR chains: when an OR contains both
   `LIKE`/`match` and non-`LIKE` branches, the previous code wrapped the
   optimized expression in `AND indexHint(<LIKE subset>)`. Index analysis
   then restricted ranges to those satisfying the `LIKE` subset, pruning
   granules where only the non-`LIKE` branch matches — producing false
   negatives. Only attach `indexHint` when every OR branch was a
   `LIKE`/`ILIKE`/`match`; for mixed chains rewrite in place without
   adding `indexHint`, matching the old analyzer's behavior.

2. Update stale comments: `multiSearchAnyCaseInsensitive` ->
   `multiSearchAnyCaseInsensitiveUTF8` in both analyzer paths and in the
   test file, since the rewrite has used the UTF-8 variant since the
   `ILIKE` UTF-8 correctness fix.

3. Remove dead `(?i)` detection for `match` patterns. A regexp pattern is
   never a pure substring, so `canUseMultiSearchAny` always returns false
   in this branch and the `is_case_insensitive` flag is unused for
   `match`-derived entries. Flags inside the original regexp (`(?i)`,
   `(?mi:...)`, etc.) are preserved verbatim in the combined alternation.

4. Update `.oldanalyzer.reference` for the remaining `EXPLAIN SYNTAX`
   alias-expansion case at the mixed `LIKE %Hello% OR ILIKE %world%`
   query that CI flagged on sha 0595fc6.

5. Add an `EXPLAIN QUERY TREE` test case exercising a mixed OR chain to
   verify the optimized result is not wrapped in `and(..., indexHint(...))`.

CI report: ClickHouse#94517

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
- Move `optimize_or_like_chain` settings history entry from 26.4 to 26.5.
  The change to enable the setting by default lands post-26.4.1, so test
  `02995_new_settings_history` expects the entry under version > 26.4.

- Disable `optimize_or_like_chain` in test `04059_explain_pretty_filters`.
  The test exercises pretty-printed filter formatting; with the optimization
  enabled by default, `b LIKE '%foo%'` rewrites to `multiSearchAny(b, ['foo'])`
  and the reference no longer matches. Disable the rewrite locally to keep
  the test focused on its actual subject.

- Update `02226_analyzer_or_like_combine.oldanalyzer.reference` so that
  `EXPLAIN SYNTAX` results match current alias-expansion behavior. The old
  analyzer now inlines the `materialize('...') AS s` expression in place of
  the alias name `s` in the formatted output, both inside the rewritten
  function calls and inside the original LIKE/ILIKE/= operands, so the
  reference is updated accordingly.

CI report: ClickHouse#94517

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The setting description previously claimed unconditionally that the original
expressions are preserved in `indexHint()` to allow index analysis. That is
only true for the new analyzer (`ConvertOrLikeChainPass`); the old-analyzer
visitor `ConvertFunctionOrLikeVisitor` rewrites to `multiSearchAny*` /
`match` without `indexHint`, so MergeTree index analysis cannot use the
original LIKE chain after the rewrite when `enable_analyzer = 0`.

Update the doc text so users running with the old analyzer know what to
expect. Addresses reviewer feedback in PR ClickHouse#94517.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The previous approach replaced `multiMatchAny` with `match` using a
combined alternation pattern (e.g. `(p1)|(p2)|...`). RE2's alternation
is significantly slower than Vectorscan/Hyperscan, which caused 1.4x to
5.9x slowdowns in the `optimize_or_like_chain_hits` performance test
once the optimization was enabled by default.

Use `multiMatchAny` for non-substring patterns (it leverages Vectorscan
when available and falls back to RE2 alternation otherwise) and only
fall back to `match` when `allow_hyperscan` is disabled. Pure substring
patterns continue to use `multiSearchAny`/`multiSearchAnyCaseInsensitiveUTF8`.

The same change is applied to the old-analyzer rewrite in
`ConvertFunctionOrLikeVisitor.cpp`. Reference outputs for
`02226_analyzer_or_like_combine` are updated accordingly.

CI: ClickHouse#94517
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ke_chain`

The `multiMatchAny` function requires Vectorscan to be compiled in. Without
it, the function is still registered but throws `NOT_IMPLEMENTED` at
execution time. This caused `Fast test` failures in PR ClickHouse#94517 once
`optimize_or_like_chain` started rewriting `OR LIKE` chains into
`multiMatchAny` by default: many unrelated tests using
`EXPLAIN ... WHERE ... LIKE 'a%' OR ... LIKE 'b%'` stopped working in
the no-Vectorscan build.

Guard both the new-analyzer pass (`ConvertOrLikeChainPass`) and the
old-analyzer visitor (`ConvertFunctionOrLikeVisitor`) with
`#if USE_VECTORSCAN`. When Vectorscan is not compiled in, generate
`match` with combined alternation (the existing fallback already used
when `allow_hyperscan = 0`) instead of `multiMatchAny`.

Restore the `no-fasttest` tag on `02226_analyzer_or_like_combine` —
its reference output expects `multiMatchAny` and only matches builds
with Vectorscan.

CI: ClickHouse#94517

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Builds without Vectorscan (e.g. the Fast test image) tripped on
`-Werror,-Wunused-member-function` for `PatternInfo::getRegexps`, since
that helper is only consumed on the `USE_VECTORSCAN` branch in
`ConvertFunctionOrLikeVisitor`. Mark it `[[maybe_unused]]`, mirroring
`getCombinedRegexp` on the opposite branch.

Also fix the `intereference` -> `interference` typo in the
`02226_analyzer_or_like_combine` test header per review feedback.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/94517/99bb9767fb571b556d5c9dfa04c863a628066a39/fast_test/build_clickhouse/build_clickhouse.log
PR: ClickHouse#94517

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The call to `fitsHyperscanLimits` in `ConvertFunctionOrLikeVisitor.cpp`
is guarded by `#if USE_VECTORSCAN`, so when ClickHouse is built without
Vectorscan (as in the Fast test build), the method becomes unreferenced
and the `-Werror,-Wunused-member-function` warning fires.

Mark the method `[[maybe_unused]]`, mirroring the adjacent `getRegexps`,
which has the same conditional usage pattern.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/94517/b77a2f3b13539bde272a152a1d7c6f74ffb5a8f7/fast_test/build_clickhouse/build_clickhouse.log
PR: ClickHouse#94517
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…llback

The old-analyzer rewrite in `ConvertFunctionOrLikeVisitor` now falls back
to `match` with combined alternation when `allow_hyperscan = 0` or when
`max_hyperscan_regexp_length` / `max_hyperscan_regexp_total_length` would
be exceeded. The previous reference still expected the original `OR`-of-
`{i}like` form to be preserved in those cases, which no longer matches
the current behavior.

Also tightens `max_hyperscan_regexp_length` from `10` to `5` so the
per-pattern limit actually triggers the fallback (the `(?i)^world` regexp
is 10 characters, and the limit check uses strict `>` so `10 > 10` does
not trigger).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=94517&sha=fcb5679fbfc9406808553f648b30a71df865f036&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%29
PR: ClickHouse#94517
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ompatibility note

Per review feedback in PR ClickHouse#94517, the compatibility entry for
`optimize_or_like_chain` previously listed only `multiSearchAny` and
combined `match` as rewrite targets. The new-analyzer rewrite can also
emit `multiMatchAny` when `allow_hyperscan` is on and the hyperscan
length limits permit it. Update the description so the compatibility
history matches the actual behavior.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ed limits

Before this commit, the fallback `match` path in `optimize_or_like_chain`
materialized one combined regexp `(p1)|(p2)|...` without any cap. With
`allow_hyperscan = 0` (or hyperscan limits exceeded), a large `OR LIKE`
chain could blow up RE2 compile limits, turning previously-successful
queries into exceptions once `optimize_or_like_chain` is enabled by
default.

Both the new-analyzer pass `ConvertOrLikeChainPass` and the old-analyzer
`ConvertFunctionOrLikeVisitor` now check `info.fitsHyperscanLimits` for
the fallback `match` path too. When patterns exceed
`max_hyperscan_regexp_length` / `max_hyperscan_regexp_total_length`, the
rewrite is skipped for that LHS group: the original LIKE/ILIKE/match
branches are kept verbatim, so the query remains executable and can
still benefit from `multiSearchAny`/`multiMatchAny` rewrites for other
groups in the same OR.

To support per-key skip, both visitors were restructured around a list
of "slots" that each hold either a single optimized match function or
the original LIKE branches kept verbatim. The slots are flattened back
into the OR's argument list at the end. The new-analyzer pass also
rebuilds the `indexHint` payload from the rewritten keys only — keys we
left unrewritten still appear in the outer OR and the index can use them
directly.

This addresses unresolved review feedback on
`ConvertOrLikeChainPass.cpp:397` and `ConvertFunctionOrLikeVisitor.cpp:292`
in ClickHouse#94517.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…_like_chain`

The previous `isExpressionNonDeterministic` only descended into `FunctionNode`
arguments, so a non-deterministic call hidden inside a `LambdaNode` body (e.g.
`arrayMap(x -> rand() + x, col)`) escaped the check. Two structurally identical
LHS expressions of that shape would then be treated as deterministic and
collapsed into a single `multiSearchAny`/`multiMatchAny`, calling `rand` once
instead of once per branch and changing query results.

Recurse into all children of the current node so the check covers lambda
bodies, subqueries, and any other intermediate node types.

Addresses an unresolved review comment on PR ClickHouse#94517.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `optimize_or_like_chain` rewrite has a fixed setup cost (constructing
`multiSearchAny` argument arrays, Hyperscan compile) that for short chains tends
to outweigh short-circuit OR evaluation of the original branches. With the
optimization now default-on, this regressed several queries in
`tests/performance/optimize_or_like_chain_hits.xml`: 2-pattern chains were
12-50% slower while 11+ pattern chains improved by 30-40%.

Address the user's note "we will have to find a set of conditions to make the
optimization always beneficial" by introducing the new setting
`optimize_or_like_chain_min_patterns` (default 5): the rewrite is applied only
when at least that many LIKE/ILIKE/match branches share the same LHS
expression; shorter chains are kept verbatim. Calibrated against the perf test,
so all short-chain queries now match `master_head` behavior while long-chain
queries keep their speedup.

Both the new-analyzer pass (`ConvertOrLikeChainPass`) and the old-analyzer
visitor (`ConvertFunctionOrLikeVisitor`) honor the setting. The existing
correctness test `02226_analyzer_or_like_combine` sets the threshold to `1`
explicitly so it continues to exercise the rewrite for its short-chain
fixtures.

CI report: ClickHouse#94517
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Address review feedback: the previous wording said the new analyzer always
preserves the original expressions in `indexHint()`, but `ConvertOrLikeChainPass`
intentionally skips `indexHint` wrapping for mixed OR chains (LIKE/ILIKE/match
combined with other branches) so that ranges matching only the non-LIKE branch
are not pruned. Update the text to match implementation.

Link: ClickHouse#94517
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Address the bot review comment on
`tests/queries/0_stateless/04209_optimize_or_like_chain_non_deterministic.sql:6`:
with the default `optimize_or_like_chain_min_patterns = 5` introduced in
`bcd89c95aa3`, every 2-pattern chain in this test was skipped regardless of
determinism, so the deterministic-chain assertion at lines 27-30 no longer
produced `multiSearchAny` and the file's reference diverged.

Force the threshold to `1` for this test so the non-deterministic guard and
the deterministic-merge case are actually exercised, matching how
`02226_analyzer_or_like_combine` was adjusted.

CI failure: `Fast test` on ClickHouse#94517

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…e_chain`

`multiMatchAny` compiles its patterns with Hyperscan's `HS_FLAG_UTF8` and
throws `BAD_ARGUMENTS` / `CANNOT_COMPILE_REGEXP` for a pattern that is not
valid UTF-8, whereas the original `match` uses RE2, which accepts such
patterns (matching them byte-wise / as Latin-1 — see
`04311_text_index_non_utf8_needle_no_prune`).

With `optimize_or_like_chain` now enabled by default, a `match` chain
containing a non-UTF-8 pattern (e.g. `match(s, '\xA9bc') OR match(s, 'one')
OR ...`) could be rewritten into `multiMatchAny` and turn a previously
successful query into an exception.

Add `PatternInfo::allRegexpsValidUTF8` and gate the `multiMatchAny` rewrite
on it in both the new-analyzer pass (`ConvertOrLikeChainPass`) and the
old-analyzer visitor (`ConvertFunctionOrLikeVisitor`); when any pattern is
not valid UTF-8 we fall back to the combined-`match` (RE2) path, which
preserves the original semantics. The pure-substring `multiSearchAny*` path
is unaffected (it is byte-oriented and has no such restriction).

Addresses review feedback on ClickHouse#94517

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…chain-indexhint

Enable `optimize_or_like_chain` by default.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimization pass: convert a chain of OR LIKE or match to a single regular expression or multi-string matching.

6 participants