Skip to content

Keep a direct read from a text index local in plan-based parallel replicas - #112723

Closed
alexey-milovidov wants to merge 9 commits into
masterfrom
fix/pr-plan-based-text-index-direct-read
Closed

alexey-milovidov wants to merge 9 commits into
masterfrom
fix/pr-plan-based-text-index-direct-read

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Related: #111990
Related: #108818

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):

Fix the logical error Column ... already added for reading when plan-based parallel replicas (parallel_replicas_plan_based) captured a plan doing a direct read from a text index (query_plan_direct_read_from_text_index), e.g. when the same text-search predicate appears in both PREWHERE and WHERE. Such a plan is now executed locally.

Description

Direct read from a text index replaces a text-search function (hasToken, hasAnyTokens, ...) with a synthetic __text_index_..._has_<hash> virtual column and registers an index read task on the ReadFromMergeTree step. That per-step state does not survive capturing the read into a plan-based parallel-replicas fragment: ReadFromMergeTree::clone copies the rewritten column list but not the index read tasks, so re-optimizing the local fragment considered direct read "not yet applied", registered the virtual column a second time, and threw the logical error Column ... already added for reading (an exception, and an abort in debug builds) when the same predicate appeared in both PREWHERE and WHERE. A remote replica also cannot resolve the synthetic column against the table (the make_distributed_plan analogue is #108818).

The text-index rewrite runs earlier in the same optimization pass, so the tasks are already registered when applyParallelReplicas runs; keep such a plan local, following the existing precedent for FINAL reads and IN (subquery).

Found by AST fuzzer (amd_debug) in the unrelated #111990 on a mutation of 04338_text_index_codec_setting_change_merge:

SELECT count() FROM t_codec_change PREWHERE hasToken(s, 'hello') WHERE hasToken(s, 'hello') LIMIT 374

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111990&sha=e26559ad01883fd20334df73425012376b5a01d7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

Verified A/B against a local server with the localhost 3-replica cluster: without the fix the new test throws the exact logical error from CI; with the fix all queries return correct results, the direct-read plan stays local, a plain read is still split for parallel replicas, and 04409_pr_plan_based and 02346_text_index_parallel_replicas still pass.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…licas

Direct read from a text index registers a synthetic
`__text_index_..._has_<hash>` virtual column and an index read task on the
`ReadFromMergeTree` step. Capturing such a read into a plan-based
parallel-replicas fragment loses the index read tasks
(`ReadFromMergeTree::clone` copies the rewritten column list but not the
tasks), so re-optimizing the local fragment registered the virtual column a
second time and threw the logical error `Column ... already added for
reading` when the same predicate appeared in both `PREWHERE` and `WHERE`.
Keep such a plan local, like the `FINAL` and `IN (subquery)` cases.

Found by AST fuzzer (amd_debug) on a mutation of
04338_text_index_codec_setting_change_merge in an unrelated PR:
#111990
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111990&sha=e26559ad01883fd20334df73425012376b5a01d7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b305123]

Summary: ✅


AI Review

Summary

This PR tightens parallel_replicas_plan_based around two real failure modes: text-index direct reads that cannot be cloned/serialized safely, and reads pinned by select_sequential_consistency. The fixes from the earlier review threads are present in the current code, but one correctness gap still remains: plan-based PR still has no counterpart to the classic distributed-plan rejection for the part-order virtual columns _part_index and _part_starting_offset.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp:72-93] [dismissed by author -- https://github.com/Keep a direct read from a text index local in plan-based parallel replicas #112723#discussion_r3743732802] mergeTreeReadCanBeShipped now mirrors the pinned-block-number guard from checkDistributedReadSupported, but it still does not reject reads exposing _part_index / _part_starting_offset. That is still a real correctness hole: the shipped-fragment path serializes only part identity and mark ranges (RangesInDataPartDescription), not part_index_in_query / part_starting_offset_in_query, and ReadFromMergeTree::serialize already documents that these part-order virtual columns must be rejected before serialization. A plan-based PR read can therefore still ship these columns and return per-replica numbering instead of the initiator's global query-order numbering. Fold the same column-name check from checkDistributedReadSupported into mergeTreeReadCanBeShipped so it also covers the broadcast side via subtreeHasUnshippableRead, and add a focused parallel_replicas_plan_based = 1 regression.
Final Verdict

❌ Request changes. The text-index and pinned-snapshot fixes look correct, but plan-based parallel replicas still appears to ship _part_index / _part_starting_offset reads with worker-local numbering semantics.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.70% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.90% +0.00%

Changed lines: Changed C/C++ lines covered: 25/26 (96.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 31, 2026
alexey-milovidov and others added 3 commits August 1, 2026 10:06
… the control query

`04658_text_index_direct_read_pr_plan_based` asserted that a read without a
direct read from a text index is still split for parallel replicas, using
`SELECT count() FROM t WHERE s != ''` as the control query. With the randomized
`optimize_trivial_count_with_sparsity_filter = 1` and
`compute_exact_num_defaults_for_sparse_columns = 1`,
`applyTrivialCountWithSparsityFilterIfPossible` answers that query from the
sparse-serialization defaults, so there is no `ReadFromMergeTree` left to
distribute and no `ReadFromParallelReplicas` in the plan - the test printed `0`
instead of `1` and failed in every stateless job.

Use `sum(length(s))`, which has to read the column, as the control query.
A/B verified locally against a three-replica localhost cluster: with the
culprit settings the old form prints `0` and the new form prints `1`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112723&sha=11119c375c78cd874658b7cbd51a4b4b4dc2bf4e&name_0=PR

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…or shipping

`planHasTextIndexDirectRead` walked the whole plan, so a direct read from a text
index that was never going to be shipped - the right (build) side of a JOIN,
which `collectReadsToDistribute` does not follow - disabled plan-based parallel
replicas for the rest of the query.

Check only the reads returned by `collectReadsToDistribute` instead. When one of
those has index read tasks the whole plan still stays local rather than dropping
that single read out of the eligible set: a union with a mix of local and
distributed branches is not supported and can produce wrong results, same as the
`FINAL` case.

Test: the left side of a JOIN whose right side does a direct text-index read is
still distributed. Verified locally against a three-replica localhost cluster -
the `EXPLAIN` has `ReadFromParallelReplicas` over `t_plain_pr_plan_based` while
the text-index read keeps its `__text_index_idx_hasToken_...` PREWHERE column
locally.

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

Copy link
Copy Markdown
Member Author

🕵 CI triage for the previous run (report):

Caused by this PR — fixed. 04658_text_index_direct_read_pr_plan_based failed in every stateless job. The control query SELECT count() FROM t WHERE s != '' was answered by applyTrivialCountWithSparsityFilterIfPossible under the randomized optimize_trivial_count_with_sparsity_filter = 1 + compute_exact_num_defaults_for_sparse_columns = 1, so there was no ReadFromMergeTree left to distribute and the test printed 0 instead of 1. It now uses sum(length(s)), which has to read the column. A/B verified locally against a three-replica localhost cluster: with the culprit settings the old form prints 0, the new form prints 1.

Unrelated.

  • 04612_join_runtime_filters_index_analysis_multi_key_anti — fails all over the place, including on master itself (pull_request_number = 0) and across ~25 unrelated PRs on 2026-07-31 per play.clickhouse.com. Nothing in this PR touches join runtime filters. I could not find a tracking issue.
  • Scraping system tables — the clickhouse-local TSan thread leak when dumping system.query_log; ~34 occurrences on 2026-07-31 alone, including on master. Labelled with Scraping system tables #110816, which is closed, so it has regressed or was never fully fixed.

@groeneai, could you investigate 04612_join_runtime_filters_index_analysis_multi_key_anti and the Scraping system tables thread leak and provide fixes in separate PRs? If either is already in progress, please link it here.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

Both are already fixed on master, and both fixes are yours. Details, plus one residual risk worth knowing about.

04612_join_runtime_filters_index_analysis_multi_key_anti

Owner: #111691, merged 2026-07-31 20:56 UTC. join_runtime_filter_min_probe_rows occurs 0 times in the test file at 11119c37 and once on master, so the cited build predates the pin.

The runner's own minimization at that sha names the culprit: 144/144 failed with the randomized settings, 182/182 passed without, culprit --join_runtime_filter_min_probe_rows 3433. The randomizer picks a value above the fixture's probe-side row count, so no runtime filter is built and the enable_join_runtime_filters_index_analysis = 0 vs = 1 equality assertions diverge. All 34 hits in the last 3 days carry result differs.

A tracking issue did exist: #112743, closed automatically when #111691 landed, about 3.5 hours before your comment.

Seven hits landed after that merge (07-31 21:08 UTC through 08-01 00:45 UTC), which looks like a failing fix but is not. I fetched the test file at each of those seven commits and the pin is absent in all seven, so they are pre-pin builds as well. Re-merging master clears this one, and no separate PR is needed.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112723&sha=11119c375c78cd874658b7cbd51a4b4b4dc2bf4e&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29

Scraping system tables

The signature at 11119c37 is the query_log AsyncLogger thread leak raised from OwnAsyncSplitChannel::open, not the minio dump timeout that also appears under this check name.

Root cause is #107363 (merged 2026-07-29 13:05 UTC), reverted by your #112793 (merged 2026-07-31 19:05 UTC). The cited build is about 8 hours older than the revert. Per-day counts are 14 on 07-29, 22 on 07-30, 34 on 07-31, 1 on 08-01. I probed OwnSplitChannel.cpp at all 12 thread-leak commits from the last two days, including the 07-31 21:09 UTC one that postdates the revert by two hours: every one still contains dequeueMessageForFlush, so all 12 are pre-revert builds and there are no post-revert occurrences. #110816 is correctly closed.

The residual is that the revert hides the defect rather than removing it. LocalServer derives from ClientApplicationBase, Loggers, IServer, and stopLogging is called only from BaseDaemon.cpp:150, so clickhouse-local still never joins its logging threads. Before #107363 the consumers blocked in waitDequeueMessage and TSan skipped them, since CollectThreadLeaks only reports threads already in ThreadStatusFinished. The polling while (is_open) loop let them reach that state and exposed the missing join. Master is back to the blocking form, so the leak is masked again, not gone.

Your #112753 was the durable fix and it was closed unmerged 41 minutes after the revert. @ nikitamikhaylov still wants #107363 in ("This PR fully deserves being merged") and I see no open re-land. Whenever it returns, this leak returns with it unless the ~LocalServer / stopLogging change lands first. I am happy to open that change as its own PR if you would rather not reopen #112753, just say which you prefer.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112723&sha=11119c375c78cd874658b7cbd51a4b4b4dc2bf4e&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20parallel%2C%203%2F3%29

Session id: cron:clickhouse-premium-slot-25:20260801-110700

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

The last check of `04658_text_index_direct_read_pr_plan_based` asserts that a direct
text-index read on the side that `collectReadsToDistribute` never follows does not
disable plan-based parallel replicas for the other side. Which side that is depends on
the join order, and the stateless test harness randomizes it through
`query_plan_optimize_join_order_randomize`: with a seed that swaps the tables, the
text-index read becomes the eligible one, the whole plan legitimately stays local, and
the test printed `0` instead of `1`.

Pin `query_plan_optimize_join_order_randomize`, `query_plan_optimize_join_order_limit`
and `query_plan_join_swap_table` for that query. Verified locally: the test fails with
the two seeds reported by CI (`183078`, `481645`) before this change and passes with
them after it.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks for the analysis — confirmed on both counts, and this PR is green now that master is merged.

On the residual: no separate PR is needed. The re-land of #107363 is #112803, and it already carries the durable fix that #112753 proposed — it adds LocalServer::~LocalServer calling stopLogging (programs/local/LocalServer.cpp / .h), so clickhouse-local joins its logging threads before exit. The leak will not come back with the re-land.

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b305123a8 with master 2c2cfce3a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.92 MiB 687.89 MiB -3.03 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

…rect text-index read

`collectReadsToDistribute` follows only the coordinated side of a JOIN, so the
guard in `insertParallelReplicasSplit` never sees the broadcast side. When
`liftSplitAboveJoin` then ships the whole join subtree, a broadcast-side
`ReadFromMergeTree` with direct text-index tasks is serialized without them,
and the remote replica fails with `Column __text_index_... not found in table`
(NOT_FOUND_COLUMN_IN_BLOCK): the PREWHERE references the synthetic virtual
column that only the index read tasks can produce.

Teach `subtreeHasUnshippableRead` to treat a read with non-empty
`getIndexReadTasks` as unshippable, so the split stays below the join: the
coordinated read is still distributed and the join with its broadcast side
stays local. Extend the test with an executed (not just explained) JOIN where
dropping the broadcast-side filter would change the result.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ased parallel replicas

A read with a pinned block-number boundary (`select_sequential_consistency`
clamps the read to the parts confirmed by the insert quorum) must not be
shipped into a plan-based parallel-replicas fragment: `ReadFromMergeTree`
serialization does not carry the pin and `deserialize` rebuilds the read
with `max_block_numbers_to_read = nullptr`, so a follower replica silently
reads parts the initiator's snapshot excludes and returns rows the quorum
never confirmed.

Reject `hasPinnedBlockNumbers` in `mergeTreeReadCanBeShipped`, mirroring
the rejection in `make_distributed_plan` (`makeDistributed.cpp`); the
predicate gates both the coordinated reads (`collectReadsToDistribute`)
and the broadcast side of a lifted join (`subtreeHasUnshippableRead`).

A/B verified locally against a 3-replica localhost cluster with a
two-replica quorum fixture (`SYSTEM STOP FETCHES` + failed quorum insert):
without the guard the pinned read is split and a remote-only execution
returns (435, 30) instead of the quorum-consistent (45, 10); with the
guard it stays local and returns (45, 10), and a plain read is still
distributed.

Co-Authored-By: Claude Fable 5 <[email protected]>
return false;
}

/// Direct read from a text index (`query_plan_direct_read_from_text_index`) replaces a text-search

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.

@groeneai Please shorten this comment to a single line.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Proposed:

/// A direct text-index read cannot be shipped: its index read tasks are not serialized, so a replica cannot resolve `__text_index_*`.

134 chars, within the 140 column limit. I do not have push access to this branch, so this is a suggestion rather than a commit.

One note on which half I kept. The clause saying ReadFromMergeTree::clone copies the rewritten column list but not the index read tasks is no longer true at this head: it copies them at ReadFromMergeTree.cpp:3777, added in 764308f and pulled into this branch by the 08-02 master merge, i.e. after this comment was written. Serialization still omits them, so the remote-resolution reason is the one that survives.

CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 10, 2026
Add to 04836 and 04837 the scenarios that the rejected-behavior tests of
the superseded PRs covered and the new positive tests did not: the AST
fuzzer shape with a mixed PREWHERE conjunction and a xor in WHERE, a text
index read shipped through a subquery under a shuffle join (both from
ClickHouse#108818), and a join whose
side carries a direct text-index read with a filter-sensitive result
(from ClickHouse#112723). Every query
is repeated with the distributed mode off and must return identical
results.

Related: ClickHouse#108818
Related: ClickHouse#112723

Co-Authored-By: Claude Fable 5 <[email protected]>
@CurtizJ

CurtizJ commented Aug 10, 2026

Copy link
Copy Markdown
Member

I'm trying to add proper support in #114242. Closing this for now.

@CurtizJ CurtizJ closed this Aug 10, 2026
pull Bot pushed a commit to TCeason/ClickHouse that referenced this pull request Aug 25, 2026
…plicas

select_sequential_consistency clamps a ReplicatedMergeTree read to the parts
the initiator saw confirmed by the insert quorum, via max_block_numbers_to_read.
The pin is not serialized: ReadFromMergeTree::deserialize rebuilds a shipped
read with max_block_numbers_to_read = nullptr. mergeTreeReadCanBeShipped did
not consult it, so the read was split for parallel replicas and each follower
silently read its own unclamped part set, returning rows the quorum never
confirmed with no exception.

Reject hasPinnedBlockNumbers in mergeTreeReadCanBeShipped, mirroring the
rejection for the same property in make_distributed_plan
(checkDistributedReadSupported, makeDistributed.cpp). The predicate gates both
collectReadsToDistribute (the coordinated read) and subtreeHasUnshippableRead
(the broadcast side of a lifted join), so one check covers both carriers.
Returning false rather than throwing matches how this path already keeps a
refreshable-MV target read local, and how the same file keeps FINAL reads and
IN (subquery) plans local: make_distributed_plan is an explicit opt-in,
plan-based parallel replicas falls back to a local read.

A/B on a two-replica quorum fixture (SYSTEM STOP FETCHES plus a timed-out
insert_quorum = 2, insert_quorum_parallel = 0 insert, so /quorum/status stays
set), remote-only, with the guard reverted and nothing else changed: the pinned
read is split and returns (435, 30) instead of the quorum-consistent (45, 10),
and a join reading the pinned table on its broadcast side returns 30 rows where
the truth is 10. The fixture is asserted armed before measuring, since SYSTEM
STOP FETCHES is in-memory only and a restart evaporates the pin.

The join arm coordinates a plain MergeTree, which has no sequential-consistency
branch and therefore keeps its split marker, so the broadcast-side check is
reached rather than short-circuited by the coordinated read being rejected
first. It asserts step order rather than step presence: refusing the lift keeps
the split below the join, so ReadFromParallelReplicas appears either way and
only its position distinguishes a local join over a distributed read from a
fully shipped join.

The fix and its regression test are Alexey Milovidov's, from commit
b305123 on ClickHouse#112723, which was closed unmerged in favour of ClickHouse#114242. That
PR reworks text-index distributed reads and does not carry this guard.

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

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants