Skip to content

Fix wrong subcolumn value and row loss over a Buffer table with a mistyped destination - #113231

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-derivable-subcolumn-type-mismatch
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-derivable-subcolumn-type-mismatch

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 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 wrong results and silent row loss when reading a subcolumn (for example arr.size0 or c.null) from a Buffer table whose declared column type differs from the destination table's. Such a subcolumn is now computed from the converted parent column instead of being filled with a default value or causing the destination table to be skipped.

Description

Related: #110812

On 26.8.10.6, SELECT sum(length(arr)) FROM buf over a Buffer declaring arr Array(UInt8) above a destination column arr String returns 0 instead of 3, on default settings.

A Buffer whose declared column type differs from its destination's converts the parent column correctly but mishandles any subcolumn of it: a subcolumn-only select loses the destination's rows, and selecting both returns a correct parent beside a defaulted subcolumn. optimize_functions_to_subcolumns folds length(arr) into arr.size0 by default, hence the result above. Nullable.null, Tuple and Map subcolumns are affected.

Two root causes, both fixed:

  1. StorageBuffer::read treats "the destination cannot resolve this name" as "the column is absent" rather than "derivable from a parent the Buffer converts anyway", so the name is either erased from the column intersection (emptying it, which skips the destination) or defaulted by addMissingDefaults, which runs before the conversion. The fix reads the parent, keeps derivable names out of the defaults list and both conversion targets, and supplies them from an extraction DAG over the converted block.

  2. A forwarded PREWHERE or row-level filter consumes the parent, and a column matched to a filter DAG's input is dropped unless it is also an output, so the derivation read back a fabricated default. Each derivable parent is now kept as a pass-through output of the merged filter actions, so, like the other pass-throughs since Keep a Buffer's forwarded filter from retyping the destination's own columns #113900, it leaves the read at the destination's type and is converted with the rest of the block. The loop is inert when nothing is derivable.

Two limitations remain. An explicit PREWHERE on the derived subcolumn still fails with NOT_FOUND_COLUMN_IN_BLOCK, though a plain WHERE on it is fixed. Over a Distributed destination there is no post-read conversion point, so a requested subcolumn now raises an explicit NOT_IMPLEMENTED naming the column rather than an opaque UNKNOWN_IDENTIFIER.

Measured on master 3ade111d (contains #113900) vs. with the fix (same script, same machine)

Fixture: destination arr String, buffer arr Array(UInt8).

query master with fix correct
SELECT count() FROM (SELECT arr.size0 FROM buf) 0 1 1
SELECT arr, arr.size0 FROM buf (optimize_functions_to_subcolumns = 0) [1,2,3] 0 [1,2,3] 3 ... 3
SELECT sum(length(arr)) FROM buf (default settings) 0 3 3
SELECT k, arr.size0 FROM buf PREWHERE has(arr, 2) 1 0 1 3 1 3
SELECT k, arr.size0 FROM buf WHERE arr.size0 = 3 no rows 1 3 1 3
SELECT m.keys, m.values FROM mbuf PREWHERE mapContains(m, 'k') [] [] ['k'] [7] ['k'] [7]
SELECT arr, arr.size0 over a Distributed destination Code: 47 Code: 48 NOT_IMPLEMENTED not supported

Unchanged: equal types, destination missing the column entirely (defaults and warning preserved), a
mismatch on an ordinary column with no subcolumn requested, a dynamic JSON subcolumn PREWHERE, and
a matched-types Buffer-over-Distributed subcolumn query.

A row policy and a PREWHERE both over the same parent was a separate defect (wrong values, and a debug-build abort over a Map buffer), fixed on master by #113900. The restored parent takes its pass-through path, and its tests pass with this change.


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

A Buffer table whose declared column type differs from its destination's
converts the parent column correctly but mishandles any requested subcolumn
of it. StorageBuffer::read treats "the destination cannot resolve this name"
as "the column is absent" rather than "it is derivable from a parent the
Buffer converts anyway", which produces two distinct wrong behaviours.

The name is erased from columns_intersection, so a subcolumn-only request
empties the intersection and the destination is not read at all: with rows in
both the destination and the in-memory buffer, only the buffer's rows come
back. When the parent is also requested the destination is read, but
addMissingDefaults runs before makeConvertingActions (the inverse order of
StorageMerge), so the subcolumn is filled with a type default before the
parent is converted, and is never revisited.

Both shapes are reachable without any subcolumn syntax: at the default
optimize_functions_to_subcolumns = 1 the analyzer folds length(arr) and
empty(arr) into arr.size0, so with a destination arr String, a Buffer
arr Array(UInt8) and one row '[1,2,3,4,5,6]', SELECT sum(length(arr))
returns 0 instead of 6. Nullable.null, Tuple elements, Map.keys/.values and
nested arrays behave the same way.

The parent is now read from the destination even when only the subcolumn was
requested, derivable subcolumn names are excluded from the defaults list and
from both conversion targets (addMissingDefaults would zero the name, and
makeConvertingActions would throw THERE_IS_NO_COLUMN for a result column with
no matching input), and the subcolumn is supplied by merging an extraction
DAG into the existing conversion step. The extraction DAG is constructed from
the post-conversion block, where the parent already has the Buffer's declared
type and therefore exposes the subcolumn; built from the pre-conversion plan
header it would come back empty and the fix would silently do nothing, so
that case now throws instead. addMissingDefaults and
createSubcolumnsExtractionActions are used unmodified.

Two limitations are deliberately left. A filter predicate on the derived
subcolumn still fails with NOT_FOUND_COLUMN_IN_BLOCK: restricting
supportedPrewhereColumns would reject valid dynamic JSON/Dynamic subcolumn
PREWHERE queries, which cannot be enumerated. Over a Distributed destination
the query runs above FetchColumns with no post-read conversion point, so a
requested subcolumn now raises an explicit NOT_IMPLEMENTED naming the column
instead of an opaque UNKNOWN_IDENTIFIER; length(arr) returning the string
length there is a separate root cause and is unchanged.

One consequence of no longer skipping the destination: subcolumn-only queries
now undergo the same pre-filter parent conversion that parent-requesting
queries already undergo on master, where that conversion is merged into the
row-policy actions. On a fixture whose policy-hidden row holds an
unconvertible value, such a query now fails with the same error master
already returns for SELECT arr on that fixture. Both are errors, never a
wrong answer, and deferring the conversion past the filter would restructure
that block for every Buffer query.

Related: ClickHouse#110812
Three rows of 04709 asserted values that pristine master already produces, so
they would have survived a full revert of the fix and proved nothing.

The Map fixture declared the destination column as a Map too, so the destination
resolved m.keys and m.values through its own type system and tryGetDerivableSubcolumn
returned early. The destination parent is now Array(Tuple(String, UInt64)), which
casts to the Buffer's Map but exposes no such subcolumn, so the derivation runs.
The expected values are unchanged, since they were already the correct answer;
what changes is that master no longer produces them.

The Nullable carrier is genuinely affected but its value oracle cannot move: the
correct .null for a non-NULL row is 0, exactly the type default master fills in,
and a non-zero value would need a NULL in a destination column that is
non-Nullable by construction. A row-count assertion is added beside the existing
row, which loses its only row on master. The value row is kept as a guard.

The Distributed refusal asserted only the error code, but StorageBuffer::read
throws an unrelated NOT_IMPLEMENTED on the same engine combination, so a
regression that relocated the failure there would still have passed. Since
TestHint has no message-matching form, the message is now asserted from a
companion shell test, which also fails if the diagnostic stops naming the column.

Every row was measured on both binaries: nine differ and six are identical by
design. Both tests pass 50 randomized runs at -j1 and at -j4, so neither needs a
no-parallel tag.

Related: ClickHouse#110812
…mn admission

Master `e62b2d51` (`Admit subcolumns into PREWHERE only for storages that can
resolve them`) gave `StorageBuffer` a `supportedPrewhereColumns` contract that
deliberately admits type-mismatched columns, plus
`supportedPrewhereColumnsIncludeSubcolumns` forwarding to the destination. A
plain `WHERE` on a derived subcolumn of a mistyped `Buffer` is therefore now
auto-moved into `PREWHERE`, which is the path this change interacts with.
A subcolumn derived after the destination read needs its parent column in the
read's output block. StorageBuffer::read requests the parent, but when the
forwarded PREWHERE or row-level filter consumes it the parent is neither an
input nor an output of the filter's own ActionsDAG, so ActionsDAG::updateHeader
drops it: it matches a DAG input, is marked for removal, and is re-inserted only
if it is also an output. addMissingDefaults then fabricates a type default for
the now-absent parent, and the extraction step casts that default instead of the
data. On a fixture where every array is valid that surfaced as
CANNOT_READ_ARRAY_FROM_TEXT, and for a Map parent as a silently empty result,
while the parent's own value converted correctly in the same row.

Restore each derivable parent as an output of the merged filter actions before
trimming them, mirroring restoreDAGInputs in ReadFromMergeTree, which does the
same for sorting-key, merging-params and sampling columns; addReadColumn there
documents this exact mechanism. Deduplicate on both sides: two subcolumns can
share one parent, and the planner already adds selected read columns to the
PREWHERE outputs, so an unconditional append would duplicate a column in the
read's header. tryRestoreColumn returning false means the parent is nowhere in
the DAG, which would silently reintroduce the bug, so it throws instead.

The loop body never runs when no subcolumn is derivable, and EXPLAIN header is
byte-identical to before the change for a Buffer whose types match. The
previously wrong shapes now return the correct value: a filter consuming the
parent, a plain WHERE on the derived subcolumn, a row policy on a parent
expression, and two subcolumns of one parent.
…filters

StorageBuffer::read forwards the row-level filter and the PREWHERE filter
through merge_converting_prefix, which is therefore invoked twice, and both
merged DAGs run as consecutive PrewhereExprSteps over the same block. Keeping
the parent alive in both prefixes made each of them carry the converting half's
CAST as an output, so the first step already emitted the parent at this table's
type while the second step's CAST was still bound to the destination type at
build time. Reading a derivable subcolumn with both a row policy and a PREWHERE
present then failed with CANNOT_READ_ARRAY_FROM_TEXT, including on shapes that
returned the correct value before the parent was kept alive at all.

Track which parents an earlier filter already converted and re-declare those
source columns at this table's type for the next invocation, so
makeConvertingActions finds the types equal and adds no CAST node. The
conversion happens exactly once per parent regardless of how many filters are
forwarded, and the restore itself is unchanged because suppressing it in the
first prefix makes the second prefix miss a column it needs.

The set stays empty when no subcolumn is derivable, so a mistyped column that no
filter references still loses both its output and its input to
removeUnusedActions and is converted only after the read, as before.

Tests cover both filters together across the parent-consuming, ordinary,
matched-types and no-subcolumn-requested shapes, asserting the parent beside the
subcolumn plus a row count rather than an aggregate, since a bare sum cannot
distinguish row loss from a defaulted value.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 review rounds, 2 replans; click to expand)

Each round: an independent review by a model that did not write the change, plus an independent
second-model gate pass. Rounds 1-3 raised issues that were fixed; round 4 is clean on the
independent review of src/ and produced 2 gate findings, both disagreed with source evidence
below. No blocker is outstanding.

Round 4 (ff0c980) - agreed and fixed

# Finding Verdict
⚠️ The scope statement was narrower than what was measured. An earlier draft said the residual two-filter exposure was "errors, never a wrong answer". While attributing an unrelated server death I reproduced that pre-existing shape ABORTING a pristine-master debug build (Bad cast from type DB::ColumnMap to DB::ColumnArray, exit 134) on a Map(String, UInt64) buffer over an Array(Tuple(String, UInt64)) destination, with a row policy and a PREWHERE both on the parent. This change makes that shape answer correctly. AGREE, fixed. The description now states it; the disclosure strengthens the PR rather than weakening it.
⚠️ Three limitations were cited with no tracking behind them. AGREE, fixed. The two scoped-out carriers, the pre-existing two-filter defect, and the note that this only partly discharges #110844 are each tracked now; the two-filter one is raised in priority because it can abort a debug build.
💡 The set recording which parents an earlier forwarded filter already converted carries an undocumented ordering invariant. AGREE, noted. It is correct because every invocation restores every derivable parent, so the set saturates after the first call, and because the filters execute in construction order. That reasoning is in the commit message rather than a source comment.

Round 4 - disagreed, with evidence

❌ "The new NOT_IMPLEMENTED guard is over-broad: a local MergeTree destination can reach it
too."
MergeTreeData::getQueryProcessingStage returns a stage above FetchColumns only inside
if (!allow_experimental_analyzer), and that setting defaults to true. Turning it off is not
sufficient either: canUseTaskBasedParallelReplicas refuses when the analyzer is off while
parallel_replicas_only_with_analyzer is set, which also defaults to true. So the throw needs two
non-default settings flipped together plus parallel replicas configured. It is also not a
behaviour change for the gated shape: above FetchColumns the subcolumn is already erased from the
column intersection and the post-read conversion is already skipped, so that path already failed.
Naming the column in an explicit error is strictly more informative, and the companion .sh test
asserts the name appears.

❌ "A row policy whose predicate references the derived subcolumn is a new unsupported carrier."
It is the carrier this description already lists, reached through a different clause. A policy on
the subcolumn becomes a row-level filter through supportedPrewhereColumns admitting it by
name-in-storage, which is the identical admit-then-fail mechanism as the explicit PREWHERE
spelling. Master fails on it as well: the subcolumn is erased from the intersection there too
while the forwarded filter still requires it, and the destination resolves filter inputs against
its own snapshot. The failure is fail-closed, raised while building the read before any row is
produced, so no policy is bypassed and no wrong value is returned. Deriving the subcolumn before
the filter would restructure the filter-forwarding block for every Buffer query, which is a
separate root cause and is tracked as such.

Earlier rounds, in brief

Round 1 (5b8fd23) raised 3 test-liveness issues, all fixed with no src/ change: the Map case
never reached the new code (both tables declared m as Map, so the destination resolved the
subcolumns itself and the row survived a full revert); the Nullable.null oracle could not move,
because the correct .null for a non-NULL row is the same 0 a default supplies; and the
Distributed refusal asserted only the error code while StorageBuffer::read throws a second
unrelated NOT_IMPLEMENTED on the same engine combination.

Rounds 2 and 3 each found one blocker that was a REGRESSION invisible against master alone, which
is why every later measurement carries a third arm. Round 2: a semantic conflict with a merged
upstream commit that git merge-tree reports as clean. Round 3: the filter-forwarding lambda is
invoked once per forwarded filter and both results run as consecutive steps over one block, so the
round-2 fix made the first step emit the parent already converted while the second step's cast was
still bound to the source type.

Validation - the new rows were A/B'd against the immediately preceding commit, not only
against master: eight shapes return the correct value here and fail with
CANNOT_READ_ARRAY_FROM_TEXT on that prior commit, and each has a reference row. 100/100
randomized runs of both tests, single-process and self-parallel, so neither needs a no-parallel
tag. The Buffer suite passes except three tests that fail identically on a pristine-master
control. Several candidates were refuted from source rather than by argument and so never reached
the author, including one that reads like a regression but is a fixture artifact: one measurement
arm ran against a leftover same-named table, which its own error message reveals by naming a
different value type than the script creates.

Session id: cron:clickhouse-review-slot-8:20260804-035400

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, for both root causes, and wrong on every run with no randomization or timing involved. Cause 1 (clickhouse local, no server): destination arr String, buffer arr Array(UInt8). SELECT count() FROM (SELECT arr.size0 FROM buf) returns 0 (want 1), SELECT arr, arr.size0 FROM buf returns [1,2,3] 0 (want 3), SELECT sum(length(arr)) FROM buf returns 0 on default settings. Cause 2, same fixture: SELECT k, arr.size0 FROM buf PREWHERE has(arr, 2) returns a wrong 1 0 on master, and CANNOT_READ_ARRAY_FROM_TEXT on a build carrying only the cause-1 fix, on a fixture where every array is valid. Cause 3, on a real server (a row policy is required, so clickhouse local cannot express it): with CREATE ROW POLICY ... USING k = 1 TO ALL active, SELECT k, arr.size0 FROM buf PREWHERE k = 1 returns a wrong 1 0 on master and CANNOT_READ_ARRAY_FROM_TEXT on a build carrying only the cause-1 and cause-2 fixes. Neither filter touches arr: merely having both forwarded filters present is enough.
b Root cause explained? Yes. StorageBuffer::read treats "the destination cannot resolve this name" as "the column is absent" instead of "it is derivable from a parent the Buffer converts anyway". The name is erased from columns_intersection, so a subcolumn-only request empties the intersection and the destination is never read (row loss). When the parent is also requested, addMissingDefaults runs before makeConvertingActions (the inverse of StorageMerge), so the subcolumn is defaulted before the parent is converted, and never revisited. Second root cause: a PREWHERE or row-level filter forwarded to the destination consumes the parent, and ActionsDAG::updateHeader drops a header column that matches a DAG input unless it is also an output, so the parent never comes back from the read; addMissingDefaults then fabricates a type default for it and the extraction casts that default instead of the data. A third cause, found by implementing the second: the converting prefix is built once per FORWARDED FILTER (merge_converting_prefix is invoked for row_level_filter and again for prewhere_info) and both merged DAGs run as consecutive PrewhereExprSteps over the SAME block, so keeping the parent alive in both made the first step emit it already converted while the second step's CAST was still bound to the destination type at build time. The conversion must therefore happen exactly once per parent, not once per filter.
c Fix matches root cause? Yes. The subcolumn is computed from the parent at the point where the parent has already been converted, and its name is removed from the paths that would otherwise zero it. For the second cause the remedy is at the layer that drops the column, not at the symptom: the parent is restored as an output of the merged filter actions, so nothing downstream ever sees it as absent. Suppressing addMissingDefaults instead was rejected because a filter-consumed parent and a genuinely absent one are indistinguishable there, and the latter must keep defaulting. No widened bound, no no-random-* tag, no data reduction, no guard at the symptom site, and no capability downgrade (supportsOptimizationToSubcolumns and supportedPrewhereColumns are untouched). For the third cause, a NameSet records which parents an earlier forwarded filter already converted, and those source columns are re-declared at this table's type for the next invocation so makeConvertingActions finds the types equal and adds no CAST node at all. Suppressing the restore in the first prefix instead was implemented and measured, and is wrong: it turns another shape into NOT_FOUND_COLUMN_IN_BLOCK, because when the parent is also selected the planner puts it on the row-level DAG's outputs by itself.
d Test intent preserved / new tests added? Yes. No existing test weakened or removed; the closest existing test to the blast radius, 00910_buffer_prewhere_different_types (Buffer + PREWHERE + mismatched types), passes unchanged, as do 00126_buffer, 00168_buffer_defaults, 01514_empty_buffer_different_types, 01277_buffer_column_order and the rest of the Buffer suite. New 04709_buffer_subcolumn_of_convertible_parent adds 35 assertions and the companion 04709_buffer_subcolumn_distributed_refusal.sh adds 2. Every row was A/B'd against a pristine master binary, and the second-cause rows also against a build carrying only the first fix, since a row that reddens on master alone would not have caught the second defect. The second cause is covered per filter/select-list combination rather than once: filter consumes the parent with the parent unselected (three spellings, including enable_analyzer = 0), parent also selected, filter not touching the parent, another parent expression keeping it alive, plain WHERE, a row policy whose predicate consumes the parent, and two subcolumns sharing one parent. The discriminators use row counts where row loss is possible, the parent beside the subcolumn, and an independent length() oracle; for Nullable.null, whose correct value coincides with the type default, the witness is the row count instead. No row asserts today's wrong answer. Both tests are parallel-safe with copies of themselves (100/100 at -j4), so neither carries no-parallel. The two-forwarded-filter axis was added for the third cause: parent-consuming policy, ordinary (non-parent) policy, both filters consuming the parent, a matched-types control that must stay a no-op, and a no-subcolumn-requested control that must stay byte-identical to master. Under the randomized-settings runner both tests are 100/100 over 50 iterations each, with no logical error in the server log.
e Both directions demonstrated? Yes, three-way, because the second defect is invisible against master alone: master returns a wrong answer, the first-fix-only build returns an error, and only the final build is correct. The repro from (a) gives 0 / [..] 0 / 0 on the pristine master snapshot and 1 / [..] 3 / 3 with the fix; the PREWHERE has(arr, 2) row gives 1 0 on master, CANNOT_READ_ARRAY_FROM_TEXT on the first-fix-only build, and 1 3 with both. The regression test itself FAILS against a pristine master server, and fails for the right reasons (rows 1 instead of 2, explicit 1 [1,2,3] 0 3 instead of ... 3 3, then NOT_FOUND_COLUMN_IN_BLOCK on the PREWHERE row) and PASSES with the fix. The companion .sh likewise FAILS on a pristine master server (neither NOT_IMPLEMENTED nor arr.size0 is produced) and PASSES with the fix; it also reddens if the diagnostic is genericized or the failure relocates to the other NOT_IMPLEMENTED in StorageBuffer::read. Both runs on Build-ID-verified binaries, with each server's buildId() asserted equal to its binary's. For the third cause the pre-fix arm is essential for the same reason: against master alone the two-filter rows read as "a wrong answer becomes an error", which understates a regression of the cause-2 fix. Measured on three separate servers, each asserting its own buildId(): the whole regression test FAILS with CANNOT_READ_ARRAY_FROM_TEXT on pristine master AND on the pre-fix build, and PASSES only with the complete fix.
f Fix is general across code paths? Yes. The change is at the single point where "unresolvable in the destination" is decided, so all four measured shapes (row loss, defaulted value, PREWHERE throw, above-FetchColumns) are handled together rather than guarded individually. Sibling wrappers were enumerated, not assumed: the Merge carrier is #112975, StorageView/StorageMaterializedView delegate getQueryProcessingStage identically and are deliberately left to their own PR (one root cause per PR), and the in-memory BufferSource half already resolved subcolumns correctly and is untouched. The second fix sits in the single lambda both forwarded filters share, so PREWHERE and the row-level filter are covered by the same lines and both have test rows; it mirrors restoreDAGInputs in ReadFromMergeTree, which does the same for sorting-key, merging-params and sampling columns.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and it is kind-agnostic by construction: it goes through tryGetSubcolumnType/getSubcolumn rather than any hardcoded subcolumn name. Covered in the test: .size0, Nullable.null, a Tuple element, nested Array(Array(UInt8)), Map.keys and .values, LowCardinality inside the parent, both values of optimize_functions_to_subcolumns, a destination missing the column entirely, equal types (fast path), and a Distributed destination both with and without the type mismatch. Filter spellings: has, arrayElement, mapContains, length, a plain WHERE, and a row-policy predicate, under both analyzers.
h Backward compatible? Yes. No setting default changed, no new setting, no serialization or on-disk format change, so no SettingsChangesHistory.cpp entry is required. The behavior changes are wrong-results and row loss becoming correct, plus two error paths: NOT_FOUND_COLUMN_IN_BLOCK becoming a correct answer, and UNKNOWN_IDENTIFIER (or a silently empty result) becoming an explicit NOT_IMPLEMENTED. Nothing that succeeds correctly today changes its answer, which the unchanged rows of the test and the existing Buffer suite verify.
i Invariants and contracts preserved? Yes. columns_intersection still lists only names the destination can actually read: the subcolumn never enters it, only its parent. Every block negotiated with the destination is derived from one shared header that omits derivable names, so addMissingDefaults' required columns and both conversion targets are consistent and no path can reference a name its input lacks. The full sample block remains the plan's output structure, which is what the final union matches against the buffer half. ActionsDAG::merge preserves execution order (conversion first, extraction bound to its outputs by name) and does not drop unconsumed columns. Error paths: an empty extraction DAG throws instead of silently shipping the unfixed behavior, and the above-FetchColumns case throws before any plan is built. The restore is idempotent (it returns early when the name is already an output) and dedupes on both sides, among the requested parents and against the filter's own outputs, which the planner populates for selected read columns, so no column is duplicated in the read's header. A failed lookup throws rather than silently reverting to the fabricated-default bug. No lock or shared state is touched.

Session id: cron:clickhouse-review-slot-8:20260804-035400

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @Avogar, could you review this? A Buffer whose declared column type differs from its destination's converts the parent column but mishandles any subcolumn of it: the name is treated as absent rather than derivable, so a subcolumn-only select empties the column intersection and skips the destination entirely, and selecting both returns a correct parent beside a defaulted subcolumn. Subcolumn syntax is not required, since optimize_functions_to_subcolumns folds length(arr) into arr.size0 by default.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai isn't there a PR already fixing this?

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

No. I rechecked at publication and again now.

The measured table in the description comes from a binary built from master 8c925c5b, which already contains the recent Buffer/subcolumn changes: #111948 (dynamic subcolumns through a Buffer), your #112326 (supportedPrewhereColumns on StorageBuffer) and #102470. Every shape listed there is still wrong on that binary, including sum(length(arr)) returning 0 on default settings.

#112326 is the closest of them. It constrains which Buffer columns may be pushed into PREWHERE and reshapes the forwarded filter merge, but not the ordering this PR fixes: StorageBuffer::read runs addMissingDefaults before makeConvertingActions, so a subcolumn of a mistyped parent is defaulted, or erased from the column intersection so the destination is skipped entirely, before the parent is converted.

#110844 is related in the opposite direction: this PR is its prerequisite, not a duplicate (I noted the partial discharge there in #110844 (comment)). #112975 and #113057 are the same defect class in StorageMerge and StorageView, different files.

If you had a different PR in mind, point me at it and I will close this one.

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

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6216edc]

Summary: ❌

job_name test_name status info comment
Build (amd_fuzzers) FAIL
Build ClickHouse FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
05237_with_expression_alias_scope_descendant FAIL cidb
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05237_time_series_old_metric_family_name_inner_column FAIL cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb
Stress test (arm_asan_ubsan) FAIL
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb

AI Review

Summary

This PR fixes a real StorageBuffer correctness bug around subcolumns of parents whose declared type differs from the destination table: it stops defaulting or dropping derivable subcolumns, preserves the parent through forwarded filters long enough to convert it once, and then derives the requested subcolumn from the converted value. The implementation and new regression coverage line up with that contract, and after reading the current diff plus the prior PR discussion I do not see a remaining blocker or major issue inside the scope this PR explicitly takes on.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ff0c980

CI is fully finished on this head: 175 checks reported, 155 success, 20 skipped, 0 failures.
No failure needs an owner on this run.

Check / test Reason Owner / fixing PR
(none) - -

Session id: cron:our-pr-ci-monitor:20260804-120000

@Avogar Avogar self-assigned this Aug 5, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

The separately-tracked defect that description mentions, a row policy and a PREWHERE both over the same mistyped parent column, now has a fix in #113624. It is independent of this change: it touches only the converting-prefix construction in StorageBuffer::read, adds no subcolumn handling, and its own regression test needs no subcolumn to be requested at all. The two do conflict textually, since both edit the same lambda, so whichever lands second needs a trivial rebase.

@groeneai

Copy link
Copy Markdown
Collaborator Author

One measurement worth adding to root cause 1's description, from re-testing this area on master
184fb1399a91277 today.

Defaulting a derivable subcolumn instead of deriving it is also an access-control consequence, not
only a wrong-value one: a row policy written on such a subcolumn is evaluated against the default.
With a destination that does not support PREWHERE, so the policy stays post-read:

CREATE TABLE dst (k UInt64, arr String) ENGINE = Log;
CREATE TABLE buf (k UInt64, arr Array(UInt8))
    ENGINE = Buffer(currentDatabase(), dst, 1, 100, 100, 10, 100, 10000, 10000000);
INSERT INTO dst VALUES (9, '[4,5]');
INSERT INTO buf VALUES (1, [1,2,3]);
SELECT k, arr, arr.size0 FROM buf ORDER BY k SETTINGS optimize_functions_to_subcolumns = 0;
-- 1  [1,2,3]  3
-- 9  [4,5]    0      <- real size is 2
CREATE ROW POLICY p ON buf USING arr.size0 = 0 TO ALL;
SELECT k FROM buf ORDER BY k SETTINGS optimize_functions_to_subcolumns = 0;
-- 9              <- no row has size 0, so the policy should hide both

I have not built this branch, so I am reporting the master behaviour only, not a before/after. If
that row does come from the same defaulting this PR removes, the changelog entry could say so.

Separately, the limitation this description discloses (an explicit PREWHERE on the derived
subcolumn still failing NOT_FOUND_COLUMN_IN_BLOCK) is tracked. The row-policy spelling and the
implicit WHERE to PREWHERE move fail the same way, at default settings and without subcolumn
syntax, for example SELECT k FROM buf PREWHERE length(arr) = 3 and
CREATE ROW POLICY p ON buf USING has(m.keys, 'a'). Fixing them needs the derivation to run inside
the converting prefix that this PR rebuilds, so it is sequenced behind this one rather than opened
beside it.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Dear @Avogar, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 23, 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 and others added 3 commits October 3, 2026 12:34
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.
The design narration (why the extraction binds to the converted parent,
why derivable names stay out of the conversion targets) is in the PR
description and the earlier commit messages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With optimize_functions_to_subcolumns randomized to 0 the query reads
the parent, which master already converts correctly, so the row passed
without the fix (7 on both). Pinned to 1, master returns 4 and the fix 7.

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

clickhouse-gh Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6216edc63 with master 3761d6851 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4127c6565; 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

5 object files changed (+28.64 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageBuffer.cpp.o 885.34 KiB 913.97 KiB +28.63 KiB (+3.23%)

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, 14 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6216edc

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
Build (amd_fuzzers) / Build ClickHouse not from this PR: the same job is red on master and on 97 PRs in 24h; the clickhouse_fuzzer link outgrows the 2 GiB reach of the small code model #122521 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05237_time_series_old_metric_family_name_inner_column not from this PR: on a parallel replica timeSeriesMetricFamilies(ts_v5) resolves its target as default.ts_v5 (UNKNOWN_TABLE); 10 PRs in 24h on this new job #118518 (external, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database: the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table; 109 PRs in 24h a fix task is created (fix in progress, fixing-PR link to follow here)
Stress test (arm_asan_ubsan) / Cannot start clickhouse-server, Check failed not from this PR: after the restart the MongoDB table e08 left by 05315_mongodb_connection_options_secrets cannot attach because its named collection was already dropped (NAMED_COLLECTION_DOESNT_EXIST); Check failed is the same start failure #123632 (external, open) and #123636 (mine, open)
Mergeable Check, PR rollups, red only because of the rows above #122521, #118518, #123632, #123636 and the fix task above (a fix task is created)

None of these touches the Buffer subcolumn read path this PR changes. All 160 checks completed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261003-183140

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

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-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants