Skip to content

fix: handle decimal addition and subtraction when Spark allows negative scales - #7811

Open
sunchao wants to merge 3 commits into
apache:mainfrom
sunchao:fix/decimal-add-sub-alignment
Open

sunchao wants to merge 3 commits into
apache:mainfrom
sunchao:fix/decimal-add-sub-alignment

Conversation

@sunchao

@sunchao sunchao commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Which issue does this PR close?

Closes #7810.

Why are the changes needed?

The affected inputs require spark.sql.legacy.allowNegativeScaleOfDecimal=true. With Spark's default nonnegative scales, the existing arithmetic paths stay the same.

  • For two DECIMAL(3,-125) operands, the aligned width is only 3. Arrow first computes 3 - (-125) in i8. This panics with overflow checks enabled. In release builds the intermediate wraps, so Arrow reports precision 38. For column results, Comet's outer overflow check restores Spark's precision 4.
  • DECIMAL(19,-128) + DECIMAL(3,0) already used the wide kernel. Alignment needs a factor of 10^128. The old i256_pow10 assertion panicked even in release builds. A smaller power can also fit while the aligned coefficient overflows.

What changes were proposed in this PR?

Keep addition and subtraction native. Route around Arrow when either integer digit count exceeds 127. At precision 3, scale -124 still uses Arrow and -125 uses Comet's wide kernel.

The wide kernel keeps i256 when the aligned coefficients and rescaling factors fit the 76-digit bound. Otherwise it uses BigInt to add or subtract exactly and rounds once with HALF_UP to Spark's target scale. Both paths share overflow handling. ANSI reports the value before rounding. TRY and legacy mode return NULL on overflow.

Multiplication keeps its existing arithmetic. #7865 tracks remainder, which calls Arrow even after widening to Decimal256.

How was this PR tested?

Rust tests check routing and intermediate precision, the 76/77-digit boundary, signed rounding, ANSI error values and NULL handling. CometExpressionSuite compares native results with Spark for the -125 case, scale-6 rounding of DECIMAL(38,-1) with DECIMAL(38,38), and TRY at scale -128. Plain ANSI addition must raise Spark's numeric overflow error.

Rust and Scala formatting and git diff --check passed locally. The Rust tests and Spark 4.1 expression suite passed in fork CI. No tests ran locally.

Wide decimal benchmark

The paired benchmark results compare the overflow refactor (af8a150 to 092eb7f) on the same CPU. All 11 cases exercising WideDecimalBinaryExpr took less time in all six pairs. For 8,192 rows, same-scale addition went from 145.86 to 98.86 µs and multiplication from 246.07 to 230.99 µs. The five unchanged cast-chain controls moved by less than 1% in median paired time. These cases measure the existing nonnegative-scale path. The benchmark does not exercise BigInt.

@github-actions github-actions Bot added bug Something isn't working area:expressions Expression evaluation labels Dec 1, 2026
@sunchao

sunchao commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

cc @andygrove @viirya @comphead

@rich7420 rich7420 left a comment

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.

@sunchao thanks for the patch!

withTable("decimal_align") {
sql("CREATE TABLE decimal_align(flag BOOLEAN, n INT) USING parquet")
sql("INSERT INTO decimal_align VALUES (true, 7), (false, 7), (false, NULL)")
val coarseType = DecimalType(19, -128)

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.

Width here is 147, so this took the wide kernel before too. Maybe add the issue's DECIMAL(3,-125) case?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1. CI builds the native library with overflow-checks = false, so the debug panic wouldn't show up there. Reading decimal_op, a release build returns the type Decimal128(38,-125) instead of (4,-125) for DECIMAL(3,-125) + DECIMAL(3,-125). A Spark comparison would show whether that difference was ever visible. Could the query also include (38,-1) + (38,38) with the default allowPrecisionLoss? That is the only shape where the BigInt path rounds, and right now its expected values are worked out by hand in the Rust test instead of compared against Spark.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@rich7420 @viirya I added both Spark comparisons in 092eb7f. The (3,-125) case includes a carry into the fourth digit. The (38,-1) and (38,38) case uses both signs with allowPrecisionLoss=true, so Spark checks the scale-6 ties for both addition and subtraction.

I traced the old release path. Arrow returned the right coefficients and scale but labeled the array (38,-125). Comet's outer CheckOverflow restored (4,-125) before Spark saw those rows. I also added a Rust assertion on the intermediate type before that wrapper, where the difference is visible.

val coarse = when(col("flag"), nonzero).otherwise(lit(0).cast(coarseType))
val fine = col("n").cast(DecimalType(3, 0))
val input = spark.table("decimal_align")
val query = input.select(try_add(coarse, fine), try_subtract(fine, coarse))

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.

try_add and try_subtract stay in TRY mode here. Worth a plain + case for the ANSI error too?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added plain coarse + fine with ANSI enabled in 092eb7f. checkSparkError verifies native execution and compares the exception type, error class and SQLSTATE with Spark. The TRY projections still cover returning NULL on overflow.

Comment on lines +1405 to +1407
// Arrow subtracts scale from precision in i8 before adding the scale back.
let integer_digits = width - i16::from(s1.max(s2));
width >= i16::from(DECIMAL128_MAX_PRECISION) || integer_digits > i16::from(i8::MAX)

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.

DECIMAL(3,-125) % DECIMAL(3,-125) still panics for me in Arrow's rem on a debug build. Is a follow-up issue planned?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Copying the new planner condition into create_modulo_expr wouldn't fix this. Its wide branch casts to Decimal256 but still calls Arrow's rem, and decimal_op computes *p1 as i8 - s1 for every decimal width. DECIMAL(3,-125) % DECIMAL(3,-125) has width 3, so it takes the narrow branch anyway. Could CometRemainder.getSupportLevel return Unsupported when an operand has precision - scale > 127? If that belongs in another PR, could you file an issue and link it here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@rich7420 @viirya I filed #7865 and kept this PR focused on addition and subtraction. Both remainder paths call Arrow's rem, so widening to Decimal256 leaves the i8 subtraction in place. The issue covers the suggested support check for either operand and a second case where both digit counts fit but the alignment factor wraps.

@comphead comphead left a comment

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.

The routing change is right. Arrow's decimal_op computes p - s in i8 (arrow-arith-59.3.2/src/numeric.rs), so integer_digits > 127 is exactly the overflow point, and the three BigInt conditions match the i256 limits (76-digit coefficients sum below i256::MAX, and 10^76 is the largest power). The kernel takes p_out and s_out from Spark's result type, so allowPrecisionLoss only changes the target scale. For (38,-1) + (38,38) Spark's adjustPrecisionScale gives (38,6), which is what the test uses, and a single HALF_UP rounding of the exact sum is what Spark does. I did not run anything. The comments are about the size of the design and some duplicated lines.

Comment on lines +175 to +181
fn add_sub_needs_bigint((p1, s1): (u8, i8), (p2, s2): (u8, i8), out: i8) -> bool {
let scale = i16::from(s1.max(s2));
let widest = scale.max(i16::from(out));
i16::from(p1) + widest - i16::from(s1) > 76
|| i16::from(p2) + widest - i16::from(s2) > 76
|| scale - i16::from(out) > 76
}

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.

With Spark's normal scale range 0 to 38 and precision at most 38, none of these three conditions can hold. p + widest - s is at most 38 + 38 - 0 = 76 and scale - out is at most 38. So add_sub_bigint is only reachable with spark.sql.legacy.allowNegativeScaleOfDecimal=true, and it is a second implementation of the add/subtract rounding and overflow logic of about 60 lines for that mode. The repo has already handled the unsafe negative-scale operator by falling back, in CometDivide.negScaleDecimalArithmeticReason for #5013. The same in CometAdd and CometSubtract getSupportLevel would be a much smaller change. The test "division on negative-scale decimal reports unsupported via getSupportLevel" in CometExpressionSuite.scala (line 1699) pins CometAdd as Compatible() for negative scales, so choosing fallback means reversing that deliberately. Is native add/subtract with negative scales something to keep? If yes the design is fine, and the title and description should say it only applies under that config.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'd keep native add/subtract. A blanket fallback would also move cases like scale -1 back to Spark even when the existing kernel can handle them. The new path only needs BigInt when the intermediate can exceed the i256 bound. I updated the title and description to spell out the negative-scale setting and shared the overflow handling in 092eb7f.

Comment on lines +228 to +232
let text = raw.to_string();
let digits = text.trim_start_matches('-').len();
Err(ArrowError::ExternalError(Box::new(
SparkError::NumericValueOutOfRange {
value: format_decimal_str(&text, digits, aligned),

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.

These lines repeat the Add | Subtract arm of check_overflow_and_convert (lines 470 to 474 at this head: to_string, trim_start_matches('-'), format_decimal_str). A small helper taking the unscaled string and the scale, called from both places, keeps the Spark overflow message from drifting between the i256 and BigInt paths.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in 092eb7f. Both paths now pass the exact, unrounded value and its scale to the same overflow helper. It formats the ANSI error in one place and also handles the TRY and legacy NULL sentinel.

Comment on lines +1800 to +1802
checkCometAnswer(
query,
Seq(Row(null, null), Row(BigDecimal(7), BigDecimal(7)), Row(null, null)))

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.

checkSparkAnswerAndOperator on the line above already asserts that Comet's answer equals Spark's. The hard-coded checkCometAnswer only adds something if Spark's own answer for these rows differs from (null, null), (7, 7), (null, null). If it does not differ, drop it. If it does, a comment saying so would help. I did not run this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed the hard-coded rows in 092eb7f. checkSparkAnswerAndOperator already compares all three rows with Spark and checks that the projection runs in Comet.

@comphead comphead left a comment

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.

thanks @sunchao, the PR goes into right direction, please check some nits!

@viirya viirya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the fix. One thing worth adding to the description: before this PR the (19,-128) + (3,0) shape hit the assert! in i256_pow10, so it panicked in release builds too, not only with overflow checks on.

This PR also disproves a claim the code still makes outside the diff. The comment above negScaleDecimalArithmeticReason in arithmetic.scala says Add, Subtract and Remainder are safe on negative scales because they scale-align by 10^(max_scale - s), "which is never negative". The comments in the "division on negative-scale decimal reports unsupported via getSupportLevel" and "safe ops on negative-scale decimal run natively (regression pin)" tests say the same thing. The real limits are Arrow's i8 p - s and the i256 bounds. Could you update those comments? They need to change whichever way the fallback question is settled.

…t Spark

Check the intermediate precision before CheckOverflow can mask a release-build mismatch. Exercise signed HALF_UP rounding, TRY results and a plain ANSI addition in the native Spark projection.
@sunchao sunchao changed the title fix: align extreme decimal scales safely for addition and subtraction fix: handle decimal addition and subtraction when Spark allows negative scales Dec 4, 2026
@sunchao

sunchao commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

@viirya Following up on your review, I updated the description to call out the release panic. The (19,-128) + (3,0) case hit the unconditional assertion in i256_pow10.

I also corrected the comments in arithmetic.scala and both tests in 092eb7f. The tests now describe the scales they cover. The separate limits in Arrow's remainder kernel are tracked in #7865.

@viirya viirya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the updates. The fallback reasoning, the remainder split into #7865, and the new Spark comparisons all look good to me. I'll approve once the benchmark question below is answered and CI is green.

// optimization of the closure rather than the number of stores. #5309
// tracks removing the sentinel and `Cell` by writing null bits directly.
let overflowed = Cell::new(false);
let check_overflow = |result: i256, raw: i256, report_scale| {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This closure now runs the overflow check for every wide add, subtract and multiply, including the default nonnegative-scale path. The comment above overflowed notes that the closure's shape alone cost 3 to 5% on overflow-bearing batches. Could you run cargo bench --bench wide_decimal in native/spark-expr before and after 092eb7f and share the numbers? If the non-overflow cases regress, marking overflow #[cold] or #[inline(never)] would keep the error formatting out of the loop.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I started a paired run of wide_decimal on af8a150 and 092eb7f with the default bench profile. It pins both binaries to the same CPU and alternates which runs first. I'll post the timings here. The Rust suite passed. Three other CI jobs hit Maven Central HTTP 429 fetching the parent POM, and I'll retry those once the workflow finishes.

@sunchao sunchao Dec 4, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@viirya I found no regression in the non-overflow cases. All 11 cases that exercise WideDecimalBinaryExpr took less time after 092eb7f in all six pairs. I left the inlining attributes unchanged.

I built cargo bench --locked --bench wide_decimal --no-run in native/spark-expr at each commit with the default bench profile. I ran the two Criterion binaries on the same pinned CPU (Xeon 6975P-C, rustc 1.100.1), alternating which ran first. Each run took 100 samples per case. Times are medians of six Criterion slope estimates in µs per 8,192 rows. The last column is the median of the six paired time changes. Lower is faster.

Case af8a150 092eb7f Change
Add, same scale 145.86 98.86 −32.2%
Add, different scales 145.98 98.67 −32.3%
Subtract 145.81 98.92 −32.2%
Multiply 246.07 230.99 −5.8%
Multiply, 48-digit products 240.09 227.04 −5.4%
Add, no overflow 145.23 98.44 −32.0%
Add, no overflow with nulls 111.74 89.04 −20.2%
Add, ANSI, no overflow 145.07 98.41 −31.9%
Add, overflow on last row 152.91 106.51 −30.4%
Add, overflow every 17 rows 153.22 106.63 −30.3%
Add, overflow every other row 154.28 111.24 −27.9%

The benchmark's five old/ cases use the unchanged cast chain. Their median paired changes ranged from −0.55% to +0.76%. These measurements cover the regular nonnegative-scale kernel on this runner. They don't measure the BigInt path or isolate which compiler optimization produced the difference.

Full results, including controls and individual pairs · Raw Criterion samples · Runner script

The Rust tests and Spark 4.1 expression suite passed. Fork CI passed on the same commit after retrying the jobs that hit Maven Central HTTP 429.

@viirya viirya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the benchmark numbers. No regression on the regular path, so this looks good to me.

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

Labels

area:expressions Expression evaluation bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Native decimal addition and subtraction can panic or wrap at extreme negative scales

4 participants