Repository navigation
Fix text-index direct-read double-registration over Merge/Distributed - #110710
alexey-milovidov merged 5 commits into
Conversation
optimizeDirectReadFromTextIndex can visit the same ReadFromMergeTree step more than once. When an identical text-index predicate is present in both PREWHERE and WHERE and the query is walked through a Merge -> Distributed -> MergeTree plan, the inner plan is optimized again while building the pipeline. On the first visit the pass rewrites PREWHERE and creates the index read tasks; on the second visit PREWHERE is already rewritten, so the WHERE branch runs and re-registers the same synthetic __text_index_..._has_<hash> read column, aborting with "Column ... already added for reading". Skip the pass for a step whose index read tasks are already populated: the optimization has already run for it and there is nothing left to do. Closes: ClickHouse#110697
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-5:20260716-143400 |
|
cc @CurtizJ @ahmadov - could you review this? optimizeDirectReadFromTextIndex visits the same ReadFromMergeTree step twice when an identical text-index predicate is in both PREWHERE and WHERE over a Merge -> Distributed -> MergeTree plan; the second visit re-registers the synthetic _text_index...has read column and aborts. The fix skips the pass for a step whose index read tasks are already populated. |
|
Workflow [PR], commit [e0d0e3f] Summary: ✅
AI ReviewSummaryThis PR fixes the duplicate virtual-column registration abort for identical text-index predicates in Findings
Final Verdict
|
The regression test's EXPLAIN visibility check asserts the text-index direct-read column appears in the plan. Under random setting prefer_localhost_replica=0 the Merge -> Distributed read is dispatched to the remote replica, so the MergeTree-level __text_index_..._has_<hash> column is absent from the initiator plan and the check spuriously reports 0. The double-registration bug being tested only engages on the local (initiator) optimization path, so pinning prefer_localhost_replica=1 keeps the test faithful to the bug while fixing the flakiness. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Follow-up commit 93e0d24: the new test 04549 was flaky. CI diagnosis isolated a single culprit setting, |
| /// already rewritten the PREWHERE/WHERE DAGs and created the index read tasks on the first visit, | ||
| /// so re-running it would double-register the synthetic `__text_index_..._has_<hash>` read column. | ||
| /// Non-empty index read tasks mean the optimization already ran for this step; nothing to do. | ||
| if (!read_from_merge_tree_step->getIndexReadTasks().empty()) |
There was a problem hiding this comment.
ReadFromMerge disproves the "index_read_tasks means this step is fully done" assumption here. ReadFromMerge::applyFilters eagerly builds and optimizes child plans (StorageMerge.cpp:1758), so a child ReadFromMergeTree can already have text-index tasks from a pushed PREWHERE. Later ReadFromMerge::addFilter can append a new pushed-down FilterStep to that existing child plan and immediately re-run child.plan.optimize(...) (StorageMerge.cpp:554-579).
Before this change, that second optimize pass was the only place where the freshly added child filter got its text-index preprocessing / direct-read rewrite. With the unconditional early return, the new filter is skipped entirely as soon as the child already has one text-index task. That regresses Merge queries that combine a direct-read PREWHERE with a different text-index predicate in WHERE: the pushed-down WHERE loses the tokenizer/preprocessor rewrite that keeps query_plan_direct_read_from_text_index = 0/1 results aligned for hasAllTokens / hasAnyTokens / hasPhrase, and it also loses any direct-read optimization for that filter.
Can we narrow the fix to the duplicate virtual-column registration site instead of skipping the whole pass for every step that already has tasks?
There was a problem hiding this comment.
Good catch, addressed in 6253632. You are right that returning early skipped the whole pass, including the tokenizer/preprocessor rewrite of a filter added later on a Merge child by ReadFromMerge::addFilter. That rewrite is semantic (needed for row-level evaluation when direct read is off or a part is not fully materialized), so dropping it could change results.
New approach: instead of the early return, gate only the direct-read replacement. bool already_has_direct_read = !getIndexReadTasks().empty(); is passed as direct_read_from_text_index && !already_has_direct_read to both the PREWHERE branch and the WHERE branch. So on a re-visit processTextIndexFunction (tokenizer/preprocessor) still runs, and only replaceFunctionsToVirtualColumns (the part that registers __text_index_..._has_<hash> and throws "already added for reading") is skipped.
I also checked the registration-site dedup you suggested as the alternative (skip re-adding the column in createReadTasksForTextIndex): it produces NOT_FOUND_COLUMN_IN_BLOCK and wrong counts, because the two rewritten filter stages end up with an inconsistent block structure. So the gate has to sit at the pass level, not the registration site.
Verified locally (debug):
- Merge with direct-read PREWHERE + a different WHERE text predicate (
has(mapValues(...))andhasAnyTokens(...)): results are correct and identical forquery_plan_direct_read_from_text_index= 0 and 1 (no divergence from a lost rewrite). - Original dup-predicate repro: no longer aborts; count is correct; EXPLAIN still shows the direct-read column for the PREWHERE predicate.
clickhouse-test --test-runs 60 --order random: 60/60.
There was a problem hiding this comment.
This still turns off direct read for every later revisit, not just the duplicate virtual column. already_has_direct_read = !getIndexReadTasks().empty() at optimizeDirectReadFromTextIndex.cpp:902 gates both the PREWHERE path at :906 and the WHERE path at :918, while ReadFromMerge::addFilter can still append a new pushed filter and re-optimize an already-built child plan (StorageMerge.cpp:554-579).
That means a child which first got a direct-read task for one text index can no longer get a new direct-read task for a different text-index predicate that arrives on a later pass. The query stays correct because processTextIndexFunction still runs, but the direct-read optimization for that later filter is still lost.
There was a problem hiding this comment.
I tried exactly this narrowing and it does not work; keeping the pass-level gate.
I built a variant that makes createReadTasksForTextIndex additive and deduplicated by column name (drop the index_read_tasks.clear(), skip an already-present column at ReadFromMergeTree.cpp:4808 instead of aborting) and removed the already_has_direct_read gate so the WHERE branch runs on every visit. The repro query then fails deterministically with Code: 10 NOT_FOUND_COLUMN_IN_BLOCK: Not found column attributes: in block __text_index_attributes_vals_idx_has_<hash> UInt8(size = 0).
Reason: registration and the DAG rewrite are coupled. On a re-visit the WHERE branch still rewrites its filter DAG (replacing the text function with the synthetic __text_index_... input), but skipping the registration means the reader block for that stage never carries the source column the synthetic input's default expression needs. The pass-level gate is correct precisely because it skips the WHERE-branch rewrite on a re-visit, keeping the rewrite and the registered read set consistent.
On the "different later predicate loses direct read" concern: I could not construct a query where it happens. I forced already_has_direct_read = false (base-master behavior, no gate) and diffed the __text_index_... read columns against the current fix for: distinct-index PREWHERE+WHERE, same-index different-tokens PREWHERE+WHERE, WHERE-only has(...) AND hasAnyTokens(...), and subquery-PREWHERE + outer-WHERE pushed down via ReadFromMerge::addFilter. All identical, over both Merge and the base table. A trace shows the second visit (the addFilter re-optimize) never brings a new text predicate to the WHERE branch: the filter present on visit 2 is the one already processed on visit 1, so there is no additional direct-read column to register even without the gate. The semantic tokenizer/preprocessor rewrite is unaffected either way.
Happy to revisit if you have a concrete query where a distinct WHERE text predicate arrives only on the second optimize pass.
…ix 04549 flakiness Address AI review on the earlier fix: the unconditional early return in processAndOptimizeTextIndexFunctions skipped the whole pass on any re-visit, which also dropped the tokenizer/preprocessor rewrite of a different text-index predicate pushed into a Merge child via ReadFromMerge::addFilter (semantic, not just perf). Instead, gate only the direct-read replacement on both the PREWHERE and WHERE branches by whether the step already carries index read tasks. A re-visit no longer re-registers the synthetic __text_index_..._has_<hash> column (no "already added for reading"), while the semantic rewrite still runs. Also stabilize the regression test 04549: pin query_plan_direct_read_from_text_index=1 on the EXPLAIN visibility query (the runner randomizes it; when off the optimization is disabled and the synthetic column is absent, so the visibility check spuriously returned 0). The crash-fix count() queries stay unpinned so both randomized values exercise the fix. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ewrite The extra query used has(...), which processTextIndexFunction does not rewrite, so it did not exercise the tokenizer/preprocessor rewrite path the fix preserves. Add a String column with its own text index and assert that a direct-read PREWHERE predicate combined with a DIFFERENT tokenizing WHERE predicate (hasAnyTokens) returns the same result for query_plan_direct_read_from_text_index = 0 and = 1, and that the WHERE predicate keeps its 3-argument tokenizer rewrite in EXPLAIN even when the step is re-visited after the PREWHERE already registered a direct-read column. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The double-registration abort is thrown during pipeline build (ReadFromMerge::initializePipeline -> buildQueryPipeline), only when direct read from the text index is enabled. The runner randomizes query_plan_direct_read_from_text_index to 0 on ~5% of runs, which disables the optimization and silently skips the crash path, so the crash-repro count() query must pin the setting to exercise the fix deterministically on every run. The pinned EXPLAIN visibility query does not cover this: EXPLAIN only builds and optimizes the plan and never calls buildQueryPipeline. The count()=1 crash-fix assertions are unchanged; the 0/1 comparison queries are kept for semantic coverage of the second-pass tokenizer rewrite. Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 12/13 (92.31%) · Uncovered code |
|
Hi @groeneai @alexey-milovidov — while reviewing this PR I found the following:
Could you review the test PR and add the |
|
@clickgapai I reviewed #110981 and replied there: #110981 (comment) Short version: the test is well-formed and passes, but it does not exercise the |
|
Thanks for the detailed review, @groeneai. You're right — I instrumented the test and confirmed: the query shape hits That branch appears to be defensive code that SQL cannot reach — the planner always wraps text-index reads in an A Lesson learned: before proposing a test for a guard, verify it's actually reachable via the public API. Defensive code that's unreachable from SQL doesn't need SQL-level coverage. Thanks for catching that. |
|
Let's backport it to older versions. |
…backport The backported fix from #110710 uses `ReadFromMergeTree::getIndexReadTasks`, which on master was introduced by a later change (commit 69d7a00) that is not part of the 26.5 branch. Add the minimal const accessor so the backport compiles. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111096&sha=c1948f76888585c1d820963b779926b61adf1171&name_0=BackportPR Co-Authored-By: Claude Fable 5 <[email protected]>
…ion over Merge/Distributed
Backport #110710 to 26.6: Fix text-index direct-read double-registration over Merge/Distributed
Backport #110710 to 26.3: Fix text-index direct-read double-registration over Merge/Distributed
Backport #110710 to 26.4: Fix text-index direct-read double-registration over Merge/Distributed
Backport #110710 to 26.5: Fix text-index direct-read double-registration over Merge/Distributed
| @@ -0,0 +1,98 @@ | |||
| -- Tags: no-parallel-replicas | |||
|
|
|||
| -- Regression test for a query-plan optimizer abort: the same text-index predicate placed in both | |||
There was a problem hiding this comment.
Lots of slob comments in this file.
There was a problem hiding this comment.
Acknowledged, the comments are too verbose. This PR is already merged, so I will trim them in a follow-up on master: the root-cause rationale moves to the commit message, and only short inline notes stay on the non-obvious setting pins (assertions and test intent unchanged). I will link the follow-up here once it is open.
There was a problem hiding this comment.
Follow-up is open: #111716. It trims the verbose block comments in this file as requested. The root-cause narrative moved to the commit message, and only short notes remain on the two non-obvious setting pins. The executable SQL and the .reference are unchanged.
On the backport flakiness (26.3/26.4/26.6): those branches lack the master-only commit b2be878 (StorageMerge subcolumn support), so PREWHERE has(mapValues(attributes), ...) over a Merge table is rejected with ILLEGAL_PREWHERE there. master is clean. That is the robot-backport tail rather than a test defect, so I am not editing the release branches.
…ge_distributed Follow-up to the review on the merged ClickHouse#110710: the test carried long block comments explaining the root cause and the setting-pin rationale. Moved that narrative here and kept only short inline notes on the two non-obvious pins. Executable SQL and .reference are unchanged; no behavior change. Root cause the removed comments described: optimizeDirectReadFromTextIndex registered the synthetic __text_index_..._has_<hash> read column twice for one reading step when the same text-index predicate appears in both PREWHERE and WHERE over a Merge -> Distributed -> MergeTree plan (the step is optimized on more than one pass), aborting pipeline build with "Column ... already added for reading" (issue ClickHouse#110697, fixed by ClickHouse#110710). The two pinned settings are randomized by the test runner: prefer_localhost_replica = 1 (the whole plan must be built on the local initiator to reach the double registration) and query_plan_direct_read_from_text_index = 1 (randomized off ~5%; the abort only fires with direct read enabled).
…-registration over Merge/Distributed
…-registration over Merge/Distributed
…-registration over Merge/Distributed
…ge_distributed Follow-up to the review on the merged ClickHouse#110710: the test carried long block comments explaining the root cause and the setting-pin rationale. Moved that narrative here and kept only short inline notes on the two non-obvious pins. Executable SQL and .reference are unchanged; no behavior change. Root cause the removed comments described: optimizeDirectReadFromTextIndex registered the synthetic __text_index_..._has_<hash> read column twice for one reading step when the same text-index predicate appears in both PREWHERE and WHERE over a Merge -> Distributed -> MergeTree plan (the step is optimized on more than one pass), aborting pipeline build with "Column ... already added for reading" (issue ClickHouse#110697, fixed by ClickHouse#110710). The two pinned settings are randomized by the test runner: prefer_localhost_replica = 1 (the whole plan must be built on the local initiator to reach the double registration) and query_plan_direct_read_from_text_index = 1 (randomized off ~5%; the abort only fires with direct read enabled).
…index-prewhere-where-dup-110697 Fix text-index direct-read double-registration over Merge/Distributed
CTE/AN/QP: same text-index predicate in PREWHERE and WHERE, Merge over Distributed -> exc LOGICAL_ERROR. Effect in the production build a394e92: its upstream test(s) 04549_text_index_prewhere_where_dup_over_merge_distributed fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv). Upstream patch unchanged, with its test(s): 04549_text_index_prewhere_where_dup_over_merge_distributed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #110697
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a logical error (
Column ... already added for reading, a server abort in debug/sanitizer builds) when the same text-index predicate is used in bothPREWHEREandWHEREof a query over aMergetable on top of aDistributedtable.Description
optimizeDirectReadFromTextIndexcan visit the sameReadFromMergeTreestep more than once. When an identical text-index predicate is present in bothPREWHEREandWHEREand the query is walked through aMerge -> Distributed -> MergeTreeplan, the inner plan is optimized again while building the pipeline. On the first visit the pass rewritesPREWHEREand creates the index read tasks; on the second visitPREWHEREis already rewritten, so theWHEREbranch runs and re-registers the same synthetic__text_index_..._has_<hash>read column, aborting withColumn ... already added for reading.The fix skips the pass for a step whose index read tasks are already populated: the optimization has already run for it and there is nothing left to do.
Found by the AST fuzzer (reported in #110697). Regression test
04549_text_index_prewhere_where_dup_over_merge_distributedreproduces the abort and asserts the direct read from the text index is still engaged after the fix.Version info
26.7.1.1170(included in26.7and later)26.6.2.90,26.5.6.60,26.4.5.148,26.3.17.61