Skip to content

Fix a text index direct read silently returning no rows while an update is pending - #118496

Merged
rschu1ze merged 6 commits into
masterfrom
fix-text-index-direct-read-ignores-patch
Sep 9, 2026
Merged

rschu1ze merged 6 commits into
masterfrom
fix-text-index-direct-read-ignores-patch

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #106460
Related: #117277

Problem

A query filtered by hasToken / hasAnyTokens / hasAllTokens returns no rows at all, silently, while a lightweight update is pending on the table. No error, no warning. Everything is at its default: enable_lightweight_update, apply_patch_parts and query_plan_direct_read_from_text_index are all on, so a table with a text index and a token predicate is enough to hit it.

CREATE TABLE tb (id UInt64, c UInt64, s String, INDEX idx s TYPE text(tokenizer = splitByNonAlpha))
ENGINE = MergeTree ORDER BY id
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;

INSERT INTO tb SELECT number, 0, concat('tok', toString(number % 10), ' word') FROM numbers(1000);
SYSTEM STOP MERGES tb;

UPDATE tb SET c = 1 WHERE id < 10;   -- lightweight update, patch part now pending

100 rows match tok1, of which only id = 1 was updated:

query rows expected
SELECT c FROM tb WHERE hasToken(s, 'tok1') 0 100
SELECT id, c FROM tb WHERE hasToken(s, 'tok1') AND id < 25 0 3
SELECT sum(c) FROM tb WHERE hasToken(s, 'tok1') 0 1
… the same with query_plan_direct_read_from_text_index = 0 100 / 3 / 1 correct
SELECT id FROM tb WHERE hasToken(s, 'tok1') (unpatched column) 100 100
SELECT count() FROM tb WHERE hasToken(s, 'tok1') 100 100

The discriminator is whether the query materializes a column the patch updates. That is why it is easy to misread: sum(c) = 0 looks like a stale pre-update value, but it is a sum over the empty set, and a bare count() is fine because the column is never read.

Root cause

A direct read answers the predicate from a column the index reader synthesizes rather than by reading the indexed column. MergeTreeSelectProcessor::getPrewhereActions gives it a read step of its own on purpose:

/// Add steps for reading virtual columns for indexes.
/// Those must be separate steps, because index readers
/// cannot read physical columns from table.

That is a hard constraint, not a preference — MergeTreeReaderIndex::readRows throws unless it is handed exactly one column.

A pending lightweight update adds a patch part, and the reader chain applies it by reading the patch key columns — for MergeOnKey, the sorting key plus _block_number, _block_offset and _part_data_version. They have to be in the first read step, because MergeTreeReadersChain::read calls readPatches immediately after the first reader and executeSortingKeyExpressions looks the key columns up in that block.

addPatchPartsColumns therefore appends them to result.pre_columns.front() — which, for a direct read, is the index step. The step then mixes index and physical columns, and getIndexReadTaskForReadStep bails out:

if (!index_for_step.empty() && has_non_index_columns)
    return nullptr;

so the step goes to the main reader, which cannot produce __text_index_*. The filter sees only its default and every row is filtered out.

Instrumented, reading the patched column vs. an unpatched one:

A) SELECT c   (patched, 0 rows)
   step columns=[__text_index_idx_hasToken_3eb56adb…, _block_offset, _part_data_version, _block_number, id]
   index_for_step='idx'  has_non_index_columns=true      <- index reader dropped

B) SELECT id  (unpatched, 100 rows)
   step columns=[__text_index_idx_hasToken_3eb56adb…]
   index_for_step='idx'  has_non_index_columns=false

Fix

Decline the direct read while a selected part has a pending patch. collectTextIndexReadInfos already resolves per-part AlterConversions to decide whether the index is stale, so this is that same guard extended with a second reason to decline.

A patch of an indexed column was already covered there — AlterConversions::addPatchPart records patched columns in getAllUpdatedColumns too, which canUseIndex consults. What was missing is a patch of a column the index does not cover, where the index stays valid and the direct read stayed on.

Cost: a part with a pending lightweight update loses the text-index direct read until the patch materializes. Lightweight updates are transient, and correctness comes first. Making the two coexist is worth doing later, but it is not a small change: it needs either the patch key columns readable outside the first read step, or readPatches deferred past the leading index steps — and the latter is built around the first reader's header covering all of read_result.columns.

Regression test 05059_text_index_direct_read_pending_patch, placed next to 05059_text_index_direct_read_pending_mutation: the two are halves of one invariant, that being an on-fly mutation and a patch part. Two notes on the test:

  • tagged no-parallel-replicas, because make_distributed_plan forces use_skip_indexes_on_data_read = 0 (adjustSettingsForMakeDistributedPlan), which turns the direct read off whatever query_plan_direct_read_from_text_index says and would leave the test exercising only the fallback path;
  • it keeps its patches pending with apply_patches_on_merge = 0 rather than by SYSTEM STOP MERGES alone, which stops merges on one replica only;
  • the post-materialization arm asserts through EXPLAIN that the synthesized column is back, since the query results alone are identical whether or not the optimization is applied.

Changelog category (leave one):

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

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

Fixed a query with a hasToken-family predicate on a text index silently returning no rows when the query also read a column modified by a pending lightweight update.


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

Version info

  • Merged into: 26.9.1.1038 (included in 26.9 and later)
  • Backported to: 26.8.8.5

…ding

A query filtered by `hasToken` and friends returned an empty result, with no
error, whenever the query also read a column that a pending lightweight update
had modified. All settings default: `enable_lightweight_update` and
`apply_patch_parts` are both on, so a table with a text index and a
`hasToken`-family predicate is enough.

The discriminator is whether the query materializes a patched column. Reading
only unpatched columns, or a bare `count()`, was unaffected - which is why
`SELECT sum(c) ... WHERE hasToken(s, 'tok1')` looks like it answers a stale
value: it is a sum over the empty set, not the pre-update value.

A direct read answers the predicate from a column the index reader synthesizes,
in a read step of its own. `MergeTreeSelectProcessor::getPrewhereActions` makes
it a separate step on purpose, because an index reader produces exactly one
column and reads nothing from the part - `MergeTreeReaderIndex::readRows`
rejects any other column count. A pending update adds a patch part, which the
reader chain applies by reading the patch key columns - for `MergeOnKey`, the
sorting key plus `_block_number`, `_block_offset` and `_part_data_version` - in
its first read step, because `readPatches` runs right after the first reader.
`addPatchPartsColumns` put them in `pre_columns.front()`, which for a direct
read is the index step. That step then mixed index and physical columns, so
`getIndexReadTaskForReadStep` handed it to the main reader, which cannot produce
the index column: the filter saw its default and every row was filtered out.

Skip the direct read while a selected part has a pending patch. The loop in
`collectTextIndexReadInfos` already resolves per-part `AlterConversions` to
decide whether the index is stale, so this is the same guard extended to a
second reason to decline. A patch of an indexed column was already covered
there, because `AlterConversions::addPatchPart` records patched columns in
`getAllUpdatedColumns` as well; what was missing is a patch of a column the
index does not cover, where the index stays valid and the direct read stayed on.

Making the two coexist is worth doing, but it is not a small change: it needs
either the patch key columns readable outside the first step, or `readPatches`
deferred past the leading index steps, and the latter is built around the first
reader's header covering all of `read_result.columns`. Correctness first; a part
with a pending lightweight update loses the optimization until the patch
materializes.

The test is tagged `no-parallel-replicas` because `make_distributed_plan` forces
`use_skip_indexes_on_data_read = 0`, which would turn the direct read off and
leave the test exercising only the fallback path. It keeps its patches pending
with `apply_patches_on_merge = 0` rather than by `SYSTEM STOP MERGES` alone,
which stops merges on one replica only.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1729b9b]

Summary: ✅


AI Review

Summary

This PR fixes the wrong-result path where a text-index direct read can silently filter everything out while a lightweight update patch is pending and the query also reads a patched column. The correctness fix is on the right path, but the new guard is broader than the broken invariant and now turns off query_plan_direct_read_from_text_index for safe query shapes that never need patch application.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:220-230, 662-666] The new has_patched_parts guard disables direct reads whenever any selected part has any patch part, but patch key columns are only injected when AlterConversions::getPatchesForColumns decides that this read actually needs patched columns or a lightweight-delete mask. Queries such as SELECT count() or SELECT id ... WHERE hasToken(...) with a pending update on some other column were already correct and could still use the text-index direct read; after this change they fall back to reading the full text column for the entire patch lifetime. The guard should be driven by the actual patch/read-set overlap, or at least suppressed only for the affected parts.
Final Verdict

Changes requested. The remaining issue is a user-visible performance regression in the direct-read path for query shapes that do not consume any patched data.

LLVM Coverage Report

Measured on commit 1729b9b.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 81.20% 81.20% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
/// A patch of an indexed column is already excluded by `canUseIndex` below, because
/// `AlterConversions::addPatchPart` records patched columns in `getAllUpdatedColumns` as well.
/// This covers the remaining case: a patch of a column that the index does not cover.
if (any_part_has_patches)

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.

This is broader than the failure mode. AlterConversions::getPatchesForColumns only returns a patch when the current read actually needs a patched column (or a lightweight-delete mask), so shapes like SELECT count() / SELECT id from the new test never had the first-step key-column injection that breaks getIndexReadTaskForReadStep. Bailing out on hasPatches() alone now disables query_plan_direct_read_from_text_index for every text-index query on the part for the full patch lifetime, including those safe shapes.

Can we drive this fallback from the actual patch/read-set overlap instead of from the existence of any patch part?

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

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1729b9ba8 with master 644ca986b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4ee25bab4; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

127 object files changed (+359.08 KiB total), 3 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/LimitRangeStep.cpp.o new 133.48 KiB +133.48 KiB
src/CMakeFiles/dbms.dir/Processors/LimitRangeTransform.cpp.o new 113.07 KiB +113.07 KiB
src/CMakeFiles/dbms.dir/Processors/Transforms/ChunkRowRange.cpp.o new 23.45 KiB +23.45 KiB
src/CMakeFiles/dbms.dir/Planner/Planner.cpp.o 765.71 KiB 787.97 KiB +22.26 KiB (+2.91%)

716 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

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

Job report

@rschu1ze

rschu1ze commented Sep 7, 2026

Copy link
Copy Markdown
Member

@tiandiwonder Does this fix #106460?

@rschu1ze rschu1ze self-assigned this Sep 7, 2026
The guard's comment named functions in other files and re-told the whole
mechanism, which the pull request description already carries. It is down to the
one causal sentence a reader at that line needs.

The test now opens with what it checks rather than with the root cause, and no
longer mentions C++ symbols: the tag rationale talks about the distributed plan
and `use_skip_indexes_on_data_read` instead of the function that sets it, and the
last section says the search has to see the updated value instead of naming the
check that already covered it. The per-arm one-liners stay - they are what says
why an arm exists and why a setting is pinned, so a later cleanup cannot quietly
make an arm vacuous.

Comments only: `git diff` over non-comment lines is empty, and 05059 still
matches its reference.
@tiandiwonder

Copy link
Copy Markdown
Contributor Author

Yes — same root cause, different symptom (there the query errors instead of silently returning nothing). Verified by swapping only optimizeDirectReadFromTextIndex.cpp between master and this branch on one build: that issue's compound hasToken(text, …) AND hasToken(json_title, …) after the lightweight update throws UNKNOWN_IDENTIFIER on master and returns the correct 2 here, with every other step of the reproducer unchanged.

alexey-milovidov and others added 4 commits September 8, 2026 05:45
…nalysis

Returning from `collectTextIndexReadInfos` when a part has a pending patch
turned out to disable more than the direct read. The entry it stops collecting
is also what the filter rewrite reads the index's preprocessor from, so a text
index declared with one silently lost it while an update was pending on any
column: for `INDEX idx_s s TYPE text(..., preprocessor = lower(s))`,
`hasAnyTokens(s, 'hello')` stopped matching `Hello World` at
`use_skip_indexes = 1` and answered 0 instead of 10. Fewer rows, no error - a
correctness regression, not the performance trade-off the pull request
described.

The entry is now always collected and carries `has_pending_patch` instead. The
flag is consumed where the virtual column would be registered, which already had
the branch for this: it records the analyzed condition without a virtual column,
so the tokenizer, preprocessor and postprocessor are still injected and only the
read from the index is given up.

The regression was reachable through the same table shape an existing test
already uses, `02346_text_index_functions_select_expression`, which does not
create a patch and therefore stayed green. 05059 now covers it: the two
`use_skip_indexes` answers have to be the same with an update pending on a column
the index does not cover as they are without one. Verified 0/10 both times, and
0/0 on the previous commit.
@rschu1ze
rschu1ze force-pushed the fix-text-index-direct-read-ignores-patch branch from 4d7586b to 1729b9b Compare September 8, 2026 13:54
@rschu1ze
rschu1ze added this pull request to the merge queue Sep 9, 2026
Merged via the queue into master with commit 5b33963 Sep 9, 2026
174 checks passed
@rschu1ze
rschu1ze deleted the fix-text-index-direct-read-ignores-patch branch September 9, 2026 12:22
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 9, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 18, 2026
Backport #118496 to 26.8: Fix a text index direct read silently returning no rows while an update is pending
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Sep 21, 2026
…ntly returning no rows while an update is pending
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 28, 2026
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Oct 10, 2026
… skip index

`collectTextIndexReadInfos` called `getAlterConversionsForPart` for every part of the table to collect
the columns updated on the fly (ClickHouse#99543) and to find whether
any part has a pending patch (ClickHouse#118496). It ran for every
query with any useful skip index, before checking whether one of them is a text index, over all parts of
the table (they are not filtered by the index analysis yet), and the lookup of patches for a part is
linear in the number of patch parts and builds the sorting key of every patch part. On tables with
hundreds of parts and patch parts it added hundreds of milliseconds to the planning of point queries
that use a `bloom_filter` index. Also, a single pending patch anywhere in the table turned the direct
read from a text index off for the whole query.

Now:
- `collectTextIndexReadInfos` returns early if no useful index is a text index.
- The planner rejects a text index whose columns are changed on the fly without building
  `AlterConversions` for every part: the columns updated by patch parts and data mutations are taken
  from the whole mutations snapshot, the columns changed by alter mutations are collected per part only
  when such mutations exist, and masking policies are parsed once. This check must stay in planning:
  the on-fly mutation steps are built from the columns of the query, which do not contain the indexed
  columns replaced by the virtual columns, and whether the preprocessor of the index is applied to the
  search functions must not depend on the part.
- A part with pending patches (of other columns) does not read the virtual columns from the index: like
  a part without the materialized index, it computes them by their default expressions (the original
  predicates), because the patch key columns must be read in the first read step, which the reader of the
  text index cannot do. The other parts read the index.

Related: ClickHouse#123334
Related: ClickHouse#124085
Related: ClickHouse#118496
Related: ClickHouse#99543
Related: ClickHouse/clickhouse-private#75816
Related: https://clickhouse-inc.slack.com/archives/C0B6DBVRPKJ/p1791474075046099

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
CurtizJ added a commit that referenced this pull request Oct 11, 2026
Resolve conflicts of the cherry-pick of #124931 to 26.7:
- 26.7 has no `has_patched_parts` gate (#118496 is not
  backported), so only the per-part loop over `getAlterConversionsForPart` in `collectTextIndexReadInfos`
  is replaced by `getColumnsUpdatedOnFly`.
- `MergeTreeReadTaskInfo` has no `data_part_info` on 26.7, so `getIndexReadTaskForReadStep` takes the
  part and its `AlterConversions` separately.
- `getMaskingPolicyCommands` is placed before the 26.7 version of `getPatchPartMetadata`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FTS index after Light-Weight Update is not working for MATERIALIZED column

7 participants