Skip to content

Fix LOGICAL_ERROR on a lazy FINAL text index read with different PREWHERE and WHERE predicates - #121041

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-text-index-foreign-granule-lazy-final
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-text-index-foreign-granule-lazy-final

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113664
Related: #106809

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 LOGICAL_ERROR (Query builder not found for text search query with function ...) for a FINAL query with query_plan_optimize_lazy_final = 1 that reads a text index directly and carries different text search predicates in PREWHERE and WHERE.

Description

Found by AST fuzzer (amd_tsan) on PR #119839 (report, STID 3694-54bc): it mutated 02346_text_index_bug106809.sql by adding a second, different PREWHERE predicate. A debug build aborts; a release build fails the query.

Root cause: for non-intersecting parts, optimizeLazyFinal builds its own reading step, copying the original step's text index read tasks but re-deriving its skip index conditions from the WHERE filter alone. Its granule therefore carries query builders only for the WHERE predicate, while the reader looks up the inherited PREWHERE one, and TextIndexAnalyzer::getQueryBuilder refuses a hash it never registered. Identical predicates hash the same, so only different ones expose it. Third route into that message: #113664 was the shipped parallel-replicas fragment, fixed by not distributing such a read.

Fix: accept a granule only when its analyzer covers this reader's own search queries, else read the granule from the reader's own condition. Both arrival points need it: the granule's first use (constructor transport), and setPrecomputedGranule (use_skip_indexes_on_data_read = 1), which a read pool calls again for every further task of the same part, after initialization. The LOGICAL_ERROR stays: this removes the violation, not the check. The synthetic step still analyzes the WHERE filter alone, so it prunes fewer granules: a pre-existing missed optimization, left alone.

Validation: the new test aborts a debug master server, aborts again with only the first-use check, and passes here 50/50 under randomized settings. Forcing the predicate to true restores the abort. 232 *text_index*/*lazy_final* tests: 227 pass, 4 skip, 1 fails (02346_text_index_hits, tagged stateful, dies at INSERT ... FROM test.hits before any index read).

Reproducer
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(str) FROM tab FINAL PREWHERE str = 'baz' WHERE str = 'bar' SETTINGS
    query_plan_optimize_lazy_final = 1, min_filtered_ratio_for_lazy_final = 0, optimize_move_to_prewhere = 0;

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

…HERE and WHERE predicates

A FINAL query with query_plan_optimize_lazy_final = 1 that reads a text index
directly and carries two different text search predicates on the indexed column,
one in PREWHERE and one in WHERE, aborted a debug build with

  Logical error: 'Query builder not found for text search query with function 'equals''

and failed the query in a release build.

For non-intersecting parts, optimizeLazyFinal builds its own reading step. That
step copies the original step's text index read tasks, which is what makes the
rewritten filter's virtual column available at all (issue ClickHouse#106809), but it then
registers only the WHERE FilterStep before applyFilters(), so it re-derives its
skip index conditions from that one filter. The granule its analysis publishes in
read_hints.index_granules therefore carries a TextIndexAnalyzer holding query
builders only for the WHERE predicate, while MergeTreeReaderTextIndex resolves
its virtual columns against the inherited condition template and so looks up the
PREWHERE predicate's search query. TextIndexAnalyzer::getQueryBuilder rightly
refuses a hash it never registered. read_hints.index_granules is keyed by index
name only, which is how a granule crosses a step boundary that does not preserve
the granule/condition pairing. Two identical predicates hash to one search query
and cannot expose this, which is why only different ones do, and why the function
name in the message is whichever query the reader happened to look up.

Accept a precomputed granule only when its analyzer covers the search queries the
reader resolves, otherwise read the granule from the reader's own condition. The
check is at the granule's first use rather than at installation, so one check
covers both ways a foreign granule reaches this reader: the constructor parameter
and setPrecomputedGranule under use_skip_indexes_on_data_read = 1. A granule the
reader reads itself covers its queries by construction, and whenever the analysis
condition holds a superset of them, which is the ordinary case, the granule is
reused exactly as before. The LOGICAL_ERROR is deliberately left in place: this
removes the violation, not the check.

Two other routes into the same message are already handled and are untouched
here: shipping a direct text index read to parallel replicas (fixed by
e0eccd2) and partition key constant folding (ClickHouse#110770).

Found by AST fuzzer (amd_tsan) on PR ClickHouse#119839, which mutated the regression test
of issue ClickHouse#106809 by adding the second predicate.
The test left two claims of the fix unmeasured.

use_skip_indexes_on_data_read defaults to 1, so every row of the first
group inherited the data-read transport (setPrecomputedGranule) that the
third group already pins explicitly, and the constructor transport
(IMergeTreeReader.cpp, fed from read_hints.index_granules) was never
exercised. Pin the setting to 0 in the session block, so the two groups
now cover one transport each and no assertion depends on a default. The
constructor transport is defective too: the same query aborts on an
unfixed binary with the setting pinned to 0.

Every row drove a reader holding exactly one search query, where all_of
and any_of are the same function, so the predicate's quantifier had no
oracle. A PREWHERE with two text search predicates, one of which is also
the WHERE predicate, produces a reader whose two queries the synthetic
step's analyzer covers only one of. Add that row and its ground-truth
control; both return 1, so a fix that stopped the abort by dropping rows
would fail them. Weakening all_of to any_of aborts on that row alone,
whether prewhere read steps are split or not.
The check at the granule's first use runs at most once per reader object,
and reader objects outlive read tasks. When the next task is for the same
part, MergeTreeReadPoolBase::createTask moves the readers over with
previous_task->releaseReaders() and only refreshes their mark ranges, then
the new task's initializeReadersChain calls setPrecomputedGranule on that
already initialized reader. is_initialized is never reset, so from the
second task of a part onward the reader kept the granule that call
installed, and buildPostingsForQuery reached getQueryBuilder with the other
step's analyzer again. Any part that yields more than one read task was
still affected, which is the ordinary case for a part of any size.

Apply the same predicate at installation, so an incompatible granule is
never installed in the first place and the reader keeps the one it read for
itself. The first-use check stays: it covers the constructor transport,
where nothing re-installs. Resetting is_initialized instead would also stop
the abort, but it would re-run classifyVirtualColumns and the stream
initialization on every task of every multi-task part, including the
ordinary case where the granule is compatible.

A compatible granule is still installed unchanged, and no extra granule
read appears on that path.

The regression test gains a second fixture, one part of 8-row marks wide
enough for the read pool to cut many tasks from it. Two settings the
existing rows relied on defaults for are now pinned per row: a row limit
with read_overflow_mode = throw disables reading the index on data read
outright, and the stateless test profile sets one, so the rows that name
that route did not take it; and max_threads above 1 is what selects the
read pool that splits a part at all, since the in-order pool puts every
mark range in a single task.
The two value queries of the reuse group pinned task sizing but inherited
allow_prefetched_read_pool_for_remote_filesystem, which defaults to true.
MergeTreePrefetchedReadPool::createTask builds a task from its own readers
future whenever it has one, so it never consults previous_task and the
same-part reader reuse that the installation-time check exists for does not
happen. The expected output is the same either way, so the group passed
while covering nothing on the flavors that select that pool: builds whose
parts are all on remote storage, since the local sibling setting defaults
to false, and not debug builds, where the test runner already forces the
remote one off.

Pin it off on those two rows only. The controls next to them keep running
on whatever pool CI picks.

The comment above the group also gave a false reason for one of the pins:
merge_tree_min_rows_for_concurrent_read is randomized nowhere. It is pinned
because its default is far above this part's row count, so without it the
part yields a single read task and the coverage disappears with the test
still green. Give each pinned setting its own reason instead.
Dropped the two-line rationale at setPrecomputedGranule and shortened the readRows note to one invariant line.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Independent passes over this diff (an internal reviewer and a second model, both without the implementation notes), then adjudication against the recorded measurements.

Finding Verdict
❌ The check sat only at the granule's first use, and is_initialized is never reset: from the second read task of a part onward, setPrecomputedGranule re-installed the foreign granule on an initialized reader and it reached getQueryBuilder at read time. Agreed, and fixed: an incompatible granule is now refused at installation as well. A regression row that forces several read tasks from one part aborts on a binary carrying only the first-use check.
⚠️ The test left use_skip_indexes_on_data_read at its default (1) in the first group, so it exercised the read-time route twice and never the constructor route. Agreed. The transport is now pinned explicitly per group, and the constructor route is measured on the unfixed binary.
⚠️ The new predicate is all_of over the reader's search queries, but every test row drove a reader holding exactly one query, so the quantifier had no oracle. Agreed. A row with two text search predicates in one PREWHERE, one shared with WHERE, now pins it, with an any_of mutant as the control.
⚠️ The reader-reuse rows did not pin the prefetched read pool, which creates a reader per task rather than moving one between tasks, so that group could stop covering reuse while still printing the expected values. Agreed, and pinned off on those two rows. Narrower than first stated: the output is identical on either pool, so nothing flaked. Re-run after the pin, a binary carrying only the first-use check still aborts inside that group, on the reuse route.
💡 Pinning the session default to 0 left the read-time route, the default since 26.2, guarded by result value alone. Agreed, folded in: that route now carries its own EXPLAIN assertion.
💡 A comment justified two pinned settings as defences against CI randomization; only one of them is randomized. Agreed, reworded: each pinned setting now carries its own reason.
💡 The predicate tolerates a null search query, which cannot occur: getSearchQueryForVirtualColumn throws instead of returning null. Noted, not changed: it mirrors the existing guard in initializeFallbackReader.

Checked and found sound: the guard fires on exactly the set of states that aborted before, because the per-column getQueryBuilder lookup in classifyVirtualColumns was already unconditional, so no path that works today changes behaviour; accepting a granule whose analyzer holds a superset of this reader's queries stays correct; refusing rather than re-reading on the reuse route is right because read pools move readers only between tasks of the same part; keying on the query hash rather than on condition identity is required, since index analysis substitutes per-partition constants while the reader holds the unsubstituted condition; and of the granule and analyzer pairings elsewhere in src/, each one pairs a granule with the very condition that produced it, so the two reader installation routes are the only carriers.

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c273288]

Summary: ✅


AI Review

Summary

The PR fixes a LOGICAL_ERROR in lazy FINAL queries with different text search predicates in PREWHERE and WHERE. It validates precomputed granules against every search query required by the reader, including when readers are reused across tasks. The regression tests cover both granule handoff paths, multiple predicates, and reader reuse. No actionable findings.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 19, 2026
@groeneai
groeneai requested review from CurtizJ and ahmadov September 19, 2026 15:42
@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 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c2732886e with master 4d1bce945 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c6e4b71cf; 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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 163385a

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Column A already added for reading (STID 4792-5e4c) pre-existing text-index direct-read defect, not this diff: __text_index_idx_equals_* is registered for reading twice. The same shape has fired on four unrelated branches since 2026-08-27, none of which carry this fix #111844 (mine, open)

PR is the praktika aggregator reporting the row above, not a separate failure.

Session id: cron:our-pr-ci-monitor:20260919-213105

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted, old_compatibility) / Column A already added for reading (STID 4792-5e4c) row of the ledger above: #122534. It replaces the #111844 link there, which was closed unmerged.

…ndex-foreign-granule-lazy-final

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderTextIndex.h
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c3f85b4

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.

Every test that ran on this head passed (0 failed tests in CIDB). The red comes only from jobs that never ran, and from jobs that needed the release builds.

Check / test Reason Owner / fixing PR
Build (amd_release), Build (arm_release), Stateless tests (amd_tsan, flaky check), Stateless tests (arm_binary, parallel / sequential), Unit tests (tsan / tsan, function_prop_fuzzer), Parser memory check, Storage memory check, Build profile diff infra: GitHub Actions outage on 2026-10-07 (githubstatus critical incidents at 15:14Z and 16:52Z). GitHub never assigned a runner, so praktika marked these 10 jobs DROPPED (Job did not finish, GitHub reported [abandoned]) a fix task is created (it re-runs the lost jobs on a fresh head)
Docker server image, Docker keeper image, Install packages (amd_release / arm_release), Compatibility check (amd_release / arm_release), Upgrade check (amd_release), Performance Comparison (arm_release, master_head, 1/6 to 6/6), ClickBench (amd_release / arm_release), Docs examples infra, same outage: the release builds above never ran, so these 16 jobs found no build artifacts (URLS has not been read from build report) and errored at 15:28Z a fix task is created (same task: the re-run covers them)

Session id: cron:our-pr-ci-monitor:20261007-180301

alexey-milovidov and others added 2 commits October 22, 2026 02:45
The fixture asserts that `tab_reuse` ends up as one part of at least 512
marks, so the queries below really get several read tasks. A compact part
computes its granularity per written block and folds a short tail into the
previous mark, so when the OPTIMIZE merge writes blocks of a randomized,
small `merge_max_block_size` the merged part can get fewer marks. CI drew
`merge_max_block_size = 265` with a compact part and `optimize_on_insert = 0`
(Stateless tests (amd_tsan, s3 storage, targeted), head c9a76d4), and
the merge produced 510 marks (511 with the final one), so the precondition
returned 0.

Pin the merge block at its default next to the existing `index_granularity`
pin, so the merged part has 8-row marks under any draw. Replaying that run's
exact settings, the old file fails 20/20 and the pinned one passes 20/20.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a5fb123

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
Performance Comparison (arm_release, master_head, 3/6) / long_primary_key #0, long_primary_key #2 not from this PR (it changes only the lazy FINAL text index reader and its test): client time 0.31 s to 0.40-0.43 s, scored as a confirmed regression. The same queries were flagged slower on 15 of the 18 PRs that ran this shard between 06:03Z and 06:58Z today, while the master run in that window was not. The shard's min_max_index_with_cast #0 is only unstable and does not block a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the owner of the row above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-083003

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 3/6) long_primary_key red: #127365

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-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants