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 56182e58 [SPARK-61321][CONNECT][PYTHON] Send the count of
DataFrame.take to the server as limit does, and pass the receiver to transform
as PySpark does
56182e58 is described below
commit 56182e58d6bc3b3978456cd1d922133a98653c9d
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 09:41:41 2026 +0900
[SPARK-61321][CONNECT][PYTHON] Send the count of DataFrame.take to the
server as limit does, and pass the receiver to transform as PySpark does
### What changes were proposed in this pull request?
[SPARK-61321](https://issues.apache.org/jira/browse/SPARK-61321): Send the
count of `DataFrame.take` to the server as `limit` does, and pass the receiver
to `DataFrame.transform` as PySpark does.
- `DataFrame.take(num)` takes `num` as an int, as `head` and `limit` do,
and runs `limit(num).collect()`, as PySpark's `take` does. The server checks
the count: `take(-1)` raises `AnalysisException`
`INVALID_LIMIT_LIKE_EXPRESSION.IS_NEGATIVE`, as PySpark does. Before, the
drop-in rejected a negative count while converting the argument, with
`OverflowError: can't convert negative int to unsigned`.
- `DataFrame.transform(func, *args, **kwargs)` calls `func` with the
DataFrame it is called on, as PySpark's does, so a subclass of
`pyspark.sql.connect.dataframe.DataFrame` keeps its methods in the callback and
`transform(lambda d: d)` returns the subclass instance. Before, the callback
got a new base-class frame of the same plan.
Checked and unchanged: `cache`, `persist` and `unpersist` already return
the receiver. `pandas_api`, `foreach` and `foreachPartition` already pass the
bound receiver. `checkpoint` and `localCheckpoint` return a new base-class
frame, as PySpark's Connect client does.
### Why are the changes needed?
- `spark.range(3).take(-1)` raised `OverflowError`, while `head(-1)` and
`limit(-1)` raised the server's `AnalysisException`, as PySpark does.
- `MyDF(plan, session).transform(lambda d: d.twice())` raised `'Column'
object is not callable`, because the callback's argument was a base-class frame
without `twice`. PySpark passes the `MyDF` instance and the call works.
### Does this PR introduce _any_ user-facing change?
Yes. `take` of a negative count raises the server's `AnalysisException`,
and `transform` passes the DataFrame it is called on, a subclass instance
included. Nothing else changes.
### How was this patch tested?
- Offline test `test_transform_passes_the_receiver_itself_as_pyspark` in
`python/tests/test_dropin_offline.py` (before
`test_join_on_lists_join_on_their_conjunction_or_names_as_pyspark`): with a
subclass of `pyspark.sql.connect.dataframe.DataFrame`, the callback gets the
receiver itself, `transform(lambda d: d)` returns the subclass instance, and
`d.twice()` in the callback sends a Project plan. With PySpark 4.3.0 the same
statements give `MyDF` and the `twice()` rows, `[(0,), (2,), (4,)]`.
- Offline test
`test_take_sends_its_count_as_a_limit_for_the_server_to_check` in
`python/tests/test_dropin_offline.py` (same place): `take(2)` and `take(-1)`
send `Relation.limit` with the count, as an int32, which the server checks.
- Live test
`test_take_of_a_negative_count_raises_the_server_error_as_pyspark` in
`python/tests/test_dropin_e2e.py` (before
`test_collected_rows_behave_as_pyspark_rows`): `take(-1)` raises
`AnalysisException` with the condition
`INVALID_LIMIT_LIKE_EXPRESSION.IS_NEGATIVE`, and `take(2)` returns two rows.
PySpark 4.3.0 on the same server gives the same condition.
- Both offline tests and the live test fail with the previous `take` and
`transform` (checked by reverting the change temporarily).
- The build of all tests, the offline Python suites (2929 passed, 8
skipped) with the rebuilt extension, the new offline tests also under pytest
9.2, and the live drop-in tests `-k "transform or take"` (24 passed) against a
local Spark 4.3.0 server. Clippy reports no new diagnostics 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 #442 from HyukjinKwon/SPARK-61321-take-and-transform.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 15 +++++++-------
python/tests/test_dropin_e2e.py | 7 +++++++
python/tests/test_dropin_offline.py | 40 +++++++++++++++++++++++++++++++++++++
3 files changed, 55 insertions(+), 7 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 4799811d..e7532f8e 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -2039,14 +2039,14 @@ impl PyDataFrame {
/// `df.transform(func, *args, **kwargs)` == `func(df, *args, **kwargs)`.
#[pyo3(signature = (func, *args, **kwargs))]
fn transform(
- &self,
- py: Python<'_>,
+ slf: &Bound<'_, Self>,
func: &Bound<'_, PyAny>,
args: &Bound<'_, PyTuple>,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<Py<PyAny>> {
- let this = Py::new(py, PyDataFrame::new(self.dataframe.clone()))?;
- let mut call_args: Vec<Py<PyAny>> = vec![this.into_any()];
+ // As PySpark's, which passes `self`: a subclass of DataFrame keeps
its methods and type.
+ let py = slf.py();
+ let mut call_args: Vec<Py<PyAny>> =
vec![slf.clone().into_any().unbind()];
for a in args.iter() {
call_args.push(a.unbind());
}
@@ -2438,10 +2438,11 @@ impl PyDataFrame {
}
}
- /// Get the first n rows.
- fn take(&self, py: Python<'_>, num: usize) -> PyResult<Vec<Py<PyAny>>> {
+ /// 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>>> {
let (rows, schema) = py
- .detach(|| self.dataframe.take_with_schema(num))
+ .detach(|| self.dataframe.limit(num).collect_with_schema())
.to_pyerr()?;
rows_to_py(py, &self.dataframe, &rows, schema.as_ref())
}
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 17f527ba..e59a7b35 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2544,6 +2544,13 @@ def
test_session_builders_keep_the_options_set_on_them_as_pyspark(session):
session.conf.unset("spark.connect.rust.test.builder")
+def test_take_of_a_negative_count_raises_the_server_error_as_pyspark(session):
+ # As PySpark's take, which is limit(num).collect(): the server rejects a
negative count with
+ # INVALID_LIMIT_LIKE_EXPRESSION.IS_NEGATIVE, as for head and limit.
+ with pytest.raises(AnalysisException) as error:
+ session.range(3).take(-1)
+ assert error.value.getCondition() ==
"INVALID_LIMIT_LIKE_EXPRESSION.IS_NEGATIVE"
+ assert len(session.range(3).take(2)) == 2
def test_collected_rows_behave_as_pyspark_rows(session):
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index ed520ade..c9ee5676 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -16033,6 +16033,46 @@ def
test_join_types_are_sent_as_pyspark_join_types(mock_connect, how, join_type)
assert parse_message(parse_message(plan)[5][0])[4] == [join_type]
+def test_transform_passes_the_receiver_itself_as_pyspark(mock_connect):
+ # As PySpark's transform, which calls func with self: a DataFrame subclass
keeps its methods
+ # in the callback, and the callback gets the receiver itself, not a plain
DataFrame.
+ from pyspark.sql import functions as F
+ from pyspark.sql.connect.dataframe import DataFrame
+
+ spark, service = mock_connect
+
+ class MyDF(DataFrame):
+ def twice(self):
+ return self.select((F.col("id") * 2).alias("x"))
+
+ frame = MyDF(spark.range(3)._plan, spark)
+ seen = []
+ assert frame.transform(lambda d: seen.append(d) or d) is frame
+ assert seen[0] is frame
+ assert type(frame.transform(lambda d: d)) is MyDF
+ # ExecutePlanRequest.plan=3, Plan.root=1, Relation.project=3: the
callback's twice() is a Project.
+ frame.transform(lambda d: d.twice()).collect()
+ plan =
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+ assert 3 in parse_message(plan)
+
+
+def test_take_sends_its_count_as_a_limit_for_the_server_to_check(mock_connect):
+ # As PySpark's take, which is limit(num).collect(): a negative count is
sent as the Limit
+ # of the plan, and the server raises its AnalysisException, not an
overflow in the drop-in.
+ spark, service = mock_connect
+
+ def sent_limit():
+ # ExecutePlanRequest.plan=3, Plan.root=1, Relation.limit=8,
Limit.limit=2 (an int32, a
+ # negative one as its ten-byte varint).
+ plan =
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+ return parse_message(parse_message(plan)[8][0])[2][0]
+
+ spark.range(3).take(2)
+ assert sent_limit() == 2
+ spark.range(3).take(-1)
+ assert sent_limit() == 2**64 - 1
+
+
def
test_join_on_lists_join_on_their_conjunction_or_names_as_pyspark(mock_connect):
# As PySpark's plan.Join: a list of conditions joins on their conjunction,
a list of names
# is a using join, and an empty list is no condition at all.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]