Repository navigation
Fix divideDecimal for divisors that do not fit an Int256 long division - #118628
yakov-olkhovskiy wants to merge 2 commits into
Conversation
`DecimalOpHelpers::divide` performs a digit-by-digit long division and keeps
the running remainder in an `Int256`. That value reaches `divisor * 10 + 9`,
which is past the `Int256` maximum of about `5.8 * 10^76` as soon as the
divisor spans the full 76-digit `Decimal256` precision. The multiplication
wrapped around, `temp / divisor` then produced "digits" outside `0` to `9`,
and `divideDecimal` returned a silently wrong result:
SELECT divideDecimal(toDecimal256('1' || repeat('0', 75), 0),
toDecimal256('7' || repeat('0', 75), 0), 20);
0.16723628755473868519 -- was, instead of 0.14285714285714285714
Over random dividends with a 76-digit divisor, roughly one call in five came
out wrong.
The running value is now unsigned, which covers every value the `Decimal256`
type can hold: 76 digits keep `divisor * 10 + 9` below `10^77` and `UInt256`
reaches past `1.15 * 10^77`. Decimal addition and multiplication do not
enforce the declared precision, though, so a field value can be wider than
that - `toDecimal256(repeat('9', 76), 0) * 2` already is - and such a divisor
is divided in 512 bits instead.
Picking the narrower type where it fits also makes the common case faster,
because unsigned 256-bit division is cheaper than signed: a 42-digit dividend
over a two-digit divisor, the shape the `divide_decimal` performance test
measures, went from 45.1 ms to 18.4 ms per 40000 divisions in a standalone
benchmark of the loop.
Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
|
|
Workflow [PR], commit [7cd7606] Summary: ✅
AI ReviewSummaryThis PR widens the internal Findings❌ Blockers
Final Verdict
LLVM Coverage ReportMeasured on commit 7cd7606.
Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code |
| { | ||
| using WideDivisor = wide::integer<512, unsigned>; | ||
|
|
||
| /// `Int256` cannot hold the magnitude of its own minimum, so the widening comes first. |
There was a problem hiding this comment.
divide now knows how to widen INT256_MIN safely, but divideDecimal still computes the absolute values in signed 256 bits before this helper sees them: a.value * sign_a at src/Functions/divideDecimal.cpp:33 and b.value * sign_b at src/Functions/divideDecimal.cpp:50. A Decimal256 carrying the signed minimum is already user-reachable via reinterpret(toInt256('-57896044618658097711785492504343953926634992332820282019728792003956564819968'), 'Decimal256(0)') (see tests/queries/0_stateless/04107_count_digits_int_min_ubsan.sql), so divideDecimal still overflows or wraps before the widened division path runs.
Please move sign stripping behind a widening step for both operands, or add a shared helper that produces digits / divisor magnitude without ever materializing abs(INT256_MIN) in Int256, and add a regression for the signed-minimum Decimal256 as both divisor and dividend.
DecimalOpHelpers::divideperforms a digit-by-digit long division and keeps the running remainder in anInt256. That value reachesdivisor * 10 + 9, which is past theInt256maximum of about5.8 * 10^76as soon as the divisor spans the full 76-digitDecimal256precision. The multiplication wrapped around,temp / divisorthen produced "digits" outside0to9, anddivideDecimalreturned a silently wrong result:The divisor does not have to be written out in full to reach that size, because decimal addition and multiplication do not enforce the precision the type declares:
The running value is now unsigned, which covers every value the
Decimal256type can hold: 76 digits keepdivisor * 10 + 9below10^77, andUInt256reaches past1.15 * 10^77. A divisor wider than the declared precision, as in the second example, does not fit a 256-bit division at all and is divided in 512 bits instead.Picking the narrower type where it fits also makes the common case faster, because unsigned 256-bit division is cheaper than signed. On the
divideDecimalshape fromtests/performance/wide_integer_division.xml, over 2000000 rows so that the arithmetic dominates process start-up, the median goes from 8.27 s to 6.71 s, a factor of 1.23. The isolated loop is about 2.4 times faster; the end-to-end gain is smaller because building the digit vector and reassembling the result cost the same either way.Verified against the binaries CI built for this branch and for the head of #118346, which have byte-identical compiler flags:
masteron the first ten queries and passes on the last three, which use divisors small enough that the old code was already correct. Every expected value was cross-checked against exact arithmetic in a wider type.divideDecimalcalls with operands spanning the whole precision,masterdisagrees with exact arithmetic on 75 and this branch on none. Exactly those 75 results change; the other 39925 are byte-identical, so nothing that was already correct moved.masteris wrong on 335 and this branch on none.02475_precise_decimal_arithmetics,03314_divide_decimal_short_circuit,03456_wide_integer_cross_platform_consistencyand03457_wide_integer_double_conversion_edge_casesall still pass.This touches the same lines as #118346, which fixes an unrelated off-by-one in the same loop, so whichever merges second needs a trivial conflict resolution. The two fixes are independent: the test here is unaffected by that off-by-one, and it was verified to produce the same reference under either loop bound.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
divideDecimalreturning a silently wrong result when the divisor is large enough that the intermediate value of the long division leaves theInt256range, which happens once the divisor spans the full 76-digitDecimal256precision.Workflow [PR]
Sync PR [sync-upstream/pr/118628]