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 22dfbe3c [SPARK-61496][CONNECT][PYTHON][FOLLOWUP] Raise PySpark's
errors for a how or direction of the as-of join that is not a name
22dfbe3c is described below
commit 22dfbe3c4bd03f208b7ddbb00025ec225616c80a
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 18:39:35 2026 +0900
[SPARK-61496][CONNECT][PYTHON][FOLLOWUP] Raise PySpark's errors for a how
or direction of the as-of join that is not a name
### What changes were proposed in this pull request?
A follow-up of #543 (SPARK-61496), from a review of it. The Python client's
`_joinAsOf` (`crates/pyspark-rs/src/dataframe.rs`), which #543 changed to parse
`how` and `direction` into `AsOfJoinType` and `AsOfJoinDirection`, now raises
PySpark's errors for the values that are not names. #543 says the client raises
no error that PySpark does not.
PySpark's `_joinAsOf` only asserts `isinstance(how, str)`, and does not
check `direction`. It puts both in protobuf string fields when it sends the
plan, so their errors are those of protobuf's default backend, upb
(pyspark/sql/connect/dataframe.py and plan.py `AsOfJoin`). This client builds
the plan at once, so it raises those errors at the call:
- A `how` that is a str but that UTF-8 cannot encode (a lone surrogate)
passes PySpark's assert, and raises the `UnicodeEncodeError` of its encoding.
It was the `AssertionError` "how should be a string", which says the wrong
thing of a str.
- `direction` is now taken as any value (`DefaultedOption`, with the same
signature): a str (the `UnicodeEncodeError` of a lone surrogate), bytes decoded
as UTF-8 (the `UnicodeDecodeError` of invalid ones), as upb does, where bytes
were a `TypeError`, and anything else upb's `TypeError` "bad argument type for
built-in operation". Its errors come after those of PySpark's own checks, as
the plan is sent after them.
- The doc of `PlanIds::node_of` names `root_id_of` too, among the ways a
node gets a plan ID.
### Why are the changes needed?
To match PySpark 4.3.0 with its default protobuf backend, upb. Probes with
its Connect client against a local Spark 4.3.0 server, with `left =
spark.range(3)` and `left._joinAsOf(spark.range(3), "id", "id", ...)`:
| argument | PySpark 4.3.0, raised when the plan is sent | this client
before, at the call |
|---|---|---|
| `how="a\ud800"` | `UnicodeEncodeError: 'utf-8' codec can't encode
character '\ud800' in position 1: surrogates not allowed` | `AssertionError:
how should be a string` |
| `direction="a\ud800"` | the same `UnicodeEncodeError` | the same |
| `direction=b"forward"` | no error, `forward` | `TypeError` |
| `direction=b"\xff"` | `UnicodeDecodeError: 'utf-8' codec can't decode
byte 0xff in position 0: invalid start byte` | `TypeError` |
| `direction=1`, `direction=None` | `TypeError: bad argument type for
built-in operation` | `TypeError: argument 'direction': ...` |
This client now raises PySpark's error class and message in each case, at
the call. The timing differs, as for the option strings of #550.
The probes ran without `PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION`. Protobuf's
pure-Python backend raises a `ValueError` for the lone surrogate and other
messages, but a default install of PySpark uses upb.
### Does this PR introduce _any_ user-facing change?
Yes, on unreleased changes: the errors above, and `direction` given as
UTF-8 bytes.
### How was this patch tested?
- `test_join_as_of_sends_the_as_of_join_as_pyspark`
(`python/tests/test_dropin_offline.py`) now covers each case of the table. It
fails on an extension built from master and passes with the change. Each
expected message was checked with official PySpark 4.3.0 on the upb backend.
- The offline drop-in and ML suites (2016 passed), the as-of join tests of
`test_dropin_e2e.py` against a Spark 4.3.0 server, `cargo build -p pyspark-rs
--release`, `cargo fmt --all -- --check`, `ruff check`, and
`scripts/audit_no_stubs.sh`.
### 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 #556 from HyukjinKwon/SPARK-61496-followup-asof-args.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 52 ++++++++++++++++++++++++++++++-------
crates/spark-connect/src/plan.rs | 5 ++--
python/tests/test_dropin_offline.py | 20 ++++++++++++++
3 files changed, 66 insertions(+), 11 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 52da6bd6..953498e7 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -10,7 +10,7 @@ use crate::column::PyColumn;
use crate::errors::{not_expected_type, ResultExt};
use crate::group::PyGroupedData;
use crate::interrupt::interruptible;
-use crate::options::{set_option_skip_none, set_options_skip_none};
+use crate::options::{set_option_skip_none, set_options_skip_none,
DefaultedOption};
use crate::row::{FieldConverters, NestedFieldNames};
use crate::streaming::PyDataStreamWriter;
use crate::types::PyDataType;
@@ -536,6 +536,24 @@ fn proto_string_type_error(value: &Bound<'_, PyAny>) ->
PyErr {
))
}
+/// The text of the `direction` of `_joinAsOf`, as protobuf's default upb
backend sets the string
+/// field `AsOfJoin.direction` from it when PySpark sends the plan: a str, of
which one that UTF-8
+/// cannot encode raises the `UnicodeEncodeError` of its encoding, or bytes,
decoded as UTF-8 with
+/// the `UnicodeDecodeError` of invalid ones. Any other value is upb's
`TypeError`.
+fn as_of_direction(value: &Bound<'_, PyAny>) -> PyResult<String> {
+ if value.is_instance_of::<pyo3::types::PyString>() {
+ return value.extract::<String>();
+ }
+ if value.is_instance_of::<pyo3::types::PyBytes>() {
+ return value
+ .call_method1(pyo3::intern!(value.py(), "decode"), ("utf-8",))?
+ .extract::<String>();
+ }
+ Err(pyo3::exceptions::PyTypeError::new_err(
+ "bad argument type for built-in operation",
+ ))
+}
+
/// The join condition of `_joinAsOf` for its `on`, as PySpark's `AsOfJoin`
plan sends it: a
/// name or a list of names (`using_columns`), or a Column or a list of
Columns, which are
/// joined on their conjunction (`join_expr`).
@@ -1051,7 +1069,11 @@ impl PyDataFrame {
/// default) and `direction` are not checked, as PySpark does not check
them: a string that
/// is none of the join types or directions of the core is sent as it is,
and the server
/// refuses what it does not read.
- #[pyo3(name = "_joinAsOf", signature = (other, leftAsOfColumn,
rightAsOfColumn, on=None, how=None, *, tolerance=None, allowExactMatches=true,
direction="backward"))]
+ #[pyo3(
+ name = "_joinAsOf",
+ signature = (other, leftAsOfColumn, rightAsOfColumn, on=None,
how=None, *, tolerance=None, allowExactMatches=true,
direction=DefaultedOption::Omitted),
+ text_signature = "($self, other, leftAsOfColumn, rightAsOfColumn,
on=None, how=None, *, tolerance=None, allowExactMatches=True,
direction='backward')"
+ )]
#[allow(non_snake_case, clippy::too_many_arguments)]
fn join_as_of(
&self,
@@ -1062,17 +1084,22 @@ impl PyDataFrame {
how: Option<Bound<'_, PyAny>>,
tolerance: Option<Bound<'_, PyAny>>,
allowExactMatches: bool,
- direction: &str,
+ direction: DefaultedOption,
) -> PyResult<PyDataFrame> {
// As PySpark's `_check_same_session`, first.
let other = self.same_session(other)?;
+ // As PySpark's `assert isinstance(how, str)`. A str that UTF-8 cannot
encode is one, and
+ // raises the UnicodeEncodeError of its encoding once PySpark sends
the plan, in protobuf's
+ // default upb backend; this client builds the plan here, so it raises
that error here.
let join_type = match how.filter(|how| !how.is_none()) {
None => AsOfJoinType::Inner,
- Some(how) => {
- let how = how.extract::<String>().map_err(|_| {
- pyo3::exceptions::PyAssertionError::new_err("how should be
a string")
- })?;
- AsOfJoinType::parse(&how)
+ Some(how) if how.is_instance_of::<pyo3::types::PyString>() => {
+ AsOfJoinType::parse(&how.extract::<String>()?)
+ }
+ Some(_) => {
+ return Err(pyo3::exceptions::PyAssertionError::new_err(
+ "how should be a string",
+ ))
}
};
let tolerance = match tolerance.filter(|tolerance|
!tolerance.is_none()) {
@@ -1096,7 +1123,14 @@ impl PyDataFrame {
join_type,
tolerance,
allow_exact_matches: allowExactMatches,
- direction: AsOfJoinDirection::parse(direction),
+ // PySpark does not check `direction`, so its errors come last, as
those of protobuf
+ // when the plan is sent (`as_of_direction`).
+ direction: match &direction {
+ DefaultedOption::Omitted => AsOfJoinDirection::Backward,
+ DefaultedOption::Given(direction) => {
+
AsOfJoinDirection::parse(&as_of_direction(direction.bind(leftAsOfColumn.py()))?)
+ }
+ },
};
let df = self
.dataframe
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index 23dad520..4a12fc05 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -692,8 +692,9 @@ impl PlanIds {
/// A live node of the plan ID `id`, such as that of the DataFrame of a
relation that this
/// session sent.
///
- /// A plan ID is of one node that this session numbered (`id_of`), and of
each node that
- /// was given it (`assign`): each DataFrame of a relation that the session
sent, such as
+ /// A plan ID is of one node that this session numbered (`id_of`, or
`root_id_of` for the
+ /// relation within the `WithRelations` that sends it), and of each node
that was given it
+ /// (`assign`): each DataFrame of a relation that the session sent, such as
/// each unpickled copy of a DataFrame, is a node of its own with the plan
ID of the
/// DataFrame it was of, which may be alive too. Any one of them is given,
on purpose: they
/// are all the relation of that plan ID, and each copy took the
Observations of a node of
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 52027cb2..b1e556e3 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -11175,6 +11175,26 @@ def
test_join_as_of_sends_the_as_of_join_as_pyspark(mock_connect):
with pytest.raises(AssertionError, match="^how should be a string$"):
left._joinAsOf(right, "id", "id", how=how)
+ # PySpark sends `how` and `direction` as protobuf string fields, whose
errors it raises when
+ # it sends the plan, those of protobuf's default upb backend; this client
builds the plan at
+ # once, so it raises them at the call. A str that UTF-8 cannot encode is a
str to the assert
+ # of `how`, and the UnicodeEncodeError of its encoding; a `direction` of
bytes is decoded as
+ # UTF-8, and any other value is upb's TypeError.
+ for kwargs in ({"how": "a\ud800"}, {"direction": "a\ud800"}):
+ with pytest.raises(UnicodeEncodeError) as e:
+ left._joinAsOf(right, "id", "id", **kwargs)
+ assert str(e.value) == (
+ "'utf-8' codec can't encode character '\\ud800' in position 1:
surrogates not allowed"
+ )
+ join = sent_as_of_join(left._joinAsOf(right, "id", "id",
direction=b"forward"))
+ assert join[10] == [b"forward"]
+ with pytest.raises(UnicodeDecodeError) as e:
+ left._joinAsOf(right, "id", "id", direction=b"\xff")
+ assert str(e.value) == "'utf-8' codec can't decode byte 0xff in position
0: invalid start byte"
+ for direction in (1, None):
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ left._joinAsOf(right, "id", "id", direction=direction)
+
def
test_grouping_sets_group_by_their_grouping_columns_as_pyspark(mock_connect):
# As PySpark's, groupingSets(groupingSets, *cols) groups by the sets with
the grouping
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]