Skip to content

Keep a Buffer's forwarded filter from retyping the destination's own columns - #113900

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-passthrough-destination-type
Oct 2, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-passthrough-destination-type

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 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):

Fixed a LOGICAL_ERROR (Unexpected return type from materialize, a server abort in debug and sanitizer builds) when reading a Buffer table whose destination declares a column with a different but convertible type and a forwarded filter references that column: with a row policy and the implicit WHERE to PREWHERE move, and under query_plan_optimize_lazy_final. The same cause made such a read fail with NOT_FOUND_COLUMN_IN_BLOCK when a text index on that column was read directly and the predicate appeared in both PREWHERE and WHERE, fail with TYPE_MISMATCH over a URL(Parquet) destination, and abort with Bad cast from ColumnMap to ColumnArray when a row policy and an explicit PREWHERE both referenced it.

Description

Declaring a Buffer column differently from its destination is supported:
StorageBuffer::supportedPrewhereColumns says so because read() prepends a
converting prefix to a forwarded filter.

That prefix converted every output of the filter's DAG, and buildFilterInfo
also appends the filter's inputs as outputs, which are pass-throughs of the
destination's own columns. Converting them made the read advertise columns the
destination cannot produce, and whichever consumer looked first broke:

  • the plan header, where the moved PREWHERE feeds a Buffer-typed column into
    a destination-typed materialize node;
  • the text index direct read (NOT_FOUND_COLUMN_IN_BLOCK, at default settings);
  • lazy FINAL, which clones the filter onto the read it builds for the
    deduplicating keys;
  • the Parquet reader, which takes the field as a per-column type hint;
  • the second prefix, which cast an already-converted column.

Now only the predicate is converted. A pass-through output is restored to the
merged DAG's own input node, which the merge already maps onto the prefix's
destination-typed source, so no action is emitted. A bare predicate (USING f,
PREWHERE f) is the very node it carries as data, so one name would have to hold
two types at once; that case aliases the predicate, as
StorageMerge::RowPolicyData::init already does.

Validated on debug builds of this branch and of its merge base, at
enable_analyzer 1 and 0: 13 witness shapes fixed, 10 controls unchanged,
EXPLAIN byte-identical on every non-diverging control, and no regression in a
607-test row-policy/prewhere/buffer slice. The lazy FINAL consumer is what the
AST fuzzer hit on #110321; the text index one came out of reproducing it. Each
arm of the new 04849 test has a control disabling only its own consumer, so a
wrong row count cannot pass.

Supersedes #113624, whose tests are carried over here.


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

Version info

  • Merged into: 26.10.1.1315-master (included in 26.10 and later)

…columns

StorageBuffer::read forwards a row policy or PREWHERE into the raw destination
read, prepending a converting prefix so the filter sees the types this table
declares. The prefix converted every output of that DAG, but buildFilterInfo
appends the filter's inputs as outputs too, and those are pass-throughs of the
destination's own columns. Converting them made the destination read describe
columns the destination cannot produce, which broke whichever consumer looked
first:

  - the plan header, when only a row policy is forwarded and the implicit
    WHERE to PREWHERE move turns the Buffer's addMissingDefaults step into an
    ExpressionStep: its header rebuild feeds a Buffer-typed column into a
    destination-typed materialize node and aborts with
    "Unexpected return type from materialize";
  - the Parquet reader, which takes the same field as a per-column type hint
    and refuses with TYPE_MISMATCH, reachable over a URL destination with or
    without a filter;
  - the second prefix, which emitted a cast on a column the first had already
    converted and aborted with "Bad cast from ColumnMap to ColumnArray".

Only the predicate is converted now. A pass-through output is restored to the
merged DAG's own input node, which the merge already maps onto the prefix's
destination-typed source, so this emits no actions. A bare predicate
("USING f", "PREWHERE f") is the very node it carries as data, so one name
would have to hold two types at once; that case gives the predicate a
collision-safe alias, as StorageMerge::RowPolicyData::init already does for
the same clash. A computed predicate needs nothing and takes no new path.

The Buffer/destination type divergence is supported on purpose:
supportedPrewhereColumns says a differently declared type is fine because
read() prepends a converting prefix to the filter.

Tests cover both destination kinds. Over File(Parquet) and URL(Parquet):
a policy with the moved WHERE, with an explicit PREWHERE, with the column
merely projected, and two bare-column policies where converting the predicate
would either reject it outright or silently change its truthiness. The
MergeTree arms cover the composed prefixes across Array, Nullable,
LowCardinality, bare and matching-type parents.
Two ways the arms could go green without exercising the fix.

