Repository navigation
Refuse ORDER BY over a Distributed table whose declared type breaks the shards' order - #118445
Conversation
…he shards' order The shards resolve their own table and sort by its column type, and `StorageDistributed::read` casts the result to the declared type only above that sort, so when the cast does not preserve the order (`String` to `Int8`) the initiator merges the streams as if they were sorted by the declared type: wrong order, wrong rows cut by `LIMIT`, duplicates under `DISTINCT`, and in a debug build `DistinctSortedStreamTransform` throws `Equal values are not contiguous within the range assumed to be sorted`. The stress fuzzer reaches it through the retyped clone of the `Distributed` fixture of `04870_distinct_merge_over_distributed.sql`. `StorageDistributed::getQueryProcessingStage` now throws `INCOMPATIBLE_COLUMNS` for a query with `ORDER BY` when the local copy of the shard table shows such a column. A shard sorts and applies its preliminary `LIMIT` at every stage from `WithMergeableState` on, and a `Distributed` table cannot be read at `FetchColumns`, so there is no stage to fall back to. `conversionPreservesOrder` moves from `StorageMerge.cpp` to `DataTypes/Utils.h` so both engines share it, and accepts the exact widenings `Float32` to `Float64`, `Date` to `Date32`, `DateTime` to `DateTime64`, a `Decimal` with no smaller scale and no fewer integer digits, and `FixedString` to `String`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=d9d115ba1a4d3d9c1d6269bc2ff4745b4a7803c9&name_0=MasterCI&name_1=Stress%20test%20%28amd_asan_ubsan%29 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [d92ff28] Summary: ✅
AI ReviewSummaryThis PR does a careful job of refusing Findings❌ Blockers
Final Verdict
LLVM Coverage ReportMeasured on commit d92ff28.
Changed lines: Changed C/C++ lines covered: 129/141 (91.49%) · Uncovered code |
|
TL;DR: I traced every pair the whitelist accepts and probed each adversarially on a pre-fix build (26.9.1.1, two-shard loopback): all accepted conversions are weakly monotonic, so nothing silently-wrong hides behind the whitelist, and the
One below-bar note: |
Address the review of #118445. The check scanned every shared-name column of the table, so a `Distributed` table with one sloppily declared column it never sorts by lost all of its `ORDER BY` queries: with a shard table `(k Int32, s String)` declared as `(k Int32, s Int8)`, `SELECT k FROM dist ORDER BY k` is correct today (only `k` participates, and it matches exactly) but was refused. A column that no sorting key expression reads is converted above the shards' sort like any other expression - its values are merely carried along in whatever order the sorted columns dictate - so only the columns feeding the `ORDER BY` are collected now, on both analyzer paths, and only those are compared. `ORDER BY ALL` and a positional `ORDER BY 1` name no column on the old analyzer path; there every column is still checked, which is what the previous revision did unconditionally, so nothing new is refused anywhere. Also fix the comment justifying `FixedString(N)` to `String`: the cast trims the trailing zero bytes rather than copying the padding. Trimming is still strictly monotonic on a fixed length, but a future extension must not build on the wrong premise. `01263_type_conversion_nvartolomei` declares `Enum8('a' = 1)` over a shard's `Enum8('a' = 1, 'b' = 2)` and expected `UNKNOWN_ELEMENT_OF_ENUM` from the conversion of the fetched value; the check now refuses that `ORDER BY` earlier with `INCOMPATIBLE_COLUMNS`, so the assertion is updated. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Thank you for the adversarial probing - both findings are adopted, and the 1. Collateral refusals of queries that never touch the mismatched column - fixed. You are right: the scan covered every shared-name column, so a table with one sloppily declared column lost all of its
2. The 3. CI. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+33.18 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units29 translation units recompiled, 226 s compile time in total, 29 of them have a recent master baseline. |
…d skip a column-free sort key The collector kept only bare column names, so `ORDER BY dim.s` over a JOIN, or a lambda argument named like a column, hit the compatibility check of the `Distributed` table's own `s`; and an empty set stood both for "the sorted-by columns are unknown" and for a sort key that reads no column at all, so `ORDER BY tuple()` was checked against every column. The collector now keeps the column source: only columns of `query_info.table_expression` are checked, an `ARRAY JOIN` column is traced back to the array expression it is an element of (the array is what crosses the cast), a column of another table or scope is ignored, and a column that cannot be attributed makes the check fall back to every column. A sort key without columns of this table skips the check. The old-analyzer probes are dropped from the test, `enable_analyzer` is frozen at 1 since 26.9, and the AST branch of the collector goes with them. The test is renumbered to `05227`. The `GROUP BY` probe of the test pins `group_by_two_level_threshold`: with it 1 the shards send a two-level `String` state the initiator cannot merge into its single-level `Int8` one (`UNKNOWN_AGGREGATED_DATA_VARIANT`), a separate defect present without this change, filed as #120781. `test_create_as_select_on_cluster_distributed` declared `num Int32` over a `UInt64` shard column, a conversion that does not preserve the order, so its `ORDER BY num` was refused; the test now declares the shard table's type. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118445&sha=6b3849319d48ecda44a71307e0da45c6a89221c3&name_0=PR PR: #118445 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…er-breaking-cast # Conflicts: # src/Storages/StorageDistributed.cpp
…`JOIN USING` keys Without a query tree (internal reads with an empty `SelectQueryInfo`, the old interpreter) the collector treated every read as sorted by unknown columns, so a plain `SELECT count()` over a retyped `Distributed` table would be refused. Decide from the AST instead: no `ORDER BY` means nothing relies on the shards' order. A `JOIN USING` key is a `ColumnNode` sourced from the `JOIN` whose expression is a list of the columns of both sides; walk that list (as `CollectSourceColumnsVisitor` does) instead of marking the key unknown, so `JOIN dim USING (k) ORDER BY k` is not refused because of an unrelated retyped column. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts: # src/Storages/StorageMerge.cpp
…t `Enum` to unsigned integers At `Complete` and the stages above it (a single shard, `distributed_group_by_no_merge`, a GROUP BY by the sharding key) a shard finalizes DISTINCT, GROUP BY and LIMIT BY by its own type, so a conversion that merges distinct values leaves duplicate groups behind. `StorageDistributed::getQueryProcessingStage` now chooses the stage first and checks the columns of those keys too when the shards finalize them. `conversionPreservesOrder` now accepts an `Enum` converted to a wide enough unsigned integer when none of its values is negative, as that mapping is the identity. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…` type The previous commit asked `to.getSizeOfValueInMemory` before checking that the target is an integer, which throws a `LOGICAL_ERROR` exception for types without a fixed size, such as `Nullable(Enum16(...))` in `04721_merge_child_type_conversion_order`. Check the target kind first, so a `Nullable` target falls through to the unwrapping as before. `02517_wrong_total_structure_crash` declares a fuzzed `Distributed` column type that does not match the shard table, which the new check now refuses with `INCOMPATIBLE_COLUMNS` before the `TYPE_MISMATCH` is reached; accept either. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118445&sha=f686dd504e7800c2659d5ebc1ff773f4c2b59dac&name_0=PR&name_1=Fast%20test #118445 Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (shards_finalize_reductions) | ||
| { | ||
| /// A shard groups and deduplicates by its own type, and the cast to the declared one comes after | ||
| /// it: `String` values '1' and '01' are distinct groups on the shard and both become `1` as `Int8`. | ||
| /// `DISTINCT ON` is already rewritten into LIMIT BY here. | ||
| if (query_node->hasGroupBy()) | ||
| collect(query_node->getGroupByNode(), collect); | ||
| if (query_node->hasLimitBy()) | ||
| collect(query_node->getLimitByNode(), collect); | ||
| if (query_node->isDistinct()) | ||
| collect(query_node->getProjectionNode(), collect); |
There was a problem hiding this comment.
This still misses aggregate-function arguments once the shard is allowed to finalize the query.
A concrete repro is the same existing setup with a single-shard Distributed table over t_str: SELECT max(s) FROM dist_one_int8 is executed at Complete, so the shard computes max in String order and RemoteQueryExecutor::adaptBlockStructure only casts the final result to Int8 afterwards. That returns 9 instead of the Int8 maximum 20.
Because this block only adds GROUP BY, LIMIT BY, and DISTINCT inputs to key_columns, the same “shard finalizes on one type, initiator interprets it as another” bug is still open for max/min/similar aggregates at Complete, distributed_group_by_no_merge, and the sharding-key optimization stages. I think the fail-close set here also needs to include the columns read by aggregate-function arguments executed on the shard.
alexey-milovidov
left a comment
There was a problem hiding this comment.
The logic of this check is quite ad-hoc, but it is well-contained in the code, so it is ok to merge.
Related: #113242
Related: #115831
Related: #115455
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Refuse a query with
ORDER BYover aDistributedtable whose declared column type differs from the shard table's type in a way that does not preserve the order (for exampleInt8declared over aStringcolumn). The shards sorted by their own type and the initiator merged the streams as if they were sorted by the declared type, which returned the rows in the wrong order, cut the wrong rows withLIMIT, and duplicated values underDISTINCT. The check runs when a shard is the local server, where the shard table's types are known, and only for the columns the query sorts by. Exact widenings (Float32toFloat64,DatetoDate32,DateTimetoDateTime64, aDecimalwith no smaller scale and no fewer integer digits,FixedStringtoString) are now recognized as order-preserving by both this check and the one of theMergeengine.Description
Master stress test failure,
Logical error: 'Equal values are not contiguous within the range assumed to be sorted'(STID 2508-3796):https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=d9d115ba1a4d3d9c1d6269bc2ff4745b4a7803c9&name_0=MasterCI&name_1=Stress%20test%20%28amd_asan_ubsan%29
The aborting query, from
fatal.log, is the fuzzer's retyped clone of theDistributedfixture of04870_distinct_merge_over_distributed.sql:This is the
Distributedarm of the defect that #113242 fixed forMerge: the shards resolve their own table and sortsasString,readcasts the result toInt8above that sort (createLocalPlan,RemoteQueryExecutor::adaptBlockStructure), and the initiator merges the streams as sorted, soDistinctSortedStreamTransformmeets equal values that are not adjacent. In a release build theDISTINCTreturns 31 rows instead of 21, andORDER BY s DESC LIMIT 3returns9, 8, 7instead of20, 19, 18. The family keeps landing on unrelated pull requests, several times a day.The
Mergefix drops its children toFetchColumns. That is not available here: a shard sorts and applies its preliminaryLIMITat every stage fromWithMergeableStateon (without aggregation theORDER BYis part of the first stage), so an initiator-side re-sort cannot recover the rows a shard has already cut, and aDistributedtable cannot be read atFetchColumnson the analyzer path (StorageDistributed::readbuilds the shard query from the whole query tree, so a join in the query is executed by the shards and its columns come back in the header;PlannerJoinTreealso drops the identifier-named output columns of such a read). MakingFetchColumnsa real stage forDistributedis a larger change than this fix should carry, and shipping the cast to the shards is a design change of its own. So the query is refused withINCOMPATIBLE_COLUMNSand a message that names both types, instead of returning wrong rows. The check only fires when the query has anORDER BY, which is the only shape where the shards' order is relied upon: without it aDISTINCTorGROUP BYis redone on the initiator over the converted values, and aLIMITwas arbitrary to begin with. It is also scoped to the source columns of the sorting key expressions, because a column no sorting key expression reads is converted above the shards' sort like any other expression and its values are merely carried along: a table with one sloppily declared column keeps everyORDER BYquery that does not sort by it.ORDER BY ALLand a positionalORDER BY 1name no column on the old analyzer path, so there every column is checked.The initiator only knows the shard table's types when a shard is this server, which is the case for every
localhostcluster and for the clusters the tests and the fuzzer use; remote-only clusters cannot be checked at planning time.enableMemoryBoundMergingtakes the same "local shard or nothing" stance.conversionPreservesOrdermoves fromStorageMerge.cpptoDataTypes/Utils.hso both engines share it, and it now accepts the exact widenings listed in the changelog entry; every one is strictly monotonic and injective, so both the order and the distinctness survive. ADecimaltarget with a smaller scale rounds distinct values together and stays refused, as does an equal-width sign change.Not covered on purpose:
_shard_num(deprecated) is already0on theFetchColumnspath theMergefix takes, and aWHERE s = 5over the retyped table already fails on the shard withNO_COMMON_TYPEon master; neither is changed here.Workflow [PR]
Sync PR [sync-upstream/pr/118445]
Version info
26.10.1.1534-master(included in26.10and later)