Skip to content

Fix wrong results, mis-sorted output and an exception in key analysis of arithmetic over Array/Tuple values - #112339

Merged
Ergus merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-compound-key-noninjective-monotonicity
Jul 29, 2026
Merged

Ergus merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-compound-key-noninjective-monotonicity

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112231
Related: #112151

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

Fixed wrong results, wrongly ordered ORDER BY output and a BAD_TYPE_OF_FIELD exception when the primary key is an Array or Tuple and the query applies plus, minus, multiply, divide or intDiv to it. Arithmetic on a compound value is evaluated element-wise, while the comparison of a compound value is lexicographic, so primary key analysis no longer treats such an expression as monotonic.

Description

FunctionBinaryArithmeticWithConstants::getMonotonicityForRange decided monotonicity from the element arithmetic without checking that its argument type is a scalar. Arithmetic on an Array/Tuple is evaluated element-wise, but the comparison of a compound value is lexicographic, so an element-wise verdict cannot establish the order of the whole value: as soon as two leading elements map to the same output, the compound order is decided by a later element that carries no relation to the input order.

Three user-visible symptoms, all from that one missing check.

1. Wrong results: matching rows are dropped. An ordinary positive divisor is enough; no overflow, no wrap, no reinterpretation.

CREATE TABLE k (a Array(Int64)) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 1;
INSERT INTO k VALUES ([10,100]), ([11,5]), ([12,0]), ([20,0]);

SELECT count() FROM k WHERE intDiv(a, toInt64(10)) = [toInt64(1), toInt64(0)];
-- 0 before, 2 after (ENGINE = Memory answers 2)

EXPLAIN indexes = 1 reported Parts: 0/1, Granules: 0/4. [10,100] < [11,5] lexicographically, but intDiv(., 10) maps them to [1,10] and [1,0]: the leading elements tie and the order inverts.

2. Wrongly ordered output. ReadInOrderOptimizer reads the same verdict and skipped the sort:

SELECT intDiv(a, toInt64(10)) FROM k ORDER BY intDiv(a, toInt64(10));
-- [[1,10],[1,0],[1,0],[2,0]] before -- not sorted; [[1,0],[1,0],[1,10],[2,0]] after

3. A valid query threw. With the compound value on the right of the operator, or with a compound constant, analysis compared an Array endpoint against an integer:

CREATE TABLE nz (a Array(Int64)) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 1;
INSERT INTO nz VALUES ([10,100]), ([11,5]), ([12,4]), ([20,2]);

SELECT count() FROM nz WHERE intDiv(toInt64(100), a) = [toInt64(9), toInt64(20)];
-- Code: 169. DB::Exception: Cannot compare DB::Array with long. (BAD_TYPE_OF_FIELD)
-- 1 after

The throw happens inside key analysis, so no query-level setting avoids it. In the IN spelling the same class of shape violated the MergeTreeSetIndex binary-search invariant and aborted a debug build.

All five monotonic functions are affected: plus and minus through a compound constant against a compound key, multiply through a compound constant against a scalar key and through Tuple * Tuple (which lowers to dotProduct and has a scalar result), divide and intDiv through every shape above.

The fix rejects monotonicity in getMonotonicityForRange when the unwrapped argument type or the unwrapped result type is Array/Tuple/Map. This is the statement negate already makes in tree (src/Functions/negate.cpp: "For compound types (Tuple, Array, etc.) monotonicity analysis is not applicable.") and that FunctionUnaryArithmetic carries; FunctionBinaryArithmetic was missing it. The checked type comes from the type parameter, which callers already set to the varying argument's type, not from operand position, which is the defect 51ff0e13ea2b26 fixed. Both halves are needed: an argument can be compound while the result is scalar (Tuple * Tuple), and the result can be compound while the varying argument is scalar (a compound constant over a scalar key).

No sound narrower predicate exists at this layer, because the two properties that would justify pruning are not expressible there:

  • Arity is not a type property. DataTypeArray stores only the nested type, so one Array(Int64) column holds [5] and [10,100] in the same table. On such a mixed table the old verdict was wrong in the other direction: an overcount, through the implicit-projection path.
  • Lexicographic order needs injectivity, which no cheap element test gives. A magnitude-1 divisor is not safe (intDiv(Array(UInt64), 1) still jumps at 2^63), and element width is not safe either (divide(Array(Int32), 5e-324) maps 1, 2 and 3 all to inf).

Endpoint-inversion detection does not work: the element-wise image of a lexicographic interval is not an interval, so the transformed endpoints can keep their order while an interior value escapes the transformed range. is_strict does not work either: divide reports itself strict while being a carrier.

Performance. Monotonic pruning and read-in-order are given up for arithmetic over a compound key. This is a real cost, not a free one: on an Array(Int64) key holding [number * 100, number] over numbers(100) with index_granularity = 1, plus, minus, divide and intDiv all prune tightly today (Granules: 2/100 for point predicates, 51/100 for a range) and after this change read every granule. Only multiply was already degenerate there (Granules: 99/100).

Those specific queries do return the right answer today, but only by accident of the data: the verdict they rest on is unsound for every one of the five functions over a compound key, and a small change of values turns each into wrong results. Same fixture shape, one value moved:

function shape before oracle
plus key [[1,0],[1,9223372036854775807],[2,0]], plus(a, [0,1]) = [1,-9223372036854775808] 0 (Granules: 0/3) 1
intDiv key [[1,0],[1,25],[2,0]], intDiv(a, 10) = [0,2] 0 1
divide key [[9007199254740992,5],[9007199254740993,1]], divide(a, 1) = [9007199254740992,1] 0 1

So the choice is not "keep a sound optimization or lose it" but "keep an unsound one". Scalar keys are completely untouched. Date/DateTime/Date32/DateTime64 keys with a Tuple(INTERVAL, INTERVAL) operand have a scalar result and keep pruning (asserted, on both operand sides), as does a String key with INTERVAL.

The new test 04652_compound_key_monotonicity prints every keyed answer beside an ENGINE = Memory oracle and asserts exact granule counts for the preserved shapes, so both an under-fire and an over-fire of the check show up in the reference diff. Each clause of the check is covered by a mutation test.

Map is included in the check as fail-closed defence in depth; a Map operand is rejected earlier with Code 43 today, so this changes nothing for it.

Relationship to #112231. That PR makes key analysis tolerate a monotonic chain that throws, which would stop symptom 3 from failing the query. It is complementary rather than a substitute: symptoms 1 and 2 need the verdict itself to be correct. Merge order does not matter and the changes do not overlap textually.

Relationship to #112151. That PR fixes a narrower case in the same function (an intDiv constant that reinterprets to an effectively negative value) and pins two compound preservation controls, Granules: 2/100 for intDiv(Array(Int64), 10) and Granules: 2/256 for intDiv(Array(UInt8), 255). This change deliberately stops both from pruning, because their safety rests on the compound value having exactly one element, which the type system cannot express. Whichever of the two lands second re-expresses those two assertions as answer-correctness checks; the code changes themselves do not conflict (git merge-tree is clean both ways).

Version info

  • Merged into: 26.8.1.358 (included in 26.8 and later)

groeneai added 2 commits July 28, 2026 15:11
`FunctionBinaryArithmeticWithConstants::getMonotonicityForRange` decided
monotonicity from the element arithmetic without checking that its argument
type is a scalar. Arithmetic on an `Array`/`Tuple` is evaluated element-wise,
while the comparison of a compound value is lexicographic, so an element-wise
verdict cannot establish the order of the whole value: once two leading
elements map to the same output, the compound order is decided by a later
element that carries no relation to the input order.

Every pre-existing guard in that function models a scalar hazard and calls
`IDataType::getSizeOfValueInMemory()` or `accurateLessOrEqual`, both undefined
for a container, so for a compound argument they silently did not apply and the
function fell through to reporting monotonicity.

Three user-visible symptoms followed, for all five monotonic functions
(`plus`, `minus`, `multiply`, `divide`, `intDiv`):

  * matching rows were dropped, with an ordinary positive divisor and no
    overflow, wrap or reinterpretation involved;
  * `ORDER BY` returned unsorted output, because `ReadInOrderOptimizer` reads
    the same verdict and skipped the sort;
  * a valid query threw `BAD_TYPE_OF_FIELD` during key analysis, and in the
    `IN` spelling violated the `MergeTreeSetIndex` binary-search precondition
    and aborted debug builds.

Reject monotonicity when the unwrapped argument type or the unwrapped result
type is a container. This is the statement `negate` and
`FunctionUnaryArithmetic` already make in tree, which
`FunctionBinaryArithmetic` was missing. The checked type comes from the `type`
parameter, which callers already set to the varying argument's type, rather
than from operand position, which is the defect 51ff0e1 fixed. Both
halves are required: an argument can be compound while the result is scalar
(`Tuple * Tuple`, which lowers to `dotProduct`), and the result can be compound
while the varying argument is scalar (a compound constant over a scalar key).

No narrower predicate is sound at this layer. Arity is not a property of the
type, so an arity-1 exemption is unexpressible and a mixed-arity column was
wrong in the other direction through the implicit-projection path. Injectivity
of the element map is what lexicographic order needs, and no cheap element test
delivers it: a magnitude-1 divisor still jumps at 2^63 for an unsigned element,
and element width does not help either, since a tiny `divide` constant sends
every element to `inf`.

Monotonic pruning and read-in-order are given up for arithmetic over a
compound key. Every shape given up answers incorrectly today, scalar keys are
untouched, and the pruning was degenerate anyway: `multiply` over an `Array`
key already read 99 of 100 granules. Date and time keys with a
`Tuple(INTERVAL, INTERVAL)` operand have a scalar result and keep pruning, as
does a `String` key with `INTERVAL`.
Two of the test's assertions could pass without the fix.

The two ORDER BY rows are the only coverage of the mis-sorted-output symptom, and
they depend on read-in-order actually running. CI randomizes
optimize_read_in_order, and with read-in-order off an ordinary sort answers
correctly even without the fix, so those rows asserted nothing in about half of
the runs. Pin the setting for them.

The plus/minus rows used an identity constant, so they could only ever exercise
the BAD_TYPE_OF_FIELD throw and never the wrong-results half. Add a fixture whose
interior element overflows while the transformed endpoints keep their order, which
is exactly the case the endpoint comparison cannot see: without the fix both new
rows drop the matching row and prune every granule away.

No source change: the assertions now fail deterministically on an unpatched
binary instead of intermittently.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 6 findings, 4 AGREE / 2 noted) - click to expand

An independent model reviewed this change cold (no access to the author's evidence) in two rounds,
plus a separate reviewer pass. Every finding below was adjudicated against measurement on
Build-ID-verified binaries, never against argument.

Round 1: 2 majors, both AGREED and fixed (test-only; the source fix was unchanged).

❌ Both ORDER BY assertions were dead in about half of CI runs. tests/clickhouse-test
randomizes optimize_read_in_order, and it is the only randomized input of
read_in_order = query_plan_enable_optimizations && optimize_read_in_order && query_plan_read_in_order.
With it at 0 an ordinary sort answers correctly even on an unpatched binary, which is exactly what
the reference asserts, so the only coverage of the mis-sorted-output symptom was silently vacuous.
Fixed by pinning optimize_read_in_order = 1 for those rows (pin the offender, not a blanket tag).
Verified both ways: with the pin, an unpatched binary reports both rows wrong even when the client
forces the setting off; without the pin, both rows match the reference and prove nothing.

❌ No wrong-results coverage for plus and minus. The existing rows used a [0, 0] constant,
an identity map, so they could only ever exercise the exception path. The gate's stated mechanism was
wrong (it claimed those rows pruned to 2/4 granules on a baseline binary; they actually throw
Code: 169, so they are live and cover the exception symptom), but its requested addition was right.
Two carriers were added over a key holding an Int64 maximum in the interior: the transformed
endpoints keep their order while the interior element overflows, so the granule is pruned away:
unpatched 0 against an oracle's 1, Granules: 0/3. Confirmed directly at
index_granularity = 8, where all rows sit in one granule and it is still reported as 0/1.

Round 2: 1 major and 3 nits. Contract accuracy fixed, source untouched.

❌ The exception example in this description was not reproducible as written. It reused the table
from the first example, whose elements include a 0, so after the fix that query returns
Code: 153 ILLEGAL_DIVISION instead of an answer, so a reader copying both snippets would conclude
the fix does not work. Rewritten to create its own zero-free table (the same shape the test uses,
whose comment already notes the divisor column must be free of zeros): unpatched Code: 169, fixed
1.

⚠️ The related pull requests were linked only inside the HTML comment, which does not render.
Both are now visible Related: lines.

💡 Noted, not blocking: one doc comment writes a method name with parentheses against the repository
convention; and the partition-pruner consumer is untested. Measured, it has no wrong-results carrier
at all, because that path short-circuits monotonicity for a single point, and the exception it did
raise is fixed here for free.

Independently re-derived rather than accepted: the carrier set is closed. Variant, Dynamic
and JSON are rejected as key types outright, LowCardinality of a container and Nullable(Array)
fail type creation, Nullable(Tuple) is reachable and covered, and a Map operand is rejected at
arithmetic type-check. Sibling unary monotonic functions cannot receive a compound argument at all.
All six production consumers of the verdict bail out on a non-monotonic answer rather than proceeding.
The reference is byte-stable across fourteen randomized settings dimensions, and the reported
Granules numbers were re-measured before and after the change.

Gate spend for this review: $42.40 across three rounds.

Session id: cron:clickhouse-review-slot-54:20260728-175800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --queries-file tests/queries/0_stateless/04652_compound_key_monotonicity.sql fails 100% of the time on an unpatched debug build: 12 rows answer differently from the ENGINE = Memory oracle, both ORDER BY rows come back unsorted, and the run then aborts (SIGABRT, Invalid binary search result in MergeTreeSetIndex). No randomization, timing or concurrency involved.
b Root cause explained? Yes. FunctionBinaryArithmeticWithConstants::getMonotonicityForRange derives its verdict from the element arithmetic and never checks that the argument type is a scalar. Arithmetic on an Array/Tuple is element-wise, while the comparison of a compound value is lexicographic, so once two leading elements map to the same output the compound order is decided by a later element unrelated to the input order. Every pre-existing guard in that function models a scalar hazard and calls getSizeOfValueInMemory() / accurateLessOrEqual, which are undefined for a container, so for a compound argument they silently do not apply and the function falls through to is_monotonic = true.
c Fix matches root cause? Yes. The check makes the verdict refuse exactly the case it cannot describe, in the one function all three consumers read (KeyCondition pruning, ReadInOrderOptimizer, actionsDAGUtils / implicit projections). It is not a symptom guard: making the downstream throw survivable would leave the wrong-results and mis-sort halves intact, because those need the verdict itself to be correct.
d Test intent preserved / new tests added? New test 04652_compound_key_monotonicity.{sql,reference}: 31 carrier rows printed keyed-vs-oracle plus 15 preservation rows asserting exact granule counts, so both an under-fire and an over-fire of the check surface in the reference diff. optimize_read_in_order is pinned for the two ORDER BY rows: CI randomizes it, and with read-in-order off an ordinary sort answers correctly even on an unpatched binary, which would have left those rows vacuous in about half the runs. No existing test was removed, weakened or retagged.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Without the fix: RC=134, 61 reference lines differ (12 rows answer wrongly, then the run aborts before the remaining 33). With the fix: RC=0, reference matches, and 100 of 100 runs pass across 50 randomized plus 50 no-randomization runs. Additionally, ten mutations each revert one clause and rebuild (asserting the Build ID moved, so a stale binary cannot fake a pass), turning exactly the rows that clause protects red: removing the check, placing it after the null-endpoint split, narrowing to isArray(), deriving the type from operand position instead of the parameter, dropping the result-type half, dropping the argument-type half, substituting isValueRepresentedByNumber(), dropping the Nullable unwrap, widening to "either operand is compound", and removing the optimize_read_in_order pin (which makes both ORDER BY rows pass on an unpatched binary, proving the pin is load-bearing).
f Fix is general across code paths? Fixed at getMonotonicityForRange, which is the single point read by all three consumers of the false verdict; the test asserts all three (=, range and IN pruning, both ORDER BY shapes, and a mixed-arity table under optimize_use_implicit_projections 0 and 1). A fix in KeyCondition::isFunctionReallyMonotonic was rejected because it is not on the applyMonotonicFunctionsChainToRange path and is never called from ReadInOrderOptimizer.cpp or actionsDAGUtils.cpp, so the mis-sorted output would have survived. The sibling family (negate / FunctionUnaryArithmetic) already carries this same guard.
g Fix generalizes across inputs (params/datatypes/wrappers)? All five monotonic functions (plus, minus, multiply, divide, intDiv); containers Array, Tuple, Array(Array), Nullable(Tuple) and Map; element types Int8, Int32, Int64, Int128, UInt8, UInt64; divisors positive, magnitude 1, straddling 2^63, high-bit unsigned, and 5e-324; arity 1, 2 and mixed within one column; =, range and IN spellings; and both operand sides. LowCardinality cannot contain a container, so that arm of the unwrap is symmetry with the neighbouring code; Nullable(Tuple) is reachable and is a carrier, which the dropped-unwrap mutation proves. Map is fail-closed defence in depth only: a Map operand is rejected earlier with Code 43, so nothing changes for it.
h Backward compatible? (maintainer-approved exception only) Yes, there is no compatibility surface: no new or changed setting, no default change, no serialization or format change. Hence no SettingsChangesHistory.cpp entry and no experimental gate. Analysis simply becomes conservative for shapes that answer incorrectly today.
i Invariants and contracts preserved? The invariant restored is the contract of IFunctionBase::getMonotonicityForRange itself: the verdict must describe the order of the whole argument value, which for a compound value is lexicographic. The check is a pure early return placed before any state is touched, so it holds on all paths including error and early-return ones. It removes two failure modes from key analysis rather than adding any: the BAD_TYPE_OF_FIELD throw on a valid query, and the MergeTreeSetIndex binary-search precondition violation that aborted debug builds. No lifetime, ownership or concurrency surface is involved: no allocation, no locking, references only, and the result-type pointer is null-guarded.

Session id: cron:clickhouse-impl-slot-46:20260728-172200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @george-larionov @Ergus - could you review this? It adds the scalar-type check that FunctionBinaryArithmeticWithConstants::getMonotonicityForRange was missing, so key analysis no longer claims monotonicity for element-wise arithmetic over an Array/Tuple key, whose comparison is lexicographic. You both have context on the two narrower fixes in the same function (#112151, #112156); note this one deliberately makes #112151's two compound preservation controls stop pruning, which is disclosed in the description.

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

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c19da87]

Summary: ✅


AI Review

Summary

This PR makes FunctionBinaryArithmeticWithConstants::getMonotonicityForRange fail closed for compound Array/Tuple/Map inputs or results, so MergeTree key analysis and read-in-order stop treating element-wise arithmetic as monotonic under lexicographic comparison. The implementation matches that contract, the new stateless coverage exercises the wrong-results / mis-sorted-output / exception carriers plus the intended preservation cases, and I did not find a remaining correctness or safety issue in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.10% +0.10%
Branches 78.30% 78.50% +0.20%

Changed lines: Changed C/C++ lines covered: 13/14 (92.86%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c19da87

CI is fully finished on this commit with no failures: all 174 checks completed, zero
FAIL/ERROR rows ingested into the CI database, and the Config Workflow / Style check /
Fast test / Finish Workflow aggregators are all green. There is nothing to own.

Session id: cron:our-pr-ci-monitor:20260729-013000

@PedroTadim

Copy link
Copy Markdown
Member

@nihalzp I think this can be merged?

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Overall LGTM

But worth checking these comments


// For compound types (Tuple, Array, etc.) monotonicity analysis is not applicable: the
// arithmetic is element-wise, while the comparison of a compound value is lexicographic,
// so an element-wise verdict says nothing about the order of the whole value. `type` is the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this valid for every type?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, and the reason is that isNaNField is a tag check rather than a conversion, so for a non-float endpoint it is inert instead of wrong.

isNaNField (src/Core/Field.h:917) forwards to Field::isNaN (:456), which is which == Types::Float64 && std::isnan(get<Float64>()). It only inspects the discriminator, so it returns false for a UInt64, Int64, Int128, Int256, Decimal, String, Array, Tuple or Map endpoint, for Null, and for both infinities, and it cannot throw. Float32 is still covered because a float Field is always stored as Float64 (comment at :915).

That distinction is what makes the guard order here safe. This guard sits above the compound-type guard, so it does see Array and Tuple endpoints. The other spelling of the same test, the local lambda in negate.cpp:107-111, goes through applyVisitor(FieldVisitorConvertToNumber<Float64>(), f), and that visitor throws CANNOT_CONVERT_TYPE for String, Array, Tuple, Map and Object (FieldVisitorConvertToNumber.h:35-52). Had this site used that form, a compound endpoint would have thrown before ever reaching the compound guard.

Measured on the merge commit 339f89d, one keyed MergeTree per cell at index_granularity = 1 against an ENGINE = Log oracle: UInt8, Int64, Date, Decimal(9,2), Float32 with NaN, Float64 with NaN, Nullable(Float64) with NaN, LowCardinality(Float64) with NaN, LowCardinality(Nullable(Int64)), Array(Int64), Tuple(Int64, Int64), IPv4, IPv6 and Nullable(IPv4) all agree with their oracle. An integer key compared against a NaN constant (WHERE a + 1 > nan) also agrees, at 0 rows both ways.

Worth recording since it is easy to misread from the diff: this guard predates the PR. The change only names the previously unnamed type parameter and adds the compound guard below it.

/// (`Nullable(Tuple)` is a reachable key type). Takes a reference rather than a `DataTypePtr`
/// because `getMonotonicityForRange` receives one, and `IDataType::getPtr()` throws for a type
/// that is not owned by a `shared_ptr`.
static bool isCompoundForMonotonicity(const IDataType & type)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This code is exactly the same as NegateMonotonicity::get

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai maybe you can deduplicate the code?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed on the shared part, and I will send a follow-up PR for it, since this one merged before I could apply it.

The identical part is the unwrap prologue: negate.cpp:43-50 and isCompoundForMonotonicity both strip LowCardinality then Nullable by typeid_cast, in that order, and those are the only two copies of it under src/Functions. That is worth extracting into one reference-taking helper. src/Formats/PNGSerializer.cpp:82-88 already has the same helper privately, so a shared one would remove three copies rather than two.

The test that follows it is not the same predicate, though, so I do not want to merge those blindly. isCompoundForMonotonicity asks isArray || isTuple || isMap; negate.cpp:54 asks !isValueRepresentedByNumber(). Those differ for any type that is neither compound nor number-represented, and they are not complements: isValueRepresentedByNumber defaults to false on IDataType (IDataType.h:268) and is overridden true only by DataTypeNumberBase, DataTypeDecimalBase, DataTypeEnum, DataTypeIPv4andIPv6 and DataTypeLowCardinality (delegating). So String, FixedString, UUID and Object are declined by the negate spelling and accepted by mine.

For the binary arithmetic site that difference is currently unreachable, which is why I would rather keep the two tests distinct than widen either one. Measured on 339f89d, String, FixedString, UUID and Enum8 never reach key analysis at all, since plus rejects them at type check with Code: 43 ILLEGAL_TYPE_OF_ARGUMENT. IPv4 and IPv6 do reach it, and both declare isValueRepresentedByNumber() == true (DataTypeIPv4andIPv6.h:41), so both predicates agree there; IPv4, IPv6 and Nullable(IPv4) keys all match an ENGINE = Log oracle. Adopting !isValueRepresentedByNumber() here would therefore be behaviour-neutral today but would start declining monotonicity for any future type that becomes arithmetic-capable without being number-represented, which is a silent pruning loss rather than a correctness change, so it is not something I want to fold into a cleanup.

One constraint for the shared helper: it has to take const IDataType &. getMonotonicityForRange is handed a reference, and IDataType::getPtr throws for a type that is not owned by a shared_ptr, so a DataTypePtr signature would reintroduce that throw at this call site.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, and I will send it as a follow-up PR: this merged at 14:52 UTC, about 38 minutes after the request, so there was no head left to push to.

Details are in the reply on the sibling thread, but in short: the unwrap prologue is genuinely duplicated (this helper and negate.cpp:43-50 are the only two copies under src/Functions, and PNGSerializer.cpp:82-88 has a third privately), so that part becomes one reference-taking helper. The compound test itself I would keep distinct from negate.cpp:54, which asks !isValueRepresentedByNumber(): that is a strictly wider predicate, and unifying on it would be behaviour-neutral today only because String, FixedString, UUID and Enum8 never reach arithmetic key analysis (Code: 43 at type check), while silently declining pruning for any future arithmetic-capable type that is not number-represented.

I will link the follow-up PR here once it is open.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Follow-up PR as promised: #113458

One correction to what I wrote above, since it turned out to be load-bearing for the scope. I said the prologue had two copies under src/Functions and three in total. Measured over all of src/, it is 4 under src/Functions and 8 in src/. I had missed IFunctionCustomWeek.h:47 and IFunctionDateOrDateTime.h:129 because they spell the casts checkAndGetDataType<DataTypeLowCardinality>, which is a literal one-line alias for typeid_cast<const T *> (FunctionHelpers.h:26-29).

So the PR converts 4 sites rather than 2: this one, negate.cpp:43, and those two headers. It adds a raw-pointer overload of removeLowCardinalityAndNullable beside the existing DataTypePtr one, which is what lets these callers reach it at all, given the reference-taking constraint I mentioned. The other 4 carriers are deferred with reasons in the body: KeyCondition.cpp:1789 and :2843 (hottest file in key analysis, several open PRs), SetUtils.cpp:34 (holds a DataTypePtr, so it can just call the existing function), and PNGSerializer.cpp:73 (PR 112846 rewrites that file, and its removeLowCardinalityType half is also used alone).

The test after the prologue stays distinct per site, exactly as described above. No behaviour change.

Two of the four converted sites had no test pinning them: no stateless test combined a negate or week or date-transform key with a LowCardinality or Nullable wrapper and asserted pruning, so a wrong unwrap there landed green. 04747_unwrap_monotonicity_dedup adds that pin; six mutants each fail it 20 of 20 randomized runs.

@Ergus
Ergus added this pull request to the merge queue Jul 29, 2026
Merged via the queue into ClickHouse:master with commit 339f89d Jul 29, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 29, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 30, 2026
…riable-monotonicity

Resolves one conflict in src/Functions/FunctionBinaryArithmetic.h, at the top of
getMonotonicityForRange. Both sides append an independent early-return guard at the
same insertion point and both return the same non-monotonic verdict, so the
resolution keeps both: master's compound-type guard (from the merged ClickHouse#112339) first,
in its original position, then this branch's numeric-operand guard for the
`const / variable` arm.

The two guards are orthogonal: the compound guard rejects Array/Tuple/Map key or
result types, while this branch's guard rejects IPv4/IPv6 operands of a constant
dividend. Neither subsumes the other and neither changes the other's outcome.

Verified line-exact: the resolved file's change set against the merge base is the
union of the two sides (+73/-10 == +51/-9 ours plus +22/-1 master), with no line
added or removed beyond that union.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 30, 2026
Resolve the one conflict in src/Functions/FunctionBinaryArithmetic.h.

Master's merged ClickHouse#112339 inserted a compound-type early return at the top of
getMonotonicityForRange, at the same place this branch inserts the normalized
right_constant. The two additions are orthogonal, so both are kept: the
compound guard runs first, so a compound type returns before the constant is
normalized, and substituteIPType / substituteIPField are unaffected.

Verified the merged file adds and removes exactly the same 55 and 10 lines
against master as this branch did against the merge base, so the resolution
introduces no behaviour of its own. 04652_intdiv_ip_key_monotonicity fails on
master (9 disagreeing rows, then BAD_TYPE_OF_FIELD) and passes here;
04652_compound_key_monotonicity still passes, so master's guard is intact.
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

This PR was merged without a must-backport label, so the automation never produced anything,
and all 5 active release branches still return wrong results for arithmetic over an
Array/Tuple key. @alexey-milovidov could you apply v25.8-must-backport here? That
expands to ['25.8','26.3','26.5','26.6','26.7'], and I measured every one of them as
affected.

Measured on the official per-branch builds, Array(Int64) MergeTree key with rows
[10,100],[11,5],[12,0],[20,0], compared against an ENGINE = Memory oracle over the same
rows:

branch version intDiv(a,10) = [1,0] keyed / oracle intDiv(a,4) = [2,25] keyed / oracle
25.8 LTS 25.8.29.42 0 / 2 wrong 0 / 1 wrong
26.3 26.3.17.99 0 / 2 wrong 0 / 1 wrong
26.5 26.5.6.104 0 / 2 wrong 0 / 1 wrong
26.6 26.6.2.140 0 / 2 wrong 0 / 1 wrong
26.7 26.7.2.56 0 / 2 wrong 0 / 1 wrong
master 26.8.1.1 2 / 2 correct 1 / 1 correct

Silent row loss on a plain SELECT, no error. A scalar key prunes correctly on every
branch, so only the compound shape is affected.

Two things about the cherry-picks, since both produce a backport that merges cleanly and is
still broken:

  1. 25.8 and 26.3 must not take the whole conflict region. Reproducing the automation's
    merge shape, 26.7 is clean and the other four conflict in FunctionBinaryArithmetic.h
    (25.8 and 26.3 in two regions, 26.5 and 26.6 in one). The upper region on master holds my
    compound guard plus an unrelated NaN guard from another PR that uses isNaNField, and
    isNaNField does not exist on 25.8 or 26.3 (it arrived in 34415f0, which is an
    ancestor of 26.5+ only). Taking the master side wholesale there does not compile. The two
    guards are independent, so the resolution is to keep only the compound-type if block.

  2. The test needs one case dropped below 26.6. Line 55 of
    04652_compound_key_monotonicity.sql does SET enable_nullable_tuple_type = 1, which is
    Code: 115 UNKNOWN_SETTING on 25.8, 26.3 and 26.5. That setting is unrelated to this fix,
    so the test would fail there even with the fix applied. Dropping the
    Nullable(Tuple(Int64, Int64)) sub-case and its reference lines is enough; the rest is
    portable.

Everything else the guard needs is already present on all five branches
(isArray/isTuple/isMap, both DataType includes, the return_type member), so after
those resolutions the guard lands whole.

Session id: cron:clickhouse-plan-slot-38:20260802-043400

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

Labels

can be tested Allows running workflows for external contributors 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.

4 participants