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 45c2d21f [SPARK-61628][CONNECT][PYTHON] Match PySpark's SRID and 
type-string errors, and the bool arguments of checkpoint and unionByName, in 
the Python client
45c2d21f is described below

commit 45c2d21ff391832baea4725b8f8d721ddf4dff15
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 17:52:31 2026 +0900

    [SPARK-61628][CONNECT][PYTHON] Match PySpark's SRID and type-string errors, 
and the bool arguments of checkpoint and unionByName, in the Python client
    
    ### What changes were proposed in this pull request?
    
    This fixes three differences from PySpark 4.3.0 that a post-merge review of 
#612 (SRIDs) and #614 (the bools of the catalog and the writers) found. It also 
documents two known, crate-wide differences.
    
    1. **The SRID error of a collect.** collect, head, first, take, tail, 
toPandas and toArrow of a DataFrame whose schema has an SRID that PySpark does 
not support raised the server's error: `SparkException: not support type: 
GeometryType(2154)`. PySpark raises its `IllegalArgumentException` 
[ST_INVALID_SRID_VALUE]: it converts the schema of the first response that 
carries one, before the server's later failure of the stream. Those responses 
come in the order session, schema, result_comp [...]
    2. **Nested types assert a DataType.** `StructField`, `ArrayType` and 
`MapType` took a type string, such as `StructField("g", "int")`, where 
PySpark's constructors assert `isinstance(..., DataType)`. They now raise 
PySpark's `AssertionError`, with its messages: `dataType int should be an 
instance of <class 'pyspark.sql.types.DataType'>`, and the same for 
`elementType`, `keyType` and `valueType`. `StructType.add` still takes a type 
string, as PySpark's does. The `ValueError` of a bad t [...]
    3. **The bool flags of checkpoint and unionByName.** `checkpoint(eager)`, 
`localCheckpoint(eager)` and `unionByName(allowMissingColumns)` took a strict 
bool. They are now converted as PySpark's protobuf messages convert them, as 
#614 converts the other flags:
       - 0, 1 and objects with `__index__` are taken;
       - None leaves `eager` unset (false), as PySpark's constructor of the 
command does, and is a `TypeError` for `allowMissingColumns`;
       - `"x"` and `1.5` are `TypeError`s.
    4. **Docs:** two notes in the "What drop-in means" section of 
`docs/compatibility.md`:
       - PyO3's `TypeError` for too many positional arguments counts them 
without `self`;
       - a warning that the Rust core raises is attributed to the caller's 
frame and module, so `warnings.filterwarnings(..., module="pyspark")` does not 
match it.
    
    ### Why are the changes needed?
    
    For parity with PySpark 4.3.0: the error class of an unsupported SRID, the 
constructors of the nested types, and the bool arguments that PySpark accepts.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes:
    - an unsupported SRID now raises PySpark's error from these methods;
    - the nested-type constructors reject type strings;
    - the three bool flags take the values that PySpark takes.
    
    ### How was this patch tested?
    
    - New offline tests in `python/tests/test_dropin_offline.py`, all four 
failing before the change and passing after:
      - a mock that sends a `geometry(2154)` schema and then fails the stream;
      - the asserts of the nested constructors;
      - the message of a bad type string;
      - the bool conversions of the three flags.
    - Live, against a Spark 4.3.0 Connect server, the drop-in and the reference 
client give the same results:
      - collect, toPandas, first, head, take, tail, toLocalIterator and toArrow 
of the SRID case;
      - the nested constructors with a str, None, a geography string and 5;
      - the three flags with True, False, 0, 1, 2, None, an `__index__` object, 
`"x"` and `1.5`.
    - `tests/test_dropin_offline.py` and `tests/test_ml_offline.py` (2154 
passed, 8 skipped, after rebasing on master) and `tests/test_dropin_e2e.py` 
(279 passed) pass, as do `cargo test -p apache-spark-connect --lib` (679 
passed) and the live Rust e2e suites that cover collecting. `cargo fmt 
--check`, `scripts/audit_no_stubs.sh` and `ruff check` pass.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #630 from HyukjinKwon/SPARK-61628-srid-nested-bools.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs    |  98 ++++++++++++++++++++++-----
 crates/pyspark-rs/src/types.rs        |  26 +++++--
 crates/spark-connect/src/dataframe.rs |  43 +++++++++++-
 docs/compatibility.md                 |   6 ++
 python/tests/test_dropin_offline.py   | 123 ++++++++++++++++++++++++++++++++++
 5 files changed, 270 insertions(+), 26 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 8caea1ff..24a14e57 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -13,7 +13,7 @@ use crate::interrupt::interruptible;
 use crate::options::{set_option_skip_none, set_options_skip_none, 
DefaultedOption};
 use crate::row::{FieldConverters, NestedFieldNames};
 use crate::stat_arguments::proto_int;
-use crate::streaming::PyDataStreamWriter;
+use crate::streaming::{proto_bool, ProtoBool, PyDataStreamWriter};
 use crate::types::PyDataType;
 
 /// Flatten `*cols` args that are each a str or a list of str (pyspark
@@ -118,7 +118,7 @@ impl PyDataFrame {
         })?;
         let (batches, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
             self.dataframe
-                .collect_record_batches_with_schema()
+                
.collect_record_batches_with_schema_checked(check_schema_at_receipt)
                 .map_err(Box::new)
         })?;
         check_schema_conversion(py, schema.as_ref())?;
@@ -1374,18 +1374,21 @@ impl PyDataFrame {
         Ok(PyDataFrame::new(self.dataframe.union(&other.dataframe)))
     }
 
-    /// Union by name, optionally filling columns missing on one side with 
null.
-    #[pyo3(signature = (other, allowMissingColumns=false))]
+    /// Union by name, optionally filling columns missing on one side with 
null. The flag is
+    /// converted as PySpark's set operation sets it: None is a `TypeError`.
+    #[pyo3(signature = (other, allowMissingColumns=ProtoBool::default()))]
     fn unionByName(
         &self,
+        py: Python<'_>,
         other: &Bound<'_, PyAny>,
-        allowMissingColumns: bool,
+        allowMissingColumns: ProtoBool,
     ) -> PyResult<PyDataFrame> {
+        let allow_missing_columns = allowMissingColumns.value(py)?;
         let other = self.same_session(other)?;
-        Ok(PyDataFrame::new(
-            self.dataframe
-                .union_by_name_opt(&other.dataframe, allowMissingColumns),
-        ))
+        Ok(PyDataFrame::new(self.dataframe.union_by_name_opt(
+            &other.dataframe,
+            allow_missing_columns,
+        )))
     }
 
     /// Intersect with another DataFrame.
@@ -1945,8 +1948,9 @@ impl PyDataFrame {
     }
 
     /// Reliable checkpoint (materialize + truncate lineage), at once if 
`eager`, as PySpark's.
-    #[pyo3(signature = (eager=true))]
-    fn checkpoint(&self, py: Python<'_>, eager: bool) -> PyResult<PyDataFrame> 
{
+    #[pyo3(signature = (eager=DefaultedOption::Omitted), text_signature = 
"($self, eager=True)")]
+    fn checkpoint(&self, py: Python<'_>, eager: DefaultedOption) -> 
PyResult<PyDataFrame> {
+        let eager = checkpoint_eager(py, &eager)?;
         Ok(PyDataFrame::new(interruptible(
             py,
             &self.dataframe.spark_session(),
@@ -1956,13 +1960,18 @@ impl PyDataFrame {
 
     /// Local checkpoint, at once if `eager`, kept at `storageLevel`, else at 
the server's
     /// default, as PySpark's.
-    #[pyo3(name = "localCheckpoint", signature = (eager=true, 
storageLevel=None))]
+    #[pyo3(
+        name = "localCheckpoint",
+        signature = (eager=DefaultedOption::Omitted, storageLevel=None),
+        text_signature = "($self, eager=True, storageLevel=None)"
+    )]
     fn local_checkpoint(
         &self,
         py: Python<'_>,
-        eager: bool,
+        eager: DefaultedOption,
         storageLevel: Option<Bound<'_, PyAny>>,
     ) -> PyResult<PyDataFrame> {
+        let eager = checkpoint_eager(py, &eager)?;
         let level = storageLevel
             .filter(|level| !level.is_none())
             .map(|level| crate::storagelevel::storage_level_proto(&level))
@@ -2405,7 +2414,9 @@ impl PyDataFrame {
     fn collect(&self, py: Python<'_>) -> PyResult<Vec<Py<PyAny>>> {
         // Release the GIL across the blocking RPC so other Python threads run.
         let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
-            self.dataframe.collect_with_schema().map_err(Box::new)
+            self.dataframe
+                .collect_with_schema_checked(check_schema_at_receipt)
+                .map_err(Box::new)
         })?;
         rows_to_py(py, &self.dataframe, &rows, schema.as_ref())
     }
@@ -2452,7 +2463,7 @@ impl PyDataFrame {
     fn to_arrow(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
         let (batches, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
             self.dataframe
-                .collect_record_batches_with_schema()
+                
.collect_record_batches_with_schema_checked(check_schema_at_receipt)
                 .map_err(Box::new)
         })?;
         check_schema_conversion(py, schema.as_ref())?;
@@ -2632,7 +2643,9 @@ impl PyDataFrame {
     /// Get the first row.
     fn first(&self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
         let (row, schema) = interruptible(py, &self.dataframe.spark_session(), 
|| {
-            self.dataframe.first_with_schema().map_err(Box::new)
+            self.dataframe
+                .first_with_schema_checked(check_schema_at_receipt)
+                .map_err(Box::new)
         })?;
         Ok(rows_to_py(py, &self.dataframe, row.as_slice(), 
schema.as_ref())?.pop())
     }
@@ -2655,7 +2668,7 @@ impl PyDataFrame {
         let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
             self.dataframe
                 .limit(num)
-                .collect_with_schema()
+                .collect_with_schema_checked(check_schema_at_receipt)
                 .map_err(Box::new)
         })?;
         rows_to_py(py, &self.dataframe, &rows, schema.as_ref())
@@ -2678,7 +2691,7 @@ impl PyDataFrame {
         let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
             self.dataframe
                 .tail(num)
-                .collect_with_schema()
+                .collect_with_schema_checked(check_schema_at_receipt)
                 .map_err(Box::new)
         })?;
         rows_to_py(py, &self.dataframe, &rows, schema.as_ref())
@@ -4799,6 +4812,55 @@ pub(crate) fn check_schema_conversion(
     }
 }
 
+/// The `eager` flag of a checkpoint, which PySpark passes to the constructor 
of its command: true
+/// when it is omitted, and false for None, which the constructor leaves 
unset. Another value is
+/// converted as [`proto_bool`] converts it.
+fn checkpoint_eager(py: Python<'_>, eager: &DefaultedOption) -> PyResult<bool> 
{
+    match eager {
+        DefaultedOption::Omitted => Ok(true),
+        DefaultedOption::Given(value) => {
+            let value = value.bind(py);
+            if value.is_none() {
+                Ok(false)
+            } else {
+                proto_bool(value)
+            }
+        }
+    }
+}
+
+/// The error that [`check_schema_conversion`] raises for a schema that it 
cannot convert, as the
+/// core error of the same PySpark error class and parameters.
+fn unconvertible_schema_error(
+    schema: &spark_connect::types::DataType,
+) -> Option<spark_connect_core::error::SparkError> {
+    use spark_connect_core::error::{SparkError, SparkErrorKind};
+    unconvertible_type(schema).map(|unconvertible| match unconvertible {
+        UnconvertibleType::NanosecondTimestamp(text) => SparkError::classed(
+            SparkErrorKind::ValueError,
+            "UNSUPPORTED_OPERATION",
+            &[("operation", &format!("data type {text}"))],
+        ),
+        UnconvertibleType::SpatialSrid(srid) => SparkError::classed(
+            SparkErrorKind::IllegalArgument,
+            "ST_INVALID_SRID_VALUE",
+            &[("srid", &srid.to_string())],
+        ),
+    })
+}
+
+/// The check of the schema that the collecting APIs run as the server sends 
it, as
+/// [`unconvertible_schema_error`]: PySpark raises the error of a schema that 
it cannot convert
+/// when it receives the schema, before the rows and any later failure of the 
execution.
+fn check_schema_at_receipt(
+    schema: &spark_connect::types::DataType,
+) -> spark_connect_core::error::Result<()> {
+    match unconvertible_schema_error(schema) {
+        Some(error) => Err(error),
+        None => Ok(()),
+    }
+}
+
 /// Raises as PySpark's Arrow conversion of the rows does for a result of 
`schema` with a
 /// year-month interval, which Spark Connect cannot collect: the error is 
raised even when the
 /// result has no rows.
diff --git a/crates/pyspark-rs/src/types.rs b/crates/pyspark-rs/src/types.rs
index 860b770a..f19edc09 100644
--- a/crates/pyspark-rs/src/types.rs
+++ b/crates/pyspark-rs/src/types.rs
@@ -1782,7 +1782,7 @@ impl PyArrayType {
         elementType: &Bound<'_, PyAny>,
         containsNull: bool,
     ) -> PyResult<pyo3::PyClassInitializer<Self>> {
-        let et = py_to_data_type(elementType)?;
+        let et = nested_data_type(elementType, "elementType")?;
         Ok(init_chain!(
             DataType::Array {
                 element_type: Box::new(et.clone()),
@@ -1924,8 +1924,8 @@ impl PyMapType {
         valueType: &Bound<'_, PyAny>,
         valueContainsNull: bool,
     ) -> PyResult<pyo3::PyClassInitializer<Self>> {
-        let kt = py_to_data_type(keyType)?;
-        let vt = py_to_data_type(valueType)?;
+        let kt = nested_data_type(keyType, "keyType")?;
+        let vt = nested_data_type(valueType, "valueType")?;
         Ok(init_chain!(
             DataType::Map {
                 key_type: Box::new(kt.clone()),
@@ -2251,7 +2251,7 @@ impl PyStructField {
         };
         let field = StructField {
             name,
-            data_type: py_to_data_type(dataType)?,
+            data_type: nested_data_type(dataType, "dataType")?,
             nullable,
             metadata: md,
         };
@@ -3930,6 +3930,21 @@ pub(crate) fn schema_data_type(
     py_to_data_type(schema)
 }
 
+/// The type of a constructor of a nested type (`ArrayType`, `MapType`, 
`StructField`), which
+/// PySpark asserts to be a `DataType` before it reads it: a type string, or 
any other value, is an
+/// `AssertionError` with PySpark's message, for the argument `name`.
+fn nested_data_type(obj: &Bound<'_, PyAny>, name: &str) -> PyResult<DataType> {
+    let data_type_class = 
obj.py().import("pyspark.sql.types")?.getattr("DataType")?;
+    if !obj.is_instance(&data_type_class)? {
+        return Err(pyo3::exceptions::PyAssertionError::new_err(format!(
+            "{name} {} should be an instance of {}",
+            obj.str()?,
+            data_type_class.str()?
+        )));
+    }
+    py_to_data_type(obj)
+}
+
 pub(crate) fn py_to_data_type(obj: &Bound<'_, PyAny>) -> PyResult<DataType> {
     if let Ok(g) = obj.extract::<PyRef<PyGeometryType>>() {
         return Ok(DataType::Geometry { srid: g.srid });
@@ -4094,7 +4109,8 @@ pub(crate) fn py_to_data_type(obj: &Bound<'_, PyAny>) -> 
PyResult<DataType> {
     if let Ok(s) = obj.extract::<String>() {
         return DataType::from_ddl(&s).map_err(|e| {
             PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
-                "invalid type string '{s}': {e:?}"
+                "invalid type string '{s}': {}",
+                e.message()
             ))
         });
     }
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 7fb80ed7..0827bf02 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1002,6 +1002,19 @@ impl DataFrame {
     /// (`ExecutePlanResponse.schema`), as the reference client's `_to_table` 
returns it.
     /// Unlike the Arrow schema of the rows, it has the user-defined types of 
the columns.
     pub fn collect_with_schema(&self) -> Result<(Vec<Row>, Option<DataType>)> {
+        self.collect_with_schema_checked(|_| Ok(()))
+    }
+
+    /// As [`DataFrame::collect_with_schema`], but `check` runs on the schema 
as soon as the server
+    /// sends it, before the rows and any later response are read: an error 
that it returns ends
+    /// the execution then. PySpark's client converts the schema of the 
response that carries it,
+    /// so a schema that it cannot convert raises before a later failure of 
the stream. Not a
+    /// stable API.
+    #[doc(hidden)]
+    pub fn collect_with_schema_checked(
+        &self,
+        check: impl Fn(&DataType) -> Result<()>,
+    ) -> Result<(Vec<Row>, Option<DataType>)> {
         let request = self.build_execute_request()?;
         let observations = self.plan.observations();
         let mut stream = self.session.execute_plan(request)?;
@@ -1018,7 +1031,9 @@ impl DataFrame {
             capture_execution(&mut resp, &mut info, &self.session, 
&observations)
                 .map_err(|error| stream.fail(error))?;
             if let Some(data_type) = resp.schema.take() {
-                schema = Some(DataType::from_proto(&data_type).map_err(|e| 
stream.fail(e))?);
+                let data_type = DataType::from_proto(&data_type).map_err(|e| 
stream.fail(e))?;
+                check(&data_type).map_err(|e| stream.fail(e))?;
+                schema = Some(data_type);
             }
             if let 
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) =
                 resp.response_type
@@ -1097,6 +1112,16 @@ impl DataFrame {
     /// user-defined types.
     pub fn collect_record_batches_with_schema(
         &self,
+    ) -> Result<(Vec<arrow::record_batch::RecordBatch>, Option<DataType>)> {
+        self.collect_record_batches_with_schema_checked(|_| Ok(()))
+    }
+
+    /// As [`DataFrame::collect_record_batches_with_schema`], with `check` run 
on the schema as
+    /// [`DataFrame::collect_with_schema_checked`] runs it. Not a stable API.
+    #[doc(hidden)]
+    pub fn collect_record_batches_with_schema_checked(
+        &self,
+        check: impl Fn(&DataType) -> Result<()>,
     ) -> Result<(Vec<arrow::record_batch::RecordBatch>, Option<DataType>)> {
         let request = self.build_execute_request()?;
         let observations = self.plan.observations();
@@ -1114,7 +1139,9 @@ impl DataFrame {
             capture_execution(&mut resp, &mut info, &self.session, 
&observations)
                 .map_err(|error| stream.fail(error))?;
             if let Some(data_type) = resp.schema.take() {
-                schema = Some(DataType::from_proto(&data_type).map_err(|e| 
stream.fail(e))?);
+                let data_type = DataType::from_proto(&data_type).map_err(|e| 
stream.fail(e))?;
+                check(&data_type).map_err(|e| stream.fail(e))?;
+                schema = Some(data_type);
             }
             if let 
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) =
                 resp.response_type
@@ -1496,7 +1523,17 @@ impl DataFrame {
 
     /// The first row, with the schema of the result, as 
[`DataFrame::collect_with_schema`].
     pub fn first_with_schema(&self) -> Result<(Option<Row>, Option<DataType>)> 
{
-        let (rows, schema) = self.limit(1).collect_with_schema()?;
+        self.first_with_schema_checked(|_| Ok(()))
+    }
+
+    /// The first row, with the schema of the result, as 
[`DataFrame::collect_with_schema_checked`]
+    /// checks it. Not a stable API.
+    #[doc(hidden)]
+    pub fn first_with_schema_checked(
+        &self,
+        check: impl Fn(&DataType) -> Result<()>,
+    ) -> Result<(Option<Row>, Option<DataType>)> {
+        let (rows, schema) = self.limit(1).collect_with_schema_checked(check)?;
         Ok((rows.into_iter().next(), schema))
     }
 
diff --git a/docs/compatibility.md b/docs/compatibility.md
index fcb1f62a..fd7d8ec4 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -594,6 +594,12 @@ unpickles it, as CPython's `copyreg._reconstructor` cannot 
create the drop-in's
 class with a native base; protocols 2 and up, pickle's default, load in both 
clients, and PySpark
 loads the drop-in's at every protocol.
 
+The `TypeError` for too many positional arguments counts them without `self`: 
where CPython says
+"takes from 2 to 4 positional arguments but 5 were given", the drop-in says 
"takes from 1 to 3
+positional arguments but 4 were given". A warning that the Rust core raises, 
such as the
+`FutureWarning` of `registerTempTable`, is attributed to the caller's frame 
and module, so a
+`warnings.filterwarnings(..., module="pyspark")` does not match it, as it 
matches PySpark's.
+
 ## Native NaiveBayes
 
 The Rust `ml::NaiveBayes` and `ml::NaiveBayesModel` train and predict through 
Spark
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 3d8e901b..d643be54 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -391,6 +391,76 @@ def 
test_schema_surfaces_raise_for_a_spatial_srid_that_pyspark_does_not_take(moc
         assert repr(df) == f"DataFrame[g: {simple}]"
 
 
+def 
test_collect_raises_the_srid_error_of_the_schema_before_a_later_stream_failure(mock_connect):
+    # As PySpark, which converts the schema of the first response that carries 
one, so an SRID
+    # that PySpark does not take raises ST_INVALID_SRID_VALUE before the 
stream fails after the
+    # schema, in each read of the rows, and the rows are not converted.
+    from pyspark.errors import IllegalArgumentException
+
+    spark, service = mock_connect
+    # The settings that toPandas reads before the execution.
+    service.confs = {"spark.sql.session.timeZone": "UTC",
+                     "spark.sql.execution.pandas.structHandlingMode": "legacy",
+                     "spark.sql.execution.arrow.pyspark.selfDestruct.enabled": 
"false"}
+    # DataType.geometry=26 with its srid=1; DataType.struct=21 
(Struct.fields=1; StructField
+    # name=1, data_type=2, nullable=3).
+    geometry = message_field(26, varint_field(1, 2154))
+    schema = message_field(21, message_field(
+        1, message_field(1, "g") + message_field(2, geometry) + 
varint_field(3, 1)))
+    # ExecutePlanResponse.schema=7, and then the stream fails.
+    service.execute_payloads = [message_field(7, schema)]
+    service.stream_failure = "INTERNAL"
+    df = spark.range(1)
+    for read in (lambda: df.collect(),
+                 lambda: df.toPandas(),
+                 lambda: df.first(),
+                 lambda: df.head(2),
+                 lambda: df.take(2),
+                 lambda: df.tail(2),
+                 lambda: list(df.toLocalIterator())):
+        with pytest.raises(IllegalArgumentException) as e:
+            read()
+        assert e.value.getCondition() == "ST_INVALID_SRID_VALUE"
+        assert e.value.getMessageParameters() == {"srid": "2154"}
+
+
+def test_nested_types_assert_a_data_type_not_a_type_string_as_pyspark():
+    # As PySpark's constructors, which assert that the type is a DataType, so 
a type string is an
+    # AssertionError, as is any other value. StructType.add takes a type 
string, which it parses.
+    import pyspark.sql.types as T
+
+    data_type_class = "<class 'pyspark.sql.types.DataType'>"
+    cases = [
+        (lambda: T.StructField("g", "int"),
+         f"dataType int should be an instance of {data_type_class}"),
+        (lambda: T.StructField("g", None),
+         f"dataType None should be an instance of {data_type_class}"),
+        (lambda: T.StructField("g", "geography(2154)"),
+         f"dataType geography(2154) should be an instance of 
{data_type_class}"),
+        (lambda: T.ArrayType("int"), f"elementType int should be an instance 
of {data_type_class}"),
+        (lambda: T.ArrayType(5), f"elementType 5 should be an instance of 
{data_type_class}"),
+        (lambda: T.MapType("int", T.IntegerType()),
+         f"keyType int should be an instance of {data_type_class}"),
+        (lambda: T.MapType(T.IntegerType(), "int"),
+         f"valueType int should be an instance of {data_type_class}"),
+    ]
+    for make, message in cases:
+        with pytest.raises(AssertionError) as e:
+            make()
+        assert str(e.value) == message
+    assert T.StructType().add("g", "string").fields[0].dataType == 
T.StringType()
+    assert T.StructType().add("g", T.LongType()).fields[0].dataType == 
T.LongType()
+
+
+def test_bad_type_strings_raise_their_message_not_a_debug_dump(mock_connect):
+    # A type string that does not parse, as the schema of `to`, raises a 
ValueError with the message
+    # of its error, not the Debug output of the error.
+    spark, _ = mock_connect
+    with pytest.raises(ValueError) as e:
+        spark.range(1).to("foo bar")
+    assert str(e.value) == "invalid type string 'foo bar': 
[INVALID_DATATYPE_FORMAT]"
+
+
 def test_json_forms_accept_trailing_whitespace_as_pyspark(mock_connect):
     # As PySpark's `_parse_datatype_json_value`, whose patterns match a prefix 
of the string: the
     # whitespace after a form with an argument or a field is not a part of it. 
A bare name is
@@ -1012,6 +1082,59 @@ def 
test_dataframe_plot_is_the_plot_accessor_of_pyspark():
     assert plot.data is df
 
 
+def 
test_bool_arguments_of_checkpoints_and_union_convert_as_protobuf_does(mock_connect):
+    # As PySpark, which passes the flags into the proto bool fields: upb 
converts 0, 1, 2 and an
+    # object with __index__ as bools. None is unset in the constructor of a 
checkpoint command,
+    # but a TypeError in the attribute of a set operation. Any other value is 
a TypeError.
+    spark, service = mock_connect
+    # ExecutePlanResponse.checkpoint_command_result=19 -> relation=1 -> 
relation_id=1.
+    service.execute_payload = message_field(19, message_field(1, 
message_field(1, "r1")))
+
+    class Index:
+        def __index__(self):
+            return 1
+
+    kept = []
+
+    def checkpoint_eager(make):
+        # The checkpoints are kept, as a dropped one sends its removal in the 
background.
+        kept.append(make())
+        # ExecutePlanRequest.plan=3 -> Plan.command=2 -> 
Command.checkpoint_command=14, whose
+        # CheckpointCommand.eager=3 is sent when true, and not when false.
+        plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+        return parse_message(parse_message(plan[2][0])[14][0]).get(3, [])
+
+    def union_allow_missing(value):
+        spark.range(1).unionByName(spark.range(1), value).collect()
+        # ExecutePlanRequest.plan=3 -> Plan.root=1 -> Relation.set_op=6, whose
+        # SetOperation.allow_missing_columns=6 is sent as a present field.
+        plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+        return parse_message(parse_message(plan[1][0])[6][0]).get(6)
+
+    df = spark.range(1)
+    other = spark.range(1)
+    cases = [(True, [1], [1]), (False, [], [0]), (0, [], [0]), (1, [1], [1]), 
(2, [1], [1]),
+             (Index(), [1], [1])]
+    for value, eager, allow_missing in cases:
+        assert checkpoint_eager(lambda: df.checkpoint(eager=value)) == eager, 
value
+        assert checkpoint_eager(lambda: df.localCheckpoint(eager=value)) == 
eager, value
+        assert union_allow_missing(value) == allow_missing, value
+    # None is unset for the checkpoint command, which the constructor takes, 
as false.
+    assert checkpoint_eager(lambda: df.checkpoint(eager=None)) == []
+    assert checkpoint_eager(lambda: df.localCheckpoint(eager=None)) == []
+    with pytest.raises(TypeError) as e:
+        df.unionByName(other, None)
+    assert str(e.value) == "'NoneType' object cannot be interpreted as an 
integer"
+    for value, message in [("x", "'str' object cannot be interpreted as an 
integer"),
+                           (1.5, "'float' object cannot be interpreted as an 
integer")]:
+        for make in (lambda: df.checkpoint(eager=value),
+                     lambda: df.localCheckpoint(eager=value),
+                     lambda: df.unionByName(other, value)):
+            with pytest.raises(TypeError) as e:
+                make()
+            assert str(e.value) == message
+
+
 def 
test_checkpoints_send_their_eager_and_storage_level_as_pyspark(mock_connect):
     # As PySpark's, checkpoint(eager) and localCheckpoint(eager, storageLevel) 
send them in
     # their CheckpointCommand, of which the mock answers with a 
CachedRemoteRelation.


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

Reply via email to