Skip to content

Fix text index LOGICAL_ERROR with constant folding and partition key - #110770

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-text-index-constant-folding-partition-key
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-text-index-constant-folding-partition-key

Conversation

@groeneai

@groeneai groeneai commented Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #104582

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix a LOGICAL_ERROR ("Query builder not found for text search query with function") when a query filters a column that has a text index and is also the partition key, with the setting use_constant_folding_in_index_analysis enabled.

Description

Introduced in 26.7 by #104582. It needs use_constant_folding_in_index_analysis = 1 (default 0); with it, the query in the test fails on 26.9.19.9 with Query builder not found for text search query with function 'like' (LOGICAL_ERROR).

The text index direct-read path registers its virtual columns against the unsubstituted condition at plan time (the virtual column name embeds the unsubstituted search-query hash), and the reader looks them up via generateUnsubstituted(). When use_constant_folding_in_index_analysis is on and the text-indexed column is also the partition key, the granule analyzer was built from the per-partition constant-folded condition instead, whose search queries hash differently. The reader could not find the query builder and threw the logical error (server abort in debug/sanitizer builds).

The fix keeps constant folding off for text index conditions that contain a direct-read search query, so the granule analyzer and the reader use the same unsubstituted set of search queries. Other index types are unaffected.

Found by the AST fuzzer (STID 3694-54bc), report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100173&sha=e196b05a52cdcdcdf80b1f6c6a41071b5deec053&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

The text index direct-read path registers virtual columns against the
unsubstituted condition at plan time (the virtual column name embeds the
unsubstituted search-query hash) and the reader looks them up via
generateUnsubstituted(). With use_constant_folding_in_index_analysis and the
indexed column also being the partition key, the granule analyzer was instead
built from the per-partition constant-folded condition, whose search queries
hash differently. The reader then failed to find the query builder and threw
LOGICAL_ERROR "Query builder not found for text search query with function".

Keep constant folding off for text index condition templates so the granule
analyzer and the reader use the same (unsubstituted) set of search queries.

Found by the AST fuzzer (STID 3694-54bc).

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT s FROM tab WHERE s LIKE '%...%' SETTINGS use_constant_folding_in_index_analysis=1 on a text-indexed column that is also the partition key aborts the server every time with the exact CI error.
b Root cause explained? The optimizer registers direct-read virtual columns against the unsubstituted condition (the virtual column name embeds the unsubstituted search-query hash), and the reader looks them up via generateUnsubstituted(). With constant folding on and the indexed column = partition key, the granule analyzer was built from the per-partition constant-folded condition (via generateForPartition), whose search queries hash differently. The unsubstituted hash is then absent from the folded analyzer's query_builders map → getQueryBuilder throws LOGICAL_ERROR.
c Fix matches root cause? Yes. It forces skip_constant_folding for the text index's own condition template, so the granule analyzer and the reader use the same (unsubstituted) search-query set. It targets the exact inconsistency, not the throw site.
d Test intent preserved / new tests added? New regression test 04424_text_index_constant_folding_partition_key added; it aborts pristine master and passes with the fix. Also asserts result correctness (hasToken count matches). No existing test weakened.
e Both directions demonstrated? Yes. Pristine master (Build ID 08FB80): server aborts with "Query builder not found for text search query with function 'like'". With fix (Build ID C2AD7E): 15/15 runs pass, server alive, results correct.
f Fix is general across code paths? Yes. The hash-keyed virtual-column direct-read mechanism is unique to the text index (isTextIndex()); other index types (minmax, set, vector) have no such plan-time/read-time hash coupling and keep constant folding. All text-index reader lookup sites (classifyVirtualColumns, posting build, direct fill) go through the one analyzer that is now consistent.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The inconsistency is independent of column datatype/wrapper — it stems from partition-vs-unsubstituted condition divergence for any Hint-mode text-search function (like, startsWith, endsWith, equals, hasPhrase, ...). Disabling folding for the whole text-index condition template covers all of them regardless of predicate/tokenizer/preprocessor.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, on-disk/wire format, or validation change. use_constant_folding_in_index_analysis still folds for all non-text indexes; only text-index granule analysis stops folding (it never produced a correct/usable result there — it crashed). No behavior a user could have relied on is removed.
i Invariants and contracts preserved? Yes. The restored invariant is exactly the one the reader relies on: the granule analyzer's query_builders must contain the search-query hashes the reader looks up. ConditionTemplate::generateForPartition already falls back to generateUnsubstituted() when skip_folding is set, so text-index granule filtering and the reader now share one condition instance on all paths.

Session id: cron:clickhouse-worker-slot-2:20260717-004400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @ahmadov — could you review this? The text index direct-read path registers virtual columns against the unsubstituted condition but the granule analyzer was built from the per-partition constant-folded condition when use_constant_folding_in_index_analysis is on and the indexed column is also the partition key, so the reader's search-query hash was missing from the analyzer (LOGICAL_ERROR). The fix keeps constant folding off for text index condition templates. Found by the AST fuzzer.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [74a672d]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
Server died FAIL cidb
Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) FAIL cidb, issue
BuzzHouse (amd_debug) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) FAIL cidb

AI Review

Summary

This PR fixes the LOGICAL_ERROR caused by hashing text-index virtual columns from the unsubstituted predicate while the granule analyzer was built from a per-partition folded one. The main fix and the regression test are directionally right, but the new skip_folding guard is still broader than the reader-backed path that needs hash stability, so it regresses partition specialization for some queries where no virtual-column lookup happens at all.

Findings

⚠️ Majors

Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 17, 2026
Only skip per-partition constant folding for a text index when its
condition actually contains a non-None direct-read query, i.e. one that
emits a direct-read virtual column looked up by the reader via
generateUnsubstituted(). None-mode conditions (match, multiSearchAny*,
multiMatchAny, hasAny on non-array tokenizers, LIKE with
query_plan_text_index_add_hint = 0) are dropped before the
virtual-column rewrite and never looked up, so they keep their
per-partition constant-folding specialization.

Pin query_plan_direct_read_from_text_index and query_plan_text_index_add_hint
in the regression test so CI randomization cannot route the query away
from the virtual-column lookup path that this fix targets.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
[](const auto & entry) { return entry.second->getDirectReadMode() != TextIndexDirectReadMode::None; });

if (has_direct_read_query)
condition_template = std::make_shared<ConditionTemplate<MergeTreeIndexConditionPtr>>(

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.

getDirectReadMode() != TextIndexDirectReadMode::None is still broader than the path that needs the hash-stable unsubstituted condition here. getDirectReadMode() depends only on the function/index shape; it does not check the global query_plan_direct_read_from_text_index switch, while processAndOptimizeTextIndexFunctions only emits the reader-backed virtual columns when that optimization setting is on. With SET query_plan_direct_read_from_text_index = 0, this branch still rebuilds the template with skip_folding = true, so generateForPartition stops specializing partition-key text-index predicates (LIKE, hasToken, hasPhrase, etc.) even though nothing will ever look them up via generateUnsubstituted().

Can we gate this on the direct-read plan setting as well (or otherwise on whether a virtual column will actually be emitted), and add a regression test for the query_plan_direct_read_from_text_index = 0 case?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — cdb195f

Every failure below has an owner: a fixing PR. None is PR-caused (this PR only touches the text-index constant-folding guard and its regression test).

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: ScatterExchangeStep should have one source shard (STID 4636-3f0c) crash #108401 (ours, open) — Issue #107946
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky #110030 (ours, open)
Stateless tests (amd_tsan, parallel) / 04498_query_condition_cache_local_files flaky #110763 (external, open)

Session id: cron:our-pr-ci-monitor:20260717-143000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — cdb195f

CI fully finished on this head (Finish Workflow SUCCESS). All failures owned; none PR-caused (all unrelated to the text-index constant-folding fix).

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) / 04498_query_condition_cache_local_files flaky (instance-wide QueryConditionCache wiped by a parallel sibling; 21 unrelated PRs, 14d) #110763 (external, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / ScatterExchangeStep should have one source shard (STID 4636-3f0c) crash (distributed scatter-exchange, unrelated to text index) #108401 (ours, open)
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (known, #110036) #110030 (ours, open)

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

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.80% -0.10%
Branches 78.50% 78.30% -0.20%

Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 74a672d

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 (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Server died + Logical error: Got read request from replica A for unknown stream B (STID 5217-5b3d) with parallel replicas, a projection optimization replaces the initiator's ReadFromMergeTree with a ReadFromPreparedSource, so the empty-read-set announcement is skipped and a follower requests a stream the coordinator never registered #111689 (mine, open)
BuzzHouse (amd_debug) / Logical error: Inconsistent AST formatting (STID 1941-1bfa) a CAST nested inside a notEquals argument list does not round-trip through the formatter; long-standing trunk family, 40+ unrelated PRs in 90 days a fix task is tracking it (investigating at full effort — fixing-PR link to follow here)

The Server died row and the unknown stream row are one event with one owner: the logical error
aborts the server, and Server died is its consequence.

Neither family is caused by this PR's diff (a text-index constant-folding fix plus its stateless
test): both reproduce on master and across many unrelated PRs.

Session id: cron:our-pr-ci-monitor:20260729-060000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 4, 2026
@rschu1ze

rschu1ze commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Introduced by #104582, doesn't reproduce with the default settings.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Right, it needs use_constant_folding_in_index_analysis = 1 (default 0). With that setting the test query still fails on the 26.9.19.9 release (Code: 49. DB::Exception: Query builder not found for text search query with function 'like' ... (LOGICAL_ERROR)) and on current master, so I kept Bug Fix and added #104582 to the description.

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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants