Skip to content

Use text index for LIKE/ILIKE with ESCAPE - #105848

Merged
ahmadov merged 28 commits into
ClickHouse:masterfrom
groeneai:groeneai/test-text-index-like-escape
Sep 3, 2026
Merged

ahmadov merged 28 commits into
ClickHouse:masterfrom
groeneai:groeneai/test-text-index-like-escape

Conversation

@groeneai

@groeneai groeneai commented May 26, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

LIKE ... ESCAPE 'c' and ILIKE ... ESCAPE 'c' predicates now use TYPE text skip indexes to prune granules, and LIKE ... ESCAPE 'c' additionally uses the ngrambf_v1, tokenbf_v1 and sparse_grams skip indexes, plus the primary key when the column is in the sorting key, instead of falling back to a full scan. NOT LIKE ... ESCAPE 'c' is recognized by the bloom-filter skip indexes and the primary key, matching what plain NOT LIKE already does. The TYPE text index does not support NOT LIKE, with or without an ESCAPE clause.

Documentation entry for user-facing changes

  • Documentation is unchanged (the existing text-index docs already describe LIKE-based pruning; this only fills a coverage gap for the ESCAPE clause).

Description

Closes #105885. Follow-up to #99774, which added the ESCAPE clause.

... WHERE col LIKE pattern ESCAPE 'c' silently bypassed the primary key, the TYPE text index and the bloom-filter text indexes (ngrambf_v1, tokenbf_v1, sparse_grams), full-scanning even when such an index was defined.

Root cause: LIKE pattern ESCAPE 'c' parses into a 3-argument call like(col, pattern, escape_char), and MergeTreeIndexConditionText::traverseAtomNode, MergeTreeConditionBloomFilterText::extractAtomFromTree and KeyCondition::extractAtomFromTree accepted only 2-argument forms, so the 3-argument call was rejected before reaching the LIKE handler. Results were always correct, since FunctionsStringSearch::executeImpl already folds the custom escape with likePatternWithCustomEscapeToLikePattern; only performance was affected.

This applies the same fold at index-analysis time and dispatches through the existing 2-argument handler: like/ilike for the text index, like/notLike for the bloom-filter indexes and the primary key (ilike/notILike are absent from atom_map and keep falling back to row-level evaluation, as with 2 arguments). The pattern and the escape argument must both be constant strings, the escape a single ASCII byte; anything else declines the atom. The ASCII check mirrors the execution layer, so an invalid escape byte raises at planning time instead of being dropped by a downstream optimization.

Rebased onto #115634, now merged: the unknown-backslash-escape guard this PR used to carry is on master, so the diff here is the ESCAPE fold only.

Validation, one binary per arm with Build-IDs asserted: 04277_text_index_function_like_escape, 04292_105885_primary_key_like_escape and 04351_bloom_filter_text_index_like_escape all fail on master and pass with this change.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate

a) Deterministic repro? Yes. Without the fix, on commit 56b7c4ee3715:

SELECT trimLeft(explain) FROM (
    EXPLAIN indexes=1 SELECT count() FROM tab WHERE message LIKE '%World%' ESCAPE '|'
) WHERE explain LIKE '%Parts:%' OR explain LIKE '%Granules:%';
-- before: Parts: 4/4, Granules: 4096/4096  (index not used)
-- after:  Parts: 1/4, Granules: 1024/4096  (index used, same as plain LIKE)

b) Root cause explained? Yes. LIKE ... ESCAPE 'c' is parsed into like(col, pattern, escape_char). MergeTreeIndexConditionText::traverseAtomNode had if (function_arguments_size != 2) return false;, which rejected the 3-arg form before it reached the LIKE handler. Result correctness was never affected because FunctionsStringSearch::executeImpl already normalizes the pattern with the escape character at execution time via likePatternWithCustomEscapeToLikePattern. Only the index path was missing the same normalization.

c) Fix matches root cause? Yes. Apply the same likePatternWithCustomEscapeToLikePattern rewrite at index-condition time before dispatching through the existing 2-arg LIKE handler. The fix targets exactly the missing fold step, not a workaround.

d) Test intent preserved? / New tests added? New test 04277_text_index_function_like_escape.sql covers the previously-untested combination (text index + LIKE/ILIKE ... ESCAPE). It uses EXPLAIN indexes = 1 to assert that the index narrows parts and granules, so it actually catches the same regression in the future. Existing tests 02346_text_index_function_like, 02346_text_index_function_ilike, and 04040_like_escape all still pass.

e) Both directions demonstrated?

  • WITHOUT fix (stashed change, rebuilt, restarted server): test FAILS with diff lines showing the Description: text / Parts: / Granules: lines missing for ESCAPE queries.
  • WITH fix (un-stashed, rebuilt, restarted server): test PASSES 30/30 with full settings randomization.

