Repository navigation
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
Conversation
…'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]>
Collaborator
Author
Internal second-model review (3 rounds): 2 blockers fixed, 1 disagreed, 4 nits
|
Collaborator
Author
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261007-032600 |
Contributor
|
Workflow [PR], commit [c8e0f36] Summary: ✅
AI ReviewSummaryThis PR prevents Missing context / blind spots
Final VerdictStatus: ✅ Approve. |
…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]>
Contributor
Build profile diff (arm_release)Commit See the job log for details. |
…-over-merge-order-breaking-cast Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
Merged
5 of 31 tasks
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related: #117261
Related: #113242
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results of
ORDER BY,DISTINCTandLIMIT BY, and aCANNOT_CONVERT_TYPEerror in aggregations, when reading aBuffertable or a materialized view whose destination is aMergetable over aDistributedtable (also through anAlias, anotherBufferor a materialized view) and that declares a column with a type that does not keep the order of the destination's type, for exampleUInt64overInt64.Description
Found by the AST fuzzer on #124296, not caused by it (report):
SELECT DISTINCT A ... ORDER BY ALL DESC NULLS FIRSToverBuffer(A Decimal(38, 28))->Merge(A Nullable(Int64))->Distributed(A Int64)failed withLogical error: 'Equal values are not contiguous within the range assumed to be sorted'. On 26.8.18 and 26.3.42, overBuffer(A UInt64)->Merge(A Int64)-> a two-shardDistributed(A Int64)holding-number,SELECT DISTINCT A FROM buf ORDER BY A DESC LIMIT 3returns0first, as does a materialized viewTOthatMergedeclaringA UInt64.StorageBuffer::getQueryProcessingStagereturned the destination's stage, andStorageBuffer::readcasts the result to the Buffer's types above that stage. TheMerge's own conversion preserves the order, so it keeps the stage: the shards sort and aggregate inInt64and the initiator merges cast, unsorted streams. A materialized view does the same.Now both read at
FetchColumnswhen the read lands on aMerge(directly or behind anAlias, a table-function proxy, aBufferor a materialized view) and a column converts without preserving the order, also through a subcolumn or a virtual column (a.x UInt64overa Tuple(x Int64)). The read repeats it on the metadata it locks, so anALTERbetween choosing the stage and the read fails the query withINCOMPATIBLE_COLUMNS. Unchanged: aDistributeddestination (#117261: itsFetchColumnsread returns identifiers).The new test fails on master and passes 50/50 randomized runs; 763
*buffer*, materialized-view andMergetests (incl.05183) show no regression.Workflow [PR]
Sync PR [sync-upstream/pr/124361]