Skip to content

Fix divideDecimal for divisors that do not fit an Int256 long division - #118628

Draft
yakov-olkhovskiy wants to merge 2 commits into
masterfrom
cursor/divide-decimal-int256-overflow-8fd8
Draft

yakov-olkhovskiy wants to merge 2 commits into
masterfrom
cursor/divide-decimal-int256-overflow-8fd8

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

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   -- instead of 0.14285714285714285714

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:

WITH toDecimal256(repeat('9', 76), 0) AS n SELECT divideDecimal(n, n + n, 20);

0.00482076400002501942   -- instead of 0.5

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. 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 divideDecimal shape from tests/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:

  • The new test fails on master on 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.
  • Over 40000 randomly generated divideDecimal calls with operands spanning the whole precision, master disagrees 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.
  • Over 500 calls whose divisor is built by decimal arithmetic and so exceeds the declared precision, master is wrong on 335 and this branch on none.
  • 02475_precise_decimal_arithmetics, 03314_divide_decimal_short_circuit, 03456_wide_integer_cross_platform_consistency and 03457_wide_integer_double_conversion_edge_cases all 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):

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

Fix divideDecimal returning a silently wrong result when the divisor is large enough that the intermediate value of the long division leaves the Int256 range, which happens once the divisor spans the full 76-digit Decimal256 precision.

Open in Web Open in Cursor 

Workflow [PR]
Sync PR [sync-upstream/pr/118628]

`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]>
@CLAassistant

CLAassistant commented Sep 7, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ alexey-milovidov
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7cd7606]

Summary: ✅


AI Review

Summary

This PR widens the internal divideDecimal long-division state so wide positive divisors no longer corrupt the quotient, but the signed-minimum Decimal256 path is still broken before the widened helper is reached. Because that input is already user-reachable and the new regression test does not cover it, I would keep this PR blocked.

Findings

❌ Blockers

  • [src/Functions/divideDecimal.cpp:33,50] divideDecimal still materializes abs(INT256_MIN) in signed 256-bit arithmetic via a.value * sign_a and b.value * sign_b before the new DecimalOpHelpers::divide widening logic runs. A Decimal256(0) carrying the signed minimum is already reachable through reinterpret(toInt256('-57896044618658097711785492504343953926634992332820282019728792003956564819968'), 'Decimal256(0)'), so these multiplications can still overflow or wrap and return a wrong result for a signed-minimum dividend or divisor. Move sign stripping behind a widening step for both operands, or add a helper that produces digits and divisor magnitude without ever forming abs(INT256_MIN) in Int256, and add a focused regression for signed-minimum Decimal256 values in both positions.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: fix the signed-minimum Decimal256 path in divideDecimal so magnitude extraction never happens in Int256, and add a regression that exercises signed-minimum Decimal256 as both dividend and divisor.

LLVM Coverage Report

Measured on commit 7cd7606.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.50% 79.50% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
{
using WideDivisor = wide::integer<512, unsigned>;

/// `Int256` cannot hold the magnitude of its own minimum, so the widening comes first.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

This branch has not been deployed

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

Labels

comp-decimal Decimal datatype semantics, arithmetic, casting, serialization. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants