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 8a59c430 [SPARK-61542][CONNECT][PYTHON] Convert the counts of limit, 
offset, tail, head, take, repartition, repartitionByRange, coalesce and 
repartitionById as protobuf's default backend does, refusing a bool, as PySpark 
does
8a59c430 is described below

commit 8a59c430e075a44059069e2a2b52d90123772484
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 21:37:47 2026 +0900

    [SPARK-61542][CONNECT][PYTHON] Convert the counts of limit, offset, tail, 
head, take, repartition, repartitionByRange, coalesce and repartitionById as 
protobuf's default backend does, refusing a bool, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #560 (SPARK-61524), from the same review. On protobuf 7.34+, 
which a fresh install of `pyspark-client` 4.3.0 gets, official PySpark converts 
the counts that it sets in proto int fields with upb's conversion:
    - a bool raises `TypeError: Field spark.connect.Limit.limit: Expected an 
int, got a boolean.`;
    - a value that is not an int raises the `TypeError` of `operator.index`, 
such as `'float' object cannot be interpreted as an integer`. A NumPy int is 
taken, but not a NumPy bool.
    - an int out of the field's range raises `ValueError: Value out of range: 
1099511627776`.
    
    The Python client took these counts through PyO3. A bool was sent as 1 or 
0, and the other errors were PyO3's, prefixed with the argument's name (an 
`OverflowError` for a big int).
    
    The changes:
    - `proto_int::<T>` (`crates/pyspark-rs/src/stat_arguments.rs`) converts as 
upb does, and replaces dropna's `proto_int32`.
    - `limit`, `offset`, `tail`, `head`, `take`, `repartition`, 
`repartitionByRange`, `coalesce` and `repartitionById` 
(`crates/pyspark-rs/src/dataframe.rs`) now take the value as it is. Each runs 
PySpark's own checks first, in PySpark's order, then converts with the field's 
full name:
      - the type checks;
      - `not numPartitions > 0`, whose `VALUE_NOT_POSITIVE` shows the `str` of 
the value (`'False'`);
      - `CANNOT_BE_EMPTY`.
    - `head(n)` is `take(n)`, as in PySpark.
    - A `partitionIdCol` of `repartitionById` that is neither a Column nor a 
str raises PySpark's `NOT_EXPECTED_TYPE` of `col` (`F._to_col`). It used to be 
a custom `TypeError`.
    
    PySpark raises the proto errors when it sends the plan; this client builds 
the plan at the call, so it raises them there.
    
    Not in this PR, and noted for follow-ups: `bucketBy` (sent only when 
`num_buckets > 0` in PySpark), the bounds of 
`Window.rowsBetween`/`rangeBetween`, and `StorageLevel.replication`, which 
refuse a bool in PySpark too.
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0 with protobuf 7. A probe of 21 inputs over 12 cases 
against official `pyspark-client` 4.3.0 with protobuf 7.36.2 now matches on 
every line except `bucketBy`'s. Inputs include True, False, 1.5, "1", None, 
2**40, -(2**31)-1, 0, -1, `np.int64` and `np.True_`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. In the Python client, these methods refuse a bool count. They raise 
PySpark's errors for a count that is not an int or is out of range.
    
    ### How was this patch tested?
    
    - `test_counts_that_the_proto_refuses_are_refused_as_pyspark`, new: exact 
types and messages, the order of PySpark's checks, and the keyword forms.
    - `test_counts_are_sent_by_their_index_as_pyspark`, new: NumPy, 
int-subclass, `__index__` and int32-bound values are sent as their ints, and 
refused counts send nothing.
    - Both fail without the change.
    - The related offline tests (143) and the whole offline file pass, and so 
do the related e2e tests against a Spark 4.3.0 server.
    - `cargo build -p pyspark-rs --release`, `cargo fmt --all --check` and 
`ruff check`.
    
    ### 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 #571 from HyukjinKwon/SPARK-61542-proto-int-counts.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs      | 123 ++++++++++++++----------
 crates/pyspark-rs/src/stat_arguments.rs |  35 ++++---
 python/tests/test_dropin_offline.py     | 162 ++++++++++++++++++++++++++++++++
 3 files changed, 256 insertions(+), 64 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 036ea0a1..86283fc3 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -12,6 +12,7 @@ use crate::group::PyGroupedData;
 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::types::PyDataType;
 
@@ -370,18 +371,25 @@ fn unwrap_sequence(cols: Vec<Bound<'_, PyAny>>) -> 
PyResult<Vec<Bound<'_, PyAny>
     }
 }
 
-/// PySpark's `VALUE_NOT_POSITIVE` error of `numPartitions`, unless it is 
positive.
-fn positive_partitions(py: Python<'_>, num_partitions: i64) -> PyResult<i32> {
-    if num_partitions > 0 {
-        return Ok(i32::try_from(num_partitions)?);
+/// PySpark's check of the `numPartitions` of `repartition`, 
`repartitionByRange` and `coalesce`,
+/// `not numPartitions > 0`: `VALUE_NOT_POSITIVE`, or the `TypeError` of the 
comparison, as for
+/// None in `coalesce`. The count is converted after, as the proto's int32 
([`proto_int`]).
+fn positive_partitions(num_partitions: &Bound<'_, PyAny>) -> PyResult<()> {
+    if num_partitions.gt(0)? {
+        return Ok(());
     }
-    Err(crate::column::raise_pyspark(
-        py,
+    Err(not_positive_partitions(num_partitions)?)
+}
+
+/// PySpark's `VALUE_NOT_POSITIVE` error of `numPartitions`, of its `str`.
+fn not_positive_partitions(num_partitions: &Bound<'_, PyAny>) -> 
PyResult<PyErr> {
+    Ok(crate::column::raise_pyspark(
+        num_partitions.py(),
         "PySparkValueError",
         "VALUE_NOT_POSITIVE",
         &[
             ("arg_name", "numPartitions"),
-            ("arg_value", &num_partitions.to_string()),
+            ("arg_value", &num_partitions.str()?.to_cow()?),
         ],
     ))
 }
@@ -908,14 +916,18 @@ impl PyDataFrame {
         ))
     }
 
-    /// Limit the number of rows.
-    fn limit(&self, num: i32) -> PyDataFrame {
-        PyDataFrame::new(self.dataframe.limit(num))
+    /// Limit the number of rows, as PySpark's `limit`, which does not check 
`num`: its plan sets
+    /// `num` in the proto's int32, whose errors ([`proto_int`]) PySpark 
raises once it sends the
+    /// plan; this client builds the plan here, so it raises them here. The 
server checks the rest.
+    fn limit(&self, num: &Bound<'_, PyAny>) -> PyResult<PyDataFrame> {
+        let num = proto_int(num, "spark.connect.Limit.limit")?;
+        Ok(PyDataFrame::new(self.dataframe.limit(num)))
     }
 
-    /// Skip the first n rows.
-    fn offset(&self, num: i32) -> PyDataFrame {
-        PyDataFrame::new(self.dataframe.offset(num))
+    /// Skip the first `num` rows, as PySpark's `offset`, which sends `num` as 
`limit` does.
+    fn offset(&self, num: &Bound<'_, PyAny>) -> PyResult<PyDataFrame> {
+        let num = proto_int(num, "spark.connect.Offset.offset")?;
+        Ok(PyDataFrame::new(self.dataframe.offset(num)))
     }
 
     /// Remove duplicate rows.
@@ -1187,7 +1199,7 @@ impl PyDataFrame {
         // As PySpark's: a positive partition count and columns, or columns 
alone. The columns
         // are sorted ascending unless they are sort orders, by 
`repartition_by_range_opt`.
         let (num_partitions, cols) = if 
numPartitions.is_instance_of::<PyInt>() {
-            let n = positive_partitions(py, numPartitions.extract()?)?;
+            positive_partitions(&numPartitions)?;
             if cols.is_empty() {
                 return Err(crate::column::raise_pyspark(
                     py,
@@ -1196,7 +1208,7 @@ impl PyDataFrame {
                     &[("item", "cols")],
                 ));
             }
-            (Some(n), cols)
+            (Some(numPartitions), cols)
         } else if numPartitions.is_instance_of::<pyo3::types::PyString>()
             || numPartitions.extract::<PyRef<'_, PyColumn>>().is_ok()
         {
@@ -1216,6 +1228,11 @@ impl PyDataFrame {
             .into_iter()
             .map(|c| c.expression().clone())
             .collect();
+        // The count is the proto's int32 of the plan, which PySpark converts 
once it sends the
+        // plan, after the columns; this client builds the plan here, so it 
converts it here.
+        let num_partitions = num_partitions
+            .map(|n| proto_int(&n, 
"spark.connect.RepartitionByExpression.num_partitions"))
+            .transpose()?;
         Ok(PyDataFrame::new(
             self.dataframe
                 .repartition_by_range_opt(num_partitions, exprs)
@@ -1229,31 +1246,36 @@ impl PyDataFrame {
     #[allow(non_snake_case)]
     fn repartitionById(
         &self,
-        py: Python<'_>,
         numPartitions: &Bound<'_, PyAny>,
         partitionIdCol: &Bound<'_, PyAny>,
     ) -> PyResult<PyDataFrame> {
-        // As PySpark's: an int that is not a bool, and positive.
+        // As PySpark's: an int that is not a bool, and not `numPartitions <= 
0`.
         if !numPartitions.is_instance_of::<PyInt>()
             || numPartitions.is_instance_of::<pyo3::types::PyBool>()
         {
             return Err(not_expected_type(numPartitions, "numPartitions", 
"int"));
         }
-        let numPartitions = positive_partitions(py, numPartitions.extract()?)?;
-        // A `ColumnOrName`, as in pyspark: a string is a column name, not a 
literal.
+        if numPartitions.le(0)? {
+            return Err(not_positive_partitions(numPartitions)?);
+        }
+        // A `ColumnOrName`, as PySpark's `F._to_col`: a string is a column 
name, by `col`, of its
+        // origin, not a literal, and another value is NOT_EXPECTED_TYPE of 
`col`.
         let col = if let Ok(c) = partitionIdCol.extract::<Bound<'_, 
PyColumn>>() {
             c.borrow().column.clone()
-        } else if let Ok(name) = partitionIdCol.extract::<String>() {
-            // As PySpark's `F._to_col`, by `col`, of its origin.
+        } else if partitionIdCol.is_instance_of::<pyo3::types::PyString>() {
             let _origin = crate::origin::with_origin("col")?;
-            spark_connect::functions::col(&name)
+            spark_connect::functions::col(&partitionIdCol.extract::<String>()?)
         } else {
-            return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
-                "partitionIdCol should be a Column or a column name (str)",
-            ));
+            return Err(not_expected_type(partitionIdCol, "col", "Column or 
str"));
         };
+        // The count is the proto's int32 of the plan, converted after the 
column, as in
+        // `repartitionByRange`.
+        let num_partitions = proto_int(
+            numPartitions,
+            "spark.connect.RepartitionByExpression.num_partitions",
+        )?;
         Ok(PyDataFrame::new(
-            self.dataframe.repartition_by_id(numPartitions, col),
+            self.dataframe.repartition_by_id(num_partitions, col),
         ))
     }
 
@@ -1322,15 +1344,16 @@ impl PyDataFrame {
     #[pyo3(signature = (numPartitions, *cols))]
     fn repartition(
         &self,
-        py: Python<'_>,
         numPartitions: Bound<'_, PyAny>,
         cols: Vec<Bound<'_, PyAny>>,
     ) -> PyResult<PyDataFrame> {
         // As PySpark's: a positive partition count, or a partition column 
(str/Column), at
-        // the server's count (passed as 0 = unset).
+        // the server's count (passed as 0 = unset). The count is the proto's 
int32 of the plan,
+        // converted after the columns, as in `repartitionByRange`.
         if numPartitions.is_instance_of::<PyInt>() {
-            let n = positive_partitions(py, numPartitions.extract()?)?;
+            positive_partitions(&numPartitions)?;
             if cols.is_empty() {
+                let n = proto_int(&numPartitions, 
"spark.connect.Repartition.num_partitions")?;
                 return Ok(PyDataFrame::new(self.dataframe.repartition(n)));
             }
             // As PySpark's `_to_cols(cols)`, which does not unpack a list 
among them.
@@ -1338,6 +1361,10 @@ impl PyDataFrame {
                 .iter()
                 .map(|c| c.expression().clone())
                 .collect();
+            let n = proto_int(
+                &numPartitions,
+                "spark.connect.RepartitionByExpression.num_partitions",
+            )?;
             return Ok(PyDataFrame::new(
                 self.dataframe.repartition_by_expressions(n, exprs),
             ));
@@ -1362,9 +1389,11 @@ impl PyDataFrame {
         ))
     }
 
-    /// Coalesce.
-    fn coalesce(&self, py: Python<'_>, numPartitions: i64) -> 
PyResult<PyDataFrame> {
-        let num_partitions = positive_partitions(py, numPartitions)?;
+    /// Coalesce into `numPartitions` partitions, as PySpark's `coalesce`: any 
value that is
+    /// `> 0`, which is then the proto's int32 of the plan, as in 
`repartitionByRange`.
+    fn coalesce(&self, numPartitions: &Bound<'_, PyAny>) -> 
PyResult<PyDataFrame> {
+        positive_partitions(numPartitions)?;
+        let num_partitions = proto_int(numPartitions, 
"spark.connect.Repartition.num_partitions")?;
         Ok(PyDataFrame::new(self.dataframe.coalesce(num_partitions)))
     }
 
@@ -2529,29 +2558,21 @@ impl PyDataFrame {
         Ok(rows_to_py(py, &self.dataframe, row.as_slice(), 
schema.as_ref())?.pop())
     }
 
-    /// Alias for first.
+    /// The first row, or None, or with `n`, a list of the first `n` rows, as 
PySpark's `head`,
+    /// whose `head(n)` is `take(n)`.
     #[pyo3(signature = (n=None))]
-    fn head(&self, py: Python<'_>, n: Option<i32>) -> PyResult<Py<PyAny>> {
+    fn head(&self, py: Python<'_>, n: Option<&Bound<'_, PyAny>>) -> 
PyResult<Py<PyAny>> {
         use pyo3::IntoPyObjectExt;
         match n {
-            // head() -> the first Row (or None), matching reference pyspark.
             None => self.first(py)?.into_py_any(py),
-            // head(n) -> a list of the first n Rows.
-            Some(k) => {
-                let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
-                    self.dataframe
-                        .limit(k)
-                        .collect_with_schema()
-                        .map_err(Box::new)
-                })?;
-                rows_to_py(py, &self.dataframe, &rows, 
schema.as_ref())?.into_py_any(py)
-            }
+            Some(n) => self.take(py, n)?.into_py_any(py),
         }
     }
 
-    /// Get the first n rows, as PySpark's `DataFrame.take`, which is 
`limit(num).collect()`, so
-    /// the server checks `num`.
-    fn take(&self, py: Python<'_>, num: i32) -> PyResult<Vec<Py<PyAny>>> {
+    /// Get the first n rows, as PySpark's `DataFrame.take`, which is 
`limit(num).collect()`: `num`
+    /// is converted as `limit` converts it, and the server checks the rest.
+    fn take(&self, py: Python<'_>, num: &Bound<'_, PyAny>) -> 
PyResult<Vec<Py<PyAny>>> {
+        let num = proto_int(num, "spark.connect.Limit.limit")?;
         let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
             self.dataframe
                 .limit(num)
@@ -2571,8 +2592,10 @@ impl PyDataFrame {
         interruptible(py, &session, || self.dataframe.columns())
     }
 
-    /// Get the last `num` rows as a list of Rows (eager, like pyspark `tail`).
-    fn tail(&self, py: Python<'_>, num: i32) -> PyResult<Vec<Py<PyAny>>> {
+    /// Get the last `num` rows as a list of Rows (eager, like pyspark 
`tail`), of `num` as the
+    /// proto's int32 of the plan, converted as `limit` converts it.
+    fn tail(&self, py: Python<'_>, num: &Bound<'_, PyAny>) -> 
PyResult<Vec<Py<PyAny>>> {
+        let num = proto_int(num, "spark.connect.Tail.limit")?;
         let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
             self.dataframe
                 .tail(num)
diff --git a/crates/pyspark-rs/src/stat_arguments.rs 
b/crates/pyspark-rs/src/stat_arguments.rs
index 5533f55a..db94056d 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -84,7 +84,7 @@ pub(crate) fn dropna(
 }
 
 /// The `thresh` and the `subset` of `dropna`, checked as PySpark's. The 
`subset` is checked
-/// before the `thresh` is sent as a proto int, which [`proto_int32`] checks.
+/// before the `thresh` is sent as the proto's int32, which [`proto_int`] 
converts.
 fn dropna_thresh_and_subset(
     thresh: Option<&Bound<'_, PyAny>>,
     subset: Option<&Bound<'_, PyAny>>,
@@ -95,7 +95,9 @@ fn dropna_thresh_and_subset(
         Some(thresh) => return Err(not_expected_type(thresh, "thresh", "int")),
     };
     let columns = subset_columns(subset, "list, str or tuple")?;
-    let thresh = thresh.map(proto_int32).transpose()?;
+    let thresh = thresh
+        .map(|thresh| proto_int(thresh, "spark.connect.NADrop.min_non_nulls"))
+        .transpose()?;
     Ok((thresh, columns))
 }
 
@@ -108,19 +110,24 @@ pub(crate) fn bool_not_proto_int(field: &str) -> PyErr {
     ))
 }
 
-/// An int, the `thresh` of `dropna`, as the proto's int32. A bool, which is 
an int, is refused as
-/// the proto refuses it, `TypeError`, and an int out of the range of an int32 
is a `ValueError`.
-fn proto_int32(thresh: &Bound<'_, PyAny>) -> PyResult<i32> {
-    if thresh.is_instance_of::<pyo3::types::PyBool>() {
-        return Err(bool_not_proto_int("spark.connect.NADrop.min_non_nulls"));
-    }
-    match thresh.extract::<i32>() {
-        Ok(thresh) => Ok(thresh),
-        Err(_) => Err(pyo3::exceptions::PyValueError::new_err(format!(
-            "Value out of range: {}",
-            thresh.str()?
-        ))),
+/// A value that PySpark sets in the proto's int field `field`, the full name 
of the field, of the
+/// type `T` of the field (`i32` or `i64`), as protobuf's default (upb) 
backend converts it. A
+/// bool, which is an int, is refused, as [`bool_not_proto_int`] gives; any 
other value is the int
+/// of its `__index__`, so a float, a str or None raises the `TypeError` of 
`operator.index`, and a
+/// NumPy int is taken, but not a NumPy bool. An int beyond a long is the 
`ValueError` of that int,
+/// and one out of the range of `T`, the `ValueError` of the value itself, as 
upb shows them.
+pub(crate) fn proto_int<T: TryFrom<i64>>(value: &Bound<'_, PyAny>, field: 
&str) -> PyResult<T> {
+    if value.is_instance_of::<pyo3::types::PyBool>() {
+        return Err(bool_not_proto_int(field));
     }
+    // SAFETY: PyNumber_Index returns a new reference, or NULL with an 
exception set.
+    let index = unsafe {
+        Bound::from_owned_ptr_or_err(value.py(), 
pyo3::ffi::PyNumber_Index(value.as_ptr()))
+    }?;
+    let long: i64 = index
+        .extract()
+        .map_err(|_| crate::session::value_out_of_range(&index))?;
+    T::try_from(long).map_err(|_| crate::session::value_out_of_range(value))
 }
 
 /// `df.fillna(value, subset)` and `df.na.fill`, as PySpark's: `value` is a 
bool, an int, a
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 3d23550c..2ac7e3d4 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -4376,6 +4376,168 @@ def 
test_dropna_thresh_that_the_proto_refuses_is_refused_as_pyspark():
     assert isinstance(df.na.drop(thresh=-(2**31)), DataFrame)
 
 
+def test_counts_that_the_proto_refuses_are_refused_as_pyspark():
+    # As PySpark's limit, offset, tail, head, take, repartition, coalesce, 
repartitionByRange and
+    # repartitionById, whose plans set the count in a proto int32 after 
PySpark's own checks:
+    # protobuf's default (upb) backend refuses a bool, which is an int, since 
protobuf 7.34, takes
+    # any other value by its __index__, so a float, a str or None is the 
TypeError of
+    # operator.index, and refuses an int out of the range of the field with a 
ValueError, of the
+    # value itself, or of its int when that is beyond a long. PySpark raises 
these once it sends
+    # the plan; this client builds the plan at the call, so it raises them 
there.
+    import operator
+
+    from pyspark.errors import PySparkTypeError, PySparkValueError
+
+    class Shown(int):
+        def __str__(self):
+            return "shown"
+
+    def index_error(value):
+        with pytest.raises(TypeError) as error:
+            operator.index(value)
+        return str(error.value)
+
+    def refused(field):
+        return TypeError, f"Field spark.connect.{field}: Expected an int, got 
a boolean."
+
+    df = _offline_session().range(1)
+    for method, field in (
+        (df.limit, "Limit.limit"),
+        (df.offset, "Offset.offset"),
+        (df.tail, "Tail.limit"),
+        (df.head, "Limit.limit"),
+        (df.take, "Limit.limit"),
+    ):
+        for value, error_type, message in (
+            (True, *refused(field)),
+            (False, *refused(field)),
+            (1.5, TypeError, index_error(1.5)),
+            ("1", TypeError, index_error("1")),
+            (np.True_, TypeError, index_error(np.True_)),
+            (2**40, ValueError, "Value out of range: 1099511627776"),
+            (-(2**31) - 1, ValueError, "Value out of range: -2147483649"),
+            (np.int64(2**31), ValueError, "Value out of range: 2147483648"),
+            (Shown(2**40), ValueError, "Value out of range: shown"),
+            (Shown(2**70), ValueError, "Value out of range: 
1180591620717411303424"),
+        ):
+            with pytest.raises(error_type) as error:
+                method(value)
+            assert type(error.value) is error_type, (method, value)
+            assert str(error.value) == message, (method, value)
+    count_cases = [
+        (lambda: df.limit(None), TypeError, index_error(None)),
+        (lambda: df.take(None), TypeError, index_error(None)),
+        (lambda: df.limit(num=True), *refused("Limit.limit")),
+        (lambda: df.head(n=True), *refused("Limit.limit")),
+        (lambda: df.repartition(True), *refused("Repartition.num_partitions")),
+        (lambda: df.repartition(True, "id"), 
*refused("RepartitionByExpression.num_partitions")),
+        (lambda: df.coalesce(True), *refused("Repartition.num_partitions")),
+        (lambda: df.repartitionByRange(True, "id"),
+         *refused("RepartitionByExpression.num_partitions")),
+        (lambda: df.repartition(2**40), ValueError, "Value out of range: 
1099511627776"),
+        (lambda: df.repartition(2**31, "id"), ValueError, "Value out of range: 
2147483648"),
+        (lambda: df.coalesce(2**70), ValueError, "Value out of range: 
1180591620717411303424"),
+        (lambda: df.repartitionByRange(Shown(2**40), "id"), ValueError,
+         "Value out of range: shown"),
+        (lambda: df.repartitionById(2**40, "id"), ValueError, "Value out of 
range: 1099511627776"),
+        # coalesce compares any value with 0 first, so that the proto takes 
what passes.
+        (lambda: df.coalesce(1.5), TypeError, index_error(1.5)),
+        (lambda: df.coalesce(np.True_), TypeError, index_error(np.True_)),
+        (lambda: df.coalesce(None), TypeError,
+         "'>' not supported between instances of 'NoneType' and 'int'"),
+        (lambda: df.coalesce("1"), TypeError,
+         "'>' not supported between instances of 'str' and 'int'"),
+    ]
+    for call, error_type, message in count_cases:
+        with pytest.raises(error_type) as error:
+            call()
+        assert type(error.value) is error_type, message
+        assert str(error.value) == message
+
+    def not_positive(value):
+        return PySparkValueError, "VALUE_NOT_POSITIVE", {
+            "arg_name": "numPartitions", "arg_value": value}
+
+    def not_expected(arg_name, expected_type, arg_type):
+        return PySparkTypeError, "NOT_EXPECTED_TYPE", {
+            "arg_name": arg_name, "expected_type": expected_type, "arg_type": 
arg_type}
+
+    # PySpark's own checks come first, of the str of the count, and so do 
those of the columns.
+    pyspark_cases = [
+        (lambda: df.repartition(False), not_positive("False")),
+        (lambda: df.repartition(Shown(0), "id"), not_positive("shown")),
+        (lambda: df.coalesce(False), not_positive("False")),
+        (lambda: df.coalesce(np.False_), not_positive("False")),
+        (lambda: df.repartitionByRange(False, "id"), not_positive("False")),
+        (lambda: df.repartitionById(Shown(0), "id"), not_positive("shown")),
+        (lambda: df.repartitionByRange(True),
+         (PySparkValueError, "CANNOT_BE_EMPTY", {"item": "cols"})),
+        (lambda: df.repartition(np.int64(2)),
+         not_expected("numPartitions", "Column or str", "int64")),
+        (lambda: df.repartitionByRange(np.int64(2), "id"),
+         not_expected("numPartitions", "Column, int or str", "int64")),
+        (lambda: df.repartition(2**40, 1.5), not_expected("cols", "Column or 
str", "float")),
+        (lambda: df.repartitionByRange(True, 1.5),
+         not_expected("cols", "Column or str", "float")),
+        (lambda: df.repartitionById(2**40, 1.5), not_expected("col", "Column 
or str", "float")),
+    ]
+    for call, (error_type, condition, parameters) in pyspark_cases:
+        with pytest.raises(error_type) as error:
+            call()
+        assert error.value.getCondition() == condition
+        assert error.value.getMessageParameters() == parameters
+
+
+def test_counts_are_sent_by_their_index_as_pyspark(mock_connect):
+    # As protobuf's default (upb) backend takes the count of these plans, by 
its __index__: a
+    # NumPy int, an int of a subclass, or another object with __index__ is 
sent as its int, and so
+    # are the bounds of an int32, for the server to check. A count that it 
refuses sends nothing.
+    spark, service = mock_connect
+    df = spark.range(3)
+
+    class Index:
+        def __index__(self):
+            return 2
+
+    class Shown(int):
+        def __str__(self):
+            return "shown"
+
+    def sent(field, number):
+        # ExecutePlanRequest.plan=3, Plan.root=1; Relation.limit=8, offset=13, 
repartition=17,
+        # tail=22 and repartition_by_expression=27, of their counts.
+        return _sent_relation(service.execute_requests[-1], field, 
execute=True)[number]
+
+    for run, field, number, count in (
+        (lambda: df.limit(np.int64(2)).collect(), 8, 2, 2),
+        (lambda: df.limit(Index()).collect(), 8, 2, 2),
+        (lambda: df.limit(2**31 - 1).collect(), 8, 2, 2**31 - 1),
+        (lambda: df.limit(-(2**31)).collect(), 8, 2, 2**64 - 2**31),
+        (lambda: df.offset(np.int32(1)).collect(), 13, 2, 1),
+        (lambda: df.tail(np.int64(2)), 22, 2, 2),
+        (lambda: df.take(Index()), 8, 2, 2),
+        (lambda: df.head(Shown(2)), 8, 2, 2),
+        (lambda: df.coalesce(np.int64(2)).collect(), 17, 2, 2),
+        (lambda: df.repartition(Shown(2)).collect(), 17, 2, 2),
+        (lambda: df.repartition(Shown(2), "id").collect(), 27, 3, 2),
+        (lambda: df.repartitionByRange(Shown(2), "id").collect(), 27, 3, 2),
+        (lambda: df.repartitionById(Shown(2), "id").collect(), 27, 3, 2),
+    ):
+        run()
+        assert sent(field, number) == [count]
+    before = len(service.execute_requests)
+    for run, error_type in (
+        (lambda: df.take(True), TypeError),
+        (lambda: df.head(False), TypeError),
+        (lambda: df.tail(2**40), ValueError),
+        (lambda: df.limit(True).collect(), TypeError),
+        (lambda: df.coalesce(True).collect(), TypeError),
+    ):
+        with pytest.raises(error_type):
+            run()
+    assert len(service.execute_requests) == before
+
+
 def test_avro_protobuf_partitioning_submodules():
     # The official import paths resolve (the implementations live in
     # pyspark.sql.functions and are re-exported here).


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

Reply via email to