This is an automated email from the ASF dual-hosted git repository.

HyukjinKwon 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 9b05073c [SPARK-61434][CONNECT][PYTHON] Raise the error of a converter 
before that of PyArrow in createDataFrame of local rows, as PySpark does
9b05073c is described below

commit 9b05073cc7a15bd9ee63a325b4c847dffbf8ca0f
Author: Timothy Meehan <[email protected]>
AuthorDate: Thu Nov 12 09:31:15 2026 +0900

    [SPARK-61434][CONNECT][PYTHON] Raise the error of a converter before that 
of PyArrow in createDataFrame of local rows, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61434](https://issues.apache.org/jira/browse/SPARK-61434): raise the 
error of a converter before that of PyArrow in `createDataFrame` of local rows, 
as PySpark does.
    
    - `infer::convert` (`crates/pyspark-rs/src/infer.rs`) takes a `Late` that 
keeps the first error of PyArrow (a boolean, integer, float, day-time interval, 
date or time value that Arrow rejects, a lone surrogate in a string, an array 
that is not a sequence, and the parts of a `VariantVal`, a `Geometry` or a 
`Geography` that Arrow rejects), puts a null in the place of the value and goes 
on, without building the errors of later values. The errors of PySpark's 
converters (type assertions,  [...]
    - `createDataFrame` (`crates/pyspark-rs/src/session.rs`) raises the kept 
error after the checks of the Arrow schema, where PySpark's 
`pa.Table.from_arrays` runs. The conversion stays one pass over the values.
    
    ### Why are the changes needed?
    
    PySpark runs every value of every column through its converters before 
PyArrow builds any column. For the row `(128, 0)` and the schema `a tinyint, b 
timestamp`, PySpark raises `AssertionError` (the `0` is not a datetime) and the 
Rust client raised `ArrowInvalid: Value 128 too large to fit in C integer 
type`, for the `128` in the earlier column. A fuzzer of `createDataFrame` found 
319 of 18,000 cases (1.8%) with a different error class, all with two bad 
values. Both clients reject the [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for data that PyArrow rejects: the error raised is the one PySpark 
raises. Valid data gives the same result. Rows with several bad values raise 
the error of a converter before that of PyArrow. Data with one bad value 
changes only when the schema has a type that Arrow cannot build as well: `128` 
in `a tinyint, b interval year to month` now raises PySpark's 
`PySparkTypeError` for the type, not `ArrowInvalid`, as PySpark does. A single 
bad value of a supported schema raises the same [...]
    
    ### How was this patch tested?
    
    Offline, through the mock server, the error of `createDataFrame` for 35 
cases of rows and schemas, before and after, against 
`LocalDataToArrowConversion.convert` of pyspark-client 4.3.0 (an excerpt):
    
    | rows | schema | PySpark | before | after |
    |---|---|---|---|---|
    | `[(128, 0)]` | `a tinyint, b timestamp` | `AssertionError` | 
`ArrowInvalid` | `AssertionError` |
    | `[(128, None)]` | `a tinyint, b int not null` | `PySparkValueError` | 
`ArrowInvalid` | `PySparkValueError` |
    | `[("abc", 0)]` | `a int, b timestamp` | `AssertionError` | `ArrowInvalid` 
| `AssertionError` |
    | `[([128], "x")]` | `a array<tinyint>, b decimal(5,2)` | `AssertionError` 
| `ArrowInvalid` | `AssertionError` |
    | `[(128, None)]` | `a tinyint, b interval year to month` | 
`PySparkTypeError` | `ArrowInvalid` | `PySparkTypeError` |
    | `[(128, "x")]` | `a tinyint, b int` | `ArrowInvalid` | `ArrowInvalid` | 
`ArrowInvalid` |
    
    Of the first 16 cases, 11 differed from PySpark before and all 16 match 
after; the other 6 (the order against the checks of the Arrow schema, an array 
that is not a sequence, a map key, a time) were added after the change and also 
match, and so do 13 more: a lone surrogate, a non-nullable column, a map key, 
and the parts of a `VariantVal` and a `Geometry` that are not bytes or an int, 
before and after an error of a converter. Against the loopback Spark 4.3.0 
Connect server the repro n [...]
    
    Test added: 
`test_local_rows_raise_the_error_of_a_converter_before_that_of_pyarrow` in 
`python/tests/test_dropin_offline.py`, 19 cases (the table above, nested array 
and struct values, a map key, a non-nullable column, a lone surrogate, several 
rows, an array that is not a sequence, the parts of a `VariantVal` and of a 
`Geometry`, and the order of two errors of PyArrow). 14 of the 19 fail against 
master; the other 5 guard the order of errors that were already right.
    
    Checks: `cargo test -p apache-spark-connect --release --lib` 599 passed, 
and `-p apache-spark-connect-core` passes; `--no-run` builds, with and without 
`wasm-udf`; `cargo fmt --all --check` and `ruff check` clean; clippy reports no 
diagnostic on the changed lines; offline Python suites 
`tests/test_dropin_offline.py tests/test_ml_offline.py 
tests/test_arrow_handoff.py` 3133 passed, 8 skipped; live drop-in, Arrow and ML 
suites against a local Spark 4.3.0 server 281 passed, 1 skipped.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Sonnet 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #520 from tdcmeehan/SPARK-61434-createdataframe-error-order.
    
    Lead-authored-by: Timothy Meehan <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/infer.rs      | 249 +++++++++++++++++++++++-------------
 crates/pyspark-rs/src/session.rs    |  10 +-
 python/tests/test_dropin_offline.py |  48 +++++++
 3 files changed, 218 insertions(+), 89 deletions(-)

diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index bf022020..44164610 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -1154,8 +1154,43 @@ pub(crate) fn wall_clock_micros(obj: &Bound<'_, PyAny>) 
-> PyResult<i64> {
     Ok(seconds * 1_000_000 + micros)
 }
 
+/// The first error of PyArrow in the conversion of the values of a table. 
PySpark converts all
+/// the values with its converters before PyArrow builds any column, so that 
an error of a
+/// converter is raised before one of PyArrow, wherever the values are.
+#[derive(Default)]
+pub(crate) struct Late(Option<PyErr>);
+
+impl Late {
+    /// The value of `convert`, or a null in its place once its error is kept. 
Once one is
+    /// kept, `convert` is not called: PySpark stops at the first error of 
PyArrow.
+    fn defer(&mut self, convert: impl FnOnce() -> PyResult<Value>) -> Value {
+        if self.0.is_some() {
+            return Value::Null;
+        }
+        convert().unwrap_or_else(|err| {
+            self.0 = Some(err);
+            Value::Null
+        })
+    }
+
+    /// The error to raise once every value is converted, if any.
+    pub(crate) fn finish(self) -> PyResult<()> {
+        self.0.map_or(Ok(()), Err)
+    }
+}
+
+/// The text of `text` as PyArrow encodes it, which fails for a lone surrogate.
+fn utf8_text(text: &Bound<'_, PyString>) -> PyResult<Value> {
+    Ok(Value::String(text.to_cow()?.into_owned()))
+}
+
 /// A field value of `dt` from `obj`, as PySpark's converters and then PyArrow 
convert it.
-pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: &DataType, nullable: bool) 
-> PyResult<Value> {
+pub(crate) fn convert(
+    obj: &Bound<'_, PyAny>,
+    dt: &DataType,
+    nullable: bool,
+    late: &mut Late,
+) -> PyResult<Value> {
     let py = obj.py();
     if obj.is_none() {
         // A null type takes None either way.
@@ -1174,7 +1209,7 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
                 obj.str()?
             ),
         )),
-        DataType::Struct { fields } => convert_struct(obj, fields),
+        DataType::Struct { fields } => convert_struct(obj, fields, late),
         DataType::Array {
             element_type,
             contains_null,
@@ -1189,20 +1224,22 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
                     return Err(assertion());
                 }
             } else if obj.is_instance_of::<PyDict>() || 
obj.try_iter().is_err() {
-                return Err(pyarrow_error(
-                    py,
-                    "ArrowTypeError",
-                    format!(
-                        "Could not convert {} with type {}: was not a sequence 
or recognized \
-                         null for conversion to list type",
-                        obj.repr()?,
-                        arrow_type_name(obj)?
-                    ),
-                )?);
+                return Ok(late.defer(|| {
+                    Err(pyarrow_error(
+                        py,
+                        "ArrowTypeError",
+                        format!(
+                            "Could not convert {} with type {}: was not a 
sequence or \
+                             recognized null for conversion to list type",
+                            obj.repr()?,
+                            arrow_type_name(obj)?
+                        ),
+                    )?)
+                }));
             }
             let mut items = Vec::with_capacity(obj.len().unwrap_or(0));
             for item in obj.try_iter()? {
-                items.push(convert(&item?, element_type, *contains_null)?);
+                items.push(convert(&item?, element_type, *contains_null, 
late)?);
             }
             Ok(Value::List(items))
         }
@@ -1215,8 +1252,8 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
             let mut entries = Vec::with_capacity(dict.len());
             for (key, value) in dict.iter() {
                 entries.push((
-                    convert(&key, key_type, false)?,
-                    convert(&value, value_type, *value_contains_null)?,
+                    convert(&key, key_type, false, late)?,
+                    convert(&value, value_type, *value_contains_null, late)?,
                 ));
             }
             Ok(Value::Map(entries))
@@ -1277,15 +1314,17 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
             })
         }
         DataType::String { .. } => {
-            let text = if obj.is_exact_instance_of::<PyString>() {
-                obj.cast::<PyString>()?.to_cow()?.into_owned()
-            } else if obj.is_instance_of::<PyBool>() {
+            if obj.is_exact_instance_of::<PyString>() {
+                return Ok(late.defer(|| utf8_text(obj.cast::<PyString>()?)));
+            }
+            if obj.is_instance_of::<PyBool>() {
                 // As PySpark Classic, which converts a bool to a string in 
the JVM.
-                (if obj.is_truthy()? { "true" } else { "false" }).to_string()
-            } else {
-                obj.str()?.to_cow()?.into_owned()
-            };
-            Ok(Value::String(text))
+                return Ok(Value::String(
+                    (if obj.is_truthy()? { "true" } else { "false" 
}).to_string(),
+                ));
+            }
+            let text = obj.str()?;
+            Ok(late.defer(|| utf8_text(&text)))
         }
         // As PySpark, which has no converter of these types: the value goes 
as it is to
         // `to_arrow_schema`, which raises for the type 
(`unsupported_arrow_type`).
@@ -1293,57 +1332,16 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
         | DataType::Varchar { .. }
         | DataType::YearMonthInterval { .. }
         | DataType::CalendarInterval => Ok(Value::Null),
-        DataType::Boolean => {
-            if obj.is_instance_of::<PyBool>() || numpy_scalar(obj)? == 
Some(NumpyScalar::Bool) {
-                Ok(Value::Bool(obj.is_truthy()?))
-            } else {
-                Err(arrow_invalid(obj, "boolean")?)
-            }
-        }
-        DataType::Byte | DataType::Short | DataType::Integer | DataType::Long 
=> {
-            convert_integral(obj, dt)
-        }
-        DataType::Float | DataType::Double => {
-            // PyArrow takes a float, a bool, an int that it represents 
exactly, and a NumPy
-            // float or integer, but not a NumPy bool.
-            let value = if obj.is_instance_of::<PyFloat>() || 
obj.is_instance_of::<PyBool>() {
-                obj.extract::<f64>()?
-            } else if obj.is_instance_of::<PyInt>() {
-                exact_float(obj, dt)?
-            } else {
-                match numpy_scalar(obj)? {
-                    Some(NumpyScalar::Floating) => obj.extract::<f64>()?,
-                    Some(NumpyScalar::Integer) => exact_float(obj, dt)?,
-                    _ => {
-                        let arrow_type = if matches!(dt, DataType::Float) {
-                            "float32"
-                        } else {
-                            "double"
-                        };
-                        return Err(arrow_invalid(obj, arrow_type)?);
-                    }
-                }
-            };
-            Ok(match dt {
-                DataType::Float => Value::Float(value as f32),
-                _ => Value::Double(value),
-            })
-        }
-        DataType::DayTimeInterval { .. } => 
Ok(Value::DayTimeInterval(duration_micros(obj)?)),
-        DataType::Date => Ok(Value::Date(date_days(obj)?)),
-        // As PyArrow's `time64[ns]`, to which PySpark passes the value as it 
is: a time, else
-        // the nanoseconds of the value as `CIntFromPython` takes it.
-        DataType::Time { .. } => {
-            if obj.is_instance(TIME.import(py, "datetime", "time")?.as_any())? 
{
-                Ok(Value::Time(time_nanos(obj)?))
-            } else {
-                Ok(Value::Time(c_int_from_python(
-                    obj,
-                    64,
-                    Some("Integer too large for int64"),
-                )?))
-            }
-        }
+        DataType::Boolean
+        | DataType::Byte
+        | DataType::Short
+        | DataType::Integer
+        | DataType::Long
+        | DataType::Float
+        | DataType::Double
+        | DataType::DayTimeInterval { .. }
+        | DataType::Date
+        | DataType::Time { .. } => Ok(late.defer(|| arrow_scalar(obj, dt))),
         // As PySpark's converters of these types, their `toInternal`: the 
`value` and
         // `metadata` attributes of a VariantVal, and the `srid` and `wkb` of 
a Geometry or a
         // Geography, which PyArrow converts as the fields of the structs of 
their Arrow types.
@@ -1351,10 +1349,12 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
             if obj.is_instance(variant_val_class(py)?)? {
                 let value = obj.getattr(intern!(py, "value"))?;
                 let metadata = obj.getattr(intern!(py, "metadata"))?;
-                Ok(Value::Variant {
-                    value: arrow_binary(&value)?,
-                    metadata: arrow_binary(&metadata)?,
-                })
+                Ok(late.defer(|| {
+                    Ok(Value::Variant {
+                        value: arrow_binary(&value)?,
+                        metadata: arrow_binary(&metadata)?,
+                    })
+                }))
             } else {
                 Err(raise_pyspark(
                     py,
@@ -1366,7 +1366,7 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
         }
         DataType::Geometry { .. } => {
             if obj.is_instance(geometry_class(py)?)? {
-                spatial_value(obj)
+                spatial_value(obj, late)
             } else {
                 Err(raise_pyspark(
                     py,
@@ -1378,7 +1378,7 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
         }
         DataType::Geography { .. } => {
             if obj.is_instance(geography_class(py)?)? {
-                spatial_value(obj)
+                spatial_value(obj, late)
             } else {
                 Err(raise_pyspark(
                     py,
@@ -1402,12 +1402,72 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt: 
&DataType, nullable: bool) ->
                 serialized_python_class.as_deref(),
             )?;
             let serialized = udt.call_method1(intern!(py, "serialize"), 
(obj,))?;
-            convert(&serialized, sql_type, nullable)
+            convert(&serialized, sql_type, nullable, late)
         }
         _ => Err(unsupported(obj)?),
     }
 }
 
+/// The value of a type that PySpark has no converter of, as PyArrow converts 
it.
+fn arrow_scalar(obj: &Bound<'_, PyAny>, dt: &DataType) -> PyResult<Value> {
+    let py = obj.py();
+    match dt {
+        DataType::Boolean => {
+            if obj.is_instance_of::<PyBool>() || numpy_scalar(obj)? == 
Some(NumpyScalar::Bool) {
+                Ok(Value::Bool(obj.is_truthy()?))
+            } else {
+                Err(arrow_invalid(obj, "boolean")?)
+            }
+        }
+        DataType::Byte | DataType::Short | DataType::Integer | DataType::Long 
=> {
+            convert_integral(obj, dt)
+        }
+        DataType::Float | DataType::Double => {
+            // PyArrow takes a float, a bool, an int that it represents 
exactly, and a NumPy
+            // float or integer, but not a NumPy bool.
+            let value = if obj.is_instance_of::<PyFloat>() || 
obj.is_instance_of::<PyBool>() {
+                obj.extract::<f64>()?
+            } else if obj.is_instance_of::<PyInt>() {
+                exact_float(obj, dt)?
+            } else {
+                match numpy_scalar(obj)? {
+                    Some(NumpyScalar::Floating) => obj.extract::<f64>()?,
+                    Some(NumpyScalar::Integer) => exact_float(obj, dt)?,
+                    _ => {
+                        let arrow_type = if matches!(dt, DataType::Float) {
+                            "float32"
+                        } else {
+                            "double"
+                        };
+                        return Err(arrow_invalid(obj, arrow_type)?);
+                    }
+                }
+            };
+            Ok(match dt {
+                DataType::Float => Value::Float(value as f32),
+                _ => Value::Double(value),
+            })
+        }
+        DataType::DayTimeInterval { .. } => 
Ok(Value::DayTimeInterval(duration_micros(obj)?)),
+        DataType::Date => Ok(Value::Date(date_days(obj)?)),
+        // As PyArrow's `time64[ns]`, to which PySpark passes the value as it 
is: a time, else
+        // the nanoseconds of the value as `CIntFromPython` takes it.
+        DataType::Time { .. } => {
+            if obj.is_instance(TIME.import(py, "datetime", "time")?.as_any())? 
{
+                Ok(Value::Time(time_nanos(obj)?))
+            } else {
+                Ok(Value::Time(c_int_from_python(
+                    obj,
+                    64,
+                    Some("Integer too large for int64"),
+                )?))
+            }
+        }
+        // `convert` calls this for the types above only, those that PySpark 
has no converter of.
+        _ => unreachable!("arrow_scalar of {dt:?}, a type that convert does 
not defer to it"),
+    }
+}
+
 /// The days since the epoch of a value of a date column, as PyArrow converts 
it to date32: a
 /// date, or the date of a datetime, else the days of the value as 
`CIntFromPython` takes it, in
 /// the range of an int32, else the `ArrowInvalid` "Integer too large for 
date32".
@@ -1524,16 +1584,21 @@ pub(crate) fn time_nanos(obj: &Bound<'_, PyAny>) -> 
PyResult<i64> {
 
 /// The value of a Geometry or a Geography `obj`, as their `toInternal`, the 
dict of its `srid`
 /// and `wkb` attributes, which PyArrow converts to the int32 and the binary 
of their struct.
-fn spatial_value(obj: &Bound<'_, PyAny>) -> PyResult<Value> {
+fn spatial_value(obj: &Bound<'_, PyAny>, late: &mut Late) -> PyResult<Value> {
     let py = obj.py();
     let srid = obj.getattr(intern!(py, "srid"))?;
     let wkb = obj.getattr(intern!(py, "wkb"))?;
+    Ok(late.defer(|| spatial_struct(&srid, &wkb)))
+}
+
+/// The struct of a Geometry or a Geography, from its `srid` and `wkb` as 
PyArrow converts them.
+fn spatial_struct(srid: &Bound<'_, PyAny>, wkb: &Bound<'_, PyAny>) -> 
PyResult<Value> {
     Ok(Value::Struct(
         spark_connect::row::Row::new(
             vec!["srid".to_string(), "wkb".to_string()],
             vec![
-                convert_integral(&srid, &DataType::Integer)?,
-                Value::Binary(arrow_binary(&wkb)?),
+                convert_integral(srid, &DataType::Integer)?,
+                Value::Binary(arrow_binary(wkb)?),
             ],
         )
         .into(),
@@ -1730,7 +1795,11 @@ fn values_by_position<'py>(
 
 /// A struct value, as PySpark converts one: a tuple or a Row by position, a 
dict by name,
 /// and another object by the names of its `__dict__`.
-fn convert_struct(obj: &Bound<'_, PyAny>, fields: &[StructField]) -> 
PyResult<Value> {
+fn convert_struct(
+    obj: &Bound<'_, PyAny>,
+    fields: &[StructField],
+    late: &mut Late,
+) -> PyResult<Value> {
     let py = obj.py();
     let values = if let Ok(tuple) = obj.cast::<PyTuple>() {
         values_by_position(py, tuple.iter().collect(), fields)?
@@ -1746,15 +1815,19 @@ fn convert_struct(obj: &Bound<'_, PyAny>, fields: 
&[StructField]) -> PyResult<Va
             obj.str()?
         )));
     };
-    struct_of(&values, fields)
+    struct_of(&values, fields, late)
 }
 
-fn struct_of(values: &[Bound<'_, PyAny>], fields: &[StructField]) -> 
PyResult<Value> {
+fn struct_of(
+    values: &[Bound<'_, PyAny>],
+    fields: &[StructField],
+    late: &mut Late,
+) -> PyResult<Value> {
     let names: std::sync::Arc<[String]> = fields.iter().map(|f| 
f.name.clone()).collect();
     let values = values
         .iter()
         .zip(fields)
-        .map(|(value, f)| convert(value, &f.data_type, f.nullable))
+        .map(|(value, f)| convert(value, &f.data_type, f.nullable, late))
         .collect::<PyResult<Vec<_>>>()?;
     Ok(Value::Struct(StructValue::new(names, values)))
 }
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 97e48f08..9232c0f9 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -1000,11 +1000,17 @@ impl PySparkSession {
         let mut values: Vec<Vec<Value>> = (0..parts.len())
             .map(|_| Vec::with_capacity(fields.len()))
             .collect();
+        let mut late = infer::Late::default();
         {
             let _quanta = infer::DecimalQuanta::new();
             for (i, field) in fields.iter().enumerate() {
                 for (row, out) in parts.iter().zip(values.iter_mut()) {
-                    out.push(infer::convert(&row[i], &field.data_type, 
field.nullable)?);
+                    out.push(infer::convert(
+                        &row[i],
+                        &field.data_type,
+                        field.nullable,
+                        &mut late,
+                    )?);
                 }
             }
         }
@@ -1020,6 +1026,8 @@ impl PySparkSession {
                 return Err(err);
             }
         }
+        // Then the columns are built, which rejects the values that no 
converter of PySpark does.
+        late.finish()?;
         // The names, with those that inference added, must name every column.
         if let Some(cols) = &cols {
             if cols.len() != fields.len() {
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index b9a3ec1c..63fdc5af 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -14927,6 +14927,54 @@ def 
test_values_of_local_rows_convert_and_raise_as_pyarrow(mock_connect):
         assert e.value.getCondition() == 
"UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION"
         assert e.value.getMessageParameters() == {"data_type": data_type}
 
[email protected](
+    "rows,ddl,error,message",
+    [
+        # The converters of PySpark check every value before PyArrow builds 
any column.
+        ([(128, 0)], "a tinyint, b timestamp", AssertionError, ""),
+        ([(128, datetime.datetime(2020, 1, 1)), (1, 0)], "a tinyint, b 
timestamp",
+         AssertionError, ""),
+        ([(128, None)], "a tinyint, b int not null", "PySparkValueError",
+         "input for IntegerType() must not be None"),
+        ([("x", 0)], "a int, b binary", AssertionError, ""),
+        ([([128], "x")], "a array<tinyint>, b decimal(5,2)", AssertionError, 
""),
+        ([((128, 0),)], "a struct<x:tinyint,y:timestamp>", AssertionError, ""),
+        ([({"k": 1}, 0)], "a array<int>, b timestamp", AssertionError, ""),
+        # A value that a map or a non-nullable column keeps for PyArrow, and a 
lone surrogate,
+        # which PyArrow cannot encode, wait behind the converters too.
+        ([({300: "x"}, 0)], "a map<tinyint,string>, b timestamp", 
AssertionError, ""),
+        ([(128, 0)], "a tinyint not null, b timestamp", AssertionError, ""),
+        ([("\ud800", 0)], "a string, b timestamp", AssertionError, ""),
+        # The parts of a VariantVal and of a Geometry are PyArrow's to convert.
+        ([(T.VariantVal(7, b""), 0)], "a variant, b timestamp", 
AssertionError, ""),
+        ([(T.Geometry(7, 4326), 0)], "a geometry(4326), b timestamp", 
AssertionError, ""),
+        ([(T.Geometry(b"\x00", "x"), 0)], "a geometry(4326), b timestamp", 
AssertionError, ""),
+        # PyArrow raises its own errors in the order of the columns.
+        ([(128, "\ud800")], "a tinyint, b string", "ArrowInvalid", "Value 128 
too large"),
+        ([(128,)], "a tinyint not null", "ArrowInvalid", "Value 128 too 
large"),
+        ([(128, "x")], "a tinyint, b int", "ArrowInvalid", "Value 128 too 
large"),
+        ([("x", 300)], "a int, b tinyint", "ArrowInvalid", "Could not convert 
'x'"),
+        # The error of the Arrow schema is before that of a value.
+        ([(128, None)], "a tinyint, b interval year to month", 
"PySparkTypeError",
+         "UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION"),
+        ([("\ud800",)], "a string", UnicodeEncodeError, "surrogates not 
allowed"),
+    ],
+)
+def test_local_rows_raise_the_error_of_a_converter_before_that_of_pyarrow(
+    mock_connect, rows, ddl, error, message
+):
+    import pyarrow as pa
+    import pyspark.errors as errors
+
+    error = {"ArrowInvalid": pa.ArrowInvalid, "PySparkValueError": 
errors.PySparkValueError,
+             "PySparkTypeError": errors.PySparkTypeError}.get(error, error)
+    spark, _ = mock_connect
+    with pytest.raises(error) as e:
+        spark.createDataFrame(rows, ddl)
+    assert type(e.value) is error
+    assert message in str(e.value)
+
+
 def 
test_nested_duplicate_field_names_are_deduplicated_in_the_arrow_schema(mock_connect):
     # As PySpark's _deduplicate_field_names: the Arrow schema of nested struct 
fields numbers
     # duplicate names, which the server cannot read, while the schema of the 
relation keeps


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to