This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-12389-77c30334719634f233e38fd6ae6bedc3cfb4491b in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 52faedec7007a1386ce6107b3b8bb46d098ebdaa Author: Subodh <[email protected]> AuthorDate: Fri Nov 27 05:15:48 2026 +0000 fix: handle decimal casts with extreme scale increases (#12389) # Which issue does this PR close? Closes #11589 # Rationale for this change When casting decimals with an extreme scale increase where `output_scale - input_scale > O::MAX_PRECISION`, `make_upscaler` returns `None` because the scale delta exceeds the precomputed power-of-ten table `O::MAX_FOR_EACH_PRECISION`. Previously, `convert_to_bigger_or_equal_scale_decimal` unconditionally returned an unhandled `ArrowError::CastError("... Value overflows for output scale")` when `make_upscaler` returned `None`. This caused two correctness issues: 1. Safe casts (`CastOptions { safe: true, .. }`) failed with an `Err` instead of returning `None` (null) for overflowing elements. 2. Individual representable values such as `0` (`0 * 10^k = 0`) failed with an error even though zero never overflows any precision or scale. Similarly, in `rescale_decimal`, when upscaling exceeded the precision table, it returned `None` even for `0`, while downscaling (`input_scale > output_scale`) already had fallback logic returning `(value == ZERO).then_some(ZERO)`. # What changes are included in this PR? 1. **Array Casting (`convert_to_bigger_or_equal_scale_decimal`)**: When `make_upscaler` returns `None`, construct a fallible mapping closure `move |x| (x == I::Native::ZERO).then_some(O::Native::ZERO)` and route through `apply_decimal_cast`. - When `safe: true`, non-zero elements map to `None` (null slots in the output array), while zero values are preserved. - When `safe: false`, non-zero elements produce the expected `ArrowError::CastError("Cannot cast to ... Overflowing on <x>")`. 2. **Scalar Rescaling (`rescale_decimal`)**: When `make_upscaler` returns `None`, return `(value == I::Native::ZERO).then_some(O::Native::ZERO)`, providing symmetry with the existing downscaling fallback path. 3. **Docstrings**: Updated docstrings on `make_upscaler` and `rescale_decimal` to note that zero values remain representable when scaling exceeds precision tables. # Are these changes tested? Yes: - **Unit test**: Added `test_rescale_decimal_upscale_large_delta` in `arrow-cast/src/cast/decimal.rs` verifying scalar upscaling with large scale delta for `Decimal128` and `Decimal32`. - **Integration tests**: - Added `test_cast_decimal_extreme_scale_increase` in `arrow-cast/tests/cast/decimal.rs` covering: - Decimal128 ($\Delta s = 40$), Decimal32 ($\Delta s = 19$), Decimal64 ($\Delta s = 33$), Decimal256 ($\Delta s = 152$). - Cross-type decimal cast (`Decimal32` to `Decimal64`). - Array topologies: mixed elements, all-zeros, all-nulls, and empty arrays. - Precision table boundary transitions ($\Delta s = 38$ vs $\Delta s = 39$). - Updated `test_cast_decimal256_extreme_scale_difference` to verify null outputs under `safe: true`. Verified locally: - `cargo fmt --check` (clean) - `cargo clippy -p arrow-cast -- -D warnings` (clean, 0 warnings) - `cargo test -p arrow-cast --lib decimal` (21 passed) - `cargo test -p arrow-cast --test cast decimal` (92 passed) - `cargo test -p parquet-variant-compute` (369 unit tests + 15 doctests passed) # Are there any significant user-facing changes? No breaking changes. Safe decimal casts with scale increases exceeding destination precision tables now correctly return nulls instead of returning an unhandled error, and zero values are preserved. --- arrow-cast/src/cast/decimal.rs | 56 +++++++++---- arrow-cast/tests/cast/decimal.rs | 167 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 198 insertions(+), 25 deletions(-) diff --git a/arrow-cast/src/cast/decimal.rs b/arrow-cast/src/cast/decimal.rs index 80e7a60b7e..006ba505f2 100644 --- a/arrow-cast/src/cast/decimal.rs +++ b/arrow-cast/src/cast/decimal.rs @@ -174,8 +174,7 @@ impl DecimalCast for i256 { /// /// Returns `None` if the required scale increase `delta_scale = output_scale - input_scale` /// exceeds the supported precomputed precision table `O::MAX_FOR_EACH_PRECISION`. -/// In that case, the caller should treat this as an overflow for the output scale -/// and handle it accordingly (e.g., return a cast error). +/// In that case, non-zero values overflow the output scale while zero values remain representable. #[expect(clippy::type_complexity)] fn make_upscaler<I: DecimalType, O: DecimalType>( input_precision: u8, @@ -309,9 +308,9 @@ where /// The function first validates that the requested precision and scale are supported for /// both the source and destination decimal types. It then either upscales (multiplying /// by an appropriate power of ten) or downscales (dividing with rounding) the input value. -/// When the scaling factor exceeds the precision table of the destination type, the value -/// is treated as an overflow for upscaling, or rounded to zero for downscaling (as any -/// possible result would be zero at the requested scale). +/// When the scaling factor exceeds the precision table of the destination type, zero remains +/// representable while non-zero values overflow for upscaling, or rounded to zero for downscaling +/// (as any possible result would be zero at the requested scale). /// /// This mirrors the column-oriented helpers of decimal casting but operates on a single value /// (row-level) instead of an entire array. @@ -332,9 +331,14 @@ where validate_decimal_precision_and_scale::<O>(output_precision, output_scale).ok()?; if input_scale <= output_scale { - let (f, f_infallible) = - make_upscaler::<I, O>(input_precision, input_scale, output_precision, output_scale)?; - apply_rescaler::<I, O>(value, output_precision, f, f_infallible) + if let Some((f, f_infallible)) = + make_upscaler::<I, O>(input_precision, input_scale, output_precision, output_scale) + { + apply_rescaler::<I, O>(value, output_precision, f, f_infallible) + } else { + // Scale increase exceeds supported precision table; zero remains representable, non-zero overflows + (value == I::Native::ZERO).then_some(O::Native::ZERO) + } } else { let Some((f, f_infallible)) = make_downscaler::<I, O>(input_precision, input_scale, output_precision, output_scale) @@ -453,13 +457,17 @@ where cast_options, ) } else { - // Scale increase exceeds supported precision; return overflow error - Err(ArrowError::CastError(format!( - "Cannot cast to {}({}, {}). Value overflows for output scale", - O::PREFIX, + // Scale increase exceeds supported precision table; non-zero values overflow + // while zero remains representable. + let f_fallible = move |x| (x == I::Native::ZERO).then_some(O::Native::ZERO); + apply_decimal_cast( + array, output_precision, - output_scale - ))) + output_scale, + f_fallible, + None::<fn(I::Native) -> O::Native>, + cast_options, + ) } } @@ -1405,4 +1413,24 @@ mod tests { let result = rescale_decimal::<Decimal128Type, Decimal128Type>(123_i128, 38, 38, 39, 39); assert_eq!(result, None); } + + #[test] + fn test_rescale_decimal_upscale_large_delta() { + // Delta scale 40 exceeds Decimal128 table (38 max precision) + let zero = rescale_decimal::<Decimal128Type, Decimal128Type>(0_i128, 5, -2, 38, 38); + assert_eq!(zero, Some(0_i128)); + + let non_zero = rescale_decimal::<Decimal128Type, Decimal128Type>(1_i128, 5, -2, 38, 38); + assert_eq!(non_zero, None); + + let negative = rescale_decimal::<Decimal128Type, Decimal128Type>(-1_i128, 5, -2, 38, 38); + assert_eq!(negative, None); + + // Delta scale 19 exceeds Decimal32 table (9 max precision) + let zero_d32 = rescale_decimal::<Decimal32Type, Decimal32Type>(0_i32, 3, -10, 9, 9); + assert_eq!(zero_d32, Some(0_i32)); + + let non_zero_d32 = rescale_decimal::<Decimal32Type, Decimal32Type>(1_i32, 3, -10, 9, 9); + assert_eq!(non_zero_d32, None); + } } diff --git a/arrow-cast/tests/cast/decimal.rs b/arrow-cast/tests/cast/decimal.rs index 9eb9a557d3..9f3f9c62f7 100644 --- a/arrow-cast/tests/cast/decimal.rs +++ b/arrow-cast/tests/cast/decimal.rs @@ -2425,17 +2425,28 @@ fn test_cast_decimal256_extreme_scale_difference() { let input = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::MINUS_ONE), None]) .with_precision_and_scale(76, i8::MIN) .unwrap(); - for safe in [true, false] { - let options = CastOptions { - safe, - ..Default::default() - }; - let error = cast_with_options(&input, &DataType::Decimal256(76, 76), &options).unwrap_err(); - assert_eq!( - error.to_string(), - "Cast error: Cannot cast to Decimal256(76, 76). Value overflows for output scale" - ); - } + + let safe_options = CastOptions { + safe: true, + ..Default::default() + }; + let safe_result = + cast_with_options(&input, &DataType::Decimal256(76, 76), &safe_options).unwrap(); + let expected_safe = Decimal256Array::from(vec![None, None, None]) + .with_precision_and_scale(76, 76) + .unwrap(); + assert_eq!(safe_result.as_primitive::<Decimal256Type>(), &expected_safe); + + let strict_options = CastOptions { + safe: false, + ..Default::default() + }; + let error = + cast_with_options(&input, &DataType::Decimal256(76, 76), &strict_options).unwrap_err(); + assert_eq!( + error.to_string(), + "Cast error: Cannot cast to Decimal256(76, 76). Overflowing on 1" + ); let input = input.with_precision_and_scale(76, 76).unwrap(); let expected = Decimal256Array::from(vec![Some(i256::ZERO), Some(i256::ZERO), None]) @@ -2452,6 +2463,140 @@ fn test_cast_decimal256_extreme_scale_difference() { } } +#[test] +fn test_cast_decimal_extreme_scale_increase() { + let safe_opts = CastOptions { + safe: true, + ..Default::default() + }; + let strict_opts = CastOptions { + safe: false, + ..Default::default() + }; + + // 1. Decimal128: delta_scale = 40 (exceeds table length 39) + let mixed = Decimal128Array::from(vec![Some(0), Some(1), Some(-1), None]) + .with_precision_and_scale(5, -2) + .unwrap(); + let res = cast_with_options(&mixed, &DataType::Decimal128(38, 38), &safe_opts).unwrap(); + let expected = Decimal128Array::from(vec![Some(0), None, None, None]) + .with_precision_and_scale(38, 38) + .unwrap(); + assert_eq!(res.as_primitive::<Decimal128Type>(), &expected); + + let err = cast_with_options(&mixed, &DataType::Decimal128(38, 38), &strict_opts).unwrap_err(); + assert_eq!( + err.to_string(), + "Cast error: Cannot cast to Decimal128(38, 38). Overflowing on 1" + ); + + // All zeros: succeeds for both safe and strict + let zeros = Decimal128Array::from(vec![Some(0), Some(0)]) + .with_precision_and_scale(5, -2) + .unwrap(); + for opts in [&safe_opts, &strict_opts] { + let res = cast_with_options(&zeros, &DataType::Decimal128(38, 38), opts).unwrap(); + let expected = Decimal128Array::from(vec![Some(0), Some(0)]) + .with_precision_and_scale(38, 38) + .unwrap(); + assert_eq!(res.as_primitive::<Decimal128Type>(), &expected); + } + + // All nulls and empty arrays + let nulls = Decimal128Array::from(vec![None, None] as Vec<Option<i128>>) + .with_precision_and_scale(5, -2) + .unwrap(); + for opts in [&safe_opts, &strict_opts] { + let res = cast_with_options(&nulls, &DataType::Decimal128(38, 38), opts).unwrap(); + let expected = Decimal128Array::from(vec![None, None] as Vec<Option<i128>>) + .with_precision_and_scale(38, 38) + .unwrap(); + assert_eq!(res.as_primitive::<Decimal128Type>(), &expected); + } + + let empty = Decimal128Array::from(vec![] as Vec<i128>) + .with_precision_and_scale(5, -2) + .unwrap(); + for opts in [&safe_opts, &strict_opts] { + let res = cast_with_options(&empty, &DataType::Decimal128(38, 38), opts).unwrap(); + assert_eq!(res.len(), 0); + } + + // 2. Decimal32: delta_scale = 19 (exceeds table length 10) + let d32 = Decimal32Array::from(vec![Some(0), Some(1), None]) + .with_precision_and_scale(3, -10) + .unwrap(); + let res = cast_with_options(&d32, &DataType::Decimal32(9, 9), &safe_opts).unwrap(); + let expected = Decimal32Array::from(vec![Some(0), None, None]) + .with_precision_and_scale(9, 9) + .unwrap(); + assert_eq!(res.as_primitive::<Decimal32Type>(), &expected); + let err = cast_with_options(&d32, &DataType::Decimal32(9, 9), &strict_opts).unwrap_err(); + assert_eq!( + err.to_string(), + "Cast error: Cannot cast to Decimal32(9, 9). Overflowing on 1" + ); + + // 3. Decimal64: delta_scale = 33 (exceeds table length 19) + let d64 = Decimal64Array::from(vec![Some(0), Some(-1), None]) + .with_precision_and_scale(5, -15) + .unwrap(); + let res = cast_with_options(&d64, &DataType::Decimal64(18, 18), &safe_opts).unwrap(); + let expected = Decimal64Array::from(vec![Some(0), None, None]) + .with_precision_and_scale(18, 18) + .unwrap(); + assert_eq!(res.as_primitive::<Decimal64Type>(), &expected); + let err = cast_with_options(&d64, &DataType::Decimal64(18, 18), &strict_opts).unwrap_err(); + assert_eq!( + err.to_string(), + "Cast error: Cannot cast to Decimal64(18, 18). Overflowing on -1" + ); + + // 4. Decimal256: delta_scale = 152 (exceeds table length 77) + let d256 = Decimal256Array::from(vec![Some(i256::ZERO), Some(i256::ONE), None]) + .with_precision_and_scale(10, -76) + .unwrap(); + let res = cast_with_options(&d256, &DataType::Decimal256(76, 76), &safe_opts).unwrap(); + let expected = Decimal256Array::from(vec![Some(i256::ZERO), None, None]) + .with_precision_and_scale(76, 76) + .unwrap(); + assert_eq!(res.as_primitive::<Decimal256Type>(), &expected); + + // 5. Cross-type: Decimal32 -> Decimal64 (delta_scale = 33, exceeds Decimal64 table length 19) + let cross_d32 = Decimal32Array::from(vec![Some(0), Some(5)]) + .with_precision_and_scale(3, -15) + .unwrap(); + let res = cast_with_options(&cross_d32, &DataType::Decimal64(18, 18), &safe_opts).unwrap(); + let expected = Decimal64Array::from(vec![Some(0), None]) + .with_precision_and_scale(18, 18) + .unwrap(); + assert_eq!(res.as_primitive::<Decimal64Type>(), &expected); + + // 6. Boundary transition: immediately within (delta_scale = 38) vs immediately beyond (delta_scale = 39) + let boundary_in = Decimal128Array::from(vec![Some(0), Some(1)]) + .with_precision_and_scale(1, 0) + .unwrap(); + let res_in = + cast_with_options(&boundary_in, &DataType::Decimal128(38, 38), &safe_opts).unwrap(); + let expected_in = Decimal128Array::from(vec![Some(0), None]) + .with_precision_and_scale(38, 38) + .unwrap(); + assert_eq!(res_in.as_primitive::<Decimal128Type>(), &expected_in); + + let boundary_out = Decimal128Array::from(vec![Some(0), Some(1)]) + .with_precision_and_scale(1, -1) + .unwrap(); + let res_out = + cast_with_options(&boundary_out, &DataType::Decimal128(38, 38), &safe_opts).unwrap(); + assert_eq!(res_out.as_primitive::<Decimal128Type>(), &expected_in); + let err_out = + cast_with_options(&boundary_out, &DataType::Decimal128(38, 38), &strict_opts).unwrap_err(); + assert_eq!( + err_out.to_string(), + "Cast error: Cannot cast to Decimal128(38, 38). Overflowing on 1" + ); +} + #[test] fn test_cast_decimal128_to_decimal128_negative_scale() { let input_type = DataType::Decimal128(20, 0);
