Repository navigation
Do not push sorting into Merge children across an order-breaking cast - #113242
alexey-milovidov merged 11 commits into
Conversation
A Merge table reports its child's query processing stage, which lets the planner install a MergingSorted step that merges without sorting because the children are assumed to have sorted already. convertAndFilterSourceStream then appends the declared-type conversion above each child's sort, so for a declared type that disagrees with the child's the streams arrive reinterpreted. Casting negative Int64 to an unsigned type reorders them, so the merge reads streams that are no longer sorted: ORDER BY returns wrong rows in a release build, and DISTINCT in order trips the "Equal values are not contiguous within the range assumed to be sorted" assertion in a debug build. Refuse the delegation instead, mirroring the existing JOIN and ARRAY JOIN FetchColumns refusal in the same function: when a selected table's column type differs from the declared type in a way that does not preserve order, return FetchColumns and sort on the initiator. The refusal is applied after the stage arithmetic, since std::max over child stages would otherwise erase it, and is gated on the effective stage rather than the requested one, because a single-node Distributed child returns Complete even for a FetchColumns request. conversionPreservesOrder follows the shape of isSafeForKeyConversion in MergeTreeData.cpp: it recognises identical types, Enum to its underlying number, and LowCardinality to its dictionary type, and reports anything else as unsafe. That direction is deliberate; a wrong "safe" answer is silent wrong results, while a wrong "unsafe" answer only costs one query's pushdown. Types are compared including wrappers, so a Nullable change, which moves where NULLs sort, is also treated as unsafe. Found by the AST fuzzer. Co-Authored-By: Claude Fable 5 <[email protected]>
Follow-up to the previous commit, narrowing it to what is reachable. The recursive descent into a nested Merge child (with the alias unwrapping and depth bound that existed only to serve it) could never fire. createPlanForTable's must_return_interpreter_select_query_plan forces a StorageMerge child under processed_stage > FetchColumns onto the interpreter path, so that child's own grandchild conversion is emitted below its own sort and never reaches the outer merge. An aliased inner Merge is covered for the same reason: StorageAlias forwards getQueryProcessingStage to its target, so the outer child loop's call reaches the inner Merge, which then refuses on its own behalf. Deleting the descent leaves all nested and aliased shapes correct on both analyzers, so this removes structurally dead code rather than an untested guard. What is load-bearing and stays is the flat per-child comparison combined with OR into one flag applied after the stage arithmetic. It has to survive that arithmetic because FetchColumns is 0, so std::max over the children erases a refusal from an unsafe non-Merge child whenever a sibling reports a higher stage. The comparison now folds into the existing child loop, which already holds each child's metadata, so the separate traversal is gone: it re-walked every child and re-fetched metadata per child, and StorageMerge's own getInMemoryMetadataPtr runs a traverseTablesUntil with an access check on each call. Read-in-order needs no matching refusal. It walks each child plan's DAG including the inserted _CAST and requires a monotonic chain under unbounded NULL bounds, which rejects every conversion this predicate calls unsafe, so its accepted set is a subset of the safe set. The test asserts values through a top-level ORDER BY. A subquery's ORDER BY is not preserved by its parent, so an oracle that nests the sort reports failures that depend only on how many streams the pipeline happened to use. DISTINCT drops the per-shard duplication so the expected sequence does not depend on stream count either. Covered: the reported DISTINCT query on both analyzers, aggregate states (which fail with CANNOT_CONVERT_TYPE before the fix), a window sort with no top-level ORDER BY, LIMIT BY and its negative sibling, UNION ALL, GROUP BY over nested and aliased carriers, a self-referential Merge, and two controls whose declared types match their children, asserting that they still push the stage down.
conversionPreservesOrder was modelled on isSafeForKeyConversion, which answers a
strictly stronger question: whether a converted value serializes byte-identically,
as minmax indices require. Order preservation does not need that bound, so copying
the shape refused conversions that keep every value in place.
Two of the refused pairs are ones StorageMerge derives itself. With no column list,
getColumnsDescriptionFromSourceTablesImpl merges disagreeing child descriptions
through getLeastSupertypeOrVariant, which widens integers and adds Nullable. So a
plain ENGINE = Merge(...) over children that differ only in integer width or in
nullability returned FetchColumns for every query, which stops each Distributed
child from aggregating and sorting on the shards. Those tables are correct today:
the cast is monotone, so the shard-side order agrees with the initiator's merge.
Now accepted, with ToNumberMonotonicity as the in-tree authority for the set:
- T -> Nullable(T), and Nullable(A) -> Nullable(B) when A -> B is accepted:
adding or keeping nullability introduces no NULL, so no value moves.
- native integer widening when the signedness is preserved or the target is
signed, mirroring ToNumberMonotonicity's expansion branch.
- Enum8 -> Enum16 and Enum8/Enum16 -> a signed integer at least as wide, since
an Enum is stored as its underlying number.
Still refused: the reported Int64 -> UInt64 carrier and every other equal-width
signedness flip (the sign bit reorders), every narrowing (it wraps), Nullable
removal (NULL placement changes), Int64 -> IPv4, and anything unrecognised.
getQueryProcessingStage now reads the declared columns from the StorageSnapshot it
already receives rather than through the getInMemoryMetadataPtr override, which runs
a traverseTablesUntil with an access check per call. That snapshot is what builds the
common header, so it is also what convertAndFilterSourceStream casts children to.
The two existing controls in 04721 use identical declared and child types, so they
only reach the from.equals(to) early return and cannot detect over-refusal. Added an
Int64-declared-over-Int32-child control and a Nullable(Int64)-over-Int64-child one,
which return 0 before this commit and 1 after, plus a value assertion over each so a
later over-broadening cannot hide behind the plan check.
… conversions
Two gaps in the predicate added by the previous commits.
The child-side enumeration used getAllPhysical, which skips ColumnDefaultKind::Alias,
so an ALIAS column was never compared against the declared type. Aliases do cross the
same boundary: their expansion is not gated on the stage, and convertAndFilterSourceStream
adds the alias expressions below the converting DAG, which is the same above-the-sort
position that is the whole bug. Measured before widening anything: a Merge whose declared
x is UInt64 over a child whose x is an Int64 ALIAS, with every physical column agreeing,
keeps the merge step and returns values out of order, and the reported DISTINCT query
aborts in a debug build with the same assertion. Both sides now enumerate and look up with
AllPhysicalAndAliases. Ephemeral stays out, since it is never read from a source table.
Three order-preserving conversions were still refused, all of them shapes Merge derives
itself through getLeastSupertypeOrVariant for a column-list-less table:
- LowCardinality(Int32) -> LowCardinality(Int64) matched neither one-sided branch,
because each required the other side to be the bare dictionary type. When both sides
are LowCardinality the predicate now recurses on the dictionary types, which is sound
because ColumnLowCardinality::compareAt compares through the dictionary, so a
LowCardinality column orders exactly like its nested type. LowCardinality(String) to
String and the reverse keep their existing one-sided handling.
- Enum8 -> Nullable(Enum16) and Enum16 -> Nullable(Int32) were refused because both Enum
branches returned unconditionally, so a Nullable target failed the Enum cast and
returned false before the Nullable unwrapping could run. The Enum handling now falls
through on an unmatched target instead of returning. The integer branch never had this
defect, which is why Int32 -> Nullable(Int64) already worked.
The two Enum branches also collapse into one over IDataTypeEnum, gated on the stored
width, so an Enum16 still refuses Int8.
Array(Int32) -> Array(Int64) is deliberately NOT accepted, although it is derived the same
way. ColumnArray::compareAt is elementwise lexicographic, which needs STRICT monotonicity
of the element conversion, and this predicate does not state strictness. Every pair it
accepts today happens to be strict, so the trap is latent rather than live: the moment a
non-strict pair is accepted, two arrays differing at element i would become equal there
and the order would change at element i+1. Leaving Array refused costs one pushdown on a
rarer schema.
Verified over 24 declared-to-child pairs, each type read back from system.columns before
the verdict was taken. The three shapes above flip from refused to accepted; the reported
Int64 -> UInt64 carrier, LowCardinality(Int64) -> LowCardinality(UInt64), every narrowing,
Nullable removal, Int64 -> IPv4 and Array all stay refused, and no previously measured pair
changed.
Two settings are pinned in the new test arms, for defects that are not this one. With
optimize_respect_aliases off, reading an alias from a Merge over a Distributed at
FetchColumns fails with UNKNOWN_IDENTIFIER on plain master too, with identical declared
and child types. And SELECT DISTINCT over a Merge of a Distributed emits one block per
shard, so every value appears twice at any cardinality, again on plain master with
identical types, which is why the value assertions are LIMITed like the existing ones.
The two one-sided `LowCardinality` branches of `conversionPreservesOrder` had the same pre-emption defect as the two `Enum` branches fixed in the previous commit: they returned unconditionally, so the `Nullable` unwrapping below them was unreachable for a pair with `LowCardinality` on exactly one side. The three `LowCardinality` branches were therefore mutually inconsistent, with the both-sided one recursing while the one-sided ones demanded byte equality of the unwrapped side. The consequence needs no unusual DDL and no setting. `LowCardinality(String) -> Nullable(String)` was refused although it is order-preserving, and a column-list-less `Merge` over a `LowCardinality(String)` child beside a `Nullable(String)` child derives exactly that pair: the `LowCardinality` phase of `getLeastSupertype` runs above the `Nullable` phase and returns the bare nested supertype for a mix of `LowCardinality` and non-`LowCardinality` inputs, which the `Nullable` phase then wraps. So an ordinary two-table `Merge` of default-legal `String` columns permanently lost shard-side sorting and aggregation pushdown for every query it served. Stripping the wrapper from whichever side carries it is sound because `ColumnLowCardinality::compareAtImpl` compares through the dictionary in all cases, so a `LowCardinality` column orders exactly like its nested type. It terminates because `DataTypeLowCardinality`'s constructor rejects a dictionary type that cannot be inside `LowCardinality`, so the wrapper never nests. It accepts nothing beyond the wrapper either: `WhichDataType` reports `TypeIndex::LowCardinality`, so the integer and `Enum` branches above could not see through it, and the stripped pair reaches exactly the decision it would have reached unwrapped. The two previously accepted one-sided pairs keep their verdict as the `from.equals(to)` case of the general rule. Measured over 31 child-to-declared pairs, on the binary with and without this change: only `LowCardinality(String) -> Nullable(String)`, `LowCardinality(Int32) -> Int64` and `LowCardinality(Nullable(Int32)) -> Nullable(Int64)` flip to accepted. The equal-width signedness flip stays refused through the new one-sided path as well as the both-sided one, as do the narrowings and the removal of nullability. The regression test gains one arm with no column list, which pins the derived declared type that makes these shapes ordinary rather than exotic. That derivation was cited as the reason the wrapper block exists but was not exercised anywhere, because every other wrapper table in the test declares its destination type.
Two corrections to conversionPreservesOrder.
An Enum-to-Enum pair was accepted on to_enum->contains(from_enum) alone. That
predicate does not bound the target's width: when a source name is absent from
the target, EnumValues::containsAll falls back to hasValue(static_cast<T>(v))
with T the TARGET's field type, so the value is truncated before the membership
test. The actual conversion (FunctionTo<DataTypeEnum<F>> derives from
FunctionTo<DataTypeNumber<F>>) truncates the data the same way, and truncation
is not order preserving. Enum16('a' = 0, 'b' = 128) to Enum8('c' = 0,
'd' = -128) was accepted although 128 becomes -128, so a shard sorted ascending
was merged as if ascending while the values arrived reversed.
checkEnumToEnumConversion does not stop it: it only compares values for names
present in both enums, and here the name sets are disjoint.
Requiring sizeof(from) <= sizeof(to) is sufficient and minimal, because a
static_cast between signed integers cannot change a value when the target is at
least as wide. It also makes the equal-names narrowing
Enum16('a' = 1, 'b' = 2) to Enum8('a' = 1, 'b' = 2) refused. That pair happens
to be safe today, but the conservative direction costs only a pushdown, while
accepting it would depend on an enum definition that ALTER can change.
Second, an Array whose element conversion is order preserving was refused
although getLeastSupertype recurses into Array, so an ordinary column-list-less
Merge over an Array(Int32) child beside an Array(Int64) child derives
Array(Int64) with no unusual DDL. ColumnArray::compareAtImpl compares
elementwise and then by length, so an elementwise strictly monotonic conversion
orders arrays the same way. Strictness, not merely monotonicity, is what the
recursion needs: a conversion collapsing two values could turn [1, 5] < [2, 3]
into [1, 5] > [1, 3]. Every accepted pair is injective, and the Enum arm is now
injective by construction, so the contract comment states both properties.
Tuple and Map stay refused deliberately. getLeastSuperTypeForTuple also unifies
element names, and a Map's key-type change reshapes the nested Tuple that
ColumnMap::compareAt delegates to, so each needs its own analysis.
The regression test gains the Enum narrowing carrier, the derived Array
widening, and the pairs that must stay refused: an equal-width flip and a
narrowing inside the array, a one-sided Array, Tuple and Map.
…child-conversion-order # Conflicts: # src/Storages/StorageMerge.cpp
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 6 review rounds, 23 findings
Severity: ❌ blocker / Read-in-order needed no matching refusal: its monotonicity analysis walks the inserted Session id: cron:clickhouse-review-slot-48:20260804-061600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-47:20260804-014400 |
|
cc @azat @davenger, could you review this? |
|
Workflow [PR], commit [9b1d030] Summary: ✅
AI ReviewSummaryThis PR fixes the wrong-results path where Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 9b1d030.
Changed lines: Changed C/C++ lines covered: 57/68 (83.82%) · Uncovered code |
|
| filter value | initiator read_rows |
rows out |
|---|---|---|
the child's own (Distributed) name |
1, prefilter admits | 0, the post-read filter rejects against the materialized local name |
| the materialized local name | 0, prefilter prunes the child | 0 |
It is already reachable on released master, without this PR, and without any type conversion.
getQueryProcessingStage returns FetchColumns unconditionally for JOIN/ARRAY JOIN
(StorageMerge.cpp:478-480), which predates this change. On the official
builds.clickhouse.com/master/amd64/clickhouse build, version 26.8.1.734, over a same-type
UInt32/UInt32 pair so that no cast is involved:
CREATE TABLE sl1 (date Date, value UInt32) ENGINE = MergeTree ORDER BY date;
CREATE TABLE sl2 (date Date, value UInt32) ENGINE = MergeTree ORDER BY date;
CREATE TABLE sd1 AS sl1 ENGINE = Distributed('test_shard_localhost', currentDatabase(), sl1, rand());
CREATE TABLE sd2 AS sl2 ENGINE = Distributed('test_shard_localhost', currentDatabase(), sl2, rand());
INSERT INTO sl1 VALUES ('2018-08-01', 100);
INSERT INTO sl2 VALUES ('2018-08-01', 200);
-- 1 row, correct
SELECT _table, value FROM merge(currentDatabase(), 'sd1|sd2') WHERE _table = 'sl2';
-- 2 rows, _table = sl1 / sl2: the rows and the names are both there
SELECT m._table, m.value FROM merge(currentDatabase(), 'sd1|sd2') AS m
JOIN (SELECT '2018-08-01'::Date AS date) AS j ON m.date = j.date;
-- 0 rows: same filter as the first query, now at FetchColumns
SELECT m._table, m.value FROM merge(currentDatabase(), 'sd1|sd2') AS m
JOIN (SELECT '2018-08-01'::Date AS date) AS j ON m.date = j.date WHERE m._table = 'sl2';00717 only covers the Complete shape, which is why master is green.
What I am not doing. I am not widening conversionPreservesOrder to accept the Int64/UInt64
pair to make the test green. That pair genuinely breaks order (equal width, sign-bit flip), accepting
it would reintroduce the wrong-ORDER BY class this PR exists to close, and it would leave the defect
reachable through the JOIN path regardless.
A fix task owns the _table defect, and its fixing-PR link will be posted here when it opens. This
PR then either sequences behind it or narrows the gate so a remote child is not downgraded; I will
decide that in the re-plan and update the description. Sorry for the noise on the review request while
this is in flux.
Session id: cron:clickhouse-maint-slot-14:20260804-090600
Re-plan outcome: this PR is correct as it stands and waits for the
|
|
The prefilter fixing PR is now open, as promised: #113735. It fixes the One correction to the detail I left for whoever looked at the prefilter: I wrote that |
…child-conversion-order Co-Authored-By: Claude Fable 5 <[email protected]>
This is now the top
|
Merge table |
result | expected |
|---|---|---|
s String (same as the child) |
21 | 21 |
s Int256 (retyped, Distributed child) |
31 | 21 |
s Int256 (retyped, local MergeTree child, i.e. the FetchColumns path this PR forces) |
21 | 21 |
EXPLAIN on the failing shape shows Sorting (Merge sorted streams for ORDER BY, without aggregation) directly above ReadFromMerge, so the initiator really is only merging pre-sorted
child streams while the cast sits underneath — the mechanism described in the PR body.
Still blocked on #113735, and that blocker is real. I confirmed on current master that
SELECT count() FROM <Merge over a Distributed child> WHERE _table = '<child>' returns 0 instead of
200, so the 00717_merge_and_distributed row that this PR drops is the pre-existing prefilter
defect, exactly as described above. #113735 is refreshed on master as well. Expected order:
#113735 merges first, then master gets merged in here again and 00717 is re-checked.
Reproducer-- needs a server with the standard test clusters (clickhouse-local has none)
CREATE TABLE t_neg (A Int64) ENGINE = MergeTree ORDER BY A;
INSERT INTO t_neg SELECT -number FROM numbers(1000);
CREATE TABLE dist_neg AS t_neg ENGINE = Distributed('test_cluster_two_shards_localhost', currentDatabase(), t_neg);
CREATE TABLE m_retyped (`A` UInt64) ENGINE = Merge(currentDatabase(), '^dist_neg$');
SELECT DISTINCT A FROM m_retyped ORDER BY A ASC LIMIT 3;
-- 26.7 / 26.6 / 26.5 / 26.3 / 25.8: 18446744073709550617, 18446744073709550618, 18446744073709550619
-- expected (and master since #113242): 0, 18446744073709550617, 18446744073709550618
-- the shards sorted on Int64, the initiator only merged the streams, and the UInt64 cast landed above that sortResults:
CC component owner: @alexey-milovidov @CurtizJ Analysis metadata
Introducing change: predates `v22.3.20.29` (oldest testable release)
|
|
@alexey-milovidov could you apply I checked affectedness against official release binaries rather than relying on that list. One correction: the triage's master build Separately, |
|
This PR accidentally merged two heap-profile artifacts into the repository root: |
|
Confirmed, both are still on master (45 KB total). I will open a PR deleting them and adding a |
|
Opened #117279: both files deleted, plus the |
`jeprof.2964715.0.heap` and `jeprof.3011593.0.heap`, 45130 bytes together, are jemalloc `heap_v2` profiler output tracked in the repository root. Nothing references them and they are the only tracked files of that shape. When jemalloc's `opt.prof_prefix` is left at its default `jeprof`, `flushProfile` in `src/Common/Jemalloc.cpp` formats a relative `jeprof.<pid>.<seq>.heap`, so a server with profiling enabled writes the dump into its working directory. Nothing in `.gitignore` matched that name, and the large-file check in `ci/jobs/scripts/check_style/various_checks.sh` has a 5 MB threshold, so a 22 KB dump passed both. The new entry is scoped to exactly that shape and leaves the tracked `ci/docker/test-base/jeprof` helper and every other `.heap` name alone. Reported by @ zlareb1 in ClickHouse#113242 (comment) Co-Authored-By: Claude Opus 5 <[email protected]>
|
26.8 release CI has hit this three times since the branch was cut. Each time the AST fuzzer redeclared the
This PR is in 26.9 and 26.10 but not in 26.8 or 26.3, so the |
Related: #112931
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong
ORDER BYandDISTINCTresults, and aCANNOT_CONVERT_TYPEerror for aggregate functions, when reading aMergetable whose declared column type differs from a source table's type in a way that does not preserve sort order, for exampleUInt64over a source holding negativeInt64.Description
StorageMerge::getQueryProcessingStagereports whatever stage its children report, so aDistributedchild makes the shards apply theORDER BYwhile the initiator only merges thesorted streams.
ReadFromMerge::convertAndFilterSourceStreamthen casts each child's output tothe declared types, and that cast lands above the child's own sort, so an order-breaking
conversion reinterprets the values after they were sorted. The promise cannot be withdrawn, since
the merging step was chosen from the stage, not from a sort property. It also enables
DISTINCT-in-order, which in debug builds throws
Equal values are not contiguous within the range assumed to be sorted.The fix refuses the delegation where it is issued:
getQueryProcessingStagereturnsFetchColumnswhen a child's column type differs from the declared type un-order-preservingly,as it already does for
JOIN. The flag is applied after the stage arithmetic, sinceFetchColumnsis zero andstd::maxwould erase the refusal.The type test must be order-preserving and injective, because it composes elementwise inside
Array. FollowingToNumberMonotonicity, it accepts integer widening that keeps the signednessor targets a signed type, adding
Nullable, strippingLowCardinality, anEnumtarget atleast as wide as the source, and
ArrayoverArraywith an accepted element pair. Everythingelse is refused, including a narrower
Enumtarget, which truncates and so reverses the ordereven where
containsaccepts the pair. A false "safe" gives silently wrong results; a false"unsafe" costs one pushdown.
Mergederives such pairs itself viagetLeastSupertypeOrVariant.Read-in-order needs no change: its monotonicity analysis already rejects the inserted
_CAST.Tuple,Map,StorageBuffer,StorageView,StorageMaterializedViewandbuildQueryTreeForShardneed their own fixes.Found by the AST fuzzer, which had retyped a
Mergecolumn toIPv4overInt64(2508-36d8,report).
Closes: #115455
Workflow [PR]
Sync PR [sync-upstream/pr/113242]