Repository navigation
Keep a Buffer's forwarded filter from retyping the destination's own columns - #113900
Conversation
…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.
Internal second-model review (click to expand)Two review rounds by a second model, independent of the author. Round 0 reviewed Round 0: the code I enumerated the invariant carriers independently before reading the author's ❌ The tests could not force the carrier they exist to test. Three arms of ❌ Every arm asserted only rows, so losing the pushdown entirely would go 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
💡 Recorded for a future reader, no change requested. My round-0 note reached the 💡 The shell probe sends the client's stderr to Verdicts: 3 agreed and fixed, 4 disagreed with evidence and terminal, 1 Gate spend across the PR: $123.96. Session id: cron:clickhouse-review-self-slot-58:20260807-224700 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260807-205620 |
|
cc @azat @KochetovNicolai, could you review this? |
|
Workflow [PR], commit [39a7eef] Summary: ✅
AI ReviewSummaryThis PR narrows the forwarded-filter conversion in Final Verdict
LLVM Coverage ReportMeasured on commit 39a7eef.
Changed lines: Changed C/C++ lines covered: 57/59 (96.61%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+17.56 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 13 s compile time in total, 7 of them have a recent master baseline. |
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]>
CI finish ledger - 661de28Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
On the one row: the abort is 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]>
Internal second-model review (2 rounds, all findings resolved)This PR now also covers two carriers reported by the Round 1 — one major, fixed
Fixed by pinning Both new assertions were checked to be real oracles, each with a negative control: the text-index Round 2 — clean
💡 The description overstated the provenance of one carrier. The ❌ Nothing. Noted, not blocking
Session id: cron:clickhouse-review-slot-10:20260811-051800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260811-045900 |
CI finish ledger - aeecd6eCI is fully finished on this head and there are no failures to own.
175 leaf jobs: 156 OK, 19 skipped, 0 failed, 0 dropped. The praktika report for this head Session id: cron:our-pr-ci-monitor:20260811-113000 |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (1 of 43)
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_officialFlagged queries (2 of 22)
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
|
…-passthrough-destination-type
…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.
|
The merge-queue failure on this branch was master drift rather than a defect in the change, and it is fixed on Two things moved under the branch since it last ran CI on 2026-08-11.
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- All four tests still fail on a pristine master binary, which is what makes them witnesses: The |
CI finish ledger - e68af8dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The discriminator is in the shard reports themselves: shards 3/6, 5/6 and 6/6 of this same run Session id: cron:our-pr-ci-monitor:20260923-163416 |
…-passthrough-destination-type
…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]>
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.
|
@groeneai @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
…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]>
Changelog category (leave one):
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 aBuffertable whose destination declares a column with a different but convertible type and a forwarded filter references that column: with a row policy and the implicitWHEREtoPREWHEREmove, and underquery_plan_optimize_lazy_final. The same cause made such a read fail withNOT_FOUND_COLUMN_IN_BLOCKwhen a text index on that column was read directly and the predicate appeared in bothPREWHEREandWHERE, fail withTYPE_MISMATCHover aURL(Parquet)destination, and abort withBad cast from ColumnMap to ColumnArraywhen a row policy and an explicitPREWHEREboth referenced it.Description
Declaring a
Buffercolumn differently from its destination is supported:StorageBuffer::supportedPrewhereColumnssays so becauseread()prepends aconverting prefix to a forwarded filter.
That prefix converted every output of the filter's DAG, and
buildFilterInfoalso 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:
PREWHEREfeeds a Buffer-typed column intoa destination-typed
materializenode;NOT_FOUND_COLUMN_IN_BLOCK, at default settings);deduplicating keys;
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 holdtwo types at once; that case aliases the predicate, as
StorageMerge::RowPolicyData::initalready does.Validated on debug builds of this branch and of its merge base, at
enable_analyzer1 and 0: 13 witness shapes fixed, 10 controls unchanged,EXPLAINbyte-identical on every non-diverging control, and no regression in a607-test row-policy/prewhere/buffer slice. The lazy FINAL consumer is what the
AST fuzzerhit on #110321; the text index one came out of reproducing it. Eacharm of the new
04849test has a control disabling only its own consumer, so awrong row count cannot pass.
Supersedes #113624, whose tests are carried over here.
Workflow [PR]
Sync PR [sync-upstream/pr/113900]
Version info
26.10.1.1315-master(included in26.10and later)