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 6bed27e7 [SPARK-61290][CONNECT][PYTHON] Raise 
CANNOT_INFER_ARRAY_ELEMENT_TYPE for a list without an element type in the 
Column methods of the Python client, as PySpark does
6bed27e7 is described below

commit 6bed27e7fdf22b3b6733852c54bdc63ff3952dfc
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 15:51:13 2026 +0900

    [SPARK-61290][CONNECT][PYTHON] Raise CANNOT_INFER_ARRAY_ELEMENT_TYPE for a 
list without an element type in the Column methods of the Python client, as 
PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61290](https://issues.apache.org/jira/browse/SPARK-61290): raise 
`CANNOT_INFER_ARRAY_ELEMENT_TYPE` for a list without an element type in the 
Column methods of the Python client, as PySpark does.
    
    - `crates/pyspark-rs/src/functions.rs`: a new `to_value_column` converts a 
value that a Column method takes. A list becomes a typed array literal, as 
PySpark's `LiteralExpression._from_value` makes it: the element type is that of 
the first element, an empty list or one that starts with None raises 
`CANNOT_INFER_ARRAY_ELEMENT_TYPE`, and each element is converted to that type 
(a None element is a typed null, a nested list is an array of the element type, 
and a value of another type rais [...]
    - `crates/pyspark-rs/src/column.rs`: `when`, `otherwise`, `getItem`, 
`__getitem__` and the elements of `isin` use `to_value_column`. These are the 
Column methods that PySpark converts their values through `LiteralExpression`.
    
    The comparison and arithmetic operators, `between`, `contains`, 
`startswith` and `endswith` are unchanged: PySpark does not convert a list in 
those methods (it raises `AttributeError`), so they do not reach the typed 
literal.
    
    ### Why are the changes needed?
    
    With this change `F.col("id") > 0` style code that passes `[]` or `[None, 
2]` to `when`, `otherwise` or `getItem` fails on the Python client as it does 
on PySpark 4.3.0, instead of sending an `array()` of the elements. A list of a 
valid type sends the same literal as PySpark: for `[1, None, 3]`, `array<int>` 
with the null typed as `int`. `F.when(F.lit(True), [])` still returns an 
`array()`, as PySpark's functions do.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Python client only. `Column.otherwise([])`, 
`Column.otherwise([None, 2])`, `Column.when(cond, [])`, `Column.getItem([])` 
and `Column[[]]` now raise `PySparkTypeError` with 
`CANNOT_INFER_ARRAY_ELEMENT_TYPE`, as PySpark does. Previously they were 
accepted and sent as `array(...)`, for example `Row(o=[])` and `Row(o=[None, 
2])`.
    
    ### How was this patch tested?
    
    - Offline, `python/tests/test_dropin_offline.py`: 
`test_column_methods_cannot_infer_the_element_type_of_a_list_as_pyspark` 
(parametrized over `[]`, `[None, 2]` and `[[], [1]]`, across when/otherwise, 
getItem, `[]` and isin), 
`test_column_methods_send_a_list_as_the_typed_array_literal_of_pyspark` (the 
sent literal for valid lists, including nested lists, a long element type, a 
bool among ints, and the AssertionError cases), and 
`test_functions_lit_of_a_list_stays_an_array_as_pyspark` ( [...]
    - Live, `python/tests/test_dropin_e2e.py`: 
`test_column_list_values_are_typed_array_literals_on_the_server_as_pyspark` 
against a Spark 4.3.0 Connect server: `otherwise([])` and `otherwise([None, 
2])` raise `CANNOT_INFER_ARRAY_ELEMENT_TYPE`, `otherwise([1, 2])` gives the 
rows `[Row(o=[1, 2]), Row(o=[1])]` as PySpark does, and `F.when(F.lit(True), 
[])` gives `[Row(w=[])]`.
    - The literal sent for 23 lists was compared with PySpark 4.3.0's 
`LiteralExpression` protos (`getItem` argument), and all match, including the 
error cases.
    - `cargo test -p apache-spark-connect --release --lib` (528 passed), 
`--no-run` and `--features wasm-udf --no-run`, and `cargo fmt --all --check` 
pass. Clippy reports no diagnostics on the changed lines.
    - Full offline suites (`test_dropin_offline.py`, `test_ml_offline.py`, 
`test_arrow_handoff.py`): 2932 passed, 8 skipped. Live suites 
(`test_arrow_e2e.py`, `test_dropin_e2e.py`, `test_ml_e2e.py`): 237 passed, 1 
skipped. Two clippy-only edits after these runs were re-tested with the 
affected offline and live tests.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #454 from tdcmeehan/SPARK-61290-column-method-list-element-type.
    
    Authored-by: Timothy Meehan <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/column.rs     |  12 ++--
 crates/pyspark-rs/src/functions.rs  | 138 ++++++++++++++++++++++++++++++++++++
 python/tests/test_dropin_e2e.py     |  19 +++++
 python/tests/test_dropin_offline.py |  58 +++++++++++++++
 4 files changed, 221 insertions(+), 6 deletions(-)

diff --git a/crates/pyspark-rs/src/column.rs b/crates/pyspark-rs/src/column.rs
index d7402378..9d915ba9 100644
--- a/crates/pyspark-rs/src/column.rs
+++ b/crates/pyspark-rs/src/column.rs
@@ -5,7 +5,7 @@ use pyo3::types::PyDict;
 use spark_connect::column::Column;
 use spark_connect::expression::{Alias, ExpressionNode, NullOrdering};
 
-use crate::functions::to_column;
+use crate::functions::{to_column, to_value_column};
 
 /// Raise a `pyspark.errors` exception (`class_name`) carrying the given 
`error_class`
 /// condition and message parameters, mirroring the reference Column 
guard-rails.
@@ -265,7 +265,7 @@ impl PyColumn {
     #[pyo3(name = "getItem")]
     fn get_item(&self, key: &Bound<'_, PyAny>) -> PyResult<PyColumn> {
         let _origin = crate::origin::with_origin("getItem");
-        let key_col = py_obj_to_column(key)?;
+        let key_col = to_value_column(key)?;
         Ok(PyColumn::new(self.column.clone().get_item(key_col)))
     }
 
@@ -427,7 +427,7 @@ impl PyColumn {
                 ))
             }
         }
-        let val_col = py_obj_to_column(value)?;
+        let val_col = to_value_column(value)?;
         Ok(PyColumn::new(
             self.column.clone().when(condition.column.clone(), val_col),
         ))
@@ -452,7 +452,7 @@ impl PyColumn {
                 .call1((message,))?;
             return Err(PyErr::from_value(error));
         }
-        let val_col = py_obj_to_column(value)?;
+        let val_col = to_value_column(value)?;
         Ok(PyColumn::new(self.column.clone().otherwise(val_col)))
     }
 
@@ -471,7 +471,7 @@ impl PyColumn {
             }
             return self.substr(&key.getattr("start")?, &key.getattr("stop")?);
         }
-        let key_col = py_obj_to_column(key)?;
+        let key_col = to_value_column(key)?;
         Ok(PyColumn::new(self.column.clone().get_item(key_col)))
     }
 
@@ -962,7 +962,7 @@ impl PyColumn {
         }
         let mut vals = Vec::with_capacity(items.len());
         for c in &items {
-            vals.push(to_column(&c.bind(py))?);
+            vals.push(to_value_column(c.bind(py))?);
         }
         Ok(PyColumn::new(self.column.clone().isin(vals)))
     }
diff --git a/crates/pyspark-rs/src/functions.rs 
b/crates/pyspark-rs/src/functions.rs
index 3aa22b96..7fde16cf 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -327,6 +327,144 @@ pub fn to_column(obj: &Bound<'_, PyAny>) -> 
PyResult<Column> {
     ))
 }
 
+/// Convert a Python object that a Column method takes as a value, such as 
`when`, `otherwise`
+/// or `getItem`, to a Column. A list is a typed array literal, as PySpark's
+/// `LiteralExpression._from_value` makes it, so an empty list or one that 
starts with None is
+/// CANNOT_INFER_ARRAY_ELEMENT_TYPE. `to_column` builds a list as `lit` does, 
for the functions.
+pub(crate) fn to_value_column(obj: &Bound<'_, PyAny>) -> PyResult<Column> {
+    let obj = &enum_to_value(obj)?;
+    if let Ok(list) = obj.cast::<pyo3::types::PyList>() {
+        return 
Ok(Column::new(Expression::literal(typed_array_literal(list)?)));
+    }
+    to_column(obj)
+}
+
+/// The array literal of a list, of the type of its first element, as PySpark's
+/// `LiteralExpression` infers it. Each element is then a literal of that 
type, as
+/// `literal_as` makes it.
+fn typed_array_literal(list: &Bound<'_, pyo3::types::PyList>) -> 
PyResult<LiteralExpression> {
+    let Some(first) = list.iter().next().filter(|first| !first.is_none()) else 
{
+        return Err(crate::column::raise_pyspark(
+            list.py(),
+            "PySparkTypeError",
+            "CANNOT_INFER_ARRAY_ELEMENT_TYPE",
+            &[],
+        ));
+    };
+    let first = match first.cast::<pyo3::types::PyList>() {
+        Ok(inner) => typed_array_literal(inner)?,
+        Err(_) => scalar_literal_of(&first)?,
+    };
+    let element_type = literal_data_type(&first);
+    let elements = list
+        .iter()
+        .map(|item| literal_as(&item, &element_type))
+        .collect::<PyResult<Vec<_>>>()?;
+    Ok(LiteralExpression::Array {
+        element_type: Box::new(element_type),
+        elements,
+    })
+}
+
+/// The literal of `obj` as a value of `data_type`, as PySpark's 
`LiteralExpression(obj, type)`:
+/// None is a null, a list is an array of the element type, and another value 
must be of the
+/// type, else a bare AssertionError, as PySpark's asserts raise. As in 
Python, an int is a long
+/// and a bool is an int.
+fn literal_as(
+    obj: &Bound<'_, PyAny>,
+    data_type: &spark_connect::types::DataType,
+) -> PyResult<LiteralExpression> {
+    use spark_connect::types::DataType;
+    if obj.is_none() {
+        return Ok(LiteralExpression::Null(data_type.clone()));
+    }
+    let assertion = || pyo3::exceptions::PyAssertionError::new_err(());
+    if let DataType::Array { element_type, .. } = data_type {
+        let list = obj.cast::<pyo3::types::PyList>().map_err(|_| assertion())?;
+        let elements = list
+            .iter()
+            .map(|item| literal_as(&item, element_type))
+            .collect::<PyResult<Vec<_>>>()?;
+        return Ok(LiteralExpression::Array {
+            element_type: element_type.clone(),
+            elements,
+        });
+    }
+    if obj.is_instance_of::<pyo3::types::PyList>() {
+        return Err(assertion());
+    }
+    match (scalar_literal_of(obj)?, data_type) {
+        (LiteralExpression::Integer(value), DataType::Long) => {
+            Ok(LiteralExpression::Long(i64::from(value)))
+        }
+        (LiteralExpression::Boolean(value), DataType::Integer) => {
+            Ok(LiteralExpression::Integer(i32::from(value)))
+        }
+        (LiteralExpression::Boolean(value), DataType::Long) => {
+            Ok(LiteralExpression::Long(i64::from(value)))
+        }
+        (literal, data_type) if literal_data_type(&literal) == *data_type => 
Ok(literal),
+        _ => Err(assertion()),
+    }
+}
+
+/// The literal of a value that is not a list, as `to_column` builds it.
+fn scalar_literal_of(obj: &Bound<'_, PyAny>) -> PyResult<LiteralExpression> {
+    match to_column(obj)?.expression().node() {
+        ExpressionNode::Literal(literal) => Ok(literal.clone()),
+        _ => {
+            let type_name = obj
+                .get_type()
+                .name()
+                .map(|n| n.to_string())
+                .unwrap_or_else(|_| "<unknown>".to_string());
+            Err(crate::column::raise_pyspark(
+                obj.py(),
+                "PySparkTypeError",
+                "UNSUPPORTED_DATA_TYPE",
+                &[("data_type", &type_name)],
+            ))
+        }
+    }
+}
+
+/// The data type of a literal, as the type of PySpark's `LiteralExpression` 
of it.
+fn literal_data_type(literal: &LiteralExpression) -> 
spark_connect::types::DataType {
+    use spark_connect::types::DataType;
+    match literal {
+        LiteralExpression::Null(data_type) => data_type.clone(),
+        LiteralExpression::Boolean(_) => DataType::Boolean,
+        LiteralExpression::Byte(_) => DataType::Byte,
+        LiteralExpression::Short(_) => DataType::Short,
+        LiteralExpression::Integer(_) => DataType::Integer,
+        LiteralExpression::Long(_) => DataType::Long,
+        LiteralExpression::Float(_) => DataType::Float,
+        LiteralExpression::Double(_) => DataType::Double,
+        LiteralExpression::Decimal {
+            precision, scale, ..
+        } => DataType::Decimal {
+            precision: *precision,
+            scale: *scale,
+        },
+        LiteralExpression::String(_) => crate::infer::string_type(),
+        LiteralExpression::Binary(_) => DataType::Binary,
+        LiteralExpression::Date(_) => DataType::Date,
+        LiteralExpression::Timestamp(_) => DataType::Timestamp,
+        LiteralExpression::TimestampNtz(_) => DataType::TimestampNtz,
+        LiteralExpression::DayTimeInterval(_) => DataType::DayTimeInterval {
+            start_field: 0,
+            end_field: 3,
+        },
+        LiteralExpression::Time { precision, .. } => DataType::Time {
+            precision: *precision,
+        },
+        LiteralExpression::Array { element_type, .. } => DataType::Array {
+            element_type: element_type.clone(),
+            contains_null: true,
+        },
+    }
+}
+
 /// The number of dimensions of `obj` if it is a `numpy.ndarray`. NumPy is 
looked up in
 /// `sys.modules`, as an array exists only when it is imported, so this does 
not import it.
 fn numpy_ndarray_ndim(obj: &Bound<'_, PyAny>) -> PyResult<Option<usize>> {
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index c1d4260e..f92bd1ed 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3629,6 +3629,25 @@ def 
test_try_cast_and_isin_raise_the_errors_of_pyspark(session):
     assert df.where(F.col("id").isin([1, 2])).count() == 2
 
 
+def 
test_column_list_values_are_typed_array_literals_on_the_server_as_pyspark(session):
+    # As PySpark Connect's: a list that a Column method takes as a value is an 
array of its
+    # first element's type, so an empty one, or one that starts with None, is 
an error, while
+    # F.lit of a list is an array() whatever it holds.
+    from pyspark.errors import PySparkTypeError
+    from pyspark.sql import functions as F
+
+    df = session.range(2)
+    chosen = F.when(F.col("id") > 0, F.array(F.lit(1)))
+    for value in ([], [None, 2]):
+        with pytest.raises(PySparkTypeError) as e:
+            df.select(chosen.otherwise(value).alias("o"))
+        assert e.value.getCondition() == "CANNOT_INFER_ARRAY_ELEMENT_TYPE"
+    assert df.select(chosen.otherwise([1, 2]).alias("o")).collect() == [
+        Row(o=[1, 2]), Row(o=[1])]
+    assert session.range(1).select(F.when(F.lit(True), 
[]).alias("w")).collect() == [
+        Row(w=[])]
+
+
 
 
 def test_ml_vector_functions_as_pyspark(session):
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 16b2dab8..881f1a09 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -2142,6 +2142,64 @@ def 
test_try_cast_and_isin_take_their_arguments_as_pyspark():
     assert e.value.getMessageParameters() == {"data_type": "tuple"}
 
 
[email protected]("value", [[], [None, 2], [[], [1]]])
+def 
test_column_methods_cannot_infer_the_element_type_of_a_list_as_pyspark(value):
+    # As PySpark's LiteralExpression of a list: its element type is that of 
its first element,
+    # which an empty list, or one that starts with None, does not have.
+    from pyspark.errors import PySparkTypeError
+    from pyspark.sql import functions as F
+
+    column = F.col("a")
+    for build in (
+        lambda: F.when(F.lit(True), 1).otherwise(value),
+        lambda: column.getItem(value),
+        lambda: column[value],
+        lambda: column.isin([value]),
+    ):
+        with pytest.raises(PySparkTypeError) as e:
+            build()
+        assert e.value.getCondition() == "CANNOT_INFER_ARRAY_ELEMENT_TYPE"
+
+
+def test_column_methods_send_a_list_as_the_typed_array_literal_of_pyspark():
+    from google.protobuf.json_format import MessageToDict
+    from pyspark.sql import functions as F
+
+    def sent_literal(value):
+        plan = F.col("a").getItem(value)._expr.to_plan(None)
+        return MessageToDict(plan.unresolved_extract_value.extraction.literal)
+
+    assert sent_literal([1, None, 3]) == {"array": {
+        "elementType": {"integer": {}},
+        "elements": [{"integer": 1}, {"null": {"integer": {}}}, {"integer": 
3}]}}
+    assert sent_literal([[1, 2], [None]]) == {"array": {
+        "elementType": {"array": {"containsNull": True, "elementType": 
{"integer": {}}}},
+        "elements": [
+            {"array": {"elementType": {"integer": {}},
+                       "elements": [{"integer": 1}, {"integer": 2}]}},
+            {"array": {"elementType": {"integer": {}}, "elements": [{"null": 
{"integer": {}}}]}}]}}
+    assert sent_literal([2 ** 40, 1]) == {"array": {
+        "elementType": {"long": {}}, "elements": [{"long": "1099511627776"}, 
{"long": "1"}]}}
+    # As in Python, a bool is an int, so [1, True] is [1, 1].
+    assert sent_literal([1, True]) == {"array": {
+        "elementType": {"integer": {}}, "elements": [{"integer": 1}, 
{"integer": 1}]}}
+    # An element of another type than the first's is an AssertionError, as 
PySpark's asserts.
+    for value in ([1, 2.5], [1.5, 2], [1, "a"], [1, 2 ** 40], [[1], [2.5]]):
+        with pytest.raises(AssertionError):
+            sent_literal(value)
+
+
+def test_functions_lit_of_a_list_stays_an_array_as_pyspark():
+    # As PySpark's functions: lit builds the array of a list, which F.when 
takes without an
+    # element type, so the empty list is an array() and not 
CANNOT_INFER_ARRAY_ELEMENT_TYPE.
+    from pyspark.sql import functions as F
+
+    assert F.lit([])._expr.to_plan(None).unresolved_function.function_name == 
"array"
+    when = F.when(F.lit(True), [])._expr.to_plan(None).unresolved_function
+    assert when.function_name == "when"
+    assert when.arguments[1].unresolved_function.function_name == "array"
+
+
 
 
 def test_map_functions_send_their_resource_profile_as_pyspark(mock_connect):


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

Reply via email to