Repository navigation
Fix wrong intDiv/divide monotonicity for a Decimal dividend with a large constant divisor - #116608
Conversation
…rge constant divisor intDiv and divide with a Decimal dividend compute in the decimal's own native signed width (DecimalBinaryOperation::NativeResultType) and materialise the constant divisor into that width with static_cast. For Decimal(5, 4) that width is Int32, so intDiv(a, -9223372036854775807) actually divides by 1 and increases. getMonotonicityForRange derived the direction from the untruncated literal and reported decreasing, and its only Decimal guard tested the divisor, which is the wrong operand for this shape. Key analysis then called Range::invert() on a range whose values never reversed, so left > right. For a set atom MergeTreeSetIndex::checkInRange then gets begin > end and hits its debug-only assertion, reported by the AST fuzzer as STID 3252-3a4a. For a range atom there is no assertion at all, so every matching granule is pruned away and the query silently returns wrong results in release builds too: on Decimal(5, 4) data holding 0..9, WHERE intDiv(a, -9223372036854775807) > 4 returned 0 rows where 5 match. Add one shared predicate, decimalDivConstDivisorTruncates, and call it from both variable / constant branches of getMonotonicityForRange. The second branch handles ranges with an infinite endpoint, which forAnyHyperrectangle produces routinely, so a fix applied only to the finite-endpoint branch leaves those exposed; a mutant that removes the call from the infinite branch alone still reddens two of the new test arms. The predicate is a round-trip test rather than a blanket rejection, so intDiv(decimal_col, small_const) keeps its pruning, and it is gated on an integer divisor because a Float divisor converts both operands to Float64 and stays order preserving. The defect does not depend on the literal's sign: a positive 9223372036854775807 casts to Int32 -1, so the function decreases while the claim says it increases, and that fails the same way. Both directions are covered by test arms, as are all the invariant carriers: divide as well as intDiv, both checkInRange overloads, IN and NOT IN, range atoms as well as set atoms, ascending and DESC keys, and the wider Decimal widths where the same constant survives the cast. This is the third defect of this family, after ClickHouse#107586 and ClickHouse#113048; ClickHouse#112156 fixed the mirror case of a constant dividend. Co-Authored-By: Claude Opus 5 <[email protected]>
Two comments in 04340_intdiv_variable_constant_monotonicity.sql stated that the Decimal guard rejects only a Decimal divisor. The monotonicity predicate here also rejects an integer divisor whose value does not survive the cast into the dividend's native width, so that claim no longer holds. Both comments now state the surviving-cast condition that actually keeps their own arms monotonic: those arms use Decimal64(0), whose native width is Int64, and the constant 10 survives that cast. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex). 2 findings; the re-review after the
Also noticed and deliberately not pursued: on the same shape a constant whose low bits are zero casts to Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-48:20260826-222900 |
Pre-PR validation gate
Also verified: 50/50 runs of the changed test under randomized settings; a 238-test sweep of the |
|
Workflow [PR], commit [87e9996] Summary: ✅
AI ReviewSummaryThis PR fixes primary-key monotonicity analysis for Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 87e9996.
Changed lines: Changed C/C++ lines covered: 21/22 (95.45%) · Uncovered code |
|
cc @tiandiwonder @george-larionov, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units32 translation units recompiled, 467 s compile time in total, 32 of them have a recent master baseline. |
| case sizeof(Int128): return exceeds(std::type_identity<Int128>{}); | ||
| case sizeof(Int256): return exceeds(std::type_identity<Int256>{}); |
There was a problem hiding this comment.
These two arms have no coverage, and they're reachable as wrong results rather than just lost pruning: on an unfixed binary intDiv(toDecimal256(5,4), toUInt256('115792089237316195423570985008687907853269984665640564039457584007913129639935')) is -5, same as intDiv(a, -1). An all-ones constant casts to -1, so the quotient varies across the range and the direction reverses exactly like the Decimal32 / 4294967295 case you already cover.
Two traps when adding the cells, both of which cost me a wrong first measurement: a bare literal that wide parses as Float64 (toTypeName(340282366920938463463374607431768211455) is Float64), so it takes the Decimal-with-Float path and never reaches this switch; and the constant has to arrive in a type wider than the decimal — toUInt128(<UInt128 max>) against Decimal(38,4) does not truncate, while the same value as toUInt256(...) does.
There was a problem hiding this comment.
Added both arms in f7ac9a2. Your reproducer holds verbatim on a pristine master binary: intDiv(toDecimal256(5, 4), toUInt256('115792...639935')) is -5, byte-equal to intDiv(a, -1), with f(0) = 0 and f(9) = -9.
I made the two cells range atoms rather than set atoms, so they fail as wrong results in every build instead of only on the debug assertion. Unfixed, on 0..9 with index_granularity = 2:
indexed countIf
Decimal(38, 4) < -4 0 5
Decimal(76, 4) < -4 0 5
The gap is where you said it is. With case sizeof(Int128) neutered the published file still passes (43/43 reference lines), and the same for case sizeof(Int256); each added arm reddens only for its own arm, and the keep-pruning and bare-literal cells stay green under both mutants.
One correction on the second trap, since the type width is not what cost you the measurement: the constant does not have to be wider than the decimal. toUInt128('340282366920938463463374607431768211455') against Decimal(38, 4) does truncate to -1, and that arm aborts. What is inert is the bare literal, which is trap 1 again: it round-trips through Float64 and arrives as 340282366920938463426481119284349108225, so the effective divisor is -36893488147419103231 rather than -1, the quotient is a constant 0, and the direction never reverses. On a dividend large enough to separate the two:
intDiv(toDecimal128('92233720368547758070', 4), toUInt128(340282366920938463463374607431768211455)) = -2
intDiv(toDecimal128('92233720368547758070', 4), -36893488147419103231) = -2
intDiv(toDecimal128('92233720368547758070', 4), toUInt128('340282366920938463463374607431768211455')) = -92233720368547758070
intDiv(toDecimal128('92233720368547758070', 4), -1) = -92233720368547758070
That is why the test comment pins the string spelling rather than the divisor's width.
| case sizeof(Int64): return exceeds(std::type_identity<Int64>{}); | ||
| case sizeof(Int128): return exceeds(std::type_identity<Int128>{}); | ||
| case sizeof(Int256): return exceeds(std::type_identity<Int256>{}); | ||
| default: return true; |
There was a problem hiding this comment.
optional: a trailing clause here would save the next reader a check — it's the one branch whose intent isn't self-evident.
something like "unreachable for the four Decimal widths above; fails close if a new one appears".
There was a problem hiding this comment.
Added verbatim in f7ac9a2:
default: return true; /// unreachable for the four `Decimal` widths above; fails close if a new one appearsReported by @ tiandiwonder on the review: the two wider arms of the switch in decimalDivConstDivisorTruncates had no coverage, and the class is reachable as wrong results rather than only lost pruning. Measured on a pristine master binary. An all-ones unsigned constant casts to -1, so a range atom over a Decimal(38, 4) or Decimal(76, 4) key returns 0 rows where 5 match, and the set atom aborts with 'Invalid binary search result in MergeTreeSetIndex'. The published file is blind to both arms: with case sizeof(Int128) neutered it still passes 43/43, and likewise for case sizeof(Int256), while each added arm reddens for its own arm only. The constant has to arrive as a string. A literal that wide parses as Float64, so toUInt128(340282366920938463463374607431768211455) delivers 340282366920938463426481119284349108225, whose Int128 cast is a large negative divisor rather than -1: the quotient is then a constant 0, the direction never reverses, and the arm is inert. Also adds the trailing clause on the default arm that he asked for. Co-Authored-By: Claude Opus 5 <[email protected]>
CI finish ledger for f7ac9a2Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
One red out of 175 checks. Owner evidence: the abort is in Session id: cron:our-pr-ci-monitor:20260827-170000 |
| CREATE TABLE t_intdiv_mono (a Decimal(38, 4)) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 2; | ||
| INSERT INTO t_intdiv_mono SELECT toDecimal128(number, 4) FROM numbers(10); | ||
| SELECT (SELECT count() FROM t_intdiv_mono WHERE intDiv(a, toUInt128('340282366920938463463374607431768211455')) < -4) | ||
| = (SELECT countIf(intDiv(a, toUInt128('340282366920938463463374607431768211455')) < -4) FROM t_intdiv_mono); |
There was a problem hiding this comment.
the in-range control for the Int128 arm — without it an always-true mutant here passes.
| = (SELECT countIf(intDiv(a, toUInt128('340282366920938463463374607431768211455')) < -4) FROM t_intdiv_mono); | |
| = (SELECT countIf(intDiv(a, toUInt128('340282366920938463463374607431768211455')) < -4) FROM t_intdiv_mono); | |
| SELECT (SELECT count() FROM t_intdiv_mono WHERE intDiv(a, -3) IN (-2)) | |
| = (SELECT countIf(intDiv(a, -3) IN (-2)) FROM t_intdiv_mono); | |
| SELECT count() FROM (EXPLAIN indexes = 1 SELECT sum(a) FROM t_intdiv_mono WHERE intDiv(a, -3) IN (-2)) | |
| WHERE explain LIKE '%Granules: 3/5%'; |
There was a problem hiding this comment.
Applied, plus the same pair on the Int256 arm and the four reference rows: 87e999637dfa365.
Confirmed blind, with one build carrying two independently togglable per-case mutations. With case sizeof(Int128) forced to true, the published 45-line file is 45/45 green and the new file reddens on exactly one line, the Decimal128 granule assertion. case sizeof(Int256) is the mirror image, and neither touches the Decimal64 granule assertion, so each new line is load-bearing for its own arm.
One detail: the count-equality line is not what catches that mutant, because an over-declining guard still returns the right rows. The Granules: 3/5 line is. I kept both, since the pair is what the Decimal64 block above already asserts.
I also checked the attribution, since a granule string can come from the automatic statistics part pruner rather than the key: Indexes: holds a single PrimaryKey entry on both widths, and the match survives use_skip_indexes = 0 and use_statistics_for_part_pruning = 0. 30/30 under full randomization.
A separate commit in the same push backticks the literal names in the comment lines this pull request added, per .claude/CLAUDE.md.
| CREATE TABLE t_intdiv_mono (a Decimal(76, 4)) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 2; | ||
| INSERT INTO t_intdiv_mono SELECT toDecimal256(number, 4) FROM numbers(10); | ||
| SELECT (SELECT count() FROM t_intdiv_mono WHERE intDiv(a, toUInt256('115792089237316195423570985008687907853269984665640564039457584007913129639935')) < -4) | ||
| = (SELECT countIf(intDiv(a, toUInt256('115792089237316195423570985008687907853269984665640564039457584007913129639935')) < -4) FROM t_intdiv_mono); |
There was a problem hiding this comment.
same for the Int256 arm; Granules: 3/5 holds on Decimal(76, 4) too.
| = (SELECT countIf(intDiv(a, toUInt256('115792089237316195423570985008687907853269984665640564039457584007913129639935')) < -4) FROM t_intdiv_mono); | |
| = (SELECT countIf(intDiv(a, toUInt256('115792089237316195423570985008687907853269984665640564039457584007913129639935')) < -4) FROM t_intdiv_mono); | |
| SELECT (SELECT count() FROM t_intdiv_mono WHERE intDiv(a, -3) IN (-2)) | |
| = (SELECT countIf(intDiv(a, -3) IN (-2)) FROM t_intdiv_mono); | |
| SELECT count() FROM (EXPLAIN indexes = 1 SELECT sum(a) FROM t_intdiv_mono WHERE intDiv(a, -3) IN (-2)) | |
| WHERE explain LIKE '%Granules: 3/5%'; |
There was a problem hiding this comment.
Applied. Granules: 3/5 does hold on Decimal(76, 4), and case sizeof(Int256) forced to true reddens this arm's granule line and nothing else in the file.
| 1 | ||
| 1 | ||
| 1 | ||
| 1 |
There was a problem hiding this comment.
four more rows for the two suggestions above.
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 |
There was a problem hiding this comment.
Added, four rows. Every new statement prints 1, so appending them is equivalent to interleaving them at their statements.
The Decimal128 and Decimal256 arms added in f7ac9a2 only assert that the out-of-native-width constant no longer returns wrong rows. They are blind to the opposite regression: a decimalDivConstDivisorTruncates that returns true for those two widths unconditionally keeps the answers correct and silently drops key-range pruning. Each arm now carries the in-range pair the Decimal64 block already has, a count-equality check and a `Granules: 3/5` assertion for `intDiv(a, -3)`. Measured with one build carrying two independently togglable per-case mutations. With `case sizeof(Int128)` forced to true the published 45-line file stays green and the new file reddens on exactly one line, the Decimal128 granule assertion; `case sizeof(Int256)` is the mirror image; both leave the Decimal64 granule assertion green. The matched string is the PrimaryKey entry of the plan's index chain on both widths, unchanged by `use_skip_indexes = 0` and `use_statistics_for_part_pruning = 0`. Requested by tiandiwonder.
`.claude/CLAUDE.md` asks for literal names from the ClickHouse SQL language, classes and functions, and literal excerpts from log messages to be wrapped in inline code blocks, and for method names to be written as `f` rather than `f()`. Applies to the comment lines this pull request added; the pre-existing comments in the file are left alone.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results and a
LOGICAL_ERRORin primary key analysis forintDivanddivideover aDecimalkey with an integer constant divisor that does not fit the decimal's native width. Such a query could return no rows at all instead of the matching ones.Description
Related: #90461, #108096. Found by the AST fuzzer as
Logical error: Invalid binary search result in MergeTreeSetIndex, STID3252-3a4a: report.#108096 read this STID as a possible separate lazy-
FINALcause, because the query CI records against an aborting id is the pre-fuzz text. The query that actually aborted isintDiv(a, -9223372036854775807) GLOBAL NOT IN (10)on aDecimal(5, 4)key, so it is this family.intDiv/dividewith aDecimaldividend computes in the decimal's own native signed width and casts the constant divisor into that width. ForDecimal(5, 4)that width isInt32, sointDiv(a, -9223372036854775807)really divides by1and increases, whilegetMonotonicityForRangederives the direction from the untruncated literal and reports decreasing. Key analysis then inverts a range whose values never reversed, soleft > right.The existing
Decimalguard tested the divisor, which is the wrong operand for this shape. The fix adds one shared predicate ("the constant does not survive the cast into the dividend's native width") and calls it from bothvariable / constantbranches (the second handles ranges with an infinite endpoint; fixing only the first leaves those exposed). A constant that does survive the cast keeps its pruning, and aFloatdivisor is unaffected because it computes in floating point.The user-visible half needs no debug build: for a range predicate there is no assertion, so on
Decimal(5, 4)dataWHERE intDiv(a, -9223372036854775807) > 4returned 0 rows where 5 match. Both truncation directions are covered: a positive literal casting to-1fails the same way. Third defect of this family after #107586 and #113048.04340_intdiv_variable_constant_monotonicityis extended; it reddens without this fix and passes with it, 50/50 under randomization.Workflow [PR]
Sync PR [sync-upstream/pr/116608]
Version info
26.9.1.410(included in26.9and later)