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 4bb13e19 [SPARK-61342][CONNECT][PYTHON] Raise the exception of the 
done call of a progress handler from the execution, as PySpark does
4bb13e19 is described below

commit 4bb13e19d9f6766ed33d7b9efb27ca253128303d
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 17:35:42 2026 +0900

    [SPARK-61342][CONNECT][PYTHON] Raise the exception of the done call of a 
progress handler from the execution, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61342](https://issues.apache.org/jira/browse/SPARK-61342): the 
exception of the done call of a progress handler is raised from the execution, 
as PySpark raises it.
    
    - Core (`crates/spark-connect/src/progress.rs`):
      - `ProgressTracker::finish` makes the done call once.
      - `ExecutionStream::message` calls it when the stream ends, and when it 
fails (the stream, the update of a handler, or the chunks of a batch).
      - `SparkSession::execute_plan` calls it when the execution fails to start.
      - Its error is the error of the execution, and replaces the execution's 
own error, as the exception of PySpark's `Progress.__exit__` does.
    - An execution dropped before its end (an iterator its caller stopped 
reading) still gets its done call on drop. Its error has no caller left, so it 
goes to the new `spark_connect::progress::set_unreturned_error_handler`; an 
error that a done error replaced goes there too.
    - The drop-in (`crates/pyspark-rs/src/progress.rs`):
      - returns the done-call exception like any other, to be raised from the 
execution;
      - installs a handler that reports a dropped execution's exception to 
`sys.unraisablehook`, as PySpark's generator does;
      - releases a replaced one, which PySpark keeps as the `__context__` of 
the one it raises.
    - Executions that PySpark runs without a `Progress` no longer call the 
handlers:
      - the registrations of functions, table functions, data sources and Java 
functions (its `_execute`), through the new `execute_command_unreported`;
      - pipeline runs (its `execute_command_as_iterator`);
      - the drop-in's removal of a server listener before a new add, which 
PySpark does not send.
    - `register_fallible_progress_handler` documents the done-call error.
    
    ### Why are the changes needed?
    
    When a progress handler raised on its done call, the drop-in returned the 
result of the execution and sent the exception to `sys.unraisablehook`. That 
happened for collect, toPandas, toArrow, toLocalIterator, count, first, 
isEmpty, show, writes, spark.sql, catalog calls and foreachPartition. PySpark 
4.3.0 raises it from all of them:
    - Its done call is made in `Progress.__exit__`, inside the `with` of the 
execution (`_execute_and_fetch` and `to_table_as_iterator` of `client/core.py`).
    - So the exception goes out of the call, and replaces the execution's error 
when there is one.
    
    The Rust API dropped the done-call error of a fallible handler.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes:
    - A progress handler that raises on its done call now fails the execution 
with its exception, as in PySpark, and it replaces the execution's own error.
    - The registrations of functions, table functions, data sources and Java 
functions, and pipeline runs, no longer call the progress handlers, as in 
PySpark.
    - In the Rust API, `set_unreturned_error_handler` and `UnreturnedError` are 
new.
    
    ### How was this patch tested?
    
    - Offline (`python/tests/test_dropin_offline.py`): 
`test_the_exception_of_a_done_call_fails_the_execution_as_pyspark`.
      - The done exception goes out of collect and toLocalIterator (with and 
without prefetch), and not to `sys.unraisablehook`.
      - It replaces the error of an execution that fails.
      - A UDF registration makes no handler call.
      - The existing test that asserted the unraisable done exception now 
asserts the raise.
      - Both fail without the change.
    - Live (`python/tests/test_dropin_e2e.py`): 
`test_the_exception_of_a_done_call_fails_the_execution_as_pyspark`. It fails 
without the change.
    - Rust (`progress.rs`): 
`the_error_of_the_done_call_is_the_error_of_the_execution`.
      - `finish` calls once, and its error replaces the execution's.
      - A tracker dropped before its end hands its error over.
    - The reviewer's probes against official PySpark 4.3.0 now match, apart 
from the number of progress updates, which depends on server timing:
      - the done exception on 16 entry points, both modes;
      - no done call for the registrations;
      - an iterator closed early.
    - Checks:
      - lib tests of both crates (717 passed);
      - the build of all tests (also `wasm-udf`, `datafusion,polars`) without 
warnings;
      - `cargo fmt --all --check`, and clippy with no diagnostics on the 
changed lines;
      - the offline Python suites (2980 passed, 8 skipped);
      - the live drop-in, Arrow and ML suites against a local Spark 4.3.0 
server (255 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.
    
    Closes #462 from HyukjinKwon/s16-progress-done-error.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/progress.rs     |  37 ++++++---
 crates/spark-connect/src/dataframe.rs |  43 ++++++----
 crates/spark-connect/src/pipelines.rs |   4 +-
 crates/spark-connect/src/progress.rs  | 151 +++++++++++++++++++++++++++++++---
 crates/spark-connect/src/session.rs   |  24 ++++--
 crates/spark-connect/src/streaming.rs |  20 +++--
 python/tests/test_dropin_e2e.py       |  29 +++++++
 python/tests/test_dropin_offline.py   |  58 ++++++++++++-
 8 files changed, 313 insertions(+), 53 deletions(-)

diff --git a/crates/pyspark-rs/src/progress.rs 
b/crates/pyspark-rs/src/progress.rs
index a53fa8b1..9f75bff0 100644
--- a/crates/pyspark-rs/src/progress.rs
+++ b/crates/pyspark-rs/src/progress.rs
@@ -45,10 +45,32 @@ pub(crate) fn session_progress(py: Python<'_>, session: 
&SparkSession) -> Arc<Se
     });
     let shared = Arc::clone(&progress);
     session.register_fallible_progress_handler(move |update| 
shared.notify(update));
+    install_unreturned_error_handler();
     registry.insert(id, Arc::clone(&progress));
     progress
 }
 
+/// 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.
+fn install_unreturned_error_handler() {
+    static INSTALL: std::sync::Once = std::sync::Once::new();
+    INSTALL.call_once(|| {
+        spark_connect::progress::set_unreturned_error_handler(|error| {
+            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)
+                }
+                UnreturnedError::Replaced(error) => {
+                    drop(crate::errors::spark_error_to_py_exception(error))
+                }
+            })
+        });
+    });
+}
+
 /// Forget the progress of a stopped session.
 pub(crate) fn forget_session(session: &SparkSession) {
     registry()
@@ -90,21 +112,16 @@ impl SessionProgress {
     }
 
     /// Call the handlers with `update`. The exception of a handler fails the 
execution that
-    /// called it, and is raised in its caller, as PySpark's result loop 
raises it. The done call
-    /// is the last of the execution, which has no caller left: its exception 
goes to
-    /// `sys.unraisablehook`.
+    /// called it, and is raised in its caller, as PySpark's result loop 
raises it; that of the
+    /// done call too, as PySpark's `Progress.__exit__` raises it from the 
execution.
     fn notify(&self, update: &ProgressUpdate) -> Result<(), SparkError> {
         let bar = progress_bar_enabled();
         if self.count.load(Ordering::SeqCst) == 0 && !bar {
             return Ok(());
         }
-        Python::attach(|py| match self.notify_python(py, update, bar) {
-            Ok(()) => Ok(()),
-            Err(error) if update.done => {
-                error.write_unraisable(py, None);
-                Ok(())
-            }
-            Err(error) => Err(crate::errors::callback_error(error)),
+        Python::attach(|py| {
+            self.notify_python(py, update, bar)
+                .map_err(crate::errors::callback_error)
         })
     }
 
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 170f0724..2225c2aa 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -2570,25 +2570,26 @@ pub(crate) fn build_input_relation(
     crate::plan::relation_with_ids(plan, session.plan_ids())
 }
 
-/// Execute a `Command` against the server and drain the response stream.
-///
-/// Writes (and other side-effecting operations) are modeled as commands rather
-/// than relations, so they are submitted through an `ExecutePlanRequest` whose
-/// plan carries a `Command` and produce no rows to collect.
-pub(crate) fn execute_command(
+/// Execute a `Command` against the server and drain the response stream, 
returning the
+/// collected responses so callers can read a command result (e.g. 
`CheckpointCommandResult`,
+/// `WriteStreamOperationStartResult`). Writes (and other side-effecting 
operations) are modeled
+/// as commands rather than relations, so they are submitted through an 
`ExecutePlanRequest`
+/// whose plan carries a `Command`.
+pub(crate) fn execute_command_collect(
     session: &SparkSession,
     command_type: proto::command::CommandType,
-) -> Result<()> {
-    execute_command_collect(session, command_type).map(|_| ())
+) -> Result<Vec<proto::ExecutePlanResponse>> {
+    execute_command_with_info(session, command_type).map(|(responses, _)| 
responses)
 }
 
-/// Like `execute_command`, but returns the collected responses so callers can 
read
-/// a command result (e.g. `CheckpointCommandResult`, 
`WriteStreamOperationStartResult`).
-pub(crate) fn execute_command_collect(
+/// Like `execute_command_collect`, for a command that PySpark runs without a 
`Progress` (its
+/// `_execute`, of the registrations of functions, table functions and data 
sources): the
+/// progress of its execution, and its done call, does not reach the progress 
handlers.
+pub(crate) fn execute_command_unreported(
     session: &SparkSession,
     command_type: proto::command::CommandType,
-) -> Result<Vec<proto::ExecutePlanResponse>> {
-    execute_command_with_info(session, command_type).map(|(responses, _)| 
responses)
+) -> Result<()> {
+    execute_command_reporting(session, command_type, false).map(|_| ())
 }
 
 /// Like `execute_command_collect`, and also returns the information of the 
execution, which
@@ -2596,6 +2597,16 @@ pub(crate) fn execute_command_collect(
 pub(crate) fn execute_command_with_info(
     session: &SparkSession,
     command_type: proto::command::CommandType,
+) -> Result<(Vec<proto::ExecutePlanResponse>, ExecutionInfo)> {
+    execute_command_reporting(session, command_type, true)
+}
+
+/// The command `command_type`, executed with its progress for the progress 
handlers when
+/// `reported`.
+fn execute_command_reporting(
+    session: &SparkSession,
+    command_type: proto::command::CommandType,
+    reported: bool,
 ) -> Result<(Vec<proto::ExecutePlanResponse>, ExecutionInfo)> {
     let mut command = proto::Command::default();
     command.command_type = Some(command_type);
@@ -2609,7 +2620,11 @@ pub(crate) fn execute_command_with_info(
     request.tags = session.tags();
     request.plan = Some(plan);
 
-    let mut stream = session.execute_plan(request)?;
+    let mut stream = if reported {
+        session.execute_plan(request)?
+    } else {
+        session.execute_plan_unreported(request)?
+    };
     // Drain the response stream so the command runs to completion server-side,
     // capturing any metrics/progress emitted along the way.
     let mut info = ExecutionInfo::default();
diff --git a/crates/spark-connect/src/pipelines.rs 
b/crates/spark-connect/src/pipelines.rs
index ae272c34..c27f4472 100644
--- a/crates/spark-connect/src/pipelines.rs
+++ b/crates/spark-connect/src/pipelines.rs
@@ -240,7 +240,9 @@ impl PipelineRunStream {
                 .request
                 .take()
                 .expect("pipeline run stream already exhausted its request");
-            self.stream = Some(self.session.execute_plan(request)?);
+            // As PySpark's `execute_command_as_iterator`, which runs a 
pipeline without a
+            // `Progress`: the progress of the run does not reach the progress 
handlers.
+            self.stream = Some(self.session.execute_plan_unreported(request)?);
         }
         block_on(self.stream.as_mut().unwrap().message())
     }
diff --git a/crates/spark-connect/src/progress.rs 
b/crates/spark-connect/src/progress.rs
index 9f78f8dd..f8c0f0a6 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -5,7 +5,7 @@
 use std::sync::Arc;
 
 use spark_connect_core::client::ReattachableResponseStream;
-use spark_connect_core::error::Result;
+use spark_connect_core::error::{Result, SparkError};
 use spark_connect_core::runtime::CallbackGuard;
 use spark_connect_proto as proto;
 
@@ -45,12 +45,51 @@ pub struct ProgressUpdate {
     pub done: bool,
 }
 
+/// The error of a progress handler that no caller is left to return to.
+#[derive(Debug)]
+pub enum UnreturnedError {
+    /// 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),
+}
+
+type UnreturnedErrorHandler = Arc<dyn Fn(UnreturnedError) + Send + Sync>;
+
+static UNRETURNED_ERROR_HANDLER: 
std::sync::Mutex<Option<UnreturnedErrorHandler>> =
+    std::sync::Mutex::new(None);
+
+/// 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) {
+    *UNRETURNED_ERROR_HANDLER
+        .lock()
+        .unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(handler));
+}
+
+fn hand_over(error: UnreturnedError) {
+    let handler = UNRETURNED_ERROR_HANDLER
+        .lock()
+        .unwrap_or_else(|e| e.into_inner())
+        .clone();
+    if let Some(handler) = handler {
+        handler(error);
+    }
+}
+
 /// The progress of one execution, as PySpark's `Progress` of the execution of 
a request.
 pub(crate) struct ProgressTracker {
     handlers: ProgressHandlers,
     operation_id: Option<String>,
     stages: Vec<StageInfo>,
     inflight_tasks: i64,
+    /// Whether the done call was made.
+    finished: bool,
 }
 
 impl ProgressTracker {
@@ -69,6 +108,29 @@ impl ProgressTracker {
             operation_id,
             stages: Vec::new(),
             inflight_tasks: 0,
+            finished: false,
+        }
+    }
+
+    /// The done call of the handlers, as PySpark's `Progress.__exit__` makes 
it when its
+    /// execution ends, also of an error: made once. Its error is the error of 
the execution, as
+    /// the exception of `__exit__` is raised from the execution.
+    pub(crate) fn finish(&mut self) -> Result<()> {
+        if std::mem::replace(&mut self.finished, true) {
+            return Ok(());
+        }
+        self.notify(true)
+    }
+
+    /// The error of an execution that ends with `error`, after the done call: 
the error of the
+    /// done call replaces it, as the exception of PySpark's 
`Progress.__exit__` does.
+    pub(crate) fn finish_after(&mut self, error: SparkError) -> SparkError {
+        match self.finish() {
+            Ok(()) => error,
+            Err(done) => {
+                hand_over(UnreturnedError::Replaced(error));
+                done
+            }
         }
     }
 
@@ -122,13 +184,16 @@ impl ProgressTracker {
 }
 
 impl Drop for ProgressTracker {
-    /// As PySpark's `Progress.finish` when its execution ends, also of an 
error. While a panic
-    /// unwinds, a handler is not called: one that panics again would abort 
the process. An
-    /// error of the done call has no caller left to return to, so it is 
dropped here; the
-    /// handlers of the drop-in report theirs themselves.
+    /// The done call of an execution dropped before its end, as PySpark's 
`Progress.finish` of a
+    /// generator that its caller closed: an error of it has no caller left to 
return to, so it
+    /// is handed over as [`UnreturnedError::DroppedDone`]. While a panic 
unwinds, a handler is
+    /// not called: one that panics again would abort the process.
     fn drop(&mut self) {
-        if !std::thread::panicking() {
-            let _ = self.notify(true);
+        if !self.finished && !std::thread::panicking() {
+            self.finished = true;
+            if let Err(error) = self.notify(true) {
+                hand_over(UnreturnedError::DroppedDone(error));
+            }
         }
     }
 }
@@ -153,16 +218,30 @@ impl ExecutionStream {
     /// The next response of the execution, as 
`ReattachableResponseStream::message`, with the
     /// chunks of an Arrow batch joined into the batch: the response of a 
chunk that is not the
     /// last one has no batch.
+    /// When the execution ends, of its result or of an error, the handlers 
get their done call,
+    /// whose error is the error of the execution, as PySpark's 
`Progress.__exit__` raises it.
     pub(crate) async fn message(&mut self) -> 
Result<Option<proto::ExecutePlanResponse>> {
-        let response = self.stream.message().await?;
+        let response = match self.stream.message().await {
+            Ok(response) => response,
+            Err(error) => return Err(self.progress.finish_after(error)),
+        };
         if let Some(response) = &response {
             if let 
Some(proto::execute_plan_response::ResponseType::ExecutionProgress(progress)) =
                 &response.response_type
             {
-                self.progress.update(progress, &response.operation_id)?;
+                if let Err(error) = self.progress.update(progress, 
&response.operation_id) {
+                    return Err(self.progress.finish_after(error));
+                }
             }
         }
-        self.chunks.join(response)
+        match self.chunks.join(response) {
+            Ok(None) => {
+                self.progress.finish()?;
+                Ok(None)
+            }
+            Ok(Some(response)) => Ok(Some(response)),
+            Err(error) => Err(self.progress.finish_after(error)),
+        }
     }
 }
 
@@ -296,6 +375,57 @@ mod tests {
         session.remove_progress_handler(after);
     }
 
+    /// As PySpark's `Progress.__exit__`: the done call is made once and its 
error is the error
+    /// of the execution, replacing an error of the execution, which is handed 
over; a tracker
+    /// dropped before its end hands the error of its done call over.
+    #[test]
+    fn the_error_of_the_done_call_is_the_error_of_the_execution() {
+        let session = SparkSession::builder()
+            .remote("sc://localhost:15002")
+            .get_or_create()
+            .expect("session");
+        let done_calls = Arc::new(AtomicUsize::new(0));
+        let seen = Arc::clone(&done_calls);
+        let id = session.register_fallible_progress_handler(move |update| {
+            if update.done {
+                seen.fetch_add(1, Ordering::SeqCst);
+                return Err(SparkError::connect_msg("s16 done failed"));
+            }
+            Ok(())
+        });
+        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),
+            };
+            if error.message().starts_with("s16") {
+                sink.lock()
+                    .unwrap()
+                    .push(format!("{kind}: {}", error.message()));
+            }
+        });
+
+        let mut tracker = ProgressTracker::new(&session, None);
+        assert_eq!(tracker.finish().unwrap_err().message(), "s16 done failed");
+        assert!(tracker.finish().is_ok());
+        drop(tracker);
+        assert_eq!(done_calls.load(Ordering::SeqCst), 1);
+
+        let mut tracker = ProgressTracker::new(&session, None);
+        let error = tracker.finish_after(SparkError::connect_msg("s16 
execution failed"));
+        assert_eq!(error.message(), "s16 done failed");
+        drop(tracker);
+        drop(ProgressTracker::new(&session, None));
+        assert_eq!(done_calls.load(Ordering::SeqCst), 3);
+        assert_eq!(
+            *handed.lock().unwrap(),
+            vec!["replaced: s16 execution failed", "dropped: s16 done failed"]
+        );
+        session.remove_progress_handler(id);
+    }
+
     #[test]
     fn detached_progress_registry_preserves_the_execution_recursion_bound() {
         use spark_connect_core::error::SparkErrorKind;
@@ -329,6 +459,7 @@ mod tests {
                         operation_id: Some("nested".to_string()),
                         stages: Vec::new(),
                         inflight_tasks: 0,
+                        finished: false,
                     };
                     nested.notify(false).unwrap();
                 }
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index e4489786..3f39fe7d 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -263,7 +263,12 @@ impl SparkSession {
     /// [`SparkSession::register_progress_handler`]. An error it returns fails 
the execution
     /// that calls it: the execution ends, the error goes to the caller of 
that execution, and
     /// the handlers after it are not called for that update, as PySpark's 
client does when a
-    /// handler raises. The handler is still called as done when the execution 
ends. Used by
+    /// handler raises. The handler is still called as done when the execution 
ends, and an
+    /// error of that done call is the error of the execution, also replacing 
the execution's own
+    /// error, as the exception of PySpark's `Progress.__exit__` is. For an 
execution dropped
+    /// before its end, as an iterator that its caller stopped reading, the 
error of the done call
+    /// has no caller left: it goes to the handler of
+    /// 
[`set_unreturned_error_handler`](crate::progress::set_unreturned_error_handler).
 Used by
     /// the Python drop-in to raise a handler's exception from the call that 
ran it.
     pub fn register_fallible_progress_handler(
         &self,
@@ -327,8 +332,13 @@ impl SparkSession {
             .clone();
         // Before the request: an execution that fails to start ends, as done, 
too.
         check_callback_depth()?;
-        let progress = ProgressTracker::with_handlers(handlers, 
Some(operation_id));
-        let stream = 
block_on(self.client().execute_plan_reattachable(request))?;
+        let mut progress = ProgressTracker::with_handlers(handlers, 
Some(operation_id));
+        // An execution that fails to start ends too: the error of the done 
call is its error, as
+        // the `Progress` of PySpark wraps its request.
+        let stream = match 
block_on(self.client().execute_plan_reattachable(request)) {
+            Ok(stream) => stream,
+            Err(error) => return Err(progress.finish_after(error)),
+        };
         Ok(ExecutionStream::new(stream, progress))
     }
 
@@ -827,7 +837,7 @@ impl SparkSession {
         fun.deterministic = false;
         fun.function =
             
Some(proto::common_inline_user_defined_function::Function::JavaUdf(java_udf));
-        crate::dataframe::execute_command_collect(
+        crate::dataframe::execute_command_unreported(
             self,
             proto::command::CommandType::RegisterFunction(fun),
         )?;
@@ -1154,7 +1164,7 @@ impl SparkSession {
         &self,
         udf: crate::udf::CommonInlineUserDefinedFunctionExpression,
     ) -> Result<()> {
-        crate::dataframe::execute_command(
+        crate::dataframe::execute_command_unreported(
             self,
             proto::command::CommandType::RegisterFunction(udf.to_proto()),
         )
@@ -1184,7 +1194,7 @@ impl SparkSession {
             command,
             python_ver,
         );
-        crate::dataframe::execute_command(
+        crate::dataframe::execute_command_unreported(
             self,
             proto::command::CommandType::RegisterTableFunction(function),
         )
@@ -1234,7 +1244,7 @@ impl SparkSession {
         &self,
         data_source: 
crate::datasource::CommonInlineUserDefinedDataSourceExpression,
     ) -> Result<()> {
-        crate::dataframe::execute_command(
+        crate::dataframe::execute_command_unreported(
             self,
             
proto::command::CommandType::RegisterDataSource(data_source.to_proto()),
         )
diff --git a/crates/spark-connect/src/streaming.rs 
b/crates/spark-connect/src/streaming.rs
index 557d28b4..4ad742d2 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -1312,7 +1312,7 @@ impl StreamingQueryManager {
         drop(stale);
         Self::join_listener_thread(previous);
         if release_server {
-            if let Err(error) = self.remove_server_listener() {
+            if let Err(error) = self.remove_server_listener(false) {
                 // Without the removal, the server would answer the add below 
with no response,
                 // and the add would wait for ever. Keep the flag, so that a 
retry removes first.
                 let mut state = self.bus.state.lock().unwrap();
@@ -1442,7 +1442,7 @@ impl StreamingQueryManager {
         let worker = state.thread.take();
         drop(state);
         let removal = if had_listeners {
-            self.remove_server_listener()
+            self.remove_server_listener(true)
         } else {
             Ok(())
         };
@@ -1539,16 +1539,20 @@ impl StreamingQueryManager {
         }
     }
 
-    /// Send RemoveListenerBusListener so the server ends the event stream.
-    fn remove_server_listener(&self) -> Result<()> {
+    /// Send RemoveListenerBusListener so the server ends the event stream. 
Its progress reaches
+    /// the progress handlers when `reported`, as PySpark's removal of the 
last listener's does;
+    /// the removal before a new add, which PySpark does not send, reports 
none.
+    fn remove_server_listener(&self, reported: bool) -> Result<()> {
         let mut command = proto::StreamingQueryListenerBusCommand::default();
         command.command = Some(
             
proto::streaming_query_listener_bus_command::Command::RemoveListenerBusListener(true),
         );
-        crate::dataframe::execute_command_collect(
-            &self.session,
-            
proto::command::CommandType::StreamingQueryListenerBusCommand(command),
-        )?;
+        let command = 
proto::command::CommandType::StreamingQueryListenerBusCommand(command);
+        if reported {
+            crate::dataframe::execute_command_collect(&self.session, command)?;
+        } else {
+            crate::dataframe::execute_command_unreported(&self.session, 
command)?;
+        }
         Ok(())
     }
 
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 70036731..9e2a51e8 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1366,6 +1366,35 @@ print(spark.range(3).count())
     ], result.stdout
 
 
+def test_the_exception_of_a_done_call_fails_the_execution_as_pyspark(session):
+    # As PySpark Connect's Progress.__exit__: the exception of a progress 
handler's done call goes
+    # out of the execution, and a registration of a function, which PySpark 
runs without a
+    # Progress, makes no call.
+    from pyspark.sql.functions import udf
+
+    error = ValueError("the done call raises")
+    calls = []
+
+    def failing(**kwargs):
+        calls.append(kwargs["done"])
+        if kwargs["done"]:
+            raise error
+
+    session.registerProgressHandler(failing)
+    try:
+        with pytest.raises(ValueError) as raised:
+            session.range(10).collect()
+        assert raised.value is error and calls[-1] is True
+        with pytest.raises(ValueError):
+            session.range(10).toPandas()
+        calls.clear()
+        session.udf.register("s16_f4_done_udf", udf(lambda: 1))
+        assert calls == []
+    finally:
+        session.removeProgressHandler(failing)
+    assert session.sql("SELECT s16_f4_done_udf()").collect()[0][0] == "1"
+
+
 def test_progress_handler_runs_a_query_of_its_own_as_pyspark(session):
     # As PySpark's: a handler runs while the execution runs, and a query of 
the handler runs
     # too, the progress of the execution having no effect on it.
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 0403953c..97809e27 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1899,8 +1899,8 @@ def 
test_progress_handlers_are_called_with_the_progress_of_executions_as_pyspark
     # of ProgressHandler, of the StageInfo of each stage, for each progress of 
an execution that
     # has tasks, and once more, as done, when it ends; removing a handler that 
is not registered
     # raises a ValueError; an exception of a handler fails the execution (see 
the test below), and
-    # its done call goes to sys.unraisablehook; and 
SPARK_CONNECT_PROGRESS_BAR_ENABLED prints the
-    # progress bar.
+    # so does that of its done call, which replaces it, as PySpark's 
Progress.__exit__ raises it;
+    # and SPARK_CONNECT_PROGRESS_BAR_ENABLED prints the progress bar.
     import sys
 
     from pyspark.sql.connect.shell.progress import StageInfo
@@ -1937,7 +1937,7 @@ def 
test_progress_handlers_are_called_with_the_progress_of_executions_as_pyspark
     spark.registerProgressHandler(failing)
     with pytest.raises(ZeroDivisionError):
         spark.range(1).collect()
-    assert unraisable and isinstance(unraisable[0].exc_value, 
ZeroDivisionError)
+    assert unraisable == []
     spark.removeProgressHandler(failing)
 
     monkeypatch.setenv("SPARK_CONNECT_PROGRESS_BAR_ENABLED", "1")
@@ -12272,6 +12272,58 @@ def 
test_udf_profiles_are_collected_from_the_python_accumulators_as_pyspark(
 
 
 
+def 
test_the_exception_of_a_done_call_fails_the_execution_as_pyspark(mock_connect, 
monkeypatch):
+    # As PySpark Connect's Progress.__exit__, which makes the done call when 
the execution ends:
+    # the exception of a handler's done call goes out of the execution as it 
is, not to
+    # sys.unraisablehook, and it replaces the error of an execution that 
fails, which PySpark
+    # keeps as its __context__. A registration of a function, which PySpark 
runs without a
+    # Progress, makes no call.
+    import sys
+
+    from pyspark.sql.functions import udf
+
+    spark, service = mock_connect
+    # ExecutePlanResponse.execution_progress=18 -> one stage with tasks, as 
the tests above.
+    stage = (varint_field(1, 7) + varint_field(2, 4) + varint_field(3, 1)
+             + varint_field(4, 1024) + varint_field(5, 0))
+    service.execute_payload = message_field(18, message_field(1, stage) + 
varint_field(2, 3))
+    unraisable = []
+    monkeypatch.setattr(sys, "unraisablehook", unraisable.append)
+    error = ValueError("the done call raises")
+    calls = []
+
+    def failing(**kwargs):
+        calls.append(kwargs["done"])
+        if kwargs["done"]:
+            raise error
+
+    spark.registerProgressHandler(failing)
+    try:
+        for action in [lambda: spark.range(1).collect(),
+                       lambda: list(spark.range(1).toLocalIterator()),
+                       lambda: 
list(spark.range(1).toLocalIterator(prefetchPartitions=True))]:
+            calls.clear()
+            with pytest.raises(ValueError) as raised:
+                action()
+            assert raised.value is error and calls == [False, True]
+        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"))
+        with pytest.raises(ValueError) as raised:
+            spark.range(1).collect()
+        assert raised.value is error
+        service.execute_error = None
+        calls.clear()
+        spark.udf.register("f", udf(lambda: 1))
+        assert calls == []
+    finally:
+        service.execute_error = None
+        spark.removeProgressHandler(failing)
+    assert unraisable == []
+    service.execute_payload = b""
+    assert spark.range(1).collect() == []
+
+
 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]

Reply via email to