f) Fix is general, not a narrow patch? The fix handles both like and ilike (the LIKE-family that text index supports for 2-arg form). The bloom-filter text index (MergeTreeIndexBloomFilterText) has the same 2-arg gate at line 378 and would benefit from a parallel fix; intentionally left out of this PR to keep the change minimal and to match what is exercised by the canonical 02346_text_index_function_like.sql family. Happy to file a follow-up if reviewers prefer.

Session: cron:clickhouse-ci-task-worker:20260526-113000.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @ahmadov — could you review this? It fills a coverage gap so that LIKE pattern ESCAPE 'c' and ILIKE pattern ESCAPE 'c' queries can still use a text index. MergeTreeIndexConditionText previously rejected the 3-arg form; the fix folds the escape character into the pattern (via the existing likePatternWithCustomEscapeToLikePattern helper) and dispatches through the existing 2-arg LIKE handler. Follow-up to PR #99774 at PedroTadim's request.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label May 26, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai LIKE ESCAPE is not supported by text indexes at the moment, and extra code is needed? If so, @ahmadov or @CurtizJ can review this?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim Yes, confirmed. MergeTreeIndexConditionText::traverseAtomNode previously bailed out at the function_arguments_size != 2 check, so the 3-arg like(col, pattern, escape_char) form produced by LIKE ... ESCAPE 'c' never reached the existing LIKE handler. The fix adds a 3-arg branch that folds the escape character into the pattern via likePatternWithCustomEscapeToLikePattern and dispatches through the same 2-arg path. Already cc'd CurtizJ and ahmadov in the comment above.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai add a test for the primary key case as described here #105885 , then this PR can close that issue.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 50fb54c (Use primary key for LIKE/ILIKE/NOT LIKE/NOT ILIKE with ESCAPE). Extended the same escape-fold to KeyCondition::extractAtomFromTree and added regression test 04292_105885_primary_key_like_escape.sql (operator form, functional form, and NOT LIKE ... ESCAPE with a remaining wildcard). The test FAILS on master without this commit and PASSES with it. PR description updated to reference Closes #105885.

Pre-PR validation gate for this follow-up commit:

# Question Status
a Deterministic repro? Yes. EXPLAIN indexes = 1 SELECT * FROM tab WHERE s LIKE 'abc|%' ESCAPE '|' shows Condition: true on master, Condition: (s in ['abc%', 'abc&')) with the commit.
b Root cause explained? Yes. LIKE ... ESCAPE parses to a 3-arg like(col, pattern, escape). extractAtomFromTree has only num_args == 1 and num_args == 2 branches, so the 3-arg form falls through to else { return false; } and no key range is built.
c Fix matches root cause? Yes. Add an early branch for 3-arg like/ilike/notLike/notILike, fold the custom escape via likePatternWithCustomEscapeToLikePattern, then dispatch through the existing 2-arg path.
d Test intent preserved? Yes. Existing 04277 still passes; the new 04292 adds coverage rather than weakening anything.
e Both directions demonstrated? Yes. 04292 fails on master (3 diff lines: Condition: true instead of the expected ranges) and passes with the commit. Verified locally with 20 randomized-settings iterations (40/40).
f Fix general, not narrow? Yes. All four like-family atoms in atom_map are covered. ilike/notILike are not in KeyCondition::atom_map, so they short-circuit at the existing atom_map check before the new branch (consistent with 2-arg ILIKE behavior). The text index half only handles like/ilike because MergeTreeIndexConditionText::isSupportedFunction does not list notLike/notILike.

@clickhouse-gh

clickhouse-gh Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [82d2ce3]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue ISSUE EXISTS
Stress test (arm_release) FAIL
Logical error: Initiator received more initial requests than there are replicas: replica_num=A (STID: 7334-48d5) FAIL cidb IGNORED
LLVM Coverage FAIL
Generate LLVM Coverage Diff Report FAIL cidb IGNORED
Print Uncovered Code FAIL cidb IGNORED

AI Review

Summary

This PR restores LIKE ... ESCAPE pruning for the existing MergeTree analyzer paths: the primary key, TYPE text indexes, and bloom-filter text indexes, while mirroring the execution-layer ESCAPE validation so invalid arguments still raise instead of being optimized away. I checked the current diff, traced the rewritten 3-argument paths through the unchanged helpers they reuse, and reconciled the open and resolved review threads against the current PR text and code. I did not find a remaining correctness, contract, or coverage issue in the current revision.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

⚠️ No coverage measurement for commit 82d2ce3: bash ci/jobs/scripts/generate_diff_coverage_report.sh failed (its output is on the Generate LLVM Coverage Diff Report result).

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 26, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai the arm tidy build failed, fix it

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 163fbaa. clang-tidy bugprone-empty-catch flagged the catch at MergeTreeIndexConditionText.cpp:515 (the new 3-arg like(col, pattern, escape) path). The catch was intentionally a no-op since the surrounding block falls through to return false, but the empty body did not convey that. Made it explicit by return false inside the catch (same pattern as the sibling fix in KeyCondition::extractAtomFromTree on this PR). No behavioral change.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 27, 2026
Per clickhouse-gh[bot] review on PR ClickHouse#105848: `KeyCondition::atom_map` only
contains `like` and `notLike`. The check `if (atom_map.find(func_name) ==
std::end(atom_map)) return false;` at the top of `extractAtomFromTree` rejects
`ilike` and `notILike` before they can reach the new 3-arg rewrite branch, so
listing them in the branch's condition and comment was misleading.

Drop `ilike`/`notILike` from the condition and rewrite the comment to document
the limitation: case-insensitive forms fall back to row-level evaluation, same
as the existing 2-arg behavior. The text index path (test 04277) still covers
all four forms because `MergeTreeIndexConditionText::traverseAtomNode` has its
own dispatch. Test 04292 (primary key) and its reference are unchanged because
they never exercised an ILIKE case.

This is a no-op refactor: cleans up dead branches in the source and the test
header. Extending primary-key pruning to `ilike`/`notILike` would require new
atom_map entries with case-folding-aware prefix extraction and belongs in a
separate PR.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@alexey-milovidov alexey-milovidov self-assigned this May 30, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 30, 2026
Per inline review on PR ClickHouse#105848: let the exception propagate from
`likePatternWithCustomEscapeToLikePattern` in both
`KeyCondition::extractAtomFromTree` and
`MergeTreeIndexConditionText::traverseAtomNode` instead of swallowing
it and bailing out. Matches what row-level evaluation in
`FunctionsStringSearch.h` does and surfaces an invalid escape sequence
at query planning time instead of execution time.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov done in f21f410. Removed the try/catch around likePatternWithCustomEscapeToLikePattern in both KeyCondition::extractAtomFromTree and MergeTreeIndexConditionText::traverseAtomNode so an invalid escape sequence propagates as CANNOT_PARSE_ESCAPE_SEQUENCE from index analysis (same as the row-level path in FunctionsStringSearch.h).

Verified locally with clickhouse-local:

  • valid LIKE 'abc|%' ESCAPE '|' still narrows the primary key to (s in ['abc%', 'abc&')) and the text index still selects 1/4 parts
  • invalid LIKE 'abc|' ESCAPE '|' now raises Code: 25, CANNOT_PARSE_ESCAPE_SEQUENCE at query planning time
  • 04277 and 04292 reference output unchanged

Pre-PR validation gate (6/6):

  • (a) deterministic repro: yes (above)
  • (b) root cause: silent try/catch was a fallback path swallowing the exception
  • (c) fix matches: drop the try/catch as requested
  • (d) test intent preserved: 04277 and 04292 still pass
  • (e) both directions: invalid pattern now throws from planning instead of execution; valid pattern still gets index pruning
  • (f) fix general: applied to both primary key and text index paths

session: cron:clickhouse-ci-task-worker:20260530-063000

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA df0c9c96a51cf78b9c3324ace9864f07ff04dd15

CI fully finished on this HEAD (last check completed 2026-06-04 07:37 UTC, 20-min ingestion buffer elapsed). Two non-PR-caused failures, both chronic, both tracked:

Failure Class Disposition
BuzzHouse (amd_debug) — Logical error: 'Inconsistent AST formatting (STID 1941-1bfa)' Chronic trunk fuzzer bug 81 distinct PRs hit it in 30d, 9 master hits. Crash query is INSERT INTO ... url('https://localhost:8443/...') with Enum16 identifiers, entirely unrelated to LIKE/ILIKE/ESCAPE. Tracked under issue #106358 and our internal task for STID 1941-1bfa (40+ PRs in 90d, 4 trigger shapes). Partial fix in PR #104991 merged 2026-05-31; tail still surfacing.
Performance Comparison (arm_release, master_head, 6/6) Chronic perf-noise Job-level failure (check_status = failure, no per-test FAIL rows). 30+ unrelated PRs hit it in 30d (#104976×12, #104591×9, #101796×5, etc.); only 1 master hit in 30d. Slower/unstable test basket rotates across runs (logical_functions_medium, min_max_index_with_cast, optimize_trivial_group_by_limit, uniqExactIf), no consistent regressing test. Affected tests are entirely unrelated to LIKE-ESCAPE / text index / KeyCondition changes in this PR.

No PR-caused failures on this HEAD.

Awaiting reviewer re-review (@CurtizJ or @ahmadov as suggested 2026-05-26).

Session id: cron:our-pr-ci-monitor:20260604-080000

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the unknown-backslash-escape wrong-results concern in commit 3ab6da51ec4.

The 3-argument LIKE ... ESCAPE pruning folds the escape into a standard-backslash pattern and dispatches it through the existing index and primary-key handlers. For an unknown backslash escape (backslash + a byte other than %, _, \), row-level matching keeps the literal backslash, but extractFixedPrefixFromLikePattern (primary key) and nextInStringLike (text index) drop it. The analyzer then built a prefix range / token set for the backslash-stripped pattern and could prune a part or granule that actually held matching rows.

Fix: added likePatternHasUnknownBackslashEscape and, at both analyzer sites, decline the index/PK condition when the rewritten pattern contains such a sequence, falling back to row-level evaluation. The other escape shapes (\%, \_, \\) are interpreted identically on both sides, so they continue to prune.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. With index_granularity = 2 and rows starting with a literal a\b, SELECT count() FROM t WHERE s LIKE 'a\b%' ESCAPE '\' returns 2 of 4 matching rows under primary-key pruning (full scan returns 4); with a splitByNonAlpha text index, LIKE '% a\b %' ESCAPE '\' returns 0 instead of 1. Both reproduced via clickhouse-local.
b Root cause explained? likePatternWithCustomEscapeToLikePattern('a\b%', '\') produces a\b%. Row-level matching reads \b as a literal backslash followed by b, but extractFixedPrefixFromLikePattern and nextInStringLike read \b as just b (backslash dropped). The analyzer therefore prunes against prefix ab / token ab, excluding the literal-backslash values (which sort below ab and tokenize as separate a/b).
c Fix matches root cause? Yes. The decline check fires exactly on \c where c is not %, _ or \ (the only shape where row-level and the extractors diverge), and only for the new 3-argument path. Other shapes still prune.
d Test intent preserved / new tests added? Existing valid-escape assertions in 04277 and 04292 are unchanged (still prune). New regression sections added to both: a primary-key case (LIKE 'a\b%' ESCAPE '\' returns all 4 rows, Condition: true) and a text-index case (LIKE '% a\b %' ESCAPE '\' returns the matching row, all granules scanned).
e Both directions demonstrated? Yes. Without the fix: PK 4 vs 2, text index 1 vs 0 (wrong). With the fix: 4 == 4 and 1 == 1, matching full-scan ground truth. A correctness matrix over \b / \\ / \% / \_ / plain confirms only the unknown-backslash case changed; all others still prune correctly.
f Fix is general, not a narrow patch? Yes. Both analyzer sites that fold a 3-argument LIKE ESCAPE are covered (KeyCondition::extractAtomFromTree and MergeTreeIndexConditionText::traverseAtomNode); these are the only two callers of likePatternWithCustomEscapeToLikePattern under src/Storages/MergeTree/. The shared row-level path was already correct and is unchanged.

Session id: cron:clickhouse-worker-slot-1:20260610-130800

Comment thread src/Common/likePatternToRegexp.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Follow-up commit 79faafb (extends the unknown-backslash-escape decline to the 2-argument LIKE paths, per the bot review on likePatternToRegexp.h).

# Question Answer
a Deterministic repro? Yes. optimize_rewrite_like_perfect_affix=0, then primary key: SELECT count() FROM t WHERE s LIKE 'a\b%' over a\b01..04,abZZ,zzz (index_granularity 2) returns 2 (should be 4); text index (splitByNonAlpha): SELECT count() FROM t WHERE msg LIKE '% a\b %' over a row holding literal a\b returns 0 (should be 1).
b Root cause explained? extractFixedPrefixFromLikePattern (PK) and nextInStringLike (text index) drop the backslash for an unknown escape \c, while likePatternToRegexp (row level) keeps it. With the affix rewrite disabled the 2-arg LIKE reaches the analyzers as like/notLike, so they build a prefix range / token set for the backslash-stripped pattern and prune parts/granules that actually match.
c Fix matches root cause? Yes. Adds the likePatternHasUnknownBackslashEscape decline at the shared 2-argument dispatch in KeyCondition::extractAtomFromTree and at the 2-argument like handler in MergeTreeIndexConditionText. Such patterns fall back to row-level evaluation. \%, \_, \\ are interpreted identically on both sides and still prune.
d Test intent preserved / new tests added? Existing 3-arg sections unchanged and still pass. Added 2-argument regression cases to 04277 (text index) and 04292 (primary key), each asserting the correct row count and that the index/PK declines (Condition: true / all granules scanned).
e Both directions demonstrated? Yes. PK: without fix count=2, with fix count=4. Text index: without fix count=0, with fix count=1. Verified on a debug build by stashing the fix, rebuilding, and comparing.
f Fix is general, not a narrow patch? Covers both analyzer sites that feed like patterns into the backslash-dropping extractors (PK + text index), for both the 3-arg rewritten and plain 2-arg forms. The deeper extractor/tokenizer mismatch (which also makes LikePerfectAffixRewritePass wrong at row level at default settings) is pre-existing and core; flagged in the inline reply for a separate focused PR rather than widening this one.

Session id: cron:clickhouse-worker-slot-7:20260610-151400

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (map LIKE backslash decline, 4f9c52f)

# Question Answer
a Deterministic repro? Yes. Text index on mapKeys/mapValues (splitByNonAlpha), key foo a\b bar and value foo a\b baz. mapContainsKeyLike(m, '% a\b %') / mapContainsValueLike(m, '% a\b %') return no rows with the index (EXPLAIN indexes=1 shows Granules: 0/3) while a full scan returns the matching row. On demand, every run.
b Root cause explained? The map LIKE branches call stringLikeToTokens directly. nextInStringLike drops the backslash for an unknown escape \c, so it requests token ab; splitByNonAlpha indexed the value as separate tokens a and b, so token ab is absent and the granule is pruned. Row-level LIKE keeps the literal backslash and matches, so the index produces a false negative (wrong results). Same divergence class already fixed for the plain like branch.
c Fix matches root cause? Yes. Declines mapContainsKeyLike / mapContainsValueLike via the existing likePatternHasUnknownBackslashEscape check before stringLikeToTokens, falling back to row-level evaluation, exactly mirroring the plain like and the 2-arg/3-arg fixes already in this PR. Not a symptom guard: it stops the index from answering a pattern it tokenizes inconsistently.
d Test intent preserved / new tests added? New regression added to 04277_text_index_function_like_escape: text index on mapKeys/mapValues, asserts the matching key and value rows are returned and the index declines (Granules: 3/3) for the unknown-backslash pattern, plus a control proving a valid pattern still prunes (Granules: 1/3). No existing assertions weakened.
e Both directions demonstrated? Yes. Without the fix the regression fails (rows 1,2 missing, Granules: 0/3 for both map functions). With the fix it passes (rows returned, Granules: 3/3), and the control still prunes (Granules: 1/3). Verified by reverting only the source change, rebuilding, and re-running.
f Fix is general, not a narrow patch? Yes. Grepped all stringLikeToTokens call sites in MergeTreeIndexConditionText.cpp: the three callers (mapContainsKeyLike, mapContainsValueLike, plain like) are now all guarded. The deeper root cause (nextInStringLike / extractFixedPrefixFromLikePattern disagreeing with likePatternToRegexp for unknown backslash escapes) is pre-existing and was flagged earlier in this PR for a separate focused PR; this PR keeps index/PK pruning consistent with row-level by declining.

Session id: cron:clickhouse-worker-slot-4:20260610-220500

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on f9092af2. One job failed, and it is not caused by this PR.

AST fuzzer (amd_debug): Logical error: 'index >= result.start' (STID 2508-6d1e) in FunctionSecretArgumentsFinder::markSecretArgument via findS3FunctionSecretArguments (a fuzzed s3() call with mixed named/positional arguments). This PR only touches text-index LIKE/ILIKE matching (MergeTreeIndexConditionText.cpp, KeyCondition.cpp, likePatternToRegexp), not the secret-arguments finder. 0 master hits in 30d (STID first seen 2026-06-18, also on one unrelated fuzzer run the same day). Already fixed on master by #107818 (merged 2026-06-18 13:18Z); this branch predates that commit (behind by 12), so a rebase clears it.

Mergeable Check, PR and CH Inc sync are cascades of that single AST fuzzer failure.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105848&sha=f9092af21261071d30d67a3715dbb3901f2c0f1c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

(cron:our-pr-ci-monitor:20260619-003000)

@alexey-milovidov

Copy link
Copy Markdown
Member

Re-merged master into the branch (f9092af2126..3a798cd1bd8) to clear the sole CI failure.

The only red was the AST fuzzer (amd_debug) Logical error: 'index >= result.start' (STID: 2508-6d1e), which is unrelated to this PR. The stack trace shows it originates in FunctionSecretArgumentsFinder::markSecretArgument → findS3FunctionSecretArguments (the S3 secret-argument masker for a fuzzer-generated s3() call) — this PR touches only likePatternToRegexp, KeyCondition.cpp, and MergeTreeIndexConditionText.cpp. The same STID also hit unrelated PR #106189 the same day, confirming it is a master-level latent bug, not a regression here.

That bug was fixed on master by commit 3b213912e43 ("Do not abort the secret arguments finder on mixed named and positional arguments"), which widens the masked range instead of asserting on argument order. The re-merge brings that fix into this branch (verified result.start = std::min(result.start, index); is present in the merged tree), so the crash can no longer reproduce.

The merge is clean: master's KeyCondition.cpp changes (16 commits, e.g. the boolean_context parameter and tryRewriteCoalesceCondition) land in disjoint regions; this PR's escape-fold additions are byte-identical and untouched. No unresolved review threads remain and the AI review verdict is ✅ Approve; the PR remains BLOCKED only on human maintainer approval (PedroTadim cc'd @CurtizJ / @ahmadov).

Without the ESCAPE clause the predicate matches no rows; the index keeps the
second part as a candidate, which is what produces the 16-granule plan. Say
that instead of claiming a row match.
@ahmadov

ahmadov commented Aug 25, 2026

Copy link
Copy Markdown
Member

@groeneai can you apply the similar "comment removal" changes suggested by @rschu1ze in tests files (changed by this PR)? Also, remove comments for settings why they are used e.g.:

-- The cache would answer a repeated query without reporting granule counts.
SET use_query_condition_cache = 0;

… tests

Extends the comment cleanup to the test files. Removes the per-SET rationale
comments, the no-parallel-replicas tag rationale, the fixture granularity note
and the two comments restating what the adjacent query already says.

Comments only. Every executed statement is byte-identical to the previous
revision (verified by stripping comment lines from both and comparing), the
tests do not run in `-- { echo }` mode, and none of the three `.reference`
files changed.

Kept the byte-level clarifications spelling out how many backslashes a SQL
literal denotes, and the note recording that the `literal 50 discount token`
row is what makes the 16-of-48-granule arm non-vacuous: a reader cannot
recover either from the code, and the latter is the only record that the arm
can redden.

Facts moved here rather than into a comment: `use_query_condition_cache = 0`
is set because the query condition cache would answer a repeated query
without reporting granule counts; `no-parallel-replicas` is set because
`EXPLAIN indexes = 1` prints the local primary-key analysis and a
parallel-replicas plan changes the output; the 04292 fixture uses
`index_granularity = 8192` so its five rows land in one granule and the
primary-key ranges read 1/1.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in b916a23.

Removed the per-SET rationale comments you pointed at (use_query_condition_cache = 0 in both 04277 and 04351), the no-parallel-replicas tag rationale in 04292, the fixture granularity note, and the two comments that only restated what the adjacent query already said.

You are right that my earlier pass left this category behind. My 18:29 reply said I had cleaned 04292 and 04351 "the same way", and that was true for the engine-internals references only; the settings comments survived it.

Two comments deliberately stay. The byte-level ones spelling out how many backslashes a SQL literal denotes, because 'a\\b01' is ambiguous on the page. And the note above the literal 50 discount token insert in 04277, because that row is what makes the 16-of-48-granule arm non-vacuous: without it the same query reads 8 of 40 granules from a single part, so deleting the note would drop the only record that the arm can redden. The reasons for the comments I did remove are in the commit message instead.

Comments only, so no re-approval needed for behavior. Every executed statement is byte-identical to the previous revision (checked by stripping comment lines from both revisions and comparing), the tests do not use -- { echo } mode, and none of the three .reference files changed. All three pass locally.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b916a23

Every failure below has an owner: a fixing PR (ours 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
Docker server image / clickhouse/clickhouse-server:head-arm64 infra, not this diff: us-east-1.ec2.ports.ubuntu.com returned 503 for arm64 packages, so the apt stage of docker/server/Dockerfile.ubuntu died with exit code: 100. The merged Canonical-mirror fallback did not fire because its buildx anchor token is misspelled, so the retry ladder stopped at apt mirror 1/2 #116441 (ours, open)
Mergeable Check aggregator verdict, driven solely by the Docker server image row above #116441 (ours, open)
Sync - CH Inc sync (private, not actionable)

The same arm64 mirror burst hit true master at least 5 times plus 12 other PR carriers in the
same window, and no *-amd64 or *-alpine-* image row failed at all, which is what places the
cause at the ports mirror rather than at any diff.

Every functional, integration, stress, fuzzer and performance check on this head is green.

Session id: cron:our-pr-ci-monitor:20260826-043752

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

Also, try to merge the latest origin/master into it again.

--
-- Issue: https://github.com/ClickHouse/ClickHouse/issues/105885

SET enable_analyzer = 1;

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.

let's add SET use_query_condition_cache = 0;

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.

Added right after SET enable_analyzer = 1; in 9f5bb91.

04292 was the only one of the three files without the pin. The setting defaults to 1 and tests/clickhouse-test randomizes it per run, so roughly half of the runs had the cache enabled while these arms assert Parts:/Granules: counts. .reference is unchanged.

Per review. 04292 was the one file in the trio without the pin, while its
two siblings already carry it.

The setting defaults to 1 and is randomized per run by
`tests/clickhouse-test` (`"use_query_condition_cache": lambda:
random.randint(0, 1)`), so without the pin the cache is enabled in about half
of all CI runs. Two of the arms fold to the identical condition
`(s in ['abc%', 'abc%'])` on the same table, one through the operator form
and one through `like(s, pattern, escape)`, which is exactly the shape a
cache entry can answer, and the arms assert `Parts:`/`Granules:` counts.

Test file only, no behavior change.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both asks are in 9f5bb91.

SET use_query_condition_cache = 0; is now in 04292, right after SET enable_analyzer = 1;, with no rationale comment.

Merged the latest master (4606a6e39e320ba76402118f7632ac2184533c34), no conflicts. Master moved the text index pre/postprocessor in that window, so I re-ran all three tests against the merged tree: 04277, 04292 and 04351 reproduce their .reference byte for byte, and no reference file changed. Behaviour is unchanged, so I am not re-requesting review.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9f5bb91

Every failure below has an owner: a fixing PR (ours 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
Stress test (amd_debug) / STID 1941-26fa, Inconsistent AST formatting on CREATE TABLE ... AS numbers(10) PRIMARY KEY tuple(number) trunk defect, not caused by this PR #116645 (ours, open)
Stress test (amd_tsan) / STID 2945-3346, Column x UInt8 query tree node does not have valid source node trunk defect, not caused by this PR #111327 (ours, open)

CI is fully finished at this head: 175 unique check runs, 0 incomplete, one parent workflow run
(33078328364), and Config Workflow, Style check and Finish Workflow all success. The praktika
report has 178 nodes, 0 DROPPED. CIDB returns 306k+ rows at this commit, of which exactly the two
failures above are ownable, so the classification is a measurement and not an empty read.

Neither red is caused by this PR, whose diff is confined to KeyCondition.cpp,
MergeTreeIndexBloomFilterText.cpp, MergeTreeIndexConditionText.cpp and its own tests.

STID 1941-26fa is a CREATE TABLE ... AS <table function> round-trip formatting defect: the failing
statement is CREATE TABLE test_1.t3__fuzz_16 (number UInt64) AS numbers(10) PRIMARY KEY tuple(number),
whose metadata is written in a form the parser cannot read back. #116645 names this exact STID in its
description and fixes that statement class. Over 30 days the signature measures 152 rows across 109
distinct PRs with 3 true-master hits (a fabricated-phrase control returns 0), so it is a wide trunk
defect rather than anything specific to this branch.

STID 2945-3346 aborts in ColumnNode::getColumnSource() reached from
ReadFromMerge::applyFilters -> filterTablesAndCreateChildrenPlans -> createPlanForTable ->
StorageDistributed::read -> the analyzer, which is exactly the mechanism #111327 fixes: a bare-column
predicate left in the per-table child query that ReadFromMerge builds, whose source is then dangling
when the Distributed child is re-planned for the shards. Over 30 days that signature measures 12 rows
across 12 distinct PRs, every one of them through CollectSourceColumnsVisitor, with 0 true-master hits.

Session id: cron:our-pr-ci-monitor:20260827-190000

@ahmadov

ahmadov commented Aug 31, 2026

Copy link
Copy Markdown
Member

@groeneai merge the latest origin/master again into this branch and fix conflict.

Resolves one conflict in MergeTreeIndexConditionText.cpp, where master's
explicit-tokenizer overload (ClickHouse#115348) and this branch's LIKE ESCAPE fold both
claim the three-argument branch of traverseAtomNode.

Both are kept. The LIKE ESCAPE case is checked first because it is gated on the
function name and returns on every path; tokenizerArgumentMatchesIndex accepts
only hasAnyTokens, hasAllTokens and hasPhrase, so with the order reversed it
would reject like/ilike before the fold ran and the index would stop answering
LIKE ... ESCAPE. Everything else with three arguments still goes through
master's tokenizer check.

Merged master commit: 595bd75
canAnswerFunctionNode sends every three-child function node through
tokenizerArgumentMatchesIndex, which accepts only hasAnyTokens, hasAllTokens
and hasPhrase. A folded `like`/`ilike` atom therefore built a search query and
had it discarded again in selectConditions, so `LIKE ... ESCAPE` got granule
pruning but not the direct-read rewrite its two-argument form gets.

Measured on this tree before the change, with the two-argument form as a
live-channel control:

  s LIKE '%foo%'            Prewhere filter column: s LIKE '%foo%' AND __text_index_idx_s_like_eca00f43...
  like(s, '%foo%', '#')     Filter column: like(s, '%foo%', '#')

and after it both forms produce the same __text_index_idx_s_like_eca00f43...
column, which is also evidence the fold is exact. A three-argument
hasAnyTokens whose tokenizer does not match the index is still rejected, so
the tokenizer check keeps its meaning.

Safe because none of needApplyTokenizer, needApplyPreprocessor or
needApplyPostprocessor names `like`, so applyTransforms returns before the
point where a third argument would be overwritten with a tokenizer
description.

The new arm in 04277 asserts the column for the ESCAPE form with the
two-argument form beside it; turning the two plan settings off in that arm
flips its result from 1 to 0, so it can fail.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged the latest origin/master (595bd75f7931b7f45b9752d6200319c064a6a47c) and resolved the conflict.

The conflict is a single one, in MergeTreeIndexConditionText.cpp: the explicit-tokenizer overload from #115348 and this branch's LIKE ... ESCAPE fold both claim the three-argument branch of traverseAtomNode. I kept both, with the like/ilike case first. That order is load bearing: tokenizerArgumentMatchesIndex accepts only hasAnyTokens, hasAllTokens and hasPhrase, so the reverse order rejects like before the fold runs and the index stops answering LIKE ... ESCAPE at all.

Resolving it textually was not enough. canAnswerFunctionNode routes every three-child node through that same tokenizer check, and selectConditions builds the folded search query and then discards it there, so after the merge the ESCAPE form kept granule pruning but lost the direct-read rewrite that its two-argument form gets. Measured on the merged tree, with the two-argument form as a live-channel control:

s LIKE '%foo%'           Prewhere filter column:  s LIKE '%foo%' AND __text_index_idx_s_like_eca00f43...
like(s, '%foo%', '#')    Filter column:           like(s, '%foo%', '#')

The second commit exempts like and ilike there, since their third argument is an escape character and not a tokenizer. Both forms now produce the same __text_index_idx_s_like_eca00f43... column, which is also evidence that the fold is exact, and a three-argument hasAnyTokens whose tokenizer does not match the index is still rejected. This is safe at the rewrite site because none of needApplyTokenizer, needApplyPreprocessor or needApplyPostprocessor names like, so applyTransforms returns before the point where a third argument would be overwritten with a tokenizer description.

04277 gained an EXPLAIN actions = 1 arm for this, with the two-argument form beside it; turning the two plan settings off in that arm flips its result from 1 to 0, so it can fail. No .reference row of the existing arms changed, and 04277, 04292 and 04351 all reproduce their references byte for byte on the merged tree, as do 13 of the 14 tests in the text-index tokenizer family that master moved in this window (the fourteenth reads system.query_log, which my local server does not enable).

Behaviour for the two-argument forms is unchanged from the tree you approved.

The two commits are going up to the branch now.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2472b21

CI is fully finished at this commit. One job of 170 failed, it has an owner, and it is not caused by this diff: the change touches three files under src/Storages/MergeTree/ plus six stateless tests, and no CI configuration.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) Job-level container-memory abort with no failing test assertion. dmesg-follow.log records 6 constraint=CONSTRAINT_MEMCG kills of nested containers under the /docker cgroup leaf, victims gdb x4 and clickhouse x2. #117202 is present in this tree and serialized the shutdown gdb attach, which cleared the 2/6 and 5/6 shards, but 6/6 is a measured residual of it, so what is left to size is the leaf's own cap rather than the attach concurrency #117411 and #117412 (external, open)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105848&sha=2472b21ec51ced554f0603b8add70b956c2576e6&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29

Session id: cron:our-pr-ci-monitor:20260901-050000

@ahmadov
ahmadov removed this pull request from the merge queue due to a manual request Sep 2, 2026
…ape_bug105885

The leading 04292_105885_ read like two test numbers. The issue number now
follows the description, as bug105885.
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 82d2ce3

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, and it passed at this
head, so it gets no row.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Logical error: Initiator received more initial requests than there are replicas: replica_num=0 (STID 7334-48d5) pre-existing trunk defect in the parallel replicas coordinator, unreachable from this diff (text index for LIKE/ILIKE with ESCAPE). Keyed on the assertion text over 90 d: 21 rows across 20 distinct pull requests and 1 true-master tree (82cfa6a421bb, 2026-08-26), first seen 2026-08-08; the needle-removed control returns 3.4e9 rows, so that is not a vacuous count #115786 (mine, open): the server-side AST fuzzer re-entering a collaborative worker context, which reaches this guard as well as the sibling Duplicate announcement received for replica number N message
Stress test (amd_asan_ubsan) / Logical error: Not-ready Set is passed as the second argument for function 'globalNotIn' (STID 0250-41a5) pre-existing trunk on the object-storage _path / _file prefilter, not a query plan and not this branch: the abort runs StorageObjectStorageSource::createFileIterator into VirtualColumnUtils::filterByPathOrFile, getFilterByPathAndFileIndexes, filterBlockWithExpression (src/Storages/VirtualColumnUtils.cpp:163) and FunctionIn::executeImpl (src/Functions/in.cpp:155), under ReadFromObjectStorageStep::createIterator, i.e. while the pipeline is being built, where a GLOBAL set is deliberately still unbuilt #112968 (external, open): it changes exactly those frames so pruning is deferred when a set is not ready, and its own test covers WHERE _path GLOBAL IN and GLOBAL NOT IN
LLVM Coverage / Generate LLVM Coverage Diff Report + Print Uncovered Code CI infra, not this branch: the coverage baseline lookup still asks for a master key that resolves in none of the tracked commits, and the second leaf did not run because the first failed #117718 (external, open)

Mergeable Check names Stress test (arm_release) and LLVM Coverage; the amd_asan_ubsan stress
red is non-gating and is listed anyway so the set is complete.

Session id: cron:our-pr-ci-monitor:20260903-030000

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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product 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.

3-arg LIKE ... ESCAPE bypasses primary key and text index conditions due to arity-gated rejection

6 participants