Skip to content

Refuse ORDER BY over a Distributed table whose declared type breaks the shards' order - #118445

Merged
alexey-milovidov merged 11 commits into
masterfrom
fix-distributed-order-breaking-cast
Oct 4, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
fix-distributed-order-breaking-cast

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Related: #113242
Related: #115831
Related: #115455

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):

Refuse a query with ORDER BY over a Distributed table whose declared column type differs from the shard table's type in a way that does not preserve the order (for example Int8 declared over a String column). 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 with LIMIT, and duplicated values under DISTINCT. 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 (Float32 to Float64, Date to Date32, DateTime to DateTime64, a Decimal with no smaller scale and no fewer integer digits, FixedString to String) are now recognized as order-preserving by both this check and the one of the Merge engine.

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 the Distributed fixture of 04870_distinct_merge_over_distributed.sql:

-- dist_distinct__fuzz_4 is (`s` Int8) ENGINE = Distributed(..., 't_distinct') over `s String`
SELECT count() FROM (SELECT DISTINCT s FROM dist_distinct__fuzz_4 ORDER BY s ASC LIMIT 100)
    SETTINGS max_threads = 1, distributed_aggregation_memory_efficient = 0, optimize_distinct_in_order = 1

This is the Distributed arm of the defect that #113242 fixed for Merge: the shards resolve their own table and sort s as String, read casts the result to Int8 above that sort (createLocalPlan, RemoteQueryExecutor::adaptBlockStructure), and the initiator merges the streams as sorted, so DistinctSortedStreamTransform meets equal values that are not adjacent. In a release build the DISTINCT returns 31 rows instead of 21, and ORDER BY s DESC LIMIT 3 returns 9, 8, 7 instead of 20, 19, 18. The family keeps landing on unrelated pull requests, several times a day.

The Merge fix drops its children to FetchColumns. That is not available here: a shard sorts and applies its preliminary LIMIT at every stage from WithMergeableState on (without aggregation the ORDER BY is part of the first stage), so an initiator-side re-sort cannot recover the rows a shard has already cut, and a Distributed table cannot be read at FetchColumns on the analyzer path (StorageDistributed::read builds 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; PlannerJoinTree also drops the identifier-named output columns of such a read). Making FetchColumns a real stage for Distributed is 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 with INCOMPATIBLE_COLUMNS and a message that names both types, instead of returning wrong rows. The check only fires when the query has an ORDER BY, which is the only shape where the shards' order is relied upon: without it a DISTINCT or GROUP BY is redone on the initiator over the converted values, and a LIMIT was 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 every ORDER BY query that does not sort by it. ORDER BY ALL and a positional ORDER BY 1 name 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 localhost cluster and for the clusters the tests and the fuzzer use; remote-only clusters cannot be checked at planning time. enableMemoryBoundMerging takes the same "local shard or nothing" stance.

conversionPreservesOrder moves from StorageMerge.cpp to DataTypes/Utils.h so 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. A Decimal target 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 already 0 on the FetchColumns path the Merge fix takes, and a WHERE s = 5 over the retyped table already fails on the shard with NO_COMMON_TYPE on master; neither is changed here.


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

Version info

  • Merged into: 26.10.1.1534-master (included in 26.10 and later)

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d92ff28]

Summary: ✅


AI Review

Summary

This PR does a careful job of refusing ORDER BY/DISTINCT/GROUP BY/LIMIT BY queries whose Distributed-table declared types would reorder shard results after the initiator casts them, and the focused tests cover many tricky name-resolution cases. I still see one correctness hole in the same area: once a shard is allowed to finalize the query at Complete or above, aggregate-function arguments are still left on the wrong-result path even though GROUP BY/LIMIT BY/DISTINCT were closed.

Findings

❌ Blockers

  • [src/Storages/StorageDistributed.cpp:373] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118445#discussion_r4097498383] getKeyColumns only adds GROUP BY, LIMIT BY, and DISTINCT inputs when shards_finalize_reductions is true. Aggregate-function arguments are still omitted, so a query like SELECT max(s) FROM dist_one_int8 over shard s String declared as s Int8 is computed in String order on the shard and only cast to Int8 afterwards, returning the wrong value (9 instead of 20 on the existing t_str repro data). That is the same “shard finalizes on one type, initiator interprets as another” invariant this PR is trying to fail-close, so I still consider it a release-blocking correctness gap. Suggested fix: when the chosen stage is Complete or higher, also collect the source columns read by aggregate-function arguments that execute on the shard and run the same compatibility check on them.
Final Verdict
  • Status: ❌ Block
  • Minimum required action: extend the new fail-close logic to aggregate-function arguments evaluated on the shard at Complete/distributed_group_by_no_merge/sharding-key-optimized stages, and cover it with a focused stateless repro such as SELECT max(s) FROM dist_one_int8.

LLVM Coverage Report

Measured on commit d92ff28.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.20% +0.10%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 129/141 (91.49%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 6, 2026
@zlareb1

zlareb1 commented Sep 6, 2026

Copy link
Copy Markdown
Member

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 GROUP BY refusal is justified (shard-side Top-K group pruning orders by the shard type: SELECT s, count() FROM dist GROUP BY s ORDER BY s LIMIT 5 over a String shard column declared Int8 returns 0,1,10,11,12 pre-fix). Two findings worth addressing before merge:

  1. The check refuses queries that never touch the mismatched column. The scan covers every shared-name column of the table, not just the columns feeding the ORDER BY. With a shard table (k Int32, s String) declared as (k Int32, s Int8), the query SELECT k FROM dist ORDER BY k is correct today (only k participates, and it matches exactly) but is refused after this change. A Distributed table with one sloppily-declared column it never sorts by loses all ORDER BY queries. Scoping the check to the source columns of the sorting key expressions would keep the fix and drop the collateral refusals; the error message already names the offending column, so the fix stays discoverable either way.

  2. The comment justifying FixedString(N) → String is factually wrong, though the conclusion survives. It says the bytes are copied "padding included", but the actual CAST trims trailing zero bytes (probed: 0x610000 arrives as 0x61, on both the local plan and the prefer_localhost_replica=0 remote path). Trimming is still strictly monotonic on fixed-N inputs (first-differing-byte argument: the trimmed suffix is all zeros, and a zero byte is the minimum, so relative order of any two distinct values is preserved), but the comment should state the real mechanism so a future extension does not build on the "padding included" premise.

One below-bar note: DateTime64(3) → DateTime64(6) is an exact widening (same argument as the Decimal branch: scale-up by a power of ten with no overflow possible) but is refused; extending the Decimal scale/precision logic to DateTime64 would cover the most plausible real-world declared-type drift.

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 6, 2026
alexey-milovidov and others added 2 commits September 11, 2026 07:06
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you for the adversarial probing - both findings are adopted, and the DateTime64 note is refuted.

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 ORDER BY queries. The check now collects the source columns of the sorting key expressions and compares only those, on both analyzer paths: SELECT k FROM dist ORDER BY k over a shard table (k Int32, s String) declared (k Int32, s Int8) works again, while ORDER BY s, ORDER BY -s and ORDER BY k, s stay refused. Justification for the narrowing: a column that no sorting key expression reads is converted above the shards' sort like any other expression, and its values are merely carried along in whatever order the sorted columns dictate - nothing is out of order.

ORDER BY ALL and a positional ORDER BY 1 name no column on the old analyzer path, so there every column is still checked; the analyzer resolves both to columns before this point, so it narrows there too. That conservative branch is exactly what the previous revision did unconditionally, so nothing new is refused anywhere - the change is strictly a narrowing. Coverage added in 05099_distributed_declared_type_conversion_order.

2. The FixedString(N) to String comment - fixed. The comment now states the real mechanism (the cast trims the trailing zero bytes) and carries the first-differing-byte argument for why trimming is still strictly monotonic on a fixed length, rather than the wrong "padding included" premise.

3. DateTime64(3) to DateTime64(6) - refused deliberately, because the general scale widening overflows. The scale-up is not unconditionally exact the way the Decimal branch is, because a DateTime64 has no precision to compare: it is always an Int64. DateTime64 accepts values up to 2299-12-31, and 2299-12-31 in nanoseconds is about 1.04e19, past the Int64 maximum 9.22e18 (the boundary is 2262). So DateTime64(3) to DateTime64(9) wraps for any value after 2262, which destroys the order outright - precisely the class of bug this check exists to refuse. Admitting only the pairs that cannot overflow would mean hard-coding a target-scale bound whose correctness rests on the accepted value range rather than on the types, which is a weaker guarantee than every other branch here rests on, so the pair stays refused. Declaring the column with the shard's scale costs nothing.

CI. 01263_type_conversion_nvartolomei was the one real red: it 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 'b'; the check refuses that ORDER BY earlier with INCOMPATIBLE_COLUMNS, which is the more precise diagnosis, so the assertion is updated. Verified locally: 05099_distributed_declared_type_conversion_order and 01263_type_conversion_nvartolomei both pass, and the C++ style checks are clean. master is merged in.

Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d92ff28fe with master 2493c465d (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

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

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageDistributed.cpp.o 1.08 MiB 1.11 MiB +31.43 KiB (+2.84%)

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

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

Job report

…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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
alexey-milovidov and others added 2 commits September 24, 2026 18:21
…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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/DataTypes/Utils.cpp Resolved
alexey-milovidov and others added 4 commits October 2, 2026 18:03
# 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]>
Comment on lines +373 to +383
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);

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.

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 alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The logic of this check is quite ad-hoc, but it is well-contained in the code, so it is ok to merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants