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 f4974a6e [SPARK-61443][CONNECT][PYTHON] Fix the races of the progress 
handlers and streaming listeners, and the swallowed errors of the error 
conversion, of the Python client
f4974a6e is described below

commit f4974a6ec75c3d4c1006a402ec7ec4f8f2b2910e
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Thu Nov 12 07:18:32 2026 +0900

    [SPARK-61443][CONNECT][PYTHON] Fix the races of the progress handlers and 
streaming listeners, and the swallowed errors of the error conversion, of the 
Python client
    
    ### What changes were proposed in this pull request?
    
    Four fixes in the PyO3 extension (`crates/pyspark-rs`), from a review of 
its concurrency and state handling:
    
    - **Progress handlers** (`progress.rs`): the number of handlers kept beside 
the list is now read from the list and stored under one lock after every 
change, so the count left after concurrent changes is that of the last one. The 
registry of the sessions no longer makes Python objects while it is locked.
    - **`toLocalIterator`** (`dataframe.rs`): `__next__` and `close` take the 
iterator with `try_borrow_mut`, and a call made while another thread is waiting 
in it raises `ValueError: generator already executing`.
    - **Streaming listeners** (`streaming.rs`): the id of each registration is 
kept in its adapter in the bus, not in a `_rust_listener_ids` attribute of the 
user's listener. `removeListener` reads the bus of its session and removes the 
first registration that is the listener or equal to it, and reads the bus again 
when another call removed that registration first.
    - **Error conversion** (`errors.rs`): a failure to make the exception of 
the connect classes, or of the class of the kind of the error, becomes the 
`__context__` of the exception raised in its place. The context of the done 
error of a progress handler is set with `PyException_SetContext`. A refused 
`_operation_id` goes to `sys.unraisablehook`.
    
    The review also flagged that `addArtifacts` puts a pyfile zip on `sys.path` 
before it knows the session is open. That is left as it is: PySpark's 
`_parse_artifacts` does the `sys.path.insert` before it opens the file and 
before any RPC, and 
`test_add_artifacts_puts_a_pyfile_zip_on_the_client_path_before_opening_it` 
already pins that order.
    
    ### Why are the changes needed?
    
    The extension declares `gil_used = false`, and several of these paths also 
run Python code (`__eq__`, `__del__`) between two steps that were meant to be 
one.
    
    - A progress handler registered while another change of the handlers was in 
flight could be left uncounted and never called. This does not need a second 
thread: the `__del__` of a handler that `clearProgressHandlers` drops can 
register one.
    - The second caller of a running `toLocalIterator` got `RuntimeError: 
Already borrowed`, where PySpark's generator raises `ValueError: generator 
already executing`. The state of the iterator was never shared, as the borrow 
is exclusive.
    - `addListener` changed the user's listener, failed for an object that 
cannot take the attribute, and left registrations in the bus when several 
threads added and removed the same listener, also with the GIL. PySpark's bus 
keeps its listeners in its own list and removes with `list.remove`.
    - Failures inside the error conversion were dropped with `.ok()` and `let _ 
=`, so a broken conversion silently raised a less specific exception.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    
    - A listener no longer gets a `_rust_listener_ids` attribute, and 
`removeListener` also removes a registered listener that is equal to the one 
given, as PySpark does.
    - A concurrent `next` or `close` of a running `toLocalIterator` raises 
`ValueError` instead of `RuntimeError`.
    - An exception raised in place of one that could not be made has the 
failure as its `__context__`.
    
    ### How was this patch tested?
    
    Nine tests added to `python/tests` (`test_dropin_offline.py`, 
`streaming_listener_cases.py`). Eight fail without the fix; the ninth, the 
multi-threaded test of the progress handlers, only fails without the GIL, and 
the `__del__` test covers that fix deterministically. The existing listener 
tests that read `_rust_listener_ids` now assert on 
`spark.streams._sqlb._listener_bus`.
    
    `test_dropin_offline.py` and `test_ml_offline.py` pass (1934 passed, 8 
skipped), as do `cargo fmt --all --check`, `ruff check` and `ruff format 
--check`. The multi-threaded tests were run on a GIL build of Python 3.11 only.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Fable 5.2)
    
    Closes #511 from viirya/pyspark-rs-races-a20cb0.
    
    Authored-by: Liang-Chi Hsieh <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs       |  40 ++++--
 crates/pyspark-rs/src/errors.rs          | 158 ++++++++++++++---------
 crates/pyspark-rs/src/progress.rs        |  62 ++++++---
 crates/pyspark-rs/src/streaming.rs       | 112 ++++++++++------
 python/tests/streaming_listener_cases.py | 152 ++++++++++++++++------
 python/tests/test_dropin_offline.py      | 214 +++++++++++++++++++++++++++++++
 6 files changed, 570 insertions(+), 168 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index cb6b906b..56a38316 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -4657,6 +4657,27 @@ impl PyLocalRowIterator {
     }
 }
 
+impl PyLocalRowIterator {
+    /// The iterator, for a call that runs or closes it. The fetch of a row 
releases the GIL
+    /// with the iterator borrowed, so that a second thread can call it 
meanwhile: its state is
+    /// never shared, as the borrow is exclusive, and the second call raises 
the `ValueError` of
+    /// a generator that is already executing, as PySpark's generator does, 
rather than the
+    /// `RuntimeError` of the borrow.
+    fn not_executing<'py>(slf: &Bound<'py, Self>) -> PyResult<PyRefMut<'py, 
Self>> {
+        slf.try_borrow_mut()
+            .map_err(|_| pyo3::exceptions::PyValueError::new_err("generator 
already executing"))
+    }
+
+    /// End the iteration, releasing its execution without the GIL.
+    fn finish(&mut self, py: Python<'_>) {
+        let iterator = self.iterator.take();
+        self.finished = true;
+        self.fields = None;
+        self.nested_fields.clear();
+        py.detach(move || drop(iterator));
+    }
+}
+
 #[pymethods]
 impl PyLocalRowIterator {
     /// Make this object an iterator by returning self.
@@ -4666,26 +4687,25 @@ impl PyLocalRowIterator {
 
     /// Close the iterator, as a generator does: the rows that are left are 
not fetched, so the
     /// execution of the query is released, and the iteration ends. Closing it 
again does nothing.
-    fn close(&mut self, py: Python<'_>) {
-        let iterator = self.iterator.take();
-        self.finished = true;
-        self.fields = None;
-        self.nested_fields.clear();
-        py.detach(move || drop(iterator));
+    fn close(slf: &Bound<'_, Self>) -> PyResult<()> {
+        Self::not_executing(slf)?.finish(slf.py());
+        Ok(())
     }
 
     /// Fetch the next row from the iterator.
     ///
     /// The first call snapshots the binary result setting before starting 
execution.
     /// Both the Config RPC and blocking row fetch release the GIL.
-    fn __next__(&mut self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
-        if self.finished {
+    fn __next__(slf: &Bound<'_, Self>) -> PyResult<Option<Py<PyAny>>> {
+        let py = slf.py();
+        let mut this = Self::not_executing(slf)?;
+        if this.finished {
             return Ok(None);
         }
-        match self.next_python_row(py) {
+        match this.next_python_row(py) {
             Ok(Some(row)) => Ok(Some(row)),
             result => {
-                self.close(py);
+                this.finish(py);
                 result
             }
         }
diff --git a/crates/pyspark-rs/src/errors.rs b/crates/pyspark-rs/src/errors.rs
index c26e3ee9..b472aa64 100644
--- a/crates/pyspark-rs/src/errors.rs
+++ b/crates/pyspark-rs/src/errors.rs
@@ -245,13 +245,52 @@ pub(crate) fn set_callback_context(py: Python<'_>, err: 
&SparkError, context: Py
     let Some(id) = callback_id(err) else {
         return;
     };
-    let exceptions = CALLBACK_EXCEPTIONS
+    // Taken out of the lock: dropping the context that the exception had can 
run Python code.
+    let exception = 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));
+        .unwrap_or_else(|e| e.into_inner())
+        .get(&id)
+        .map(|exception| exception.clone_ref(py));
+    if let Some(exception) = exception {
+        set_context(py, exception.value(py), context);
+    }
+}
+
+/// Make `context` the `__context__` of `exception`, as Python makes the 
exception that is being
+/// handled the context of one that is raised: through the C API, which cannot 
fail, rather than
+/// by setting the attribute, which the `__setattr__` of the class of the 
exception could refuse.
+/// An exception is never made its own context.
+fn set_context(
+    py: Python<'_>,
+    exception: &Bound<'_, pyo3::exceptions::PyBaseException>,
+    context: PyErr,
+) {
+    let context = context.into_value(py);
+    if context.as_ptr() == exception.as_ptr() {
+        return;
+    }
+    // SAFETY: both are exception instances, held with the interpreter 
attached, and
+    // `PyException_SetContext` steals the reference to the context that 
`into_ptr` gives it.
+    unsafe { pyo3::ffi::PyException_SetContext(exception.as_ptr(), 
context.into_ptr()) }
+}
+
+/// `raised`, with `secondary` as its `__context__`: an exception that kept 
the client from
+/// raising a more specific exception than `raised` is not dropped, but 
chained to the one that
+/// is raised in its place, as Python chains an exception raised while another 
is handled.
+fn with_context(py: Python<'_>, raised: PyErr, secondary: PyErr) -> PyErr {
+    set_context(py, raised.value(py), secondary);
+    raised
+}
+
+/// Stamp `_operation_id` on an exception of an ExecutePlan, as the reference 
client does (read
+/// through `operation_id`). The id is auxiliary: an exception that refuses 
the attribute is
+/// still the one to raise, so the refusal does not replace it, and goes to
+/// `sys.unraisablehook` instead of being dropped.
+fn stamp_operation_id(exception: &Bound<'_, PyAny>, operation_id: 
Option<&str>) {
+    if let Some(operation_id) = operation_id {
+        if let Err(error) = exception.setattr("_operation_id", operation_id) {
+            error.write_unraisable(exception.py(), Some(exception));
+        }
     }
 }
 
@@ -287,73 +326,72 @@ pub fn spark_error_to_py_exception(err: SparkError) -> 
PyErr {
     let operation_id = err.operation_id.clone();
     let class_name = kind_to_pyspark_class_name(err.kind);
 
-    // Try to acquire the GIL and import the exception class from 
pyspark.errors
     Python::attach(|py| {
-        // Should the connect classes not import, fall back to the class by 
kind below.
+        // An error of the server, or of gRPC, is the exception of the connect 
classes. Should
+        // making it fail, the error is raised as the class of its kind below, 
with the
+        // exception of the failure as its `__context__`.
         let connect_error = match (&err.server, err.grpc_code) {
-            (Some(server), _) => server_error_to_py(py, &err, server).ok(),
-            (None, Some(code)) => grpc_error_to_py(py, &msg, code).ok(),
+            (Some(server), _) => Some(server_error_to_py(py, &err, server)),
+            (None, Some(code)) => Some(grpc_error_to_py(py, &msg, code)),
             (None, None) => None,
         };
-        if let Some(exc_instance) = connect_error {
-            if let Some(op) = &operation_id {
-                let _ = exc_instance.setattr("_operation_id", op);
-            }
-            return PyErr::from_value(exc_instance);
-        }
-        // First, verify and get the exception class from pyspark.errors
-        let errors_module = match py.import("pyspark.errors") {
-            Ok(m) => m,
-            Err(_) => {
-                // If import fails, return PyRuntimeError as fallback
-                return exceptions::PyRuntimeError::new_err(msg);
+        let connect_failure = match connect_error {
+            Some(Ok(exc_instance)) => {
+                stamp_operation_id(&exc_instance, operation_id.as_deref());
+                return PyErr::from_value(exc_instance);
             }
+            Some(Err(failure)) => Some(failure),
+            None => None,
         };
-
-        // A classed Connect error, such as `NO_ACTIVE_SESSION`, and a Connect 
error of a plain
-        // message are `SparkConnectException`s, as the reference client 
raises them.
-        let connect_class = err.kind == SparkErrorKind::ConnectMessage
-            || (err.kind == SparkErrorKind::Connect && 
!err.error_class.is_empty());
-        let exc_class = if connect_class {
-            py.import("pyspark.errors.exceptions.connect")
-                .and_then(|module| module.getattr("SparkConnectException"))
-        } else {
-            errors_module.getattr(class_name)
-        };
-        // Get the exception class from the module
-        match exc_class {
-            Ok(exc_class) => {
-                // Instantiate the exception class: of the error class and 
message parameters
-                // of an error of a PySpark error class, otherwise of the 
message.
-                let created = match classed_exception(&exc_class, &err) {
-                    Some(exc_instance) => Ok(exc_instance),
-                    None => exc_class.call1((msg.clone(),)),
-                };
-                match created {
-                    Ok(exc_instance) => {
-                        // Mirror the reference client, which stamps 
`_operation_id` on
-                        // errors raised for an ExecutePlan (read via 
`operation_id`).
-                        if let Some(op) = &operation_id {
-                            let _ = exc_instance.setattr("_operation_id", op);
-                        }
-                        // Convert the exception instance to a PyErr.
-                        // We use unsafe code to construct the PyErr from the 
exception value.
-                        PyErr::from_value(exc_instance)
-                    }
-                    Err(_) => {
-                        // If instantiation fails, fall back to PyRuntimeError
-                        exceptions::PyRuntimeError::new_err(msg)
-                    }
+        match kind_exception(py, &err, class_name, &msg) {
+            Ok(exc_instance) => {
+                stamp_operation_id(&exc_instance, operation_id.as_deref());
+                let raised = PyErr::from_value(exc_instance);
+                match connect_failure {
+                    Some(failure) => with_context(py, raised, failure),
+                    None => raised,
                 }
             }
-            Err(_) => {
-                // If class not found, fall back to PyRuntimeError
-                exceptions::PyRuntimeError::new_err(msg)
+            // The class of the kind does not import, or does not take the 
message: a
+            // RuntimeError of the message, with the exception of the failure 
as its context,
+            // which the failure of the connect classes, if any, came before.
+            Err(failure) => {
+                let failure = match connect_failure {
+                    Some(earlier) => with_context(py, failure, earlier),
+                    None => failure,
+                };
+                with_context(py, exceptions::PyRuntimeError::new_err(msg), 
failure)
             }
         }
     })
 }
 
+/// The exception of `err` of the class of its kind, `class_name` of 
`pyspark.errors`.
+fn kind_exception<'py>(
+    py: Python<'py>,
+    err: &SparkError,
+    class_name: &str,
+    msg: &str,
+) -> PyResult<Bound<'py, PyAny>> {
+    let errors_module = py.import("pyspark.errors")?;
+    // A classed Connect error, such as `NO_ACTIVE_SESSION`, and a Connect 
error of a plain
+    // message are `SparkConnectException`s, as the reference client raises 
them.
+    let connect_class = err.kind == SparkErrorKind::ConnectMessage
+        || (err.kind == SparkErrorKind::Connect && 
!err.error_class.is_empty());
+    let exc_class = if connect_class {
+        py.import("pyspark.errors.exceptions.connect")?
+            .getattr("SparkConnectException")?
+    } else {
+        errors_module.getattr(class_name)?
+    };
+    // Of the error class and message parameters of an error of a PySpark 
error class,
+    // otherwise of the message.
+    match classed_exception(&exc_class, err) {
+        Some(exc_instance) => Ok(exc_instance),
+        None => exc_class.call1((msg,)),
+    }
+}
+
 /// The exception of `exc_class` for an error of a PySpark error class that 
the client raised,
 /// as PySpark raises it: of the error class and the message parameters, from 
which the
 /// exception renders its message, so that `getCondition` and 
`getMessageParameters` return
diff --git a/crates/pyspark-rs/src/progress.rs 
b/crates/pyspark-rs/src/progress.rs
index 1814bdd5..b72f716e 100644
--- a/crates/pyspark-rs/src/progress.rs
+++ b/crates/pyspark-rs/src/progress.rs
@@ -22,7 +22,11 @@ pub(crate) struct SessionProgress {
     /// The `Progress` of each execution of a progress bar, by its operation 
ID.
     bars: Py<PyDict>,
     /// The number of handlers, so that an execution takes the GIL only for a 
handler or a bar.
+    /// Written only by [`SessionProgress::sync_count`].
     count: AtomicUsize,
+    /// Makes reading the length of `handlers` and storing it in `count` one 
step, so that the
+    /// count that is left after concurrent changes of the list is that of the 
last one.
+    count_sync: Mutex<()>,
 }
 
 /// The progress of each session of the client, by its session ID: every 
Python object of a
@@ -32,19 +36,30 @@ fn registry() -> &'static Mutex<HashMap<String, 
Arc<SessionProgress>>> {
     REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
 }
 
+fn lock_registry() -> std::sync::MutexGuard<'static, HashMap<String, 
Arc<SessionProgress>>> {
+    registry().lock().unwrap_or_else(|e| e.into_inner())
+}
+
 /// The progress of `session`: the first time, it registers the handler of the 
core session
 /// that calls the Python handlers and drives the progress bars.
 pub(crate) fn session_progress(py: Python<'_>, session: &SparkSession) -> 
Arc<SessionProgress> {
-    let mut registry = registry().lock().unwrap_or_else(|e| e.into_inner());
     let id = session.session_id().to_string();
-    if let Some(progress) = registry.get(&id) {
+    if let Some(progress) = lock_registry().get(&id) {
         return Arc::clone(progress);
     }
+    // The Python objects are made before the registry is locked: making one 
can run the
+    // garbage collector, and with it any Python code, which must not find the 
registry locked.
     let progress = Arc::new(SessionProgress {
         handlers: PyList::empty(py).unbind(),
         bars: PyDict::new(py).unbind(),
         count: AtomicUsize::new(0),
+        count_sync: Mutex::new(()),
     });
+    let mut registry = lock_registry();
+    if let Some(progress) = registry.get(&id) {
+        // Another thread registered the progress of the session meanwhile.
+        return Arc::clone(progress);
+    }
     let shared = Arc::clone(&progress);
     session.register_fallible_progress_handler(move |update| 
shared.notify(update));
     install_unreturned_error_handler();
@@ -81,10 +96,7 @@ fn install_unreturned_error_handler() {
 
 /// Forget the progress of a stopped session.
 pub(crate) fn forget_session(session: &SparkSession) {
-    registry()
-        .lock()
-        .unwrap_or_else(|e| e.into_inner())
-        .remove(session.session_id());
+    lock_registry().remove(session.session_id());
 }
 
 /// Whether the progress bar is enabled, as 
`pyspark.sql.connect.shell.progress_bar_enabled`.
@@ -93,30 +105,46 @@ fn progress_bar_enabled() -> bool {
 }
 
 impl SessionProgress {
+    /// Make `count` the number of handlers, after a change of the list. A 
change of the list
+    /// can run Python code, the `__eq__` of a handler or the `__del__` of one 
that it drops,
+    /// and on a free-threaded build nothing orders two changes, so that the 
length that a
+    /// change left may be stale by the time it is stored: the length is read 
and stored under
+    /// one lock, and each change calls this after it, so that the last store 
is of a length
+    /// read after every change. No Python code runs under the lock.
+    fn sync_count(&self, py: Python<'_>) {
+        let _sync = self.count_sync.lock().unwrap_or_else(|e| e.into_inner());
+        self.count
+            .store(self.handlers.bind(py).len(), Ordering::SeqCst);
+    }
+
     /// As PySpark's `register_progress_handler`: a handler is registered once.
     pub(crate) fn register(&self, py: Python<'_>, handler: &Bound<'_, PyAny>) 
-> PyResult<()> {
         let handlers = self.handlers.bind(py);
-        if !handlers.contains(handler)? {
-            handlers.append(handler)?;
-        }
-        self.count.store(handlers.len(), Ordering::SeqCst);
-        Ok(())
+        let registered = handlers.contains(handler).and_then(|found| {
+            if found {
+                Ok(())
+            } else {
+                handlers.append(handler)
+            }
+        });
+        self.sync_count(py);
+        registered
     }
 
     /// As PySpark's `remove_progress_handler`: a `ValueError` for a handler 
that is not
     /// registered, of `list.remove`.
     pub(crate) fn remove(&self, py: Python<'_>, handler: &Bound<'_, PyAny>) -> 
PyResult<()> {
         let handlers = self.handlers.bind(py);
-        handlers.call_method1("remove", (handler,))?;
-        self.count.store(handlers.len(), Ordering::SeqCst);
-        Ok(())
+        let removed = handlers.call_method1("remove", (handler,));
+        self.sync_count(py);
+        removed.map(|_| ())
     }
 
     /// As PySpark's `clear_progress_handlers`.
     pub(crate) fn clear(&self, py: Python<'_>) -> PyResult<()> {
-        self.handlers.bind(py).call_method0("clear")?;
-        self.count.store(0, Ordering::SeqCst);
-        Ok(())
+        let cleared = self.handlers.bind(py).call_method0("clear");
+        self.sync_count(py);
+        cleared.map(|_| ())
     }
 
     /// Call the handlers with `update`. The exception of a handler fails the 
execution that
diff --git a/crates/pyspark-rs/src/streaming.rs 
b/crates/pyspark-rs/src/streaming.rs
index 935c3c03..efff48b9 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -21,6 +21,11 @@ use crate::options::{set_option_skip_none, 
set_options_skip_none};
 /// errors return to the bus, and terminal failures produce the reference 
handler warning.
 struct PyListenerAdapter {
     listener: Py<PyAny>,
+    /// The id of this registration in the bus of its session, once the bus 
has added it. It is
+    /// kept here, not on the listener: the listener is the user's object, 
which may have no
+    /// attributes to set (`__slots__`), and may be added by several threads 
and to several
+    /// sessions at once.
+    id: std::sync::OnceLock<String>,
 }
 
 /// An unisolated dispatch failure. Keep Python errors intact so synchronous 
starts
@@ -1377,9 +1382,9 @@ impl PyStreamingQueryManager {
     /// Register a client-side listener object (with 
onQueryStarted/Progress/Idle/
     /// Terminated callbacks). Mirrors `StreamingQueryManager.addListener`: 
the listener gets the
     /// session as its `spark`, and the native Rust bus of the session 
dispatches its events to
-    /// it. The id of each registration is appended to the listener's 
`_rust_listener_ids`, as a
-    /// listener added twice is in the bus twice. Should the server fail to 
add its listener, this
-    /// warns, as PySpark Connect's does.
+    /// it. A listener added twice is in the bus twice, and each registration 
keeps its own id
+    /// (see `PyListenerAdapter::id`); nothing is stored on the listener. 
Should the server fail
+    /// to add its listener, this warns, as PySpark Connect's does.
     /// A terminal event-stream end or error clears the registrations; add 
listeners again
     /// to open a new subscription.
     fn addListener(&self, py: Python<'_>, listener: Py<PyAny>) -> PyResult<()> 
{
@@ -1388,17 +1393,17 @@ impl PyStreamingQueryManager {
             .bind(py)
             .call_method1("_set_spark_session", (session,))?;
         let adapter = Arc::new(PyListenerAdapter {
-            listener: listener.clone_ref(py),
+            listener,
+            id: std::sync::OnceLock::new(),
         });
+        let registration = Arc::clone(&adapter);
         match interruptible_outcome(py, &self.inner.spark_session(), || {
-            self.inner.add_listener(adapter).map_err(Box::new)
+            self.inner.add_listener(registration).map_err(Box::new)
         })? {
             Ok(id) => {
-                let bound = listener.bind(py);
-                match bound.getattr("_rust_listener_ids") {
-                    Ok(ids) => ids.call_method1("append", (id,)).map(|_| ()),
-                    Err(_) => bound.setattr("_rust_listener_ids", vec![id]),
-                }
+                // Set once, by the only call that adds this adapter.
+                let _ = adapter.id.set(id);
+                Ok(())
             }
             Err(error) => warn(
                 py,
@@ -1413,43 +1418,66 @@ impl PyStreamingQueryManager {
 
     /// Remove a previously-added client-side listener object. Mirrors
     /// `StreamingQueryManager.removeListener`: one registration of the 
listener is removed from
-    /// the bus of the session, the first one that the bus has (as the bus 
removes the first
-    /// occurrence), and the others, which are of other buses, stay. Should 
the server fail to
-    /// remove its listener, this warns, and the listener stays, as PySpark 
Connect's does.
-    /// A callback coalesced with another caller's in-progress last-listener 
removal or close
-    /// keeps its ids so a failed operation can be retried. Only a completed 
removal consumes
-    /// one matching id from this session's bus.
+    /// the bus of the session, the first one that the bus has, as PySpark's 
`list.remove` of
+    /// its bus finds it: the first that is the listener, or equal to it. The 
registrations of
+    /// the listener in the buses of other sessions stay. Should the server 
fail to remove its
+    /// listener, this warns, and the listener stays, as PySpark Connect's 
does.
+    /// The registrations are read from the bus, so a removal that did not 
complete, such as a
+    /// callback coalesced with another caller's in-progress last-listener 
removal or close,
+    /// leaves its registration there to be removed again, and those that a 
terminal end of the
+    /// event stream cleared are not looked for.
     fn removeListener(&self, py: Python<'_>, listener: Py<PyAny>) -> 
PyResult<()> {
-        let bound = listener.bind(py);
-        let Ok(ids) = bound.getattr("_rust_listener_ids") else {
-            return Ok(());
-        };
-        let registered: Vec<String> = ids.extract()?;
-        for id in registered {
-            match interruptible_outcome(py, &self.inner.spark_session(), || {
-                self.inner.remove_listener_found(&id).map_err(Box::new)
-            })? {
-                Ok(false) => continue,
-                Ok(true) => {
-                    ids.call_method1("remove", (&id,))?;
-                    if ids.len()? == 0 {
-                        let _ = bound.delattr("_rust_listener_ids");
-                    }
-                    return Ok(());
+        let listener = listener.bind(py);
+        // The registrations that this call did not remove: another call 
removed them first,
+        // or their removal is left to the caller that is closing the bus.
+        let mut tried: Vec<String> = Vec::new();
+        loop {
+            let mut registered = Vec::new();
+            for candidate in self.inner.listeners() {
+                let Some(adapter) = candidate
+                    .as_any()
+                    .and_then(|any| any.downcast_ref::<PyListenerAdapter>())
+                else {
+                    continue;
+                };
+                // A registration without an id is still being added by 
another thread: this
+                // removal is before it.
+                let Some(id) = adapter.id.get() else {
+                    continue;
+                };
+                if tried.contains(id) {
+                    continue;
                 }
-                Err(error) => {
-                    return warn(
-                        py,
-                        format!(
-                            "Failed to remove the listener because of 
exception: {}\n\
-                             The listener is not removed, please remove it 
again.",
-                            spark_error_to_py_exception(*error).value(py)
-                        ),
-                    );
+                let found = adapter.listener.bind(py);
+                if found.is(listener) || found.eq(listener)? {
+                    registered.push(id.clone());
+                }
+            }
+            if registered.is_empty() {
+                return Ok(());
+            }
+            for id in registered {
+                match interruptible_outcome(py, &self.inner.spark_session(), 
|| {
+                    self.inner.remove_listener_found(&id).map_err(Box::new)
+                })? {
+                    // The bus is read again once these are tried: a call that 
removed this
+                    // registration first leaves its own to this one, which 
may have been
+                    // added since the bus was read.
+                    Ok(false) => tried.push(id),
+                    Ok(true) => return Ok(()),
+                    Err(error) => {
+                        return warn(
+                            py,
+                            format!(
+                                "Failed to remove the listener because of 
exception: {}\n\
+                                 The listener is not removed, please remove it 
again.",
+                                spark_error_to_py_exception(*error).value(py)
+                            ),
+                        );
+                    }
                 }
             }
         }
-        Ok(())
     }
 
     /// The listener bus of the session, as PySpark Connect's `_sqlb`.
diff --git a/python/tests/streaming_listener_cases.py 
b/python/tests/streaming_listener_cases.py
index d24c14d8..7da24931 100644
--- a/python/tests/streaming_listener_cases.py
+++ b/python/tests/streaming_listener_cases.py
@@ -487,27 +487,21 @@ class TestStreamingListenerLifecycle:
         try:
             spark.streams.addListener(listener)
             spark.streams.addListener(listener)
-            first, second = listener._rust_listener_ids
             other.streams.addListener(listener)
-            third = listener._rust_listener_ids[-1]
-            assert len({first, second, third}) == 3
             assert spark.streams._sqlb._listener_bus == [listener, listener]
             assert other.streams._sqlb._listener_bus == [listener]
             assert service.listener_subscriptions == 2
 
             other.streams.removeListener(listener)
-            assert listener._rust_listener_ids == [first, second]
             assert other.streams._sqlb._listener_bus == []
             assert spark.streams._sqlb._listener_bus == [listener, listener]
             assert service.listener_removals == 1
             assert service.wait_listener_streams_finished(1)
 
             spark.streams.removeListener(listener)
-            assert listener._rust_listener_ids == [second]
             assert spark.streams._sqlb._listener_bus == [listener]
             assert service.listener_removals == 1
             spark.streams.removeListener(listener)
-            assert not hasattr(listener, "_rust_listener_ids")
             assert spark.streams._sqlb._listener_bus == []
             assert service.listener_removals == 2
             assert service.wait_listener_streams_finished(2)
@@ -515,6 +509,101 @@ class TestStreamingListenerLifecycle:
             other.stop()
             spark.streams.close()
 
+    def 
test_streaming_listener_registrations_are_not_kept_on_the_listener(self, 
mock_connect):
+        # As PySpark's bus, which keeps its listeners in its own list: adding 
a listener leaves
+        # nothing on the object but the session that _set_spark_session gives 
it, so a listener
+        # that has no room for another attribute, of __slots__, is added and 
removed.
+        # (PySpark's client-side bus takes any object with the callbacks.)
+        spark, service = mock_connect
+        service.listener_bus_enabled = True
+
+        class SlottedListener:
+            # Not a StreamingQueryListener, whose instances have a __dict__.
+            __slots__ = ("spark",)
+
+            def _set_spark_session(self, session):
+                self.spark = session
+
+        slotted, plain = SlottedListener(), IdleListener()
+        assert not hasattr(slotted, "__dict__")
+        try:
+            spark.streams.addListener(plain)
+            attributes = set(vars(plain))
+            spark.streams.addListener(plain)
+            assert set(vars(plain)) == attributes
+            spark.streams.addListener(slotted)
+            assert spark.streams._sqlb._listener_bus == [plain, plain, slotted]
+            spark.streams.removeListener(slotted)
+            assert spark.streams._sqlb._listener_bus == [plain, plain]
+            spark.streams.removeListener(plain)
+            spark.streams.removeListener(plain)
+            assert spark.streams._sqlb._listener_bus == []
+            # Not registered any more: nothing to remove, as PySpark's remove 
does nothing.
+            spark.streams.removeListener(plain)
+            assert service.listener_removals == 1
+        finally:
+            spark.streams.close()
+
+    def test_streaming_listener_is_removed_by_equality_as_pyspark(self, 
mock_connect):
+        # As the list.remove of PySpark's bus: the first listener that is the 
one given, or
+        # equal to it, is removed.
+        spark, service = mock_connect
+        service.listener_bus_enabled = True
+
+        class NamedListener(IdleListener):
+            def __init__(self, name):
+                super().__init__()
+                self.name = name
+
+            def __eq__(self, other):
+                return isinstance(other, NamedListener) and self.name == 
other.name
+
+            __hash__ = None
+
+        first, second = NamedListener("a"), NamedListener("b")
+        try:
+            spark.streams.addListener(first)
+            spark.streams.addListener(second)
+            spark.streams.removeListener(NamedListener("b"))
+            [left] = spark.streams._sqlb._listener_bus
+            assert left is first
+        finally:
+            spark.streams.close()
+
+    def 
test_streaming_listener_added_and_removed_by_many_threads_at_once(self, 
mock_connect):
+        # The registrations of one listener that several threads add and 
remove at once are
+        # each removed once: none is lost, and none is left in the bus.
+        spark, service = mock_connect
+        service.listener_bus_enabled = True
+        listener, keeper = IdleListener(), IdleListener()
+        threads, rounds = 8, 25
+        barrier = threading.Barrier(threads)
+        failures = []
+
+        def work():
+            try:
+                barrier.wait(10)
+                for _ in range(rounds):
+                    spark.streams.addListener(listener)
+                    spark.streams.removeListener(listener)
+            except BaseException as error:  # noqa: BLE001
+                failures.append(error)
+
+        try:
+            # A listener that stays keeps the bus open, so that the rounds 
make no RPC.
+            spark.streams.addListener(keeper)
+            workers = [threading.Thread(target=work) for _ in range(threads)]
+            for worker in workers:
+                worker.start()
+            for worker in workers:
+                worker.join(60)
+            assert failures == []
+            assert spark.streams._sqlb._listener_bus == [keeper]
+            assert not hasattr(listener, "_rust_listener_ids")
+            assert service.listener_subscriptions == 1
+        finally:
+            spark.streams.close()
+
     def test_streaming_listener_registration_failure_can_be_retried(self, 
mock_connect):
         spark, service = mock_connect
         service.listener_bus_enabled = True
@@ -523,7 +612,7 @@ class TestStreamingListenerLifecycle:
         with pytest.warns(UserWarning, match="listener registration failed") 
as caught:
             assert spark.streams.addListener(listener) is None
         assert "The listener is not added, please add it again." in 
str(caught[0].message)
-        assert not hasattr(listener, "_rust_listener_ids")
+        assert spark.streams._sqlb._listener_bus == []
         service.listener_register_failure = False
         try:
             spark.streams.addListener(listener)
@@ -539,7 +628,6 @@ class TestStreamingListenerLifecycle:
         service.listener_bus_enabled = True
         listener = IdleListener()
         spark.streams.addListener(listener)
-        listener_ids = list(listener._rust_listener_ids)
 
         def remove():
             if method == "removeListener":
@@ -554,7 +642,7 @@ class TestStreamingListenerLifecycle:
                 "The listener is not removed, please remove it again."
                 in str(caught[0].message)
             )
-            assert listener._rust_listener_ids == listener_ids
+            assert spark.streams._sqlb._listener_bus == [listener]
             assert service.listener_streams_finished == 0
             emit_idle(service, spark, "still-registered")
             listener.wait_for("still-registered")
@@ -563,19 +651,17 @@ class TestStreamingListenerLifecycle:
             assert remove() is None
             assert service.listener_removals == 2
             assert service.wait_listener_streams_finished(1)
-            # A completed remove consumes its id; manager close leaves stale 
private ids,
-            # which must not prevent registering and removing the same object 
again.
-            remaining_ids = listener_ids if method == "close" else []
-            assert getattr(listener, "_rust_listener_ids", []) == remaining_ids
+            # A completed remove, or close, leaves no registration of the 
listener, so the
+            # same object registers and is removed again.
+            assert spark.streams._sqlb._listener_bus == []
             # A fresh registration after removal opens a new server 
subscription.
             spark.streams.addListener(listener)
-            assert listener._rust_listener_ids[:-1] == remaining_ids
-            assert listener._rust_listener_ids[-1] not in listener_ids
+            assert spark.streams._sqlb._listener_bus == [listener]
             assert service.listener_subscriptions == 2
             emit_idle(service, spark, "registered-again")
             listener.wait_for("registered-again")
             spark.streams.removeListener(listener)
-            assert getattr(listener, "_rust_listener_ids", []) == remaining_ids
+            assert spark.streams._sqlb._listener_bus == []
             assert service.listener_removals == 3
             assert service.wait_listener_streams_finished(2)
         finally:
@@ -839,7 +925,6 @@ def concurrent_close_case(remove_failure, callback_action):
         listener = RemovingListener()
         for _ in range(registrations):
             spark.streams.addListener(listener)
-        listener_ids = list(listener._rust_listener_ids)
         closing = threading.Thread(target=close, daemon=True)
         try:
             with warnings.catch_warnings(record=True) as caught:
@@ -856,7 +941,9 @@ def concurrent_close_case(remove_failure, callback_action):
                     assert all(thread not in (caller_thread, closing.ident)
                                for thread in callback_threads)
                     assert closing.is_alive()
-                    assert listener._rust_listener_ids == listener_ids
+                    if callback_action != "stop":
+                        # The callback's own removal did not consume a 
registration.
+                        assert spark.streams._sqlb._listener_bus == [listener] 
* registrations
                 finally:
                     release.set()
                     service.release_listener_removal()
@@ -872,7 +959,7 @@ def concurrent_close_case(remove_failure, callback_action):
                 assert len(add_warnings) == 1
                 assert "cannot change the listener bus from its own callback" 
in add_warnings[0]
                 assert "The listener is not added, please add it again." in 
add_warnings[0]
-                assert not hasattr(attempted, "_rust_listener_ids")
+                assert attempted not in spark.streams._sqlb._listener_bus
                 assert attempted.timestamps == []
             else:
                 assert add_warnings == []
@@ -898,20 +985,15 @@ def concurrent_close_case(remove_failure, 
callback_action):
                 for remaining in range(registrations - 1, -1, -1):
                     spark.streams.removeListener(listener)
                     assert spark.streams._sqlb._listener_bus == [listener] * 
remaining
-                    if remaining:
-                        assert listener._rust_listener_ids == 
listener_ids[-remaining:]
-                    else:
-                        assert not hasattr(listener, "_rust_listener_ids")
                 assert service.listener_removals == 2
             else:
                 assert service.listener_removals == 1
             assert service.wait_listener_streams_finished(1)
-            # Successful external close leaves stale ids. A fresh add appends 
a new id
-            # and opens exactly one subscription; failed-close retries 
consumed their ids.
-            remaining_ids = list(getattr(listener, "_rust_listener_ids", []))
+            # A close, or the retried removals, leaves no registration. A 
fresh add is the
+            # only one, and opens exactly one subscription.
+            assert spark.streams._sqlb._listener_bus == []
             spark.streams.addListener(listener)
-            assert listener._rust_listener_ids[:-1] == remaining_ids
-            assert listener._rust_listener_ids[-1] not in listener_ids
+            assert spark.streams._sqlb._listener_bus == [listener]
             assert service.listener_subscriptions == 2
             emit_idle(service, spark, "registered-again")
             listener.wait_for("registered-again")
@@ -1104,7 +1186,6 @@ def pending_registration_case(method):
             assert len(relevant) == 1
             assert "NO_ACTIVE_SESSION" in relevant[0]
             assert "The listener is not added, please add it again." in 
relevant[0]
-            assert not hasattr(listener, "_rust_listener_ids")
             assert spark.is_stopped
             assert spark.streams._sqlb._listener_bus == []
             assert service.listener_removals == 0
@@ -1126,7 +1207,6 @@ def ended_stream_case(termination):
         listener = IdleListener()
         try:
             manager.addListener(listener)
-            stale_ids = list(listener._rust_listener_ids)
             emit_idle(service, spark, "before-end")
             listener.wait_for("before-end")
             # End the subscription without a client removal RPC, either at 
ResultComplete
@@ -1134,20 +1214,16 @@ def ended_stream_case(termination):
             assert service.end_listener_stream(spark.session_id, 
failure=termination == "error")
             assert service.wait_listener_streams_finished(1)
             wait_for_empty_bus(manager, "ended stream kept its registrations")
-            assert listener._rust_listener_ids == stale_ids
             manager.removeListener(listener)
-            assert listener._rust_listener_ids == stale_ids
             assert service.listener_removals == 0
 
-            # Reuse the same manager and object: stale tokens must not match 
the new
-            # generation or prevent removal of its one active registration. A 
failed stream
+            # Reuse the same manager and object: the registrations that the 
end cleared
+            # must not prevent removal of its one active registration. A 
failed stream
             # leaves the server's registration held, so the add removes it 
first; a normal
             # end leaves none.
             removals = 1 if termination == "error" else 0
             manager.addListener(listener)
             assert service.listener_removals == removals
-            assert listener._rust_listener_ids[:-1] == stale_ids
-            assert listener._rust_listener_ids[-1] not in stale_ids
             assert service.listener_subscriptions == 2
             assert manager._sqlb._listener_bus == [listener]
             emit_idle(service, spark, "after-end")
@@ -1155,11 +1231,9 @@ def ended_stream_case(termination):
             assert listener.timestamps == ["before-end", "after-end"]
             manager.removeListener(listener)
             assert manager._sqlb._listener_bus == []
-            assert listener._rust_listener_ids == stale_ids
             assert service.listener_removals == removals + 1
             assert service.wait_listener_streams_finished(2)
             manager.removeListener(listener)
-            assert listener._rust_listener_ids == stale_ids
             assert service.listener_removals == removals + 1
         finally:
             manager.close()
@@ -1203,7 +1277,7 @@ def second_rpc_case():
             service.release_listener_registration()
             starting.join(5)
             assert not starting.is_alive()
-            assert hasattr(listener, "_rust_listener_ids")
+            assert spark.streams._sqlb._listener_bus == [listener]
             closing.start()
             assert service.wait_listener_removal(2)
             assert closing.is_alive()
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 0ddd4e49..0f6bd0d6 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -13688,6 +13688,220 @@ def 
test_the_done_error_of_a_progress_handler_keeps_the_execution_error_as_conte
     assert "TABLE_OR_VIEW_NOT_FOUND" in str(raised.value.__context__)
 
 
+def _progress_of_one_stage(service):
+    # ExecutePlanResponse.execution_progress=18 -> ExecutionProgress.stages=1 
(StageInfo
+    # stage_id=1, num_tasks=2, num_completed_tasks=3, input_bytes_read=4, 
done=5),
+    # num_inflight_tasks=2.
+    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))
+
+
+def 
test_a_progress_handler_registered_while_the_handlers_are_cleared_is_called(mock_connect):
+    # Clearing the handlers drops them, which runs the __del__ of one that 
nothing else holds;
+    # a handler that it registers is in the list after the clear, as in the 
_progress_handlers
+    # of PySpark's client, and is called. The number of handlers that the 
client keeps beside
+    # the list must not be left at that of the cleared list.
+    spark, service = mock_connect
+    _progress_of_one_stage(service)
+    calls = []
+
+    def late(**kwargs):
+        calls.append(kwargs["done"])
+
+    class Registering:
+        def __call__(self, **kwargs):
+            pass
+
+        def __del__(self):
+            spark.registerProgressHandler(late)
+
+    spark.registerProgressHandler(Registering())
+    spark.clearProgressHandlers()
+    try:
+        spark.range(1).collect()
+    finally:
+        spark.clearProgressHandlers()
+    assert calls == [False, True]
+
+
+def 
test_progress_handlers_registered_and_removed_by_many_threads_at_once(mock_connect):
+    # Threads that register and remove their own handlers at once leave the 
handlers, and the
+    # number of them that the client keeps beside the list, as the last change 
left them: a
+    # handler registered after them is called, and none is once they are all 
removed.
+    import threading
+
+    spark, service = mock_connect
+    _progress_of_one_stage(service)
+    threads, rounds = 8, 200
+    barrier = threading.Barrier(threads)
+    failures, calls = [], []
+
+    def work(index):
+        def own(**kwargs):
+            calls.append(index)
+
+        try:
+            barrier.wait(10)
+            for _ in range(rounds):
+                spark.registerProgressHandler(own)
+                spark.removeProgressHandler(own)
+        except BaseException as error:  # noqa: BLE001
+            failures.append(error)
+
+    def kept(**kwargs):
+        calls.append("kept")
+
+    spark.registerProgressHandler(kept)
+    workers = [threading.Thread(target=work, args=(index,)) for index in 
range(threads)]
+    for worker in workers:
+        worker.start()
+    for worker in workers:
+        worker.join(60)
+    assert failures == []
+    try:
+        spark.range(1).collect()
+        assert calls == ["kept", "kept"]
+        spark.removeProgressHandler(kept)
+        calls.clear()
+        spark.range(1).collect()
+        assert calls == []
+    finally:
+        spark.clearProgressHandlers()
+
+
+def 
test_a_local_iterator_that_a_thread_is_running_raises_as_a_generator_does(mock_connect):
+    # As PySpark's toLocalIterator, a generator: while a thread waits in it 
for the next row,
+    # the next or close of another thread raises the ValueError of a generator 
that is already
+    # executing, and the iterator goes on for the thread that runs it.
+    import threading
+
+    spark, service = mock_connect
+    _two_row_range_results(service)
+    service.block_result_complete = True
+    rows = spark.range(2).toLocalIterator()
+    assert [next(rows).id, next(rows).id] == [0, 1]
+    entering = threading.Event()
+    outcome = []
+
+    def wait_for_the_end():
+        entering.set()
+        try:
+            outcome.append(next(rows))
+        except BaseException as error:  # noqa: BLE001
+            outcome.append(error)
+
+    waiting = threading.Thread(target=wait_for_the_end)
+    waiting.start()
+    try:
+        assert entering.wait(5)
+        # The thread is in the fetch, without the GIL, once it has not ended 
for a while.
+        waiting.join(0.5)
+        assert waiting.is_alive()
+        for call in (lambda: next(rows), rows.close):
+            with pytest.raises(ValueError, match="generator already 
executing"):
+                call()
+    finally:
+        service.block_result_complete = False
+        service.release_response()
+        waiting.join(10)
+    assert not waiting.is_alive()
+    [ended] = outcome
+    assert isinstance(ended, StopIteration)
+    assert list(rows) == []
+
+
+def 
test_the_done_error_of_a_handler_that_refuses_attributes_keeps_its_context(mock_connect):
+    # As Python chains an exception raised while another is handled, which 
PySpark's
+    # Progress.__exit__ relies on: the context is not set through the 
__setattr__ of the
+    # exception, so one that refuses attributes has it too.
+    from pyspark.errors import AnalysisException
+
+    class Refusing(ValueError):
+        def __setattr__(self, name, value):
+            raise AttributeError(name)
+
+    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 = Refusing("done")
+
+    def failing(**kwargs):
+        if kwargs["done"]:
+            raise error
+
+    spark.registerProgressHandler(failing)
+    try:
+        with pytest.raises(Refusing) 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)
+
+
+def test_a_failure_to_make_the_exception_of_a_server_error_is_its_context(
+        mock_connect, monkeypatch):
+    # Should the exception of the connect classes of an error of the server 
fail to be made,
+    # the error is raised as the class of its kind, and the failure is not 
dropped: it is the
+    # __context__ of the exception that is raised.
+    import pyspark.errors.exceptions.connect as connect_errors
+    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"))
+    failure = LookupError("no exception of the connect classes")
+
+    def failing(**kwargs):
+        raise failure
+
+    monkeypatch.setattr(connect_errors, "_convert_server_error", failing)
+    try:
+        with pytest.raises(AnalysisException) as raised:
+            spark.range(1).collect()
+    finally:
+        service.execute_error = None
+    assert "TABLE_OR_VIEW_NOT_FOUND" in str(raised.value)
+    assert raised.value.__context__ is failure
+
+
+def 
test_an_exception_that_refuses_its_operation_id_is_raised_and_the_refusal_reported(
+        mock_connect, monkeypatch):
+    # The _operation_id that the client stamps on the exception of an 
execution, as the
+    # reference client does, is auxiliary: an exception that refuses it is the 
one raised, and
+    # the refusal goes to sys.unraisablehook rather than nowhere.
+    import sys
+
+    import pyspark.errors.exceptions.connect as connect_errors
+
+    class Refusing(Exception):
+        def __setattr__(self, name, value):
+            raise AttributeError(f"refused {name}")
+
+    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 = Refusing("server")
+    unraisable = []
+    monkeypatch.setattr(sys, "unraisablehook", unraisable.append)
+    monkeypatch.setattr(connect_errors, "_convert_server_error", lambda 
**kwargs: error)
+    try:
+        with pytest.raises(Refusing) as raised:
+            spark.range(1).collect()
+    finally:
+        service.execute_error = None
+    assert raised.value is error
+    [reported] = unraisable
+    assert isinstance(reported.exc_value, AttributeError)
+    assert "refused _operation_id" in str(reported.exc_value)
+    assert reported.object is error
+
+
 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:


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

Reply via email to