Skip to content

Support text indexes with distributed plan execution - #114242

Draft
CurtizJ wants to merge 5 commits into
ClickHouse:masterfrom
CurtizJ:text-index-direct-read-distributed
Draft

CurtizJ wants to merge 5 commits into
ClickHouse:masterfrom
CurtizJ:text-index-direct-read-distributed

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Aug 10, 2026

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

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

Direct read from a text index now works in distributed query plans: with make_distributed_plan = 1 and with plan-based parallel replicas.

Fixes #112723.
Fixes #108818.
Fixes #109329.

CurtizJ and others added 3 commits August 10, 2026 16:16
The direct-read optimization replaces text-search functions with
`__text_index_*` virtual columns before a plan is split for
`make_distributed_plan` or captured for plan-based parallel replicas.
The serialized `ReadFromMergeTree` did not carry the state behind those
columns, so the receiving node rebuilt the step from its own table and
failed with `NOT_FOUND_COLUMN_IN_BLOCK`, and the feature had to be
disabled under `make_distributed_plan` via a settings quirk.

Ship the state with the plan instead (query plan serialization
version 6): for every index read task, the index name, `is_final`, the
condition's `global_search_mode`, and per virtual column its
`TextSearchQuery` and default expression (evaluated for parts without
the materialized index and for abandoned pattern scans). On
deserialization the virtual columns are registered in the storage
snapshot before the step is built, and the index read tasks are rebuilt
against the receiving node's own metadata. Search patterns are
recompiled from their retained `%token%` LIKE sources, because a
compiled `OptimizedRegularExpression` is not serializable. A peer below
serialization version 6 is rejected with `SUPPORT_IS_DISABLED` instead
of being sent a payload it would misparse.

Remove the `make_distributed_plan` settings quirk that disabled
`use_skip_indexes_on_data_read` and
`query_plan_direct_read_from_text_index`, and the rejections of
bucketed distributed reads that carry index read tasks.

Closes: ClickHouse#109329
Related: ClickHouse#108818
Related: ClickHouse#112723

Co-Authored-By: Claude Fable 5 <[email protected]>
The flag fed the can_skip_marks decision of MergeTreeReaderTextIndex
(a FINAL read must not skip marks before the merging algorithm), but
commit 69bdbf3 moved granule analysis out of the reader and deleted
the only consumer, leaving the field write-only. Drop the field, the
is_final parameter of createReadTasksForTextIndex, and its byte in the
serialized text index read task payload (safe: query plan serialization
version 6 is introduced by this branch and has not been released).

Co-Authored-By: Claude Fable 5 <[email protected]>
Add to 04836 and 04837 the scenarios that the rejected-behavior tests of
the superseded PRs covered and the new positive tests did not: the AST
fuzzer shape with a mixed PREWHERE conjunction and a xor in WHERE, a text
index read shipped through a subquery under a shuffle join (both from
ClickHouse#108818), and a join whose
side carries a direct text-index read with a filter-sensitive result
(from ClickHouse#112723). Every query
is repeated with the distributed mode off and must return identical
results.

Related: ClickHouse#108818
Related: ClickHouse#112723

Co-Authored-By: Claude Fable 5 <[email protected]>
@CurtizJ
CurtizJ marked this pull request as draft August 10, 2026 22:13
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8343985]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Query builder not found for text search query with function 'A (STID: 3694-54bc) FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Query builder not found for text search query with function 'A (STID: 3694-54bc) FAIL cidb
Stress test (arm_asan_ubsan, s3) FAIL
Sanitizer (STID: 1367-26c6) FAIL cidb, issue

AI Review

Summary

This PR teaches serialized ReadFromMergeTree fragments to carry the __text_index_* state that distributed plans and plan-based parallel replicas need for remote direct reads from text indexes, and it removes the old make_distributed_plan setting quirk that disabled that path. The serialization/deserialization flow and regression coverage look good overall, but one correctness issue remains: the remote side still rebinds shipped text-index queries to whatever current index definition has the same name, so a concurrent index redefinition can silently change results instead of failing closed.

Missing context / blind spots
  • ⚠️ I could not fully validate the shared-storage stateless-worker path from this checkout, because the ReadFromMergeTreeAtWorker implementation referenced by makeDistributed.cpp is not present here. That gap closes if ReadFromMergeTreeAtWorker::canCreateFrom is verified to reject reads with index_read_tasks, or if there is a focused shared-storage worker test for distributed text-index direct reads.
Findings

❌ Blockers

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:5818-5847] The restored task only verifies index_name / isTextIndex() and then binds the shipped TextSearchQuery objects to the worker's current MergeTreeIndexText helper. If the table is altered after planning but before fragment execution and the index keeps the same name (different tokenizer, preprocessor, postprocessor, or support_phrase_search, or a drop/add with a new definition), the worker can interpret already-tokenized queries against a different index definition and either return wrong rows or fail in a definition-specific way instead of rejecting the stale plan. Suggested fix: serialize a stable fingerprint of the text-index definition (at least the semantics-affecting arguments and any format capability the query depends on) and throw on mismatch during restoreTextIndexReadTasks, or ship only source predicate state and rebuild each TextSearchQuery from the validated worker metadata.
Final Verdict

Request changes: distributed text-index direct reads are close, but the current restore path still is not fail-closed across concurrent index redefinitions.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 263/282 (93.26%) · Uncovered code

Full report · Diff report

task.index_name, data.getStorageID().getNameForLogs());
}

auto index_helper = MergeTreeIndexFactory::instance().get(metadata_snapshot, *index_it, *data.getSettings());

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.

