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 2acffdcf [SPARK-61493][CONNECT][PYTHON] Ignore the prefetchPartitions 
of toLocalIterator, give its generator the code name toLocalIterator, and do 
not check the session IDs of artifact responses, as PySpark does
2acffdcf is described below

commit 2acffdcff6a1a887fc671637e10b983f3542dd9e
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 12:20:51 2026 +0900

    [SPARK-61493][CONNECT][PYTHON] Ignore the prefetchPartitions of 
toLocalIterator, give its generator the code name toLocalIterator, and do not 
check the session IDs of artifact responses, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61493](https://issues.apache.org/jira/browse/SPARK-61493): 
follow-ups of a post-hoc review of SPARK-61413 (#519) and SPARK-61410 (#517), 
checked against PySpark 4.3.0.
    
    - **`prefetchPartitions` of `DataFrame.toLocalIterator`** 
(`crates/pyspark-rs/src/dataframe.rs`): any value is taken, by position or by 
name, and ignored, as PySpark Connect's `toLocalIterator(self, 
prefetchPartitions: bool = False)` ignores it. The signature still shows the 
default `False`.
    - **The code name of the generator** 
(`python/pyspark/sql/connect/dataframe.py`): the generator that 
`toLocalIterator` returns has the code name `toLocalIterator`, and the 
qualified name `DataFrame.toLocalIterator` on Python 3.11 and later, as 
PySpark's. Only `__name__` and `__qualname__` were set before.
    - **The session IDs of artifact responses** 
(`crates/spark-connect-core/src/client.rs`): `cache_artifacts`, 
`upload_artifact` and `artifact_status` no longer check the session IDs of the 
`ArtifactStatus` and `AddArtifacts` responses. PySpark's `ArtifactManager` does 
not check them, and its requests, like ours, carry no observed server-side 
session ID.
    
    ### Why are the changes needed?
    
    - **`toLocalIterator` raised for a non-bool value.** 
`df.toLocalIterator(1)`, `toLocalIterator(None)` and 
`toLocalIterator(prefetchPartitions="x")` raised a PyO3 `TypeError` at the 
call. PySpark returns the rows.
    - **The generator had another code name.** Its code name was `_local_rows`, 
which `gi_code`, tracebacks and `inspect` show. A traceback through the 
generator now shows `toLocalIterator`, as PySpark's does.
    - **Artifact calls closed the client after a server restart.** When 
`spark.addArtifacts(...)`, or a cache of artifacts, was the first call after a 
server restart, ours raised an assertion error and closed the client. PySpark's 
call returns, and the next call of the client raises. With this change, ours 
does the same: the next call raises and closes the client, as SPARK-61410 made 
it do.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, as above: `toLocalIterator` takes any `prefetchPartitions`, its 
generator has PySpark's code name, and artifact calls after a server restart 
return as PySpark's do.
    
    ### How was this patch tested?
    
    - Offline (`python/tests/test_dropin_offline.py`):
      - `test_local_iterators_take_any_prefetch_partitions_as_pyspark`, placed 
before 
`test_is_streaming_is_empty_and_input_files_are_asked_once_per_dataframe_as_pyspark`.
 With `True`, `False`, `1`, `0`, `None`, `"x"` and `[1]`, by position and by 
name, it checks the rows and that the plan is the default's. It also checks the 
signature's default `False`, and that two arguments raise a `TypeError`.
      - `test_to_local_iterator_is_a_generator_as_pyspark` also checks 
`gi_code.co_name`, `co_qualname`, and the name of the traceback frame of a 
`throw()` into the started generator.
    - Rust (`crates/spark-connect-core/tests/server_session.rs`): 
`artifact_responses_of_a_restarted_server_are_not_checked_as_pyspark`. After 
the fake server's session changes, `artifact_status` and `cache_artifacts` 
return, the client stays open, and the next `config` call raises the assertion 
error and closes it.
    - Live, against a local Spark 4.3.0 server, with the server-side session ID 
that the client observed changed under it: `spark.addArtifacts(path, 
pyfile=True)` returns, then the next call raises `NO_ACTIVE_SESSION` and 
`is_stopped` is True, as with PySpark 4.3.0. Before, `addArtifacts` raised 
`PySparkAssertionError` and closed the session. `collect` and `toLocalIterator` 
raise `NO_ACTIVE_SESSION` at once, as before and as PySpark does.
    - Each new check fails without its change:
      - the prefetch test with `TypeError: argument 'prefetchPartitions': 'int' 
object is not an instance of 'bool'`;
      - the generator test with `'_local_rows' == 'toLocalIterator'`;
      - the Rust test at `artifact_status`, which raised.
    - Checks:
      - the lib tests of both crates: 808 passed, and 1 failed, 
`test_interrupt_all_request_structure`, unrelated to this change. That test 
raced another one over `SPARK_CONNECT_AUTHENTICATE_TOKEN`, which #542 fixes;
      - the build of all tests, also with `wasm-udf` and `datafusion,polars`, 
without warnings;
      - `cargo fmt --all --check`, and clippy with no diagnostics on the 
changed lines;
      - `ruff check` and `ruff format --check`;
      - a full trial on master before the merge.
    
    ### 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 #540 from HyukjinKwon/s18b-posthoc-followups.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs                |  8 +++-
 crates/spark-connect-core/src/client.rs           | 31 ++++++---------
 crates/spark-connect-core/tests/server_session.rs | 46 +++++++++++++++++++++++
 python/pyspark/sql/connect/dataframe.py           |  9 +++++
 python/tests/test_dropin_offline.py               | 44 +++++++++++++++++++++-
 5 files changed, 116 insertions(+), 22 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 136696f3..b2b412fb 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -2291,12 +2291,16 @@ impl PyDataFrame {
     /// which ignores `prefetchPartitions`, a batch is fetched when the 
iteration reaches it, so
     /// the progress handlers of the execution are called by `next()`, on the 
iterating thread.
     #[pyo3(name = "toLocalIterator")]
-    #[pyo3(signature = (prefetchPartitions=false))]
+    #[pyo3(
+        signature = (prefetchPartitions=None),
+        text_signature = "($self, prefetchPartitions=False)"
+    )]
     fn to_local_iterator<'py>(
         &self,
         py: Python<'py>,
-        prefetchPartitions: bool,
+        prefetchPartitions: Option<&Bound<'py, PyAny>>,
     ) -> PyResult<Bound<'py, PyAny>> {
+        // Any value, as PySpark Connect's, which ignores it.
         let _ = prefetchPartitions;
         let rows = PyLocalRowIterator::new(self.dataframe.clone());
         py.import("pyspark.sql.connect.dataframe")?
diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index c20e0d63..655028c2 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -2050,14 +2050,11 @@ impl SparkConnectClient {
             .cloned()
             .collect();
         let (blobs, names, unique) = (&blobs, &names, &unique);
-        // The IDs of the status response, checked once the retries are done, 
as its own.
-        let (status_ids, uploaded) = self
+        // As PySpark's ArtifactManager, which does not check the IDs of its 
responses: a change of
+        // the server-side session is raised by the next call of the client.
+        let uploaded = self
             .with_retry(|| async move {
                 let status = self.artifact_status_rpc(unique).await?;
-                let status_ids = (
-                    status.session_id.clone(),
-                    status.server_side_session_id.clone(),
-                );
                 let cached: std::collections::HashMap<String, bool> = status
                     .statuses
                     .into_iter()
@@ -2071,18 +2068,16 @@ impl SparkConnectClient {
                     }
                 }
                 if artifacts.is_empty() {
-                    return Ok((status_ids, None));
+                    return Ok(None);
                 }
                 let expected: HashSet<String> =
                     artifacts.iter().map(|(name, _)| name.clone()).collect();
                 let requests = 
cache_artifact_requests(self.session_id.clone(), artifacts);
                 let response = self.add_artifacts_rpc(requests).await?;
-                Ok((status_ids, Some((response, expected))))
+                Ok(Some((response, expected)))
             })
             .await?;
-        self.verify_response(&status_ids.0, &status_ids.1)?;
         if let Some((response, expected)) = uploaded {
-            self.verify_response(&response.session_id, 
&response.server_side_session_id)?;
             check_artifact_upload(response, Some(&expected))?;
         }
         Ok(hashes)
@@ -2147,7 +2142,7 @@ impl SparkConnectClient {
                 result.map_err(RetryError::Status)
             })
             .await?;
-        self.verify_response(&response.session_id, 
&response.server_side_session_id)?;
+        // The IDs of the response are not checked, as by PySpark's 
ArtifactManager.
         check_artifact_upload(response, None)
     }
 
@@ -2181,14 +2176,12 @@ impl SparkConnectClient {
         self.ensure_open()?;
         let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
         match self.artifact_status_rpc(&names).await {
-            Ok(response) => {
-                self.verify_response(&response.session_id, 
&response.server_side_session_id)?;
-                Ok(response
-                    .statuses
-                    .into_iter()
-                    .map(|(name, status)| (name, status.exists))
-                    .collect())
-            }
+            // The IDs of the response are not checked, as by PySpark's 
ArtifactManager.
+            Ok(response) => Ok(response
+                .statuses
+                .into_iter()
+                .map(|(name, status)| (name, status.exists))
+                .collect()),
             Err(status) => Err(self.error_from_status(status).await),
         }
     }
diff --git a/crates/spark-connect-core/tests/server_session.rs 
b/crates/spark-connect-core/tests/server_session.rs
index dd772057..c29a6200 100644
--- a/crates/spark-connect-core/tests/server_session.rs
+++ b/crates/spark-connect-core/tests/server_session.rs
@@ -233,6 +233,24 @@ impl UnaryService<Vec<u8>> for Unary {
                 ..Default::default()
             }
             .encode_to_vec(),
+            // Every artifact that is asked for exists.
+            "ArtifactStatus" => spark_connect_proto::ArtifactStatusesResponse {
+                session_id,
+                server_side_session_id,
+                statuses: 
spark_connect_proto::ArtifactStatusesRequest::decode(bytes.as_slice())
+                    .map(|request| request.names)
+                    .unwrap_or_default()
+                    .into_iter()
+                    .map(|name| {
+                        let exists =
+                            
spark_connect_proto::artifact_statuses_response::ArtifactStatus {
+                                exists: true,
+                            };
+                        (name, exists)
+                    })
+                    .collect(),
+            }
+            .encode_to_vec(),
             _ => Vec::new(),
         };
         Box::pin(async { Ok(Response::new(body)) })
@@ -394,6 +412,34 @@ async fn a_restarted_server_raises_and_closes_the_client() 
{
     assert_eq!(error.get_condition().as_deref(), Some("NO_ACTIVE_SESSION"));
 }
 
+/// As PySpark's ArtifactManager, which does not check the IDs of its 
responses: the artifact
+/// statuses of a restarted server are returned, also to a cache of artifacts, 
and the next call
+/// of the client raises.
+#[tokio::test]
+async fn artifact_responses_of_a_restarted_server_are_not_checked_as_pyspark() 
{
+    let fixture = Fixture::start().await;
+    let client = fixture.client().await;
+    client.config(config_request(&client)).await.unwrap();
+
+    *fixture.state.server_session_id.lock().unwrap() = 
RESTARTED_SERVER_ID.to_string();
+    let statuses = client
+        .artifact_status(&["cache/a"])
+        .await
+        .expect("an artifact status");
+    assert_eq!(statuses.get("cache/a"), Some(&true));
+    client
+        .cache_artifacts(vec![b"blob".to_vec()])
+        .await
+        .expect("a cache of artifacts that exist");
+    assert!(!client.is_closed());
+    let error = client
+        .config(config_request(&client))
+        .await
+        .expect_err("the next call of the client raises");
+    assert_eq!(error.kind, SparkErrorKind::AssertionError);
+    assert!(client.is_closed());
+}
+
 #[tokio::test]
 async fn 
a_restart_that_the_plan_compression_lookup_sees_sends_no_plan_as_pyspark() {
     use spark_connect_proto::analyze_plan_request::{Analyze, Schema};
diff --git a/python/pyspark/sql/connect/dataframe.py 
b/python/pyspark/sql/connect/dataframe.py
index 08645210..782593ae 100644
--- a/python/pyspark/sql/connect/dataframe.py
+++ b/python/pyspark/sql/connect/dataframe.py
@@ -36,6 +36,15 @@ def _local_rows(rows: Any) -> Iterator[Any]:
 
 _local_rows.__name__ = "toLocalIterator"
 _local_rows.__qualname__ = "DataFrame.toLocalIterator"
+# And the name of its code, as PySpark's generator, which tracebacks and 
`inspect` show.
+_local_rows.__code__ = _local_rows.__code__.replace(
+    co_name="toLocalIterator",
+    **(
+        {"co_qualname": "DataFrame.toLocalIterator"}
+        if hasattr(_local_rows.__code__, "co_qualname")
+        else {}
+    ),
+)
 
 
 def _reduce_dataframe(session: Any, relation: bytes) -> tuple[Callable[..., 
Any], tuple[Any, ...]]:
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 165017e7..7c9f57f6 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -9557,6 +9557,32 @@ def 
test_local_iterators_call_the_progress_handlers_in_next_whatever_the_prefetc
     spark.clearProgressHandlers()
 
 
+def test_local_iterators_take_any_prefetch_partitions_as_pyspark(mock_connect):
+    # As PySpark Connect's toLocalIterator, which ignores prefetchPartitions: 
any value, by
+    # position or by name, sends the plan of the default and yields the rows. 
The default is
+    # False, as PySpark's.
+    import inspect
+
+    import pyarrow as pa
+    from binary_configuration_cases import _results
+
+    spark, service = mock_connect
+    _results(service, pa.RecordBatch.from_arrays([pa.array([0, 1])], 
names=["id"]))
+    df = spark.range(2)
+    assert [row.id for row in df.toLocalIterator()] == [0, 1]
+    # ExecutePlanRequest.plan=3.
+    plan = parse_message(service.execute_requests[-1])[3]
+    for value in (True, False, 1, 0, None, "x", [1]):
+        assert [row.id for row in df.toLocalIterator(value)] == [0, 1]
+        assert parse_message(service.execute_requests[-1])[3] == plan
+        assert [row.id for row in 
df.toLocalIterator(prefetchPartitions=value)] == [0, 1]
+        assert parse_message(service.execute_requests[-1])[3] == plan
+    signature = inspect.signature(type(df).toLocalIterator)
+    assert signature.parameters["prefetchPartitions"].default is False
+    with pytest.raises(TypeError):
+        df.toLocalIterator(True, 1)
+
+
 def 
test_is_streaming_is_empty_and_input_files_are_asked_once_per_dataframe_as_pyspark(
         mock_connect):
     # As PySpark's isStreaming (a cached_property), isEmpty and inputFiles 
(functools.cache): a
@@ -17748,18 +17774,34 @@ def 
test_local_iterator_close_ends_it_before_it_runs_as_pyspark(mock_connect):
 
 
 def test_to_local_iterator_is_a_generator_as_pyspark(mock_connect):
-    # As PySpark's generator function, which sends nothing until its first row.
+    # As PySpark's generator function, which sends nothing until its first 
row, and whose code,
+    # which tracebacks show, has the name of the method.
     import inspect
+    import sys
+    import traceback
     import types
 
+    import pyarrow as pa
+    from binary_configuration_cases import _results
+
     spark, service = mock_connect
     rows = spark.range(3).toLocalIterator()
     assert isinstance(rows, types.GeneratorType)
     assert rows.__name__ == "toLocalIterator"
     assert rows.__qualname__ == "DataFrame.toLocalIterator"
+    assert rows.gi_code.co_name == "toLocalIterator"
+    if sys.version_info >= (3, 11):
+        assert rows.gi_code.co_qualname == "DataFrame.toLocalIterator"
     assert inspect.getgeneratorstate(rows) == inspect.GEN_CREATED
     assert service.rpc_events == []
 
+    _results(service, pa.RecordBatch.from_arrays([pa.array([0, 1])], 
names=["id"]))
+    rows = spark.range(2).toLocalIterator()
+    assert next(rows).id == 0
+    with pytest.raises(ValueError, match="stop") as raised:
+        rows.throw(ValueError("stop"))
+    assert traceback.extract_tb(raised.tb)[-1].name == "toLocalIterator"
+
 
 @pytest.mark.parametrize("ending", ["close", "throw"])
 def 
test_to_local_iterator_ending_releases_the_execution_as_pyspark(mock_connect, 
ending):


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

Reply via email to