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 4019f042 [SPARK-61485][CONNECT][PYTHON] Pickle the methods of Row, 
VariantVal, Geometry and Geography by reference to pyspark.sql.types, and read 
an Arrow stream of one schema in the invalid-UTF-8 scan
4019f042 is described below

commit 4019f042ae3198ad3015a2cdc4389d103399cd69
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:15:52 2026 +0900

    [SPARK-61485][CONNECT][PYTHON] Pickle the methods of Row, VariantVal, 
Geometry and Geography by reference to pyspark.sql.types, and read an Arrow 
stream of one schema in the invalid-UTF-8 scan
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61485](https://issues.apache.org/jira/browse/SPARK-61485): 
follow-ups of a post-hoc review of SPARK-61402 (#476) and SPARK-61405 (#478), 
checked against PySpark 4.3.0.
    
    - **Methods of `Row`, `VariantVal`, `Geometry` and `Geography`** 
(`crates/pyspark-rs/src/row.py`, `values.py`): the embedded modules set the 
`__module__` of their methods to `pyspark.sql.types`, as they did for the 
classes. This covers functions, classmethods, staticmethods and properties, as 
PySpark's methods are of `pyspark.sql.types`.
    - **The invalid-UTF-8 scan of a result** 
(`crates/spark-connect/src/dataframe.rs`, `read_strings_as_binary`) reads a 
stream of one schema only, as a valid Arrow IPC stream is. A stream with 
another schema message is not read there, and the decoding error is reported as 
it is.
    - **Docs** (`docs/compatibility.md`): SPARK-61405's changes:
      - the strata that `sample_by` rejects;
      - the seed that it draws on the client;
      - the `Value::Map` fill of `fillna_value`.
    
    ### Why are the changes needed?
    
    - **UDF methods fail on the server.** A UDF that is, or captures, a method 
of these classes failed on the server, for example:
      - `F.udf(Geography.getSrid, "int")`;
      - `F.udf(VariantVal.toJson, "string")`;
      - `F.udf(variant.toJson, "string")`;
      - a UDF that captures `Row.asDict`.
    
      It raised `PythonException: ... ModuleNotFoundError: No module named 
'pyspark._values'` (or `'pyspark._row'`). cloudpickle pickles a method by 
reference to its module, and `pyspark._values` and `pyspark._row` exist on the 
client only; official PySpark's methods are of `pyspark.sql.types`, which the 
server's Python workers import. Official PySpark returns `4326`, `{"b":2}`, 
`{"a":1}` and the dict.
    - **A panic on a malformed stream.** The scan took the column count from 
the first batch and the field types from the last schema message. A stream with 
a second, narrower schema therefore panicked with an index out of bounds 
(`arrow-schema` `schema.rs`). Spark never sends such a stream, but a server 
response should not panic the client.
    - **Stale docs.** They did not describe the SPARK-61405 changes.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. UDFs of these methods run on the server, as with PySpark, and a 
malformed stream raises its decoding error instead of panicking.
    
    ### How was this patch tested?
    
    - Offline (`python/tests/test_dropin_offline.py`, placed before 
`test_spatial_values_copy_pickle_and_are_subclassed_as_pyspark`): 
`test_methods_of_rows_and_values_pickle_by_reference_to_pyspark_sql_types_as_pyspark`.
 The cloudpickles of their functions and bound methods name `pyspark.sql.types` 
and not `pyspark._values` or `pyspark._row`. A classmethod pickles by value, as 
PySpark's does.
    - Live (`python/tests/test_dropin_e2e.py`, placed after 
`test_udfs_that_refer_to_variant_and_spatial_values_run_on_the_server_as_pyspark`):
 `test_udfs_of_methods_of_rows_and_values_run_on_the_server_as_pyspark`. It 
runs UDFs of `Geography.getSrid` and `VariantVal.toJson`, and one that captures 
`Row.asDict`, against a local Spark 4.3.0 server.
    - Rust (`dataframe.rs`): 
`a_stream_of_two_schemas_has_no_invalid_utf8_to_report`.
    - Each new test fails without its change: the live test with the server's 
`ModuleNotFoundError: No module named 'pyspark._values'`, and the Rust test 
with the index-out-of-bounds panic.
    - Checks:
      - the lib tests of both crates (806 passed);
      - 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` on `row.py`;
      - a full trial on master, chained after #495, 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 #531 from HyukjinKwon/s18-posthoc-followups.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/row.py          | 21 +++++++++++++++++++++
 crates/pyspark-rs/src/values.py       | 21 +++++++++++++++++++++
 crates/spark-connect/src/dataframe.rs | 33 +++++++++++++++++++++++++++++++++
 docs/compatibility.md                 | 16 ++++++++++------
 python/tests/test_dropin_e2e.py       | 22 ++++++++++++++++++++++
 python/tests/test_dropin_offline.py   | 22 ++++++++++++++++++++++
 6 files changed, 129 insertions(+), 6 deletions(-)

diff --git a/crates/pyspark-rs/src/row.py b/crates/pyspark-rs/src/row.py
index 6af09bec..bb629565 100644
--- a/crates/pyspark-rs/src/row.py
+++ b/crates/pyspark-rs/src/row.py
@@ -226,3 +226,24 @@ class Row(tuple):
                 "%s=%r" % (key, value) for key, value in zip(self.__fields__, 
tuple(self))
             )
         return "<Row(%s)>" % ", ".join(repr(value) for value in self)
+
+
+def _publish_methods(*classes) -> None:
+    # As the methods of PySpark's classes, those of this class are of 
``pyspark.sql.types``, the
+    # module that the server's Python workers import: a UDF that is, or 
captures, one of them pickles
+    # it by reference to that module, where ``pyspark._row`` exists on the 
client only.
+    import types
+
+    for cls in classes:
+        for value in vars(cls).values():
+            if isinstance(value, property):
+                functions = [value.fget, value.fset, value.fdel]
+            else:
+                functions = [getattr(value, "__func__", value)]
+            for function in functions:
+                if isinstance(function, types.FunctionType):
+                    function.__module__ = cls.__module__
+
+
+_publish_methods(Row)
+del _publish_methods
diff --git a/crates/pyspark-rs/src/values.py b/crates/pyspark-rs/src/values.py
index 837a853f..e06a09f5 100644
--- a/crates/pyspark-rs/src/values.py
+++ b/crates/pyspark-rs/src/values.py
@@ -255,3 +255,24 @@ class Geometry:
         :return: Python representation of the Geometry type value.
         """
         return Geometry(wkb, srid)
+
+
+def _publish_methods(*classes: type) -> None:
+    # As the methods of PySpark's classes, those of these classes are of 
``pyspark.sql.types``, the
+    # module that the server's Python workers import: a UDF that is, or 
captures, one of them pickles
+    # it by reference to that module, where ``pyspark._values`` exists on the 
client only.
+    import types
+
+    for cls in classes:
+        for value in vars(cls).values():
+            if isinstance(value, property):
+                functions = [value.fget, value.fset, value.fdel]
+            else:
+                functions = [getattr(value, "__func__", value)]
+            for function in functions:
+                if isinstance(function, types.FunctionType):
+                    function.__module__ = cls.__module__
+
+
+_publish_methods(VariantVal, Geography, Geometry)
+del _publish_methods
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 9a75e3ea..fb52a150 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -3017,6 +3017,9 @@ fn read_strings_as_binary(
         let message = root_as_message(take(&mut rest, meta_len)?).ok()?;
         let body = take(&mut rest, 
usize::try_from(message.bodyLength()).ok()?)?;
         match message.header_type() {
+            // A stream has one schema: with another, its batches would not 
have the columns
+            // of the types read, so it does not read.
+            MessageHeader::Schema if strings.is_some() => return None,
             MessageHeader::Schema => {
                 let fields = fb_to_schema(message.header_as_schema()?);
                 schema = Some(Arc::new(binary_schema(&fields)));
@@ -4186,6 +4189,36 @@ mod nested_decode_tests {
         );
     }
 
+    #[test]
+    fn a_stream_of_two_schemas_has_no_invalid_utf8_to_report() {
+        // An IPC stream has one schema. With a second one of fewer columns, 
the scan, which took
+        // the columns of the first batch and the types of the last schema, 
indexed out of bounds.
+        use arrow::ipc::writer::StreamWriter;
+        let stream = |names: &[&str]| {
+            let fields: Vec<_> = names
+                .iter()
+                .map(|name| Field::new(*name, DataType::Utf8, true))
+                .collect();
+            let schema = Arc::new(arrow::datatypes::Schema::new(fields));
+            let columns = names
+                .iter()
+                .map(|_| Arc::new(arrow::array::StringArray::from(vec!["a"])) 
as ArrayRef)
+                .collect();
+            let batch = 
arrow::record_batch::RecordBatch::try_new(schema.clone(), columns).unwrap();
+            let mut data = vec![];
+            let mut writer = StreamWriter::try_new(&mut data, 
&schema).unwrap();
+            writer.write(&batch).unwrap();
+            writer.finish().unwrap();
+            drop(writer);
+            data
+        };
+        let mut data = stream(&["x", "y"]);
+        // Without its end of stream, so that the second stream's schema 
follows its batch.
+        data.truncate(data.len() - 8);
+        data.extend(stream(&["x"]));
+        assert_eq!(first_invalid_utf8(&data), None);
+    }
+
     #[test]
     fn 
unsupported_children_remain_lazy_under_nulls_empty_containers_and_variants() {
         let null_duration = DurationSecondArray::from(vec![None]);
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 7245b72a..a87a8e06 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -53,8 +53,10 @@ int. `MlOperator::new` makes a uid of the simple class name 
and 12 hex digits
 `dropna` does. As PySpark's `fillna`, they take a bool, an integer, a float or 
a
 string (an integer is sent as a long, a float as a double), and reject other 
values
 with `NOT_EXPECTED_TYPE` and an empty map with `CANNOT_BE_EMPTY`. Before, such 
a
-value filled string columns with its debug text. `fillna`, `fillna_double`,
-`fillna_string` and `fillna_bool` are unchanged.
+value filled string columns with its debug text. A `Value::Map` given to
+`fillna_value` fills the columns of its keys, as PySpark's `fillna` of a dict, 
instead
+of being rejected. `fillna`, `fillna_double`, `fillna_string` and 
`fillna_bool` are
+unchanged.
 
 A transport failure has the gRPC code that grpc-python gives it, which 
PySpark's errors and
 retries see. `SparkError::grpc_code` is `UNAVAILABLE` (14) for a connection 
that closes or is reset
@@ -132,10 +134,12 @@ matches on these enums must handle the new variant. The 
Python client still rais
 As PySpark's `repartitionByRange`, a partition count that is not positive is
 `VALUE_NOT_POSITIVE` and an empty column list `CANNOT_BE_EMPTY`. Before, the 
server
 split the rows round-robin for an empty column list. `StatFunctions::sample_by`
-returns a `Result` too: a stratum that is not a literal is
-`DISALLOWED_TYPE_FOR_CONTAINER`, as PySpark rejects a key that is not a float, 
an int
-or a str. Before, it was sent as an empty literal, which failed only when the
-DataFrame ran.
+returns a `Result` too: a stratum that is not a literal of a bool, an integer, 
a float
+or a string (a null, a decimal, binary, a date, a timestamp, an interval or an 
array)
+is `DISALLOWED_TYPE_FOR_CONTAINER`, as PySpark rejects a key that is not a 
float, an
+int or a str. Before, it was sent as an empty literal, which failed only when 
the
+DataFrame ran, or as its own literal, which sampled no rows. Without a seed,
+`sample_by` sends one that the client draws, as `sample` and `random_split` do.
 
 A panic of a native `StreamingQueryListener` on an event of the listener bus is
 isolated, as on the started event and as PySpark isolates the exception of a 
listener:
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index ac85c0d6..573e610c 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2665,6 +2665,28 @@ def 
test_udfs_that_refer_to_variant_and_spatial_values_run_on_the_server_as_pysp
     assert session.range(1).select(described("id")).first()[0] == '{"a":1} 
4326 3857'
 
 
+def 
test_udfs_of_methods_of_rows_and_values_run_on_the_server_as_pyspark(session):
+    # As PySpark's: a UDF that is, or captures, a method of Row, VariantVal, 
Geometry or Geography
+    # pickles it by reference to pyspark.sql.types, which the server's Python 
workers import.
+    from pyspark.sql import functions as F
+    from pyspark.sql.types import Geography, Row, VariantVal
+
+    geography = session.sql(
+        "SELECT st_geogfromwkb(X'0101000000000000000000F03F0000000000000040') 
AS g")
+    assert geography.select(F.udf(Geography.getSrid, "int")("g")).first()[0] 
== 4326
+    variant = session.sql("""SELECT parse_json('{"b": 2}') AS v""")
+    assert variant.select(F.udf(VariantVal.toJson, "string")("v")).first()[0] 
== '{"b":2}'
+    row = Row(a=1, b="x")
+    as_dict = Row.asDict
+
+    @F.udf("string")
+    def captured(_):
+        return str(as_dict(row))
+
+    assert session.range(1).select(captured("id")).first()[0] == "{'a': 1, 
'b': 'x'}"
+
+
+
 def test_create_dataframe_of_multi_and_categorical_labels_as_pyspark(session):
     # As PySpark's: a frame whose labels are a MultiIndex or a 
CategoricalIndex converts its
     # cells as a frame of default labels does. A naive datetime of a list 
reads back unchanged
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index d3671cbd..b9a3ec1c 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7172,6 +7172,28 @@ def 
test_variant_and_spatial_values_pickle_as_pysparks_plain_classes_which_load_
             assert {field: getattr(restored, field) for field in fields} == 
fields
 
 
+def 
test_methods_of_rows_and_values_pickle_by_reference_to_pyspark_sql_types_as_pyspark():
+    # As PySpark's, whose methods are of pyspark.sql.types: a UDF that is, or 
captures, a method of
+    # Row, VariantVal, Geometry or Geography pickles it by reference to that 
module, which the
+    # server's Python workers import, where pyspark._values and pyspark._row 
are of the client only.
+    from pyspark import cloudpickle
+    from pyspark.sql.types import Geography, Geometry, Row, VariantVal
+
+    wkb = bytes.fromhex("0101000000000000000000F03F0000000000000040")
+    variant = VariantVal(b"\x0c\x01", b"\x01\x00\x00")
+    geography, geometry, row = Geography(wkb, 4326), Geometry(wkb, 0), Row(a=1)
+    # Their functions and bound methods; a classmethod pickles by value, as 
PySpark's does.
+    methods = [
+        VariantVal.toJson, variant.toJson, VariantVal.toPython,
+        Geography.getSrid, geography.getBytes, Geometry.getSrid, 
geometry.getBytes,
+        Row.asDict, row.asDict, Row.__repr__,
+    ]
+    for method in methods:
+        data = cloudpickle.dumps(method)
+        assert b"pyspark._values" not in data and b"pyspark._row" not in data, 
method
+        assert b"pyspark.sql.types" in data, method
+
+
 def test_spatial_values_copy_pickle_and_are_subclassed_as_pyspark():
     # As PySpark's Geometry and Geography, plain classes: they are copied and 
pickled, also in a
     # Row, and subclassed, of an __init__ that unpickling does not run. And as 
of PySpark's


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

Reply via email to