This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
The following commit(s) were added to refs/heads/main by this push:
new 093ef043e9 perf(arrow-cast): inline `is_valid_decimal_precision` in
decimal casts (#12342)
093ef043e9 is described below
commit 093ef043e9f5c94bec1265e08bd8f230195ace7c
Author: Oleks V <[email protected]>
AuthorDate: Fri Nov 20 01:55:35 2026 +0000
perf(arrow-cast): inline `is_valid_decimal_precision` in decimal casts
(#12342)
# Which issue does this PR close?
- Closes #12326.
# Rationale for this change
Marking the `is_valid_decimal_precision` implementations `#[inline]`, as
proposed in #12326, is not enough on its own. It removes the out-of-line
call per value, but it also made some decimal casts slower, `cast
decimal256 to decimal128 512` by 88%, because LLVM then compiles the
surrounding arrow-cast kernels differently. This PR adds two small
kernel changes that avoid those slowdowns.
# What changes are included in this PR?
- `#[inline]` on the four `is_valid_decimal_precision` implementations.
- `make_downscaler` rounds with `std::hint::select_unpredictable`,
stable since Rust 1.88, the MSRV. Otherwise LLVM compiles the rounding
as a branch on the remainder, which mispredicts on random data.
- `DecimalCast::mul_checked_opt` returns `None` on overflow without
building an `ArrowError`. `make_upscaler` and the safe
integer-to-decimal cast use it instead of `mul_checked(..).ok()`, which
keeps their per-row closures small enough to inline into the loop.
# Are these changes tested?
The behavior does not change, and existing tests cover the rewritten
paths, including
`test_rescale_decimal_downscale_rounds_half_away_from_zero`,
`test_cast_numeric_to_decimal128_overflow` and the
`test_cast_decimal*_to_decimal*_overflow` tests.
The first commit adds `cast_kernels` cases with mixed-sign values and
with remainders that never round. The benchmark bot, this PR against
that commit:
| Benchmark | arm64 (Neoverse-V2) | amd64 | x86-64-v3 |
|---|---:|---:|---:|
| `cast decimal256 to decimal128 512` | -27% | -29% | -31% |
| `cast decimal256 to decimal256 512` | -36% | -38% | -36% |
| `cast int64 to decimal32(9, 0) 512` | -24% | -26% | -25% |
| `cast int32 to decimal32(8, 0) 8192 precision overflow safe` | -30% |
+1% | -2% |
| `cast int64 within 1e6 late overflow to decimal128(18, 2) 512` | -9% |
-7% | -8% |
| `cast decimal256 to decimal128 512 mixed sign` | -12% | -17% | -17% |
| `cast decimal256 to decimal128 512 zero remainder` | +11% | +10% | +3%
|
Inputs that get slower:
- `cast decimal256 to decimal128 512 zero remainder`, by 3% to 11%. On
Linux, `main` branches on the remainder, and that branch is always
predicted when no value rounds. This PR always selects.
- `cast float32 to decimal32(7, 2) 8192`: `valid safe` is 5% to 7%
slower on x86-64-v3, and `valid strict` ranged from 0% to +18% on amd64
across runs. The disassembly does not explain either.
- Four more cases were 5% to 6% slower in one configuration, and faster
or within 2% in the other two: `"cast invalid float64 to to
decimal128(32, 3)"` and `cast decimal256 to decimal256 512 with same
scale` on amd64, `cast float64 to decimal64(3, 0) 8192 precision
overflow safe` on x86-64-v3, and `cast int64 to decimal128(38, 2) 8192
valid strict` on arm64.
# Are there any significant user-facing changes?
No. `DecimalCast` gains a provided method, so existing implementations
keep compiling.
The changes, measurements and this description were prepared with Claude
Code.
---
arrow-array/src/types.rs | 4 ++++
arrow-cast/src/cast/decimal.rs | 46 +++++++++++++++++++++++++++++++++++-------
arrow/benches/cast_kernels.rs | 32 +++++++++++++++++++++++++++++
3 files changed, 75 insertions(+), 7 deletions(-)
diff --git a/arrow-array/src/types.rs b/arrow-array/src/types.rs
index eb9cf74ec9..131327cef7 100644
--- a/arrow-array/src/types.rs
+++ b/arrow-array/src/types.rs
@@ -1490,6 +1490,7 @@ impl DecimalType for Decimal32Type {
validate_decimal32_precision(num, precision, scale)
}
+ #[inline]
fn is_valid_decimal_precision(value: Self::Native, precision: u8) -> bool {
is_validate_decimal32_precision(value, precision)
}
@@ -1522,6 +1523,7 @@ impl DecimalType for Decimal64Type {
validate_decimal64_precision(num, precision, scale)
}
+ #[inline]
fn is_valid_decimal_precision(value: Self::Native, precision: u8) -> bool {
is_validate_decimal64_precision(value, precision)
}
@@ -1554,6 +1556,7 @@ impl DecimalType for Decimal128Type {
validate_decimal_precision(num, precision, scale)
}
+ #[inline]
fn is_valid_decimal_precision(value: Self::Native, precision: u8) -> bool {
is_validate_decimal_precision(value, precision)
}
@@ -1586,6 +1589,7 @@ impl DecimalType for Decimal256Type {
validate_decimal256_precision(num, precision, scale)
}
+ #[inline]
fn is_valid_decimal_precision(value: Self::Native, precision: u8) -> bool {
is_validate_decimal256_precision(value, precision)
}
diff --git a/arrow-cast/src/cast/decimal.rs b/arrow-cast/src/cast/decimal.rs
index 8aef0f418a..80e7a60b7e 100644
--- a/arrow-cast/src/cast/decimal.rs
+++ b/arrow-cast/src/cast/decimal.rs
@@ -25,6 +25,17 @@ pub trait DecimalCast: Sized {
/// Convert a decimal from a f64
fn from_f64(n: f64) -> Option<Self>;
+
+ /// Multiply, returning `None` on overflow
+ ///
+ /// Unlike [`ArrowNativeTypeOp::mul_checked`], this does not build an error
+ /// message, which keeps per-value closures small enough to inline.
+ fn mul_checked_opt(self, rhs: Self) -> Option<Self>
+ where
+ Self: ArrowNativeTypeOp,
+ {
+ self.mul_checked(rhs).ok()
+ }
}
impl DecimalCast for i32 {
@@ -51,6 +62,11 @@ impl DecimalCast for i32 {
fn from_f64(n: f64) -> Option<Self> {
n.to_i32()
}
+
+ #[inline]
+ fn mul_checked_opt(self, rhs: Self) -> Option<Self> {
+ self.checked_mul(rhs)
+ }
}
impl DecimalCast for i64 {
@@ -79,6 +95,11 @@ impl DecimalCast for i64 {
// in arrow-buffer that behaves differently.
num_traits::ToPrimitive::to_i64(&n)
}
+
+ #[inline]
+ fn mul_checked_opt(self, rhs: Self) -> Option<Self> {
+ self.checked_mul(rhs)
+ }
}
impl DecimalCast for i128 {
@@ -105,6 +126,11 @@ impl DecimalCast for i128 {
fn from_f64(n: f64) -> Option<Self> {
n.to_i128()
}
+
+ #[inline]
+ fn mul_checked_opt(self, rhs: Self) -> Option<Self> {
+ self.checked_mul(rhs)
+ }
}
impl DecimalCast for i256 {
@@ -131,6 +157,11 @@ impl DecimalCast for i256 {
fn from_f64(n: f64) -> Option<Self> {
i256::from_f64(n)
}
+
+ #[inline]
+ fn mul_checked_opt(self, rhs: Self) -> Option<Self> {
+ self.checked_mul(rhs)
+ }
}
/// Construct closures to upscale decimals from `(input_precision,
input_scale)` to
@@ -167,7 +198,7 @@ where
// handling, which is faster and simpler for scaling by 10^delta_scale.
let max = O::MAX_FOR_EACH_PRECISION.get(delta_scale as usize)?;
let mul = max.add_wrapping(O::Native::ONE);
- let f_fallible = move |x|
O::Native::from_decimal(x)?.mul_checked(mul).ok();
+ let f_fallible = move |x| O::Native::from_decimal(x)?.mul_checked_opt(mul);
// if the gain in precision (digits) is greater than the multiplication
due to scaling
// every number will fit into the output type
@@ -226,11 +257,12 @@ where
// div is >= 10 and so this cannot overflow
let (d, r) = x.div_rem_wrapping(div);
- // Round result
- let adjusted = match x >= I::Native::ZERO {
- true if r >= half => d.add_wrapping(I::Native::ONE),
- false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
- _ => d,
+ // Round half away from zero. Whether a value rounds depends on the
+ // data, so select the result instead of branching on it.
+ let adjusted = if x >= I::Native::ZERO {
+ std::hint::select_unpredictable(r >= half,
d.add_wrapping(I::Native::ONE), d)
+ } else {
+ std::hint::select_unpredictable(r <= half_neg,
d.sub_wrapping(I::Native::ONE), d)
};
O::Native::from_decimal(adjusted)
};
@@ -1029,7 +1061,7 @@ where
} else if cast_options.safe {
array.unary_opt::<_, D>(|v| {
let v = integer_to_decimal_native::<_, M>(v)
- .and_then(|v| v.mul_checked(scale_factor).ok())?;
+ .and_then(|v| v.mul_checked_opt(scale_factor))?;
(D::is_valid_decimal_precision(v, precision)).then_some(v)
})
} else {
diff --git a/arrow/benches/cast_kernels.rs b/arrow/benches/cast_kernels.rs
index d32694bd90..402f6878da 100644
--- a/arrow/benches/cast_kernels.rs
+++ b/arrow/benches/cast_kernels.rs
@@ -242,6 +242,24 @@ fn add_benchmark(c: &mut Criterion) {
let decimal128_array: ArrayRef = Arc::new(create_decimal128_array(8_000,
10, 3));
let decimal256_array: ArrayRef = Arc::new(create_decimal256_array(8_000,
50, 3));
+ // Downscaling rounds on the sign of each value and on its remainder.
These inputs
+ // have random signs, or remainders that are always zero.
+ let mixed_sign =
+ create_primitive_array_range::<Int64Type>(8_000, 0.0,
-1_000_000_000..1_000_000_000);
+ let small = create_primitive_array_range::<Int64Type>(8_000, 0.0,
0..100_000);
+ let decimal128 = |array: &Int64Array, mul: i64| -> ArrayRef {
+ let array = array.unary::<_, Decimal128Type>(|v| (v * mul) as i128);
+ Arc::new(array.with_precision_and_scale(10, 3).unwrap())
+ };
+ let decimal256 = |array: &Int64Array, mul: i64| -> ArrayRef {
+ let array = array.unary::<_, Decimal256Type>(|v| i256::from_i128((v *
mul) as i128));
+ Arc::new(array.with_precision_and_scale(50, 3).unwrap())
+ };
+ let decimal128_mixed_sign = decimal128(&mixed_sign, 1);
+ let decimal256_mixed_sign = decimal256(&mixed_sign, 1);
+ // Multiples of 10^4 and 10, the divisors of the two downscales below
+ let decimal128_zero_remainder = decimal128(&small, 10_000);
+ let decimal256_zero_remainder = decimal256(&small, 10);
let string_array = build_string_array(512);
let wide_string_array = cast(&string_array, &DataType::LargeUtf8).unwrap();
@@ -399,6 +417,12 @@ fn add_benchmark(c: &mut Criterion) {
c.bench_function("cast decimal256 to decimal128 512", |b| {
b.iter(|| cast_array(&decimal256_array, DataType::Decimal128(38, 2)))
});
+ c.bench_function("cast decimal256 to decimal128 512 mixed sign", |b| {
+ b.iter(|| cast_array(&decimal256_mixed_sign, DataType::Decimal128(38,
2)))
+ });
+ c.bench_function("cast decimal256 to decimal128 512 zero remainder", |b| {
+ b.iter(|| cast_array(&decimal256_zero_remainder,
DataType::Decimal128(38, 2)))
+ });
c.bench_function("cast decimal256 to decimal256 512", |b| {
b.iter(|| cast_array(&decimal256_array, DataType::Decimal256(50, 5)))
});
@@ -411,6 +435,14 @@ fn add_benchmark(c: &mut Criterion) {
"cast decimal128 to decimal128 512 with lower scale (infallible)",
|b| b.iter(|| cast_array(&decimal128_array, DataType::Decimal128(7,
-1))),
);
+ c.bench_function(
+ "cast decimal128 to decimal128 512 with lower scale (infallible) mixed
sign",
+ |b| b.iter(|| cast_array(&decimal128_mixed_sign,
DataType::Decimal128(7, -1))),
+ );
+ c.bench_function(
+ "cast decimal128 to decimal128 512 with lower scale (infallible) zero
remainder",
+ |b| b.iter(|| cast_array(&decimal128_zero_remainder,
DataType::Decimal128(7, -1))),
+ );
c.bench_function("cast decimal256 to decimal256 512 with same scale", |b| {
b.iter(|| cast_array(&decimal256_array, DataType::Decimal256(60, 3)))