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 1fd443d2 [SPARK-61259][CONNECT][PYTHON] Raise KeyboardInterrupt on 
SIGINT during a running action in the Python client, as PySpark does
1fd443d2 is described below

commit 1fd443d2a0efaa82db8f55e3b1ce40493ddbf51c
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 15:52:14 2026 +0900

    [SPARK-61259][CONNECT][PYTHON] Raise KeyboardInterrupt on SIGINT during a 
running action in the Python client, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61259](https://issues.apache.org/jira/browse/SPARK-61259): Raise 
`KeyboardInterrupt` on SIGINT during a running action in the Python client, as 
PySpark does.
    
    - `runtime::with_wait_watch` installs a poll on the current thread. While a 
wait for the server runs on that thread (the plain path and `block_in_place` 
inside a multi-thread runtime), `block_on` races the future against a 200 ms 
tick and calls the poll on each tick. The current-thread path 
(`block_on_other_thread`) is unchanged and does not poll.
    - `pyspark-rs` `interrupt::interruptible` (used by the actions, writers, 
commands, stream and catalog calls, ML fit/evaluate, and pipelines that wait on 
the server) installs a poll that takes the GIL for `check_signals`. When a 
handler raises, it returns an interrupt for the execution in flight of the 
calling thread (`SparkSession::running_operation_id`, an `Interrupt` by 
operation ID as PySpark's handler sends it). The future is then driven to its 
end, and the handler's exception is  [...]
    - `SparkConnectClient::running_operation_id` reads an in-flight registry of 
executions, keyed by the calling thread, which the reattachable stream 
registers before its first RPC.
    - The raw transport stub that the reference client drives 
(`RustConnectStub`: `execute_plan`, `reattach_execute`, and the reads of 
`ResponseStream`) raises the handler's exception from the waiting call; the 
reference client's own handler then interrupts the operation.
    
    Not converted: analysis-only and configuration calls, `addArtifacts` (an 
upload with no operation to interrupt), and the listener-event reader that a 
daemon thread consumes. An analysis still waiting for its response is not 
interrupted; its exception is raised when the response arrives. A call made 
inside a `current_thread` Tokio runtime waits on another thread (SPARK-61250) 
and does not poll the signals. PySpark releases the execution 
(`ReleaseExecute`) before it sends the interrupt; [...]
    
    ### Why are the changes needed?
    
    With a Spark 4.3.0 Connect server on loopback, the issue's repro 
(`spark.range(0, 10**12, 1, 2).agg(F.sum(F.sqrt("id"))).collect()` with a 
`SIGINT` three seconds in) stayed blocked for 60 seconds on master. PySpark 
4.3.0 raises `KeyboardInterrupt` after 3.00 seconds, the server cancels the 
operation, and `spark.range(3).count()` returns 3. This change matches that.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A `SIGINT` (or an exception raised by a Python signal handler) during 
a long-running call in the Python client raises that exception promptly, and 
the server cancels the operation. Previously the call kept blocking. Successful 
results are unchanged.
    
    ### How was this patch tested?
    
    - Offline Python (new in `python/tests/test_dropin_offline.py`, with the 
mock server recording `Interrupt` requests and ending a held execution when it 
is interrupted): 
`test_sigint_during_collect_raises_keyboard_interrupt_and_interrupts_the_operation`,
 `test_exception_of_a_signal_handler_is_raised_by_collect_as_pyspark`, and 
`test_sigint_while_the_transport_waits_raises_keyboard_interrupt[execute|next]`.
 They fail on the parent commit: the call waits for the mock's 5-second 
deadline  [...]
    - Live Python (new in `python/tests/test_dropin_e2e.py`): the issue's repro 
in a subprocess raises `KeyboardInterrupt` after 3.0 s, `interruptAll()` 
returns `[]`, and `count()` returns 3; and 
`test_progress_handlers_run_on_the_thread_of_an_interruptible_collect_as_pyspark`,
 which records `threading.get_ident()` in a progress handler (main thread for 
all 14 calls; PySpark 4.3.0 gives the same).
    - Live Rust (new in `crates/spark-connect/tests/e2e_session_catalog.rs`): a 
wait with a watch that interrupts after 2 seconds cancels the execution 
(`collect` fails, `interrupt_all` is empty, and the session then counts 3 rows).
    - Rust unit tests (new in `runtime.rs`): the watch is called while a future 
waits, an interrupt is driven to the end of the wait, and `with_wait_watch` 
restores the enclosing watch; plus 
`client::tests::test_running_operation_id_is_the_innermost_execution_of_the_calling_thread`.
    - Overhead on a short call (1000 × `count()` of `spark.range(1)`, best of 
2, alternating with the parent commit): 18.99 / 19.05 ms before, 19.05 / 19.19 
ms after. Unconverted `spark.conf.get`: 0.09 ms in both.
    - Existing suites: `cargo test -p apache-spark-connect-core --lib` (154 
passed), `cargo test -p apache-spark-connect --lib` (528 passed), `--no-run` 
for the default and `wasm-udf` builds, `cargo fmt --all --check`; offline 
Python `test_dropin_offline.py test_ml_offline.py test_arrow_handoff.py` (2931 
passed, 8 skipped); live Python `test_arrow_e2e.py test_dropin_e2e.py 
test_ml_e2e.py` (238 passed, 1 skipped); live Rust `e2e_session_catalog`, 
`e2e_dataframe`, `e2e_streaming`, `e2e_inte [...]
    - Clippy: no diagnostics on the changed lines. `pyspark-rs` has 71 
diagnostics in the workspace against 125 on master (the closure 
`result_large_err` lint that the replaced `py.detach` closures also triggered, 
now fixed on the changed call sites).
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #455 from tdcmeehan/SPARK-61259-keyboard-interrupt.
    
    Lead-authored-by: Timothy Meehan <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/catalog.rs                  |   5 +-
 crates/pyspark-rs/src/dataframe.rs                | 257 ++++++++++++++--------
 crates/pyspark-rs/src/datasource.rs               |   7 +-
 crates/pyspark-rs/src/interrupt.rs                |  91 ++++++++
 crates/pyspark-rs/src/lib.rs                      |   1 +
 crates/pyspark-rs/src/ml.rs                       |  57 +++--
 crates/pyspark-rs/src/pipelines.rs                | 117 +++++-----
 crates/pyspark-rs/src/session.rs                  |  62 +++---
 crates/pyspark-rs/src/stat_arguments.rs           |  13 +-
 crates/pyspark-rs/src/streaming.rs                |  83 ++++---
 crates/pyspark-rs/src/transport.rs                |  64 ++++--
 crates/spark-connect-core/src/client.rs           | 109 +++++++++
 crates/spark-connect-core/src/runtime.rs          | 137 +++++++++++-
 crates/spark-connect/src/group.rs                 |   5 +
 crates/spark-connect/src/merge.rs                 |   5 +
 crates/spark-connect/src/readwriter.rs            |   8 +
 crates/spark-connect/src/session.rs               |  13 ++
 crates/spark-connect/src/streaming.rs             |  12 +
 crates/spark-connect/tests/e2e_session_catalog.rs |  58 +++++
 python/tests/_mock_connect_server.py              |  34 ++-
 python/tests/test_dropin_e2e.py                   |  58 +++++
 python/tests/test_dropin_offline.py               |  84 +++++++
 22 files changed, 1022 insertions(+), 258 deletions(-)

diff --git a/crates/pyspark-rs/src/catalog.rs b/crates/pyspark-rs/src/catalog.rs
index e6a6a45a..7911a7e0 100644
--- a/crates/pyspark-rs/src/catalog.rs
+++ b/crates/pyspark-rs/src/catalog.rs
@@ -10,6 +10,7 @@ use spark_connect_core::error::SparkError;
 
 use crate::dataframe::PyDataFrame;
 use crate::errors::ResultExt;
+use crate::interrupt::interruptible;
 
 /// PySpark's FutureWarning of the deprecated `dbName` of the catalog method 
`method`.
 fn warn_db_name(py: Python<'_>, method: &str, db_name: Option<&str>) -> 
PyResult<()> {
@@ -179,13 +180,13 @@ impl PyCatalog {
     }
 
     /// `f` of the catalog without the GIL, as PySpark's requests to the 
server release it
-    /// while they wait, so that other Python threads run.
+    /// while they wait, so that other Python threads run and a signal 
interrupts the wait.
     fn detached<T: Send>(
         &self,
         py: Python<'_>,
         f: impl FnOnce(&Catalog) -> Result<T, Box<SparkError>> + Send,
     ) -> PyResult<T> {
-        py.detach(|| f(&self.catalog)).to_pyerr()
+        interruptible(py, self.catalog.spark_session(), || f(&self.catalog))
     }
 }
 
diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 90ce443e..6359ff82 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -9,6 +9,7 @@ use spark_connect::udf::{eval_type, 
CommonInlineUserDefinedFunctionExpression, P
 use crate::column::PyColumn;
 use crate::errors::ResultExt;
 use crate::group::PyGroupedData;
+use crate::interrupt::interruptible;
 use crate::row::{FieldConverters, NestedFieldNames};
 use crate::streaming::PyDataStreamWriter;
 use crate::types::PyDataType;
@@ -98,16 +99,22 @@ impl PyDataFrame {
     ) -> PyResult<Py<PyAny>> {
         let settings = py
             .detach(|| {
-                self.dataframe.spark_session().conf().get_many(&[
-                    "spark.sql.session.timeZone",
-                    "spark.sql.execution.pandas.structHandlingMode",
-                    "spark.sql.execution.arrow.pyspark.selfDestruct.enabled",
-                ])
+                self.dataframe
+                    .spark_session()
+                    .conf()
+                    .get_many(&[
+                        "spark.sql.session.timeZone",
+                        "spark.sql.execution.pandas.structHandlingMode",
+                        
"spark.sql.execution.arrow.pyspark.selfDestruct.enabled",
+                    ])
+                    .map_err(Box::new)
             })
             .to_pyerr()?;
-        let (batches, schema) = py
-            .detach(|| self.dataframe.collect_record_batches_with_schema())
-            .to_pyerr()?;
+        let (batches, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
+            self.dataframe
+                .collect_record_batches_with_schema()
+                .map_err(Box::new)
+        })?;
         check_nanosecond_timestamps(py, schema.as_ref())?;
         let table = crate::pyarrow_export::record_batches_to_pyarrow(py, 
batches)?;
         let schema = match &schema {
@@ -192,8 +199,11 @@ impl PyDataFrame {
                 }
             };
         let (n, vertical) = (n.extract::<i32>()?, vertical.extract::<bool>()?);
-        py.detach(|| self.dataframe.show_string(n, truncate, vertical))
-            .to_pyerr()
+        interruptible(py, &self.dataframe.spark_session(), || {
+            self.dataframe
+                .show_string(n, truncate, vertical)
+                .map_err(Box::new)
+        })
     }
 
     pub fn new(dataframe: DataFrame) -> Self {
@@ -207,7 +217,9 @@ impl PyDataFrame {
     /// each setting, if it is enabled.
     fn eager_eval(&self, py: Python<'_>) -> PyResult<Option<(i32, i32)>> {
         let conf = self.dataframe.spark_session().conf();
-        let values = py.detach(|| conf.get_many(&EAGER_EVAL)).to_pyerr()?;
+        let values = py
+            .detach(|| conf.get_many(&EAGER_EVAL).map_err(Box::new))
+            .to_pyerr()?;
         if values[0].as_deref() != Some("true") {
             return Ok(None);
         }
@@ -1448,7 +1460,8 @@ impl PyDataFrame {
     /// The server-side hash of this DataFrame's logical plan.
     #[pyo3(name = "semanticHash")]
     fn semantic_hash(&self, py: Python<'_>) -> PyResult<i32> {
-        py.detach(|| self.dataframe.semantic_hash()).to_pyerr()
+        py.detach(|| self.dataframe.semantic_hash().map_err(Box::new))
+            .to_pyerr()
     }
 
     /// Sort within each partition.
@@ -1601,15 +1614,22 @@ impl PyDataFrame {
                 ))
             }
         };
-        py.detach(|| self.dataframe.explain_string(&explain_mode))
-            .to_pyerr()
+        py.detach(|| {
+            self.dataframe
+                .explain_string(&explain_mode)
+                .map_err(Box::new)
+        })
+        .to_pyerr()
     }
 
     /// Register this DataFrame as a temporary view.
     #[pyo3(name = "createOrReplaceTempView")]
     fn create_or_replace_temp_view(&self, py: Python<'_>, name: &str) -> 
PyResult<()> {
-        py.detach(|| self.dataframe.create_or_replace_temp_view(name))
-            .to_pyerr()
+        interruptible(py, &self.dataframe.spark_session(), || {
+            self.dataframe
+                .create_or_replace_temp_view(name)
+                .map_err(Box::new)
+        })
     }
 
     /// Drop rows containing nulls, as PySpark's `DataFrame.dropna`.
@@ -1719,7 +1739,11 @@ impl PyDataFrame {
         {
             let observation = &observation.inner;
             return py
-                .detach(|| self.dataframe.observe_with(observation, columns))
+                .detach(|| {
+                    self.dataframe
+                        .observe_with(observation, columns)
+                        .map_err(Box::new)
+                })
                 .to_pyerr()
                 .map(PyDataFrame::new);
         }
@@ -1743,38 +1767,47 @@ impl PyDataFrame {
     /// Register as a temporary view (session-scoped).
     #[pyo3(name = "createTempView")]
     fn create_temp_view(&self, py: Python<'_>, name: &str) -> PyResult<()> {
-        py.detach(|| self.dataframe.create_temp_view(name))
-            .to_pyerr()
+        interruptible(py, &self.dataframe.spark_session(), || {
+            self.dataframe.create_temp_view(name).map_err(Box::new)
+        })
     }
 
     /// Register as a global temporary view.
     #[pyo3(name = "createGlobalTempView")]
     fn create_global_temp_view(&self, py: Python<'_>, name: &str) -> 
PyResult<()> {
-        py.detach(|| self.dataframe.create_global_temp_view(name))
-            .to_pyerr()
+        interruptible(py, &self.dataframe.spark_session(), || {
+            self.dataframe
+                .create_global_temp_view(name)
+                .map_err(Box::new)
+        })
     }
 
     /// Register as (or replace) a global temporary view.
     #[pyo3(name = "createOrReplaceGlobalTempView")]
     fn create_or_replace_global_temp_view(&self, py: Python<'_>, name: &str) 
-> PyResult<()> {
-        py.detach(|| self.dataframe.create_or_replace_global_temp_view(name))
-            .to_pyerr()
+        interruptible(py, &self.dataframe.spark_session(), || {
+            self.dataframe
+                .create_or_replace_global_temp_view(name)
+                .map_err(Box::new)
+        })
     }
 
     /// Deprecated alias for createOrReplaceTempView.
     #[pyo3(name = "registerTempTable")]
     fn register_temp_table(&self, py: Python<'_>, name: &str) -> PyResult<()> {
-        py.detach(|| self.dataframe.register_temp_table(name))
-            .to_pyerr()
+        interruptible(py, &self.dataframe.spark_session(), || {
+            self.dataframe.register_temp_table(name).map_err(Box::new)
+        })
     }
 
     /// Reliable checkpoint (materialize + truncate lineage), at once if 
`eager`, as PySpark's.
     #[pyo3(signature = (eager=true))]
     fn checkpoint(&self, py: Python<'_>, eager: bool) -> PyResult<PyDataFrame> 
{
-        Ok(PyDataFrame::new(
-            py.detach(|| 
self.dataframe.checkpoint_with(eager).map_err(Box::new))
-                .to_pyerr()?,
-        ))
+        Ok(PyDataFrame::new(interruptible(
+            py,
+            &self.dataframe.spark_session(),
+            || self.dataframe.checkpoint_with(eager).map_err(Box::new),
+        )?))
     }
 
     /// Local checkpoint, at once if `eager`, kept at `storageLevel`, else at 
the server's
@@ -1790,14 +1823,15 @@ impl PyDataFrame {
             .filter(|level| !level.is_none())
             .map(|level| crate::storagelevel::storage_level_proto(&level))
             .transpose()?;
-        Ok(PyDataFrame::new(
-            py.detach(|| {
+        Ok(PyDataFrame::new(interruptible(
+            py,
+            &self.dataframe.spark_session(),
+            || {
                 self.dataframe
                     .local_checkpoint_with(eager, level)
                     .map_err(Box::new)
-            })
-            .to_pyerr()?,
-        ))
+            },
+        )?))
     }
 
     /// Pearson correlation between two columns; PySpark's `method` is only 
"pearson".
@@ -1951,7 +1985,8 @@ impl PyDataFrame {
     /// The list of files that make up this DataFrame.
     #[pyo3(name = "inputFiles")]
     fn input_files(&self, py: Python<'_>) -> PyResult<Vec<String>> {
-        py.detach(|| self.dataframe.input_files()).to_pyerr()
+        py.detach(|| self.dataframe.input_files().map_err(Box::new))
+            .to_pyerr()
     }
 
     /// Whether the server answers that this DataFrame is local (a local 
relation).
@@ -1965,7 +2000,8 @@ impl PyDataFrame {
     #[pyo3(name = "is_cached")]
     #[getter]
     fn is_cached(&self, py: Python<'_>) -> PyResult<bool> {
-        py.detach(|| self.dataframe.is_cached()).to_pyerr()
+        py.detach(|| self.dataframe.is_cached().map_err(Box::new))
+            .to_pyerr()
     }
 
     /// Whether this DataFrame contains one or more sources that continuously 
return data.
@@ -1980,7 +2016,9 @@ impl PyDataFrame {
     #[pyo3(name = "storageLevel")]
     #[getter]
     fn storage_level(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
-        let sl = py.detach(|| self.dataframe.storage_level()).to_pyerr()?;
+        let sl = py
+            .detach(|| self.dataframe.storage_level().map_err(Box::new))
+            .to_pyerr()?;
         let cls = py.import("pyspark.storagelevel")?.getattr("StorageLevel")?;
         Ok(cls
             .call1((
@@ -2220,9 +2258,9 @@ impl PyDataFrame {
     /// Collect all rows into memory.
     fn collect(&self, py: Python<'_>) -> PyResult<Vec<Py<PyAny>>> {
         // Release the GIL across the blocking RPC so other Python threads run.
-        let (rows, schema) = py
-            .detach(|| self.dataframe.collect_with_schema())
-            .to_pyerr()?;
+        let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
+            self.dataframe.collect_with_schema().map_err(Box::new)
+        })?;
         rows_to_py(py, &self.dataframe, &rows, schema.as_ref())
     }
 
@@ -2252,13 +2290,11 @@ impl PyDataFrame {
     /// alignment and schemas requiring the IPC compatibility fallback can 
still copy.
     #[pyo3(name = "toArrow")]
     fn to_arrow(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
-        let (batches, schema) = py
-            .detach(|| {
-                self.dataframe
-                    .collect_record_batches_with_schema()
-                    .map_err(Box::new)
-            })
-            .to_pyerr()?;
+        let (batches, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
+            self.dataframe
+                .collect_record_batches_with_schema()
+                .map_err(Box::new)
+        })?;
         check_nanosecond_timestamps(py, schema.as_ref())?;
         let table = crate::pyarrow_export::record_batches_to_pyarrow(py, 
batches)?;
         let Some(schema) = schema else {
@@ -2327,7 +2363,9 @@ impl PyDataFrame {
 
     /// Get the count of rows.
     fn count(&self, py: Python<'_>) -> PyResult<i64> {
-        py.detach(|| self.dataframe.count()).to_pyerr()
+        interruptible(py, &self.dataframe.spark_session(), || {
+            self.dataframe.count().map_err(Box::new)
+        })
     }
 
     /// Print the first `n` rows as the server formats them. Mirrors 
`DataFrame.show`, which
@@ -2423,16 +2461,18 @@ impl PyDataFrame {
     /// `df.schema.fields`, `df.schema["c"]`, `df.schema.fieldNames()` all 
work.
     #[getter]
     fn schema(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
-        let schema = py.detach(|| self.dataframe.schema()).to_pyerr()?;
+        let schema = py
+            .detach(|| self.dataframe.schema().map_err(Box::new))
+            .to_pyerr()?;
         check_nanosecond_timestamps(py, Some(&schema))?;
         crate::types::data_type_to_py(py, &schema)
     }
 
     /// Get the first row.
     fn first(&self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
-        let (row, schema) = py
-            .detach(|| self.dataframe.first_with_schema())
-            .to_pyerr()?;
+        let (row, schema) = interruptible(py, &self.dataframe.spark_session(), 
|| {
+            self.dataframe.first_with_schema().map_err(Box::new)
+        })?;
         Ok(rows_to_py(py, &self.dataframe, row.as_slice(), 
schema.as_ref())?.pop())
     }
 
@@ -2445,9 +2485,12 @@ impl PyDataFrame {
             None => self.first(py)?.into_py_any(py),
             // head(n) -> a list of the first n Rows.
             Some(k) => {
-                let (rows, schema) = py
-                    .detach(|| self.dataframe.limit(k).collect_with_schema())
-                    .to_pyerr()?;
+                let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
+                    self.dataframe
+                        .limit(k)
+                        .collect_with_schema()
+                        .map_err(Box::new)
+                })?;
                 rows_to_py(py, &self.dataframe, &rows, 
schema.as_ref())?.into_py_any(py)
             }
         }
@@ -2456,9 +2499,12 @@ impl PyDataFrame {
     /// Get the first n rows, as PySpark's `DataFrame.take`, which is 
`limit(num).collect()`, so
     /// the server checks `num`.
     fn take(&self, py: Python<'_>, num: i32) -> PyResult<Vec<Py<PyAny>>> {
-        let (rows, schema) = py
-            .detach(|| self.dataframe.limit(num).collect_with_schema())
-            .to_pyerr()?;
+        let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
+            self.dataframe
+                .limit(num)
+                .collect_with_schema()
+                .map_err(Box::new)
+        })?;
         rows_to_py(py, &self.dataframe, &rows, schema.as_ref())
     }
 
@@ -2473,9 +2519,12 @@ impl PyDataFrame {
 
     /// Get the last `num` rows as a list of Rows (eager, like pyspark `tail`).
     fn tail(&self, py: Python<'_>, num: i32) -> PyResult<Vec<Py<PyAny>>> {
-        let (rows, schema) = py
-            .detach(|| self.dataframe.tail(num).collect_with_schema())
-            .to_pyerr()?;
+        let (rows, schema) = interruptible(py, 
&self.dataframe.spark_session(), || {
+            self.dataframe
+                .tail(num)
+                .collect_with_schema()
+                .map_err(Box::new)
+        })?;
         rows_to_py(py, &self.dataframe, &rows, schema.as_ref())
     }
 
@@ -2549,7 +2598,9 @@ impl PyDataFrame {
 
     /// Check if the DataFrame is empty.
     fn isEmpty(&self, py: Python<'_>) -> PyResult<bool> {
-        detached(py, || self.dataframe.is_empty().map_err(Box::new))
+        interruptible(py, &self.dataframe.spark_session(), || {
+            self.dataframe.is_empty().map_err(Box::new)
+        })
     }
 
     /// Print the schema through Python stdout, honoring the maximum nesting 
depth.
@@ -2703,9 +2754,11 @@ impl PyDataFrame {
             .load(std::sync::atomic::Ordering::Relaxed)
         {
             if let Some((n, truncate)) = self.eager_eval(py)? {
-                return py
-                    .detach(|| self.dataframe.show_string(n, truncate, false))
-                    .to_pyerr();
+                return interruptible(py, &self.dataframe.spark_session(), || {
+                    self.dataframe
+                        .show_string(n, truncate, false)
+                        .map_err(Box::new)
+                });
             }
         }
         let fields = self
@@ -2725,10 +2778,10 @@ impl PyDataFrame {
         self.support_repr_html
             .store(true, std::sync::atomic::Ordering::Relaxed);
         match self.eager_eval(py)? {
-            Some((n, truncate)) => py
-                .detach(|| self.dataframe.html_string(n, truncate))
-                .to_pyerr()
-                .map(Some),
+            Some((n, truncate)) => interruptible(py, 
&self.dataframe.spark_session(), || {
+                self.dataframe.html_string(n, truncate).map_err(Box::new)
+            })
+            .map(Some),
             None => Ok(None),
         }
     }
@@ -2745,7 +2798,9 @@ impl PyDataFrame {
         profile: Option<Bound<'_, PyAny>>,
     ) -> PyResult<PyDataFrame> {
         validate_map_function(py, &func, eval_type::SQL_MAP_PANDAS_ITER_UDF)?;
-        let cols = py.detach(|| self.dataframe.columns()).to_pyerr()?;
+        let cols = py
+            .detach(|| self.dataframe.columns().map_err(Box::new))
+            .to_pyerr()?;
         let udf = build_map_udf(
             py,
             &self.dataframe.spark_session(),
@@ -2773,7 +2828,9 @@ impl PyDataFrame {
         profile: Option<Bound<'_, PyAny>>,
     ) -> PyResult<PyDataFrame> {
         validate_map_function(py, &func, eval_type::SQL_MAP_ARROW_ITER_UDF)?;
-        let cols = py.detach(|| self.dataframe.columns()).to_pyerr()?;
+        let cols = py
+            .detach(|| self.dataframe.columns().map_err(Box::new))
+            .to_pyerr()?;
         let udf = build_map_udf(
             py,
             &self.dataframe.spark_session(),
@@ -3261,7 +3318,9 @@ impl PyMergeIntoWriter {
 
     fn merge(&self, py: Python<'_>) -> PyResult<()> {
         let writer = self.inner.get();
-        detached(py, || writer.merge().map_err(Box::new))
+        interruptible(py, &writer.spark_session(), || {
+            writer.merge().map_err(Box::new)
+        })
     }
 }
 
@@ -3570,7 +3629,7 @@ impl PyDataFrameWriter {
         }
         w = w.option("url", url).option("dbtable", table);
         self.inner.set(w.clone());
-        detached(py, || w.save(None).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || 
w.save(None).map_err(Box::new))
     }
 
     #[pyo3(signature = (path=None, format=None, mode=None, partitionBy=None, 
**options))]
@@ -3587,7 +3646,9 @@ impl PyDataFrameWriter {
         let w = apply_write_common(self.inner.get(), format, mode, 
partitionBy, options)?;
         // PySpark sets the inline format/mode/partitionBy/options on the 
writer itself.
         self.inner.set(w.clone());
-        detached(py, || w.save(path.as_deref()).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || {
+            w.save(path.as_deref()).map_err(Box::new)
+        })
     }
 
     #[pyo3(name = "saveAsTable", signature = (name, format=None, mode=None, 
partitionBy=None, **options))]
@@ -3603,7 +3664,9 @@ impl PyDataFrameWriter {
     ) -> PyResult<()> {
         let w = apply_write_common(self.inner.get(), format, mode, 
partitionBy, options)?;
         self.inner.set(w.clone());
-        detached(py, || w.save_as_table(name).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || {
+            w.save_as_table(name).map_err(Box::new)
+        })
     }
 
     /// Insert into an existing table. `overwrite` maps to overwrite/append 
mode,
@@ -3621,7 +3684,9 @@ impl PyDataFrameWriter {
         }
         // PySpark sets the overwrite/append mode on the writer itself.
         self.inner.set(w.clone());
-        detached(py, || w.insert_into(tableName).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || {
+            w.insert_into(tableName).map_err(Box::new)
+        })
     }
 
     /// Write as PARQUET - full pyspark signature; each named option is
@@ -3651,7 +3716,7 @@ impl PyDataFrameWriter {
         w = wset_opt(w, "compression", compression)?;
         // PySpark sets the mode/options/format on the writer itself, then 
saves.
         self.inner.set(w.clone().format("parquet"));
-        detached(py, || w.parquet(path).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || 
w.parquet(path).map_err(Box::new))
     }
 
     /// Write as JSON - full pyspark signature; each named option is
@@ -3682,7 +3747,7 @@ impl PyDataFrameWriter {
         w = wset_opt(w, "ignoreNullFields", ignoreNullFields)?;
         // PySpark sets the mode/options/format on the writer itself, then 
saves.
         self.inner.set(w.clone().format("json"));
-        detached(py, || w.json(path).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || 
w.json(path).map_err(Box::new))
     }
 
     /// Write as CSV - full pyspark signature; each named option is
@@ -3733,7 +3798,7 @@ impl PyDataFrameWriter {
         w = wset_opt(w, "lineSep", lineSep)?;
         // PySpark sets the mode/options/format on the writer itself, then 
saves.
         self.inner.set(w.clone().format("csv"));
-        detached(py, || w.csv(path).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || w.csv(path).map_err(Box::new))
     }
 
     /// Write as ORC - full pyspark signature; each named option is
@@ -3763,7 +3828,7 @@ impl PyDataFrameWriter {
         w = wset_opt(w, "compression", compression)?;
         // PySpark sets the mode/options/format on the writer itself, then 
saves.
         self.inner.set(w.clone().format("orc"));
-        detached(py, || w.orc(path).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || w.orc(path).map_err(Box::new))
     }
 
     /// Write as TEXT - full pyspark signature; each named option is
@@ -3782,7 +3847,7 @@ impl PyDataFrameWriter {
         w = wset_opt(w, "lineSep", lineSep)?;
         // PySpark sets the mode/options/format on the writer itself, then 
saves.
         self.inner.set(w.clone().format("text"));
-        detached(py, || w.text(path).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || 
w.text(path).map_err(Box::new))
     }
 
     /// Write as XML - full pyspark signature; each named option is
@@ -3825,7 +3890,7 @@ impl PyDataFrameWriter {
         w = wset_opt(w, "validateName", validateName)?;
         // PySpark sets the mode/options/format on the writer itself, then 
saves.
         self.inner.set(w.clone().format("xml"));
-        detached(py, || w.xml(path).map_err(Box::new))
+        interruptible(py, &w.spark_session(), || w.xml(path).map_err(Box::new))
     }
 }
 
@@ -3944,36 +4009,48 @@ impl PyDataFrameWriterV2 {
 
     fn create(&self, py: Python<'_>) -> PyResult<()> {
         let writer = self.inner.get();
-        detached(py, || writer.create().map_err(Box::new))
+        interruptible(py, &writer.spark_session(), || {
+            writer.create().map_err(Box::new)
+        })
     }
 
     fn replace(&self, py: Python<'_>) -> PyResult<()> {
         let writer = self.inner.get();
-        detached(py, || writer.replace().map_err(Box::new))
+        interruptible(py, &writer.spark_session(), || {
+            writer.replace().map_err(Box::new)
+        })
     }
 
     #[pyo3(name = "createOrReplace")]
     fn create_or_replace(&self, py: Python<'_>) -> PyResult<()> {
         let writer = self.inner.get();
-        detached(py, || writer.create_or_replace().map_err(Box::new))
+        interruptible(py, &writer.spark_session(), || {
+            writer.create_or_replace().map_err(Box::new)
+        })
     }
 
     fn append(&self, py: Python<'_>) -> PyResult<()> {
         let writer = self.inner.get();
-        detached(py, || writer.append().map_err(Box::new))
+        interruptible(py, &writer.spark_session(), || {
+            writer.append().map_err(Box::new)
+        })
     }
 
     /// Overwrite the rows of `condition`, a Column or a column name, as 
PySpark's `F._to_col`,
     /// else `NOT_EXPECTED_TYPE` of `col`.
     fn overwrite(&self, py: Python<'_>, condition: &Bound<'_, PyAny>) -> 
PyResult<()> {
         let (writer, condition) = (self.inner.get(), 
column_or_name(condition)?);
-        detached(py, || writer.overwrite(condition).map_err(Box::new))
+        interruptible(py, &writer.spark_session(), || {
+            writer.overwrite(condition).map_err(Box::new)
+        })
     }
 
     #[pyo3(name = "overwritePartitions")]
     fn overwrite_partitions(&self, py: Python<'_>) -> PyResult<()> {
         let writer = self.inner.get();
-        detached(py, || writer.overwrite_partitions().map_err(Box::new))
+        interruptible(py, &writer.spark_session(), || {
+            writer.overwrite_partitions().map_err(Box::new)
+        })
     }
 }
 
@@ -4478,7 +4555,9 @@ impl PyLocalRowIterator {
                 value
             }
         };
-        let next = py.detach(|| self.next_row());
+        let next = interruptible(py, &self.dataframe.spark_session(), || {
+            Ok::<_, 
Box<spark_connect_core::error::SparkError>>(self.next_row())
+        })?;
         if self.converters.is_none() {
             if let Some(schema) = 
self.iterator.as_ref().and_then(LocalRowIterator::schema) {
                 // The result is known once its first message arrives, 
possibly with no rows.
diff --git a/crates/pyspark-rs/src/datasource.rs 
b/crates/pyspark-rs/src/datasource.rs
index 20aa3849..0b5dd2e1 100644
--- a/crates/pyspark-rs/src/datasource.rs
+++ b/crates/pyspark-rs/src/datasource.rs
@@ -6,7 +6,7 @@ use spark_connect::datasource::{
 };
 
 use crate::dataframe::{py_cloudpickle, py_version};
-use crate::errors::ResultExt;
+use crate::interrupt::interruptible;
 use crate::session::PySparkSession;
 
 /// Python accessor for data source registration.
@@ -55,8 +55,9 @@ impl PyDataSourceRegistration {
 
         // Register with the session (release GIL during the RPC)
         let session = self.session.borrow(py).session.clone();
-        py.detach(|| session.register_data_source(expr))
-            .to_pyerr()?;
+        interruptible(py, &session, || {
+            session.register_data_source(expr).map_err(Box::new)
+        })?;
 
         Ok(())
     }
diff --git a/crates/pyspark-rs/src/interrupt.rs 
b/crates/pyspark-rs/src/interrupt.rs
new file mode 100644
index 00000000..114f3e14
--- /dev/null
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -0,0 +1,91 @@
+//! Waits on the server that a signal of the process interrupts, as PySpark's 
waits are.
+//!
+//! The wait runs on the calling thread, as PySpark's does, so the progress 
handlers and the
+//! other callbacks of the execution run there too. The wait polls the signals 
of the process,
+//! which only the main thread of Python runs the handlers of. A handler that 
raises interrupts the
+//! execution in flight of the calling thread on the server; the wait then 
ends with the server's
+//! cancellation, and the exception of the handler is raised.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+
+use pyo3::prelude::*;
+use spark_connect::session::SparkSession;
+use spark_connect_core::error::SparkError;
+use spark_connect_core::runtime::{with_wait_watch, WaitWatch, Watch};
+
+use crate::errors::ResultExt;
+
+/// The poll of the signals of one wait.
+struct SignalWatch {
+    session: SparkSession,
+    /// Whether a handler raised, once: after that, the wait only waits.
+    raised: AtomicBool,
+    /// The exception of the handler, which the wait raises once it has ended.
+    error: Mutex<Option<PyErr>>,
+}
+
+impl SignalWatch {
+    fn poll(&self) -> Watch {
+        if self.raised.load(Ordering::SeqCst) {
+            return Watch::Continue;
+        }
+        // Takes the GIL for the check only, as the wait runs without it.
+        let Err(error) = Python::attach(|py| py.check_signals()) else {
+            return Watch::Continue;
+        };
+        self.raised.store(true, Ordering::SeqCst);
+        *self.error.lock().unwrap_or_else(|e| e.into_inner()) = Some(error);
+        match self.session.running_operation_id() {
+            Some(operation_id) => {
+                let session = self.session.clone();
+                Watch::Interrupt(Box::pin(async move {
+                    // A failed interrupt does not replace the exception of 
the signal.
+                    let _ = 
session.interrupt_operation_async(&operation_id).await;
+                }))
+            }
+            None => Watch::Continue,
+        }
+    }
+}
+
+/// Run `f` without the GIL, on the calling thread, as the signals of the 
process are polled while
+/// it waits for the server. When a handler raises, the execution in flight of 
the calling thread
+/// is interrupted, and the exception of the handler is raised once `f` has 
ended. Otherwise the
+/// result of `f` is returned.
+///
+/// The execution is interrupted only when `f` has started one; a request that 
is still waiting
+/// for its response (such as an analysis) ends when the response arrives, and 
the exception is
+/// raised then.
+pub(crate) fn interruptible<T: Send, E: Send + Into<Box<SparkError>>>(
+    py: Python<'_>,
+    session: &SparkSession,
+    f: impl FnOnce() -> Result<T, E> + Send,
+) -> PyResult<T> {
+    interruptible_outcome(py, session, f)?.to_pyerr()
+}
+
+/// As [`interruptible`], but a failure of `f` is the inner result, which the 
caller handles, as
+/// a warning. The outer error is the exception of a signal handler only, 
which is never handled
+/// as a failure of the call: as PySpark's `except Exception` does not catch 
it.
+pub(crate) fn interruptible_outcome<T: Send, E: Send + Into<Box<SparkError>>>(
+    py: Python<'_>,
+    session: &SparkSession,
+    f: impl FnOnce() -> Result<T, E> + Send,
+) -> PyResult<Result<T, Box<SparkError>>> {
+    let watch = Arc::new(SignalWatch {
+        session: session.clone(),
+        raised: AtomicBool::new(false),
+        error: Mutex::new(None),
+    });
+    let poll: Arc<WaitWatch> = {
+        let watch = Arc::clone(&watch);
+        Arc::new(move || watch.poll())
+    };
+    let output = py.detach(|| with_wait_watch(poll, f));
+    let signal = watch.error.lock().unwrap_or_else(|e| e.into_inner()).take();
+    match signal {
+        Some(error) => Err(error),
+        None => Ok(output.map_err(Into::into)),
+    }
+}
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index de3ec235..c2ab246f 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -35,6 +35,7 @@ mod eval_type;
 mod functions;
 mod group;
 mod infer;
+mod interrupt;
 mod ml;
 mod observation;
 mod origin;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 8c54c2f4..312a2f19 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -14,6 +14,7 @@ use spark_connect::ml::{
 
 use crate::dataframe::PyDataFrame;
 use crate::errors::ResultExt;
+use crate::interrupt::interruptible;
 
 /// A fitted ML model (result of `Estimator.fit`), wrapping a boxed core 
`Model`.
 #[pyclass(name = "MLModel", module = "pyspark.ml.connect")]
@@ -26,7 +27,9 @@ impl PyMLModel {
     /// Apply the model to a DataFrame.
     fn transform(&self, py: Python<'_>, df: &PyDataFrame) -> 
PyResult<PyDataFrame> {
         let mut m = self.model.clone_box();
-        let out = py.detach(|| m.transform(&df.dataframe)).to_pyerr()?;
+        let out = py
+            .detach(|| m.transform(&df.dataframe).map_err(Box::new))
+            .to_pyerr()?;
         Ok(PyDataFrame::new(out))
     }
 }
@@ -66,7 +69,9 @@ impl PyStandardScaler {
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
-        let model = py.detach(|| e.fit(&df.dataframe)).to_pyerr()?;
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            e.fit(&df.dataframe).map_err(Box::new)
+        })?;
         Ok(PyMLModel { model })
     }
 }
@@ -106,7 +111,9 @@ impl PyMaxAbsScaler {
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
-        let model = py.detach(|| e.fit(&df.dataframe)).to_pyerr()?;
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            e.fit(&df.dataframe).map_err(Box::new)
+        })?;
         Ok(PyMLModel { model })
     }
 }
@@ -146,7 +153,9 @@ impl PyStringIndexer {
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
-        let model = py.detach(|| e.fit(&df.dataframe)).to_pyerr()?;
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            e.fit(&df.dataframe).map_err(Box::new)
+        })?;
         Ok(PyMLModel { model })
     }
 }
@@ -188,7 +197,9 @@ impl PyVectorAssembler {
     }
     fn transform(&self, py: Python<'_>, df: &PyDataFrame) -> 
PyResult<PyDataFrame> {
         let mut t = self.inner.clone();
-        let out = py.detach(|| t.transform(&df.dataframe)).to_pyerr()?;
+        let out = py
+            .detach(|| t.transform(&df.dataframe).map_err(Box::new))
+            .to_pyerr()?;
         Ok(PyDataFrame::new(out))
     }
 }
@@ -254,7 +265,9 @@ impl PyLogisticRegression {
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
-        let model = py.detach(|| e.fit(&df.dataframe)).to_pyerr()?;
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            e.fit(&df.dataframe).map_err(Box::new)
+        })?;
         Ok(PyMLModel { model })
     }
 }
@@ -387,9 +400,9 @@ impl PyLinearSVC {
 
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut estimator = self.inner.clone();
-        let model = py
-            .detach(|| estimator.fit(&df.dataframe).map_err(Box::new))
-            .to_pyerr()?;
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            estimator.fit(&df.dataframe).map_err(Box::new)
+        })?;
         Ok(PyMLModel { model })
     }
 }
@@ -535,9 +548,9 @@ impl PyLinearRegression {
 
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut estimator = self.inner.clone();
-        let model = py
-            .detach(|| estimator.fit(&df.dataframe).map_err(Box::new))
-            .to_pyerr()?;
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            estimator.fit(&df.dataframe).map_err(Box::new)
+        })?;
         Ok(PyMLModel { model })
     }
 }
@@ -715,7 +728,9 @@ impl PyRegressionEvaluator {
         }
     }
     fn evaluate(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<f64> {
-        py.detach(|| self.inner.evaluate(&df.dataframe)).to_pyerr()
+        interruptible(py, &df.dataframe.spark_session(), || {
+            self.inner.evaluate(&df.dataframe).map_err(Box::new)
+        })
     }
 }
 
@@ -769,7 +784,9 @@ impl PyBinaryClassificationEvaluator {
         }
     }
     fn evaluate(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<f64> {
-        py.detach(|| self.inner.evaluate(&df.dataframe)).to_pyerr()
+        interruptible(py, &df.dataframe.spark_session(), || {
+            self.inner.evaluate(&df.dataframe).map_err(Box::new)
+        })
     }
 }
 
@@ -800,7 +817,9 @@ impl PyPipeline {
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
-        let model = py.detach(|| e.fit(&df.dataframe)).to_pyerr()?;
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            e.fit(&df.dataframe).map_err(Box::new)
+        })?;
         Ok(PyMLModel { model })
     }
 }
@@ -855,7 +874,9 @@ impl PyMulticlassClassificationEvaluator {
         }
     }
     fn evaluate(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<f64> {
-        py.detach(|| self.inner.evaluate(&df.dataframe)).to_pyerr()
+        interruptible(py, &df.dataframe.spark_session(), || {
+            self.inner.evaluate(&df.dataframe).map_err(Box::new)
+        })
     }
 }
 
@@ -903,7 +924,9 @@ impl PyCrossValidator {
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
-        let model = py.detach(|| e.fit(&df.dataframe)).to_pyerr()?;
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            e.fit(&df.dataframe).map_err(Box::new)
+        })?;
         Ok(PyMLModel { model })
     }
 }
diff --git a/crates/pyspark-rs/src/pipelines.rs 
b/crates/pyspark-rs/src/pipelines.rs
index b5087435..3e273278 100644
--- a/crates/pyspark-rs/src/pipelines.rs
+++ b/crates/pyspark-rs/src/pipelines.rs
@@ -15,6 +15,7 @@ use spark_connect_proto as proto;
 use crate::column::PyColumn;
 use crate::dataframe::PyDataFrame;
 use crate::errors::ResultExt;
+use crate::interrupt::interruptible;
 use crate::session::PySparkSession;
 use crate::types::py_to_data_type;
 
@@ -66,17 +67,15 @@ pub fn pipeline_create_dataflow_graph(
     sql_conf: Option<HashMap<String, String>>,
 ) -> PyResult<String> {
     let sess = session.session.clone();
-    session
-        .py()
-        .detach(|| {
-            pipelines::create_dataflow_graph(
-                &sess,
-                default_catalog,
-                default_database,
-                sql_conf.unwrap_or_default(),
-            )
-        })
-        .to_pyerr()
+    interruptible(session.py(), &sess, || {
+        pipelines::create_dataflow_graph(
+            &sess,
+            default_catalog,
+            default_database,
+            sql_conf.unwrap_or_default(),
+        )
+        .map_err(Box::new)
+    })
 }
 
 /// `PipelineCommand.DefineOutput`. `output_type` is the 
`spark.connect.OutputType` enum
@@ -141,10 +140,9 @@ pub fn pipeline_define_output(
     };
     let sess = session.session.clone();
     let gid = dataflow_graph_id.to_string();
-    session
-        .py()
-        .detach(|| pipelines::define_output(&sess, &gid, spec))
-        .to_pyerr()
+    interruptible(session.py(), &sess, || {
+        pipelines::define_output(&sess, &gid, spec).map_err(Box::new)
+    })
 }
 
 /// `PipelineCommand.DefineFlow` with a relation body (query-defined flow).
@@ -169,20 +167,18 @@ pub fn pipeline_define_flow(
         target.to_string(),
     );
     let scl = scl(scl_file, scl_line);
-    session
-        .py()
-        .detach(|| {
-            pipelines::define_flow(
-                &sess,
-                &gid,
-                &fname,
-                &tgt,
-                &df,
-                sql_conf.unwrap_or_default(),
-                scl,
-            )
-        })
-        .to_pyerr()
+    interruptible(session.py(), &sess, || {
+        pipelines::define_flow(
+            &sess,
+            &gid,
+            &fname,
+            &tgt,
+            &df,
+            sql_conf.unwrap_or_default(),
+            scl,
+        )
+        .map_err(Box::new)
+    })
 }
 
 /// `PipelineCommand.DefineFlow` carrying an Auto-CDC flow body. 
`stored_as_scd_type` is
@@ -243,20 +239,18 @@ pub fn pipeline_define_auto_cdc_flow(
         target.to_string(),
     );
     let scl = scl(scl_file, scl_line);
-    session
-        .py()
-        .detach(|| {
-            pipelines::define_auto_cdc_flow(
-                &sess,
-                &gid,
-                &fname,
-                &tgt,
-                details,
-                sql_conf.unwrap_or_default(),
-                scl,
-            )
-        })
-        .to_pyerr()
+    interruptible(session.py(), &sess, || {
+        pipelines::define_auto_cdc_flow(
+            &sess,
+            &gid,
+            &fname,
+            &tgt,
+            details,
+            sql_conf.unwrap_or_default(),
+            scl,
+        )
+        .map_err(Box::new)
+    })
 }
 
 /// `PipelineCommand.DefineSqlGraphElements`.
@@ -273,10 +267,9 @@ pub fn pipeline_define_sql_graph_elements(
         sql_text.to_string(),
         sql_file_path.to_string(),
     );
-    session
-        .py()
-        .detach(|| pipelines::define_sql_graph_elements(&sess, &gid, &text, 
&path))
-        .to_pyerr()
+    interruptible(session.py(), &sess, || {
+        pipelines::define_sql_graph_elements(&sess, &gid, &text, 
&path).map_err(Box::new)
+    })
 }
 
 /// A live, lazily-consumed stream of a pipeline run's events. Iterating yields
@@ -299,7 +292,9 @@ impl PyPipelineRunStream {
 
     fn __next__(&mut self, py: Python<'_>) -> PyResult<Option<(String, i64)>> {
         loop {
-            let resp = py.detach(|| self.inner.next_response()).to_pyerr()?;
+            let resp = py
+                .detach(|| self.inner.next_response().map_err(Box::new))
+                .to_pyerr()?;
             let Some(resp) = resp else {
                 return Ok(None); // stream complete -> StopIteration
             };
@@ -335,19 +330,17 @@ pub fn pipeline_start_run(
 ) -> PyResult<PyPipelineRunStream> {
     let sess = session.session.clone();
     let gid = dataflow_graph_id.to_string();
-    let inner = session
-        .py()
-        .detach(|| {
-            pipelines::start_run(
-                &sess,
-                &gid,
-                full_refresh.unwrap_or_default(),
-                full_refresh_all,
-                refresh.unwrap_or_default(),
-                dry,
-                storage,
-            )
-        })
-        .to_pyerr()?;
+    let inner = interruptible(session.py(), &sess, || {
+        pipelines::start_run(
+            &sess,
+            &gid,
+            full_refresh.unwrap_or_default(),
+            full_refresh_all,
+            refresh.unwrap_or_default(),
+            dry,
+            storage,
+        )
+        .map_err(Box::new)
+    })?;
     Ok(PyPipelineRunStream { inner })
 }
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index dfca928a..8ab0032c 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -12,6 +12,7 @@ use crate::catalog::PyCatalog;
 use crate::dataframe::PyDataFrame;
 use crate::datasource::PyDataSourceRegistration;
 use crate::errors::ResultExt;
+use crate::interrupt::interruptible;
 use crate::resource::PyResourceProfile;
 use crate::streaming::{PyDataStreamReader, PyStreamingQueryManager};
 
@@ -1080,6 +1081,7 @@ impl PySparkSession {
                 self.session
                     .conf()
                     
.get("spark.sql.execution.pandas.convertToArrowArraySafely")
+                    .map_err(Box::new)
             })
             .to_pyerr()?
             .as_deref()
@@ -2055,13 +2057,11 @@ impl PySparkSession {
         }
         // The statement runs to completion at once, so other Python threads 
go on meanwhile,
         // to interrupt it for one.
-        let df = py
-            .detach(|| {
-                session
-                    .sql_with_references(&query, pos, named, references)
-                    .map_err(Box::new)
-            })
-            .to_pyerr()?;
+        let df = interruptible(py, &session, || {
+            session
+                .sql_with_references(&query, pos, named, references)
+                .map_err(Box::new)
+        })?;
         Ok(PyDataFrame::new(df))
     }
 
@@ -2373,8 +2373,12 @@ impl PySparkSession {
                 "destination FS path must be an absolute path.",
             ));
         }
-        py.detach(|| self.session.copy_from_local_to_fs(local_path, dest_path))
-            .to_pyerr()
+        py.detach(|| {
+            self.session
+                .copy_from_local_to_fs(local_path, dest_path)
+                .map_err(Box::new)
+        })
+        .to_pyerr()
     }
 
     /// As PySpark Connect's: the attributes of the JVM of a classic session 
raise
@@ -2536,12 +2540,11 @@ impl PySparkSession {
                 ))
             }
         };
-        py.detach(|| {
+        interruptible(py, &self.session, || {
             self.session
                 .register_java_function_with(name, java_class_name, 
return_type, aggregate)
                 .map_err(Box::new)
         })
-        .to_pyerr()
     }
 
     /// Register a Python UDF by name so it resolves in SQL (used by
@@ -2569,8 +2572,9 @@ impl PySparkSession {
             Vec::new(),
             payload,
         );
-        py.detach(|| self.session.register_function(udf_expr))
-            .to_pyerr()
+        interruptible(py, &self.session, || {
+            self.session.register_function(udf_expr).map_err(Box::new)
+        })
     }
 
     /// Register a Python UDTF by name so SQL calls it (used by 
`UDTFRegistration.register`).
@@ -2599,7 +2603,7 @@ impl PySparkSession {
                 Err(_) => crate::types::py_to_data_type(value),
             })
             .transpose()?;
-        py.detach(|| {
+        interruptible(py, &self.session, || {
             self.session.register_table_function(
                 name,
                 return_type.as_ref(),
@@ -2609,7 +2613,6 @@ impl PySparkSession {
                 deterministic,
             )
         })
-        .to_pyerr()
     }
 
     #[pyo3(name = "sessionId")]
@@ -2679,13 +2682,11 @@ impl PySparkSession {
         use prost::Message;
         let command = spark_connect_proto::Command::decode(command)
             .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?;
-        let responses = py
-            .detach(|| {
-                self.session
-                    .execute_command_proto(command)
-                    .map_err(Box::new)
-            })
-            .to_pyerr()?;
+        let responses = interruptible(py, &self.session, || {
+            self.session
+                .execute_command_proto(command)
+                .map_err(Box::new)
+        })?;
         Ok(responses
             .iter()
             .map(|response| pyo3::types::PyBytes::new(py, 
&response.encode_to_vec()))
@@ -2998,13 +2999,18 @@ impl PySparkSession {
     /// Returns the server-assigned profile ID that can be used with 
`DataFrame.withResources()`.
     #[pyo3(name = "buildResourceProfile")]
     fn build_resource_profile(&self, py: Python<'_>, profile: 
&PyResourceProfile) -> PyResult<i32> {
-        py.detach(|| self.session.build_resource_profile(&profile.inner))
-            .to_pyerr()
+        py.detach(|| {
+            self.session
+                .build_resource_profile(&profile.inner)
+                .map_err(Box::new)
+        })
+        .to_pyerr()
     }
 
     #[getter]
     fn version(&self, py: Python<'_>) -> PyResult<String> {
-        py.detach(|| self.session.version()).to_pyerr()
+        py.detach(|| self.session.version().map_err(Box::new))
+            .to_pyerr()
     }
 
     /// The DataFrame of a table, as PySpark Connect's: `NOT_EXPECTED_TYPE` 
for a name that is not
@@ -3044,12 +3050,14 @@ impl PySparkSession {
 
     #[pyo3(name = "interruptAll")]
     fn interrupt_all(&self, py: Python<'_>) -> PyResult<Vec<String>> {
-        py.detach(|| self.session.interrupt_all()).to_pyerr()
+        py.detach(|| self.session.interrupt_all().map_err(Box::new))
+            .to_pyerr()
     }
 
     #[pyo3(name = "interruptTag")]
     fn interrupt_tag(&self, py: Python<'_>, tag: &str) -> 
PyResult<Vec<String>> {
-        py.detach(|| self.session.interrupt_tag(tag)).to_pyerr()
+        py.detach(|| self.session.interrupt_tag(tag).map_err(Box::new))
+            .to_pyerr()
     }
 
     #[pyo3(name = "interruptOperation")]
diff --git a/crates/pyspark-rs/src/stat_arguments.rs 
b/crates/pyspark-rs/src/stat_arguments.rs
index 8c6bdead..0f0a2034 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -9,6 +9,7 @@ use spark_connect::group::StatFunctions;
 use crate::column::raise_pyspark;
 use crate::dataframe::PyDataFrame;
 use crate::errors::ResultExt;
+use crate::interrupt::interruptible;
 
 /// PySpark's `NOT_EXPECTED_TYPE` error of the argument `name`, `value`, which 
should be of
 /// the type `expected`.
@@ -222,8 +223,9 @@ pub(crate) fn cov(
         string_argument(col1, "col1")?,
         string_argument(col2, "col2")?,
     );
-    py.detach(|| stat.cov(&col1, &col2).map_err(Box::new))
-        .to_pyerr()
+    interruptible(py, &stat.spark_session(), || {
+        stat.cov(&col1, &col2).map_err(Box::new)
+    })
 }
 
 /// `df.corr(col1, col2, method)`, of two column names and the method 
"pearson", the default,
@@ -249,8 +251,9 @@ pub(crate) fn corr(
             ));
         }
     }
-    py.detach(|| stat.corr(&col1, &col2).map_err(Box::new))
-        .to_pyerr()
+    interruptible(py, &stat.spark_session(), || {
+        stat.corr(&col1, &col2).map_err(Box::new)
+    })
 }
 
 /// `df.crosstab(col1, col2)`, of two column names, as PySpark's.
@@ -363,7 +366,7 @@ pub(crate) fn approx_quantile(
     }
     let refs: Vec<&str> = columns.iter().map(String::as_str).collect();
     let df = stat.approx_quantile(refs, quantiles, error);
-    let rows = py.detach(|| df.collect().map_err(Box::new)).to_pyerr()?;
+    let rows = interruptible(py, &df.spark_session(), || 
df.collect().map_err(Box::new))?;
     // One row, of the array of the quantiles of each column.
     let per_column: Vec<Vec<f64>> = match rows.first().and_then(|row| 
row.get(0)) {
         Some(Value::List(columns)) => columns
diff --git a/crates/pyspark-rs/src/streaming.rs 
b/crates/pyspark-rs/src/streaming.rs
index 50cda3d8..2cc39103 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -12,7 +12,8 @@ use std::collections::HashMap;
 use std::sync::Arc;
 
 use crate::dataframe::{PyDataFrame, WriterState};
-use crate::errors::ResultExt;
+use crate::errors::spark_error_to_py_exception;
+use crate::interrupt::{interruptible, interruptible_outcome};
 
 /// Adapts Python listeners to the native bus: deserialize one typed event for 
the whole
 /// snapshot, then dispatch it through Python's callback-exception isolation 
helper. Decode
@@ -984,7 +985,7 @@ impl PyDataStreamWriter {
     ) -> PyResult<PyStreamingQuery> {
         let writer = self.apply_write_opts(format, outputMode, partitionBy, 
queryName, options)?;
         // Memory/console/foreach sinks take no path; the core treats "" as 
unset.
-        let query = crate::dataframe::detached(py, || {
+        let query = interruptible(py, &writer.spark_session(), || {
             writer
                 .start_with_event_handler(path.unwrap_or(""), 
post_started_event)
                 .map_err(Box::new)
@@ -1005,7 +1006,7 @@ impl PyDataStreamWriter {
         options: Option<&Bound<'_, PyDict>>,
     ) -> PyResult<PyStreamingQuery> {
         let writer = self.apply_write_opts(format, outputMode, partitionBy, 
queryName, options)?;
-        let query = crate::dataframe::detached(py, || {
+        let query = interruptible(py, &writer.spark_session(), || {
             writer
                 .to_table_with_event_handler(tableName, post_started_event)
                 .map_err(Box::new)
@@ -1199,7 +1200,9 @@ impl PyStreamingQuery {
     /// `isTriggerActive`.
     #[getter]
     fn status<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
-        let status = crate::dataframe::detached(py, || 
self.inner.status().map_err(Box::new))?;
+        let status = interruptible(py, &self.inner.spark_session(), || {
+            self.inner.status().map_err(Box::new)
+        })?;
         let dict = PyDict::new(py);
         dict.set_item("message", status.status_message)?;
         dict.set_item("isDataAvailable", status.is_data_available)?;
@@ -1208,7 +1211,9 @@ impl PyStreamingQuery {
     }
 
     fn stop(&self, py: Python<'_>) -> PyResult<()> {
-        crate::dataframe::detached(py, || self.inner.stop().map_err(Box::new))
+        interruptible(py, &self.inner.spark_session(), || {
+            self.inner.stop().map_err(Box::new)
+        })
     }
 
     #[pyo3(signature = (timeout=None))]
@@ -1218,7 +1223,7 @@ impl PyStreamingQuery {
         timeout: Option<&Bound<'_, PyAny>>,
     ) -> PyResult<Option<bool>> {
         let timeout = positive_timeout(timeout)?;
-        crate::dataframe::detached(py, || {
+        interruptible(py, &self.inner.spark_session(), || {
             self.inner.await_termination(timeout).map_err(Box::new)
         })
     }
@@ -1226,8 +1231,9 @@ impl PyStreamingQuery {
     /// The last progress of the query, as PySpark's `StreamingQueryProgress`, 
or None.
     #[getter]
     fn lastProgress<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, 
PyAny>>> {
-        let progress =
-            crate::dataframe::detached(py, || 
self.inner.last_progress().map_err(Box::new))?;
+        let progress = interruptible(py, &self.inner.spark_session(), || {
+            self.inner.last_progress().map_err(Box::new)
+        })?;
         match progress {
             Some(json) => progress_from_json(py, &json).map(Some),
             None => Ok(None),
@@ -1237,23 +1243,27 @@ impl PyStreamingQuery {
     /// The recent progress of the query, each as PySpark's 
`StreamingQueryProgress`.
     #[getter]
     fn recentProgress<'py>(&self, py: Python<'py>) -> PyResult<Vec<Bound<'py, 
PyAny>>> {
-        crate::dataframe::detached(py, || 
self.inner.recent_progress().map_err(Box::new))?
-            .iter()
-            .map(|json| progress_from_json(py, json))
-            .collect()
+        interruptible(py, &self.inner.spark_session(), || {
+            self.inner.recent_progress().map_err(Box::new)
+        })?
+        .iter()
+        .map(|json| progress_from_json(py, json))
+        .collect()
     }
 
     fn processAllAvailable(&self, py: Python<'_>) -> PyResult<()> {
-        crate::dataframe::detached(py, || 
self.inner.process_all_available().map_err(Box::new))
+        interruptible(py, &self.inner.spark_session(), || {
+            self.inner.process_all_available().map_err(Box::new)
+        })
     }
 
     /// Print the plan of the query with Python's `print`, as PySpark's
     /// `StreamingQuery.explain(extended=False)`.
     #[pyo3(signature = (extended=ProtoBool(false)))]
     fn explain(&self, py: Python<'_>, extended: ProtoBool) -> PyResult<()> {
-        let plan = py
-            .detach(|| self.inner.explain(extended.0).map_err(Box::new))
-            .to_pyerr()?;
+        let plan = interruptible(py, &self.inner.spark_session(), || {
+            self.inner.explain(extended.0).map_err(Box::new)
+        })?;
         py.import("builtins")?.call_method1("print", (plan,))?;
         Ok(())
     }
@@ -1262,8 +1272,9 @@ impl PyStreamingQuery {
     /// `pyspark.errors.exceptions.connect`, of the message of the server 
without the type of
     /// its Java exception, and with its JVM stack trace, and of the error 
class as its reason.
     fn exception(&self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
-        let exception =
-            crate::dataframe::detached(py, || 
self.inner.exception().map_err(Box::new))?;
+        let exception = interruptible(py, &self.inner.spark_session(), || {
+            self.inner.exception().map_err(Box::new)
+        })?;
         let Some(exception) = exception else {
             return Ok(None);
         };
@@ -1347,12 +1358,16 @@ impl PyStreamingQueryListenerBus {
 impl PyStreamingQueryManager {
     #[getter]
     fn active(&self, py: Python<'_>) -> PyResult<Vec<PyStreamingQuery>> {
-        let queries = crate::dataframe::detached(py, || 
self.inner.active().map_err(Box::new))?;
+        let queries = interruptible(py, &self.inner.spark_session(), || {
+            self.inner.active().map_err(Box::new)
+        })?;
         Ok(queries.into_iter().map(PyStreamingQuery::new).collect())
     }
 
     fn get(&self, py: Python<'_>, id: &str) -> 
PyResult<Option<PyStreamingQuery>> {
-        let query = crate::dataframe::detached(py, || 
self.inner.get(id).map_err(Box::new))?;
+        let query = interruptible(py, &self.inner.spark_session(), || {
+            self.inner.get(id).map_err(Box::new)
+        })?;
         Ok(query.map(PyStreamingQuery::new))
     }
 
@@ -1363,13 +1378,15 @@ impl PyStreamingQueryManager {
         timeout: Option<&Bound<'_, PyAny>>,
     ) -> PyResult<Option<bool>> {
         let timeout = positive_timeout(timeout)?;
-        crate::dataframe::detached(py, || {
+        interruptible(py, &self.inner.spark_session(), || {
             self.inner.await_any_termination(timeout).map_err(Box::new)
         })
     }
 
     fn resetTerminated(&self, py: Python<'_>) -> PyResult<()> {
-        crate::dataframe::detached(py, || 
self.inner.reset_terminated().map_err(Box::new))
+        interruptible(py, &self.inner.spark_session(), || {
+            self.inner.reset_terminated().map_err(Box::new)
+        })
     }
 
     /// Register a client-side listener object (with 
onQueryStarted/Progress/Idle/
@@ -1388,8 +1405,9 @@ impl PyStreamingQueryManager {
         let adapter = Arc::new(PyListenerAdapter {
             listener: listener.clone_ref(py),
         });
-        match crate::dataframe::detached(py, || 
self.inner.add_listener(adapter).map_err(Box::new))
-        {
+        match interruptible_outcome(py, &self.inner.spark_session(), || {
+            self.inner.add_listener(adapter).map_err(Box::new)
+        })? {
             Ok(id) => {
                 let bound = listener.bind(py);
                 match bound.getattr("_rust_listener_ids") {
@@ -1402,7 +1420,7 @@ impl PyStreamingQueryManager {
                 format!(
                     "Failed to add the listener because of exception: {}\n\
                      The listener is not added, please add it again.",
-                    error.value(py)
+                    spark_error_to_py_exception(*error).value(py)
                 ),
             ),
         }
@@ -1423,9 +1441,9 @@ impl PyStreamingQueryManager {
         };
         let registered: Vec<String> = ids.extract()?;
         for id in registered {
-            match crate::dataframe::detached(py, || {
+            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,))?;
@@ -1440,7 +1458,7 @@ impl PyStreamingQueryManager {
                         format!(
                             "Failed to remove the listener because of 
exception: {}\n\
                              The listener is not removed, please remove it 
again.",
-                            error.value(py)
+                            spark_error_to_py_exception(*error).value(py)
                         ),
                     );
                 }
@@ -1461,14 +1479,15 @@ impl PyStreamingQueryManager {
     /// `StreamingQueryManager.close`. A server removal failure warns and 
keeps the
     /// listeners registered, as PySpark Connect's does, so close can be 
retried.
     fn close(&self, py: Python<'_>) -> PyResult<()> {
-        if let Err(error) = crate::dataframe::detached(py, || 
self.inner.close().map_err(Box::new))
-        {
+        if let Err(error) = interruptible_outcome(py, 
&self.inner.spark_session(), || {
+            self.inner.close().map_err(Box::new)
+        })? {
             return warn(
                 py,
                 format!(
                     "Failed to remove the listener because of exception: {}\n\
                      The listener is not removed, please remove it again.",
-                    error.value(py)
+                    spark_error_to_py_exception(*error).value(py)
                 ),
             );
         }
@@ -1476,7 +1495,7 @@ impl PyStreamingQueryManager {
     }
 
     fn streamListenerEvents(&self, py: Python<'_>) -> 
PyResult<PyListenerEventStream> {
-        let stream = crate::dataframe::detached(py, || {
+        let stream = interruptible(py, &self.inner.spark_session(), || {
             self.inner.listener_event_stream().map_err(Box::new)
         })?;
         Ok(PyListenerEventStream::new(stream))
diff --git a/crates/pyspark-rs/src/transport.rs 
b/crates/pyspark-rs/src/transport.rs
index 7ba9eb51..8af5bb83 100644
--- a/crates/pyspark-rs/src/transport.rs
+++ b/crates/pyspark-rs/src/transport.rs
@@ -22,7 +22,7 @@ use tokio::sync::Notify;
 use spark_connect_core::channel::ChannelBuilder;
 use spark_connect_core::client::SparkConnectClient;
 use spark_connect_core::retries::RetryPolicy;
-use spark_connect_core::runtime::block_on;
+use spark_connect_core::runtime::{block_on, POLL_INTERVAL};
 use spark_connect_proto as proto;
 
 use crate::errors::ResultExt;
@@ -74,6 +74,34 @@ pub struct ResponseStream {
 // gRPC CANCELLED status code, surfaced when the client closes an in-flight 
stream.
 const GRPC_CANCELLED: i32 = 1;
 
+/// Wait for `future` on the runtime, without the GIL, until a signal handler 
of the process
+/// raises: then `future` is dropped, and the exception of the handler is 
returned. The calling
+/// thread checks the signals every [`POLL_INTERVAL`], as a handler runs only 
on the main thread,
+/// with the GIL.
+fn until_signal<T: Send>(
+    py: Python<'_>,
+    future: impl std::future::Future<Output = T> + Send,
+) -> Result<T, PyErr> {
+    py.detach(|| {
+        block_on(async {
+            let signal = async {
+                let mut ticks = tokio::time::interval(POLL_INTERVAL);
+                loop {
+                    ticks.tick().await;
+                    if let Err(error) = Python::attach(|py| 
py.check_signals()) {
+                        return error;
+                    }
+                }
+            };
+            tokio::select! {
+                biased;
+                output = future => Ok(output),
+                error = signal => Err(error),
+            }
+        })
+    })
+}
+
 fn cancelled_err(py: Python<'_>) -> PyErr {
     RustRpcError::new_err((
         GRPC_CANCELLED,
@@ -103,29 +131,33 @@ impl ResponseStream {
         // Release the GIL while blocking on the next message: a long-lived 
stream must not
         // hold the GIL while it waits, or it deadlocks other Python threads 
(including the
         // main one). Race the read against cancellation so close() can 
unblock it.
-        let outcome = py.detach(|| {
-            block_on(async {
-                tokio::select! {
-                    biased;
-                    _ = cancel.notified() => None,
-                    m = stream.message() => Some(m),
-                }
-            })
+        // A signal handler that raises ends the read as the reference 
iterator's
+        // KeyboardInterrupt does: the reference client then interrupts the 
operation.
+        let outcome = until_signal(py, async {
+            tokio::select! {
+                biased;
+                _ = cancel.notified() => None,
+                m = stream.message() => Some(m),
+            }
         });
         match outcome {
+            Err(signal) => {
+                self.stream = None;
+                Err(signal)
+            }
             // Cancelled by client close: drop the stream and surface 
CANCELLED so the
             // reference reattachable iterator errors out instead of 
re-attaching forever.
-            None => {
+            Ok(None) => {
                 self.stream = None;
                 Err(cancelled_err(py))
             }
-            Some(Ok(Some(bytes))) => Ok(Some(PyBytes::new(py, 
&bytes).unbind())),
-            Some(Ok(None)) => {
+            Ok(Some(Ok(Some(bytes)))) => Ok(Some(PyBytes::new(py, 
&bytes).unbind())),
+            Ok(Some(Ok(None))) => {
                 // Stream ended; drop it to release resources promptly.
                 self.stream = None;
                 Ok(None) // StopIteration
             }
-            Some(Err(status)) => {
+            Ok(Some(Err(status))) => {
                 // On error, also drop the stream.
                 self.stream = None;
                 Err(RustRpcError::new_err((
@@ -198,8 +230,7 @@ impl RustConnectStub {
         if self.closed.load(Ordering::SeqCst) {
             return Err(cancelled_err(py));
         }
-        let stream = py
-            .detach(|| 
block_on(self.client.execute_plan_raw(request.to_vec())))
+        let stream = until_signal(py, 
self.client.execute_plan_raw(request.to_vec()))?
             .map_err(|e| spark_err_to_py(py, e))?;
         Ok(ResponseStream {
             stream: Some(stream),
@@ -213,8 +244,7 @@ impl RustConnectStub {
         if self.closed.load(Ordering::SeqCst) {
             return Err(cancelled_err(py));
         }
-        let stream = py
-            .detach(|| 
block_on(self.client.reattach_execute_raw(request.to_vec())))
+        let stream = until_signal(py, 
self.client.reattach_execute_raw(request.to_vec()))?
             .map_err(|e| spark_err_to_py(py, e))?;
         Ok(ResponseStream {
             stream: Some(stream),
diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index a83af0a7..7dc74d31 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -388,10 +388,50 @@ pub struct SparkConnectClient {
     /// check of the IDs of its responses, and its close when the server 
reports that the session
     /// changed. See [`SparkConnectClient::set_session_tracking`].
     session_tracking: bool,
+    /// The executions in flight, shared by the clones of the client, each 
with the calling
+    /// thread that started it, in the order they started. See
+    /// [`SparkConnectClient::running_operation_id`].
+    inflight_operations: std::sync::Arc<std::sync::Mutex<Vec<InflightEntry>>>,
     /// The plan compression of the client, shared by its clones, looked up on 
its first plan.
     plan_compression: std::sync::Arc<std::sync::Mutex<PlanCompression>>,
 }
 
+/// An execution in flight: the thread that started it, and its operation ID.
+#[derive(Debug, Clone, PartialEq)]
+struct InflightEntry {
+    thread: std::thread::ThreadId,
+    operation_id: String,
+}
+
+/// Keeps an execution in the registry of the in-flight executions of its 
client until it drops.
+struct InflightGuard {
+    registry: std::sync::Arc<std::sync::Mutex<Vec<InflightEntry>>>,
+    entry: InflightEntry,
+}
+
+impl InflightGuard {
+    /// Register `entry` in `registry` until the guard drops.
+    fn register(
+        registry: std::sync::Arc<std::sync::Mutex<Vec<InflightEntry>>>,
+        entry: InflightEntry,
+    ) -> Self {
+        registry
+            .lock()
+            .unwrap_or_else(|e| e.into_inner())
+            .push(entry.clone());
+        InflightGuard { registry, entry }
+    }
+}
+
+impl Drop for InflightGuard {
+    fn drop(&mut self) {
+        let mut inflight = self.registry.lock().unwrap_or_else(|e| 
e.into_inner());
+        if let Some(position) = inflight.iter().rposition(|entry| *entry == 
self.entry) {
+            inflight.remove(position);
+        }
+    }
+}
+
 /// The user context extensions of a client, as PySpark's `SparkConnectClient` 
keeps them: those
 /// of all the threads, and those of each thread, which the requests of a 
thread carry, of their
 /// IDs.
@@ -511,6 +551,7 @@ impl SparkConnectClient {
             closed: Default::default(),
             server_session_id: Default::default(),
             session_tracking: true,
+            inflight_operations: Default::default(),
             plan_compression: Default::default(),
         })
     }
@@ -541,6 +582,7 @@ impl SparkConnectClient {
             closed: Default::default(),
             server_session_id: Default::default(),
             session_tracking: self.session_tracking,
+            inflight_operations: Default::default(),
             plan_compression: Default::default(),
         }
     }
@@ -557,6 +599,22 @@ impl SparkConnectClient {
         self.closed.load(std::sync::atomic::Ordering::SeqCst)
     }
 
+    /// The operation ID of the innermost execution in flight that the calling 
thread started, if
+    /// any: the one that a wait of the calling thread is for, as PySpark 
interrupts the operation
+    /// of the iterator that is interrupted.
+    pub fn running_operation_id(&self) -> Option<String> {
+        let thread = crate::runtime::calling_thread_id();
+        let inflight = self
+            .inflight_operations
+            .lock()
+            .unwrap_or_else(|e| e.into_inner());
+        inflight
+            .iter()
+            .rev()
+            .find(|entry| entry.thread == thread)
+            .map(|entry| entry.operation_id.clone())
+    }
+
     /// The error of an RPC of a closed client, as PySpark's 
`SparkConnectClient._stub` raises it.
     #[allow(clippy::result_large_err)] // SparkError is large; changing the 
type would break the API
     fn ensure_open(&self) -> Result<()> {
@@ -1128,6 +1186,14 @@ impl SparkConnectClient {
         }
         let request = self.hooked(request)?;
         let iter = ExecutePlanResponseReattachableIterator::new(request);
+        // Before the first RPC, so that an execution that waits for the 
server is in flight.
+        let inflight = InflightGuard::register(
+            std::sync::Arc::clone(&self.inflight_operations),
+            InflightEntry {
+                thread: crate::runtime::calling_thread_id(),
+                operation_id: iter.operation_id().to_string(),
+            },
+        );
         let start = iter.request().clone();
         let deadline = self.rpc_deadlines.reattachable_execute_plan;
         let mut stream_deadline = None;
@@ -1167,6 +1233,7 @@ impl SparkConnectClient {
             execute_again: false,
             done: false,
             released: false,
+            _inflight: inflight,
         })
     }
 
@@ -1973,6 +2040,8 @@ pub struct ReattachableResponseStream {
     done: bool,
     /// Whether `ReleaseAll` was sent, after which nothing else is released.
     released: bool,
+    /// The registration of the execution as in flight, which ends with the 
stream.
+    _inflight: InflightGuard,
 }
 
 /// The user ID of a connection string that does not set one: `SPARK_USER`, 
else `USER`, as
@@ -2517,6 +2586,46 @@ mod tests {
         );
     }
 
+    #[test]
+    fn 
test_running_operation_id_is_the_innermost_execution_of_the_calling_thread() {
+        let client = connect_blocking("sc://example.com");
+        assert_eq!(client.running_operation_id(), None);
+        let entry = |thread, operation_id: &str| InflightEntry {
+            thread,
+            operation_id: operation_id.to_string(),
+        };
+        let caller = crate::runtime::calling_thread_id();
+        let outer = InflightGuard::register(
+            std::sync::Arc::clone(&client.inflight_operations),
+            entry(caller, "outer"),
+        );
+        let inner = InflightGuard::register(
+            std::sync::Arc::clone(&client.inflight_operations),
+            entry(caller, "inner"),
+        );
+        assert_eq!(client.running_operation_id().as_deref(), Some("inner"));
+        drop(inner);
+        assert_eq!(client.running_operation_id().as_deref(), Some("outer"));
+        // The executions of another thread are not those of the calling 
thread.
+        let other = std::thread::spawn({
+            let client = client.clone();
+            let registry = std::sync::Arc::clone(&client.inflight_operations);
+            move || {
+                let _guard = InflightGuard::register(
+                    registry,
+                    entry(crate::runtime::calling_thread_id(), "other"),
+                );
+                client.running_operation_id()
+            }
+        })
+        .join()
+        .unwrap();
+        assert_eq!(other.as_deref(), Some("other"));
+        assert_eq!(client.running_operation_id().as_deref(), Some("outer"));
+        drop(outer);
+        assert_eq!(client.running_operation_id(), None);
+    }
+
     /// Connects a client on a runtime of its own, for the tests that set the 
environment.
     /// The channel is lazy, so no server is dialed.
     fn connect_blocking(url: &str) -> SparkConnectClient {
diff --git a/crates/spark-connect-core/src/runtime.rs 
b/crates/spark-connect-core/src/runtime.rs
index aa6632b6..d1ec1fae 100644
--- a/crates/spark-connect-core/src/runtime.rs
+++ b/crates/spark-connect-core/src/runtime.rs
@@ -4,7 +4,10 @@
 //! and a `block_on` helper so that synchronous Python code can call async
 //! Rust functions at the PyO3 boundary.
 
-use std::sync::{Once, OnceLock};
+use std::cell::RefCell;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::{Arc, Once, OnceLock};
 use tokio::runtime::Runtime;
 
 static RUNTIME_INIT: Once = Once::new();
@@ -43,12 +46,85 @@ where
     F: std::future::Future + Send,
     F::Output: Send,
 {
+    let watch = WAIT_WATCH.with(|watch| watch.borrow().clone());
     match tokio::runtime::Handle::try_current() {
         Ok(handle) if handle.runtime_flavor() == 
tokio::runtime::RuntimeFlavor::MultiThread => {
-            tokio::task::block_in_place(|| get_runtime().block_on(f))
+            tokio::task::block_in_place(|| drive(f, watch))
         }
         Ok(_) => block_on_other_thread(f),
-        _ => get_runtime().block_on(f),
+        _ => drive(f, watch),
+    }
+}
+
+/// What a wait for the server does at a poll of the signals of the process 
(see
+/// [`with_wait_watch`]).
+pub enum Watch {
+    /// Keep waiting for the server.
+    Continue,
+    /// Interrupt the execution that the wait is for, by this future, which 
the wait drives to its
+    /// end. The wait then ends with the server's cancellation of the 
execution.
+    Interrupt(Pin<Box<dyn Future<Output = ()> + Send>>),
+}
+
+/// The poll of the signals of the process of a wait, which the wait calls 
every
+/// [`POLL_INTERVAL`] on the thread that waits.
+pub type WaitWatch = dyn Fn() -> Watch + Send + Sync;
+
+thread_local! {
+    static WAIT_WATCH: RefCell<Option<Arc<WaitWatch>>> = const { 
RefCell::new(None) };
+}
+
+/// Run `f` on this thread, with `watch` called by the waits for the server 
that `f` makes on this
+/// thread, as [`block_on`] makes them: the waits poll `watch` every 
[`POLL_INTERVAL`] while the
+/// future of each waits. A wait on another thread (see [`block_on`]) does not 
poll it. The watch of
+/// `f` ends with it, and the watch of an enclosing call is restored.
+pub fn with_wait_watch<R>(watch: Arc<WaitWatch>, f: impl FnOnce() -> R) -> R {
+    struct Restore(Option<Arc<WaitWatch>>);
+
+    impl Drop for Restore {
+        fn drop(&mut self) {
+            let previous = self.0.take();
+            WAIT_WATCH.with(|current| *current.borrow_mut() = previous);
+        }
+    }
+
+    let previous = WAIT_WATCH.with(|current| current.replace(Some(watch)));
+    let _restore = Restore(previous);
+    f()
+}
+
+/// How often a wait for the server polls its [`WaitWatch`].
+pub const POLL_INTERVAL: std::time::Duration = 
std::time::Duration::from_millis(200);
+
+/// Drive `f` on the shared runtime, polling `watch` (if any) as the wait goes 
on.
+fn drive<F: Future>(f: F, watch: Option<Arc<WaitWatch>>) -> F::Output {
+    match watch {
+        Some(watch) => get_runtime().block_on(watched(f, watch)),
+        None => get_runtime().block_on(f),
+    }
+}
+
+/// `f`, polled as it is, and `watch` called every [`POLL_INTERVAL`] until it 
returns an interrupt,
+/// which is spawned once. `f` is driven to its end, and the interrupt is 
awaited with it, so that
+/// the cleanup of `f` runs as the server ends the execution.
+async fn watched<F: Future>(f: F, watch: Arc<WaitWatch>) -> F::Output {
+    tokio::pin!(f);
+    let mut ticks = tokio::time::interval(POLL_INTERVAL);
+    let mut interrupt: Option<tokio::task::JoinHandle<()>> = None;
+    loop {
+        tokio::select! {
+            output = &mut f => {
+                if let Some(interrupt) = interrupt {
+                    let _ = interrupt.await;
+                }
+                return output;
+            }
+            _ = ticks.tick(), if interrupt.is_none() => {
+                if let Watch::Interrupt(sent) = watch() {
+                    interrupt = Some(tokio::spawn(sent));
+                }
+            }
+        }
     }
 }
 
@@ -207,6 +283,61 @@ mod tests {
         assert_eq!(result, 30);
     }
 
+    #[test]
+    fn test_watch_is_called_while_the_future_waits() {
+        use std::sync::atomic::{AtomicUsize, Ordering};
+        let calls = Arc::new(AtomicUsize::new(0));
+        let counter = Arc::clone(&calls);
+        let watch: Arc<WaitWatch> = Arc::new(move || {
+            counter.fetch_add(1, Ordering::SeqCst);
+            Watch::Continue
+        });
+        let output = with_wait_watch(watch, || {
+            block_on(async {
+                tokio::time::sleep(POLL_INTERVAL * 5).await;
+                7
+            })
+        });
+        assert_eq!(output, 7);
+        assert!(calls.load(Ordering::SeqCst) >= 2);
+    }
+
+    #[test]
+    fn test_interrupt_of_a_watch_is_driven_to_the_end_of_the_wait() {
+        use std::sync::atomic::{AtomicBool, Ordering};
+        let fired = AtomicBool::new(false);
+        let interrupted = Arc::new(AtomicBool::new(false));
+        let flag = Arc::clone(&interrupted);
+        let watch: Arc<WaitWatch> = Arc::new(move || {
+            if fired.swap(true, Ordering::SeqCst) {
+                Watch::Continue
+            } else {
+                let flag = Arc::clone(&flag);
+                Watch::Interrupt(Box::pin(async move { flag.store(true, 
Ordering::SeqCst) }))
+            }
+        });
+        let output = with_wait_watch(watch, || {
+            block_on(async {
+                tokio::time::sleep(POLL_INTERVAL * 5).await;
+                9
+            })
+        });
+        assert_eq!(output, 9);
+        assert!(interrupted.load(Ordering::SeqCst));
+    }
+
+    #[test]
+    fn test_with_wait_watch_restores_the_enclosing_watch() {
+        let outer: Arc<WaitWatch> = Arc::new(|| Watch::Continue);
+        let is_outer =
+            |w: &Option<Arc<WaitWatch>>| w.as_ref().is_some_and(|w| 
Arc::ptr_eq(w, &outer));
+        with_wait_watch(Arc::clone(&outer), || {
+            with_wait_watch(Arc::new(|| Watch::Continue), || {});
+            assert!(WAIT_WATCH.with(|w| is_outer(&w.borrow())));
+        });
+        assert!(WAIT_WATCH.with(|w| w.borrow().is_none()));
+    }
+
     fn current_thread_runtime() -> tokio::runtime::Runtime {
         tokio::runtime::Builder::new_current_thread()
             .enable_all()
diff --git a/crates/spark-connect/src/group.rs 
b/crates/spark-connect/src/group.rs
index 4bd45706..0043630f 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -606,6 +606,11 @@ pub struct StatFunctions {
 }
 
 impl StatFunctions {
+    /// The session of these statistics, whose executions they run.
+    pub fn spark_session(&self) -> crate::session::SparkSession {
+        self.dataframe.spark_session()
+    }
+
     /// Create a new StatFunctions.
     pub(crate) fn new(dataframe: DataFrame) -> Self {
         StatFunctions { dataframe }
diff --git a/crates/spark-connect/src/merge.rs 
b/crates/spark-connect/src/merge.rs
index dc9a10b6..0bf5ac54 100644
--- a/crates/spark-connect/src/merge.rs
+++ b/crates/spark-connect/src/merge.rs
@@ -52,6 +52,11 @@ pub struct MergeIntoWriter {
 }
 
 impl MergeIntoWriter {
+    /// The session of this writer, whose executions it runs.
+    pub fn spark_session(&self) -> SparkSession {
+        self.session.clone()
+    }
+
     #[cfg(test)]
     pub(crate) fn plan(&self) -> &LogicalPlan {
         self.source_plan.as_ref()
diff --git a/crates/spark-connect/src/readwriter.rs 
b/crates/spark-connect/src/readwriter.rs
index 1e6a8bdd..515c3e4d 100644
--- a/crates/spark-connect/src/readwriter.rs
+++ b/crates/spark-connect/src/readwriter.rs
@@ -302,6 +302,10 @@ pub struct DataFrameWriter {
 }
 
 impl DataFrameWriter {
+    /// The session of this writer, whose executions it runs.
+    pub fn spark_session(&self) -> SparkSession {
+        self.session.clone()
+    }
     #[cfg(test)]
     pub(crate) fn plan(&self) -> &LogicalPlan {
         self.input_plan.as_ref()
@@ -518,6 +522,10 @@ pub struct DataFrameWriterV2 {
 }
 
 impl DataFrameWriterV2 {
+    /// The session of this writer, whose executions it runs.
+    pub fn spark_session(&self) -> SparkSession {
+        self.session.clone()
+    }
     #[cfg(test)]
     pub(crate) fn plan(&self) -> &LogicalPlan {
         self.input_plan.as_ref()
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index 3f5083f3..aeb95946 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -1079,6 +1079,19 @@ impl SparkSession {
         block_on(self.client.interrupt_operation(operation_id))
     }
 
+    /// Interrupt the operation with the given operation id, as a future, for 
a wait that drives
+    /// it (see [`spark_connect_core::runtime::with_wait_watch`]).
+    pub async fn interrupt_operation_async(&self, operation_id: &str) -> 
Result<Vec<String>> {
+        self.client.interrupt_operation(operation_id).await
+    }
+
+    /// The operation ID of the innermost execution in flight that the calling 
thread started, if
+    /// any. A wait for an execution interrupts it with 
[`Self::interrupt_operation_async`] when a
+    /// signal of the process raises, as PySpark's `KeyboardInterrupt` does.
+    pub fn running_operation_id(&self) -> Option<String> {
+        self.client.running_operation_id()
+    }
+
     /// Add local files, or `file:` URIs, as artifacts of the session, 
mirroring
     /// `pyspark.sql.SparkSession.addArtifacts(*path)`: a `.jar` is added to 
the classpath and
     /// a `.class` to the classes (a Rust extension: PySpark does not upload 
class files); any
diff --git a/crates/spark-connect/src/streaming.rs 
b/crates/spark-connect/src/streaming.rs
index ff7a2c7c..557d28b4 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -299,6 +299,10 @@ pub struct DataStreamWriter {
 }
 
 impl DataStreamWriter {
+    /// The session of this writer, whose executions it runs.
+    pub fn spark_session(&self) -> SparkSession {
+        self.session.clone()
+    }
     #[cfg(test)]
     pub(crate) fn plan(&self) -> &LogicalPlan {
         self.plan.as_ref()
@@ -554,6 +558,10 @@ pub struct StreamingQuery {
 }
 
 impl StreamingQuery {
+    /// The session of this query, whose executions it runs.
+    pub fn spark_session(&self) -> SparkSession {
+        self.session.clone()
+    }
     /// Get the query ID.
     pub fn id(&self) -> &str {
         &self.query_id
@@ -1234,6 +1242,10 @@ pub struct StreamingQueryManager {
 }
 
 impl StreamingQueryManager {
+    /// The session of this manager, whose executions it runs.
+    pub fn spark_session(&self) -> SparkSession {
+        self.session.clone()
+    }
     /// Create a handle to this session's shared StreamingQueryManager state.
     pub(crate) fn new(session: SparkSession) -> Self {
         let bus = session.listener_bus();
diff --git a/crates/spark-connect/tests/e2e_session_catalog.rs 
b/crates/spark-connect/tests/e2e_session_catalog.rs
index a548c32f..2342b590 100644
--- a/crates/spark-connect/tests/e2e_session_catalog.rs
+++ b/crates/spark-connect/tests/e2e_session_catalog.rs
@@ -418,3 +418,61 @@ fn json_to_ddl_converts_on_the_server() {
     assert_eq!(ddl, "a INT,`b b` STRING NOT NULL,c BIGINT COMMENT 'the c'");
     let _ = spark.stop();
 }
+
+/// The execution that the calling thread waits for is the one that its wait 
interrupts, as
+/// PySpark's `KeyboardInterrupt` does: the wait ends with the server's 
cancellation, and the
+/// session goes on.
+#[test]
+fn interrupting_the_wait_cancels_the_execution_of_the_calling_thread() {
+    use std::sync::atomic::{AtomicBool, Ordering};
+    use std::sync::Arc;
+    use std::time::{Duration, Instant};
+
+    use spark_connect_core::runtime::{with_wait_watch, WaitWatch, Watch};
+
+    if !should_run() {
+        return;
+    }
+    let spark = session();
+    let slow = spark
+        .sql("SELECT sum(sqrt(id)) FROM range(0, 1000000000000, 1, 2)")
+        .expect("sql");
+    let started = Instant::now();
+    let interrupted = Arc::new(AtomicBool::new(false));
+    let watch_session = spark.clone();
+    let watch_interrupted = Arc::clone(&interrupted);
+    let watch: Arc<WaitWatch> = Arc::new(move || {
+        if started.elapsed() < Duration::from_secs(2) || 
watch_interrupted.load(Ordering::SeqCst) {
+            return Watch::Continue;
+        }
+        match watch_session.running_operation_id() {
+            Some(operation_id) => {
+                watch_interrupted.store(true, Ordering::SeqCst);
+                let session = watch_session.clone();
+                Watch::Interrupt(Box::pin(async move {
+                    let _ = 
session.interrupt_operation_async(&operation_id).await;
+                }))
+            }
+            None => Watch::Continue,
+        }
+    });
+    let outcome = with_wait_watch(watch, || slow.collect().map_err(Box::new));
+    assert!(
+        outcome.is_err(),
+        "the cancelled execution returned a result"
+    );
+    assert!(
+        interrupted.load(Ordering::SeqCst),
+        "no execution was in flight"
+    );
+    assert_eq!(
+        spark.interrupt_all().expect("interrupt_all"),
+        Vec::<String>::new()
+    );
+    let count = spark
+        .sql("SELECT * FROM range(3)")
+        .map_err(Box::new)
+        .and_then(|df| df.count().map_err(Box::new))
+        .expect("count");
+    assert_eq!(count, 3);
+}
diff --git a/python/tests/_mock_connect_server.py 
b/python/tests/_mock_connect_server.py
index 607fdee7..43d7d381 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -19,6 +19,7 @@
 import json
 import multiprocessing
 import re
+import time
 from concurrent.futures import ThreadPoolExecutor
 from contextlib import contextmanager
 from queue import Empty, Queue
@@ -290,6 +291,9 @@ def serve(connection):
             self.execute_payload = b""
             self.execute_failure = None
             self.execute_error = None
+            # The InterruptRequests of each Interrupt, and the operations that 
they interrupt.
+            self.interrupt_requests = []
+            self.interrupted_operations = set()
             self.error_details = b""
             self.fetched_error_ids = []
             # The warnings of each Set and Unset, as 
ConfigResponse.warnings=3, and the keys
@@ -598,7 +602,12 @@ def serve(connection):
                     if execute_epoch == self.listener_epoch:
                         self.execute_started += 1
                         self.listener_condition.notify_all()
-                if not response_gate.wait(5):
+                # ExecutePlanRequest.operation_id=6.
+                held_operation_id = parse_message(request).get(6, [b""])[0]
+                released = self.wait_for_response(response_gate, 
held_operation_id, 5)
+                if released == "interrupted":
+                    context.abort(grpc.StatusCode.CANCELLED, "Operation has 
been canceled")
+                if not released:
                     with self.listener_condition:
                         if execute_epoch == self.listener_epoch:
                             self.execute_gate_timeouts += 1
@@ -656,6 +665,28 @@ def serve(connection):
             self.release_execute_requests.append(request)
             return b""
 
+        def wait_for_response(self, gate, operation_id, timeout):
+            # Whether the gate is released, or "interrupted" once an Interrupt 
of the operation
+            # arrives, which ends the execution as the server cancels it.
+            deadline = time.monotonic() + timeout
+            while not gate.wait(0.01):
+                if operation_id in self.interrupted_operations:
+                    return "interrupted"
+                if time.monotonic() > deadline:
+                    return False
+            return True
+
+        def interrupt(self, request, context):
+            # InterruptRequest.session_id=1, interrupt_type=4, operation_id=6; 
InterruptResponse
+            # .session_id=1, interrupted_ids=2.
+            fields = parse_message(request)
+            self.interrupt_requests.append(request)
+            if fields.get(4, [0])[0] != 3:
+                context.abort(grpc.StatusCode.UNIMPLEMENTED, "only Interrupt 
of an operation")
+            operation_id = fields[6][0]
+            self.interrupted_operations.add(operation_id)
+            return message_field(1, fields[1][0]) + message_field(2, 
operation_id)
+
         def fetch_error_details(self, request, context):
             # FetchErrorDetailsRequest.error_id=3.
             
self.fetched_error_ids.append(parse_message(request)[3][0].decode())
@@ -765,6 +796,7 @@ def serve(connection):
             "FetchErrorDetails": 
grpc.unary_unary_rpc_method_handler(service.fetch_error_details),
             "Config": grpc.unary_unary_rpc_method_handler(service.config),
             "CloneSession": 
grpc.unary_unary_rpc_method_handler(service.clone_session),
+            "Interrupt": 
grpc.unary_unary_rpc_method_handler(service.interrupt),
         }
         server.add_generic_rpc_handlers(
             
(grpc.method_handlers_generic_handler("spark.connect.SparkConnectService", 
handlers),)
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index e995efe3..67ff05f9 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3680,6 +3680,64 @@ def 
test_udfs_of_types_with_user_defined_types_run_on_the_server_as_pyspark(sess
 
 
 
+def 
test_progress_handlers_run_on_the_thread_of_an_interruptible_collect_as_pyspark():
+    # As PySpark's: the handlers of an execution run in the thread that 
collects it, while the
+    # signals of the process are polled for that collect.
+    import subprocess
+    import sys
+
+    remote = os.environ.get("SPARK_REMOTE")
+    if not remote:
+        pytest.skip("SPARK_REMOTE is required for live-server tests")
+    result = subprocess.run([sys.executable, "-c", """
+import threading
+from pyspark.sql import SparkSession
+spark = SparkSession.builder.remote(%r).getOrCreate()
+spark.conf.set("spark.connect.progress.reportInterval", "10ms")
+main = threading.get_ident()
+threads = []
+spark.registerProgressHandler(lambda **kw: 
threads.append(threading.get_ident()))
+print(spark.range(0, 2000, 1, 4).repartition(20).selectExpr("sum(id) as 
t").collect())
+print("handler threads", len(threads), set(t == main for t in threads))
+""" % remote], env=dict(os.environ, TZ="UTC"), capture_output=True, text=True, 
timeout=300)
+    assert result.returncode == 0, result.stderr
+    lines = result.stdout.splitlines()
+    calls = int(lines[-1].split()[2])
+    assert calls >= 1, result.stdout
+    assert lines[-1] == "handler threads %d {True}" % calls, result.stdout
+
+
+def 
test_sigint_during_action_raises_keyboard_interrupt_and_the_session_works_as_pyspark():
+    # As PySpark's, from the issue: a SIGINT during a long action raises 
KeyboardInterrupt
+    # within a second or two, the operation is cancelled on the server, and 
the session goes on.
+    import subprocess
+    import sys
+
+    remote = os.environ.get("SPARK_REMOTE")
+    if not remote:
+        pytest.skip("SPARK_REMOTE is required for live-server tests")
+    result = subprocess.run([sys.executable, "-c", """
+import os, signal, threading, time
+from pyspark.sql import SparkSession, functions as F
+spark = SparkSession.builder.remote(%r).getOrCreate()
+slow = spark.range(0, 10**12, 1, 2).agg(F.sum(F.sqrt("id")))
+threading.Timer(3.0, lambda: os.kill(os.getpid(), signal.SIGINT)).start()
+started = time.monotonic()
+try:
+    slow.collect()
+    print("collect returned")
+except KeyboardInterrupt:
+    print("interrupted after %%.1f" %% (time.monotonic() - started))
+print("interrupted ids", spark.interruptAll())
+print("count", spark.range(3).count())
+""" % remote], env=dict(os.environ, TZ="UTC"), capture_output=True, text=True, 
timeout=120)
+    assert result.returncode == 0, result.stderr
+    lines = result.stdout.splitlines()
+    assert lines[0].startswith("interrupted after "), result.stdout
+    assert 3.0 <= float(lines[0].rsplit(" ", 1)[1]) < 5.0, result.stdout
+    assert lines[1:] == ["interrupted ids []", "count 3"], result.stdout
+
+
 def test_udfs_return_user_defined_types_of_main_as_pyspark():
     # As PySpark's: a UDT that __main__ defines, of parameters, is a UDF 
return type, as
     # cloudpickle sends its class by value and its state to the worker. In a 
new
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index de31bde1..da487539 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -16155,6 +16155,90 @@ def 
test_sql_runs_a_statement_without_holding_the_gil(mock_connect):
         statement.result(timeout=10)
 
 
+def 
test_sigint_during_collect_raises_keyboard_interrupt_and_interrupts_the_operation(mock_connect):
+    # As PySpark's: the signal raises KeyboardInterrupt while the execution 
waits for the server,
+    # which is then sent an Interrupt of the operation, and the server cancels 
the execution.
+    import signal
+    import threading
+
+    spark, service = mock_connect
+    service.block_execute = True
+    timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+    started = time.monotonic()
+    timer.start()
+    try:
+        with pytest.raises(KeyboardInterrupt):
+            spark.range(3).collect()
+    finally:
+        timer.cancel()
+    assert time.monotonic() - started < 3
+    # ExecutePlanRequest.operation_id=6.
+    operation_id = parse_message(service.execute_requests[-1]).get(6, [b""])[0]
+    # InterruptRequest.interrupt_type=4 (INTERRUPT_TYPE_OPERATION_ID=3), 
operation_id=6.
+    [interrupt] = service.interrupt_requests
+    fields = parse_message(interrupt)
+    assert fields[4] == [3]
+    assert fields[6] == [operation_id]
+
+
[email protected]("hold", ["execute", "next"])
+def 
test_sigint_while_the_transport_waits_raises_keyboard_interrupt(mock_connect, 
hold):
+    # As PySpark's: the transport stub that the reference client drives raises 
KeyboardInterrupt
+    # from the call or the read that waits for the server, which the client 
then interrupts.
+    import signal
+    import threading
+
+    from pyspark import _pyspark
+    from pyspark.sql.connect.proto import base_pb2
+
+    spark, service = mock_connect
+    if hold == "execute":
+        service.block_execute = True
+    else:
+        service.block_result_complete = True
+    stub = _pyspark.RustConnectStub(service.remote)
+    request = base_pb2.ExecutePlanRequest(session_id=spark.session_id, 
operation_id="held")
+    timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+    started = time.monotonic()
+    timer.start()
+    try:
+        with pytest.raises(KeyboardInterrupt):
+            responses = iter(stub.execute_plan(request.SerializeToString()))
+            if hold == "next":
+                next(responses)
+                next(responses)
+    finally:
+        timer.cancel()
+        service.release_response()
+    assert time.monotonic() - started < 3
+
+
+def 
test_exception_of_a_signal_handler_is_raised_by_collect_as_pyspark(mock_connect):
+    # As PySpark's: an exception that the handler of the signal raises is the 
one that the
+    # waiting call raises, and the operation is interrupted.
+    import signal
+    import threading
+
+    class Stop(Exception):
+        pass
+
+    def stop(signum, frame):
+        raise Stop()
+
+    spark, service = mock_connect
+    service.block_execute = True
+    previous = signal.signal(signal.SIGINT, stop)
+    timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+    timer.start()
+    try:
+        with pytest.raises(Stop):
+            spark.range(3).count()
+    finally:
+        timer.cancel()
+        signal.signal(signal.SIGINT, previous)
+    assert len(service.interrupt_requests) == 1
+
+
 def test_connect_registry_sends_auto_cdc_define_flow(mock_connect):
     from pyspark import pipelines as dp
     from pyspark.pipelines.graph_element_registry import 
graph_element_registration_context


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

Reply via email to