Skip to content

Do not forward a Merge destination's processing stage across an order-breaking type conversion in a Buffer or a materialized view - #124361

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-over-merge-order-breaking-cast
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-over-merge-order-breaking-cast

Conversation

@groeneai

@groeneai groeneai commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117261
Related: #113242

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 of ORDER BY, DISTINCT and LIMIT BY, and a CANNOT_CONVERT_TYPE error in aggregations, when reading a Buffer table or a materialized view whose destination is a Merge table over a Distributed table (also through an Alias, another Buffer or a materialized view) and that declares a column with a type that does not keep the order of the destination's type, for example UInt64 over Int64.

Description

Found by the AST fuzzer on #124296, not caused by it (report): SELECT DISTINCT A ... ORDER BY ALL DESC NULLS FIRST over Buffer(A Decimal(38, 28)) -> Merge(A Nullable(Int64)) -> Distributed(A Int64) failed with Logical error: 'Equal values are not contiguous within the range assumed to be sorted'. On 26.8.18 and 26.3.42, over Buffer(A UInt64) -> Merge(A Int64) -> a two-shard Distributed(A Int64) holding -number, SELECT DISTINCT A FROM buf ORDER BY A DESC LIMIT 3 returns 0 first, as does a materialized view TO that Merge declaring A UInt64.

StorageBuffer::getQueryProcessingStage returned the destination's stage, and StorageBuffer::read casts the result to the Buffer's types above that stage. The Merge's own conversion preserves the order, so it keeps the stage: the shards sort and aggregate in Int64 and the initiator merges cast, unsorted streams. A materialized view does the same.

