Repository navigation
Conversation
…nalysis intDiv(x, -1) is mathematically -x, which is not representable at the signed minimum of the computation width: TYPE_MIN / -1 overflows and folds back onto TYPE_MIN, while TYPE_MIN + 1 maps to TYPE_MAX. The function is therefore neither non-decreasing nor non-increasing on any range containing that minimum. getMonotonicityForRange already models two other intDiv wraps (intDivRangeCrossesSignedWrap for an unsigned dividend, intDivConstReinterpretsNegative for an unsigned divisor) but never modelled this result wrap, so it reported the function monotonic there. MergeTree primary-key analysis then pruned a granule that did hold a matching row, and ReadInOrderOptimizer, which probes with unbounded endpoints and reads only is_monotonic/is_positive, read the part in reverse order and emitted mis-sorted rows. Both symptoms are silent: no error, and the query succeeds. multiply already carries the equivalent guard in its check_overflow lambda; intDiv simply lacked it. The reason these widths are silent rather than a Code 153 throw is that DivideIntegralByConstantImpl::vectorConstant short-circuits b == -1 and deliberately bypasses throwIfDivisionLeadsToFPE. That specialization is registered only for (UInt64|UInt32|Int64|Int32) by a divisor of the same signedness, so with a signed dividend the affected set is exactly an Int32/Int64 dividend with a native signed divisor. Every other operand pair throws instead, at runtime as well as during analysis, so it is not a monotonicity problem and is left alone here. Two helpers are added next to the existing ones, and one guard in each of the two branches that decide intDiv's monotonicity. The containment test is decided per side, so a half-bounded range such as [0, +Inf) genuinely excludes the minimum and keeps being pruned. A range excluding the minimum stays monotonic on that range, but is_always_monotonic becomes false: it means monotonic on the whole input range, and the whole domain of a signed type always contains its minimum. Cost: the unbounded-endpoint verdict is what ReadInOrderOptimizer reads, and it has no range to narrow with, so ORDER BY intDiv(x, -1) loses read-in-order even when the minimum is absent from the data. That is unavoidable at this layer and is the same trade intDivRangeCrossesSignedWrap already makes for unbounded unsigned ranges. Co-Authored-By: Claude Fable 5 <[email protected]>
… minimum An Array/Tuple dividend divided by a scalar constant is evaluated element-wise: executeArrayWithNumericImpl and tupleIntDivByNumber unpack to the element type and re-enter the arithmetic, so the DivideIntegralByConstantImpl specialization is selected per ELEMENT. An element type that wraps instead of throwing therefore carries exactly the same defect as the scalar case. getMonotonicityForRange only ever sees the OUTER dividend type, so the scalar predicate could not detect it: hasInformationAboutMonotonicity gates on the function name alone, and BinaryArithmeticOverloadResolver builds the WithConstants specialization from "one argument is a constant" with no type test at all. An Array(Int64) key therefore fell through to the unchanged always-monotonic verdicts and stayed mis-pruned. Measured carriers, each returning the wrong count() and a mis-sorted ORDER BY against an ENGINE=Memory oracle: Array(Int64), Array(Int32), Array(Array(Int64)), Array(LowCardinality(Int64)), Tuple(Int64, Int64) and the mixed Tuple(Int64, Int8). A compound dividend with a Float, Int128 or high-bit-unsigned divisor throws ILLEGAL_DIVISION rather than wrapping and is not a carrier; Map, Array(Nullable(...)) and a compound divisor are rejected earlier. A compound carrier is reported non-monotonic unconditionally. The endpoints are Array/Tuple Fields whose element-wise containment of the wrap point is not cheaply modelled, mirroring the Decimal-divisor case immediately above, and no width is ever derived from a compound type. Also pin the granule counts for the three preserved-pruning cases that were result-only (a single-point range at the minimum and both unsigned/unsigned cases), so a change that silently stopped pruning them can no longer ship green, and finish a stale comment correction in the sibling bounded branch. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review — 2 review rounds, 8 findings, all adjudicated (click to expand)Before opening this PR I reviewed it independently (a cold reviewer that never edits the code, plus a Totals: 8 findings — 1 blocker, 1 major, 6 nits. All 8 were accepted, none disputed. The two ❌ Blocker (round 1, fixed in the second commit)The carrier predicate was scalar-only, so a compound dividend stayed mis-pruned. Measured, keyed The remedy returns non-monotonic unconditionally for a compound carrier rather than deciding
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-11:20260727-162500 |
|
cc @nihalzp @george-larionov — could you review this? |
|
Workflow [PR], commit [9eb28b4] Summary: ❌
AI ReviewSummaryThis PR correctly fixes the Findings❌ Blockers
Final Verdict❌ Changes requested |
| /// ANY of its elements is: the verdict is about the outer comparison, and one wrapping element is | ||
| /// enough to break its order. Nesting is followed recursively (`Array(Array(Int64))` is a measured | ||
| /// carrier), stripping Nullable/LowCardinality at each level like the scalar path does. | ||
| static bool intDivCompoundDividendWrapsInsteadOfThrowing( |
There was a problem hiding this comment.
This fixes the "outer type hides the element type" bug only for intDivWrapsInsteadOfThrowing, but the same blind spot is still present in the other two intDiv monotonicity carriers. executeArrayWithNumericImpl and tupleIntDivByNumber re-enter the scalar arithmetic on the element type, yet intDivRangeCrossesSignedWrap still checks isUInt(arg_type) on the outer type and intDivConstReinterpretsNegative still checks isInt(arg_type) && isUInt(divisor_type) on the outer type.
That means compound keys are still mis-analysed for the scalar shapes already covered by tests/queries/0_stateless/04340_intdiv_variable_constant_monotonicity.sql: e.g. Array(UInt64) / Tuple(UInt64, ...) with a signed divisor that crosses 2^(w-1) still falls through to the default always-monotonic verdict, and Array(Int8) / Tuple(Int8, ...) with toUInt8(200) still misses the direction flip. Those remain wrong-answer / Invalid binary search result cases for Array/Tuple keys for the same reason this helper was needed for Array(Int64) / -1.
The compound handling needs to be generalized across all three intDiv carrier predicates, not added only for the result-wrap one, and the new test should add Array/Tuple variants of the scalar cases from 04340_intdiv_variable_constant_monotonicity.sql.
There was a problem hiding this comment.
Confirmed — the mechanism is real for both shapes named here. I measured all four against an
ENGINE = Memory oracle, on this PR's head (9eb28b4f, Build ID 497737591e7b6eff) and on the
pristine merge-base (1d4408f7); the two agree, so none of this is introduced by the change:
| shape | keyed | oracle |
|---|---|---|
Array(UInt64) / toInt64(1000000000000000000), values straddling 2^63 |
0 | 1 |
Tuple(UInt64, UInt64) / same |
0 | 1 |
Array(Int8) / toUInt8(200) |
0 | 1 |
Tuple(Int8, Int8) / same |
0 | 1 |
The direction-flip half is worse than described above: the IN / NOT IN spelling of
Array(Int8) / toUInt8(200) does not merely over-prune, it aborts with
Logical error: 'Invalid binary search result in MergeTreeSetIndex' (rc=134 on a debug build).
I am still not widening this PR, and I would rather put the two reasons on record than just assert
them.
1. The suggested remedy is not sufficient — a third mechanism sits underneath it
For a compound dividend the element-wise map has to be injective, not merely monotonic, because
the compound comparison is lexicographic: once two inputs' leading elements collapse onto the same
output, the compound order is decided by a later element that carries no relation to the input order.
Measured with an ordinary positive divisor — no wrap, no reinterpretation, no effective -1 anywhere:
CREATE TABLE k (a Array(Int64)) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 1;
CREATE TABLE m (a Array(Int64)) ENGINE = Memory;
INSERT INTO k VALUES ([10,100]),([11,5]),([12,0]),([20,0]);
INSERT INTO m VALUES ([10,100]),([11,5]),([12,0]),([20,0]);
SELECT count() FROM k WHERE intDiv(a, toInt64(10)) = [toInt64(1), toInt64(0)]; -- 0
SELECT count() FROM m WHERE intDiv(a, toInt64(10)) = [toInt64(1), toInt64(0)]; -- 2EXPLAIN indexes = 1 selects Granules: 0/4; the dropped rows are [11,5] and [12,0]. Same for a
range predicate (> [toInt64(1), toInt64(0)]: 1 vs 2) and for Tuple(Int64, Int64). Controls:
intDiv(a, toInt64(1)) is injective and correct, multiply(a, toInt64(3)) and
multiply(a, toInt64(-1)) are injective and correct, and arity 1 is correct. So the discriminator is
injectivity of the element map crossed with arity >= 2; the result wrap and the direction flip are two
instances of it, and generalising only those two predicates leaves this open.
2. A blanket rejection of compound dividends would delete pruning this PR deliberately keeps
This PR pins two compound preservation controls precisely because the guard has to key on the element
type and the constant rather than on "is compound": Array(Int64) with divisor 10 asserting
Granules: 11/100, and Array(UInt8) with toUInt8(255) asserting Granules: 2/256. Both
re-measured green just now. Rejecting compound outright reddens them.
A per-element decision inside these predicates is also not available:
intDivRangeContainsResultWrapPoint and intDivRangeCrossesSignedWrap derive a width via
IDataType::getSizeOfValueInMemory(), which throws LOGICAL_ERROR for a container type
(src/DataTypes/IDataType.cpp:122-125), and accurateLessOrEqual on an Array/Tuple Field
against an integer Field throws BAD_TYPE_OF_FIELD (src/Common/FieldAccurateComparison.cpp:144,
:241 — the visitor has no container arm). That is why the guard added here returns an unconditional
non-monotonic verdict for a compound carrier instead of deciding per element, and any generalisation
faces the same constraint. Arity cannot be read off the type either: a single Array column can hold
[5] and [10,100] in the same table, so a type-level predicate cannot know it.
So: mechanism conceded, all four shapes confirmed as carriers, and the sibling-predicate blindness is
already disclosed in the description under "Deliberately out of scope". It has a different root cause
and needs its own test matrix, so per the one-concern-per-PR convention it belongs in its own change
rather than growing this one. I have opened a follow-up carrying the measurements above, the third
(injectivity) mechanism, and the constraint that any fix must not redden the two preservation controls.
If a single PR is preferred, say so and I will fold it in here instead.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 40/41 (97.56%) · Uncovered code |
CI finish ledger - 9eb28b4Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not PR-caused. This signature is trunk-wide and independent of this diff: over the last 30 days The one merged sub-cause fix for this family that I know of (the unkillable hang in random All other checks are green: 159 success, 17 skipped, Session id: cron:our-pr-ci-monitor:20260728-020000 |
|
Closing: superseded by #113048. This PR stopped key analysis from claiming monotonicity for I merged master and measured it with two builds differing only by this PR's change to Two further reasons not to land it as written:
Master still reports Worth noting separately: #113048 carries no backport label, and 26.7 and 26.6 do not contain it, |
Related: #90461
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes wrong results for queries where a
MergeTreeprimary key expression is wrapped inintDivwith an effective divisor of-1.intDiv(x, -1)maps the signed minimum of the computation width onto itself instead of onto the maximum, so it is not monotonic on any range containing that minimum, but it was reported as monotonic. Primary-key analysis therefore pruned a granule that did hold a matching row, andORDER BY intDiv(x, -1)returned mis-sorted rows through the read-in-order optimization. Both now return correct results.Description
intDiv(x, -1)is mathematically-x, which is not representable at the signed minimum of the computation width:TYPE_MIN / -1overflows and folds back ontoTYPE_MIN, whileTYPE_MIN + 1maps toTYPE_MAX. The function is therefore neither non-decreasing nor non-increasing on any range containing that minimum.FunctionBinaryArithmeticWithConstants::getMonotonicityForRangealready models two otherintDivwraps (intDivRangeCrossesSignedWrapfor an unsigned dividend,intDivConstReinterpretsNegativefor an unsigned divisor) but never modelled this result wrap, so it reported the function monotonic there.multiplyalready carries the equivalent guard in itscheck_overflowlambda (/// TYPE_MIN / -1 is UB for native signed types.);intDivsimply lacked it.Two user-visible, silent, default-reachable symptoms (no error,
RC=0):The fix adds three helpers next to the existing ones and two guards in each of the two branches that decide
intDiv's monotonicity:intDivWrapsInsteadOfThrowing— is this operand pair one that divides by an effective-1and takes the FPE-suppressing vectorized path? The wrap is produced only byDivideIntegralByConstantImpl::vectorConstant, which short-circuitsb == -1and deliberately avoidsthrowIfDivisionLeadsToFPE. With a signed dividend those registered specializations are anInt32/Int64dividend with a native signed divisor. Every other scalar operand pair throwsILLEGAL_DIVISIONinstead — at runtime as well as during analysis, verified onENGINE = Memory— so it is not a monotonicity problem and is deliberately left alone here.intDivCompoundDividendWrapsInsteadOfThrowing— the same wrap one type wrapper up. AnArray/Tupledividend divided by a scalar constant is evaluated element-wise, so an element type that wraps carries the same defect, whilegetMonotonicityForRangesees only the outer type and the scalar predicate above cannot detect it. Nesting is followed recursively, and a tuple is a carrier as soon as any one of its elements is. Measured carriers:Array(Int64),Array(Int32),Array(Array(Int64)),Array(LowCardinality(Int64)),Tuple(Int64, Int64)and the mixedTuple(Int64, Int8)— each returned the wrongcount()and a mis-sortedORDER BYbefore this change. A compound dividend with a Float,Int128or high-bit-unsigned divisor throwsILLEGAL_DIVISIONand is not a carrier. Because the endpoints areArray/TupleFields whose element-wise containment of the wrap point is not cheaply modelled, a compound carrier is reported non-monotonic unconditionally, mirroring the Decimal-divisor case immediately above.intDivRangeContainsResultWrapPoint— does the analysed range contain that minimum? Decided per side, so a range like[0, +Inf)genuinely excludes it and keeps being pruned.A range containing the wrap point now reports
{false, true, false, false}(non-monotonic, no pruning), exactly asmultiplydoes on overflow. A range excluding it stays monotonic on that range, butis_always_monotonicbecomesfalse: it means "monotonic on the whole input range", and the whole domain of a signed type always contains its minimum.Cost, stated explicitly
The unbounded-endpoint verdict is what
ReadInOrderOptimizerreads, and it has no range to narrow with, soORDER BY intDiv(x, -1)loses the read-in-order optimization even when the minimum is absent from the data (measured: such a query usesInReverseOrdertoday andDefaultafter this change). That is unavoidable at this layer — the whole column may contain the minimum and the unbounded probe cannot know — and it is the same tradeintDivRangeCrossesSignedWrapalready makes for unbounded unsigned ranges. It is a deliberate correctness-over-optimization choice, not a free fix.Ordinary
intDivpruning is unaffected, and the test asserts that: a positive divisor, a divisor that is not effectively-1, unsigned/unsigned, a Float divisor, a half-bounded range excluding the minimum, and a single-point range at the minimum all keep pruning exactly as before, with the granule counts pinned — tenEXPLAIN indexes = 1assertions in all, including two that pin anArraydividend with a positive divisor and anArray(UInt8)dividend, so the new compound guard is provably keyed on the element type and the constant rather than on "is compound".Deliberately out of scope
Code 153throws at other widths. No verdict this function can return fixes them. If the analysed range excludes the minimum a correct guard must report the range monotonic (otherwise valid pruning is lost), andKeyCondition::applyFunctionthen evaluates the chain over the entire index column, so an out-of-range minimum still in that column still throws. If the analysed range contains the minimum at a throwing width, the query throws at runtime too (theENGINE = Memoryoracle exits with the same error), so it was never analysis-injected. Same reasonsingle_pointpartition pruning is untouched:applyMonotonicFunctionsChainToRangeshort-circuits monotonicity whensingle_point, so nothing insidegetMonotonicityForRangecan reach it.intDivpredicates read the outer dividend type too.intDivRangeCrossesSignedWrapgates onisUInt(arg_type)andintDivConstReinterpretsNegativeonisInt(arg_type) && isUInt(divisor_type), so anArray/Tupledividend fails both exactly as it failed the scalar wrap predicate before this change. They model different mechanisms (a step function at2^(w-1)for an unsigned dividend, and a direction flip for a high-bit-unsigned divisor), so extending them is a separate concern with its own root cause and its own test matrix, and is tracked separately rather than bundled here.const / variablebranch reports the inverted direction on a strictly-negative range (wrong results forintDivanddivide, no wrap involved), andthrowIfDivisionLeadsToFPEcompares a floating-point dividend againstnumeric_limits<Float>::min(), which is the smallest positive value, sointDiv(2.2250738585072014e-308, -1.0)throws spuriously.