Repository navigation
Fix lazy materialization OOB and a Merge LOGICAL_ERROR from unused text index virtual columns - #111467
Conversation
The direct-read-from-text-index optimization records a __text_index_ virtual column for a predicate node, then runs removeUnusedActions() on the filter DAG. When the final rewrite keeps a different index's virtual column (or the original expression), the first virtual's input becomes unreferenced, but result.added_columns was not re-filtered, so createReadTasksForTextIndex still appended the orphaned virtual column to the ReadFromMergeTree output header. optimizeLazyMaterialization2 builds its required_columns mask positionally over the input headers of the steps above the reading step, which never contain that read-only virtual column. The mask ends up smaller than the reading step output header, so the pass indexes a vector<bool> past its end (release: out-of-bounds read; debug: cols.size() == required_columns.size() assertion). Drop from result.added_columns any virtual column whose input did not survive removeUnusedActions, reusing the surviving-inputs set already computed for removed_columns. Closes ClickHouse#111422. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-3:20260722-165000 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-3:20260722-165000 |
|
cc @george-larionov @antaljanosbenjamin — could you review this? The text-index direct-read rewrite left an unused |
|
Workflow [PR], commit [7b8214e] Summary: ✅
AI ReviewSummaryThis PR fixes Final Verdict✅ No findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · Uncovered code |
The regression query for ClickHouse#111422 reaches optimizeLazyMaterialization2 and the text-index direct-read path only via InterpreterSelectQueryAnalyzer (the new analyzer). Under the old analyzer the Map subscript in PREWHERE/WHERE is resolved by TreeRewriter::collectUsedColumns and throws UNKNOWN_IDENTIFIER (Missing columns: 'map', available columns: '_dummy') before planning, so the test FAILed in the old-analyzer coverage build. The lazy-materialization path this test guards is analyzer-only, so skip it under the deprecated analyzer. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger - 60626e6One failure, PR-caused (our own new test), fixed in this PR.
Verified locally on the fix binary (buildId Session id: cron:clickhouse-maint-slot-12:20260723-054400 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 11/11 (100.00%) · Uncovered code |
CI finish ledger - fb0726fThe PR-caused failure from the prior head (
Session id: cron:our-pr-ci-monitor:20260723-113000 |
The reconciliation in TextIndexDAGReplacer::replace already on this branch also fixes a LOGICAL_ERROR server abort that the lazy materialization test cannot reach, so cover it here. With text indexes on both mapKeys(map) and mapValues(map), the mapKeys virtual column wins the rewritten predicate and the mapValues one is left registered but unreferenced. Under SELECT count() nothing else is read, so that dead virtual column becomes the indexed Merge child's only output column while a non-indexed sibling's header stays empty. Pipe::getCommonHeader then picks the first non-empty header and unitePipes asserts the empty sibling against it. Reproduced on master (f9801d5) as Block structure mismatch in Pipe::unitePipes stream: different number of columns On this branch, whose merge-base predates the already_has_direct_read re-entry gate, the same over-registration instead trips the duplicate guard in ReadFromMergeTree::createReadTasksForTextIndex ("Column ... already added for reading"). Removing only the reconciliation loop makes the test abort here, so it is armed on this base too. The two SET statements are load-bearing: the runner randomizes query_plan_direct_read_from_text_index and query_plan_text_index_add_hint off with p=0.05 each, and either turns the EXPLAIN assertion vacuous. They are pinned per setting rather than with a blanket no-random-settings tag.
The setting was pinned after the runtime witnesses instead of before them. The test runner injects randomized settings at client level, so an injected query_plan_text_index_add_hint=0 governed the witness queries and only the later EXPLAIN assertion overrode it. Both index candidates for 'lit' IN map[...] take the hint-or-none path (MergeTreeIndexConditionText.cpp, traverseMapElementValueNode branch and mapContainsKey), and with mode None the optimizer skips virtual-column creation entirely, so no header mismatch is constructed and the witness queries assert nothing. Measured on a binary with the reconciliation removed: before this change the witness queries returned correct values under an injected add_hint=0; after it they abort as intended. 50/50 randomized runs pass.
…ug111422
The two existing queries assert results only. Both return what a plain scan
returns, so a refactor that stops routing their shape into
optimizeLazyMaterialization2 would leave the test green while no longer
exercising the code path the fix touches.
The guarded queries cannot carry a plan-shape assertion themselves: they select
only `id`, which is the sort key, so ReadFromMergeTree::
keepOnlyRequiredColumnsAndCreateLazyReadStep finds nothing to defer and returns
{} -- no LazilyReadFromMergeTree step is ever created for that shape. The new
group therefore uses its own table with a deferrable non-key column, and asserts
both that the lazy step is built and that a text index virtual column is read.
Verified deterministically rather than by repetition: with the pins stripped and
each setting injected at client level, query_plan_optimize_lazy_materialization=0
and query_plan_max_limit_for_lazy_materialization=1 each flip the first asserted
column to 0, and query_plan_direct_read_from_text_index=0 and
query_plan_text_index_add_hint=0 each flip the second, so neither column is
vacuous. On a binary without the fix the new group aborts with the same
'cols.size() == required_columns.size()' logical error the existing queries
witness.
The existing table, queries, pins and reference line are unchanged.
Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) plus an independent cold
The pushed change is test-only: Session id: cron:clickhouse-review-slot-10:20260808-222000 |
|
This push adds a regression test only, no source change. The Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260808-203600 |
|
cc @ahmadov, could you review this? The text index direct-read rewrite records a virtual column per rewritten predicate and then prunes unused actions, but only |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units9 translation units recompiled, 24 s compile time in total, 9 of them have a recent master baseline. |
CI finish ledger - 2e4ba08Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task Fresh ledger for the current head (regression-test-only push, 2026-08-08T22:11:37Z). The most recent This run is fully green: 0 failures. 175 check-runs, 0 queued/in_progress, That also settles the Nothing is owed on this head. Session id: cron:our-pr-ci-monitor:20260810-050000 |
Plan optimization runs from InterpreterExplainQuery as well as from the SELECT interpreter, so optimizeLazyMaterialization2 is reachable without executing the query. The AST fuzzer found this on master as STID 2508-458e: an EXPLAIN ANALYZE over the two-text-index Map shape of 04039_text_index_map_values_subcolumn aborted on 'cols.size() == required_columns.size()' at optimizeLazyMaterialization.cpp:620, via InterpreterExplainQuery.cpp:1202. The EXPLAIN oracle already in this test cannot cover that path: on a build without the fix the two SELECTs above it abort first, so the statement is never reached. The new arm is placed to be the reddening statement itself and asserts the prune directly, by requiring the virtual of the discarded index to be absent from the plan. Verified both directions. Reverting only the added_columns prune hunk: the arm aborts (exit 134) and the whole test aborts; with the prune the test matches its reference and passes through clickhouse-test. The verbatim fuzzed EXPLAIN ANALYZE was additionally confirmed on master (aborts) and on master with the prune applied (passes); that keyword postdates this branch's base, which is why the in-tree arm uses the plain EXPLAIN form. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Following up on the commitment I made in #107974 (comment): I said I would run the fuzzer's exact query against a pre-fix and a fixed binary and report the outcome here either way. Result: the EXPLAIN path is the same defect, and this PR fixes it. The fuzzer query (STID 2508-458e, from EXPLAIN ANALYZE compact = 0 SELECT id FROM tab
PREWHERE ('frontendfrontendfrontendfrontend') IN (map['service'])
WHERE (map['service']) IN toNullable(('frontend'))
ORDER BY id DESC NULLS LAST LIMIT 934Run against
So EXPLAIN is a second way to reach the plan the text-index rewrite already corrupted, not a second defect: the desync is created in the optimizer pass, before the interpreter choice matters. I found no evidence of a non-text-index desync path.
One caveat I will not paper over: the older 2508-50dc bucket (#108369, #95659) has no retained artifact, so whether it is this same shape stays an inference rather than a measurement. |
CI finish ledger - 4f3287fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task Fresh ledger for the current head (pushed 2026-08-15T13:35:34Z, adding the EXPLAIN arm). The most This run is fully green: 0 failures. 181 check-runs, 0 queued/in_progress, Nothing is owed on this head. Session id: cron:our-pr-ci-monitor:20260815-210000 |
|
@ahmadov Like to take a look at this one? |
|
@groeneai can you address the comments? |
Collect the candidate virtual columns while walking the DAG nodes and populate result.added_columns once, after removeUnusedActions has settled which inputs survive, instead of filling the map first and pruning it in place afterwards. Behaviour is unchanged: the same predicate (the virtual's input is in replaced_columns_set) decides membership, and an index whose only virtual is dropped now simply never gets a map entry rather than getting one and having it erased. Verified by rebuilding the previous form as a control and running the text-index and lazy-materialization suites against both binaries: identical 125 OK / 39 skipped and the same 10 bare-server environment failures (system.query_log, test.hits, missing test clusters), none touched by this diff. Test changes: drop the explicit GRANULARITY from the skip indexes, replace narrative SQL comments with SELECT markers, and reformat the CREATE TABLE statements one column per line. Removing GRANULARITY does not weaken the repro: the pre-fix binary still aborts on the reduced test with 'cols.size() == required_columns.size()' at optimizeLazyMaterialization.cpp:544 in optimizeLazyMaterialization2, and 04563 still aborts with 'Column __text_index_idx_map_values_equals_... already added for reading'. Both pass with the fix. Co-Authored-By: Claude Fable 5 <[email protected]>
|
All addressed in 7b8214e.
Same assertion the issue reports, so the reduced test still reddens pre-fix. It also still needs
Behaviour of the restructure, since it rewrites the hunk the fix consists of: I rebuilt the previous form as a control and ran |
CI finish ledger - 7b8214eCI is fully finished on this head and no check failed, so the table below has no rows
Measured on the deduplicated check-run set (newest attempt per name): 171 unique names, The matrix that ran is the full one, not a reduced selection: 26 builds, all four CIDB agrees independently for this head: 267078 Session id: cron:our-pr-ci-monitor:20260820-173000 |
|
I measured the backport scope on prebuilt release binaries before asking for a label. Affected (reproduces, fix absent): 26.7 ( Not affected: 26.8 ( Controls behaved: current master ( So the minimal label is The port is clean on both affected branches: Could a maintainer apply |
…cript in PREWHERE An explicit PREWHERE `mapContains(m, k) AND m[k]` over a text index on `mapKeys(m)` left an unused text index virtual column in the read header, and lazy materialization read past its end. Fixed by ClickHouse#111467, which has no test for this shape. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2250 Labels added:
These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix an out-of-bounds read (release) / logical error (debug) in the lazy materialization optimization, and a logical error in
Pipe::unitePipesforMergetables, when the direct-read-from-text-index optimization leaves an unused index virtual column in the read header of aMergeTreetable with multipletextindexes.Description
Closes: #111422
TextIndexDAGReplacer::replacerewrites text-search predicates into__text_index_*virtual columns, recording one per rewritten node, then runsremoveUnusedActions(). When the rewrite keeps a different index's virtual column (or the original expression), the first virtual's input becomes unreferenced, butresult.added_columnswas not re-filtered, socreateReadTasksForTextIndexstill appended that orphaned column to theReadFromMergeTreeoutput header.removed_columnswas already reconciled against the surviving inputs;added_columnswas not, and that asymmetry is the bug.The fix collects the rewritten virtuals as candidates while walking the DAG and only populates
added_columnsafterremoveUnusedActions(), keeping a candidate when its input is in the surviving-inputs set already computed forremoved_columns. The reading step's header then matches what the plan consumes, and a redundant index read goes away.One orphaned column causes two user-visible failures, both fixed:
Lazy materialization out-of-bounds read (the reported issue).
optimizeLazyMaterialization2builds itsrequired_columnsmask positionally from the input headers above the reading step, which never contain a read-only virtual column. The mask ends up shorter than that step's header and the pass indexes astd::vector<bool>past its end: out-of-bounds read in release,cols.size() == required_columns.size()assertion in debug.Mergetable logical error. Withtextindexes on bothmapKeys(map)andmapValues(map), themapKeysvirtual wins the predicate and themapValuesone is left registered but unreferenced. UnderSELECT count()nothing else is read, so the dead virtual becomes the indexed child's only output column while a non-indexed sibling's header stays empty.Pipe::getCommonHeaderpicks the first non-empty header andunitePipesasserts the empty sibling against it:Block structure mismatch in Pipe::unitePipes stream, a server abort in debug and sanitizer builds.02346_text_index_bug111422covers the first shape. The new04563_text_index_merge_heterogeneous_childrencovers the second, which the first cannot reach (nomerge(), no barecount()). It pins the two runner-randomized settings it depends on per setting, not with a blanket tag.Validation of the new test
Debug build of this branch, memory-capped server, per-slot ports.
f9801d5649(no fix)c29b56ab…Block structure mismatch in Pipe::unitePipes stream: different number of columns(Block.cpp:308<-Pipe.cpp:316<-QueryPipelineBuilder.cpp:263)fd96fd28…Column __text_index_idx_map_values_equals_… already added for reading(ReadFromMergeTree.cpp:4765); via the test runner:ClickHouse server dieda0a422da…The pre-fix signature differs between the two bases because this branch's merge-base predates the
already_has_direct_readre-entry gate (optimizeDirectReadFromTextIndex.cpp,6253632d8da4): without that gate the pass visits the step twice and the same over-registration trips the duplicate guard before a pipe is united. Same defect, two assertions.Both pinned settings were verified load-bearing and effective: with the pins removed, a client injecting
query_plan_direct_read_from_text_index=0orquery_plan_text_index_add_hint=0turns theEXPLAINassertion vacuous (1 0->0 0); with the pins present the test matches the reference under either injection and under both together.Full
text_indexsuite on this branch, base vs with the new test: 157 -> 158 tests, 7 -> 6 failures, zero new failures. All shared failures are environmental on a bare slot server (missing statefultest.hitsdataset, nolocalhost:9000, and four debug-build 600s timeouts).Workflow [PR]
Sync PR [sync-upstream/pr/111467]