This is an automated email from the ASF dual-hosted git repository.
viirya pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git
The following commit(s) were added to refs/heads/master by this push:
new 0d82e13b [SPARK-61423][CONNECT] Reject an out-of-range decimal
precision or scale when converting to Arrow instead of wrapping it, in Spark
Connect Rust
0d82e13b is described below
commit 0d82e13b3bd3583df2c46baa6b8e87cad5535fd6
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Tue Nov 10 18:09:58 2026 -0800
[SPARK-61423][CONNECT] Reject an out-of-range decimal precision or scale
when converting to Arrow instead of wrapping it, in Spark Connect Rust
### What changes were proposed in this pull request?
`DataType::Decimal` holds `i32` precision and scale. The two places in
`crates/spark-connect/src/session.rs` that turn it into an Arrow `Decimal128`
(`datatype_to_arrow`, and the decimal branch of `values_to_arrow`) narrowed
them with `as u8` / `as i8`.
Both now go through a new `decimal128_precision_and_scale`, which uses
`u8::try_from` / `i8::try_from` and Arrow's own
`validate_decimal_precision_and_scale::<Decimal128Type>`, and returns an error
naming the type:
```
unsupported decimal type decimal(300,0): precision must be between 1 and 38
unsupported decimal type decimal(38,256): scale must be between -128 and 127
unsupported decimal type decimal(5,6): scale 6 is greater than precision 5
```
In `values_to_arrow` the type is checked before the values, so a column of
nulls is covered.
Parsing is deliberately left alone. PySpark 4.3.0 accepts `DecimalType(39,
0)`, `DecimalType(5, 6)`, `DecimalType(10, -2)` and `DecimalType(300, 0)` in
the constructor and in `_parse_datatype_json_string`,
`pyspark_types_to_proto_types` copies the two fields unchecked, and the server
rejects the type on analysis (`DecimalType.scala`). So `parse_decimal` and
`DataType::from_proto` still do not validate, and a test pins that. A negative
scale that fits Arrow is not refused here either: [...]
### Why are the changes needed?
The casts wrapped silently. For a schema, or for a column with no non-null
value (a non-null value already fails in `decimal_str_to_unscaled`):
- `decimal(257,0)` became the valid `Decimal128(1, 0)`, with no error.
- `decimal(38,256)` became `Decimal128(38, 0)`, with no error.
- `decimal(300,0)` became a precision of 44, and failed later with a
message about 44.
PySpark's Arrow conversion, `pa.decimal128(dt.precision, dt.scale)`, raises
for these rather than building another type.
### Does this PR introduce _any_ user-facing change?
Yes. Building local data with a decimal type whose precision is outside 1
to 38, or whose scale does not fit Arrow, now returns `unsupported decimal type
decimal(p,s): <reason>` where it used to send a different decimal type or fail
with a message naming the wrapped precision. In-range types are unchanged.
### How was this patch tested?
New unit tests in `session.rs` and `types.rs`:
- an out-of-range precision (300, 257, 39, 0, -1) and scale (256, 128,
-129, and a scale above the precision) produce the error through the schema
path, a nested array, a column of nulls and the IPC writer;
- the in-range boundaries (precision 1 and 38, scale 0 and scale =
precision) still give the same `Decimal128`, as does a negative scale;
- out-of-range decimals still parse from JSON and round-trip through the
proto.
`cargo test -p apache-spark-connect --release --lib` (599 passed), `cargo
test -p apache-spark-connect --release --no-run` with and without `--features
wasm-udf`, and `cargo fmt --all --check`. Clippy reports nothing on the changed
lines. The server-backed e2e tests and the official-test parity gate were not
run.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (claude-fable-5-2)
Closes #500 from viirya/SPARK-61423.
Authored-by: Liang-Chi Hsieh <[email protected]>
Signed-off-by: Liang-Chi Hsieh <[email protected]>
---
crates/spark-connect/src/session.rs | 115 +++++++++++++++++++++++++++++++++++-
crates/spark-connect/src/types.rs | 15 +++++
2 files changed, 128 insertions(+), 2 deletions(-)
diff --git a/crates/spark-connect/src/session.rs
b/crates/spark-connect/src/session.rs
index 7ec8b520..1f62a87e 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -1548,6 +1548,36 @@ fn dedup_field_names<'a>(names: impl IntoIterator<Item =
&'a str>) -> Vec<String
.collect()
}
+/// The precision and scale of an Arrow `Decimal128` for a Spark
`decimal(precision, scale)`.
+///
+/// `DataType::Decimal` holds `i32`s and, as PySpark's `DecimalType`, is not
validated when it is
+/// built or parsed, so they are narrowed here with checks rather than `as`
casts, which would
+/// wrap `decimal(300,0)` to a precision of 44. Arrow's own limits apply, as
they do in PySpark's
+/// `to_arrow_type` (`pa.decimal128` raises for a precision outside 1 to 38).
+fn decimal128_precision_and_scale(precision: i32, scale: i32) -> Result<(u8,
i8)> {
+ use arrow::datatypes::{
+ validate_decimal_precision_and_scale, Decimal128Type,
DECIMAL128_MAX_PRECISION,
+ };
+ let unsupported = |reason: String| {
+ SparkError::connect_msg(format!(
+ "unsupported decimal type decimal({precision},{scale}): {reason}"
+ ))
+ };
+ let arrow_precision = u8::try_from(precision)
+ .ok()
+ .filter(|p| (1..=DECIMAL128_MAX_PRECISION).contains(p))
+ .ok_or_else(|| {
+ unsupported(format!(
+ "precision must be between 1 and {DECIMAL128_MAX_PRECISION}"
+ ))
+ })?;
+ let arrow_scale = i8::try_from(scale)
+ .map_err(|_| unsupported(format!("scale must be between {} and {}",
i8::MIN, i8::MAX)))?;
+ validate_decimal_precision_and_scale::<Decimal128Type>(arrow_precision,
arrow_scale)
+ .map_err(|e| unsupported(e.to_string()))?;
+ Ok((arrow_precision, arrow_scale))
+}
+
/// Map a Spark `DataType` to its Arrow `DataType`, recursively
(array/map/struct included).
fn datatype_to_arrow(dt: &DataType) -> Result<arrow::datatypes::DataType> {
use arrow::datatypes::{DataType as A, Field, Fields, TimeUnit};
@@ -1580,7 +1610,10 @@ fn datatype_to_arrow(dt: &DataType) ->
Result<arrow::datatypes::DataType> {
DataType::YearMonthInterval { .. } => {
A::Interval(arrow::datatypes::IntervalUnit::YearMonth)
}
- DataType::Decimal { precision, scale } => A::Decimal128(*precision as
u8, *scale as i8),
+ DataType::Decimal { precision, scale } => {
+ let (precision, scale) =
decimal128_precision_and_scale(*precision, *scale)?;
+ A::Decimal128(precision, scale)
+ }
DataType::Array {
element_type,
contains_null,
@@ -1821,6 +1854,9 @@ fn values_to_arrow(values: &[&Value], dt: &DataType) ->
Result<Arc<dyn arrow::ar
}
DataType::Decimal { precision, scale } => {
let col_scale = *scale;
+ // Checked before the values, so a column of nulls (or no rows) is
validated too.
+ let (arrow_precision, arrow_scale) =
+ decimal128_precision_and_scale(*precision, col_scale)?;
let vals: Result<Vec<Option<i128>>> = values
.iter()
.map(|v| match *v {
@@ -1834,7 +1870,7 @@ fn values_to_arrow(values: &[&Value], dt: &DataType) ->
Result<Arc<dyn arrow::ar
// Use the DECLARED precision/scale so the array matches the Arrow
schema field
// (Decimal128(precision, scale)); hardcoding 38 mismatched a
DecimalType(10, 2).
let arr = Decimal128Array::from(vals?)
- .with_precision_and_scale(*precision as u8, col_scale as i8)
+ .with_precision_and_scale(arrow_precision, arrow_scale)
.map_err(|e| SparkError::connect_msg(format!("decimal build:
{e}")))?;
Ok(Arc::new(arr))
}
@@ -2309,6 +2345,81 @@ mod tests {
);
}
+ fn decimal(precision: i32, scale: i32) -> DataType {
+ DataType::Decimal { precision, scale }
+ }
+
+ #[test]
+ fn decimal_arrow_type_rejects_an_out_of_range_precision_or_scale() {
+ // `as u8` / `as i8` used to wrap these: decimal(300,0) to a precision
of 44,
+ // decimal(257,0) to the valid Decimal128(1, 0) and decimal(38,256) to
a scale of 0.
+ for (precision, scale, reason) in [
+ (300, 0, "precision must be between 1 and 38"),
+ (257, 0, "precision must be between 1 and 38"),
+ (39, 0, "precision must be between 1 and 38"),
+ (0, 0, "precision must be between 1 and 38"),
+ (-1, 0, "precision must be between 1 and 38"),
+ (38, 256, "scale must be between -128 and 127"),
+ (38, 128, "scale must be between -128 and 127"),
+ (38, -129, "scale must be between -128 and 127"),
+ (5, 6, "scale 6 is greater than precision 5"),
+ (38, 39, "scale 39 is greater than max 38"),
+ ] {
+ let expected = format!("unsupported decimal type
decimal({precision},{scale})");
+ let dt = decimal(precision, scale);
+
+ let error = datatype_to_arrow(&dt).unwrap_err().to_string();
+ assert!(error.contains(&expected), "{error}");
+ assert!(error.contains(reason), "{error}");
+
+ // The schema of a nested type is checked as well.
+ let nested = DataType::Array {
+ element_type: Box::new(dt.clone()),
+ contains_null: true,
+ };
+ let error = datatype_to_arrow(&nested).unwrap_err().to_string();
+ assert!(error.contains(&expected), "{error}");
+
+ // A column of nulls has no value to fail on, so the type itself
must.
+ let error = values_to_arrow(&[&Value::Null], &dt)
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains(&expected), "{error}");
+ assert!(error.contains(reason), "{error}");
+
+ let error = rows_to_arrow_ipc(&[row(vec![Value::Null])],
&schema(vec![dt]))
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains(&expected), "{error}");
+ }
+ }
+
+ #[test]
+ fn decimal_arrow_type_keeps_the_in_range_boundaries() {
+ use arrow::datatypes::DataType as A;
+ for (precision, scale) in [(1, 0), (1, 1), (38, 0), (38, 38), (10, 2)]
{
+ let dt = decimal(precision, scale);
+ let expected = A::Decimal128(precision as u8, scale as i8);
+ assert_eq!(datatype_to_arrow(&dt).unwrap(), expected);
+
+ let zero = Value::Decimal {
+ value: "0".to_string(),
+ precision: None,
+ scale: None,
+ };
+ let array = values_to_arrow(&[&Value::Null, &zero], &dt).unwrap();
+ assert_eq!(array.data_type(), &expected);
+ assert_eq!(array.len(), 2);
+ assert!(array.is_null(0));
+ }
+ // Arrow represents a negative scale, so the type is not refused here;
whether Spark
+ // takes it is the server's call
(`spark.sql.legacy.allowNegativeScaleOfDecimal`).
+ assert_eq!(
+ datatype_to_arrow(&decimal(10, -2)).unwrap(),
+ A::Decimal128(10, -2)
+ );
+ }
+
fn struct_field(name: &str, data_type: DataType) ->
crate::types::StructField {
crate::types::StructField {
name: name.to_string(),
diff --git a/crates/spark-connect/src/types.rs
b/crates/spark-connect/src/types.rs
index 26b28afd..829e56e2 100644
--- a/crates/spark-connect/src/types.rs
+++ b/crates/spark-connect/src/types.rs
@@ -3701,6 +3701,21 @@ mod tests {
}
}
+ #[test]
+ fn test_decimal_out_of_range_is_not_rejected_at_parse_time() {
+ // As PySpark, whose `DecimalType(39, 0)`,
`_parse_datatype_json_string` and
+ // `pyspark_types_to_proto_types` do not validate the precision or the
scale: the server
+ // rejects the type on analysis. The client only refuses it where it
has to build an
+ // Arrow type (`decimal128_precision_and_scale` in session.rs).
+ for (precision, scale) in [(39, 0), (5, 6), (10, -2), (300, 0), (0,
0)] {
+ let dt = DataType::Decimal { precision, scale };
+ let text = format!("decimal({precision},{scale})");
+ assert_eq!(DataType::from_json(&serde_json::json!(text)).unwrap(),
dt);
+ assert_eq!(dt.json_value(), serde_json::json!(text));
+ assert_eq!(DataType::from_proto(&dt.to_proto()).unwrap(), dt);
+ }
+ }
+
#[test]
fn test_from_json_unparsed_roundtrip() {
let dt = DataType::Unparsed {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]