The runner randomizes optimize_move_to_prewhere and query_plan_optimize_prewhere
to false with probability 0.05 each, and either one alone disables the implicit
WHERE to PREWHERE move that seven of the arms are built on. On such a draw those
arms return the same rows as the control beside them, so they pass on the parent
commit: measured on a debug build of the merge base, with both settings injected
as zero, arms B, L and I emit output byte-identical to the committed reference,
while at their pinned values the same binary aborts. They now pin both settings
in their own SETTINGS clause, which wins over the runner's injection, and the
move-disabled control pins both to zero so it is deterministic in the same two
dimensions rather than one.

Every arm also asserted rows alone, and the rows are the same whether the row
policy is forwarded into the destination read or applied above it. Only the
forwarded path runs the converting prefix these tests cover, and the predicate
that gates the forwarding admits diverging types on purpose, so narrowing it
would leave the tests green. Both tests now also assert that the plan carries
Row level filter column: inside the read, at both analyzer values. A mutant that
makes the two pushdown decisions refuse leaves every row line unchanged and
flips exactly those eight lines from 1 to 0.

The assertion is a boolean rather than the marker text because the analyzers
spell the predicate differently. 04812 reads the plan with a shell grep over a
plain EXPLAIN: its arms run as a restricted user so the policy applies, and a
subquery over EXPLAIN would need CREATE TEMPORARY TABLE, which that user must
not have.
@groeneai

groeneai commented Aug 7, 2026

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

Two review rounds by a second model, independent of the author. Round 0 reviewed
the code cold and found no blocker and no major in src/; both of its majors
were about the tests being unable to detect a regression, and both were fixed in
round 1. Round 1 was a test-only change: git diff <reviewed sha> HEAD -- src/
is 0 lines and the Build ID is unchanged, which is the proof no source line
moved.

Round 0: the code

I enumerated the invariant carriers independently before reading the author's
notes and agreed with the layer: StorageBuffer::read is the only site that
merges a destination-to-own converting prefix into a forwarded filter
(StorageMerge re-analyzes the policy AST per child instead; Distributed
never lowers filters; the updateFormatPrewhereInfo call sites are consumers,
not producers). The INPUT-versus-computed classification is exhaustive: all
four producer sites append pass-throughs from getInputs, so an INPUT-typed
output is always a pass-through and the predicate is INPUT-typed only in the
bare case. The restore emits no actions because ActionsDAG::merge maps the
filter's inputs onto the prefix's outputs. Forcing remove_filter_column is
safe because applyPrewhereActions erases the synthetic alias. The
duplicate-output re-push is correct against Block::insert's structure check
and against Block::erase removing one occurrence.

❌ The tests could not force the carrier they exist to test. Three arms of
the new test relied on the implicit WHERE to PREWHERE move, which is the
whole subject of the change, but the test runner randomizes it away: it draws
optimize_move_to_prewhere and query_plan_optimize_prewhere false about one
run in twenty each, and either one alone disables the move. The vacuity was
exact rather than theoretical: the affected arm's reference block was
byte-identical to the control arm's, so on a false draw the arm was the
control and passed on unfixed code. Fixed. Both settings are now pinned in
the arms' own SETTINGS clauses. I asked for four arms; the author measured
every arm at all four draws on both analyzers and found seven, which I
re-derived independently and confirm. Proven both directions: with the same
setting injected as zero the pinned arms still pass on the fix (the query-level
clause wins) while the base binary dies, and with the pins flipped to zero the
base binary produces output byte-identical to the committed reference, that is,
genuinely vacuous.

❌ Every arm asserted only rows, so losing the pushdown entirely would go
unnoticed.
If a later change stops forwarding a mismatched-column row policy
into the destination read, both fallback paths apply the filter above the read
and return the same rows while the converting prefix never runs. That is live
exposure, not speculation: supportedPrewhereColumns gates the pushdown, it
deliberately admits diverging types today, and narrowing it is the most
plausible future edit. Fixed. Both tests now also assert
Row level filter column: inside the read, at both analyzer values. That string
is emitted only by read steps; the fallback prints Filter column: without the
Row level prefix, so the assertion discriminates the two paths, and it is
independent of the randomized settings by construction.

Round 1: the two divergences from my prescription, both correct

I had prescribed one form for both tests and one mutant; the author diverged on
both and measured why, which I verified:

⚠️ The SELECT count() > 0 FROM (EXPLAIN ...) form cannot work in the new
test. An EXPLAIN in a subquery is the viewExplain table function, which is
not allow_readonly, so it requires CREATE TEMPORARY TABLE; that test's arms
deliberately run as a restricted user holding only SELECT, because the row
policy has to apply to it. All three forms return ACCESS_DENIED there.
Granting the privilege would change what the arms measure, so that test uses a
shell boolean over a plain EXPLAIN and the other test, which runs as the
default user, keeps the prescribed form. SETTINGS enable_analyzer inside the
subquery is also rejected outright, so the analyzer toggle is a statement-level
SET.

⚠️ My prescribed mutant was an artifact. Making supportedPrewhereColumns
exclude the diverging column also reddens the pre-existing explicit-PREWHERE
arms with ILLEGAL_PREWHERE, because that predicate gates PREWHERE validity
as well as policy pushdown; the author verified this by running the previous
test versions against it. The replacement targets only the two pushdown
decisions, and the asymmetry is exact: under it the only difference from the
committed references is the eight new plan lines flipping from 1 to 0, every row
line byte-identical, and the third test fully green. That asymmetry is the
demonstration the arms are armed.

💡 Recorded for a future reader, no change requested. My round-0 note reached the
right conclusion about dropping a second prune of the merged DAG, but for the
wrong reason: I wrote that an output-orphaned node cannot execute, and that is
false, since the linearizer walks every node and the output list only selects
which results are copied out. The correct and stronger reason is that nothing is
orphaned: the merge maps the filter's input onto the prefix's output, so the
prefix's cast stays reachable from the predicate output, which is never
restored. A second prune therefore has nothing to remove, which explains the
author's measurement structurally instead of leaving it a coincidence.

💡 The shell probe sends the client's stderr to /dev/null and does not test its
exit code, so any client failure also prints 0. Deliberately accepted: the
failure direction is safe, since a broken probe reddens the arm and can never
make it pass, and it keeps the arm independent of an error text that differs
between analyzers.

Verdicts: 3 agreed and fixed, 4 disagreed with evidence and terminal, 1
dropped. Two of the disagreements are corrections of my own claims: my first
count of the arms carrying the pin was eight, which read as a stale figure in
the validation comment, and re-deriving it with the right counting unit gives
seven, matching the measured set exactly. Every countable in the PR body and the
validation comment was re-derived from the shipped tree this round.

