Skip to content

Reject make_distributed_plan over a direct read from a text index - #108818

Closed
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-text-index-make-distributed-plan-4792-6322
Closed

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-text-index-make-distributed-plan-4792-6322

Conversation

@groeneai

@groeneai groeneai commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #108256
Related: #110710

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 NOT_FOUND_COLUMN_IN_BLOCK when running a query with make_distributed_plan = 1 over a MergeTree table that does a direct read from a text index (hasToken, hasAnyTokens, hasAllTokens). Such a read is now rejected at planning time when the plan is split into fragments; a plan that stays single-stage is executed locally and keeps working.

Description

Direct read from a text index replaces a text-search function with a synthetic __text_index_..._has_<hash> column that exists only in the coordinator's ReadFromMergeTree step. A worker rebuilds its fragment against the table, where that column does not exist, so the read fails at execution:

Code: 10. Column `__text_index_idx_hasToken_069e4fda5f4a1c148cc61654dcfef458` not found in table default.t

surfacing to the client as RECEIVED_ERROR_FROM_REMOTE_IO_SERVER. The fix rejects such a read at planning time, next to the existing rejections for pinned block-number boundaries and the part-order virtual columns, and mirrors #108256 which rejects projections for distributed reads for the same reason.

Only a plan that is actually split into fragments ships the read. The check therefore runs in its own pass after the tryMakeDistributed* transforms and the exchange optimization, which is what decides whether a fragment is created, and returns early when the plan has no exchange step, i.e. exactly when makeDistributedPlan produces a single stage that QueryPlan::convertToDistributed keeps local. Next to checkDistributedReadSupported would be too early: the exchange topology does not exist yet, so every direct text index read would be rejected, including the ones that run locally and correctly today.

This PR originally also covered a single-stage LOGICAL_ERROR (Column ... already added for reading) from re-running the non-idempotent text index optimization. That no longer happens: the pass skips repeated direct-read registration once index read tasks are present (#110710), so only the shipped-fragment failure remains.

Verified against a server with the stateless worker enabled: every shipped shape in the test, including a text index read reached through a join, fails with the missing-column error on master and is rejected at planning time with this change, while both single-stage shapes return the same rows as the non-distributed plan in either build. Found by the AST fuzzer, AST fuzzer (amd_debug, targeted), STID 4792-6322.

A direct read from a text index adds ephemeral virtual columns
(__text_index_idx_...) to the MergeTree read plus a separate index-read step.
A distributed worker fragment cannot reproduce these: the virtual column is
not in the table and ReadFromDistributedPlanSource cannot materialize it.

buildQueryPipeline runs the second optimization pass once via optimize() and,
for make_distributed_plan, again via convertToDistributed(). The text index
optimization is not idempotent (it appends the virtual column to
all_column_names), so the single-stage re-optimization re-adds the same column
and aborts with the LOGICAL_ERROR "Column ... already added for reading"
(server abort in debug/sanitizer builds). The multi-stage path instead fails
at execution with NOT_FOUND_COLUMN_IN_BLOCK.

Reject the unsupported combination cleanly at planning time in
checkDistributedReadSupported, next to the existing rejections for pinned
block-number boundaries and part-order virtual columns. Found by the AST
fuzzer (STID 4792-6322).

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. make_distributed_plan=1 + direct read from a text index aborts the server every time (exit 134 in debug); the exact fuzzer query and a one-line hasToken repro both reproduce.
b Root cause explained? Yes. buildQueryPipeline runs the second optimization pass twice for make_distributed_plan (once via optimize(), again via convertToDistributed() single-stage). The text index optimization is not idempotent: it appends the ephemeral __text_index_idx_... virtual column to all_column_names, so the second run re-adds it and hits the already added for reading LOGICAL_ERROR. Underlying cause: a distributed worker fragment cannot reproduce that virtual column.
c Fix matches root cause? Yes. Rejects the unsupported combination at planning time in checkDistributedReadSupported, the same gate that already rejects pinned block-number boundaries and part-order virtual columns. Mirrors the merged #108256 (projections rejected for distributed reads).
d Test intent preserved / new tests? New regression test 04417_text_index_make_distributed_plan_not_supported. No existing test weakened.
e Demonstrated in both directions? Yes. Unfixed binary: aborts / NOT_FOUND_COLUMN_IN_BLOCK. Fixed binary: clean SUPPORT_IS_DISABLED. Test FAILS unfixed, PASSES fixed (verified by stashing the fix, rebuilding, rerunning).
f Fix is general, not a narrow patch? Yes. The planning-time gate covers all text index direct reads (WHERE, PREWHERE, both), all functions (hasToken/hasAnyTokens/hasAllTokens), and both the single-stage abort path and the multi-stage NOT_FOUND_COLUMN_IN_BLOCK path, not just the one fuzzer query.
g Generalizes across inputs? Yes. Tested hasToken/hasAnyTokens/hasAllTokens, WHERE/PREWHERE/both, empty needle, and distributed_plan_execute_locally on and off. Non-text-index distributed reads are unaffected (verified a plain table still distributes and returns correct results); non-distributed text index reads still optimize and return correct results.
h Backward compatible? Yes. Only adds a clean error for a combination that previously crashed or returned NOT_FOUND_COLUMN_IN_BLOCK. No setting default or on-disk/wire format change. make_distributed_plan is an experimental feature (default off).
i Invariants and contracts preserved? Yes. The change only throws earlier on an already-broken path; it touches no data structures, concurrency, or serialization. hasTextIndexReadTasks() is a pure read of existing index_read_tasks state.

Session id: cron:clickhouse-worker-slot-1:20260629-134800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @CurtizJ — could you review this? It rejects make_distributed_plan = 1 over a direct read from a text index in checkDistributedReadSupported (next to the existing pinned-block / part-order rejections), the same way #108256 rejects projections. Without it the single-stage path re-runs the non-idempotent text index optimization and aborts with Column ... already added for reading (AST fuzzer, STID 4792-6322); the multi-stage path fails with NOT_FOUND_COLUMN_IN_BLOCK.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [95e2471]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-3a3c) FAIL cidb

AI Review

Summary

This PR moves the text-index guard to the point where the optimizer already knows whether a ReadFromMergeTree will be shipped as a distributed fragment, so multi-stage plans fail early with SUPPORT_IS_DISABLED while single-stage/local plans keep their existing direct-read behavior. I did not find a remaining correctness issue in the current code or a new inline review comment to post; the earlier over-broad rejection reported on the inline thread is fixed in the current head.

Documented surface
  • make_distributed_plan: docs/en/ grep found no hits; Cloud-docs hits are generic experimental-feature / release-note pages only. No published flow promises that text-index direct reads work under distributed-plan fragmentation, so the documented surface remains valid.
  • query_plan_direct_read_from_text_index: docs/en/engines/table-engines/mergetree-family/textindexes.md documents direct reads in general; Cloud-docs hits are release notes only. Those docs do not promise compatibility with make_distributed_plan, and the documented non-distributed / single-stage flows still work, so the documented surface remains valid.
  • hasToken: docs/en/engines/table-engines/mergetree-family/textindexes.md and docs/en/engines/table-engines/mergetree-family/mergetree.md document text-index usage; Cloud-docs hits are generic usage guides / release notes. None document the rejected distributed-plan combination, so the documented surface remains valid.
  • hasAnyTokens: docs/en/engines/table-engines/mergetree-family/textindexes.md, docs/en/engines/table-engines/mergetree-family/mergetree.md, and docs/en/operations/system-tables/tokenizers.md document text-index usage; Cloud-docs hits are generic usage guides / release notes. None document the rejected distributed-plan combination, so the documented surface remains valid.
  • hasAllTokens: docs/en/engines/table-engines/mergetree-family/textindexes.md, docs/en/engines/table-engines/mergetree-family/mergetree.md, and docs/en/operations/system-tables/tokenizers.md document text-index usage; Cloud-docs hits are generic usage guides / release notes. None document the rejected distributed-plan combination, so the documented surface remains valid.
Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 867d48c

Every failure below has an owner: a fixing PR (ours 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) / Block structure mismatch in UnionStep stream (STID 0993-27f0) chronic trunk fuzzer bug (const vs non-const __table1.year in UnionStep; 14 master hits + 115 PRs / 30d; unrelated to this PR's makeDistributed/text-index diff) #107719 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable)

This PR's own fix (the make_distributed_plan + text-index direct-read LOGICAL_ERROR, STID 4792-6322) and its regression test 04417 are green. The lone red check is the pre-existing chronic UnionStep block-structure-mismatch (STID 0993-27f0), owned by open fixing PR #107719.

Session id: cron:our-pr-ci-monitor:20260629-183000

groeneai added 5 commits July 29, 2026 20:01
The guard was unconditional, so it also rejected queries whose plan is not
split into fragments. Such a plan is executed locally, the synthetic
__text_index_..._has_<hash> column never has to be reconstructed on a worker,
and the query runs correctly today. Rejecting it was a regression.

Whether a read ends up inside a shipped fragment is only decided by the
tryMakeDistributed* transforms and the exchange optimization, both of which run
after checkDistributedReadSupported. The check therefore moves to a separate
pass that runs after them and returns early when the plan contains no exchange
step, which is exactly when makeDistributedPlan produces a single stage that
QueryPlan::convertToDistributed keeps local.

The single-stage LOGICAL_ERROR "Column ... already added for reading" the
original guard also covered no longer happens: the direct read pass bails out
once index read tasks are present (ClickHouse#111930). What remains is the multi-stage
failure, where a worker rebuilds the fragment against the table and the
synthetic column is missing (NOT_FOUND_COLUMN_IN_BLOCK at execution). Verified
against a server with the stateless worker enabled: all four shipped shapes in
the test fail with that error on master and are rejected at planning time with
the fix, while both single-stage shapes return the same rows as the
non-distributed plan in either build.

The hasTextIndexReadTasks accessor is dropped: getIndexReadTasks is public.
…up_by

Three fixes from the second-model review of the previous commit.

The new pass was gated on the local `make_distributed_plan`, which is false once
the plan already carries exchanges. StorageMerge pushes a filter into a child
plan and re-runs the second pass on it, so the direct read can be applied for
the first time during such a later run and the guard would be skipped. Gate on
the raw setting instead, like the neighbouring `optimizeExchanges` and
`materializeConstantsForSetOperationBranches` calls. Not reachable today
(ReadFromMerge is rejected earlier as non-serializable), so no test.

distributed_plan_single_stage keeps every exchange inside one local stage, so
exchange presence alone no longer means the read is shipped. Skip the check in
that mode, otherwise the promised single-stage behavior breaks for that
debugging path.

The three count() queries in the test asserted only the error code, and the
test profile sets max_rows_to_group_by, which makes
tryMakeDistributedAggregation throw the same SUPPORT_IS_DISABLED code before
the new check is reached. Measured: with max_rows_to_group_by = 10G those
queries throw "does not support aggregation with max_rows_to_group_by" even
with direct text index reading disabled, so all three assertions passed for the
wrong reason. Pin the setting to 0, as 04320_distributed_plan_read_rejects
already does.
Two more oracle problems from the second-model review.

All the rejection queries accepted only the error code, and a server without a
stateless worker client throws the same SUPPORT_IS_DISABLED code from
DistributedPlanExecutor while constructing the executor, so the assertions did
not distinguish the planning rejection from a missing worker. Set
distributed_plan_execute_locally = 1, as the 19 sibling distributed_plan tests
do. On master the queries now fail with the actual defect
(NOT_FOUND_COLUMN_IN_BLOCK for the synthetic __text_index_ column) instead of a
generic code, which is a much sharper pre-fix signal.

The two single-stage queries only compared rows, which a plan silently falling
back to a per-row function evaluation would also satisfy. Add a plan oracle
asserting the synthetic __text_index_ column is present, so the rows prove
direct read really was applied. Measured with direct read disabled it returns 0,
so the assertion is discriminating. The outer SELECT pins make_distributed_plan
to 0 because the EXPLAIN wrapper itself is not serializable.

Also add the missing hasAllTokens carrier, verified to fail on master with the
same missing-column error.
The second-model review pointed out that a subplan with text index tasks and no
exchange of its own is attached beneath an outer plan that does have exchanges,
so the read is still shipped. Measured: a join whose right side is a local text
index read fails on master with the same missing-column error and is rejected by
this change, because the guard runs on the whole plan after the subplans are
attached. Add it as a regression case.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6f8d218

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (arm_binary, parallel) / 02354_distributed_with_external_aggregation_memory_usage trunk-visible Code 241 at the CI 5G profile limit, 22 rows across 20 unrelated pull requests and 2 master runs in 30 days; the reruns confirm it is flaky, not caused by this diff #112478 (ours, merged 2026-07-30)
Stress test (amd_msan) / Logical error: Block structure mismatch in joined block stream: different number of columns (STID 0993-3a3c) chronic trunk bug on the join pipeline, unrelated to this diff a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)

The fixing pull request for the first row is merged but is not yet on this branch, so the
test can legitimately keep failing here until master is merged in. Verified rather than assumed:
the max_insert_threads pin that #112478 adds is absent from this branch's copy of the test.
Merging master to pick it up is the next step on this pull request.

Session id: cron:our-pr-ci-monitor:20260730-163853

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.70% +0.20%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 95e2471

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
Stress test (amd_msan) / Logical error: 'Block structure mismatch in joined block stream: different number of columns: __join_result_dummy UInt8 Const(...)' (STID 0993-3a3c) trunk bug in ConstantJoin::addBlockToJoin, reached when both children of an enclosing join emit only __join_result_dummy; the carrier query is an unrelated fuzzed multi-table join #112205 (mine, open)

All 174 check-runs on this commit are completed and this is the only failing check. Not caused by
this PR: the diff is 4 files rejecting make_distributed_plan over a direct text-index read, and it
cannot affect join-side block structure.

This discharges the link-back promised on the previous head's ledger
(6f8d218db061e0dbcf13d66ec33757818f7cc3c3), where this row read "a fix task owns this, fixing-PR
link to follow on this PR". The fix is now open as #112205, whose changelog names this exact
exception, so the row is a fixing-PR link rather than a task disposition. Its own sibling
sub-signature at ConstantJoin.cpp:230 (a duplicated real column rather than a const dummy) shares
the same STID and is deliberately out of scope for #112205.

The 02354_distributed_with_external_aggregation_memory_usage row from the previous ledger is
resolved: #112478's merge commit 695cd64b66ff0f2413f3f0781570d15601554ebd is now an ancestor of
this branch and that test is green on this commit.

Session id: cron:our-pr-ci-monitor:20260730-230000

@rschu1ze

Copy link
Copy Markdown
Member

@groeneai Post a minimal reproducible example.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Needs a server with the stateless worker enabled (tests/config/config.d/distributed_query.xml); clickhouse local cannot reproduce it, it has no worker client.

SET allow_experimental_full_text_index = 1;

CREATE TABLE t_min (s String, INDEX idx s TYPE text(tokenizer = 'splitByNonAlpha'))
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_min VALUES ('uniform');

SELECT count() FROM t_min WHERE hasToken(s, 'uniform')
SETTINGS make_distributed_plan = 1, distributed_plan_execute_locally = 1;

On 26.7.4.12:

Code: 10. DB::Exception: Column `__text_index_idx_hasToken_069e4fda5f4a1c148cc61654dcfef458`
not found in table default.t_min: While executing ReadFromDistributedPlanSource.
(NOT_FOUND_COLUMN_IN_BLOCK)

Direct read replaces hasToken with that synthetic column, which exists only in the initiator's read step; the worker rebuilds the fragment against the table and cannot find it. Dropping distributed_plan_execute_locally gives the same failure through a real worker as Code: 86 RECEIVED_ERROR_FROM_REMOTE_IO_SERVER.

One thing you should know before deciding on this PR: the same file returns 1 on master today. #112463 (merged 2026-07-31, after my last push here) force-disables query_plan_direct_read_from_text_index whenever make_distributed_plan = 1, in adjustSettingsForMakeDistributedPlan, and it does so on every settings-change path, so I could not find a way to reach the failure on master at all: per-query SETTINGS, session SET in either order, a user profile default, a view carrying its own SETTINGS, and remote() all end with the setting reading false. That makes my planning-time reject unreachable on master, so the fix is now redundant there. #112463 is not on any release branch, so 26.7 and earlier are still affected, and its own comment marks the override as a temporary workaround to be removed once distributed plans carry the text-index read tasks.

So I would rather close this PR than narrow it further, unless you want the reject kept as the permanent guard for when that override is removed. Your call.

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