Skip to content

Fix logical error in STREAM read over a text-indexed table - #111504

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-streaming-text-index-double-optimize
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-streaming-text-index-double-optimize

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

Found by the AST fuzzer on #110084 (unrelated to that PR): AST fuzzer (amd_debug), STID 0993-32d6.

A SELECT ... FROM t STREAM ... PREWHERE <text-search predicate> over a table with a text index aborted with a LOGICAL_ERROR:

  • Block structure mismatch ... between ExpressionTransform and MergeTreeCommitOrderSequentialSource stream ... at MergeTreeCommitOrderSequentialSource.cpp:470 (one text index), or
  • Column __text_index_..._equals_... already added for reading at ReadFromMergeTree.cpp:4765 (two text indexes).

Root cause: buildPartitionReadingPipeline builds a per-partition snapshot sub-plan, calls plan.optimize() explicitly, then calls plan.buildQueryPipeline() with the default do_optimize=true, which optimizes the same plan a second time. The direct-read-from-text-index optimization is not idempotent: each pass appends a __text_index_* virtual column to the ReadFromMergeTree step, so the second pass corrupts the plan.

Fix: pass do_optimize=false to buildQueryPipeline (the plan is already optimized), matching the canonical pattern in InterpreterSelectQueryAnalyzer and JoinStepLogical. The optimization still runs once and is preserved.

The per-partition snapshot sub-plan built by MergeTreeCommitOrderSequentialSource
was optimized twice: buildPartitionReadingPipeline calls plan.optimize() explicitly
and then plan.buildQueryPipeline() with the default do_optimize=true, which optimizes
again. The direct-read-from-text-index optimization is not idempotent: every pass
appends a __text_index_* virtual column to the ReadFromMergeTree step. The second pass
therefore aborted with a LOGICAL_ERROR, either "Column ... already added for reading"
(two text indexes) or "Block structure mismatch ... MergeTreeCommitOrderSequentialSource
stream ..." (one text index).

Pass do_optimize=false to buildQueryPipeline since the plan is already optimized, matching
the canonical pattern in InterpreterSelectQueryAnalyzer and JoinStepLogical. The direct-read
optimization still runs once and is preserved.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT id FROM (SELECT id FROM t STREAM PREWHERE ('prod') IN (map[materialize('env')]) LIMIT 3) ORDER BY id on a table with a text index, enable_streaming_queries=1, allow_experimental_full_text_index=1, query_plan_direct_read_from_text_index=1, query_plan_merge_filters=1. Aborts every time on unfixed build.
b Root cause explained? The per-partition snapshot sub-plan is optimized twice: buildPartitionReadingPipeline calls plan.optimize() (:158) then plan.buildQueryPipeline() with the default do_optimize=true (:161), which optimizes again. createReadTasksForTextIndex appends a __text_index_* virtual column to the read on every pass but only clears index_read_tasks, not all_column_names, so the second pass throws (already added for reading, or a header mismatch with one index).
c Fix matches root cause? Yes. Removes the erroneous second optimization by passing do_optimize=false (the plan is already optimized). Targets the mechanism, not the symptom. (An earlier plan to disable the text-index optimization for this sub-plan was a band-aid and was dropped.)
d Test intent preserved / new tests added? New stateless test 04500_streaming_text_index_direct_read.sql. It pins the two settings the bug needs and includes a plan-level oracle asserting direct read from the text index is active, so it cannot silently stop covering the fix.
e Both directions demonstrated? Yes. Unfixed build: aborts (already added for reading, server abort exit 134). Fixed build: returns 0,1,2, server alive. 50/50 randomized runs pass on the fixed build.
f Fix is general across code paths? Yes. buildPartitionReadingPipeline is the only streaming sub-plan builder with this double-optimize (grep of Streaming/). The one sibling that also does optimize()+default-buildQueryPipeline (DirectJoinMergeTreeEntity) was tested over a text-indexed table and does not reproduce (its lookup filter is a key-equality filter, not a text-search predicate above the read).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Reproduced with one text index (Block structure mismatch variant) and two (already added variant); both fixed. The fix removes a duplicate pass, so it is input-agnostic. Verified across randomized prewhere/skip-index settings.
h Backward compatible? Yes. No setting/format/protocol change. The direct-read optimization still runs once and is preserved. SettingsChangesHistory.cpp not touched.
i Invariants and contracts preserved? Yes. do_optimize=false is the documented contract for an already-optimized plan (used by InterpreterSelectQueryAnalyzer and JoinStepLogical). The sub-plan the source built and optimized once is handed to pipeline construction unchanged, keeping the frozen converting step and the read header consistent.

Session id: cron:clickhouse-author-slot-3:20260723-001054

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds — 1 full pass + 1 stateful delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ Regression test asserts only rows 0,1,2, which are also returned with the text-index optimization disabled — it does not prove direct read is active AGREE — fixed Added a plan-level oracle: SELECT count()>0 FROM (EXPLAIN actions=1 SELECT count() FROM t WHERE <same predicate>) WHERE position(explain,'__text_index_')>0. Verified it prints 1 iff query_plan_direct_read_from_text_index=1 (0 otherwise).
2 ⚠️ Test does not pin query_plan_merge_filters (randomized by CI); with it off the faulty rewrite is never reached and the test passes even unfixed AGREE — fixed Confirmed empirically: query_plan_merge_filters=1 → direct read fires on the streaming sub-plan (Added count=1); =0 → does not (count=0). Pinned SET query_plan_merge_filters = 1. Re-verified both directions + 50/50.
3 ⚠️ Oracle uses a non-streaming query, so it still does not prove the runtime STREAM sub-plan used direct read; suggest a ProfileEvents assertion DISAGREE The crash on the unfixed build fires only inside the streaming snapshot sub-plan, so the test failing there already proves the sub-plan used direct read. Verified the STREAM query itself fires direct read on its own sub-plan under the pins (Added count=1). The proposed ProfileEvents/query_log remedy is timing-flaky and unavailable in a stateless test; EXPLAIN PIPELINE does not expand the runtime sub-plan. Current oracle is a strict net improvement and is retained.
4 💡 Opening comment duplicates the PR's root-cause narrative and both exception variants AGREE — fixed Trimmed the prologue to one sentence pointing to the fix commit for the mechanism.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-author-slot-3:20260723-001054

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @ahmadov — could you review this? A STREAM read over a text-indexed table hit a LOGICAL_ERROR because buildPartitionReadingPipeline optimizes the snapshot sub-plan twice (plan.optimize() then buildQueryPipeline() with the default do_optimize=true), and the direct-read-from-text-index optimization is not idempotent. Fix passes do_optimize=false.

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

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a968472]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_msan, 7/8) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb
New settings are not reflected in settings changes history (see new_settings.txt) FAIL cidb

AI Review

Summary

This PR fixes the streaming text-index exception by stopping MergeTreeCommitOrderSequentialSource from optimizing the same per-partition QueryPlan twice: it now calls plan.optimize() once and builds the pipeline with do_optimize=false, which matches the existing QueryPlan contract. I did not find a correctness issue in that C++ change itself, but the regression coverage still does not prove that the streaming plan continues to exercise the text-index direct-read rewrite, so the PR's "fix the exception without disabling the optimization" contract is still under-evidenced.

Tests
  • ⚠️ [tests/queries/0_stateless/04500_streaming_text_index_direct_read.sql:23] [dismissed by author -- https://github.com/Fix logical error in STREAM read over a text-indexed table #111504#discussion_r3636408615] The test now asserts only that the STREAM query returns 0,1,2. Those rows are identical when the planner silently falls back to row-scan evaluation, so a later refactor that stops injecting the __text_index_* direct-read column into the streaming snapshot would still pass this test while no longer covering the exception path this PR is fixing. Please add a second assertion on the same streaming query that proves the direct-read rewrite is still active, for example a STREAM EXPLAIN that matches the synthetic __text_index_* column or a stable query_log / profile-event check.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 23, 2026
/// The plan is already optimized above; do not optimize again. Some optimizations are not
/// idempotent (e.g. direct read from a text index appends virtual columns to the read step),
/// so a second pass would corrupt the plan and produce a header mismatch.
auto builder = plan.buildQueryPipeline(opt_settings, BuildQueryPipelineSettings(context), /*do_optimize=*/false);

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 what about making text index direct read optimization idempotent? Would it have a small blast radius?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good question, but making it fully idempotent is the larger blast radius here, and it guards the symptom rather than the cause.

The DAG replacer is already partially idempotent: TextIndexDAGReplacer::replace pre-populates the virtual-column map from __text_index_* inputs already present in the DAG (added for #101913). The crash isn't there. It is the step-level accumulation in ReadFromMergeTree::createReadTasksForTextIndex (throws at ReadFromMergeTree.cpp:4765): it pushes the virtual column onto all_column_names, extends new_metadata->virtuals, and rebuilds storage_snapshot / output_header / required_source_columns on every call. Making that re-entrant (skip already-present columns, don't double-rebuild the header, and handle the removed_columns erase at :4732, which is a find+erase that lands on end() on the second pass) is a change to ReadFromMergeTree, a core class used by every MergeTree read, not just streaming. That is a bigger, subtler surface than the current one-liner.

The deeper point: QueryPlan::optimize() is not idempotent by design (QueryPlan.cpp:761, no "already optimized" guard) - it re-runs the whole pass pipeline. The text-index optimization is just the first pass that throws loudly. A fully idempotent direct-read would still leave the plan exposed to any other non-idempotent pass, so it fixes one symptom of "the snapshot sub-plan is optimized twice", not the cause.

do_optimize=false removes the erroneous second optimize: 1 line, streaming-local, and it is the existing contract for an already-optimized plan (InterpreterSelectQueryAnalyzer.cpp:416, executeQuery.cpp:1953). The optimization still runs once and is preserved.

If you would prefer full idempotency of the text-index pass as a separate hardening, I am happy to do it in its own PR, but for this bug the one-liner is both the smaller change and the root-cause fix. Your call as the component owner.

Comment on lines +161 to +163
/// The plan is already optimized above; do not optimize again. Some optimizations are not
/// idempotent (e.g. direct read from a text index appends virtual columns to the read step),
/// so a second pass would corrupt the plan and produce a header mismatch.

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.

Suggested change
/// The plan is already optimized above; do not optimize again. Some optimizations are not
/// idempotent (e.g. direct read from a text index appends virtual columns to the read step),
/// so a second pass would corrupt the plan and produce a header mismatch.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in bd4dd3d: removed the comment, kept do_optimize=false. Rationale moved to the commit message.

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.

The test is super complex; make it simpler, remove comments.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in bd4dd3d. Dropped all comments and the misleading non-streaming coverage EXPLAIN, collapsed the INSERT to a single map key. The test is now just: create the two-index table, insert, run the STREAM ... PREWHERE query, assert 0,1,2.

Comment on lines +1 to +4
1
0
1
2

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.

debug the problem here in the tests, it is flaky right now.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Root cause found and fixed in bd4dd3d. The test pinned query_plan_direct_read_from_text_index and query_plan_merge_filters but not query_plan_text_index_add_hint (default true, randomized by CI). CI hit --query_plan_text_index_add_hint False, and with it off two things happened: the old non-streaming coverage EXPLAIN stopped exposing a __text_index_ column (the observed -1/+0 on reference line 1), and the STREAM query no longer crashed on the unpatched build (it lost its coverage). Now add_hint=1 is pinned too.

Verified the exact setting requirement with a matrix on the unpatched build: the abort reproduces only with all three of direct_read, add_hint, merge_filters set to 1; with any one off the query takes the row-scan path and returns 0,1,2 cleanly. So the three pins are minimal, and the STREAM query is a genuine fails-without-fix oracle (unpatched: LOGICAL_ERROR: Column __text_index_..._equals_... already added for reading; patched: 0,1,2). 50/50 runs pass with randomization on the patched build.

On liveness: because the crash only occurs when direct read actually fires (the matrix above), the crash-on-unpatched-build is itself the proof that direct read executes on the STREAM path; if it stopped firing the unpatched build would stop crashing. I kept the test to the row assertion rather than adding a TextIndexUseHint ProfileEvent check, since that event counts granules subject to text_index_hint_max_selectivity on a 20-row part and could be discarded, reintroducing flakiness. Happy to add a plan/ProfileEvent assertion if you'd prefer it over the row oracle.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

A second, distinct flakiness surfaced after the previous fix: the CI "old analyzer" combos ran the test with enable_analyzer=0, where the STREAM query throws "Streaming queries are not supported with the old analyzer" (Code 48, NOT_IMPLEMENTED) before it can exercise direct read, so the whole test errored (return code 48).

Fixed in a968472 by tagging the test no-old-analyzer, matching the existing STREAM sibling 04281_sparsity_stream_skips_trivial_count. Verified through the test runner: new analyzer + tag -> runs and passes; old analyzer + tag -> skipped; old analyzer without the tag -> the Code 48 error, i.e. the tag is load-bearing. The double-optimize crash coverage on the new-analyzer path is unchanged.

…op code comment

The regression test 04500_streaming_text_index_direct_read was flaky in CI: it
pinned query_plan_direct_read_from_text_index and query_plan_merge_filters but
not query_plan_text_index_add_hint (default true, randomized by CI). With
add_hint=False the streaming double-optimize does not crash on the unpatched
build and the non-streaming coverage-guard EXPLAIN no longer exposes a
__text_index_ column, so the reference mismatched on line 1 (observed -1/+0 in
amd_debug parallel and arm_asan_ubsan targeted).

Pin all three settings the crash requires (verified via a setting matrix: with
any one off the query takes the row-scan path and does not reproduce). Drop the
misleading non-streaming EXPLAIN coverage guard; the STREAM query is the oracle
and aborts with 'already added for reading' on the unpatched build. Simplify the
table population and remove comments per review.

Also remove the explanatory comment above the buildQueryPipeline(do_optimize=false)
call in MergeTreeCommitOrderSequentialSource.cpp per review; the rationale lives
in the commit history.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review of the rework (click to expand)

Commit bd4dd3d was run through an independent second-model review before push. Two findings, both adjudicated DISAGREE with evidence:

# Severity Finding Verdict Reason
1 major Test does not prove direct text-index read executes (rows identical under row-scan) DISAGREE This is a crash-regression test. A setting matrix on the unpatched build shows the abort reproduces only when all three of direct_read/add_hint/merge_filters are on; with any off it returns 0,1,2. So the crash-on-unpatched-build is itself proof that direct read fired. A TextIndexUseHint ProfileEvent guard was rejected as it counts granules subject to text_index_hint_max_selectivity on a 20-row part and could be discarded, reintroducing flakiness. Trade-off surfaced to the reviewer in-thread.
2 nit Missing PR-body draft DISAGREE Rework push to an already-open PR; body and changelog category already validated.

STREAM reads are analyzer-only: the old analyzer raises
"Streaming queries are not supported with the old analyzer" (NOT_IMPLEMENTED,
Code 48). The CI "old analyzer" combos run the test with enable_analyzer=0,
where the STREAM query throws before it can exercise the direct-read path, so
the whole test errors (return code 48).

Add the no-old-analyzer tag so those jobs skip the test cleanly, matching the
existing STREAM sibling 04281_sparsity_stream_skips_trivial_count. The test
still runs and passes under the analyzer, and still reproduces the double
optimize LOGICAL_ERROR without the fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Michicosun Michicosun self-assigned this Jul 23, 2026
@Michicosun

Copy link
Copy Markdown
Member

@groeneai

Streaming queries are not supported with the old analyzer

fix this, one line

@groeneai

Copy link
Copy Markdown
Collaborator Author

Already fixed in a968472 (current head), one line: added no-old-analyzer to the test's Tags line, matching the STREAM sibling 04281_sparsity_stream_skips_trivial_count. STREAM reads are analyzer-only, so the old-analyzer combos now skip the test cleanly; it still runs and passes under the analyzer, and still reproduces the double-optimize logical error without the fix. No 04500 failures on the current head.

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 47.50% 86.20% +38.70%
Functions 57.50% 92.00% +34.50%
Branches 35.90% 78.30% +42.40%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a968472

Every failure below has an owner (a fixing PR). Only CH Inc sync would be exempt; none here.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky, 656 PRs / 138 master in 30d, not this PR's area #111029 (external, open)
Upgrade check (amd_release) / New+Changed settings not in settings changes history trunk regression: join_runtime_filter_min_probe_rows (merged #104860) landed in the 26.7 history section, so it fails on every PR until relocated to 26.8 #111671 (ours, open)

The PR-caused 04500_streaming_text_index_direct_read failures are resolved on this head (no-old-analyzer tag; 0 hits at a968472).

Session id: cron:our-pr-ci-monitor:20260723-223000

@Michicosun

Copy link
Copy Markdown
Member

will be fixed as a part of #111821

@Michicosun Michicosun closed this Jul 24, 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-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants