Skip to content

Fix a bad cast when a row policy and PREWHERE both read a converted Buffer column - #113624

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-two-filter-double-conversion
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-two-filter-double-conversion

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 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 a Bad cast logical error when a row policy and a PREWHERE both reference the same column of a Buffer table 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 Buffer may declare a column with a different type than its destination, converting it on read. When a row policy and a PREWHERE both reference such a column, the server aborts:

CREATE TABLE dst (k UInt8, m Array(Tuple(String, UInt64))) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO dst VALUES (1, [('a', 1), ('b', 2)]);
CREATE TABLE buf (k UInt8, m Map(String, UInt64))
    ENGINE = Buffer(currentDatabase(), dst, 1, 100, 100, 1000, 10000, 1000000, 10000000);
CREATE ROW POLICY p ON buf USING mapContains(m, 'a') TO ALL;
SELECT m FROM buf PREWHERE mapContains(m, 'b');

Logical error: 'Bad cast from type DB::ColumnMap to DB::ColumnArray' in a debug or sanitizer build; a release build rejects it with Code: 49. It fails at planning time, so EXPLAIN fails too.

Root cause: StorageBuffer::read forwards both filters into the destination read, building a converting prefix per filter from one DAG whose _CAST binds the destination type. The prefixes then run as consecutive PREWHERE steps 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 makeConvertingActions emits no cast. Not in 26.7 or earlier, so no backport is requested.

On pristine master a Map parent aborts and Array and LowCardinality parents give Code: 44; all arms pass on the fixed build. Nullable and 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 FINAL and a row policy fails on unmodified master with a single filter: a separate FINAL-path defect, not addressed here.

groeneai and others added 6 commits August 5, 2026 03:49
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]>
@groeneai

groeneai commented Aug 6, 2026

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

Two independent review channels ran against this change: a cold code review by a reviewer that had
not seen the implementation notes, and an independent second-model gate. Seven fix rounds; the last
three changed test comments only, with the compiled binary unchanged (Build ID
4d45ee3e24eb3ace... before and after each).

Result: no blocker, no major. One nit, documented below and deliberately not applied.

💡 nit: SQL identifiers unformatted in the test's comments

The gate noted that the fixture comment writes additional_table_filters and PREWHERE without
inline code formatting, which the repository's contributor instructions ask for.

Agreed as a convention point, not applied, for three measured reasons:

  • No CI check enforces it, so nothing fails.
  • The in-tree convention for -- comments in stateless .sql tests runs the other way. Across the
    9,896 stateless .sql files, only 69 backtick any SQL token inside a -- comment; per token the
    plain form leads by 234:24 for PREWHERE, 882:36 for Nullable, 338:30 for LowCardinality,
    235:15 for MergeTree, 26:3 for Buffer.
  • This test file uses no backticks in any of its 16 comment lines, so formatting only the two
    tokens named would leave it internally inconsistent, and reformatting all 16 is prose churn on a
    file that has already been revised three times for comment wording alone.

The C++ side of the diff does follow the rule (MergeTreeSelectProcessor::getPrewhereActions and
Reader::preparePrewhere are backticked in the source comment).

What the cold review verified independently

The change makes the second converting prefix depend on the first having run, so the review
enumerated every consumer of the two forwarded filters and checked each for order and for applying
the PREWHERE prefix without the row-level one: MergeTreeSelectProcessor::getPrewhereActions,
SourceStepWithFilter::applyPrewhereActions, Parquet::Reader::preparePrewhere,
StorageObjectStorageSource, InterpreterSelectQuery::addEmptySourceToQueryPlan,
optimizeLazyFinal, the deferred-after-FINAL path in ReadFromMergeTree, the projection paths, and
optimizeTopK. All apply the row-level filter first; the paths that drop a filter drop both
together, and optimizeTopK only replaces prewhere_info when there is none forwarded. Index-read
steps that sit between the two carry actions = nullptr and are skipped by the range reader, so
they cannot disturb the block.

Membership of the already-converted set was checked in both directions: a name enters only if it is
both a filter output and a column of the sample block, which excludes the synthetic predicate column
the row-level step erases, and the over-broad mutant recorded in the validation gate shows that a
wider set breaks a control arm.

Test liveness was re-derived from the DDL rather than from the notes: which columns the destination
declares differently, which arms put both filters on the same column, and which arms are two-sided.
That derivation agrees with the recorded mutation matrix and corrected the wording of one
description in the validation gate comment.

Session id: cron:clickhouse-review-self-slot-58:20260806-053900

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES, 100% (not a rate). clickhouse local --queries-file repro.sql with the DDL + SELECT from the description: exit 134, Logical error: 'Bad cast from type DB::ColumnMap to DB::ColumnArray', Received signal Aborted (6).
b Root cause explained? YES. StorageBuffer::read built one converting DAG and cloned it into a prefix per forwarded filter; the _CAST binds the destination type. MergeTreeSelectProcessor::getPrewhereActions emits row-level then PREWHERE, SourceStepWithFilter::applyPrewhereActions chains them over one block, ActionsDAG::updateHeader carries outputs forward, and buildFilterInfo keeps a query-required filter input as a row-policy output. So the second prefix re-casts an already-converted column.
c Fix matches root cause? YES. Each prefix is built from its own source list in which an already-converted column carries this table's type, so makeConvertingActions emits no cast for it (a cast is emitted only when the types differ). No guard at the cast site, no widened bound, no disabled optimisation, no no-random-* tag.
d Test intent preserved / new tests added? YES. Nothing existing weakened or deleted. New 04741_buffer_two_filters_converted_column (.sql + .reference), 13 arms, parallel-safe (every object t04741_*-prefixed; an unqualified CREATE ROW POLICY binds to the current database), no no-parallel. Measured by running two stripped variants of the shipped test rather than by inspection: 10 arms have a row policy in force and dropping every policy changes 9 of them; 12 arms have a PREWHERE and dropping every PREWHERE changes 11 of them. The two insensitive arms are exactly the two whose purpose is that the other filter alone already selects the surviving row: arm J (policy on m, PREWHERE k = 1) and arm I (policy on k = 1, PREWHERE on m). Seven arms are two-sided, i.e. hold a row both filters accept, a row only the first filter rejects and a row only the PREWHERE rejects, so neither filter can go missing unnoticed: A, F, W, W2, Z, Y and D. (W's two filters sit on distinct columns and D's column is declared identically in the destination, so scoping that list by "the same converted column" would be wrong in both directions; the shipped test's header comment enumerates the seven instead of quantifying.) N substitutes an additional_table_filters entry for the row policy, and B, G, C are the single-filter controls, which accounts for all thirteen arms exactly once.
e Both directions demonstrated? YES. All 13 arms re-run per-arm on the final tree against four binaries (arm A aborts the server, so each arm gets its own), each with SELECT lower(buildId()) asserted against readelf -n before any verdict. Pristine master 72b3babb: FAIL, arm A aborts Logical error: 'Bad cast from type DB::ColumnMap to DB::ColumnArray', arms F and W2 give Code: 44 (Illegal column String ... of function toString and Invalid column type for ColumnUnique::insertRangeFrom); the other 10 arms are correct, so the reddening is scoped to the three affected shapes. Mutant reverting only the type substitution 70fc3004: FAIL, the same three arms, same messages. Mutant with an over-broad substitution 665fb9fe: FAIL on the other-column control (arm I) alone, with a distinct Code: 43 Function mapContainsKey requires at least one argument of type Map. Fix 4d45ee3e: PASS, 13/13 arms, 0 fatal logical errors. Restoring the fix returned the Build ID exactly to 4d45ee3e.
f Fix is general across code paths? YES. Both forwarded-filter carriers go through the one lambda. additional_table_filters measured NOT a second carrier (it folds into the PREWHERE step) and is guarded by a test arm. _row_exists / index steps carry no Buffer prefix (createLightweightDeleteStep has .actions = nullptr). Of the 21 files using makeConvertingActions under src/Storages/, only this one and the streaming commit-order source also mention the filters, and that one builds a single prefix. StorageMerge is unreachable for this shape: measured Code: 182 ILLEGAL_PREWHERE identically on both arms, because supportedPrewhereColumns erases any column whose child type differs.
g Fix generalizes across inputs (params/datatypes/wrappers)? YES. Four parent wrappers, each a different pre-fix failure: Map aborts, Array gives Code: 44 ILLEGAL_COLUMN, LowCardinality gives Code: 44 ColumnUnique::insertRangeFrom, Nullable was already correct. All four plus single-filter (over the Buffer, outside any row policy), other-column, WHERE-instead-of-PREWHERE, additional_table_filters, matching-type and bare-column row policy (USING f, where the filter column is a real table column the row-level step removes) controls were measured; 13 arms ship in the test, including one with both filters on the same Nullable column. Widening and narrowing mistypes, Float, Decimal and Nullable bare-column variants were also measured.
h Backward compatible? (maintainer-approved exception only) YES, and nothing is owed. One source file plus two new test files. No setting added or defaulted differently, so no SettingsChangesHistory.cpp entry is required; no serialization or on-disk format change; no experimental gate; no magic constant. The change only turns an abort or a rejected query into the correct answer, so no working query changes behaviour. Master only, so no backport label is requested.
i Invariants and contracts preserved? YES. The already-converted set is populated only from names that are both a filter output and a column of the sample block, i.e. exactly what updateHeader carries forward; the over-broad mutant shows a wider set breaks a control. The lambda's contract is unchanged (still restricted to the filter's outputs). No lock, no allocation in a loop, no new error path, no ownership change; getByName is guarded by a membership test whose names came from has. The only behavioural difference is building the DAG twice instead of cloning once, at planning time, inside a branch that runs only for a mistyped Buffer column with a forwarded filter.

Extra runs: the new test 50x under randomization (--test-runs 50 --order random), 50/50 passed in 28.25 s, 0 fatal logical errors, 0 signals. A 12-test Buffer / PREWHERE / row-policy set, 12/12 passed. On a broad buffer row_policy prewhere selection (332 in-tree tests besides this one) every failure was reproduced on the pristine-master snapshot as well, except 10 that were all 600s timeouts under concurrent load on this box and pass in isolation (10/10, 72s total), so there are no regressions attributable to this change.

Session id: cron:clickhouse-review-self-slot-58:20260806-053900

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir, could you review this? StorageBuffer::read forwards a row policy and a PREWHERE into the destination read and built a converting prefix for each from one DAG whose _CAST binds the destination type; the prefixes then run as consecutive prewhere steps over one block that carries each step outputs forward, so the second one cast a column the first had already converted and a debug build aborted with Bad cast from type DB::ColumnMap to DB::ColumnArray.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai isn't a PR from @alexey-milovidov fixing this already?

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

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
are already in this PR's base: 111948 ("Fix exception when reading a dynamic subcolumn
through a Buffer table", merged 2026-07-28), which guards the unchecked
tryGetByName dereference in StorageBuffer::read; and the commit
e62b2d51dc30b37 he authored inside your own 112326, which added
StorageBuffer::supportedPrewhereColumns (StorageBuffer.cpp:962 on master).

Neither touches the converting prefix. On a pristine debug build of current master
(25d677a4, both commits verified ancestors, StorageBuffer.cpp byte-identical to
that sha) the repro still aborts with Logical error: 'Bad cast from type DB::ColumnMap to DB::ColumnArray', exit 134, frames createArrayToMapWrapper ->
executeDryRunImpl -> ActionsDAG.cpp:1453 -> SourceStepWithFilter.cpp:42 ->
MergeTreeSelectProcessor.cpp:510, reached from StorageBuffer.cpp:469. The same
query on this PR's head returns {'a':1,'b':2} with no fatal line, so the probe does
discriminate. The minimal form needs no subcolumn and no non-default setting:

SELECT m FROM mt_buf PREWHERE mapContains(m, 'b');

That is why the subcolumn work does not cover it: supportedPrewhereColumns decides
which columns may enter PREWHERE, whereas here merge_converting_prefix
(StorageBuffer.cpp:440) built a prefix per forwarded filter from one DAG whose
_CAST binds the destination type, and the prefixes run as consecutive prewhere steps
over one block that carries each step's outputs forward, so the second casts a column
the first already converted.

I also enumerated all 1876 open PRs, took each file list (batched GraphQL, the 61 that
hit the 100-file page cap re-probed via REST) and decided the 41 touching this stack by
operation rather than subject. None of his five open PRs here scores on
makeConvertingActions, converting_dag, merge_converting_prefix,
createArrayToMapWrapper or row_level_filter, against 1 to 3 hits each on this
diff. 112504 is the closest by name and unrelated: it removes 11 typeid_cast uses in
src/Functions/ and ColumnArray, none in the cast wrapper that aborts here.

The only overlapping PR is mine, 113231, and its trigger is disjoint: its
already-converted set is populated only from derivable-subcolumn parents, so it stays
empty when no subcolumn is requested, and this repro still exits 134 on that PR's own
binary.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d814e5b]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Unexpected return type from A. Expected B. Got C (STID: 3262-40ad) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Fast test (arm_darwin) ERROR
Build (amd_darwin) ERROR
Build (arm_darwin) ERROR
Build (arm_v80compat) ERROR
Build (amd_freebsd) ERROR
Build (ppc64le) ERROR
Build (amd_compat) ERROR
Build (amd_musl) ERROR

AI Review

Summary

This PR fixes the double-conversion path in StorageBuffer::read by rebuilding the forwarding prefix per pushed-down filter and carrying forward which table columns were already converted between the row-level filter and PREWHERE. The added stateless coverage now exercises both the MergeTree path and the separate File(Parquet) / updateFormatPrewhereInfo carrier that the earlier review thread called out. I do not see a remaining blocker or major issue in the current code.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 6, 2026
Comment thread src/Storages/StorageBuffer.cpp Resolved
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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d814e5b8d with master a96691076 (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 689.52 MiB 686.50 MiB -3.02 MiB (-0.44%)

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

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

Job report

@groeneai

groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d814e5b

Corrected twice. A first revision called the fuzzer row PR-caused. This revision corrects
something else: three factual claims I made in the previous revision are wrong, and the fixing PR
this comment promised is now open. Both corrections are below, with what I re-measured.

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
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) / Logical error: Unexpected return type from materialize. Expected Array(Tuple(String, UInt64)). Got Map(String, UInt64) (STID 3262-40ad) NOT PR-caused: reproduces identically on pristine master (details below). A separate root cause at a different site fixing PR #113900 (ours, open)
Finish Workflow / Post Hooks not a test result: new_tests_check.py reports that no per-arch Bugfix validation job validated the bug. All five Bugfix jobs on this head ended skipped, so nothing was measured. Cascade of the row above fixing PR #113900 (ours, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6 and 5/6) runner-level wedge, not a test result: zero failing test rows on this sha (3/6: 756 OK / 0 FAIL; 5/6: 1294 OK / 0 FAIL), and this PR touches no integration test or harness file fixing PR #112984 (ours, open)

Corrections to my previous revision

Three claims in it are false. The cause was a probe defect in my own harness, and I am recording it
because it is easy to hit: programs/server/config.xml ships
<user_directories><local_directory><path>/var/lib/clickhouse/access/, and with --path overridden
the server resolves that relative to the working directory. A row policy created by one cell
persisted in a stray access/ directory and was read by every later server, including every cell I
had labelled "no policy". Passing --user_directories.local_directory.path= on the command line
does not fix it: it adds a second local_directory rather than replacing the first, which
system.user_directories reports as three entries. Correct isolation rewrites the path inside the
config and asserts one local_directory, with a per-cell count of policies before and after setup.

  1. A row policy on the diverging column IS required. With the access storage genuinely isolated,
    the minimal form I published above returns both rows correctly, 12 runs out of 12. Every "no
    policy" abort I reported was the leaked policy. A policy on a non-diverging column is also clean.
    The reachable shape needs CREATE ROW POLICY ... USING mapContains(m, 'a') on the Buffer.

  2. The stack I published is wrong. Measured on both arms, byte-identical: ActionsDAG.cpp
    executeActionForPartialResult from evaluatePartialResult from updateHeader, called from
    ExpressionTransform's constructor from ExpressionStep::transformPipeline from
    QueryPlan::buildQueryPipeline. updateFormatPrewhereInfo, applyPrewhereActions and
    StorageFile::updatePrewhereInfo are not on it. The mechanism sentence built on those names
    is therefore wrong as well.

  3. This PR does fix one carrier. With a row policy and an explicit PREWHERE on the diverging
    column, master aborts and this head returns a clean TYPE_MISMATCH. Only the implicit-move cell
    still aborts here, deterministically.

What survives unchanged: the row is not PR-caused, because the abort reproduces on a pristine-master
binary that contains none of this PR's code, and the abort site is in files this PR does not touch.
The mistyped column only has to be projected. The carrier is the implicit WHERE to PREWHERE
move: with optimize_move_to_prewhere = 0 the same query is clean. A MergeTree destination is
clean, and so are File(TSV) and File(Native), because the move only happens for a format that
supports prewhere.

The real root cause, and why #113900 supersedes this PR

StorageBuffer::read prepends a destination-to-Buffer converting prefix to a forwarded filter and
converted every output of that filter's DAG. buildFilterInfo also appends the filter's inputs
as outputs, and those are pass-throughs of the destination's own columns, so the read advertised
columns the destination cannot produce. One wrong type, three symptoms: the abort above; a
TYPE_MISMATCH over a URL(Parquet) destination with no filter at all, which is reachable on
master today and needs no Buffer-over-File fixture; and the Bad cast from ColumnMap to ColumnArray this PR set out to fix.

#113900 corrects the type where it is created, which covers this PR's case plus the two it did not.
It is not stackable on this one: this PR's already_converted suppression exists because the first
prefix leaves the pass-through Buffer-typed, and once the pass-through stays destination-typed that
suppressed cast is required again. Only one of the two can be in the tree. #113900 carries this PR's
tests: 04741_* byte-identical, and 04743_* with the TYPE_MISMATCH pin removed, because there
the query now returns rows.

I plan to close this PR in favour of #113900 unless you would rather keep it. @PedroTadim, you wrote
the converting prefix and reviewed this one, so the call is yours if you want it.

Session id: cron:clickhouse-review-self-slot-58:20260807-224700

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... label Sep 4, 2026
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #113900 (merged 2026-10-02): it carries this PR's tests and replaces its StorageBuffer change with a different design, so nothing here is left to merge.

Checked on a master debug build at 3ade111, which contains #113900: this PR's 04741 arms, run with optimize_functions_to_subcolumns = 0 as master's copy of the test does, match its .reference byte for byte, and the row policy plus PREWHERE arm of 04743 now returns the correct row instead of the TYPE_MISMATCH this PR settled for. The server log has no fatal lines.

I'll close it whenever you say so.

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-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants