sunchao commented on code in PR #7811:
URL: https://github.com/apache/datafusion-comet/pull/7811#discussion_r4805087364
##########
spark/src/test/scala/org/apache/comet/CometExpressionSuite.scala:
##########
@@ -1782,6 +1782,28 @@ class CometExpressionSuite extends CometTestBase with
AdaptiveSparkPlanHelper {
}
}
+ test("decimal addition and subtraction align extreme negative scales
natively") {
+ withSQLConf(
+ "spark.sql.legacy.allowNegativeScaleOfDecimal" -> "true",
+ SQLConf.ANSI_ENABLED.key -> "true",
+ CometConf.COMET_SCALA_UDF_CODEGEN_ENABLED.key -> "false") {
+ 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)
Review Comment:
@rich7420 @viirya I added both Spark comparisons in
[092eb7f](https://github.com/apache/datafusion-comet/commit/092eb7f5db4dabd4e5d8d18703174370d5446ed2).
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](https://github.com/apache/datafusion-comet/blob/1c0eb0b8bedbf19341dcbb5b115c0ec2235de576/native/spark-expr/src/math_funcs/internal/checkoverflow.rs#L122-L164)
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.
##########
spark/src/test/scala/org/apache/comet/CometExpressionSuite.scala:
##########
@@ -1782,6 +1782,28 @@ class CometExpressionSuite extends CometTestBase with
AdaptiveSparkPlanHelper {
}
}
+ test("decimal addition and subtraction align extreme negative scales
natively") {
+ withSQLConf(
+ "spark.sql.legacy.allowNegativeScaleOfDecimal" -> "true",
+ SQLConf.ANSI_ENABLED.key -> "true",
+ CometConf.COMET_SCALA_UDF_CODEGEN_ENABLED.key -> "false") {
+ 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)
+ val nonzero = lit(new java.math.BigDecimal("1E+128")).cast(coarseType)
+ 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))
Review Comment:
Added plain `coarse + fine` with ANSI enabled in
[092eb7f](https://github.com/apache/datafusion-comet/commit/092eb7f5db4dabd4e5d8d18703174370d5446ed2).
`checkSparkError` verifies native execution and compares the exception type,
error class and SQLSTATE with Spark. The TRY projections still cover returning
NULL on overflow.
##########
native/core/src/execution/planner.rs:
##########
@@ -1400,10 +1400,13 @@ impl PhysicalPlanner {
DataFusionOperator::Plus | DataFusionOperator::Minus |
DataFusionOperator::Multiply,
Ok(DataType::Decimal128(p1, s1)),
Ok(DataType::Decimal128(p2, s2)),
- ) if ((op == DataFusionOperator::Plus || op ==
DataFusionOperator::Minus)
- && decimal128_add_sub_width(p1, s1, p2, s2) >=
DECIMAL128_MAX_PRECISION as i16)
- || (op == DataFusionOperator::Multiply
- && p1 as i16 + p2 as i16 >= DECIMAL128_MAX_PRECISION as
i16) =>
+ ) if ((op == DataFusionOperator::Plus || op ==
DataFusionOperator::Minus) && {
+ let width = decimal128_add_sub_width(p1, s1, p2, s2);
+ // 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)
Review Comment:
@rich7420 @viirya I filed
[#7865](https://github.com/apache/datafusion-comet/issues/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.
##########
native/spark-expr/src/math_funcs/wide_decimal_binary_expr.rs:
##########
@@ -168,6 +169,74 @@ fn max_for_precision(precision: u8) -> i256 {
i256_pow10(precision as u32).wrapping_sub(i256::ONE)
}
+// Two aligned coefficients with at most 76 digits each sum to less than 2 *
10^76,
+// which fits in signed i256. A valid Decimal128 result type alone does not
bound
+// the intermediate. Include any output scale-up and the power needed to round
down.
+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
+}
Review Comment:
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](https://github.com/apache/datafusion-comet/commit/092eb7f5db4dabd4e5d8d18703174370d5446ed2).
##########
native/spark-expr/src/math_funcs/wide_decimal_binary_expr.rs:
##########
@@ -168,6 +169,74 @@ fn max_for_precision(precision: u8) -> i256 {
i256_pow10(precision as u32).wrapping_sub(i256::ONE)
}
+// Two aligned coefficients with at most 76 digits each sum to less than 2 *
10^76,
+// which fits in signed i256. A valid Decimal128 result type alone does not
bound
+// the intermediate. Include any output scale-up and the power needed to round
down.
+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
+}
+
+// Only extreme scale gaps need heap-backed arithmetic. Compute all powers
once per batch.
+fn add_sub_bigint(
+ left: &Decimal128Array,
+ right: &Decimal128Array,
+ op: WideDecimalOp,
+ precision: u8,
+ scale: i8,
+ mode: EvalMode,
+ overflowed: &Cell<bool>,
+) -> Result<Decimal128Array, ArrowError> {
+ let (_, ls) = get_precision_scale(left.data_type());
+ let (_, rs) = get_precision_scale(right.data_type());
+ let aligned = ls.max(rs);
+ let shift = i16::from(aligned) - i16::from(scale);
+ let ten = BigInt::from(10);
+ let left_factor = ten.pow((i16::from(aligned) - i16::from(ls)) as u32);
+ let right_factor = ten.pow((i16::from(aligned) - i16::from(rs)) as u32);
+ let factor = ten.pow(u32::from(shift.unsigned_abs()));
+ let bound = 10_i128.pow(u32::from(precision)) - 1;
+ arrow::compute::kernels::arity::try_binary(left, right, |l, r| {
+ let left = BigInt::from(l) * &left_factor;
+ let right = BigInt::from(r) * &right_factor;
+ let raw = if op == WideDecimalOp::Add {
+ left + right
+ } else {
+ left - right
+ };
+ let value = if shift > 0 {
+ let (mut quotient, remainder) = raw.div_rem(&factor);
+ if remainder.abs() * 2 >= factor {
+ quotient += if raw.is_negative() { -1 } else { 1 };
+ }
+ quotient.to_i128()
+ } else if shift < 0 {
+ (&raw * &factor).to_i128()
+ } else {
+ raw.to_i128()
+ };
+ if let Some(v) = value.filter(|v| (-bound..=bound).contains(v)) {
+ return Ok(v);
+ }
+ if mode != EvalMode::Ansi {
+ overflowed.set(true);
+ return Ok(i128::MAX);
+ }
+ 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),
Review Comment:
Done in
[092eb7f](https://github.com/apache/datafusion-comet/commit/092eb7f5db4dabd4e5d8d18703174370d5446ed2).
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.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]