Skip to content

Fix lazy materialization OOB and a Merge LOGICAL_ERROR from unused text index virtual columns - #111467

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111422-lazymat-text-index-orphan-column
Aug 21, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111422-lazymat-text-index-orphan-column

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

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 an out-of-bounds read (release) / logical error (debug) in the lazy materialization optimization, and a logical error in Pipe::unitePipes for Merge tables, when the direct-read-from-text-index optimization leaves an unused index virtual column in the read header of a MergeTree table with multiple text indexes.

Description

Closes: #111422

TextIndexDAGReplacer::replace rewrites text-search predicates into __text_index_* virtual columns, recording one per rewritten node, then runs removeUnusedActions(). When the 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 that orphaned column to the ReadFromMergeTree output header. removed_columns was already reconciled against the surviving inputs; added_columns was not, and that asymmetry is the bug.

The fix collects the rewritten virtuals as candidates while walking the DAG and only populates added_columns after removeUnusedActions(), keeping a candidate when its input is in the surviving-inputs set already computed for removed_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:

  1. Lazy materialization out-of-bounds read (the reported issue). optimizeLazyMaterialization2 builds its required_columns mask 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 a std::vector<bool> past its end: out-of-bounds read in release, cols.size() == required_columns.size() assertion in debug.

  2. Merge table logical error. With text indexes on both mapKeys(map) and mapValues(map), the mapKeys virtual wins the predicate and the mapValues one is left registered but unreferenced. Under SELECT 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::getCommonHeader picks the first non-empty header and unitePipes asserts the empty sibling against it: Block structure mismatch in Pipe::unitePipes stream, a server abort in debug and sanitizer builds.

02346_text_index_bug111422 covers the first shape. The new 04563_text_index_merge_heterogeneous_children covers the second, which the first cannot reach (no merge(), no bare count()). 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.

arm build id result
master f9801d5649 (no fix) c29b56ab… aborts: Block structure mismatch in Pipe::unitePipes stream: different number of columns (Block.cpp:308 <- Pipe.cpp:316 <- QueryPipelineBuilder.cpp:263)
this branch, reconciliation loop removed fd96fd28… aborts: Column __text_index_idx_map_values_equals_… already added for reading (ReadFromMergeTree.cpp:4765); via the test runner: ClickHouse server died
this branch, unmodified a0a422da… passes byte-for-byte, and 50/50 randomized runs

The pre-fix signature differs between the two bases because this branch's merge-base predates the already_has_direct_read re-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=0 or query_plan_text_index_add_hint=0 turns the EXPLAIN assertion vacuous (1 0 -> 0 0); with the pins present the test matches the reference under either injection and under both together.

Full text_index suite 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 stateful test.hits dataset, no localhost:9000, and four debug-build 600s timeouts).


Workflow [PR]
Sync PR [sync-upstream/pr/111467]

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's exact query aborts every time on pristine master (SIGABRT at optimizeLazyMaterialization.cpp:544); no randomization needed.
b Root cause explained? Yes. TextIndexDAGReplacer::replace records a __text_index_* virtual for a predicate node, then runs removeUnusedActions(). When the final rewrite keeps a different index's virtual (or the original expression), the first virtual's input becomes unreferenced, but result.added_columns is not re-filtered, so createReadTasksForTextIndex appends the orphan to the ReadFromMergeTree output header. optimizeLazyMaterialization2 builds required_columns positionally over the upper steps' input headers (which lack that read-only column), so the mask is smaller than the read header and it indexes a vector<bool> out of bounds. Confirmed via EXPLAIN: PREWHERE uses the idx_mk virtual; the idx_mv virtual in the read header is consumed by nothing.
c Fix matches root cause? Yes. Prune result.added_columns to virtuals whose input survived removeUnusedActions (the same surviving-inputs set already used for removed_columns). The orphan never enters the read header. Not a downstream guard.
d Test intent preserved / new test? Yes. New stateless SQL test 02346_text_index_bug111422 asserts BOTH the crash query (returns empty) and a matching-row variant (returns the correct id). No existing test weakened.
e Demonstrated both directions? Yes. Pristine build: test CRASHES the server. Fixed build: test PASSES.
f Fix general, not a narrow patch? Yes. replace() is the single entry point for text-index virtual injection (both PREWHERE and WHERE paths funnel through it and the same added_columns -> createReadTasksForTextIndex); no sibling function has the leak.
g Generalizes across inputs? Yes. The prune keys on surviving DAG input names, type-agnostic. Verified: single index (virtual survives, direct read preserved), two indexes both used (both survive), two indexes with one orphan (only the orphan pruned).
h Backward compatible? Yes. Pure internal query-plan bookkeeping. No setting default, on-disk/wire/replication/metadata format, or new validation changed.
i Invariants preserved? Yes. Restores the invariant optimizeLazyMaterialization2 relies on (read-step output header == columns the plan consumes). replaced_columns_set is the post-prune surviving-input set already used one block above for removed_columns. Empty index entries are erased so no empty index read task is created.

Session id: cron:clickhouse-author-slot-3:20260722-165000

@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 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ Regression test does not pin the randomized settings needed to exercise the failing path; the runner randomizes lazy-mat, its max LIMIT (choices include 1/10/100 < 681), direct-read and hint, so a broken build could pass in ~half of randomized runs AGREE — fixed Pinned query_plan_optimize_lazy_materialization=1, query_plan_max_limit_for_lazy_materialization=100000, query_plan_direct_read_from_text_index=1, query_plan_text_index_add_hint=1 in the test. Re-verified: pinned test still CRASHES pristine, PASSES fix, 50/50 pass.
2 💡 The new code comment restates the incident narrative instead of the local invariant AGREE — fixed Condensed to the local contract: added_columns keeps only virtuals whose input survived removeUnusedActions.

Severity: ❌ blocker / ⚠️ major / 💡 nit. Both findings AGREEd and fixed; the source-touching change was rebuilt (Build-ID changed) and re-verified in both directions.

Session id: cron:clickhouse-author-slot-3:20260722-165000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @george-larionov @antaljanosbenjamin — could you review this? The text-index direct-read rewrite left an unused __text_index_* virtual column in the ReadFromMergeTree output header (it recorded the virtual before removeUnusedActions pruned its input), which then desynced positional column bookkeeping in optimizeLazyMaterialization2 and caused an OOB vector<bool> read (release) / assertion (debug). The fix prunes added_columns to only virtuals whose input survived.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b8214e]

Summary: ✅


AI Review

Summary

This PR fixes TextIndexDAGReplacer::replace so text-index virtual columns are added to ReadFromMergeTree only if they survive removeUnusedActions, which removes the header skew behind both the lazy-materialization assertion / out-of-bounds read and the heterogeneous Merge-child Pipe::unitePipes failure. I did not find any remaining correctness, compatibility, or coverage issue in the current head.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 87.00% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · 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 22, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 60626e6

One failure, PR-caused (our own new test), fixed in this PR.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 3/3) / 02346_text_index_bug111422 PR-caused: the regression query reaches optimizeLazyMaterialization2 + text-index direct read only via the new analyzer; under the old analyzer the Map subscript in PREWHERE/WHERE resolves in TreeRewriter::collectUsedColumns and throws UNKNOWN_IDENTIFIER before planning PR-caused -> fixed in this PR @ fb0726f (tag no-old-analyzer)

Verified locally on the fix binary (buildId AE3A478E...): new analyzer [ OK ], old analyzer [ SKIPPED ] Reason: old-analyzer. The repro is unchanged; it is only skipped on the deprecated analyzer where the guarded path is unreachable.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111467&sha=60626e62f4ad&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%203%2F3%29

Session id: cron:clickhouse-maint-slot-12:20260723-054400

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.20% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fb0726f

The PR-caused failure from the prior head (02346_text_index_bug111422 in the old-analyzer coverage build) is fixed on this head (no-old-analyzer tag): the test is now green in every build (50/50 flaky-check on all sanitizers; old-analyzer variant correctly SKIPPED). The two remaining failures are pre-existing trunk issues, each owned by an open fixing PR.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (Replicated-DB concurrent-ALTER race, regressed 2026-07-10; 634 distinct PRs / 30d) #111029 (external, open)
Stress test (arm_release) / server abort: LOGICAL_ERROR "Part level Min-Max index was constructed from unexpected columns set" trunk (merge-time Min-Max index bug, unrelated to this PR's text-index DAG change) #111511 (ours, open)

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

groeneai and others added 3 commits August 8, 2026 17:48
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]>
@groeneai groeneai changed the title Fix lazy materialization OOB with text index unused virtual columns Fix lazy materialization OOB and a Merge LOGICAL_ERROR from unused text index virtual columns Aug 8, 2026
@groeneai

groeneai commented Aug 8, 2026

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

Pre-publication review by an independent model (engine: codex) plus an independent cold
review, over 3 rounds on this push: 4 findings, 2 fix rounds, 0 outstanding. The final
round returned 0 findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ 02346 asserted results only, so a refactor that stopped routing its shape into the lazy materialization pass would leave it green while no longer exercising the fixed code path AGREE, fixed Raised in two consecutive rounds. A plan-shape group was added on its own table, asserting both that LazilyReadFromMergeTree is built and that a __text_index_ virtual column is read. The guarded queries cannot carry that assertion themselves: they select only id, the sort key, so keepOnlyRequiredColumnsAndCreateLazyReadStep finds nothing to defer and returns {}. Both asserted columns were shown load-bearing by client-level injection with the body pins stripped: query_plan_optimize_lazy_materialization=0 and query_plan_max_limit_for_lazy_materialization=1 each flip the first, query_plan_direct_read_from_text_index=0 and query_plan_text_index_add_hint=0 each flip the second
2 ⚠️ query_plan_text_index_add_hint was pinned after the first witness query, so a run that randomized it off would exercise nothing while still passing AGREE, fixed The pin moved into the header block ahead of the first witness. Both map-subscript candidates take the hint-or-none path (traverseMapElementValueNode overrides getDirectReadMode, and mapContainsKey likewise), and on None the optimizer skips virtual-column creation entirely, so no mismatch is ever constructed. Confirmed by measurement: on a binary with the reconciliation removed and the hint injected off, the pre-move file reached all four witnesses and matched the reference; after the move it aborts at the first
3 💡 Use the full-URL Closes: form on its own visible line DISAGREE The premise does not hold: Closes #111422 is a valid closing keyword, and the body already carries the full-URL form in the template's own comment block plus a visible Closes #111422. as the first Description line
4 💡 A comment said "Both settings" ahead of a single SET; the description was 16 characters over the length budget AGREE, fixed Comment rewritten, description condensed, both before the final review round

The pushed change is test-only: git diff against this branch's merge-base shows the same
20 inserted source lines as the previous head, unchanged. Both new/changed tests were run
50 times under randomized settings (and one of them 200 times) with no failure, and the full
text_index suite shows no new failures.

Session id: cron:clickhouse-review-slot-10:20260808-222000

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

This push adds a regression test only, no source change. The added_columns reconciliation it exercises was already on this branch; the new test covers a second failure the existing one cannot reach.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One command, RC=134 on two independent pre-fix arms: pristine master f9801d5649 (Block structure mismatch in Pipe::unitePipes stream) and this branch with the reconciliation loop removed (Column __text_index_idx_map_values_equals_... already added for reading, ReadFromMergeTree.cpp:4765). Through the test runner the second arm reports ClickHouse server died. Not a failure rate.
b Root cause explained? Yes. TextIndexDAGReplacer::replace records a virtual column per rewritten text-search node, then runs removeUnusedActions(). removed_columns is reconciled against the surviving required inputs; added_columns was not. The orphan reaches createReadTasksForTextIndex, which registers it for reading and rewrites the step's output header.
c Fix matches root cause? Yes, and it is already on this branch: added_columns is narrowed by the same surviving-inputs set removed_columns uses, at the layer that produces the wrong information. No guard at the assertion site. Tolerating the mismatch in Pipe::unitePipes was considered and rejected: it would mask genuine header bugs everywhere.
d Test intent preserved / new tests added? Yes. Diff is two new files; no existing test is touched, weakened, or removed. The new test pairs the witness with four labelled control groups, and is armed on this base (removing only the reconciliation makes it abort).
e Both directions demonstrated? Yes. Fails without the reconciliation and passes byte-for-byte with it, shown on two arms and via two probe methods (clickhouse local and the test runner), then 50/50 randomized runs. The asserted value is ground truth: with query_plan_direct_read_from_text_index = 0 the witness query returns 2 for the matching literal and 0 for a non-matching one, so the test cannot pass by returning nothing.
f Fix is general across code paths? Yes. The single reconciliation covers the WHERE and PREWHERE paths and non-Merge reads. Three candidate carriers were measured and are closed: the all-virtuals-dropped state is unreachable across 26 probed shapes, the already_has_direct_read second visit is clean across 7 duplicate-predicate Merge shapes, and the removed_columns logic is untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The test sweeps count() / 1 / id / sum(id) select lists, matching and non-matching literals, single table vs Merge vs all-children-indexed. A 12-function sweep over hasToken/hasAnyTokens/hasAllTokens/mapContains/has(mapKeys)/has(mapValues)/equals gave identical answers on both arms, and a selectivity control confirms the filter is not blanket: map['env'] = 'prod' legitimately keeps both virtual columns.
h Backward compatible? (maintainer-approved exception only) Yes. Test-only diff: no setting default changed, no SettingsChangesHistory.cpp entry required, no format or serialization change.
i Invariants and contracts preserved? Yes. The test creates and drops only its own two tables inside currentDatabase(), with no SYSTEM statement, user/role/GRANT, named collection, file path, failpoint or ATTACH/DETACH. It is therefore parallel-safe with itself and carries no no-parallel tag, which the 50 concurrent runs demonstrate. The two settings it pins are randomized by the runner and were verified load-bearing: with the pins removed, injecting either setting off turns the EXPLAIN assertion vacuous (1 0 to 0 0); with the pins present the test matches the reference under either injection and under both. Pinned per setting rather than with a blanket no-random-settings tag.

Session id: cron:clickhouse-impl-slot-41:20260808-203600

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

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 removed_columns was reconciled against the surviving inputs, so an orphaned __text_index_* column still reached the read header: that desyncs positional bookkeeping in lazy materialization (out-of-bounds read in release), and over a Merge table with non-indexed children it makes the orphan a child pipe's only output column, which Pipe::unitePipes rejects. This push adds the second regression test and a plan-shape oracle; the source change is unchanged from the previous head.

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7b8214e40 with master dabcc4cde (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 704.37 MiB 701.33 MiB -3.04 MiB (-0.43%)

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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2e4ba08

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.

Fresh ledger for the current head (regression-test-only push, 2026-08-08T22:11:37Z). The most recent
previously posted ledger covered fb0726f630327703cf383af87b846f5495777334, from 2026-07-23, and is
superseded.

This run is fully green: 0 failures. 175 check-runs, 0 queued/in_progress, Config Workflow and
Finish Workflow both success, 158 success / 17 skipped / 0 failure, last completion
2026-08-09T03:36:13Z. The praktika report agrees (status: OK, 157 OK / 18 skipped, 147 executed
jobs, 0 job-level errors), and CIDB has no FAIL/ERROR row for this head.

That also settles the PR-caused line from the 2026-07-23 ledger: the
04257_text_index_lazy_profile_events failure fixed in fb0726f6 has not returned, and the second
regression test added on this head passes across the matrix.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 fatal.log, log_comment 04039_text_index_map_values_subcolumn.sql-test_2):

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 934

Run against 04039_text_index_map_values_subcolumn's table (two text indexes over one Map, queried through map['service']):

Binary Query form Result
master 8a02ec4f, no fix verbatim EXPLAIN ANALYZE aborts, optimizeLazyMaterialization.cpp:620 via InterpreterExplainQuery.cpp:1202
master 8a02ec4f, no fix plain EXPLAIN aborts, same :620, via InterpreterExplainQuery.cpp:1003
master + this PR's prune both forms pass
this PR's head, prune hunk reverted plain EXPLAIN aborts
this PR's head plain EXPLAIN passes

:620 is the line CIDB reported for that STID. EXPLAIN ANALYZE postdates this branch's base, which is why the two master arms carry the verbatim text.

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.

4f3287f1 adds an arm covering that entry path. The EXPLAIN oracle already here could not: on a build without the prune the two SELECTs above it abort first, so it is never reached. The new arm is positioned to be the reddening statement and asserts the prune directly, requiring the discarded index's virtual to be absent from the plan (0 in the second column). Reverting only the prune hunk makes that statement abort; with it the test matches its reference and passes through clickhouse-test.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4f3287f

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.

Fresh ledger for the current head (pushed 2026-08-15T13:35:34Z, adding the EXPLAIN arm). The most
recent previously posted ledger covered 2e4ba088ede7b69e4fc0a5cc6674690b92bcddbb and is superseded.

This run is fully green: 0 failures. 181 check-runs, 0 queued/in_progress, Config Workflow and
Finish Workflow both success, 160 success / 17 skipped / 0 failure, last completion
2026-08-15T20:22:46Z. The praktika report agrees (status: OK, 159 OK / 18 skipped, 0 job-level
FAIL or ERROR at any depth), and CIDB has no FAIL/ERROR row for this head across 162 checks and
338044 test rows (the only non-success job status is Integration tests (amd_asan_ubsan, targeted),
skipped).

Nothing is owed on this head.

Session id: cron:our-pr-ci-monitor:20260815-210000

@rschu1ze

Copy link
Copy Markdown
Member

@ahmadov Like to take a look at this one?

@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
@ahmadov

ahmadov commented Aug 20, 2026

Copy link
Copy Markdown
Member

@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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

All addressed in 7b8214e.

optimizeDirectReadFromTextIndex.cpp

  • Restructured as you suggested: candidates are collected into a std::vector<std::pair<String, VirtualColumnDescription>> at the node walk, and result.added_columns is populated once at the end, keeping a candidate only when its input is in replaced_columns_set. No in-place erase, no intermediate VirtualColumnsDescription. That also removed the alternative style suggestion on the same line, so I took this version rather than both.
  • Comment shortened to two lines.

02346_text_index_bug111422.sql: removed the two narrative comments, dropped GRANULARITY from both CREATE TABLEs, and replaced the remaining comments with SELECT '...' markers.

GRANULARITY was recorded in my notes as possibly load-bearing for the repro, so I measured it rather than assuming. Reverting only the fix hunk on this tree and running the reduced test:

Logical error: 'cols.size() == required_columns.size()'
  optimizeLazyMaterialization.cpp:544: optimizeLazyMaterialization2

Same assertion the issue reports, so the reduced test still reddens pre-fix. It also still needs index_granularity = 1 on the table, which I kept.

04563_text_index_merge_heterogeneous_children.sql: removed the comment above SET enable_analyzer = 1, added a one-sentence comment describing the test, and reformatted all three CREATE TABLEs one column per line. Pre-fix this test still aborts with Column __text_index_idx_map_values_equals_... already added for reading.

Behaviour of the restructure, since it rewrites the hunk the fix consists of: I rebuilt the previous form as a control and ran text_index plus lazy_material against both binaries. Identical results, 125 OK / 39 skipped, and the same 10 failures on both, all bare-server environment gaps (system.query_log, test.hits, missing test clusters), none in files this PR touches. Both new tests pass under the runner on the restructured build.

@ahmadov ahmadov left a comment

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.

LGTM

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7b8214e

CI is fully finished on this head and no check failed, so the table below has no rows
and nothing needs an owner.

Check / test Reason Owner / fixing PR

Measured on the deduplicated check-run set (newest attempt per name): 171 unique names,
0 incomplete, 0 non-green, 154 succeeded and 17 were skipped by the selected-tests gate.
No name has a superseded cancelled attempt in the raw list either (172 raw runs against
171 unique), so there is no retry ambiguity to read past here. Config Workflow,
Style check and Finish Workflow all succeeded, which makes this a real run rather
than a void one.

The matrix that ran is the full one, not a reduced selection: 26 builds, all four
sanitizer families across stateless, integration, stress and unit tests, 6 AST fuzzer
legs, 4 BuzzHouse legs, 10 Stress test legs, Upgrade check (amd_release),
LLVM Coverage, SQLLogic test, SQLStorm test, the 6 Performance Comparison legs
and both ClickBench legs. Given the pr-bugfix category, the three
Bugfix validation legs (functional amd64, functional aarch64, unit tests) also
succeeded, so the regression test does fail without the fix.

CIDB agrees independently for this head: 267078 OK test rows and 0 FAIL or ERROR
rows. The slower and unstable rows it reports (8 and 4) come from
Performance Comparison, whose check runs are green, so they are informational and not
failures.

Session id: cron:our-pr-ci-monitor:20260820-173000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit 518d389 Aug 21, 2026
177 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

I measured the backport scope on prebuilt release binaries before asking for a label.

Affected (reproduces, fix absent): 26.7 (26.7.6.48) and 26.6 (26.6.4.48), both aborting with vector<bool>::operator[] index out of bounds. The second regression test also reddens there with Code: 49, so the Merge LOGICAL_ERROR half is present on those branches too.

Not affected: 26.8 (26.8.1.2041) is clean because merge commit 518d389fdbe7 is already an ancestor of it (behind_by 0). 26.3 (26.3.26.4) is clean structurally: the introducing commit 88e2e1d1c13f from #106272 is not an ancestor of 26.3, so the regression never reached that branch. The 26.3 fixture was armed (both text indexes created, 3 rows inserted), so that reading is a measurement and not a DDL failure.

Controls behaved: current master (26.9.1.384) clean, 26.7 reproducing. Active release branches when measured: 26.3, 26.6, 26.7, 26.8.

So the minimal label is v26.6-must-backport, which expands to 26.6, 26.7, 26.8; 26.8 costs nothing because ReleaseBranch.pre_check sets _backported from git merge-base --is-ancestor and process then returns immediately. v26.3-must-backport and pr-must-backport would also target 26.3, where there is nothing to fix.

The port is clean on both affected branches: git merge-tree --merge-base=518d389fdbe7^1 applies with no conflict (5 files, +181/-1, matching the master diff) and all 10 added lines of optimizeDirectReadFromTextIndex.cpp land, so there is no half no-op. Both regression tests pass unmodified on the 26.8 release build, and the six settings they set exist with identical defaults on 26.6 and 26.7, so the tests port as they are.

Could a maintainer apply v26.6-must-backport here?

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 16, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 16, 2026
PedroTadim pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
…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]>
@watson-ch watson-ch Bot added v26.4-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 21, 2026
@watson-ch

watson-ch Bot commented Nov 21, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2250

Labels added:

  • v26.4-must-backport

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.

@robot-ch-test-poll4 robot-ch-test-poll4 added pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels Nov 21, 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 groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lazy materialization OOB: cols.size() mismatch (debug) + release vector<bool> out-of-bounds read with Map subscript + two text indexes

7 participants