Gate spend across the PR: $123.96.

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

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. File(Parquet) destination with m Array(Tuple(String, UInt64)), a Buffer declaring m Map(String, UInt64), a row policy USING mapContains(m, 'a'), then SELECT m FROM buf WHERE k > 0 ORDER BY k. On a debug build of the merge base this aborts the server every time with Logical error: 'Unexpected return type from materialize. Expected Array(Tuple(String, UInt64)). Got Map(String, UInt64)', client rc 32 and 59 <Fatal> lines. Reproduced in every base arm of this round, each on a freshly started isolated server.
b Root cause explained? StorageBuffer::read prepends a destination-to-Buffer converting prefix to a forwarded row_level_filter or prewhere_info, and converted every output of that DAG. buildFilterInfo (src/Planner/Utils.cpp:642-644) also appends the filter's inputs as outputs, and those are pass-throughs of the destination's own columns, so the destination read advertised columns the destination cannot produce. Three consumers observe that one wrong type: the plan header (a policy-only read leaves format_header at the file's types, the moved PREWHERE rebuilds the Buffer's addMissingDefaults step as an ExpressionStep, and ActionsDAG::updateHeader binds inputs by name with no type check, feeding a Buffer-typed column into a destination-typed materialize node); the Parquet reader, which takes the same field as a per-column type hint and answers TYPE_MISMATCH; and the second prefix, which casts a column the first already converted.
c Fix matches root cause? Yes. The wrong type is corrected where it is created. No widened bound, no no-random-* tag, no reduced dataset, no guard at a crash site. StorageFile.cpp's narrow guard is deliberately left untouched: widening it was measured to trade the abort for TYPE_MISMATCH and to regress two shapes that work today.
d Test intent preserved / new tests added? Both. The 13 MergeTree arms of 04741_* are adopted byte-identical and every one still passes. 04743_*'s third arm loses its { serverError TYPE_MISMATCH } pin because this change eliminates that error, so its reference gains the one row holding both keys (measured, not copied); that is a relaxation from an error to a result, stated in the PR body. A new 04812_* ships 15 labelled arms: 13 that assert rows (the witnesses over File(Parquet) and URL(Parquet) plus controls that hold without the fix) and 2 that assert the plan. Neither test can go vacuous: the seven arms that need the implicit WHERE-to-PREWHERE move pin optimize_move_to_prewhere and query_plan_optimize_prewhere in their own SETTINGS clause, because the runner draws either one false about one run in ten and either alone disables the move; and because every arm returns the same rows whether the policy is forwarded into the destination read or applied above it, both tests also assert Row level filter column: inside the read at both analyzer values.
e Both directions demonstrated? Yes, at two levels and on two Build-ID-asserted binaries (base 109b5471dbab1bce, fix 5efc6aa22ed1a5fd). Cell level: 13 witness shapes go from abort or TYPE_MISMATCH to correct rows, 10 controls unchanged, every cell run at enable_analyzer 1 and 0. Runner level: 04812_* kills the base server (server died 210, the same materialize message and stack) and passes on the fix; 04743_* kills base with Bad cast from ColumnMap to ColumnArray; 04741_* aborts base on its own witness arm. 300 of 300 runs green on the fix, counted from per-run verdict lines (150 randomized, 150 with randomization off). The two new properties were verified by measurement, not by inspection: with the pins flipped to zero the base binary produces output byte-identical to the committed reference for the arms that depend on the move, and a mutant that stops forwarding the policy leaves every row line unchanged while flipping exactly the eight new plan lines from 1 to 0.
f Fix is general across code paths? The carrier list was executed rather than argued. Both prefixes share the one lambda; the composed pair is fixed by construction; StorageURL and StorageObjectStorage are repaired with no edit of their own (their TYPE_MISMATCH had the same cause, and both URL shapes now return rows); StorageMaterializedView is not a carrier because it forwards the filter unmodified and converts strictly above the read; the Buffer's own-blocks branch is not a carrier, confirmed by an arm with rows still in the buffer; a GROUP BY arm covers processed_stage above FetchColumns; a File(TSV) arm covers destinations whose format supports no prewhere.
g Fix generalizes across inputs? Type pairs Map/Array(Tuple), UInt64/UInt8, UInt8/String and UInt8/Float64, plus 04741_*'s Array, Nullable, LowCardinality, bare-column and matching-type parents. Both destination readers (File and URL), both analyzer settings, the column projected and not projected, the filter naming it and not naming it, a computed and a bare predicate, and rows resident in the buffer as well as in the destination.
h Backward compatible? Yes. No setting is added or changed and no serialization format is touched, so no SettingsChangesHistory.cpp entry is owed. The behaviour change is confined to shapes that previously aborted or raised a hard error; the non-diverging controls are byte-identical in EXPLAIN actions=1 and EXPLAIN header=1 on both binaries.
i Invariants and contracts preserved? The internal alias is written only into objects the function has already cloned, so the parent's own filter, which the own-blocks branch uses, is untouched, and the buffered-rows arm confirms it. Output positions across the prune are not assumed: each restore is guarded by a name equality check at the recorded position, so a reordering could only skip a restore, never mis-assign one. Inputs survive the prune because the restored nodes are inputs. The alias never reaches a user: __buffer_converted_filter occurs zero times in EXPLAIN header=1 and EXPLAIN actions=1 across 12 shapes on both binaries, and a fixture whose destination really does carry a column of that name returns correct rows for SELECT f and for SELECT *.

Session id: cron:clickhouse-impl-self-slot-57:20260807-205620

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @KochetovNicolai, could you review this? StorageBuffer::read prepends a destination-to-Buffer converting prefix to a forwarded filter and converted every output of its DAG, but 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: a logical error that aborts debug builds in the plan header, TYPE_MISMATCH from the Parquet reader, and a bad cast from a second prefix. Now only the predicate is converted.

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

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [39a7eef]

Summary: ✅


AI Review

Summary

This PR narrows the forwarded-filter conversion in StorageBuffer so only the predicate is retyped to the Buffer schema while pass-through destination columns keep the destination schema. I reviewed the current StorageBuffer logic, the unchanged consumers that execute or describe these DAGs, and the prior discussion; I did not find any remaining correctness, compatibility, or regression-coverage gaps in the changed paths.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 39a7eef.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.80% 79.80% +0.00%

Changed lines: Changed C/C++ lines covered: 57/59 (96.61%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 8, 2026
Comment thread src/Storages/StorageBuffer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 39a7eefe6 with master 31d9e00c8 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

4 object files changed (+17.56 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageBuffer.cpp.o 867.53 KiB 885.09 KiB +17.57 KiB (+2.02%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

The aliasing path fires only when the forwarded filter's predicate is an INPUT
node, i.e. a bare `USING f` or a bare `PREWHERE f`. Arm Z of 04741 covers the
row policy half; every PREWHERE in the suite was a computed expression, so the
`PrewhereInfo` half had no direct test.

The fixture converts Float64 to UInt8 so that the conversion changes truthiness
rather than preserving it: 0.5 is true as Float64 and false as UInt8, so only
one row survives a converted predicate. With a truthiness-preserving pair the
arm returned the same rows whether the prefix converted the predicate or left it
on the destination's own column, and removing the aliasing path altogether was
invisible to it.

The arm reads a Parquet destination rather than MergeTree because the header
assertion is only live there: leaving the internal alias non-removable shows up
when updateFormatPrewhereInfo promotes a kept prewhere column into the read's
header, and ReadFromMergeTree never calls that function.

Both assertions are keyed on observed values, run under both analyzers, and each
is justified by a separate mutation of the shipping source: dropping the aliasing
path admits an extra row, dropping the removal-flag term from the data-role test
returns no rows, and dropping the removal flag puts __buffer_converted_filter on
the destination read's header line. An explicit PREWHERE needs neither prewhere
setting, so the arm is draw-independent and takes no SETTINGS pin.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 661de28

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
Stress test (amd_debug) / Logical error: Bad cast from type A to B (STID 3520-4525) trunk bug, not this PR #113925 (ours, open)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

On the one row: the abort is Bad cast ColumnString -> ColumnNullable in
SerializationNullable::enumerateStreams via collectOffsetsColumns - reading a dotted Nested
member's .null subcolumn from an unrewritten part. Trunk-wide and unrelated to the PREWHERE header
change here: 48 rows / 41 distinct PRs / 5 master runs in 90 days, all since 2026-08-07. #113925 is
my fix for that signature and is open, so it owns this row.

Session id: cron:our-pr-ci-monitor:20260809-013000

…olumn

Two more consumers of the mistyped pass-through output reach the defect this
branch fixes, and neither was covered.

An AST fuzzer run reported `Unexpected return type from materialize. Expected
Array(String). Got LowCardinality(String)` for

    SELECT count() FROM tab__fuzz_23 FINAL
    PREWHERE hasAllTokens(str, 'bar') WHERE hasAllTokens(str, 'bar')

where `tab__fuzz_23` is a Buffer created without a column list, so it kept an
`Array(String)` structure while its destination was re-created with
`LowCardinality(String)` and a text index. The converting prefix retyped the
filter's pass-through `str` output, the read then advertised the Buffer's type
while the destination produced its own, and a consumer that binds inputs to
header columns by name executed `materialize` against the other type.

Which consumer trips first depends on the plan. With the text index the direct
read reaches it first and raises `NOT_FOUND_COLUMN_IN_BLOCK`; without it lazy
FINAL rewrites the filter onto the read it builds for the deduplicating keys and
aborts with the reported logical error. Both arms need the predicate in PREWHERE
and WHERE, and the text index arm needs no non-default setting.

Arms A and R are the two type directions of the text index reader, L is lazy
FINAL, and each is paired with a control that disables only its own consumer, so
a wrong row count cannot pass as a fix. B, M and S are single-predicate and
matching-type controls.
The arms pin the optimizer gates they depend on, because CI randomizes
`query_plan_direct_read_from_text_index` off in about 5% of runs and randomizes
`index_granularity`, which can make lazy FINAL fall back to ordinary FINAL. Two
plan assertions pin that each optimization is still in the plan, so an arm cannot
pass by declining the consumer it is written for.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, all findings resolved)

This PR now also covers two carriers reported by the AST fuzzer on #110321. Before pushing I
ran a cold review plus an independent second-model review of the whole diff, twice. Round 1
bounced the change back for a fix; round 2 is clean. Verdicts below.

Round 1 — one major, fixed

⚠️ The new test's optimizer arms could pass without the optimizer running.
query_plan_direct_read_from_text_index is randomized off in about 5% of CI runs
(tests/clickhouse-test:1772), and it is ANDed into the direct-read gate at
QueryPlanOptimizationSettings.cpp:216. In those runs the rewrite never happens, the defect is
never reached, and the arm returns the right row count on broken code. Arm L had the analogous
hole via the min_filtered_ratio_for_lazy_final fallback (default 0.5) combined with randomized
index_granularity. My cold review and the second model landed on this independently.

Fixed by pinning query_plan_direct_read_from_text_index = 1 on the text-index arms and
min_filtered_ratio_for_lazy_final = 0 on the lazy-FINAL arms, and by adding one plan-liveness
assertion per consumer in the SELECT count() > 0 FROM (EXPLAIN ...) WHERE explain ILIKE ...
form. The pin was not a theoretical concern: with the setting off, that arm returns 32 on the
unfixed binary, i.e. green on broken code.

Both new assertions were checked to be real oracles, each with a negative control: the text-index
token is 1 with the setting on and 0 with it off, and the lazy-FINAL token likewise. An
assertion that cannot return 0 is not an assertion.

Round 2 — clean

⚠️ One prescribed assertion had to move, and that is the fix working. The plan placed the
__text_index_idx assertion on the diverging-type arm. It returns 0 there, because once the
pass-through keeps the destination's type the haystack becomes CAST(str AS ...), and
hasIndexForColumn (MergeTreeIndexConditionText.h:192) matches a column name, so the direct
read declines. Confirmed independently by force_data_skipping_indices = 'idx' raising
Code: 277 INDEX_NOT_USED there, and the decline already happens before this change on the
single-predicate shape. The assertion sits on the matching-type arm, where the direct read really
fires, with a comment in the test explaining why the diverging arms cannot carry it.

💡 The description overstated the provenance of one carrier. The AST fuzzer hit the lazy
FINAL abort; the text-index failure came out of reproducing it locally. Corrected in the
description.

❌ Nothing.

Noted, not blocking

  • The diff is test-heavy (664 added test lines against 57 added source lines across 4 files).
    Every arm fails on the merge base, so nothing here is decorative, but I am flagging it since it
    is the obvious objection.
  • No arm uses the fuzzer's own type pair (a Buffer array column against a scalar destination
    column). A scalar pair does not reach the lazy-FINAL carrier, so this is fidelity only.
  • The relationship links stay inside the leading HTML comment, which is where the upstream
    PULL_REQUEST_TEMPLATE.md puts them. The two links that matter for this change are also in the
    visible description text.

Session id: cron:clickhouse-review-slot-10:20260811-051800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM buf PREWHERE hasAllTokens(str,'bar') WHERE hasAllTokens(str,'bar') over a Buffer declaring Array(LowCardinality(String)) above a ReplacingMergeTree destination declaring Array(String) with INDEX idx (str) TYPE text(tokenizer = array). Fails on demand at all-default settings, no randomization needed. The lazy FINAL arm additionally needs query_plan_optimize_lazy_final = 1, FINAL, and two overlapping parts.
b Root cause explained? Yes. The Buffer was created with no column list, so it kept a structure its destination no longer has. StorageBuffer::read prepends a converting prefix to each forwarded filter, and that prefix converted every output of the filter DAG, including the bare pass-through of the destination's own column. The read then advertised the Buffer's type while the destination produces its own, and consumers bind DAG inputs to header columns by name with no type check (ActionsDAG::updateHeader, mergeNodes), so a materialize node resolved for one type executed against the other.
c Fix matches root cause? Yes. This branch converts only the predicate and restores a pass-through output to the merged DAG's own destination-typed input. Not a band-aid: guarding the abort site instead is #109747, which leaves the type drift in place.
d Test intent preserved / new tests added? Yes. This commit only adds 04849_buffer_converted_column_text_index_and_lazy_final; nothing existing is weakened or removed. The branch's three sibling tests (04741, 04743, 04812) re-run green.
e Both directions demonstrated? Yes, on this branch's own tree. Arms A and R go NOT_FOUND_COLUMN_IN_BLOCK to 32, arm L goes Unexpected return type from materialize (abort, exit 134) to 32, and the control arms return 32 on both binaries. Build IDs asserted distinct between the two builds. Each arm pins the optimizer gate it depends on, and two EXPLAIN assertions pin that the optimization is in the plan; both were shown to return 0 with their optimization forced off, so neither can pass vacuously.
f Fix is general across code paths? The enumerated consumers of this invariant are the plan header, the Parquet reader, the second converting prefix, the text index direct read and lazy FINAL. The first three were already covered by this branch; this commit adds the last two, which the original enumeration missed.
g Fix generalizes across inputs? Both type directions are covered (Array(LowCardinality(String)) over Array(String) and the reverse), with matching-type and single-predicate controls. Measured and recorded rather than asserted: a scalar String / LowCardinality(String) pair does not reach the lazy FINAL consumer, and the divergence must be in the Array element type.
h Backward compatible? N/A for this commit: test-only, no setting default, no serialization change, no SettingsChangesHistory entry. The branch carries a single user-facing Bug Fix changelog entry.
i Invariants and contracts preserved? N/A for this commit: no source change. The tree is identical to the branch head in src/, and it rebuilds to the same Build ID.

Session id: cron:clickhouse-impl-slot-40:20260811-045900

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aeecd6e

CI is fully finished on this head and there are no failures to own.

Check / test Reason Owner / fixing PR
(none) - no failed checks on this head
Sync - CH Inc sync (private, not actionable)

175 leaf jobs: 156 OK, 19 skipped, 0 failed, 0 dropped. The praktika report for this head
(result_pr.json) is top-level OK, and every skip carries an explicit reason (not labeled with 'pr-performance', reused from cache, no integration tests updates, Not affected by the changed files and not required), so this is a real run with coverage rather than a
dropped matrix. CIDB reports no FAIL/ERROR rows for this commit.

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

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR only changes StorageBuffer::read, which now converts just the predicate when row-level and PREWHERE filters are forwarded to a Buffer's destination table. The rest of the diff is new tests. None of the benchmark queries read from a Buffer table, so the flagged improvements cannot come from this change: clickbench Q5 at -10.1%, and tpch_adapted_1_official Q1 at -18.5% and Q7 at -17.3%. All three are downgraded to not_sure. The two TPC-H queries already have a noisy history on master, and CPU time barely moved on any of the three, which also points to run-to-run variance rather than less work being done.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 5 not_sure 257 231 -10.1% <0.0001 The PR only changes how StorageBuffer forwards filters into its destination read. ClickBench reads a plain MergeTree table, so this code never runs and the -10.1% shift is not attributable to the PR.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 53 -18.5% <0.0001 TPC-H tables are not Buffer tables, so the changed filter-conversion path in StorageBuffer::read is never reached. This query has a noisy history and its measurements were very spread out, so the -18.5% is not a PR effect.
⚠️ 7 not_sure 81 67 -17.3% <0.0001 The only code change is in StorageBuffer::read, which TPC-H Q7 does not execute. The -17.3% shift matches this query's noisy history, not anything in the diff.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: bce0d921-ff0f-4dc8-897d-962191a07b6c
  • MIRAI run: 14a6e636-7bfe-411f-a6fc-269fc07e5766
  • PR check IDs:
    • clickbench_2855472_1790921327
    • clickbench_2855485_1790921327
    • clickbench_2855491_1790921327
    • tpch_adapted_1_official_2855502_1790921327
    • tpch_adapted_1_official_2855528_1790921327
    • tpch_adapted_1_official_2855543_1790921327

@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

@alexey-milovidov alexey-milovidov 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.

Acceptable.

@alexey-milovidov alexey-milovidov self-assigned this Sep 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 22, 2026
…alyzer arms

Master moved under this branch in two ways that made its own tests fail in the
merge queue. Neither is a defect in this change.

optimize_functions_to_subcolumns rewrites a predicate over a Map to read the
keys subcolumn. A destination that declares the column as the equivalent
Array(Tuple(...)) has no such subcolumn, so 04741 died with
NOT_FOUND_COLUMN_IN_BLOCK on an arm that is only a control here. That
reproduces byte-identically on a pristine master binary, so it is independent
of this change, and ClickHouse#113231 fixes it. The setting is randomized by the test
runner too, so the test pins it and stays on the forwarded filter's own
conversion, which is what it is for.

enable_analyzer can no longer be set to 0: the analyzer is mandatory since
v26.9 and such a query returns SETTING_CONSTRAINT_VIOLATION. The arms that
repeated an assertion under the old analyzer go away with their reference
lines.

The two-filter arm on the MergeTree destination asserted rows only, and the
planner can apply a row policy above the read instead of forwarding it into
the read, which returns the same rows through the single-PREWHERE path. It now
asserts the plan the way the File and URL tests already do.

All four tests still fail on a pristine master binary, which is what makes them
witnesses: 04741 aborts it with 'Bad cast from type DB::ColumnMap to
DB::ColumnArray', 04743 returns TYPE_MISMATCH, 04812 and 04849 kill the server.
@groeneai

Copy link
Copy Markdown
Collaborator Author

The merge-queue failure on this branch was master drift rather than a defect in the change, and it is fixed on e68af8d. Apologies for the noise it caused to the entries behind it.

Two things moved under the branch since it last ran CI on 2026-08-11.

optimize_functions_to_subcolumns now routes a predicate over a Map onto the keys subcolumn. A destination that declares the column as the equivalent Array(Tuple(...)) has no such subcolumn, so 04741's single-PREWHERE control died with NOT_FOUND_COLUMN_IN_BLOCK. That reproduces byte-identically on a pristine master binary containing none of this PR's code, and the WHERE spelling of the same query silently returns 0 rows instead of 2 there, so it is the defect #113231 fixes and I have left it there. Only a MergeTree destination is affected: on File(Parquet) the same query returns TYPE_MISMATCH before this change and the correct rows after it. The setting is randomized by the test runner, so the test pins it and stays on the forwarded filter's own conversion, which is what it is for.

enable_analyzer can no longer be set to 0, so the arms that repeated an assertion under the old analyzer are gone together with their reference lines.

I also added a plan assertion to the two-filter arm on the MergeTree destination. It asserted rows only, and a row policy applied above the read instead of forwarded into it returns those same rows through the single-PREWHERE path, which works either way; 04743 and 04812 already assert this for the File and URL readers.

All four tests still fail on a pristine master binary, which is what makes them witnesses: 04741 aborts it with Bad cast from type DB::ColumnMap to DB::ColumnArray, 04743 returns TYPE_MISMATCH, and 04812 and 04849 kill the server. On this head they are 400 for 400 green across 50 randomized and 50 plain runs each, and the pinned setting was verified to hold under every draw.

The src/Storages/StorageBuffer.cpp change itself is untouched by all of this: its changed lines are byte-identical to the reviewed head, so only tests moved.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e68af8d

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
Performance Comparison (arm_release, master_head, 1/6) CI harness, not this diff: the shard is red only on 1 confirmed regression(s) on the performance dashboard; the dashboard verdict gate reds unrelated PRs with a regression that does not reproduce when the same head is re-run #121090 (mine, open), with #121189 (mine, open)
Performance Comparison (arm_release, master_head, 2/6) same gate: 1 confirmed regression(s) on the performance dashboard #121090 (mine, open), with #121189 (mine, open)
Performance Comparison (arm_release, master_head, 4/6) same gate: 2 confirmed regression(s) on the performance dashboard #121090 (mine, open), with #121189 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

The discriminator is in the shard reports themselves: shards 3/6, 5/6 and 6/6 of this same run
also report too long queries and are GREEN, so the criterion that failed 1/6, 2/6 and 4/6
is the dashboard regression verdict alone. 131 checks succeeded, 39 were skipped.
Mergeable Check and PR are the praktika aggregators, not separate failures.

Session id: cron:our-pr-ci-monitor:20260923-163416

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 24, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 24, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 27, 2026
Comment thread src/Storages/StorageBuffer.cpp Resolved
…forwarded filter

Restoring a pass-through output to the destination-typed input left the
converting node in `merged.nodes`, and `ExpressionActions` executes every node
of the DAG, so the cast still ran. Call `removeUnusedActions` again after the
restoration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into ClickHouse:master with commit f45b61d Oct 2, 2026
149 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 3, 2026
ClickHouse#113900 rewrote the forwarded-filter prefix in `StorageBuffer::read` so that an
output which merely passes a destination column through keeps the destination's
type, and only the predicate is converted. That makes this branch's previous
two-filter handling (a per-invocation converting DAG plus a set of parents
converted by an earlier filter) unnecessary: with every pass-through at the
destination type, consecutive forwarded filters agree on the parent's type by
construction.

Resolution, on top of ClickHouse#113900's shape:
- keep master's single converting DAG, with the derivable subcolumns excluded
  from its target (the destination cannot produce them);
- a parent kept alive for a derivable subcolumn is registered as a pass-through
  output, so ClickHouse#113900 re-points it to the destination-typed input instead of the
  converted one, and it is converted once, after the read, together with the
  subcolumn extraction.

Also drop the `enable_analyzer = 0` row from the test: the old analyzer is
removed on master.
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

The AMBIGUOUS_COLUMN_NAME regression above (#124581) is fixed in #124632.

alexey-milovidov pushed a commit to nihalzp/ClickHouse that referenced this pull request Oct 9, 2026
…s name

A Buffer whose column type differs from its destination forwards PREWHERE and
row policies with a converting prefix, `_CAST(v, 'Buffer type') AS v`, in
front of the filter. Since ClickHouse#113900 the pass-through output `v` is the
destination-typed input again, while the conditions still read the conversion,
so the forwarded DAG has two reachable nodes named `v` with different types.

`tryBuildPrewhereSteps` hands columns from one step to the next by name. With
two conditions on `v`, step 0 then exports both the conversion (for step 1)
and the input (for the final output) as `v`, and building its actions throws
`AMBIGUOUS_COLUMN_NAME`. When `v` is not selected, the Parquet reader instead
binds the later step's `v` to the stored column and returns wrong rows, for a
row policy as well as for a PREWHERE.

Return `false` from `tryBuildPrewhereSteps` when
`ActionsDAG::hasInputNameShadowedByComputedNode` holds, so the MergeTree,
Memory and Parquet readers evaluate such a PREWHERE in one step, which by the
function's own contract gives the same result. Lazy materialization already
declines its name-based rewrite for the same shape. Ordinary queries do not
produce it (their computed nodes are `__tableN.*` or expression-named), so
their PREWHERE is still split.

Closes ClickHouse#124581

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants