comphead commented on code in PR #7811:
URL: https://github.com/apache/datafusion-comet/pull/7811#discussion_r4762658227
##########
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:
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
https://github.com/apache/datafusion-comet/issues/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 d
esign is fine, and the title and description should say it only applies under
that config.
##########
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))
+ checkSparkAnswerAndOperator(query, Seq(classOf[CometProjectExec]))
+ checkCometAnswer(
+ query,
+ Seq(Row(null, null), Row(BigDecimal(7), BigDecimal(7)), Row(null,
null)))
Review Comment:
`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.
##########
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:
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.
--
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]