Skip to content

Fix lost rows and wrong defaults when reading a Buffer column its destination lacks - #124296

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:buffer-missing-columns-fill-over-buffer-types
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:buffer-missing-columns-fill-over-buffer-types

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113231

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 reading a Buffer table that has columns its destination table lacks, when the destination is a local table (not Distributed). After the rows were flushed, count() and queries selecting only such columns returned no rows, and the DEFAULT/MATERIALIZED values, Nested array sizes and subcolumns of such columns were computed from the wrong data, so a row read differently before and after the flush.

Description

On 26.8.18.2, SELECT count() from a Buffer table that has a column its destination lacks returns 0 instead of the destination's row count (also 26.3.42.3, 25.3.14.14):

CREATE TABLE dst (k UInt32, arr Array(UInt8)) ENGINE = MergeTree ORDER BY k;
INSERT INTO dst VALUES (1, [1, 2, 3]);
CREATE TABLE buf (k UInt32, arr Array(UInt8), c UInt8 DEFAULT 0, x UInt64 DEFAULT length(arr))
ENGINE = Buffer(currentDatabase(), dst, 1, 10, 10, 1000, 1000, 1000000, 1000000);
SELECT count() FROM buf;   -- 0, expected 1
SELECT k, x FROM buf;      -- 1 0, expected 1 3

For flushed rows, StorageBuffer::read read only the selected columns the destination has, filled the missing ones over that block in the destination's types, then converted. With no selected column in the destination, it skipped the destination.

Like Merge and the MergeTree reader, the fill now reads the default inputs (recursively, kept through a forwarded PREWHERE or row policy; the parent if the destination cannot read subcolumns), a Nested member that is an array in the Buffer for sizes, and the smallest column for the row count. It converts to the Buffer types first, fills only the selected columns and the Buffer-only columns they depend on, and extracts subcolumns from the converted or filled column. A selected subcolumn of a destination column with another type is unchanged (#113231 fixes it). Only FetchColumns reads of a local destination change. The destination columns the fill reads need SELECT; for the row count or Nested sizes it reads a column the user may read, as count() does.

The new test expects each case to read the same before and after OPTIMIZE TABLE flushes the rows. It fails on master and passes here (100 randomized runs). 00910_buffer_prewhere_different_types now returns the destination's rows for a Buffer-only column. 03631_buffer_access_check gains seven partial-grant cases.


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

groeneai and others added 5 commits October 6, 2026 12:03
A Buffer table may have columns its destination lacks. Rows already flushed are
read from the destination and those columns are filled on read, but the read
fetched only the selected columns the destination has, evaluated the defaults
over the destination's types and converted afterwards. So a default whose
inputs were not selected saw type-default constants (`x DEFAULT length(arr)`
read 0), a default over a column the destination stores under another type
used that type (7 instead of 3 for `String` vs `Array(UInt8)`), a selected
subcolumn of a missing column got its own type default, a `Nested` member got
empty arrays, a filter forwarded into the destination read consumed the inputs
before the fill, and a select with no column present in the destination
skipped the destination entirely (`count()` returned 0). The same row read
differently before and after its flush.

The fill now does what `Merge` and the `MergeTree` reader do: read the inputs
of the defaults (recursively, including the Buffer-only columns they depend
on), an array of the `Nested` group for sizes, and the smallest column when
nothing else is read; convert to the Buffer types first; fill only the selected
columns and their Buffer-only dependencies; extract the subcolumns of converted
and filled columns; keep what the fill reads through a forwarded PREWHERE or
row-level filter. This applies at `FetchColumns` over a local destination,
where the Buffer fills the columns itself; a remote destination keeps its read
list. `isSubcolumnOfDefaultValue` moves to `addMissingDefaults` so both
callers share it.

`00910_buffer_prewhere_different_types` now returns the destination's rows for
a select of a column only the Buffer has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fill of a column missing in the destination reads the inputs of its
default and a Nested size source from the destination. Their values reach
the result, so a user granted only the selected columns on the destination
could read another column through a Buffer DEFAULT (x DEFAULT secret).
Check SELECT on those columns like on the selected ones. The smallest
column read only for the row count is not checked, as for count().

03631_buffer_access_check gains a partial-grant case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… read

When no selected column exists in the destination and the fill reads no
input, the destination is read through its smallest physical column only
for the row count. That read had no access check, so a user whose only
destination grant names a column the destination lacks (`SELECT(x)`) could
read the destination's row count through the Buffer.

Gate it with the planner's own rule for a row-count-only read
(`checkAccessRights` with empty `column_names`, as for `count()`): SELECT
must be granted on at least one existing destination column. The column
that is read does not change.

03631_buffer_access_check gains the partial-grant case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sizes

The row count of a row-count-only read and the sizes of a missing `Nested`
member come from a destination column whose value is discarded. Both took
the smallest column of all candidates, ignoring grants. A destination that
re-checks the columns it reads (`Alias`) then denied a user that `count()`
on it admits, and the strict check on the size source denied a user granted
another array of the group, even on a plain MergeTree destination.

Pick the smallest candidate among the columns `checkAccessRights` reports
as readable (with empty `column_names`, as the planner does for `count()`),
falling back to all candidates when none is readable, as the planner does.
The at-least-one-readable-column rule still holds: the call throws.

03631_buffer_access_check gains an `Alias` row-count case and a `Nested`
size-source case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rewrite the fill-inputs comment in StorageBuffer::read as a one-line invariant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 fixed, 1 declined with evidence, 3 nits)
Finding Verdict
❌ Default inputs and Nested size sources were read from the destination without a SELECT check on them, so x DEFAULT secret exposed a destination column the user cannot read AGREE, fixed: the fill checks SELECT on every destination column it reads for its value; 03631_buffer_access_check covers a partial grant
❌ With no selected column in the destination, the row count was read from a destination column without any check, so a grant on a column the destination lacks was enough AGREE, fixed: that read needs SELECT on one column of the destination, as count() does; second 03631 case
❌ The column read for the row count was chosen without the user's grants, so a destination that re-checks the columns it reads (Alias, materialized view) denied a user that count() admits AGREE, fixed: it reads the smallest column the user may read, as the planner does for count(); 03631 Alias case
❌ The array read for the sizes of a Nested group was chosen the same way and then checked, so a grant on another array of the group was not enough AGREE, fixed: same choice; 03631 Nested case
❌ A selected subcolumn whose parent the destination has under another type (arr String vs Array(UInt8), arr.size0) is filled with 0 DISAGREE: unchanged from master here; it is the contract of #113231, which computes it from the converted parent
💡 A default reading a subcolumn of a Buffer-only column that has no default (x DEFAULT y.size0) still fails with NOT_FOUND_COLUMN_IN_BLOCK, as on master Noted: the INSERT fill path rejects the same shape; the remedy belongs in addMissingDefaults
💡 An input that is an ALIAS in the destination is filled from its Buffer default instead of read Noted: intended, an ALIAS has no data the destination read returns
💡 A Buffer ALIAS/EPHEMERAL column named like a destination column, read by a Buffer-only default, takes the destination's value when that column is the one read for the row count Noted: a selected column of that kind already reads the destination's value on master

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05337_buffer_columns_missing_in_destination fails on master (Code: 10 Not found column arr.size0 after the flush) with no randomization; the description's example gives 0 and 1 0 on 26.8.18.2, 26.3.42.3, 25.3.14.14.
b Root cause explained? For flushed rows the read fetched only the selected columns the destination has, filled the missing ones over that block in the destination's types, then converted; with no selected column in the destination it skipped the destination.
c Fix matches root cause? Yes. The fill reads its inputs, converts first, fills only what was selected, and extracts subcolumns, like Merge. No guard, no tag.
d Test intent preserved / new tests added? New test comparing every case before and after OPTIMIZE TABLE. Each of the 10 parts of the change, disabled alone, reddens at least one query.
e Both directions demonstrated? Yes, on Build-ID-checked binaries: master fails, fix passes; 50 + 50 randomized runs, and under the ParallelReplicas and distributed-plan job settings.
f Fix is general across code paths? The only other read-side filler, ReadFromMerge, already works this way. A remote destination keeps its read list (outputs identical to master).
g Fix generalizes across inputs (params/datatypes/wrappers)? Array vs String, Tuple, Nullable, Nested, LowCardinality, JSON paths, MATERIALIZED/ALIAS inputs, lambda parameters, subcolumns, PREWHERE and row policy.
h Backward compatible? (maintainer-approved exception only) No setting or format change. A value the Buffer type cannot hold now throws for its dependent defaults, as it already did for the column itself.
i Invariants and contracts preserved? The output header is the selected columns; the same-structure fast path is unchanged, and the destination columns the fill reads need SELECT like the selected ones; for the row count or Nested sizes it reads a column the user may read, as count() does. Of the 69 stateless tests that create a Buffer, only 00910 (whose reference recorded the skip) and the new test change result versus master.

