Skip to content

Do not push sorting into Merge children across an order-breaking cast - #113242

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-child-conversion-order
Aug 30, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-child-conversion-order

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112931

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

Fix wrong ORDER BY and DISTINCT results, and a CANNOT_CONVERT_TYPE error for aggregate functions, when reading a Merge table whose declared column type differs from a source table's type in a way that does not preserve sort order, for example UInt64 over a source holding negative Int64.

Description

StorageMerge::getQueryProcessingStage reports whatever stage its children report, so a
Distributed child makes the shards apply the ORDER BY while the initiator only merges the
sorted streams. ReadFromMerge::convertAndFilterSourceStream then casts each child's output to
the 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: getQueryProcessingStage returns
FetchColumns when 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, since
FetchColumns is zero and std::max would erase the refusal.

The type test must be order-preserving and injective, because it composes elementwise inside
Array. Following ToNumberMonotonicity, it accepts integer widening that keeps the signedness
or targets a signed type, adding Nullable, stripping LowCardinality, an Enum target at
least as wide as the source, and Array over Array with an accepted element pair. Everything
else is refused, including a narrower Enum target, which truncates and so reverses the order
even where contains accepts the pair. A false "safe" gives silently wrong results; a false
"unsafe" costs one pushdown. Merge derives such pairs itself via getLeastSupertypeOrVariant.

Read-in-order needs no change: its monotonicity analysis already rejects the inserted _CAST.
Tuple, Map, StorageBuffer, StorageView, StorageMaterializedView and
buildQueryTreeForShard need their own fixes.

Found by the AST fuzzer, which had retyped a Merge column to IPv4 over Int64 (2508-36d8,
report).

Closes: #115455


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

groeneai and others added 7 commits August 3, 2026 04:14
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
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 6 review rounds, 23 findings
adjudicated). The last two rounds returned 0 findings, the final one re-reviewing the whole change
against current master and the frozen description.

# Sev Finding Verdict Evidence / action
1 ❌ The order-preservation predicate refuses conversions that provably keep order, and Merge derives two of them itself via getLeastSupertypeOrVariant, so an ordinary column-list-less Merge would permanently lose shard-side sorting and aggregation AGREE, fixed @ 0fc9875 The first draft was modelled on isSafeForKeyConversion, which answers the stronger byte-identical-serialization question minmax indices need. Now accepts integer widening that keeps the signedness or targets a signed type, adding Nullable, and Enum widening, following ToNumberMonotonicity
2 ❌ ALIAS columns cross the same conversion boundary but were not compared, so an alias whose child type disagrees carries the defect while every physical column agrees AGREE, fixed @ 435cdb2 Verified in source: the alias expressions are added below the converting DAG in convertAndFilterSourceStream. Both sides now enumerate AllPhysicalAndAliases; a test arm exercises it
3 ❌ The LowCardinality branch demanded byte equality with the other side, so LowCardinality(Int32) to LowCardinality(Int64) and LowCardinality(Nullable(T)) shapes were refused although ColumnLowCardinality::compareAt compares through the dictionary AGREE, fixed @ b7d8eec The wrapper is now stripped from either side and the nested pair recursed. It never nests, so the stripped side is not LowCardinality again
4 ❌ The Enum arm accepts an order-BREAKING narrowing: contains does not bound the target's width, and on a name miss it tests hasValue(static_cast<TARGET>(v)), so 128 becomes -128, which the target holds AGREE, fixed @ 4b9a690 This refutes my own softer reading of the same site, which had checked only the name-present branch. Measured before fixing: ascending 0, 128 arrived as the descending sequence. Now requires the target to be at least as wide, which excludes truncation by construction
5 ⚠️ Array element widening is refused although ColumnArray::compareAt compares elementwise then by length, and getLeastSupertype recurses into Array AGREE, fixed @ 4b9a690 Raised twice, so it went into the fix plan rather than being overridden again. Both sides must be Array; the recursion is sound because every accepted pair is injective, which the predicate's contract now states
6 ⚠️ The controls used identical declared and child types, so they only exercised the early return and could never detect over-refusal AGREE, fixed @ 0fc9875 Added differing-but-order-preserving controls plus column-list-less arms whose derived type is asserted from system.columns, so a resolver change reddens instead of going vacuous
7 ⚠️ Missing CI provenance and a visible issue reference AGREE, fixed Check name, test id and the canonical report URL are in the description
8 ⚠️ The frozen description states the Enum acceptance without its width condition, and lists Array among the refused pairs after it became accepted AGREE, fixed before publication Rewrote that paragraph to state the injectivity requirement, the Enum width condition, the Array acceptance and the Tuple/Map refusal. The final gate re-reviewed the rewritten text
9 ❌ StorageBuffer misses the same shape DISAGREE The mechanism is real but the finding's necessary step is false: no Merge is required. StorageBuffer::getQueryProcessingStage delegates its destination's stage and defers the buffer-vs-destination cast to the end of its own read, so the wrong-order shape reproduces standalone. Policing it from StorageMerge would leave that query broken. Tracked separately
10 ❌ StorageMaterializedView misses the same shape DISAGREE Same refutation, same necessary step: getQueryProcessingStage forwards the target's stage and readImpl appends the conversion above the target plan, with no Merge involved
11 💡 Restrict the check to the columns the query reads DISAGREE Not available at this layer: getQueryProcessingStage takes no column list, whereas StorageMerge::read takes const Names & column_names. The comparison is also cheap where it sits, since the loop has already fetched that child's metadata for the stage call and ColumnsDescription::get is memoized on the immutable snapshot
12 💡 Nine smaller items: read declared columns from the snapshot the function already receives rather than re-fetching metadata through an override that runs a traversal with an access check per call; hoist and scope the type predicates; back-tick literal names per the repository convention; resolve the positional conflict with current master AGREE, fixed None outstanding

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Read-in-order needed no matching refusal: its monotonicity analysis walks the inserted _CAST and
already rejects every conversion this predicate calls unsafe. The test keeps that case as a
coverage guard and says so, rather than claiming to witness the fix.

Session id: cron:clickhouse-review-slot-48:20260804-061600

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t_neg (A Int64) ENGINE = MergeTree ORDER BY A; INSERT INTO t_neg SELECT -number FROM numbers(1000); a Distributed over it, then CREATE TABLE m (A UInt64) ENGINE = Merge(currentDatabase(), '^dist_neg$'). SELECT DISTINCT plus(0, A) FROM m ORDER BY ALL ASC LIMIT 1048576 throws on every attempt, on both analyzers, at max_threads 1/2/3/8/16 and with prefer_localhost_replica 0 and 1. SELECT min(A) FROM m fails with CANNOT_CONVERT_TYPE.
b Root cause explained? Yes. StorageMerge::getQueryProcessingStage reports a child's stage above FetchColumns, so shards sort and the initiator only merges pre-sorted streams. convertAndFilterSourceStream then appends the declared-type cast above each child's sort. An order-breaking cast reinterprets values after they were sorted, and the promise cannot be retracted because the merging step came from the stage, not from a sort property. A second root cause of the same shape sits inside the predicate itself: EnumValues::containsAll falls back to hasValue(static_cast<TARGET_T>(v)) on a name miss, so a source value outside the target's range is TRUNCATED before the membership test and the pair is accepted, while the conversion truncates the data identically.
c Fix matches root cause? Yes. The unsound promise is withdrawn at the function that issues it, next to the existing JOIN / ARRAY JOIN refusal. The checkEqualRangeEndAssumeSorted assertion is untouched, and IPv4 was deliberately not added to the cast-monotonicity list, since asserting monotonicity for an order-destroying conversion would turn the exception into silently wrong results. The Enum arm now also requires sizeof(from) <= sizeof(to), which excludes truncation by construction rather than range-checking today's values, since ALTER can change an enum definition. The Array recursion is admitted only because every accepted pair is injective, and that requirement is now stated in the function's contract comment instead of being an unstated dependency.
d Test intent preserved / new tests added? Yes. No existing test was weakened or removed, and the pre-existing reference lines are byte-identical after every round (107 -> 113 -> 129), verified mechanically by deleting the inserted lines and comparing to the previous file. New 04721_merge_child_type_conversion_order asserts values rather than absence of an exception, across the carriers and controls, on both analyzers. Several controls declare a type that DIFFERS from the child yet preserves order, so they detect over-refusal, which a correctness-only check cannot. One arm leaves the declared type to Merge to derive and pins the MEASURED result, so the derivation that makes these shapes ordinary is exercised rather than merely cited. No no-parallel tag, every name scoped to currentDatabase(). Two settings are pinned with the reason recorded in the test (optimize_respect_aliases, and LIMIT on the value assertions), each for a PRE-EXISTING master defect reproduced on an unpatched snapshot with identical declared and child types, not for this mechanism.
e Both directions demonstrated? Yes, through the real runner. Fixed e868212c: [ OK ] 5.27 sec. Baseline (source reverted through a patch file and rebuilt; git status on src/ empty, Build ID back to aad72744 byte-for-byte): [ FAIL ], and the diff falls on exactly one line, the derived arm's pushdown assertion (1 after, 0 before). Earlier rounds proved the original carrier, the ALIAS carrier and the wrapped conversions the same way. Round 4 repeated this for both new defects on the final binary 3295082a: on the pre-fix binary e868212c the Enum arm returns 1 (wrongly delegated) with the value sequence INVERTED versus ground truth, and the Array arm returns 0 (the over-refusal); after the fix they read 0 / correct order / 1 and the test passes with full randomization. 50/50 with default randomization (50 passed, 210.60 s) and 50/50 pinning optimize_distinct_in_order=1, optimize_sorting_by_input_stream_properties=1 (50 passed, 209.59 s). The revert and restore reproduced both Build IDs exactly this round; arm identity still rests primarily on measured behaviour plus an empty git status, because an earlier round observed identical source linking to two different IDs.
f Fix is general across code paths? Yes, fixed at the source, so all applyOrder consumers close at once: MergingSorted execution, DistinctStep in-order, convertToFinishSorting, LimitByStep, NegativeLimitByStep, UnionStep and window sorting are each exercised by the test. Read-in-order needs no change: its monotonicity analysis walks the inserted _CAST under unbounded NULL bounds and already rejects every conversion this predicate calls unsafe, which the MergeTree-child case guards. StorageBuffer, StorageView, StorageMaterializedView, buildQueryTreeForShard and StorageWithCommonVirtualColumns share the shape and are named in the description as not addressed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 38 declared-to-child pairs were measured on a real MergeTree -> Distributed -> Merge chain, on the binary with and without the change, each type read back from system.columns beside its verdict so a missing fixture cannot pass as a measurement. Accepted: Int32->Int64, UInt32->UInt64, UInt32->Int64, Int32/Int64->Nullable(Int64), LowCardinality(Int32)->LowCardinality(Int64), LowCardinality(String)<->String, LowCardinality(String)->Nullable(String), LowCardinality(Int32)->Int64, LowCardinality(Nullable(Int32))->Nullable(Int64), LowCardinality(Nullable(String))->Nullable(String), LowCardinality(String)->LowCardinality(Nullable(String)), Enum8->Enum16, Enum8->Nullable(Enum16), Enum8->Nullable(Int16), Enum8->Int16, Enum16->Int32, and Array(Int32)->Array(Int64), which an ordinary column-list-less Merge derives itself. Refused: the reported Int64->UInt64 carrier, UInt64->Int64, Int64->Int32, Int64->IPv4, Nullable(Int64)->Int64, Nullable(String)->LowCardinality(String) (nullability removal), LowCardinality(Int64)->LowCardinality(UInt64) and LowCardinality(Int64)->UInt64 (the equal-width flip through both the one-sided and the two-sided LowCardinality path, proving the recursion is not a blanket accept), LowCardinality(Int64)->LowCardinality(Int32), Enum16->Int8, Enum16->Nullable(Int8), Enum16('a'=0,'b'=128)->Enum8('c'=0,'d'=-128) (the truncating narrowing that contains alone accepted) and Enum16->Enum8 even with equal values, Array(Int64)->Array(UInt64) and Array(Int64)->Array(Int32) (order-breaking inside the array), Array(Int32)->Int64 and Int32->Array(Int64) (one-sided), and Tuple(Int32)->Tuple(Int64) and Map(String,Int32)->Map(String,Int64) deliberately, because tuple supertyping also unifies element names and a map's key-type change reshapes the nested tuple its comparison delegates to. ToNumberMonotonicity is the in-tree authority for the accepted set. Carriers cover two-shard, single-node, mixed-source, nested, aliased-table, ALIAS-column and derived-declared-type shapes.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change, no format or serialization change, so no SettingsChangesHistory.cpp entry and no experimental gate. The change only withdraws an optimization in cases that currently return wrong results.
i Invariants and contracts preserved? Yes. The function's contract is tightened only in the safe direction: a lower stage is always legal for a caller, and FetchColumns is exactly what the JOIN path already returns. The declared columns are read from the StorageSnapshot the function already receives, which outlives the call and is the same metadata the child conversion targets, so the column reference cannot dangle. Every non-test caller was traced to confirm none can pass a snapshot belonging to another table. No new lock, no allocation in a hot loop, no new error path: the comparison runs inside a loop that already fetched that child's metadata. The predicate's own contract is now STATED rather than implied (order preserving AND injective on values), which is exactly the property the Array recursion composes; it remains a pure function of two IDataType references, so there is no lifetime or concurrency surface.

Session id: cron:clickhouse-impl-slot-47:20260804-014400

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @davenger, could you review this? StorageMerge::getQueryProcessingStage forwards a child's stage, so shards apply the ORDER BY and the initiator only merges pre-sorted streams, but convertAndFilterSourceStream then appends the declared-type cast above each child's sort, so an order-breaking conversion reinterprets the values after they were sorted and the sortedness promise cannot be retracted. The fix refuses the delegation in getQueryProcessingStage itself, as the JOIN path already does.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9b1d030]

Summary: ✅


AI Review

Summary

This PR fixes the wrong-results path where StorageMerge delegates a later query stage to children and only casts their output to the declared schema afterwards, which can destroy the ordering promised by child-side sorting or aggregation. The concurrency re-check and the integer / Enum / Nullable / LowCardinality / Array cases look sound now, but the new whitelist is still too narrow: it regresses some existing Merge schemas that use other order-preserving least supertypes.

Findings

⚠️ Majors

  • [src/Storages/StorageMerge.cpp:548] conversionPreservesOrder still rejects at least one ordinary, injective promotion that Merge derives itself: Date -> Date32. getLeastSupertype picks Date32 for a plain Merge over Date and Date32, and ToDateMonotonicity<DataTypeDate32> already treats that cast as always strict. Because this helper falls through to false, those tables now drop to FetchColumns and lose shard-side ORDER BY / aggregate pushdown even though the conversion preserves order. Extend the helper to the date/time-family promotions ClickHouse already marks as strict, or reuse the cast monotonicity metadata here, and add a focused regression arm to 04721.
Final Verdict

⚠️ Changes requested: the new stage-refusal logic still regresses pushdown for at least one existing order-preserving Merge schema (Date child to declared Date32).

LLVM Coverage Report

Measured on commit 9b1d030.

Metric Baseline Current Δ
Lines 88.50% 88.60% +0.10%
Functions 92.00% 92.10% +0.10%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 57/68 (83.82%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fast test red: 00717_merge_and_distributed loses a row, and the cause is a pre-existing master defect this PR newly reaches

I root-caused the failure. The dropped row is not a wrong-results bug in this diff, but I am not
treating that as a pass: this PR is the first thing in tree that routes an in-tree test onto an
already-broken path, so it should not merge as it stands. I am re-planning it.

**The failing query is 00717_merge_and_distributed.sql:86**, WHERE _table = 'test_u64_local'(not the unorderedWHERE value = 1` on the next line, which is fine).

The defect. Merge documents that filtering on _table prunes which tables are read. For a
Distributed child at FetchColumns that is unsatisfiable, because two different names are compared
against each other:

  • the prefilter in ReadFromMerge::getSelectedTables (StorageMerge.cpp:1550-1577, applied at
    :1592) evaluates the extracted _table predicate against the Merge child's own name, i.e. the
    Distributed table;
  • the column itself is materialized in VirtualColumnUtils.cpp:534-540 from
    virtual_values.storage_id.getTableName(), which at FetchColumns is the remote local table.

At Complete only the local name is ever visible and everything agrees. At FetchColumns both are
live and disagree, so every value fails at one end or the other. Initiator read_rows for
SELECT count() ... WHERE m._table = X over a single-child Merge, so prefilter pruning shows up as
read_rows = 0:

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

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Re-plan outcome: this PR is correct as it stands and waits for the _table prefilter fix

Following up on my previous comment, where I said I would decide between sequencing this behind the
prefilter fix and narrowing the gate. I picked the first, because the second turns out not to be a
narrowing at all.

Narrowing the gate for remote children would delete the fix. Only a storage that reports a stage
above FetchColumns can reach the new gate. Going through the overrides: IStorage's default
returns FetchColumns (IStorage.h:349-352), MergeTreeData returns FetchColumns on every path
except the non-analyzer parallel-replicas branches, and the ones that do exceed it are
StorageDistributed (StorageDistributed.cpp:515-600) and IStorageCluster, with StorageProxy
and StorageAlias inheriting their target's answer. So excluding remote children removes the gate
for every realistic case, and the fuzzer report this PR fixes has a Merge over a Distributed
child in its own fixture, so the fix would then miss its own reproducer. Gating on "the query needs
order" does not help either: the failing 00717 query has an ORDER BY.

One correction to my previous comment. I had not measured what type the Merge actually
declares there. It is Int64, not the Int128 an earlier note of mine guessed, and it is Int64
only because 00717_merge_and_distributed.sql:10 sets
merge_table_max_tables_to_look_for_schema_inference = 1, so the type comes from one child instead
of the real supertype. On official 26.8.1.734 without that setting the same merge() yields
Variant(Int64, UInt64), and getLeastSupertype.cpp:139-149 explicitly refuses to promote the
Int64/UInt64 pair to Int128. The cast on the second child is therefore UInt64 -> Int64:
equal width, sign-bit flip, order-breaking. The gate is firing correctly on that query, which is
another reason not to make it green by widening the predicate.

So the diff here needs no change. I am leaving it as it is until the prefilter defect is fixed on
master, then I will merge master in, re-run 00717, and re-push. The fixing PR link for the
prefilter will be posted here when it opens, as promised.

One detail for whoever looks at the prefilter: _database does not appear to share the defect by
the same route. VirtualColumnUtils.cpp materializes _table from storage_id.getTableName()
(:534-540) but has no _database branch in that reader path, while the prefilter evaluates both
and requires both to be virtual (StorageMerge.cpp:1549).

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

The prefilter fixing PR is now open, as promised: #113735.

It fixes the _table / _database prefilter comparing the Merge child's own name against a
column materialized from the resolved storage id, which is what makes the 00717_merge_and_distributed
row loss reachable on master. Once it lands I will merge master in here, re-run 00717 and re-push.

One correction to the detail I left for whoever looked at the prefilter: I wrote that _database
does not appear to share the defect by the same route. It does. The prefilter requires both columns
to be virtual and evaluates both, and the delegating child resolves both names, so a _database
filter is unsatisfiable on the same path. #113735 covers both columns.

…child-conversion-order

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

This is now the top Stress test failure across the whole PR queue — merged current master in

Refreshed this branch onto master (15cfe1699c8, clean merge) to get a current CI run, because the
bug it fixes is currently failing CI for nearly every open pull request.

Impact. Logical error: 'Equal values are not contiguous within the range assumed to be sorted'
(STID 2508-3796) hit 38 times across 37 pull requests between 2026-08-15 and 2026-08-18, 34 of
them in Stress test lanes, 35 of them since 08-17. Example on master:
Stress test (amd_debug) @ 84688bbf.

The onset is 04870_distinct_merge_over_distributed.sql, which landed on master on 2026-08-13
(b4ad0c2cd3e, from #112931). The stress lanes fuzz test queries, so the fuzzer now clones that
test's Merge table with its s String column retyped on every run — observed Int256,
BFloat16, Decimal(18, 9), Decimal(4, 1) — which is exactly the order-breaking child
conversion this pull request refuses:

SELECT count() FROM (SELECT DISTINCT s FROM merge_distinct__fuzz_3 ORDER BY s ASC LIMIT 100)
    SETTINGS max_threads = 1, distributed_aggregation_memory_efficient = 0, optimize_distinct_in_order = 1
-- merge_distinct__fuzz_3 is (`s` Int256) ENGINE = Merge(db, '^dist_distinct$') over a
-- Distributed whose base table holds `s String`

There is no per-test way to opt out of the fuzzer (ast_fuzzer_runs is per invocation), so this
cannot be muted — and should not be, since in release builds it is silently wrong results.

Verified on master today (RelWithDebInfo, so the chassert is compiled out and the defect
shows as the release symptom), 100 rows of toString(number % 21) behind a two-shard
Distributed, count() of the DISTINCT subquery:

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.

@alexey-milovidov alexey-milovidov self-assigned this Aug 30, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 30, 2026
Merged via the queue into ClickHouse:master with commit e0b752b Aug 30, 2026
179 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 30, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
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 sort

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

CC component owner: @alexey-milovidov @CurtizJ

Analysis metadata

comp-storage-merge · Severity P2 · Finding phase_d_pr113242

  • Verified against master build 5a56420a6a10 (aarch64)
  • Could not test: master
Introducing change: predates `v22.3.20.29` (oldest testable release)
  • v22.3.20.29 is the oldest release with a downloadable binary for this reproducer, and it already reproduces — the introducing change predates it and cannot be identified from release builds.
  • Secondary components: comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov could you apply v26.3-must-backport here? The fix is on master only: this PR carries pr-bugfix ("not backported by default"), and the backport search only selects PRs labelled pr-must-backport or vX.Y-must-backport, so it is not picked up at all right now. A version label is the floor and expands to itself plus every newer active branch, so v26.3-must-backport alone covers 26.3, 26.6, 26.7 and 26.8, the four active release branches. 26.5 and 25.8 in the triage above are retired.

I checked affectedness against official release binaries rather than relying on that list. SELECT DISTINCT A FROM m_retyped ORDER BY A ASC LIMIT 3 returns 18446744073709550617, 18446744073709550618, 18446744073709550619 on 26.3.26.3, 26.6.3.62, 26.7.5.10 and 26.8.1.2041, and the correct 0, 18446744073709550617, 18446744073709550618 on master. So all four reproduce, including 26.8, which the triage did not test. Two controls held on every arm: declaring the same Merge table Int64 instead of UInt64 returns -999, -998, -997, and SELECT DISTINCT toUInt64(A) FROM t_neg ORDER BY 1 LIMIT 3 returns the correct order. The wrong answer is specific to the cast rather than to my setup.

One correction: the triage's master build 5a56420a6a10 does not predate this merge, it is 33 commits after it. e0b752b337e3 is an ancestor of it and 04721_merge_child_type_conversion_order.sql is present in that tree, so the clean master result above does attribute to this fix.

Separately, ba22813fce4f also added jeprof.2964715.0.heap and jeprof.3011593.0.heap at the repository root, about 45 KB of jemalloc heap dumps, and they are on master now. They look accidental.

@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

This PR accidentally merged two heap-profile artifacts into the repository root: jeprof.2964715.0.heap and jeprof.3011593.0.heap (250 lines each). They are now on master — worth deleting.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, both are still on master (45 KB total). I will open a PR deleting them and adding a jeprof.*.heap entry to the root .gitignore, which has no such rule today, and post the link here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Opened #117279: both files deleted, plus the jeprof.*.heap entry in the root .gitignore I mentioned. The pattern is scoped to the filename shape flushProfile builds under jemalloc's default prefix, so the tracked ci/docker/test-base/jeprof helper is unaffected.

pull Bot pushed a commit to mikeyhodl/ClickHouse that referenced this pull request Aug 31, 2026
`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

26.8 release CI has hit this three times since the branch was cut. Each time the AST fuzzer redeclared the Merge table of 04870_distinct_merge_over_distributed over its String child, which is the order-breaking cast this PR refuses, and the server stopped on the Equal values are not contiguous within the range assumed to be sorted assertion:

Date Check Declared s Report
2026-09-14 Stress test (arm_debug) Nullable(Int64) 1c847331
2026-10-04 Stress test (amd_debug) Int256 ad731b3e
2026-11-18 Stress test (amd_msan) Float32 fbee6f1a

This PR is in 26.9 and 26.10 but not in 26.8 or 26.3, so the v26.3-must-backport request above still covers exactly the active branches that lack it. src/Storages/StorageMerge.cpp merges onto 26.8 without conflicts (4 conflicting regions on 26.3). The cherry-pick would also re-add the two jeprof.*.heap files that #117279 removed from master.

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

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI 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.

Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3319)

6 participants