HyukjinKwon opened a new pull request, #538:
URL: https://github.com/apache/spark-connect-rust/pull/538

   ### What changes were proposed in this pull request?
   
   [SPARK-61483](https://issues.apache.org/jira/browse/SPARK-61483): a 
follow-up of [SPARK-61410](https://issues.apache.org/jira/browse/SPARK-61410) 
(#517), [SPARK-61414](https://issues.apache.org/jira/browse/SPARK-61414) 
(#518), [SPARK-61434](https://issues.apache.org/jira/browse/SPARK-61434) (#520) 
and [SPARK-61435](https://issues.apache.org/jira/browse/SPARK-61435) (#521). It 
fixes the siblings that their reviews found, so that these paths also match 
PySpark 4.3.0:
   
   1. **Binary literals (sibling of SPARK-61435).** A binary literal of the 
Python client now holds `bytes(value)` of a subclass of `bytes` or `bytearray`, 
as PySpark's `LiteralExpression.to_plan` sends it (`expr.literal.binary = 
bytes(self._value)`, pyspark/sql/connect/expressions.py:476). This covers 
`lit()`, the values that the functions and the Column methods take (`isin`, 
`when`, `otherwise`, `getItem`, ...), the elements of a typed array literal, 
and the arguments of `sql()`. `scalar_literal` and `literal_as` in 
`crates/pyspark-rs/src/functions.rs` used to read the buffer with 
`extract::<Vec<u8>>()`. The rule of SPARK-61435 is now one helper, 
`infer::bytes_of`, which `infer::convert` (createDataFrame) and both literal 
sites use: an exact `bytes` or `bytearray` is read as it is, and a subclass 
goes through `bytes()`.
   2. **No Config through a closed client while raising (sibling of 
SPARK-61410).** `SparkConnectClient::conf_while_raising` 
(`crates/spark-connect-core/src/client.rs`) sends nothing once the client is 
closed and returns no value. `display_server_stacktrace` takes that as true. 
PySpark's `_display_server_stack_trace` reads the setting through 
`RuntimeConf.get` -> `client.config` -> `_stub`. `_stub` raises 
NO_ACTIVE_SESSION once the client is closed, and the method's `except 
Exception` returns True (pyspark/sql/connect/client/core.py:964-970, 
2372-2384). So after a session change whose error has no `errorId`, PySpark 
sends no Config. This client used to send one through the closed client.
   3. **`corr` and `cov` without a limit (sibling of SPARK-61414).** 
`DataFrame::first_value` (`crates/spark-connect/src/dataframe.rs`) collects the 
relation as it is, instead of `limit(1).collect()`. Its only callers are 
`StatFunctions::corr` and `cov`. PySpark's `cov` and `corr` take 
`_to_table()[0][0]` of the bare `StatCov`/`StatCorr` relation 
(pyspark/sql/connect/dataframe.py:1619-1674). The Python client's `df.corr`, 
`df.cov`, `df.stat.corr` and `df.stat.cov` call the core, so they change too.
   4. **`isEmpty` reads `binaryAsBytes` (sibling of SPARK-61414).** The Python 
client's `isEmpty` reads `spark.sql.execution.pyspark.binaryAsBytes` after its 
execution. PySpark's `isEmpty` is `select().take(1)`, that is 
`limit(1).collect()`, and `collect` calls `_get_binary_as_bytes()` 
(pyspark/sql/connect/dataframe.py:285-287, 706-707, 1961-1978). `isEmpty` is 
still asked once per DataFrame, as PySpark's `functools.cache` keeps it.
   5. **The Arrow schema checks of createDataFrame of local rows run depth 
first (from the review of SPARK-61434; older than it).** 
`infer::arrow_schema_error` replaces `has_non_nullable_null_type` and 
`unsupported_arrow_type`, which ran as two passes over all the fields. It walks 
the fields once, depth first, in the order in which PySpark's `to_arrow_schema` 
and `to_arrow_type` build them (pyspark/sql/pandas/types.py:94-294). For each 
field, the type is built first, so an unsupported type inside it raises first. 
Then PyArrow's `pa.field(name, type, nullable)` raises `ValueError: A null type 
field may not be non-nullable` for a non-nullable null type. Array elements, 
map keys (which are never nullable) and map values are fields too. A 
user-defined type is built as its `sqlType()`, which the old passes did not 
look into.
   6. **"Not a sequence" as PyArrow checks it (from the review of SPARK-61434; 
older than it).** This applies to an array column whose elements need no 
converter, so PySpark passes the value to PyArrow as it is. 
`infer::is_arrow_list` mirrors PyArrow's list converter. It takes a sequence by 
`PySequence_Check`, such as a tuple, a range or a NumPy array, but never a 
dict. It also takes a `set` and a `dict_values`. Every other value gets 
PyArrow's deferred `ArrowTypeError`. Before, any iterable that was not a dict 
was taken. So a generator, an iterator, a `frozenset`, `dict_keys`, 
`dict_items` or a `mappingproxy` was converted where PySpark raises.
   
   ### Why are the changes needed?
   
   To match PySpark 4.3.0. The probes below ran the Connect client of official 
PySpark 4.3.0 and this client against a local Spark 4.3.0 Connect server.
   
   - Binary literals, with `class Bytes(bytes)` and `class 
ByteArray(bytearray)` whose `__bytes__` returns `b"other"`. The collected 
values, as PySpark 4.3.0 gives them and as this client gave them before; after 
the change, this client gives PySpark's in each case:
   
     ```
                                             PySpark 4.3.0                before
     lit(Bytes(b"orig")), lit(ByteArray(..)) b'other'                     
b'orig'
     lit([Bytes(b"orig"), Bytes(b"orig2")])  [b'other', b'other']         
[b'orig', b'orig2']
     isin(Bytes(b"orig")) on a b"other" row  1 row                        0 rows
     when(.., Bytes), otherwise(Bytes)       b'other'                     
b'orig'
     otherwise([b"b", Bytes, ByteArray])     [b'b', b'other', b'other']   
[b'b', b'orig', b'orig']
     create_map(lit("k"), lit(Bytes))        {'k': b'other'}              {'k': 
b'orig'}
     sql(.., args={"x": Bytes} or [Bytes])   b'other'                     
b'orig'
     lit of a __bytes__ that returns a str   TypeError: __bytes__ returned 
non-bytes   b'a'
     lit of a bytearray subclass whose __index__ is 2, of b"abc"   b'\x00\x00'  
      b'abc'
     ```
   
     The data differs silently, which is the bug that SPARK-61435 fixed for 
createDataFrame. PySpark raises an error of `__bytes__` when it sends the plan. 
This client builds a literal at once, so it raises the error at `lit()`.
   - The stack-trace setting: a probe of PySpark sets 
`spark.sql.connect.enrichError.enabled=false`, so that the error has no 
`errorId`, and then changes the server-side session ID. The call that hits the 
session change sends `['ExecutePlan', 'ReleaseExecute']`, with no Config. This 
client also sent a Config for `spark.sql.connect.serverStacktrace.enabled` 
through the closed client.
   - `corr`/`cov` and `isEmpty`, from a record of the RPCs of official PySpark:
   
     ```
     df.corr("id", "b"), df.stat.corr  ExecutePlan root: corr { ... }   (no 
Limit, no Config)
     df.cov("id", "b"), df.stat.cov    ExecutePlan root: cov { ... }    (no 
Limit, no Config)
     range(3).isEmpty()               ExecutePlan root: limit { project { range 
} }, then
                                      Config get_with_default 
spark.sql.execution.pyspark.binaryAsBytes
     ```
   
     Before, this client sent `limit { corr { ... } }` and `limit { cov { ... } 
}`, and its `isEmpty` read no Config. The results are unchanged: 1.0, 2.0, NaN 
for an empty relation, and False/True for `isEmpty`.
   - The Arrow schema order: 8 of 20 probed schemas raised a different error 
than PySpark. Some of them:
   
     ```
                                                      PySpark 4.3.0      before
     a interval year to month, b void NOT NULL        PySparkTypeError   
ValueError
     a struct<x: interval year to month, y: void NOT NULL>  PySparkTypeError  
ValueError
     a map<interval year to month, void> (no nulls)   PySparkTypeError   
ValueError
     a calendar interval / char(3), b void NOT NULL   PySparkTypeError   
ValueError
     a UDT of sqlType interval year to month          PySparkTypeError   no 
error
     a UDT of sqlType struct<x: void NOT NULL>, b interval year to month  
ValueError  PySparkTypeError
     ```
   
     The `PySparkTypeError` is `[UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION]`, 
of the type (e.g. `YearMonthIntervalType(0, 1)`). After the change, all 20 
match.
   - "Not a sequence", for `createDataFrame([(value,)], "a array<int>")`:
   
     ```
                                 PySpark 4.3.0                                  
before
     generator, list_iterator    ArrowTypeError ... was not a sequence ...      
[1, 2]
     dict_keys, mappingproxy     ArrowTypeError ... was not a sequence ...      
[1]
     frozenset                   ArrowTypeError ... was not a sequence ...      
[1, 2]
     dict_items                  ArrowTypeError ... was not a sequence ...      
ArrowInvalid: Could not convert (1, 2) ...
     range, set, dict_values, tuple, deque, array.array, bytes   accepted      
accepted
     ```
   
     PyArrow 22.0.0 itself gives the same answers for these values in a 
`list<int32>` column. After the change, all of them match PySpark, and the 
error still waits for the converters of the other columns, as in SPARK-61434.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes, as PySpark behaves:
   
   - A binary literal of a subclass of `bytes` or `bytearray` holds 
`bytes(value)` (the result of its `__bytes__`), and an error of `__bytes__` is 
raised.
   - `corr` and `cov`, in Rust and in the Python client, send their statistic 
without a `Limit` over it.
   - The Python client's `isEmpty` reads 
`spark.sql.execution.pyspark.binaryAsBytes` after its execution.
   - After a session change whose error has no `errorId`, the client sends no 
Config for the stack-trace setting.
   - createDataFrame of local rows raises the first error of the Arrow schema 
in PySpark's order, including inside a user-defined type. It raises PyArrow's 
`ArrowTypeError` for the iterables that PyArrow does not take as a list, in an 
array column whose elements need no converter.
   
   Values that converted before still convert the same way, except for these 
cases.
   
   ### How was this patch tested?
   
   New tests, each named after its behavior and placed next to the tests of the 
PR that it follows:
   
   - `python/tests/test_dropin_offline.py`:
     - `test_binary_literals_of_subclasses_are_sent_as_the_bytes_of_pyspark`, 
after SPARK-61435's `test_binary_subclasses_are_sent_as_the_bytes_of_pyspark`. 
It covers `lit`, `isin`, `when`, `create_map`, typed arrays with the subclass 
first and not first, an error of `__bytes__`, and the named and positional 
arguments of `sql()`.
     - `test_is_empty_reads_the_binary_setting_after_its_execution_as_pyspark` 
and `test_corr_and_cov_send_their_statistic_as_it_is_as_pyspark`, after 
SPARK-61414's 
`test_is_empty_sends_a_limit_of_one_row_over_an_empty_projection_as_pyspark`.
     - 
`test_local_rows_raise_the_first_error_of_the_arrow_schema_depth_first_as_pyspark`
 and 
`test_an_array_of_no_converter_takes_the_values_that_pyarrow_takes_as_pyspark`, 
after SPARK-61434's 
`test_local_rows_raise_the_error_of_a_converter_before_that_of_pyarrow`.
   - `crates/spark-connect-core/tests/server_session.rs`: 
`a_session_changed_error_reads_no_stack_trace_setting_as_pyspark`, after 
SPARK-61410's 
`a_session_changed_error_that_has_details_raises_no_active_session`. It checks 
that the Config that failed is the only request.
   - `crates/spark-connect/src/group.rs` (unit tests): 
`corr_and_cov_send_their_statistic_as_it_is_as_pyspark`. On a session without a 
server and without retries, an execute-plan hook records the root of each 
request and fails it.
   
   Each new test fails without the change. With the source changes reverted, 
the tests kept and the extension rebuilt, they fail with:
   
   - `test_is_empty_reads_...`: `assert ['execute'] == ['execute', 'config']`
   - `test_corr_and_cov_...` (Python): `assert ['limit', 'limit', 'limit', 
'limit'] == ['corr', 'cov', 'corr', 'cov']`
   - `test_binary_literals_...`: `assert b'orig' == b'other'`
   - `test_local_rows_raise_the_first_error_...`: `ValueError` where 
`PySparkTypeError` is expected, for `a interval year to month, b void not null`
   - `test_an_array_of_no_converter_...`: `DID NOT RAISE <class 
'pyarrow.lib.ArrowTypeError'>`
   - `a_session_changed_error_reads_no_stack_trace_setting_as_pyspark`: `left: 
["Config", "Config"]`, `right: ["Config"]`
   - `corr_and_cov_send_their_statistic_as_it_is_as_pyspark` (Rust): the 
recorded roots are `[Limit(.. Corr ..), Limit(.. Cov ..)]`
   
   The cases of the two new createDataFrame tests and the expectations of the 
new literal test also ran against official PySpark 4.3.0, and they hold there.
   
   Commands, all passing:
   
   - `cargo test -p apache-spark-connect-core --release --test server_session` 
(8 passed) and `--lib` (197 passed)
   - `cargo test -p apache-spark-connect --release --lib` (605 passed, 
including the 22 of `group::tests`)
   - `cargo test -p apache-spark-connect --release --no-run` and `cargo test -p 
apache-spark-connect --release --features wasm-udf --no-run`: no warnings
   - `cargo fmt --all --check`, and `ruff check` (0.14.0, as CI runs it)
   - `cargo clippy --release --all-targets` of `pyspark-rs`, 
`apache-spark-connect` and `apache-spark-connect-core` reports nothing in the 
changed lines
   - `python -m pytest python/tests/test_dropin_offline.py`, the whole file: 
1855 passed, 8 skipped
   - Against a local Spark 4.3.0 Connect server (`SPARK_REMOTE` set):
     - `python -m pytest python/tests/test_dropin_e2e.py -k "(binary or bytes 
or lit or corr or cov or stat or empty or create or server_session or error or 
schema or array or sql) and not stream and not Stream"`: 95 passed. This 
includes SPARK-61410's session-change test and SPARK-61435's binary test.
     - `-k "answers_that_pyspark_keeps or column_list_values_are_typed_array or 
numpy_scalar_literals or decimal_literals or datetime_literals or 
try_cast_and_isin or lists_and_numpy_arrays"`: 8 passed
     - `cargo test -p apache-spark-connect --release` with `--test 
e2e_new_methods stat_corr_cov_sample_by`, `--test e2e_dataframe is_empty` and 
`--test e2e_coverage agg_na_stat_reshape_surface`: passed
   
   ### 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.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to