Repository navigation
Fix wrong results, mis-sorted output and an exception in key analysis of arithmetic over Array/Tuple values - #112339
Conversation
`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.
Internal second-model review (2 rounds, 6 findings, 4 AGREE / 2 noted) - click to expandAn independent model reviewed this change cold (no access to the author's evidence) in two rounds, Round 1: 2 majors, both AGREED and fixed (test-only; the source fix was unchanged). ❌ Both ❌ No wrong-results coverage for 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
💡 Noted, not blocking: one doc comment writes a method name with parentheses against the repository Independently re-derived rather than accepted: the carrier set is closed. Gate spend for this review: $42.40 across three rounds. Session id: cron:clickhouse-review-slot-54:20260728-175800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-46:20260728-172200 |
|
cc @george-larionov @Ergus - could you review this? It adds the scalar-type check that |
|
Workflow [PR], commit [c19da87] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 13/14 (92.86%) · Uncovered code |
CI finish ledger — c19da87CI is fully finished on this commit with no failures: all 174 checks completed, zero Session id: cron:our-pr-ci-monitor:20260729-013000 |
|
@nihalzp I think this can be merged? |
Ergus
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
This code is exactly the same as NegateMonotonicity::get
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…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.
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.
|
This PR was merged without a must-backport label, so the automation never produced anything, Measured on the official per-branch builds,
Silent row loss on a plain Two things about the cherry-picks, since both produce a backport that merges cleanly and is
Everything else the guard needs is already present on all five branches Session id: cron:clickhouse-plan-slot-38:20260802-043400 |
Related: #112231
Related: #112151
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results, wrongly ordered
ORDER BYoutput and aBAD_TYPE_OF_FIELDexception when the primary key is anArrayorTupleand the query appliesplus,minus,multiply,divideorintDivto 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::getMonotonicityForRangedecided monotonicity from the element arithmetic without checking that its argument type is a scalar. Arithmetic on anArray/Tupleis 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.
EXPLAIN indexes = 1reportedParts: 0/1,Granules: 0/4.[10,100] < [11,5]lexicographically, butintDiv(., 10)maps them to[1,10]and[1,0]: the leading elements tie and the order inverts.2. Wrongly ordered output.
ReadInOrderOptimizerreads the same verdict and skipped the sort:3. A valid query threw. With the compound value on the right of the operator, or with a compound constant, analysis compared an
Arrayendpoint against an integer:The throw happens inside key analysis, so no query-level setting avoids it. In the
INspelling the same class of shape violated theMergeTreeSetIndexbinary-search invariant and aborted a debug build.All five monotonic functions are affected:
plusandminusthrough a compound constant against a compound key,multiplythrough a compound constant against a scalar key and throughTuple * Tuple(which lowers todotProductand has a scalar result),divideandintDivthrough every shape above.The fix rejects monotonicity in
getMonotonicityForRangewhen the unwrapped argument type or the unwrapped result type isArray/Tuple/Map. This is the statementnegatealready makes in tree (src/Functions/negate.cpp: "For compound types (Tuple, Array, etc.) monotonicity analysis is not applicable.") and thatFunctionUnaryArithmeticcarries;FunctionBinaryArithmeticwas missing it. The checked type comes from thetypeparameter, which callers already set to the varying argument's type, not from operand position, which is the defect51ff0e13ea2b26fixed. 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:
DataTypeArraystores only the nested type, so oneArray(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.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 toinf).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_strictdoes not work either:dividereports 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]overnumbers(100)withindex_granularity = 1,plus,minus,divideandintDivall prune tightly today (Granules: 2/100for point predicates,51/100for a range) and after this change read every granule. Onlymultiplywas 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:
plus[[1,0],[1,9223372036854775807],[2,0]],plus(a, [0,1]) = [1,-9223372036854775808]Granules: 0/3)intDiv[[1,0],[1,25],[2,0]],intDiv(a, 10) = [0,2]divide[[9007199254740992,5],[9007199254740993,1]],divide(a, 1) = [9007199254740992,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/DateTime64keys with aTuple(INTERVAL, INTERVAL)operand have a scalar result and keep pruning (asserted, on both operand sides), as does aStringkey withINTERVAL.The new test
04652_compound_key_monotonicityprints every keyed answer beside anENGINE = Memoryoracle 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.Mapis included in the check as fail-closed defence in depth; aMapoperand is rejected earlier withCode 43today, 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
intDivconstant that reinterprets to an effectively negative value) and pins two compound preservation controls,Granules: 2/100forintDiv(Array(Int64), 10)andGranules: 2/256forintDiv(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-treeis clean both ways).Version info
26.8.1.358(included in26.8and later)