The restored task only checks index_name and isTextIndex() before binding the shipped TextSearchQuery objects to the receiver's current index metadata. If the table is altered between planning and execution but the index keeps the same name (different tokenizer/preprocessor/postprocessor/phrase-search support, or a drop/add with a new definition), these already-tokenized queries will be interpreted against a different on-disk format and can silently return false negatives instead of failing closed.

Please serialize a stable fingerprint of the text-index definition and reject on mismatch, or ship enough source state to re-derive each TextSearchQuery from the receiver's metadata.

@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8343985bd with master dab347c4d (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
Binary Master PR Δ
programs/clickhouse-stripped 691.36 MiB 688.39 MiB -2.96 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

24 object files changed (+99.12 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMergeTree.cpp.o 2.07 MiB 2.14 MiB +67.21 KiB (+3.17%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexConditionText.cpp.o 806.98 KiB 838.71 KiB +31.72 KiB (+3.93%)

737 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

248 translation units recompiled, 3278 s compile time in total, 247 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.11 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +344.1 s (+12%) in total before that adjustment.

Job report

- `TextSearchQuery::initializeHash` hashes `pattern_sources` (the source LIKE
  pattern plus its case flag) instead of dissecting the compiled
  `OptimizedRegularExpression`. A trivial pattern keeps no RE2 object, so the
  old code always took the `getAnalyzeResult` branch and never mixed in case
  sensitivity. Only queries that carry patterns change their hash, which is
  used for in-memory cache keys and the `__text_index_*` virtual column name
  and is neither persisted nor serialized.

- `MergeTreeIndexConditionText` no longer needs two-phase initialization. The
  search queries shipped in a distributed plan are a constructor argument now,
  so `setSearchQueriesForVirtualColumns` is gone together with the state it
  guarded against: a condition holding queries but null caches. Both public
  constructors delegate to a private one that owns the member initialization
  and share `finalizeSearchTokens`.

- `MergeTreeIndexText::createIndexConditionForVirtualColumns` builds that
  condition, so `restoreTextIndexReadTasks` downcasts the index instead of the
  condition and drops one redundant check.

- The queries are passed as an `std::unordered_map` matching the member they
  fill, and moved in rather than copied element by element.

- Renamed `restoreIndexReadTasksForTextIndex` to `restoreTextIndexReadTasks`
  and shortened several comments.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Core/SettingsQuirks.cpp Resolved
`adjustSettingsForMakeDistributedPlan` no longer forces
`use_skip_indexes_on_data_read = 0` or `query_plan_direct_read_from_text_index = 0`,
but the setting help still listed both, so `DESCRIBE SETTING make_distributed_plan`
and the generated docs contradicted the runtime behavior. That is especially
confusing now that distributed text index direct reads depend on those settings
reaching the workers.

Also document why the shipped fallback predicate is formatted with
`formatWithSecretsOneLine`: that variant keeps secrets and bypasses the log
masker, so the worker parses back exactly the predicate the initiator planned.
Formatting it for logging instead would silently change the predicate under
`query_masking_rules`.

Review: ClickHouse#114242 (comment)
Review: ClickHouse#114242 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
pull Bot pushed a commit to TCeason/ClickHouse that referenced this pull request Aug 25, 2026
…plicas

select_sequential_consistency clamps a ReplicatedMergeTree read to the parts
the initiator saw confirmed by the insert quorum, via max_block_numbers_to_read.
The pin is not serialized: ReadFromMergeTree::deserialize rebuilds a shipped
read with max_block_numbers_to_read = nullptr. mergeTreeReadCanBeShipped did
not consult it, so the read was split for parallel replicas and each follower
silently read its own unclamped part set, returning rows the quorum never
confirmed with no exception.

Reject hasPinnedBlockNumbers in mergeTreeReadCanBeShipped, mirroring the
rejection for the same property in make_distributed_plan
(checkDistributedReadSupported, makeDistributed.cpp). The predicate gates both
collectReadsToDistribute (the coordinated read) and subtreeHasUnshippableRead
(the broadcast side of a lifted join), so one check covers both carriers.
Returning false rather than throwing matches how this path already keeps a
refreshable-MV target read local, and how the same file keeps FINAL reads and
IN (subquery) plans local: make_distributed_plan is an explicit opt-in,
plan-based parallel replicas falls back to a local read.

A/B on a two-replica quorum fixture (SYSTEM STOP FETCHES plus a timed-out
insert_quorum = 2, insert_quorum_parallel = 0 insert, so /quorum/status stays
set), remote-only, with the guard reverted and nothing else changed: the pinned
read is split and returns (435, 30) instead of the quorum-consistent (45, 10),
and a join reading the pinned table on its broadcast side returns 30 rows where
the truth is 10. The fixture is asserted armed before measuring, since SYSTEM
STOP FETCHES is in-memory only and a restart evaporates the pin.

The join arm coordinates a plain MergeTree, which has no sequential-consistency
branch and therefore keeps its split marker, so the broadcast-side check is
reached rather than short-circuited by the coordinated read being rejected
first. It asserts step order rather than step presence: refusing the lift keeps
the split below the join, so ReadFromParallelReplicas appears either way and
only its position distinguishes a local join over a distributed read from a
fully shipped join.

The fix and its regression test are Alexey Milovidov's, from commit
b305123 on ClickHouse#112723, which was closed unmerged in favour of ClickHouse#114242. That
PR reworks text-index distributed reads and does not carry this guard.

Co-Authored-By: Claude Fable 5 <[email protected]>
@devcrafter

Copy link
Copy Markdown
Member

Please consider covering #116360. It's the same but for plan-based parallel replicas

@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
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

1 similar comment
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

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

comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

make_distributed_plan fails on full-text search queries when direct read from text index is enabled

2 participants