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 b0a98f2c [SPARK-61398][CONNECT][PYTHON] Keep the replaced error as the
context of the done error of a progress handler, as PySpark does
b0a98f2c is described below
commit b0a98f2c3453502d5177a17ca998de8c32c2b84f
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:12:58 2026 +0900
[SPARK-61398][CONNECT][PYTHON] Keep the replaced error as the context of
the done error of a progress handler, as PySpark does
### What changes were proposed in this pull request?
[SPARK-61398](https://issues.apache.org/jira/browse/SPARK-61398): a
follow-up of #462 (SPARK-61342), from a review of it.
- When the done call of a progress handler raises after the execution
failed, the raised exception has the execution's exception as its
`__context__`, as PySpark's `Progress.__exit__` raises it. The core's
`ProgressTracker::finish_after` hands the done error to the unreturned-error
handler together with the error it replaces (`UnreturnedError::Replaced {
error, done }`), and the drop-in sets the replaced error, converted, as the
context of the done error's exception (`crates/pyspark-r [...]
- A `toLocalIterator()` dropped before its end reports its done error to
`sys.unraisablehook` with an object, the `LocalRowIterator` class, so the hook
prints an "Exception ignored in:" header, as for PySpark's generator. The
instance itself cannot be referenced while it is freed, so the header names the
class.
### Why are the changes needed?
With a handler that raises `ValueError("done-a")` on its done call,
`spark.sql("select * from no_such_table_zz").collect()` raised `ValueError:
done-a` with `__context__` None. PySpark 4.3.0 raises it with `__context__` =
`AnalysisException [TABLE_OR_VIEW_NOT_FOUND]`, and its traceback shows the
analysis error, then "During handling of the above exception, another exception
occurred". #462's description said that the drop-in keeps the context, but the
code dropped it. For a dropped it [...]
### Does this PR introduce _any_ user-facing change?
Yes. In Python, the `__context__` of a progress handler's done error and
the unraisable object of a dropped `toLocalIterator` now match PySpark (the
latter names the iterator's class). In the Rust API,
`spark_connect::progress::UnreturnedError` gets a lifetime, and its `Replaced`
variant becomes `Replaced { error, done }`, which also gives the done error.
### How was this patch tested?
- Offline tests in `python/tests/test_dropin_offline.py`: the done error
keeps the execution's `AnalysisException` as its context, and a half-consumed
iterator that is dropped hands its done error to `sys.unraisablehook` once,
with a non-None object. Both fail without the change.
- The Rust test
`progress::tests::the_error_of_the_done_call_is_the_error_of_the_execution`
checks that the done error is passed with the replaced one.
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--release --lib`, the `--no-run` builds, `cargo fmt --check`,
`scripts/audit_no_stubs.sh`, the full offline drop-in suite, and the drop-in
and Arrow e2e 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 #485 from HyukjinKwon/SPARK-61398-progress-done-error-context.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/errors.rs | 28 +++++++++++++--
crates/pyspark-rs/src/progress.rs | 16 ++++++---
crates/spark-connect/src/progress.rs | 38 ++++++++++++--------
python/tests/test_dropin_offline.py | 68 ++++++++++++++++++++++++++++++++++++
4 files changed, 129 insertions(+), 21 deletions(-)
diff --git a/crates/pyspark-rs/src/errors.rs b/crates/pyspark-rs/src/errors.rs
index 62dbd316..ba73a360 100644
--- a/crates/pyspark-rs/src/errors.rs
+++ b/crates/pyspark-rs/src/errors.rs
@@ -175,18 +175,40 @@ pub(crate) fn callback_error(exception: PyErr) ->
SparkError {
)
}
-/// The exception of the Python callback of `err`, if it is the error of one.
-fn callback_exception(err: &SparkError) -> Option<PyErr> {
+/// The ID of the exception of the Python callback that `err` is the error of,
if it is one.
+fn callback_id(err: &SparkError) -> Option<u64> {
if err.error_class != PYTHON_CALLBACK_ERROR {
return None;
}
- let id = err.params.get("callback_id")?.parse::<u64>().ok()?;
+ err.params.get("callback_id")?.parse::<u64>().ok()
+}
+
+/// The exception of the Python callback of `err`, if it is the error of one.
+fn callback_exception(err: &SparkError) -> Option<PyErr> {
+ let id = callback_id(err)?;
CALLBACK_EXCEPTIONS
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&id)
}
+/// Make `context` the `__context__` of the exception of the Python callback
that `err` is the
+/// error of, as PySpark's `Progress.__exit__` makes the exception of its body
the context of the
+/// one that it raises. An error that is not the error of a callback has no
exception to change.
+pub(crate) fn set_callback_context(py: Python<'_>, err: &SparkError, context:
PyErr) {
+ let Some(id) = callback_id(err) else {
+ return;
+ };
+ let exceptions = CALLBACK_EXCEPTIONS
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ if let Some(exception) = exceptions.get(&id) {
+ let _ = exception
+ .value(py)
+ .setattr("__context__", context.value(py));
+ }
+}
+
/// The UnicodeDecodeError of a string of the result that is not valid UTF-8,
as PySpark raises
/// it: the error of Python's own decoder of its bytes, so that the message is
the same.
fn unicode_decode_error(value: &[u8], err: &SparkError) -> PyErr {
diff --git a/crates/pyspark-rs/src/progress.rs
b/crates/pyspark-rs/src/progress.rs
index 9f75bff0..1814bdd5 100644
--- a/crates/pyspark-rs/src/progress.rs
+++ b/crates/pyspark-rs/src/progress.rs
@@ -13,6 +13,8 @@ use spark_connect::progress::ProgressUpdate;
use spark_connect::SparkSession;
use spark_connect_core::error::SparkError;
+use crate::dataframe::PyLocalRowIterator;
+
/// The progress handlers of a session, and the progress bars of its
executions.
pub(crate) struct SessionProgress {
/// The handlers, as the `_progress_handlers` list of PySpark's client.
@@ -53,7 +55,7 @@ pub(crate) fn session_progress(py: Python<'_>, session:
&SparkSession) -> Arc<Se
/// Have the core hand over the exceptions of the handlers that no caller is
left to raise: that
/// of the done call of an execution dropped before its end goes to
`sys.unraisablehook`, as
/// PySpark's generator reports it, and that of an execution that the
exception of its done call
-/// replaced, which PySpark keeps as the `__context__` of the one it raises,
is released.
+/// replaced is the `__context__` of the one the done call raises, as
PySpark's `__exit__` does.
fn install_unreturned_error_handler() {
static INSTALL: std::sync::Once = std::sync::Once::new();
INSTALL.call_once(|| {
@@ -61,10 +63,16 @@ fn install_unreturned_error_handler() {
use spark_connect::progress::UnreturnedError;
Python::attach(|py| match error {
UnreturnedError::DroppedDone(error) => {
-
crate::errors::spark_error_to_py_exception(error).write_unraisable(py, None)
+ // The iterator may be freed by now, so no reference to it
is left: its class
+ // is the object of the hook. Only a LocalRowIterator
drops an execution that
+ // calls the handlers unfinished; the other iterators do
not report progress.
+ let iterator = py.get_type::<PyLocalRowIterator>();
+ crate::errors::spark_error_to_py_exception(error)
+ .write_unraisable(py, Some(iterator.as_any()))
}
- UnreturnedError::Replaced(error) => {
- drop(crate::errors::spark_error_to_py_exception(error))
+ UnreturnedError::Replaced { error, done } => {
+ let context =
crate::errors::spark_error_to_py_exception(error);
+ crate::errors::set_callback_context(py, done, context);
}
})
});
diff --git a/crates/spark-connect/src/progress.rs
b/crates/spark-connect/src/progress.rs
index 6e9e1bd0..aefc09b3 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -47,18 +47,21 @@ pub struct ProgressUpdate {
/// The error of a progress handler that no caller is left to return to.
#[derive(Debug)]
-pub enum UnreturnedError {
+pub enum UnreturnedError<'a> {
/// The error of the done call of an execution dropped before its end, as
an iterator that
/// its caller stopped reading: PySpark's generator reports the exception
of its
/// `Progress.__exit__` as unraisable then.
DroppedDone(SparkError),
- /// The error of an execution that the error of its done call replaced: as
the exception of
- /// PySpark's `Progress.__exit__` replaces that of the body of its `with`,
which it keeps as
- /// the `__context__` of the one it raises.
- Replaced(SparkError),
+ /// The error of an execution that the error of its done call, `done`,
replaced: as the
+ /// exception of PySpark's `Progress.__exit__` replaces that of the body
of its `with`, which
+ /// it keeps as the `__context__` of the one it raises.
+ Replaced {
+ error: SparkError,
+ done: &'a SparkError,
+ },
}
-type UnreturnedErrorHandler = Arc<dyn Fn(UnreturnedError) + Send + Sync>;
+type UnreturnedErrorHandler = Arc<dyn for<'a> Fn(UnreturnedError<'a>) + Send +
Sync>;
static UNRETURNED_ERROR_HANDLER:
std::sync::Mutex<Option<UnreturnedErrorHandler>> =
std::sync::Mutex::new(None);
@@ -66,13 +69,15 @@ static UNRETURNED_ERROR_HANDLER:
std::sync::Mutex<Option<UnreturnedErrorHandler>
/// Set what becomes of the errors of progress handlers that no caller is left
to return to (see
/// [`UnreturnedError`]), for every session; by default they are dropped. The
Python client
/// reports a dropped execution's to `sys.unraisablehook`, as PySpark does.
-pub fn set_unreturned_error_handler(handler: impl Fn(UnreturnedError) + Send +
Sync + 'static) {
+pub fn set_unreturned_error_handler(
+ handler: impl for<'a> Fn(UnreturnedError<'a>) + Send + Sync + 'static,
+) {
*UNRETURNED_ERROR_HANDLER
.lock()
.unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(handler));
}
-fn hand_over(error: UnreturnedError) {
+fn hand_over(error: UnreturnedError<'_>) {
let handler = UNRETURNED_ERROR_HANDLER
.lock()
.unwrap_or_else(|e| e.into_inner())
@@ -128,7 +133,7 @@ impl ProgressTracker {
match self.finish() {
Ok(()) => error,
Err(done) => {
- hand_over(UnreturnedError::Replaced(error));
+ hand_over(UnreturnedError::Replaced { error, done: &done });
done
}
}
@@ -428,14 +433,16 @@ mod tests {
let handed = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&handed);
set_unreturned_error_handler(move |error| {
- let (kind, error) = match error {
- UnreturnedError::DroppedDone(error) => ("dropped", error),
- UnreturnedError::Replaced(error) => ("replaced", error),
+ let (kind, error, done) = match error {
+ UnreturnedError::DroppedDone(error) => ("dropped", error,
String::new()),
+ UnreturnedError::Replaced { error, done } => {
+ ("replaced", error, format!(" after {}", done.message()))
+ }
};
if error.message().starts_with("s16") {
sink.lock()
.unwrap()
- .push(format!("{kind}: {}", error.message()));
+ .push(format!("{kind}: {}{done}", error.message()));
}
});
@@ -453,7 +460,10 @@ mod tests {
assert_eq!(done_calls.load(Ordering::SeqCst), 3);
assert_eq!(
*handed.lock().unwrap(),
- vec!["replaced: s16 execution failed", "dropped: s16 done failed"]
+ vec![
+ "replaced: s16 execution failed after s16 done failed",
+ "dropped: s16 done failed"
+ ]
);
session.remove_progress_handler(id);
}
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 4fe6cb51..91cbd3c3 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -13219,6 +13219,74 @@ def
test_the_exception_of_a_done_call_fails_the_execution_as_pyspark(mock_connec
assert spark.range(1).collect() == []
+def
test_the_done_error_of_a_progress_handler_keeps_the_execution_error_as_context(mock_connect):
+ # As PySpark's Progress.__exit__: a done call that raises after the
execution failed raises
+ # its own exception, with the exception of the execution as its
__context__.
+ from pyspark.errors import AnalysisException
+
+ spark, service = mock_connect
+ classes = ["org.apache.spark.sql.AnalysisException", "java.lang.Exception"]
+ service.execute_error = ("[TABLE_OR_VIEW_NOT_FOUND] t", classes[0],
+ _error_info(classes,
errorClass="TABLE_OR_VIEW_NOT_FOUND"))
+ error = ValueError("done-a")
+
+ def failing(**kwargs):
+ if kwargs["done"]:
+ raise error
+
+ spark.registerProgressHandler(failing)
+ try:
+ with pytest.raises(ValueError) as raised:
+ spark.range(1).collect()
+ finally:
+ service.execute_error = None
+ spark.removeProgressHandler(failing)
+ assert raised.value is error
+ assert isinstance(raised.value.__context__, AnalysisException)
+ assert "TABLE_OR_VIEW_NOT_FOUND" in str(raised.value.__context__)
+
+
+def
test_a_dropped_local_iterator_hands_the_done_error_to_unraisablehook_with_an_object(
+ mock_connect, monkeypatch):
+ # As PySpark's generator of toLocalIterator, which is closed with its
execution unfinished:
+ # its done call raises, and the error goes to sys.unraisablehook with an
object, which the
+ # hook prints as the "Exception ignored in:" header.
+ import sys
+
+ pa = pytest.importorskip("pyarrow")
+
+ spark, service = mock_connect
+ # ExecutePlanResponse.arrow_batch=2: row_count=3, data=2, with three rows,
so that the
+ # iterator is left with rows when it is dropped, before the end of the
execution.
+ batch = pa.record_batch([pa.array([1, 2, 3])], names=["id"])
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, batch.schema) as writer:
+ writer.write_batch(batch)
+ service.execute_payload = message_field(2, varint_field(1, 3)
+ + message_field(2,
sink.getvalue().to_pybytes()))
+ unraisable = []
+ monkeypatch.setattr(sys, "unraisablehook", unraisable.append)
+ error = ValueError("done-b")
+
+ def failing(**kwargs):
+ if kwargs["done"]:
+ raise error
+
+ spark.registerProgressHandler(failing)
+ try:
+ rows = spark.range(3).toLocalIterator()
+ iterator_type = type(rows)
+ assert next(rows) is not None
+ rows = None
+ finally:
+ spark.removeProgressHandler(failing)
+ service.execute_payload = b""
+ assert len(unraisable) == 1
+ assert unraisable[0].exc_value is error
+ assert unraisable[0].object is not None
+ assert unraisable[0].object is iterator_type
+
+
def
test_progress_handler_that_runs_queries_without_end_is_bounded(mock_connect,
monkeypatch):
# A handler that runs a query for each progress of an execution nests the
executions past
# the bound of nested callbacks: the query past it fails with a
RecursionError, which the
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]