Repository navigation
Conversation
A Buffer table whose destination declares a column with a different type aborted the server when a row policy and a PREWHERE both referenced that column: Logical error: 'Bad cast from type DB::ColumnMap to DB::ColumnArray' A release build rejects the query with Code: 49 instead, and an Array or LowCardinality parent gives Code: 44. It fails at planning time, on the executeDryRunImpl path, so even EXPLAIN actions = 1 fails. Only plain DDL and one SELECT are needed. StorageBuffer::read forwards both filters into the destination read and built a converting prefix per filter by cloning one converting_dag, whose _CAST binds the destination type. Those prefixes then run as consecutive prewhere steps over a single block: getPrewhereActions emits the row-level step first and the PREWHERE step second, applyPrewhereActions chains them, and ActionsDAG::updateHeader carries each step's outputs forward. Because buildFilterInfo keeps every query-required filter input as an output of the row-policy DAG, the mistyped column leaves the first step already converted and the second prefix casts it again from a type it no longer has. Build each prefix from its own source list instead, substituting this table's type for any column a previous prefix already converted and left as an output, so makeConvertingActions emits no cast for it. The set is populated only from names that are both a filter output and a column of the sample block, which is exactly what updateHeader carries forward; a broader set would skip a cast that is still owed when only one filter touches the column. The correctness of this depends on the lambda's call order matching the step order in MergeTreeSelectProcessor::getPrewhereActions, which a comment in the code now records. Measured on a pristine master build (aborts), the fixed build (correct), and two mutants: reverting only the type substitution restores the abort, and an over-broad substitution breaks the row-policy-on-another-column case. Covered for Map, Array, Nullable and LowCardinality parents, each of which failed differently before, plus single-filter, other-column, additional_table_filters and matching-type controls. This code is master only; 26.7 and earlier fail earlier on the same query.
Review round 1 asked for three test-liveness repairs and one comment widening. The Array single-filter control read the destination table, so it asserted that table's own type and never entered StorageBuffer::read. It now reads the buffer and expects the converted value. Both single-filter controls were moved above the CREATE ROW POLICY on their table so they are genuinely single-filter. Every destination now holds three rows: one both filters accept, one only the row policy rejects, one only the PREWHERE rejects. Each arm therefore asserts which rows survive. Removing the row policies changes six arms and removing the PREWHERE clauses changes eleven, so no arm passes vacuously. The wrapper arm put its row policy and its PREWHERE on different columns, which is not the both-filters shape. A dedicated LowCardinality(String) pair now carries that coverage on one column; it fails on unpatched master with "Invalid column type for ColumnUnique::insertRangeFrom". The Nullable arm is kept and relabelled so it no longer claims to be the wrapper arm. A bare-column row policy (USING f) is now a permanent arm. Review asked whether such a policy needs the filter column excluded from the already-converted set, since buildFilterInfo makes that name a real table column and the row-level step removes it. Measured, it does not: for a bare column reference the filter output and the required-input output are the same DAG node, already carrying the converting prefix's cast, and Block::erase removes one positional copy, so the other converted copy reaches the next prefix. Adding the exclusion was tried and changed nothing in 37 of 38 probed shapes; the 38th showed it re-casting a column that already had this table's type. It is not in this commit. MergeTree is not the only consumer imposing row-level-then-PREWHERE order: the Parquet reader does too, and a Buffer may have a Parquet-format destination. Its carry semantics match, so the comment names it and no code changes. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two arms of 04741 could pass with their row policy silently gone, because in both the policy predicate was implied by the PREWHERE: the Array arm had `length(a) > 0` under `PREWHERE length(a) > 1`, and the bare-column arm had `USING f` under `PREWHERE f > 1`. Those are exactly the arms whose purpose is that both forwarded filters meet the same converted column, so each now has a row its policy rejects and its PREWHERE accepts. Also add an arm with both filters on the same Nullable column, which was uncovered: the existing Nullable arm puts the policy and the PREWHERE on different columns. Note a NULL-rejecting PREWHERE would imply an IS NOT NULL policy, so the arm pairs `USING n != '9'` with `PREWHERE n != '7'` over a four-row destination instead. Measured on the shipped test by running two stripped variants: of the 10 arms with a row policy, dropping every policy changes 9; of the 12 with a PREWHERE, dropping every PREWHERE changes 11. The two insensitive arms are the two whose point is that the other filter alone already selects the surviving row. No source change.
…Nullable arm The comment above the destinations claimed that dropping either filter changes the output of every two-filter arm. Measured over the shipped rows and predicates by running two stripped variants of the test, that holds for 7 of the 9 two-filter arms and fails for two. Arm J puts its PREWHERE on another column and has no row its row policy alone rejects; arm I puts its policy on another column and has no row its PREWHERE alone rejects. Both are deliberate: each exists to show a filter on a different column is unaffected. The comment now states the property where it holds, over the arms whose two filters meet the same converted column, and names J and I as the exceptions. Arm Y is also relabelled a control. A Nullable parent was already correct before the fix, so that arm pins only that the fix does not regress it; its label read like the witness arms and a green verdict on unpatched master could be mistaken for a bug. Correcting an overstatement in an earlier message on this branch: "Do not re-convert a Buffer column a previous forwarded filter converted" said the Map, Array, Nullable and LowCardinality parents "each of which failed differently before". That is wrong for Nullable. The pre-fix failures are Map (abort, Bad cast from type DB::ColumnMap to DB::ColumnArray), Array (Code: 44) and LowCardinality (Code: 44); Nullable and matching-type parents are controls that pass on unpatched master. Re-measured per arm on the pristine snapshot: exactly 3 of the 13 arms redden and the other 10 are byte-identical to the fixed build. Also backtick the two symbol names in the StorageBuffer.cpp comment, per the repo convention for literal class and function names. No behaviour change: the source edit is comment text only, verified by stripping all comments from both revisions and comparing the results byte for byte.
The comment above arm Y said the PREWHERE must accept the NULL row, otherwise it implies the row policy and the arm cannot detect a lost policy. That reason is wrong. The fixture is (1,'7') (2,NULL) (3,'9') (4,'8'), the policy is n != '9' and the PREWHERE is n != '7'; for the NULL row both comparisons evaluate to NULL, so both filters reject it and neither implies the other through it. The arm is two-sided for a different reason, which the comment now states: n = '9' is rejected by the policy alone and n = '7' by the PREWHERE alone, so dropping either filter changes the output. Measured three ways that agree - the truth table of both predicates over the four shipped rows, and the two stripped variants of the test, whose arm Y reads [8, 9] with the policy removed and [7, 8] with the PREWHERE removed against the shipped reference [8]. The NULL row is absent from all three outputs. No predicate, fixture row or reference line changes, and no source file is touched; the arm was already live in both directions and stays byte-identical in behaviour. The wrong reason had not reached the pull request description or any other artifact, but it is the kind of reasoning a later contributor would copy when building a Nullable fixture. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…tifying The header comment claimed that every arm whose two filters meet the same converted column holds a row both filters accept, a row only its row policy rejects and a row only its PREWHERE rejects, and named J and I as the only exceptions. Arm N is a third: it runs after the row policy on its table is dropped and pairs its PREWHERE with an additional_table_filters entry, which the planner appends to the WHERE filters rather than to the row-level filter, so N has no row policy for the sentence to be about. Replace the quantifier with the measured list. Arms A, F, W, W2, Z, Y and D are the two-sided ones; J and I are the deliberate other-column exceptions; N substitutes additional_table_filters for the policy; B, G and C are single-filter controls. That accounts for all thirteen arms exactly once, so an arm cannot be misdescribed by omission again. Scoping the list by "same converted column" would not have worked: D reads a Map(String, UInt64) column that the destination declares identically, so it is the matching-types control and its column is never converted, while W is two-sided with its filters on distinct columns and so belongs in the list without belonging in that set. Both facts are derived from the DDL. Verified by replaying every row policy statement in file order per target table, and by diffing the reference against two stripped variants of the shipped test, one with every row policy removed and one with every PREWHERE removed. Comment text only; no predicate, fixture row, arm or reference line changes, and the binary is unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (click to expand)Two independent review channels ran against this change: a cold code review by a reviewer that had Result: no blocker, no major. One nit, documented below and deliberately not applied. 💡 nit: SQL identifiers unformatted in the test's commentsThe gate noted that the fixture comment writes Agreed as a convention point, not applied, for three measured reasons:
The C++ side of the diff does follow the rule ( What the cold review verified independentlyThe change makes the second converting prefix depend on the first having run, so the review Membership of the already-converted set was checked in both directions: a name enters only if it is Test liveness was re-derived from the DDL rather than from the notes: which columns the destination Session id: cron:clickhouse-review-self-slot-58:20260806-053900 |
Pre-PR validation gate (click to expand)
Extra runs: the new test 50x under randomization ( Session id: cron:clickhouse-review-self-slot-58:20260806-053900 |
|
cc @novikd @vdimir, could you review this? |
|
@groeneai isn't a PR from @alexey-milovidov fixing this already? |
|
No, and I checked rather than answering from the titles. It is a fair question, because he has two recent changes in exactly this area and both Neither touches the converting prefix. On a pristine debug build of current master SELECT m FROM mt_buf PREWHERE mapContains(m, 'b');That is why the subcolumn work does not cover it: I also enumerated all 1876 open PRs, took each file list (batched GraphQL, the 61 that The only overlapping PR is mine, 113231, and its trigger is disjoint: its |
|
Workflow [PR], commit [d814e5b] Summary: ❌
AI ReviewSummaryThis PR fixes the double-conversion path in Final Verdict✅ No new findings. |
StorageBuffer::read forwards a row policy and a PREWHERE into the raw destination read, and each one gets its own converting prefix. The prefixes assume the destination applies them in order over one header that carries each filter's outputs forward, so a column the first prefix converted must not be converted again by the second. The regression added with the fix only exercises a MergeTree destination. A Buffer can equally forward into a Parquet-backed File or object-storage table, whose header is built by updateFormatPrewhereInfo in prepareReadingFromFormat.cpp. MergeTree never reaches that function, so that carrier was unpinned and a later change there could reintroduce the double conversion with every committed test still green. Add one focused arm over a File(Parquet) destination. Measured on a debug build: before the fix the third query aborts the server with Bad cast from type DB::ColumnMap to DB::ColumnArray, raised from StorageFile::read through updateFormatPrewhereInfo into SourceStepWithFilter::applyPrewhereActions, so no MergeTree arm can observe it. After the fix the same query reports TYPE_MISMATCH, which is what a single PREWHERE on that column already reports with no row policy at all, that is the pre-existing and unrelated limitation that the Parquet reader rejects a requested type the file's schema does not carry. The first two queries pin that the converted column still reads correctly with no filter and with the row policy alone. The arm stops at header building and does not reach Parquet's own Reader::preparePrewhere, which runs later during execution. The test needs no-fasttest because the fast test build configures ENABLE_LIBRARIES=0 and has no Parquet. It does not need no-parallel-replicas: the randomizer's parallel-replicas settings were measured inert here, since the destination is not a MergeTree table and parallel-replicas planning never engages.
The block had grown to six lines across review rounds, over the three-line budget, and its last two lines named the consumers by function. One of those names was misleading: Parquet's Reader::preparePrewhere runs during execution, while the ordering this code depends on is established earlier, when updateFormatPrewhereInfo builds the format header. Keep the invariant, drop the cross-file citations.
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 units7 translation units recompiled, 16 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - d814e5bCorrected twice. A first revision called the fuzzer row PR-caused. This revision corrects The fixing PR for the first two rows is #113900. Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
Corrections to my previous revisionThree claims in it are false. The cause was a probe defect in my own harness, and I am recording it
What survives unchanged: the row is not PR-caused, because the abort reproduces on a pristine-master The real root cause, and why #113900 supersedes this PR
#113900 corrects the type where it is created, which covers this PR's case plus the two it did not. I plan to close this PR in favour of #113900 unless you would rather keep it. @PedroTadim, you wrote Session id: cron:clickhouse-review-self-slot-58:20260807-224700 |
|
Superseded by #113900 (merged 2026-10-02): it carries this PR's tests and replaces its Checked on a master debug build at 3ade111, which contains #113900: this PR's I'll close it whenever you say so. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
Bad castlogical error when a row policy and aPREWHEREboth reference the same column of aBuffertable whose destination table declares that column with a different type. The column was converted twice, the second time from a type it no longer had.Description
A
Buffermay declare a column with a different type than its destination, converting it on read. When a row policy and aPREWHEREboth reference such a column, the server aborts:Logical error: 'Bad cast from type DB::ColumnMap to DB::ColumnArray'in a debug or sanitizer build; a release build rejects it withCode: 49. It fails at planning time, soEXPLAINfails too.Root cause:
StorageBuffer::readforwards both filters into the destination read, building a converting prefix per filter from one DAG whose_CASTbinds the destination type. The prefixes then run as consecutivePREWHEREsteps over one block carrying each step's outputs forward, so the second prefix casts a column the first converted, from a type it no longer has.The change builds each prefix from its own source list, where a column a previous prefix converted already carries this table's type, so
makeConvertingActionsemits no cast. Not in 26.7 or earlier, so no backport is requested.On pristine master a
Mapparent aborts andArrayandLowCardinalityparents giveCode: 44; all arms pass on the fixed build.Nullableand matching-type parents are controls. Reverting only the type substitution reddens those three arms; an over-broad substitution reddens the other-column control alone. Conflicts textually with#113231, which touches the same lambda.Reading such a column with
FINALand a row policy fails on unmodified master with a single filter: a separateFINAL-path defect, not addressed here.