Session id: cron:clickhouse-impl-self-slot-57:20261006-104400

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79601b8]

Summary: ✅


AI Review

Summary

This PR fixes the local-destination Buffer read path when the Buffer schema is wider than the destination by reading extra destination inputs, converting them to the Buffer types earlier, and filling missing columns/defaults over the converted block. The remaining blocker is that the new helper column used only to carry row count is not preserved through PREWHERE / row-policy filters, so queries that select only Buffer-only columns can still lose all flushed rows once that filter removes the helper column.

Findings

❌ Blockers

  • [src/Storages/StorageBuffer.cpp:681] The filter-preservation logic keeps only fill_support, but not the extra destination column injected solely to give addMissingDefaults the flushed row count. If a PREWHERE or row policy consumes and removes that column, the post-filter header becomes empty again and the later fill still materializes zero rows for queries that select only Buffer-only columns.
    Suggested fix: track the row-count support column when columns_intersection was empty and preserve it through merge_converting_prefix the same way as the existing fill_support columns.
Tests
  • ⚠️ Add a focused stateless case that flushes the rows, selects only a Buffer-only column, and applies either PREWHERE or a row policy on the only destination column being read; the current coverage keeps at least one destination output alive and misses this zero-row regression.
Final Verdict

Request changes: the filter path can still erase the only support column used to keep row count, so flushed rows disappear again for a realistic PREWHERE / row-policy query shape.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 6, 2026
@groeneai
groeneai requested review from azat and pufit October 6, 2026 18:57
@clickhouse-gh clickhouse-gh Bot added the comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... label Oct 6, 2026
Comment thread src/Storages/StorageBuffer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79601b8e7 with master 2b6c3dd9b (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

7 object files changed (+88.67 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageBuffer.cpp.o 913.37 KiB 1001.47 KiB +88.10 KiB (+9.65%)

711 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.88 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.3 s 16.3 s +9.9 s (+156%)
Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2840490

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
AST fuzzer (amd_debug, targeted) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID 2508-32f8) trunk logical error in the DISTINCT-in-order sortedness check (DistinctSortedStreamTransform.cpp:184, leaf ColumnDecimal<Decimal128>), reached by SELECT DISTINCT A FROM m_ok__fuzz_68 ORDER BY ALL DESC NULLS FIRST LIMIT 1023. The fuzzer declared that table as a Buffer with A Decimal(38, 28) over a Merge with A Time64(7) over a Distributed Int64 table. A exists in the destination, so the read takes the existing type conversion, not the fill of missing columns this PR changes. The same assertion fired on 53 other pull requests, 1 master run and 2 release-branch runs in 30 days; this STID suffix is new a fix task is created (investigating at full effort, fixing-PR link to follow here)
PR rollup, red only because of the row above a fix task is created (the same one as above)

All 146 check runs completed and Finish Workflow is green. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261007-010218

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer 'Equal values are not contiguous' (STID 2508-32f8) failure: #124361

groeneai and others added 2 commits November 10, 2026 16:09
…mns-fill-over-buffer-types

# Conflicts:
#	src/Storages/StorageMerge.cpp
Since ClickHouse#103402 a subcolumn inherits the grants of its column, and a grant on
the subcolumn's own name is enough to select it and to run `count()`. Two
reads of the fill still used the rules from before:

- The destination columns the fill reads were checked by their raw names,
  so a user with SELECT(t) on the destination could select `t.a` from the
  Buffer but got ACCESS_DENIED for a Buffer-only column with `DEFAULT t.a`.
  They are now mapped with getColumnNamesForSelectAccessCheck, like the
  selected columns.
- The column read for the row count was chosen among whole columns only, so
  with a grant on `j.a` alone it fell back to a column the user may not
  read, which an `Alias` destination then denied. It is now chosen by the
  planner's own chooseSmallestColumnToReadFromStorage (moved out of the
  anonymous namespace of PlannerJoinTree.cpp), so it is the column `count()`
  reads, including granted subcolumns and dynamic paths.

03631 gains both cases; each fails without its change.

Also read a default input from the destination only when the name resolves
to the same column there. With `j JSON, y DEFAULT j.c::UInt64` over a
destination that has a column named `j.c`, the fill read that column after
the flush instead of the path of `j` (9 before the flush, 0 after). The
input is now read through `j`; fixture W of 05337 covers it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageBuffer.cpp Resolved
Comment thread src/Storages/StorageBuffer.cpp Resolved
groeneai and others added 2 commits November 10, 2026 19:37
… a destination without subcolumns

Two cases where a flushed row still read differently than before the flush:

- A missing `Nested` member took its sizes from a sibling chosen by the
  destination type. A sibling that is an array in the `Buffer` but stored
  as `String` in the destination was skipped (`[]` instead of `[0,0]`),
  and a sibling that is a `String` in the `Buffer` but an array in the
  destination gave sizes the `Buffer` never had (`[0,0]` instead of `[]`).
  Siblings are now chosen by the `Buffer` type; one the destination does
  not store as an array is converted to the `Buffer` type first. A
  destination array is still used as is, so a differing element type
  cannot make the read fail.

- A default reading a subcolumn (`x DEFAULT t.a`) asked the destination
  for `t.a` even when it cannot read subcolumns (`StripeLog`), which threw
  `INCORRECT_INDEX`. Such a destination now reads `t`, and `t.a` is
  extracted after the conversion, as for any other converted input.

Both found by the AI review on ClickHouse#124296.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed members

A member stored as an array in the destination was always preferred as the
size source, even when the user may not read it while it may read another
member that is an array in the `Buffer` but stored as `String` in the
destination. That read was denied although a readable source existed. The
size source is now the smallest readable member, one that needs no
conversion first; with none readable it falls back as before and the access
check denies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// so keep the ones the fill of the missing columns reads as pass-throughs.
Names consumed_fill_support;
for (const auto * input : filter_dag.getInputs())
if (fill_support.contains(input->result_name))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Preserve the row-count support column through filters

This only keeps destination columns that the fill reads for values (fill_support). When columns_intersection was empty, the new branch above injects one destination column solely so the later addMissingDefaults sees the flushed row count. A row policy or PREWHERE can consume and remove that helper column too, and then the post-filter header is empty again, so queries that select only Buffer-only columns still return zero rows after the flush.

A minimal shape is a local destination like dst(k UInt8), a Buffer table buf(k UInt8, x UInt8 DEFAULT 0), and SELECT x FROM buf PREWHERE k = 1 (or the same predicate as a row policy). After the flush the read adds only k; the filter drops it; addMissingDefaults sees zero rows and materializes no x values. Please preserve that row-count support column through merge_converting_prefix, not only fill_support.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured on this head, this does not reproduce: after the flush, SELECT x FROM buf PREWHERE k = 1, the same predicate in WHERE, and a row policy USING k = 1 each return the 2 matching rows (MergeTree and Memory destinations; StripeLog and TinyLog for the last two). A filter is forwarded to the destination only on columns it has (supportedPrewhereColumns), which are already in the read list, so k is read as a selected column rather than the row-count fallback, and a read whose filter consumes every column still yields chunks with their row count.

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-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant