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 867c215e [SPARK-61389][CONNECT] Parse the port of the connection
string as urllib does, and raise the builtin ValueError for a bad port or
keepalive value, as PySpark does, in Spark Connect Rust
867c215e is described below
commit 867c215eda4082554879ee260d9ec19907526562
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 08:49:32 2026 +0900
[SPARK-61389][CONNECT] Parse the port of the connection string as urllib
does, and raise the builtin ValueError for a bad port or keepalive value, as
PySpark does, in Spark Connect Rust
### What changes were proposed in this pull request?
[SPARK-61389](https://issues.apache.org/jira/browse/SPARK-61389): a
follow-up of #439 (SPARK-61319) and #469 (SPARK-61362), from a review of #439.
The port of a Spark Connect connection string is now read as
`urllib.parse`'s `port` reads it, ASCII digits only within 0-65535
(`channel.rs`, new `parse_port`):
- An out-of-range port, including an overflowing run of digits, gives `Port
out of range 0-65535`.
- Any other port gives `Port could not be cast to integer value as
'<value>'`, with the value repr-quoted and no URL. The token redaction of #439
is unchanged.
- An empty port is still the default, and `0080` is 80.
The errors that PySpark raises as the builtin `ValueError`, the port errors
and the keepalive `int()` error of #469, now have a
`SparkErrorKind::BuiltinValueError`. The Python drop-in raises them as the
builtin `ValueError`, not `PySparkValueError`, as the `RecursionError` and
`UnicodeDecodeError` kinds do.
### Why are the changes needed?
Before,
`SparkSession.builder.remote("sc://localhost:99999/;token=SECRET").create()`
raised `PySparkValueError: Port could not be cast to integer value as '99999'`.
PySpark 4.3.0 raises `ValueError: Port out of range 0-65535`. A port with a
leading `+` (`sc://localhost:+80/`) was accepted, because Rust's integer parser
allows a sign; urllib rejects it. Checked against the reference with `99999`,
`65536`, `01234567890123456789`, `+80`, `notaport`, `abc`, `8 0`, `-1`, `1_0`,
`%38%30`, ` [...]
### Does this PR introduce _any_ user-facing change?
Yes, for bad connection strings only. The port error messages change as
above, a port with a sign is rejected, and these errors and the keepalive one
are the builtin `ValueError`. `PySparkValueError` is a subclass of
`ValueError`, so `except ValueError` keeps working, but `type(e)` changes.
### How was this patch tested?
- Rust unit tests in `channel.rs` for each port case, with the exact
messages and kind. The keepalive kind assertions in `channel.rs` and
`client.rs` are updated.
- An offline Python test,
`test_create_raises_for_a_port_that_urllib_rejects_as_pyspark`, that checks the
exact type and message against PySpark 4.3.0's.
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--release --lib`, the `--no-run` builds, `cargo fmt --check`, and the offline
and e2e drop-in suites against a Spark 4.3.0 server.
### 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 #479 from HyukjinKwon/SPARK-61389-connection-string-parity.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/errors.rs | 5 ++
crates/spark-connect-core/src/channel.rs | 101 +++++++++++++++++++++++++++----
crates/spark-connect-core/src/client.rs | 2 +-
crates/spark-connect-core/src/error.rs | 11 ++++
python/tests/test_dropin_offline.py | 17 ++++++
5 files changed, 122 insertions(+), 14 deletions(-)
diff --git a/crates/pyspark-rs/src/errors.rs b/crates/pyspark-rs/src/errors.rs
index 42129246..62dbd316 100644
--- a/crates/pyspark-rs/src/errors.rs
+++ b/crates/pyspark-rs/src/errors.rs
@@ -11,6 +11,7 @@ fn kind_to_pyspark_class_name(kind: SparkErrorKind) ->
&'static str {
match kind {
// PySpark builtin-like errors (these also subclass the Python
builtins)
SparkErrorKind::ValueError => "PySparkValueError",
+ SparkErrorKind::BuiltinValueError => "ValueError",
SparkErrorKind::TypeError => "PySparkTypeError",
SparkErrorKind::IndexError => "PySparkIndexError",
SparkErrorKind::AttributeError => "PySparkAttributeError",
@@ -207,6 +208,10 @@ pub fn spark_error_to_py_exception(err: SparkError) ->
PyErr {
// A builtin, as PySpark's recursion limit raises it.
return pyo3::exceptions::PyRecursionError::new_err(err.message());
}
+ if err.kind == SparkErrorKind::BuiltinValueError {
+ // A builtin, as the `int()` or `urllib` of the connection string
raises it.
+ return exceptions::PyValueError::new_err(err.message());
+ }
if let Some(value) = err.invalid_utf8_value() {
return unicode_decode_error(&value, &err);
}
diff --git a/crates/spark-connect-core/src/channel.rs
b/crates/spark-connect-core/src/channel.rs
index ba6e9d26..b3aa2862 100644
--- a/crates/spark-connect-core/src/channel.rs
+++ b/crates/spark-connect-core/src/channel.rs
@@ -288,7 +288,7 @@ impl ChannelBuilder {
] {
match self.params.get(key) {
Some(value) if python_int(value).is_none() => {
- return Err(SparkError::value_msg(format!(
+ return Err(SparkError::builtin_value_msg(format!(
"invalid literal for int() with base 10: {}",
python_repr(value)
)));
@@ -486,21 +486,30 @@ fn parse_authority(authority: &str, shown_url: &str) ->
Result<(String, u16)> {
let port = match port_str {
None | Some("") => DEFAULT_PORT,
- // As urllib's message (`Port could not be cast to integer value as
'...'`), with no URL.
- Some(p) => p.parse::<u16>().map_err(|_| {
- SparkError::value(
- "INVALID_CONNECT_URL",
- &[(
- "detail",
- &format!("Port could not be cast to integer value as
'{p}'"),
- )],
- )
- })?,
+ Some(p) => parse_port(p)?,
};
Ok((host, port))
}
+/// The port of a connection string as `urllib.parse`'s `port` reads it: ASCII
digits, within
+/// 0-65535. Its messages are those of its ValueError, which the reference
client raises
+/// unwrapped and without the URL.
+fn parse_port(text: &str) -> Result<u16> {
+ if !text.bytes().all(|b| b.is_ascii_digit()) {
+ return Err(SparkError::builtin_value_msg(format!(
+ "Port could not be cast to integer value as {}",
+ python_repr(text)
+ )));
+ }
+ // Saturating, so that a long run of digits is out of range rather than
wrapping around.
+ let port = text.bytes().fold(0u64, |port, digit| {
+ port.saturating_mul(10)
+ .saturating_add(u64::from(digit - b'0'))
+ });
+ u16::try_from(port).map_err(|_| SparkError::builtin_value_msg("Port out of
range 0-65535"))
+}
+
/// Decode `%XX` percent-escapes (CPython `urllib.parse.unquote`).
fn unquote(s: &str) -> String {
let bytes = s.as_bytes();
@@ -676,7 +685,7 @@ mod tests {
let error = c.check_keepalive().unwrap_err();
assert_eq!(
error.kind,
- crate::error::SparkErrorKind::ValueError,
+ crate::error::SparkErrorKind::BuiltinValueError,
"{params}"
);
assert_eq!(
@@ -696,6 +705,72 @@ mod tests {
}
}
+ #[test]
+ fn port_is_read_as_urllib_reads_it() {
+ // `urllib.parse`'s `port`: ASCII digits only, within 0-65535, else a
ValueError. Its
+ // messages are a builtin ValueError's, which the reference client
raises unwrapped.
+ for (port, expected) in [
+ ("15003", 15003),
+ ("0080", 80),
+ ("0", 0),
+ ("65535", 65535),
+ ("", DEFAULT_PORT), // no port, or an empty one
+ ] {
+ let c =
ChannelBuilder::parse(&format!("sc://localhost:{port}/;token=SECRET")).unwrap();
+ assert_eq!(c.port(), expected, "{port}");
+ }
+ for (url, message) in [
+ ("sc://localhost:99999/", "Port out of range 0-65535"),
+ ("sc://localhost:65536", "Port out of range 0-65535"),
+ (
+ "sc://localhost:01234567890123456789",
+ "Port out of range 0-65535",
+ ),
+ ("sc://[::1]:99999/", "Port out of range 0-65535"),
+ (
+ "sc://localhost:+80/",
+ "Port could not be cast to integer value as '+80'",
+ ),
+ (
+ "sc://localhost:-1/",
+ "Port could not be cast to integer value as '-1'",
+ ),
+ (
+ "sc://localhost:8 0/",
+ "Port could not be cast to integer value as '8 0'",
+ ),
+ (
+ "sc://localhost:80x/",
+ "Port could not be cast to integer value as '80x'",
+ ),
+ (
+ "sc://localhost:1_0/",
+ "Port could not be cast to integer value as '1_0'",
+ ),
+ (
+ "sc://localhost:%38%30/",
+ "Port could not be cast to integer value as '%38%30'",
+ ),
+ (
+ "sc://[::1]:x/",
+ "Port could not be cast to integer value as 'x'",
+ ),
+ // Not ASCII digits, even when they are the Arabic-Indic one and
two.
+ (
+ "sc://localhost:\u{0661}\u{0662}/",
+ "Port could not be cast to integer value as
'\u{0661}\u{0662}'",
+ ),
+ ] {
+ let e = ChannelBuilder::parse(url).unwrap_err();
+ assert_eq!(
+ e.kind,
+ crate::error::SparkErrorKind::BuiltinValueError,
+ "{url}"
+ );
+ assert_eq!(e.message(), message, "{url}");
+ }
+ }
+
#[test]
fn user_agent_names_the_os_as_pyspark() {
// As Python's `platform.uname().system.lower()`.
@@ -737,7 +812,7 @@ mod tests {
fn parse_errors_do_not_echo_the_token() {
// A bad port names the port only, as PySpark's message does; the URL
is not quoted.
let e =
ChannelBuilder::parse("sc://localhost:notaport/;token=SECRET").unwrap_err();
- assert_eq!(e.error_class, "INVALID_CONNECT_URL");
+ assert_eq!(e.kind, crate::error::SparkErrorKind::BuiltinValueError);
let shown = e.to_string();
assert!(
shown.contains("Port could not be cast to integer value as
'notaport'"),
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index 9a026657..2a3c669e 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -3678,7 +3678,7 @@ mod request_fields_tests {
.await
.err()
.expect("a keepalive time that is not an integer must raise");
- assert_eq!(error.kind, SparkErrorKind::ValueError);
+ assert_eq!(error.kind, SparkErrorKind::BuiltinValueError);
assert_eq!(
error.message(),
"invalid literal for int() with base 10: 'abc'"
diff --git a/crates/spark-connect-core/src/error.rs
b/crates/spark-connect-core/src/error.rs
index 71a2a6ed..ccf28ca3 100644
--- a/crates/spark-connect-core/src/error.rs
+++ b/crates/spark-connect-core/src/error.rs
@@ -277,6 +277,9 @@ pub enum SparkErrorKind {
RecursionError,
/// ``UnicodeDecodeError``, a Python builtin: a string of the result is
not valid UTF-8.
UnicodeDecode,
+ /// ``ValueError``, a Python builtin: a connection-string value that
`int()` or `urllib`
+ /// rejects, which the reference client raises unwrapped rather than as a
`PySparkValueError`.
+ BuiltinValueError,
/// ``pyspark.errors.exceptions.base.SparkRuntimeException``
SparkRuntime,
/// ``pyspark.errors.exceptions.base.SparkUpgradeException``
@@ -350,6 +353,14 @@ impl SparkError {
}
}
+ /// Create a `BuiltinValueError`-kind error with a plain message: a
`ValueError` of the Python
+ /// builtin, which is what `int()` and `urllib` raise, as the reference
client lets them.
+ pub fn builtin_value_msg(message: impl Into<String>) -> Self {
+ let mut error = Self::value_msg(message);
+ error.kind = SparkErrorKind::BuiltinValueError;
+ error
+ }
+
/// Create a RecursionError-kind error with a plain message (no error
class).
pub fn recursion_msg(message: impl Into<String>) -> Self {
Self {
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 7d3a86a4..b253b4e2 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -3383,6 +3383,23 @@ def
test_create_raises_for_a_keepalive_param_that_is_not_an_integer_as_pyspark()
assert str(error.value) == "invalid literal for int() with base 10: 'abc'"
+def test_create_raises_for_a_port_that_urllib_rejects_as_pyspark():
+ # As PySpark's channel builder, whose port (urllib's) raises a ValueError
of the builtin
+ # when the session is made, with no URL and no token in the message.
+ from pyspark.sql import SparkSession
+
+ for url, message in [
+ ("sc://localhost:99999/;token=SECRET", "Port out of range 0-65535"),
+ ("sc://localhost:+80/;token=SECRET", "Port could not be cast to
integer value as '+80'"),
+ ("sc://localhost:notaport/;token=SECRET",
+ "Port could not be cast to integer value as 'notaport'"),
+ ]:
+ with pytest.raises(ValueError) as error:
+ SparkSession.builder.remote(url).create()
+ assert type(error.value) is ValueError, url
+ assert str(error.value) == message, url
+
+
def
test_the_plan_of_a_dataframe_that_a_hook_puts_in_is_compressed_as_pyspark(mock_connect):
# As PySpark's hook, which would put in the plan of `to_proto`, which
compresses it: the plan
# of a DataFrame that an on_execute_plan hook puts in is sent compressed
over the threshold.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]