Skip to content

Fix wrong values and a crash when a stored column is named like a split PREWHERE expression - #125670

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-prewhere-steps-stored-column-name
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-prewhere-steps-stored-column-name

Conversation

@groeneai

@groeneai groeneai commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124484
Related: #124632
Related: #122470

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

Fixed wrong values, NOT_FOUND_COLUMN_IN_BLOCK errors and a crash when a MergeTree table has a column whose name equals the name of a sub-expression of a multi-condition PREWHERE (for example a column named greater(x, 1_UInt8) read with PREWHERE x > 1 AND k > 5). Closes #124484.

Description

On 26.8.21.12, SELECT x, `greater(x, 1_UInt8)` FROM t PREWHERE x > 1 AND k > 5 returns 1 instead of the stored values, and with a String column of that name the server crashes (SIGSEGV). A sub-expression shared by two conditions (plus(x, 1_UInt8) in x + 1 > 2 AND (x + 1) * k > 5) gives NOT_FOUND_COLUMN_IN_BLOCK. Memory's multi-step PREWHERE (master only), a WHERE moved to PREWHERE and the TopK dynamic filter step (#122470, also guarded inside the TopK optimization by my open #122486; the two do not conflict) hit the same path. All of it is correct with enable_multiple_prewhere_read_steps = 0.

Root cause: the split steps keep their computed columns in the block, and the readers (getReadTaskColumns, MergeTreeSelectProcessor, Memory) match columns by name, so a computed column stands in for the stored column of the same name.

Change: tryBuildPrewhereSteps gives a node computed by a step another name (__prewhere_<name>) when a stored column has its name. The steps keep their boundaries, so an earlier condition still filters the rows a later default expression or conversion is evaluated on. The outputs of PREWHERE keep their names, since the query reads them by name.

A single-condition PREWHERE x > 1 with such a column is a separate defect (wrong also with one step) and is not changed here.

Validation: new test 05394_prewhere_steps_stored_column_name (MergeTree, Memory, a guarded default expression and conversion, the TopK dynamic filter) fails on master with wrong values, an abort and NOT_FOUND_COLUMN_IN_BLOCK, and passes with the fix, also under randomized settings and parallel replicas.


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

groeneai and others added 2 commits October 13, 2026 16:43
…ike a stored column

A split PREWHERE keeps every step's computed columns in the block (an
intermediate filter column, or a sub-expression shared with a later step),
and the readers match columns by name: getReadTaskColumns treats every step
output as already read and skips the stored column of that name, and the
MergeTree and Memory sources pick result columns by name. So with a stored
column named `greater(x, 1_UInt8)`, `PREWHERE x > 1 AND k > 5` returned the
filter value instead of the stored data, a String column of that name
crashed, and a shared sub-expression gave NOT_FOUND_COLUMN_IN_BLOCK.

tryBuildPrewhereSteps now returns false (one step, the result of
enable_multiple_prewhere_read_steps = 0) when a non-input output of any step
is named like a physical column of the table, the same fallback as the
input-shadowing guard above it and the Parquet reader's.

The projection index reader built its processor without the projection's
columns while its pool's getReadTaskColumns passes them, so the two step
computations could now disagree ("PREWHERE steps count mismatch" in
createReadersChain); it passes the projection's columns too.

Closes ClickHouse#124484

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reverting the projection index reader's columns plumbing left the test green,
and no arm reached the TopK dynamic filter path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 2 findings fixed, 2 declined with evidence
Finding Verdict
⚠️ The projection-index plumbing had no test arm (reverting it left the test green) AGREE, fixed: projection-index arm added
⚠️ The TopK dynamic filter path named in the description had no test arm AGREE, fixed: TopK arm added
⚠️ The TopK arm should also assert in EXPLAIN that the TopK filter is installed DISAGREE: my open #122486 makes TopK refuse that filter on exactly this query, so such an assertion would fail once it lands; the arm checks the stored values, and the fallback is covered by the other arms without TopK
💡 Use Critical Bug Fix because of the crash DISAGREE: kept Bug Fix

@groeneai

groeneai commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Run alone on master through clickhouse local, the stored-value queries of the new test return 1 instead of the stored values (MergeTree, Memory), abort on the String column (Bad cast from type DB::ColumnVector<char8_t> to DB::ColumnString), or give NOT_FOUND_COLUMN_IN_BLOCK for the shared sub-expression.
b Root cause explained? The split steps keep their computed columns in the block, and getReadTaskColumns, MergeTreeSelectProcessor and Memory match columns by name, so a computed column replaces the stored column of the same name.
c Fix matches root cause? Yes. The split is what exposes the computed columns; such a computed node now gets another name (__prewhere_<name>), so the steps keep their read boundaries.
d Test intent preserved / new tests added? New 05394_prewhere_steps_stored_column_name, 10 queries over both engines, a guarded default expression and conversion, and the TopK dynamic filter, enable_multiple_prewhere_read_steps clamped to 1 (verified in query_log, with a negative control).
e Both directions demonstrated? Master: the stored-value queries are wrong / abort / NOT_FOUND, and the server dies under clickhouse-test. Fix: [ OK ], 50/50 randomized. Not renaming the generated and reddens its query; the earlier one-step fallback reddens the guard queries (CANNOT_PARSE_TEXT).
f Fix is general across code paths? One shared function covers MergeTree and Memory, a WHERE moved to PREWHERE and the TopK filter step (#122470 repro, in the test). The projection index reader reads only PREWHERE inputs, which no computed node shares.
g Fix generalizes across inputs (params/datatypes/wrappers)? UInt8 and String colliding columns, a shared UInt16 sub-expression, a generated and, filter and non-filter step outputs; parallel replicas 40/40 at both parallel_replicas_local_plan values. The rename compares names, so types and wrappers do not matter.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change, and the step plan is unchanged; only the internal names of colliding computed columns differ. 356 related tests: no new failures.
i Invariants and contracts preserved? Only nodes that are not PREWHERE outputs are renamed, so the query sees the same columns. The step plan does not depend on columns, only these internal names do.

Session id: cron:clickhouse-impl-slot-5:20261013-154700

@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [14c2873]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-31ed) FAIL cidb
Integration tests (arm_binary, 3/4) FAIL
test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hosts.py::test_table_on_custom_s3_disk_loads_after_upgrade FAIL cidb
test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hosts.py::test_database_on_custom_s3_disk_loads_after_upgrade FAIL cidb

AI Review

Summary

This PR prevents intermediate PREWHERE results from shadowing stored columns in MergeTree and Memory by assigning unique internal names while preserving read-step boundaries. No unresolved findings remain at commit 14c28732e2b8959686c81737d8ca7ae33b4a5172; the previous guarded-evaluation finding is fixed. The committed regression test and additional cases covering generated-name collisions, constants, shared expressions, and compressed Memory passed on the PR's Fast test binary.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 13, 2026
Falling back to one step dropped the read boundaries of a split PREWHERE:
with an unread stored column named `equals(gate, 1_UInt8)`,
`PREWHERE gate = 1 AND n > 0` evaluated the default expression of `n`,
and an exported `toUInt64(v)`, on the rows `gate = 1` rejects and threw
CANNOT_PARSE_TEXT. The check also fired for stored columns the query
never reads.

The steps now give such a computed node another name (`__prewhere_<name>`)
and keep their boundaries; the outputs of PREWHERE keep their names, since
the query reads them by name. The step count no longer depends on the
columns, and the projection index reader reads only PREWHERE inputs, which
the input-shadowing guard already covers, so its columns plumbing is
reverted.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 32e74f7

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-31ed) not from this PR: an in-order DISTINCT over merge() whose child table (t_topk_proj, ORDER BY id) is read from a projection with another ORDER BY (a). Same class on unrelated PRs; the first run's AST fuzzer (amd_debug, targeted) hit it too (STID 2508-386c) and passed on re-run #122520 (mine, open)
Stateless tests (arm_asan_ubsan, azure, parallel) / (no test row) infra, not from this PR: the self-hosted runner was lost during Run at attempt 2 (09:23Z, "lost communication", no log, no CIDB row) and the job was not re-run; at attempt 1 the same job passed (15562 tests, 0 failed) a fix task is created (fixing-PR link to follow here)
PR rollup of the two rows above #122520 (mine, open) and a fix task is created (the rows above)

The automatic retry re-ran one other job at attempt 3 and stopped there, so the lost job was never retried. The retry policy for this case is asked of the CI owner in #122501.

Session id: cron:our-pr-ci-monitor:20261014-120008

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov you can review this

alexey-milovidov pushed a commit to canhld94/ClickHouse that referenced this pull request Nov 8, 2026
…h one name

With join_use_nulls = 1, the WHERE copy of a JOIN ON condition repeated in
WHERE is computed on toNullable(col) but keeps the name of the ON copy, so
the PREWHERE DAG holds two different nodes with one name and two types
(e.g. equals(__table2.enabled, 1_Bool) as Nullable(UInt8) and UInt8).
tryBuildPrewhereSteps clones every node into its step under its own name,
the steps pass columns to each other through a Block by name, and a
non-last step keeps its filter column in the block. When the two copies
fall into non-adjacent, non-last steps, the later step inserts a column of
the same name and another type and Block::insert throws 352. Two repeated
two-condition groups collide the same way through the generated `and` name.

Clone the non-INPUT nodes whose name is shared with another node, and that
are not outputs of PREWHERE, under new names (`__prewhere_<name>`). Only the
step clones are renamed: the original DAG, and so its conjunct hashes used by
the query condition cache attribution, are unchanged, and the step
boundaries stay where they are, so an earlier condition still filters the
rows a later default expression is evaluated on (a one-step fallback would
throw there). The helper has the same shape as the one in ClickHouse#125670, which
renames for a computed node named like a stored column.

Same class as ClickHouse#111955, fixed for the FilterStep split by ClickHouse#112007.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to canhld94/ClickHouse that referenced this pull request Nov 8, 2026
The new names given to the step clones of nodes that share a name were made
unique only against the names of the PREWHERE DAG. Stored columns read after
PREWHERE are not in that DAG but land in the same block, and the readers skip
a stored column whose name a step already produced (`getReadTaskColumns` for
MergeTree, `read_missing_columns` for Memory). So a table with a column named
like a new name, e.g. `__prewhere_equals(__table2.enabled, 1_Bool)`, returned
the step's predicate value instead of the stored value.

Also skip a candidate name that is a physical column or subcolumn of the
table, with the same `is_stored_column` helper as ClickHouse#125670.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to canhld94/ClickHouse that referenced this pull request Nov 8, 2026
A step with two or more conditions gets a generated `and` filter named
after its children. With the renamed children that name is new, and a
non-last step keeps the filter in the block, so a stored column with the
same name is not read and the query returns the filter value instead.
Alias such a filter to a fresh name, as ClickHouse#125670 does, and share its two
name helpers so the two PRs fold mechanically.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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 comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Multi-step PREWHERE swaps a same-named column for a filter column; segfault

2 participants