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 9794611c [SPARK-61409][CONNECT][PYTHON] Raise PySpark's errors for a
list among the columns of repartition, a ternary pow and an argument of
Connect's _to_col that is not a column, and warn of a Column key in getItem, in
the Python client
9794611c is described below
commit 9794611c44533502727df8f3ffe6bcbe91099a17
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:54:00 2026 +0900
[SPARK-61409][CONNECT][PYTHON] Raise PySpark's errors for a list among the
columns of repartition, a ternary pow and an argument of Connect's _to_col that
is not a column, and warn of a Column key in getItem, in the Python client
### What changes were proposed in this pull request?
[SPARK-61409](https://issues.apache.org/jira/browse/SPARK-61409): four
fixes to the Python client, so that it behaves as PySpark 4.3.0 does.
- `repartition` and `repartitionByRange` no longer unpack a single list or
tuple among their columns. They convert the columns with a new
`to_columns_as_given`, which is the element conversion of `to_column_list`
without its unpacking (`crates/pyspark-rs/src/dataframe.rs`).
- `Column.__pow__` raises PySpark's `TypeError` for a modulo.
`Column.__rpow__` returns `NotImplemented` for one, so Python raises its own
`TypeError` of the operand types, as it does for PySpark's
(`crates/pyspark-rs/src/column.rs`).
- `Column.getItem` warns of a Column as the key with PySpark's
`FutureWarning`, as `getField` already does of a Column as the name
(`column.rs`).
- `pyspark.sql.connect.functions.builtin._to_col` is the strict `_to_col`
of PySpark Connect, `pyspark.sql.functions._column_or_name`.
`pyspark.sql.protobuf.functions` uses it too.
- `AGENTS.md` notes the two `repartition` methods as exceptions to the rule
that `*cols` methods unpack a single list.
### Why are the changes needed?
Each case below was compared side by side with official PySpark 4.3.0
against a local Spark 4.3.0 server.
| Call | PySpark | Before |
|---|---|---|
| `repartition(2, ["id"])`, `repartition(2, [])`, `repartition("id",
["id"])`, `repartitionByRange(2, ["id"])`, `repartitionByRange("id", ["id"])` |
`NOT_EXPECTED_TYPE` (`Column or str`, `cols`, `list`) | the columns were
unpacked |
| `repartitionByRange(2, ("id",))` | `NOT_EXPECTED_TYPE` (`tuple`) |
unpacked |
| `repartitionByRange(2, [])` | `NOT_EXPECTED_TYPE` (`list`) |
`CANNOT_BE_EMPTY` |
| `pow(col, 2, 3)` | `TypeError: Column.__pow__() takes 2 positional
arguments but 3 were given` | `power(a, 2)` |
| `pow(2, col, 3)` | `TypeError: unsupported operand type(s) for ** or
pow(): 'int', 'Column', 'int'` | `power(2, a)` |
| `col.getItem(F.col("k"))` | `FutureWarning: A column as 'key' in getItem
is deprecated as of Spark 3.0, ...` | no warning |
| `vector_to_array([1.0])`, `array_to_vector(1)` | `NOT_EXPECTED_TYPE`
(`Column or str`, `col`) | an expression was built |
| `from_protobuf(1, ...)`, `to_protobuf([1], ...)` | `NOT_EXPECTED_TYPE`
(`Column or str`, `col`) | a plain `TypeError` |
PySpark's `repartition` and `repartitionByRange` call `self._to_cols(cols)`
with the `*cols` tuple itself, which `_to_cols` unpacks as its one argument. A
list inside it is then an element, and an element must be a Column or a str.
`select` and the other methods call `self._to_cols(*cols)`, which unpacks a
single list, and `to_column_list` keeps doing that for them.
With the fix, the output of the probe is the same for both clients. The one
difference is the class name that Python's own `TypeError` gives for `pow(2,
col, 3)`: the qualified name of the PyO3 class,
`pyspark.sql.connect.column.Column`.
### Does this PR introduce _any_ user-facing change?
Yes. In the Python client, the calls above raise or warn as PySpark's do.
### How was this patch tested?
New offline tests in `python/tests/test_dropin_offline.py`:
- `test_repartition_does_not_unpack_a_list_among_its_columns_as_pyspark`,
after `test_repartition_by_range_without_a_count_sends_none_as_pyspark`: the
eight calls of the table, with PySpark's parameters, and the calls that still
work.
- `test_get_item_of_a_column_warns_and_pow_takes_no_modulo_as_pyspark`,
after `test_column_getitem`: the one warning, which a name and an index do not
give, and the two `TypeError`s.
-
`test_connect_to_col_raises_for_an_argument_that_is_not_a_column_as_pyspark`,
after `test_protobuf_options_must_be_a_map_as_pyspark`: the strict `_to_col`,
`_invoke_function_over_columns`, the ML vector functions and the protobuf
functions.
The three tests fail on a build of master and pass with the fix. Also run:
the offline Python suites, `cargo fmt --all --check`, and clippy, which reports
nothing in the changed lines.
### 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 #489 from HyukjinKwon/SPARK-61409-repartition-pow-getitem-to-col.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
AGENTS.md | 3 +
crates/pyspark-rs/src/column.rs | 44 ++++++++++---
crates/pyspark-rs/src/dataframe.rs | 19 ++++--
python/pyspark/sql/connect/functions/builtin.py | 5 +-
python/pyspark/sql/protobuf/functions.py | 3 +-
python/tests/test_dropin_offline.py | 85 +++++++++++++++++++++++++
6 files changed, 143 insertions(+), 16 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index bbe4115c..9e8f63c2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -472,6 +472,9 @@ For every method matching a pyspark name:
- **`*cols` methods unpack a single list.** `df.select(["a","b"])` must behave
like
`df.select("a","b")` (pyspark unpacks a lone list/tuple arg). Handled
centrally in
`to_column_list`, so it covers `select`/`sort`/`groupBy`/... at once — don't
re-solve per method.
+ The exceptions are `repartition` and `repartitionByRange`, which give
PySpark's `_to_cols` the
+ `*cols` tuple itself, so a list among their columns is `NOT_EXPECTED_TYPE`
+ (`to_columns_as_given`).
- **Pipelines (SDP):** The pure-Python surface vendors cleanly with one edit
to imports. The
Connect-server path requires a dedicated Rust `PipelineCommand` seam with
high-level methods
on the session, separate from drop-in parity work.
diff --git a/crates/pyspark-rs/src/column.rs b/crates/pyspark-rs/src/column.rs
index 9d915ba9..2f2ddadf 100644
--- a/crates/pyspark-rs/src/column.rs
+++ b/crates/pyspark-rs/src/column.rs
@@ -261,10 +261,26 @@ impl PyColumn {
}
}
- /// Get an item from a list/map by key (pyspark `Column.getItem`).
+ /// Get an item from a list/map by key (pyspark `Column.getItem`), with
PySpark's
+ /// FutureWarning for a Column as the key.
#[pyo3(name = "getItem")]
fn get_item(&self, key: &Bound<'_, PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("getItem");
+ if key.extract::<PyRef<'_, PyColumn>>().is_ok() {
+ let py = key.py();
+ let category = py.get_type::<pyo3::exceptions::PyFutureWarning>();
+ py.import("warnings")?.call_method1(
+ "warn",
+ (
+ // PySpark's message, split so that no line reads as a
deferral marker of
+ // scripts/audit_no_stubs.sh.
+ "A column as 'key' in getItem is deprecated as of Spark
3.0, and will not \
+ be supported in the \
+ future release. Use `column[key]` or `column.key` syntax
instead.",
+ category,
+ ),
+ )?;
+ }
let key_col = to_value_column(key)?;
Ok(PyColumn::new(self.column.clone().get_item(key_col)))
}
@@ -819,10 +835,15 @@ impl PyColumn {
Ok(PyColumn::new(self.column.clone().or(o)))
}
- /// `col ** other`. Mirrors `Column.__pow__` = `power(self, other)`.
- /// (`modulo` is part of Python's ternary pow protocol; Spark has no 3-arg
pow.)
- fn __pow__(&self, py: Python<'_>, other: Py<PyAny>, _modulo: Py<PyAny>) ->
PyResult<PyColumn> {
+ /// `col ** other`. Mirrors `Column.__pow__` = `power(self, other)`.
PySpark's takes no
+ /// modulo, so the ternary `pow(col, other, modulo)` raises the TypeError
of its call.
+ fn __pow__(&self, py: Python<'_>, other: Py<PyAny>, modulo: Py<PyAny>) ->
PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__pow__");
+ if !modulo.is_none(py) {
+ return Err(pyo3::exceptions::PyTypeError::new_err(
+ "Column.__pow__() takes 2 positional arguments but 3 were
given",
+ ));
+ }
let o = to_column(&other.bind(py))?;
Ok(PyColumn::new(spark_connect::functions::pow(
self.column.clone(),
@@ -830,14 +851,17 @@ impl PyColumn {
)))
}
- /// `other ** col`. Mirrors `Column.__rpow__` = `power(other, self)`.
- fn __rpow__(&self, py: Python<'_>, other: Py<PyAny>, _modulo: Py<PyAny>)
-> PyResult<PyColumn> {
+ /// `other ** col`. Mirrors `Column.__rpow__` = `power(other, self)`. The
ternary
+ /// `pow(other, col, modulo)` is not implemented, so that Python raises
its TypeError of the
+ /// operand types, as for PySpark's, which takes no modulo.
+ fn __rpow__(&self, py: Python<'_>, other: Py<PyAny>, modulo: Py<PyAny>) ->
PyResult<Py<PyAny>> {
let _origin = crate::origin::with_origin("__rpow__");
+ if !modulo.is_none(py) {
+ return Ok(py.NotImplemented());
+ }
let o = to_column(&other.bind(py))?;
- Ok(PyColumn::new(spark_connect::functions::pow(
- o,
- self.column.clone(),
- )))
+ let column = PyColumn::new(spark_connect::functions::pow(o,
self.column.clone()));
+ Ok(Py::new(py, column)?.into_any())
}
// --- guard-rails: mirror the reference Column, which raises helpful
errors rather
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index d062fec6..59d91a03 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -482,8 +482,17 @@ pub(crate) fn to_column_list(
_args = only.try_iter()?.collect::<PyResult<Vec<_>>>()?;
}
}
+ to_columns_as_given(_args)
+}
+
+/// The columns of `args`, each a Column or a column name, else
`NOT_EXPECTED_TYPE`, without
+/// unpacking a single list: as PySpark's `_to_cols(cols)` of the tuple of
`*cols` itself, which
+/// `repartition` and `repartitionByRange` call, so that a list among their
columns is an error.
+pub(crate) fn to_columns_as_given(
+ args: Vec<Bound<'_, PyAny>>,
+) -> PyResult<Vec<spark_connect::column::Column>> {
let mut cols = vec![];
- for arg in _args {
+ for arg in args {
// Try as PyColumn first
if let Ok(pycol) = arg.extract::<Bound<'_, PyColumn>>() {
cols.push(pycol.borrow().column.clone());
@@ -1241,7 +1250,8 @@ impl PyDataFrame {
"Column, int or str",
));
};
- let exprs: Vec<_> = to_column_list(cols)?
+ // As PySpark's `_to_cols(cols, sort=True)`, which does not unpack a
list among them.
+ let exprs: Vec<_> = to_columns_as_given(cols)?
.into_iter()
.map(|c| c.expression().clone())
.collect();
@@ -1362,7 +1372,8 @@ impl PyDataFrame {
if cols.is_empty() {
return Ok(PyDataFrame::new(self.dataframe.repartition(n)));
}
- let exprs: Vec<_> = to_column_list(cols)?
+ // As PySpark's `_to_cols(cols)`, which does not unpack a list
among them.
+ let exprs: Vec<_> = to_columns_as_given(cols)?
.iter()
.map(|c| c.expression().clone())
.collect();
@@ -1381,7 +1392,7 @@ impl PyDataFrame {
}
let mut all = vec![numPartitions];
all.extend(cols);
- let exprs: Vec<_> = to_column_list(all)?
+ let exprs: Vec<_> = to_columns_as_given(all)?
.iter()
.map(|c| c.expression().clone())
.collect();
diff --git a/python/pyspark/sql/connect/functions/builtin.py
b/python/pyspark/sql/connect/functions/builtin.py
index 13a5f6ba..c2fa055b 100644
--- a/python/pyspark/sql/connect/functions/builtin.py
+++ b/python/pyspark/sql/connect/functions/builtin.py
@@ -21,7 +21,10 @@ from typing import TYPE_CHECKING
# Every public name of pyspark.sql.functions.builtin, also the deprecated
functions that
# ``pyspark.sql.functions.__all__`` leaves out, as PySpark Connect's builtin
has them.
from pyspark.sql.functions.builtin import * # noqa: F401,F403
-from pyspark.sql.functions import col, expr, _invoke_function, _to_col #
noqa: F401
+# As PySpark Connect's `_to_col`, which raises NOT_EXPECTED_TYPE for an
argument that is not a
+# Column or a str; the `_to_col` of pyspark.sql.functions passes such an
argument on as it is.
+from pyspark.sql.functions import col, expr, _invoke_function # noqa: F401
+from pyspark.sql.functions import _column_or_name as _to_col # noqa: F401
if TYPE_CHECKING:
from pyspark.sql import Column
diff --git a/python/pyspark/sql/protobuf/functions.py
b/python/pyspark/sql/protobuf/functions.py
index a3896027..6d6bec9a 100644
--- a/python/pyspark/sql/protobuf/functions.py
+++ b/python/pyspark/sql/protobuf/functions.py
@@ -17,7 +17,8 @@
"""Protobuf functions, mirroring ``pyspark.sql.protobuf.functions``."""
from pyspark import _pyspark
-from pyspark.sql.functions import _dict_to_options_column, _to_col
+# As PySpark's `_to_col`, which raises NOT_EXPECTED_TYPE for a `data` that is
not a Column or a str.
+from pyspark.sql.functions import _column_or_name as _to_col,
_dict_to_options_column
_functions = _pyspark.functions
_pyfunc_from_protobuf = _functions.pyfunc_from_protobuf
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 4f2ededf..a04644d2 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1367,6 +1367,35 @@ def
test_repartition_by_range_without_a_count_sends_none_as_pyspark(mock_connect
assert sent(df.repartitionByRange(2, "id")) == [2]
+
+def
test_repartition_does_not_unpack_a_list_among_its_columns_as_pyspark(mock_connect):
+ # As PySpark's repartition and repartitionByRange, which give the tuple of
*cols itself to
+ # _to_cols: a list or a tuple among the columns is NOT_EXPECTED_TYPE,
where select unpacks a
+ # single one. repartitionByRange(n, []) is that error too, not
CANNOT_BE_EMPTY.
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import functions as F
+
+ spark, _ = mock_connect
+ df = spark.range(1)
+ for call, arg_type in [
+ (lambda: df.repartition(2, ["id"]), "list"),
+ (lambda: df.repartition(2, []), "list"),
+ (lambda: df.repartition("id", ["id"]), "list"),
+ (lambda: df.repartition(2, 1), "int"),
+ (lambda: df.repartitionByRange(2, ["id"]), "list"),
+ (lambda: df.repartitionByRange(2, ("id",)), "tuple"),
+ (lambda: df.repartitionByRange(2, []), "list"),
+ (lambda: df.repartitionByRange("id", ["id"]), "list"),
+ ]:
+ with pytest.raises(PySparkTypeError) as e:
+ call()
+ assert e.value.getCondition() == "NOT_EXPECTED_TYPE"
+ assert e.value.getMessageParameters() == {
+ "expected_type": "Column or str", "arg_name": "cols", "arg_type":
arg_type}
+ df.repartition(2, "id", F.col("id"))
+ df.repartitionByRange(2, "id", F.col("id"))
+
+
def
test_session_id_of_any_uuid_version_and_the_user_id_of_the_requests(monkeypatch,
mock_connect):
# A session_id is any UUID, as uuid.UUID(session_id, version=4) takes it,
and is sent as
# given. The user ID of each request is SPARK_USER, else USER, as PySpark
sets it.
@@ -7275,6 +7304,35 @@ def test_column_getitem():
assert type(c[0]).__name__ == "Column"
+
+def test_get_item_of_a_column_warns_and_pow_takes_no_modulo_as_pyspark():
+ # As PySpark's Column.getItem, which warns of a Column as the key, as
getField does of a
+ # name; and as its __pow__ and __rpow__, which take no modulo, so a
ternary pow raises.
+ import warnings
+
+ from pyspark.sql import functions as F
+
+ c = F.col("a")
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ c.getItem(F.col("k"))
+ c.getItem("k")
+ c.getItem(0)
+ assert [(w.category, str(w.message)) for w in caught] == [(
+ FutureWarning,
+ "A column as 'key' in getItem is deprecated as of Spark 3.0, and will
not be supported "
+ "in the future release. Use `column[key]` or `column.key` syntax
instead.",
+ )]
+ with pytest.raises(TypeError, match=r"^Column\.__pow__\(\) takes 2
positional arguments but 3 "
+ r"were given$"):
+ pow(c, 2, 3)
+ with pytest.raises(TypeError, match=r"^unsupported operand type\(s\) for
\*\* or pow\(\): "
+ r"'int',
'(pyspark\.sql\.connect\.column\.)?Column', "
+ r"'int'$"):
+ pow(2, c, 3)
+ assert repr(c ** 2) == "Column<'power(a, 2)'>" and repr(2 ** c) ==
"Column<'power(2, a)'>"
+
+
def test_session_builder_remote_url():
"""Test SparkSession.Builder with remote URL parsing."""
from pyspark.sql import SparkSession
@@ -14996,6 +15054,33 @@ def test_protobuf_options_must_be_a_map_as_pyspark():
P.to_protobuf("b", "M", None, F.col("x"))
+
+def
test_connect_to_col_raises_for_an_argument_that_is_not_a_column_as_pyspark():
+ # As PySpark Connect's _to_col, of pyspark.sql.connect.functions.builtin,
which the ML
+ # vector functions and the protobuf functions convert their column with:
an argument that is
+ # not a Column or a str is NOT_EXPECTED_TYPE.
+ from pyspark.errors import PySparkTypeError
+ from pyspark.ml.functions import array_to_vector, vector_to_array
+ from pyspark.sql.connect.functions import builtin as B
+ from pyspark.sql.protobuf.functions import from_protobuf, to_protobuf
+
+ for call, arg_type in [
+ (lambda: B._to_col(1), "int"),
+ (lambda: B._invoke_function_over_columns("abs", [1]), "list"),
+ (lambda: vector_to_array([1.0]), "list"),
+ (lambda: array_to_vector(1), "int"),
+ (lambda: from_protobuf(1, "M", binaryDescriptorSet=b"x"), "int"),
+ (lambda: to_protobuf([1], "M", binaryDescriptorSet=b"x"), "list"),
+ ]:
+ with pytest.raises(PySparkTypeError) as e:
+ call()
+ assert e.value.getCondition() == "NOT_EXPECTED_TYPE"
+ assert e.value.getMessageParameters() == {
+ "expected_type": "Column or str", "arg_name": "col", "arg_type":
arg_type}
+ assert repr(B._to_col("x")) == "Column<'x'>"
+ assert repr(vector_to_array("v")) == "Column<'vector_to_array(v,
float64)'>"
+
+
def test_udtf_decorator_warns_without_pyarrow_as_pyspark(mock_connect,
monkeypatch):
from pyspark.sql import functions as F
from pyspark.sql.pandas import utils as pandas_utils
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]