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 77055979 [SPARK-61413][CONNECT][PYTHON] Return a generator from
DataFrame.toLocalIterator in the Python client, as PySpark does
77055979 is described below
commit 77055979e545430b0bbe66ce19dcf9706bf8c4ba
Author: Timothy Meehan <[email protected]>
AuthorDate: Thu Nov 12 08:31:07 2026 +0900
[SPARK-61413][CONNECT][PYTHON] Return a generator from
DataFrame.toLocalIterator in the Python client, as PySpark does
### What changes were proposed in this pull request?
[SPARK-61413](https://issues.apache.org/jira/browse/SPARK-61413): make
`toLocalIterator` of the Python client return a generator, as PySpark does.
`DataFrame.toLocalIterator` of the Python client returns a generator, as
PySpark's generator function does, instead of the `LocalRowIterator` object.
The generator is a small Python function in `pyspark/sql/connect/dataframe.py`
that `yield from`s the Rust row iterator, which stays lazy: the query is sent
with the first `next()`. A `finally` closes the row iterator, so a close, a
throw, an error and the end of the generator each end the execution at once.
The error of a progress handler's done call for an iteration dropped before
its end goes to `sys.unraisablehook` with the object `types.GeneratorType`
(`crates/pyspark-rs/src/progress.rs`), the type of what `toLocalIterator`
returns, as PySpark reports its generator; it was the `LocalRowIterator` class.
### Why are the changes needed?
In PySpark, `isinstance(df.toLocalIterator(), types.GeneratorType)` and
`inspect.isgenerator` are `True`, and the result has `send()`, `throw()`,
`gi_frame` and `gi_running`. With the Rust object they were `False`, and
`throw()`, `send()` and the others raised `AttributeError`. Since SPARK-61160
`close()` already ended the execution as a generator's does; the generator
keeps that, and also ends the execution on `throw()`, which the row iterator,
having no `throw`, would leave open unt [...]
### Does this PR introduce _any_ user-facing change?
Yes, the Python client: `toLocalIterator()` returns a generator with the
name `toLocalIterator`, so code that checks for a generator or uses its methods
works as in PySpark. The rows, the error types and the lazy start are
unchanged; a traceback through the generator has one more frame, and a `next()`
while another thread runs it raises `ValueError`, as PySpark's generator does.
### How was this patch tested?
- `test_to_local_iterator_is_a_generator_as_pyspark` (offline, fails
without the fix): the type, the name and the state, and no request sent before
the first row.
- `test_to_local_iterator_ending_releases_the_execution_as_pyspark`
(offline): after one row, a `close()` and a `throw()` (with the exception kept)
each send ReleaseExecute at once. The `throw()` case fails without the
`finally`.
- `test_local_iterator_is_a_generator_as_pyspark` (live): the rows, the
state after the last row, `throw()` and `close()` in the middle.
-
`test_a_dropped_local_iterator_hands_the_done_error_to_unraisablehook_with_an_object`
(offline, existing) now sees the generator type, the type of the dropped
iterator.
- `cargo test -p apache-spark-connect --release --lib` (599 passed) and `-p
apache-spark-connect-core`, `--no-run` with and without `wasm-udf`, `cargo fmt
--all --check`, `ruff check`, `cargo clippy` (nothing on the changed lines).
- The offline Python suites (3117 passed, 8 skipped) and the live ones (282
passed, 1 skipped) against an OSS Spark 4.3.0 Connect server.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5 and Claude Sonnet 5.5
This pull request and its description were written by Isaac.
Closes #519 from tdcmeehan/SPARK-61413-local-iterator-generator.
Authored-by: Timothy Meehan <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 16 +++++++----
crates/pyspark-rs/src/progress.rs | 17 +++++------
python/pyspark/sql/connect/dataframe.py | 15 ++++++++++
python/tests/test_dropin_e2e.py | 28 ++++++++++++++++++
python/tests/test_dropin_offline.py | 50 +++++++++++++++++++++++++++++++++
5 files changed, 113 insertions(+), 13 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 56a38316..c5473a34 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -2296,9 +2296,16 @@ impl PyDataFrame {
/// the progress handlers of the execution are called by `next()`, on the
iterating thread.
#[pyo3(name = "toLocalIterator")]
#[pyo3(signature = (prefetchPartitions=false))]
- fn to_local_iterator(&self, prefetchPartitions: bool) ->
PyLocalRowIterator {
+ fn to_local_iterator<'py>(
+ &self,
+ py: Python<'py>,
+ prefetchPartitions: bool,
+ ) -> PyResult<Bound<'py, PyAny>> {
let _ = prefetchPartitions;
- PyLocalRowIterator::new(self.dataframe.clone())
+ let rows = PyLocalRowIterator::new(self.dataframe.clone());
+ py.import("pyspark.sql.connect.dataframe")?
+ .getattr("_local_rows")?
+ .call1((rows,))
}
/// Collect the DataFrame into a `pyarrow.Table`.
@@ -4538,9 +4545,8 @@ fn rows_to_py(
.collect()
}
-/// Python wrapper for LocalRowIterator yielding Row objects lazily.
-///
-/// Implements `__iter__` and `__next__` to make it a proper Python iterator.
+/// Python wrapper for LocalRowIterator yielding Row objects lazily: the rows
that the generator
+/// of `toLocalIterator` yields from. Implements `__iter__`, `__next__` and
`close`.
#[pyclass(name = "LocalRowIterator", module = "pyspark.sql.dataframe")]
pub struct PyLocalRowIterator {
dataframe: DataFrame,
diff --git a/crates/pyspark-rs/src/progress.rs
b/crates/pyspark-rs/src/progress.rs
index b72f716e..9b5a38e4 100644
--- a/crates/pyspark-rs/src/progress.rs
+++ b/crates/pyspark-rs/src/progress.rs
@@ -13,8 +13,6 @@ use spark_connect::progress::ProgressUpdate;
use spark_connect::SparkSession;
use spark_connect_core::error::SparkError;
-use crate::dataframe::PyLocalRowIterator;
-
/// The progress handlers of a session, and the progress bars of its
executions.
pub(crate) struct SessionProgress {
/// The handlers, as the `_progress_handlers` list of PySpark's client.
@@ -78,12 +76,15 @@ fn install_unreturned_error_handler() {
use spark_connect::progress::UnreturnedError;
Python::attach(|py| match error {
UnreturnedError::DroppedDone(error) => {
- // The iterator may be freed by now, so no reference to it
is left: its class
- // is the object of the hook. Only a LocalRowIterator
drops an execution that
- // calls the handlers unfinished; the other iterators do
not report progress.
- let iterator = py.get_type::<PyLocalRowIterator>();
- crate::errors::spark_error_to_py_exception(error)
- .write_unraisable(py, Some(iterator.as_any()))
+ // The generator of toLocalIterator may be freed by now,
so no reference to it
+ // is left: its type is the object of the hook. Only that
generator drops an
+ // execution that calls the handlers unfinished; the other
iterators do not
+ // report progress.
+ let error =
crate::errors::spark_error_to_py_exception(error);
+ match py.import("types").and_then(|t|
t.getattr("GeneratorType")) {
+ Ok(generator) => error.write_unraisable(py,
Some(&generator)),
+ Err(_) => error.write_unraisable(py, None),
+ }
}
UnreturnedError::Replaced { error, done } => {
let context =
crate::errors::spark_error_to_py_exception(error);
diff --git a/python/pyspark/sql/connect/dataframe.py
b/python/pyspark/sql/connect/dataframe.py
index a6be2a0b..08645210 100644
--- a/python/pyspark/sql/connect/dataframe.py
+++ b/python/pyspark/sql/connect/dataframe.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
"""Rust-backed DataFrame under the connect import path (testing/connectutils
imports from here)."""
+from collections.abc import Iterator
from typing import Any, Callable
from pyspark._pyspark import DataFrame
@@ -23,6 +24,20 @@ from pyspark.sql.dataframe import DataFrameNaFunctions,
DataFrameStatFunctions
__all__ = ["DataFrame", "DataFrameNaFunctions", "DataFrameStatFunctions"]
+def _local_rows(rows: Any) -> Iterator[Any]:
+ """The generator that ``DataFrame.toLocalIterator`` returns, as PySpark's:
the first row
+ starts the execution of the rows, and a close, a throw, an error or the
end of the generator
+ ends it."""
+ try:
+ yield from rows
+ finally:
+ rows.close()
+
+
+_local_rows.__name__ = "toLocalIterator"
+_local_rows.__qualname__ = "DataFrame.toLocalIterator"
+
+
def _reduce_dataframe(session: Any, relation: bytes) -> tuple[Callable[...,
Any], tuple[Any, ...]]:
"""The ``__reduce__`` of a DataFrame of ``session`` and the bytes of its
``relation``, as
PySpark Connect's, of its session and its plan: a function, which
cloudpickle pickles by
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index a12cdabb..c24086f1 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3384,6 +3384,34 @@ def
test_local_iterator_closes_as_a_generator_as_pyspark(session):
rows.close()
+def test_local_iterator_is_a_generator_as_pyspark(session):
+ # As PySpark's generator function: it yields the rows, and a close() or a
throw() in the
+ # middle ends it.
+ import inspect
+ import types
+
+ df = session.range(1000, numPartitions=10)
+ rows = df.toLocalIterator()
+ assert isinstance(rows, types.GeneratorType)
+ assert [row.id for row in rows] == list(range(1000))
+ assert inspect.getgeneratorstate(rows) == inspect.GEN_CLOSED
+ assert next(rows, None) is None
+
+ rows = df.toLocalIterator()
+ assert next(rows).id == 0
+ assert inspect.getgeneratorstate(rows) == inspect.GEN_SUSPENDED
+ with pytest.raises(ValueError, match="stop"):
+ rows.throw(ValueError("stop"))
+ assert inspect.getgeneratorstate(rows) == inspect.GEN_CLOSED
+ assert list(rows) == []
+
+ rows = df.toLocalIterator()
+ next(rows)
+ rows.close()
+ assert inspect.getgeneratorstate(rows) == inspect.GEN_CLOSED
+ assert list(rows) == []
+
+
def test_create_dataframe_takes_the_ddl_of_spark_as_pyspark(session):
# As PySpark Connect's, which parses a DDL schema on the server: nested
structs, arrays and
# maps of them, backtick-quoted names, and NOT NULL and COMMENT clauses.
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 982e4036..3ddf86a8 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -16837,6 +16837,56 @@ def
test_local_iterator_close_ends_it_before_it_runs_as_pyspark(mock_connect):
assert service.execute_requests == []
+def test_to_local_iterator_is_a_generator_as_pyspark(mock_connect):
+ # As PySpark's generator function, which sends nothing until its first row.
+ import inspect
+ import types
+
+ spark, service = mock_connect
+ rows = spark.range(3).toLocalIterator()
+ assert isinstance(rows, types.GeneratorType)
+ assert rows.__name__ == "toLocalIterator"
+ assert rows.__qualname__ == "DataFrame.toLocalIterator"
+ assert inspect.getgeneratorstate(rows) == inspect.GEN_CREATED
+ assert service.rpc_events == []
+
+
[email protected]("ending", ["close", "throw"])
+def
test_to_local_iterator_ending_releases_the_execution_as_pyspark(mock_connect,
ending):
+ # A close and a throw in the middle end the execution at once, also while
the exception,
+ # with its traceback, is kept.
+ import pyarrow as pa
+ from _mock_connect_server import parse_message
+ from binary_configuration_cases import _results, _wait_for
+
+ spark, service = mock_connect
+ _results(service, pa.RecordBatch.from_arrays([pa.array([0, 1])],
names=["id"]))
+ service.block_result_complete = True
+ try:
+ rows = spark.range(2).toLocalIterator()
+ assert next(rows).id == 0
+ operation_id = parse_message(service.execute_requests[0])[6][0]
+ kept = None
+ if ending == "close":
+ rows.close()
+ else:
+ with pytest.raises(ValueError, match="stop") as kept:
+ rows.throw(ValueError("stop"))
+
+ def released():
+ # ReleaseExecuteRequest.release_all=5 and operation_id=3.
+ return any(5 in fields and fields.get(3) == [operation_id]
+ for fields in map(parse_message,
service.release_execute_requests))
+
+ _wait_for(released)
+ assert released()
+ assert operation_id not in service.result_complete_operations
+ assert list(rows) == []
+ del kept
+ finally:
+ service.release_response()
+
+
def test_dataframes_of_other_sessions_raise_session_not_same_as_pyspark():
# As PySpark's `_check_same_session`, of the DataFrames that the methods
take, before any
# request: SESSION_NOT_SAME for a DataFrame of another session, and for
what is not one.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]