Repository navigation
Fix a text index direct read silently returning no rows while an update is pending - #118496
Conversation
…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]>
|
Workflow [PR], commit [1729b9b] Summary: ✅
AI ReviewSummaryThis PR fixes the wrong-result path where a Findings
Final VerdictChanges 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 ReportMeasured on commit 1729b9b.
Changed lines: Changed C/C++ lines covered: 23/23 (100.00%) · Uncovered code |
| /// 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) |
There was a problem hiding this comment.
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?
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes127 object files changed (+359.08 KiB total), 3 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units72 translation units recompiled, 785 s compile time in total, 72 of them have a recent master baseline. |
|
@tiandiwonder Does this fix #106460? |
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.
|
Yes — same root cause, different symptom (there the query errors instead of silently returning nothing). Verified by swapping only |
…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.
…direct-read-ignores-patch
4d7586b to
1729b9b
Compare
Backport #118496 to 26.8: Fix a text index direct read silently returning no rows while an update is pending
…ntly returning no rows while an update is pending
… 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]>
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]>
Closes: #106460
Related: #117277
Problem
A query filtered by
hasToken/hasAnyTokens/hasAllTokensreturns 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_partsandquery_plan_direct_read_from_text_indexare all on, so a table with atextindex and a token predicate is enough to hit it.100 rows match
tok1, of which onlyid = 1was updated:SELECT c FROM tb WHERE hasToken(s, 'tok1')SELECT id, c FROM tb WHERE hasToken(s, 'tok1') AND id < 25SELECT sum(c) FROM tb WHERE hasToken(s, 'tok1')query_plan_direct_read_from_text_index = 0SELECT id FROM tb WHERE hasToken(s, 'tok1')(unpatched column)SELECT count() FROM tb WHERE hasToken(s, 'tok1')The discriminator is whether the query materializes a column the patch updates. That is why it is easy to misread:
sum(c) = 0looks like a stale pre-update value, but it is a sum over the empty set, and a barecount()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::getPrewhereActionsgives it a read step of its own on purpose:That is a hard constraint, not a preference —
MergeTreeReaderIndex::readRowsthrows 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_offsetand_part_data_version. They have to be in the first read step, becauseMergeTreeReadersChain::readcallsreadPatchesimmediately after the first reader andexecuteSortingKeyExpressionslooks the key columns up in that block.addPatchPartsColumnstherefore appends them toresult.pre_columns.front()— which, for a direct read, is the index step. The step then mixes index and physical columns, andgetIndexReadTaskForReadStepbails out: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:
Fix
Decline the direct read while a selected part has a pending patch.
collectTextIndexReadInfosalready resolves per-partAlterConversionsto 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::addPatchPartrecords patched columns ingetAllUpdatedColumnstoo, whichcanUseIndexconsults. 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
readPatchesdeferred past the leading index steps — and the latter is built around the first reader's header covering all ofread_result.columns.Regression test
05059_text_index_direct_read_pending_patch, placed next to05059_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:no-parallel-replicas, becausemake_distributed_planforcesuse_skip_indexes_on_data_read = 0(adjustSettingsForMakeDistributedPlan), which turns the direct read off whateverquery_plan_direct_read_from_text_indexsays and would leave the test exercising only the fallback path;apply_patches_on_merge = 0rather than bySYSTEM STOP MERGESalone, which stops merges on one replica only;EXPLAINthat the synthesized column is back, since the query results alone are identical whether or not the optimization is applied.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a query with a
hasToken-family predicate on atextindex 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
26.9.1.1038(included in26.9and later)26.8.8.5