Skip to content

Fix lazy final text index direct read - #106894

Merged
Ergus merged 6 commits into
ClickHouse:masterfrom
Ergus:fix-lazy-final-text-index-direct-read
Jul 1, 2026
Merged

Ergus merged 6 commits into
ClickHouse:masterfrom
Ergus:fix-lazy-final-text-index-direct-read

Conversation

@Ergus

@Ergus Ergus commented Jun 9, 2026 •

Copy link
Copy Markdown
Member

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 wrong results when querying a ReplacingMergeTree table with FINAL and a filter on a text index while query_plan_optimize_lazy_final was enabled. The lazy FINAL optimization built reading steps that did not reproduce the direct read from the text index, so the filter dropped all matching rows.

Fixes: #106809

Version info

  • Merged into: 26.7.1.357 (included in 26.7 and later)
  • Backported to: 26.6.2.32, 26.4.5.143

@Ergus
Ergus requested a review from KochetovNicolai June 9, 2026 20:42
@Ergus
Ergus force-pushed the fix-lazy-final-text-index-direct-read branch from 192ac1e to 155ce7d Compare June 9, 2026 20:45
@clickhouse-gh

clickhouse-gh Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7549a0c]

Summary: ✅


AI Review

Summary

The PR fixes wrong results for ReplacingMergeTree queries that combine FINAL, lazy FINAL, and direct reads from text indexes. The implementation now preserves text-index read tasks for the all-non-intersecting lazy FINAL replacement and falls back to regular FINAL when intersecting parts would need the incompatible lazy true-branch path. I did not find a code correctness issue in the changed implementation.

PR Metadata

💡 The Changelog category is correct and the Changelog entry is specific enough, but the placeholder ... is still present and the related issue line does not follow the repository convention. Suggested replacement:

Fixed wrong results when querying a `ReplacingMergeTree` table with `FINAL` and a filter on a text index while `query_plan_optimize_lazy_final` was enabled. The lazy `FINAL` optimization built reading steps that did not reproduce the direct read from the text index, so the filter dropped all matching rows.

Closes: https://github.com/ClickHouse/ClickHouse/issues/106809
Final Verdict

Status: ✅ Approve

Only non-blocking cleanup: remove the changelog placeholder and use the full Closes issue link in the PR description.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 9, 2026
@Ergus
Ergus force-pushed the fix-lazy-final-text-index-direct-read branch from 155ce7d to 69d7a00 Compare June 9, 2026 21:18
@Ergus
Ergus requested a review from Copilot June 9, 2026 21:21

Copilot AI left a comment

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.

Pull request overview

Fixes a correctness bug in the lazy FINAL query-plan optimization where direct reads from a text index were not reproduced in synthetic reading steps, causing filters rewritten to __text_index_* virtual columns to drop all matching rows.

Changes:

  • Forward text-index IndexReadTasks from the original ReadFromMergeTree step into the synthetic non-FINAL step created by lazy FINAL, so __text_index_* virtual columns are produced consistently.
  • Disable lazy-FINAL splitting for intersecting-parts handling when direct text-index read tasks are present (fallback to regular FINAL), avoiding an incompatible execution path.
  • Add a stateless regression test (with reference output) covering both single-part and mixed intersecting/non-intersecting part scenarios.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
tests/queries/0_stateless/02346_text_index_bug106809.sql Adds regression coverage for lazy FINAL + text-index direct read correctness.
tests/queries/0_stateless/02346_text_index_bug106809.reference Expected outputs for the new regression test.
src/Processors/QueryPlan/ReadFromMergeTree.h Exposes get/set accessors for text-index IndexReadTasks so other plan steps can reproduce direct index reads.
src/Processors/QueryPlan/Optimizations/optimizeLazyFinal.cpp Copies text-index read tasks into synthetic reads and disables lazy FINAL split when tasks are present for intersecting-part handling.

@ahmadov ahmadov self-assigned this Jun 10, 2026
-- virtual column the rewritten filter relies on. With the optimization enabled the
-- counts below must stay correct.

SET allow_experimental_full_text_index = 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.

Not needed

-- counts below must stay correct.

SET allow_experimental_full_text_index = 1;
SET query_plan_optimize_lazy_final = 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.

Also not needed, the actual and the expected test results must match regardless of the setting.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To trigger the issue we need to ensure that both optimizations take place. Otherwise the issue don't happen


SET allow_experimental_full_text_index = 1;
SET query_plan_optimize_lazy_final = 1;
SET max_rows_for_lazy_final = 10000000;

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.

Why do we need this setting and the next?


DROP TABLE IF EXISTS tab;

SELECT 'Single part (non-intersecting): the synthetic read must still use the direct read';

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.

Readers are not able to parse this sentence, let's rewrite.

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

@Ergus @ahmadov This PR fixes wrong results, could you continue it next week? Thanks!

@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.40% +0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.60% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 15/15 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

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

LGTM 👍

@Ergus
Ergus added this pull request to the merge queue Jul 1, 2026
Merged via the queue into ClickHouse:master with commit d27141e Jul 1, 2026
167 checks passed
@Ergus
Ergus deleted the fix-lazy-final-text-index-direct-read branch July 1, 2026 16:12
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix lazy final text index direct read

ClickGap verified: reproduced it with the script below on 26.5; tested 3 version(s) — 2 affected, 1 clean (see Affects); bisected to a candidate range — a single introducing PR could not be pinned (see Bisect).

Reproduction

SET allow_experimental_full_text_index = 1;
SET query_plan_optimize_lazy_final = 1;
SET min_filtered_ratio_for_lazy_final = 0;
SET query_plan_direct_read_from_text_index = 1;

CREATE TABLE tab (id UInt64, version UInt64, str String, INDEX idx(str) TYPE text(tokenizer = array)) ENGINE = ReplacingMergeTree(version) ORDER BY id;
INSERT INTO tab VALUES (1, 1, 'foo'), (2, 1, 'bar'), (3, 1, 'baz');
INSERT INTO tab VALUES (1, 2, 'foo_updated');
OPTIMIZE TABLE tab FINAL;
SELECT count() FROM tab FINAL WHERE str = 'bar';
-- Observed: returns 0 (all matching rows dropped). Expected: 1.

Bisect

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4
  • Does NOT reproduce on: master
  • Could not test (binary unavailable): 26.3, 26.2, 26.1
  • Backport needed: 26.5, 26.4

Suggested next step

The bug reproduces as far back as the oldest tested release (26.4) and the only converged boundary is topically unrelated — this is a long-standing / pre-existing bug in comp-query-optimizer, not a recent regression; no introducing PR exists within the tested range.

Component: comp-query-optimizer
Severity: P2

cc fix PR author: @Ergus
cc fix PR reviewer: @rschu1ze @ahmadov


ClickGap · Finding: phase_d_pr106894

Triage metadata

  • Primary component: comp-query-optimizer
  • Secondary components: comp-text-index, comp-testing
  • Component owners (comp-query-optimizer): @KochetovNicolai @nickitat

@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 Jul 6, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 6, 2026
Backport #106894 to 26.6: Fix lazy final text index direct read
robot-clickhouse added a commit that referenced this pull request Jul 15, 2026
Cherry pick #106894 to 26.4: Fix lazy final text index direct read
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 16, 2026
Ergus added a commit that referenced this pull request Jul 19, 2026
Backport #106894 to 26.4: Fix lazy final text index direct read
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 3, 2026
ClickHouse#106894 fixed lazy FINAL dropping rows when a query reads directly from a
text index. Its test uses ReplacingMergeTree(version) with no is_deleted
column, so it never exercises addIsDeletedFilter alongside the copied
setIndexReadTasks. Of the 12 stateless tests that set
query_plan_optimize_lazy_final, only this one has a text index and only
04092 / 04207 have an is_deleted column, so that intersection was untested.

Append a third section covering it: one merged non-intersecting part, a
replacement deletion, and assertions that the tombstoned row is dropped
through WHERE and PREWHERE. optimizeLazyFinal.cpp:321 bails out of lazy
FINAL entirely when index read tasks exist and any part is intersecting, so
the combination is reachable only from an all-non-intersecting part set;
that is why the fixture merges into a single part and why the mixed-parts
shape is not covered here (04092 already covers it).

One assertion checks that the plan really took that shape, because the value
assertions alone also pass through a regular FINAL read. It names the EXPLAIN
options it depends on, since a bare EXPLAIN takes them from the session
setting explain_query_plan_default and the token it matches is only printed
by the pretty renderer.

Three settings are pinned in the file's existing top-level block.
use_skip_indexes_if_final is randomized and at 0 disables skip indexes under
FINAL, so the existing query_plan_direct_read_from_text_index pin was already
defeated in roughly half of all runs;
use_skip_indexes_if_final_exact_mode must stay in sync with it, since the
pair (1, 0) returns deliberately approximate results under FINAL and CI never
generates that pair on its own; enable_analyzer is required because lazy
FINAL is gated on the new analyzer. Expected values of the existing sections
are unchanged.

min_bytes_for_wide_part and index_granularity are pinned to their defaults on
the new table only, so that the three rows stay in a single granule: three
randomized MergeTree settings together write a Wide part with one row per
granule, and a randomized index_granularity of 1 or 2 splits the rows the
same way. The text index then selects a granule subset and lazy FINAL
declines.

Extends the existing test instead of adding a separate one, as requested on
ClickHouse#109705
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ndex-direct-read

Fix lazy final text index direct read
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Sep 29, 2026
…oint sorting key

`trySplitNonIntersectingParts` returns "not replaced" for a primary key the parts splitter
cannot compare (`isSafePrimaryKey`: `Nullable`, `Float*`, `BFloat16`, `Variant`, `Dynamic`,
`JSON`, also nested), for mixed `ASC`/`DESC` key columns, and when a full non-intersecting
replacement selects nothing. All three return before the checks that keep a direct read from
a text index (ClickHouse#106894) and a query that stops reading early (ClickHouse#110576) away from the
set-building plan, so `optimizeLazyFinal` built that plan anyway. Its read inherits the
`__text_index_*` column name from `getAllColumnNames` but not the index read tasks that
produce it: the filter drops rows, and when the `WHERE` repeats the `PREWHERE` predicate,
`set_plan.optimize` rewrites the copy to the same name and `createReadTasksForTextIndex`
throws `Column __text_index_... already added for reading`.

Apply the same two conditions right after the split. On every path that reaches the new
check with either condition true the reading step is still untouched, so the query keeps the
regular `FINAL` read, as it already does for a comparable key. The in-split checks stay, as
they must run before the partial split narrows the reading step. With both conditions false
the control flow is unchanged.

On 26.8.10.6, `SELECT count() FROM tab FINAL WHERE str = 'ccc'` with only
`query_plan_optimize_lazy_final = 1`, over a `ReplacingMergeTree` with a `Nullable(UInt64)`
sorting key and a text index on `str`, returns 0 instead of 1.

Found by `AST fuzzer (amd_debug, targeted, old_compatibility)` (STID 4792-5e4c) on
ClickHouse#122492:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122492&sha=f6b330abde632fb2c271eb66e098d4230b4a7004&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Tests: `02346_text_index_bug106809` gains a `Nullable`-key section (its `PREWHERE` + `WHERE`
row is 1 because `PREWHERE` is evaluated before `FINAL`), and
`04539_lazy_final_read_in_order_limit_disabled` gains `Float64`-key rows for both gates plus
a positive control.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Text index wrong result with query_plan_optimize_lazy_final

9 participants