Now both read at FetchColumns when the read lands on a Merge (directly or behind an Alias, a table-function proxy, a Buffer or a materialized view) and a column converts without preserving the order, also through a subcolumn or a virtual column (a.x UInt64 over a Tuple(x Int64)). The read repeats it on the metadata it locks, so an ALTER between choosing the stage and the read fails the query with INCOMPATIBLE_COLUMNS. Unchanged: a Distributed destination (#117261: its FetchColumns read returns identifiers).

The new test fails on master and passes 50/50 randomized runs; 763 *buffer*, materialized-view and Merge tests (incl. 05183) show no regression.


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

groeneai and others added 4 commits October 7, 2026 02:37
…'s order-breaking type conversion

`StorageBuffer::getQueryProcessingStage` returned its destination's stage
unconditionally, while `StorageBuffer::read` converts the destination's result to
the Buffer's own column types above that stage. When the destination is a `Merge`
whose own conversion keeps the order (so the ClickHouse#113242 refusal does not fire) over a
`Distributed` child that reports `WithMergeableState`, the shards sort and
deduplicate in the destination type and the Buffer then casts the sorted streams
to a type with a different order (`Int64` -> `UInt64` flips the sign bit,
`Int64` -> `Decimal(38, 28)` wraps silently above ~1.7e10). The initiator trusts
the stage and merges the streams as sorted, so `DISTINCT ... ORDER BY` returns rows
out of order (release) or aborts with "Equal values are not contiguous within the
range assumed to be sorted" in `DistinctSortedStreamTransform` (debug, the AST
fuzzer report, STID 2508-32f8), and aggregates fail `CANNOT_CONVERT_TYPE`.

Now the Buffer returns `FetchColumns` when the delegated stage is above
`FetchColumns`, the destination is a `StorageMerge`, and some destination column
converts to the Buffer's declared type without preserving the order
(`conversionPreservesOrder`, shared with ClickHouse#113242 and ClickHouse#118445). A `Merge` read at
`FetchColumns` returns plain column names whatever its children are, so the Buffer's
own planner sorts and aggregates the converted values. A `Distributed` destination
is deliberately left as is: its `FetchColumns` read still returns analyzer
identifiers (ClickHouse#117261).

`read` repeats the same check on the locked destination snapshot and throws
`INCOMPATIBLE_COLUMNS` when the stage, chosen from an earlier unlocked snapshot, is
above `FetchColumns`: only a concurrent `ALTER`/`CREATE OR REPLACE` of the
destination can make the two disagree, the same backstop `StorageMerge` has for its
own refusal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rough a forwarding wrapper

Both guards tested the Buffer's destination with a direct `dynamic_cast` to
`StorageMerge`. `StorageProxy` (a table created `AS merge(...)`), `StorageAlias`, a
nested `StorageBuffer` and `StorageMaterializedView` forward both
`getQueryProcessingStage` and `read` to their target, so a `Merge` behind any of them
reported its delegated `WithMergeableState` to the Buffer while the type test saw the
wrapper, and `Buffer(A UInt64) -> Alias -> Merge(A Int64) -> Distributed` still cast the
shards' sorted streams above the stage (`DISTINCT ... ORDER BY A DESC` returned `0`
first).

`readLandsOnMerge` follows these four wrappers (bounded by `max_storage_proxy_depth`)
and is used at both call sites, the stage refusal and the read-time backstop. A chain
that ends at a `Distributed` still returns false, so it is unchanged. These are the
same wrappers ClickHouse#119387 treats as a `Merge` behind a proxy. The compared columns do not
change: each wrapper outputs its own declared columns, which is what the Buffer casts.

The test gains one arm per wrapper. On the previous head three of them return `0`
first; the nested `Buffer` one fails with `TOO_DEEP_RECURSION`, a separate recursion of
a Buffer over a Buffer read above `FetchColumns` that also happens without any type
change and is not addressed here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`readLandsOnMerge` stopped after `max_storage_proxy_depth` (16) wrappers
and tested each storage before unwrapping it, so with 16 forwarding
wrappers it reached the `Merge` only after its last iteration and
returned false. The Buffer then forwarded the delegated stage across its
order-breaking cast again. `Alias` chains are not depth-limited (a chain
created from its far end passes the CREATE-time check), so 16 nested
`Alias` tables over the `Merge` were enough to return wrong rows.

The bound only existed to stop a cycle. Replace it with an exact guard on
the storages already passed; they are held as `StoragePtr`, so an address
freed by a concurrent DROP cannot be reused by a later hop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the comments that restate the helpers' names and the cycle guard, and shorten the read-time backstop comment to its invariant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds): 2 blockers fixed, 1 disagreed, 4 nits
Finding Verdict
❌ A Merge behind a wrapper that forwards stage and read (Alias, AS merge(...) proxy, nested Buffer, MaterializedView) bypassed the direct StorageMerge type test AGREE, fixed: the guard walks those wrappers; one test arm per wrapper
❌ The wrapper walk was bounded at 16 hops and returned "no Merge" past it (16 nested Alias tables) AGREE, fixed: exact walk with a cycle guard
❌ An Alias target exchanged between the Buffer's check and StorageAlias::read gets the old stage DISAGREE: StorageAlias::read resolves its target again for any reader of the alias, with or without a Buffer; the Buffer's check covers the snapshot it passes
💡 A directly read MaterializedView over a Merge forwards the same way noted in the description; not changed here
💡 The column-pair loop repeats StorageMerge's two loops noted, not extracted
💡 A Buffer directly over a cluster table function table (IStorageCluster) is unchanged, like Distributed noted
💡 The test runs in the distributed plan jobs (serialize_query_plan = 1) verified locally with that profile

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The fuzzer's table chain (Buffer(Decimal(38, 28)) over Merge(Nullable(Int64)) over a two-shard Distributed(Int64)) aborts a master debug server on the first run with the CI stack (ColumnDecimal<Decimal128>::getEqualRangeEndAssumeSorted from DistinctSortedStreamTransform). The new test returns wrong rows on master on every run.
b Root cause explained? StorageBuffer::getQueryProcessingStage returned the destination's stage, and StorageBuffer::read casts the destination's result to the Buffer's types above that stage. The Merge forwards WithMergeableState because its own conversion preserves the order, so the shards sort in Int64 and the initiator merges Decimal/UInt64 streams that are no longer sorted.
c Fix matches root cause? Yes. The order promise comes from the stage, so the Buffer lowers it to FetchColumns for a Merge destination with an order-breaking declared type, using the shared conversionPreservesOrder predicate (#113242, #118445). No check is relaxed.
d Test intent preserved / new tests added? New test 05332_buffer_over_merge_order_breaking_cast: sort order, the reported query shape, count/uniqExact/GROUP BY/LIMIT BY, a plan check, two order-preserving controls (Nullable(Int64), Int128) that must keep the delegated stage, and a Merge behind an Alias, a table-function proxy, a nested Buffer and a materialized view.
e Both directions demonstrated? Yes. Master: wrong rows, then CANNOT_CONVERT_TYPE; with only the stage refusal disabled, the read-time check fails the query with INCOMPATIBLE_COLUMNS; the four wrapper arms fail without the wrapper walk; with the fix: 50 of 50 randomized runs pass, and the fuzzer query returns the same rows as casting on the shards.
f Fix is general across code paths? Merge children are covered by #113242 and Distributed own types by #118445. A Merge reached through an Alias, a table-function proxy, a nested Buffer or a materialized view is handled like a direct one, at any chain depth. A chain ending at a Distributed is left unchanged on purpose: its FetchColumns read does not return plain column names yet (#117261). A concurrent ALTER between the stage decision and the read is caught by the same check in read.
g Fix generalizes across inputs (params/datatypes/wrappers)? The classification is conversionPreservesOrder (Nullable, LowCardinality, Array, Enum, widenings; covered by 04721 and 05227). Tested: Int64 to UInt64 over plain and Nullable destinations, the Decimal(38, 28) wrap from the fuzzer, and order-preserving Nullable(Int64)/Int128 controls.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Only a Buffer over a Merge with an order-breaking declared type changes its processing stage (wrong results become correct, pushdown is lost for it). The other 140 *buffer* tests and 04721/05227 give the same results as on master, and 05183 passes.
i Invariants and contracts preserved? Rows above FetchColumns are now sorted and aggregated in the Buffer's types. The stage decision and the read-time check share one helper, and the check runs on the locked destination metadata before any plan is built, so the error path leaves no partial state.

Session id: cron:clickhouse-impl-slot-5:20261007-032600

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c8e0f36]

Summary: ✅


AI Review

Summary

This PR prevents Buffer and materialized-view reads from forwarding a Merge destination's processing stage across an order-breaking type conversion. The shared guard follows forwarding wrappers and resolves physical columns, subcolumns, and virtual columns. At c8e0f36a11eef11a6a66979540f0119fd8c9c355, both prior inline findings are addressed, and no actionable findings remain.

Missing context / blind spots
  • ⚠️ Broader sanitizer and stateless CI jobs had not completed at review time. The focused 05332_buffer_over_merge_order_breaking_cast regression passes in Fast test at the reviewed head. No local build or test execution was performed.
Final Verdict

Status: ✅ Approve.

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

`StorageMaterializedView::getQueryProcessingStage` returned the target's stage, and `readImpl` converts
the target's result to the view's declared types above that stage. With `CREATE MATERIALIZED VIEW mv TO
m (A UInt64)` over `m` = `Merge(A Int64)` over a two-shard `Distributed`, the shards sorted and
deduplicated in `Int64`, so `SELECT DISTINCT A FROM mv ORDER BY A DESC LIMIT 3` returned `0` first.
A `Buffer(A UInt64)` over that view forwarded the same stage with nothing to convert itself, so it
returned the same wrong rows (reported by the automated review on the previous commit).

The view now applies the same check as the `Buffer`. Both share `getStageForConvertingRead` and
`checkStageForConvertingRead` in `Storages/Utils`, moved from `StorageBuffer.cpp` unchanged in
behaviour. A table-function proxy needs nothing: its nested `Merge` is built with the proxy's types,
so the `Merge` refuses the stage itself (measured: `CREATE TABLE tf (A UInt64) AS merge(...)` returns
the right rows, directly and behind a `Buffer`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Do not forward a Merge destination's processing stage across a Buffer's order-breaking type conversion Do not forward a Merge destination's processing stage across an order-breaking type conversion in a Buffer or a materialized view Oct 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit c8e0f36a11eef11a6a66979540f0119fd8c9c355 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

…-over-merge-order-breaking-cast

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/Utils.cpp Resolved
…king conversion

The stage guard compared only the physical columns and aliases of the two
schemas, while `StorageBuffer::read` resolves a requested name with
subcolumns and virtual columns and converts whatever it finds. So it missed:
- a name that is a column on one side and a subcolumn on the other, e.g. a
  Buffer declaring `a.x UInt64` over a Merge of `a Tuple(x Int64)`, or a
  Buffer declaring `a Tuple(x UInt64)` over a Merge of a physical `a.x Int64`
  (also a typed or dynamic `JSON` path);
- a physical column that shadows a virtual one, e.g. a destination with a
  physical `_table UInt64` read through the Buffer's virtual
  `_table LowCardinality(String)`.
The shards sorted and deduplicated in the destination type and the Buffer
converted the result above the delegated stage, returning wrong results for
`DISTINCT ... ORDER BY ... DESC` (`0` first) or aborting with "Equal values
are not contiguous within the range assumed to be sorted". The same holds for
a materialized view over a Merge.

Compare the two storage snapshots with the options `StorageBuffer::read`
uses. `getColumns` does not enumerate dynamic subcolumns, so the declared
columns are also resolved in the source. The read-time diagnostic reports the
resolved types instead of looking the name up as a physical column.

Found by clickhouse-gh[bot] on ClickHouse#124361 (r4265032564); the virtual-column case
by the second-model review of that fix.

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

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-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants