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 ed710bf1 [SPARK-61470][CONNECT][PYTHON] Let Ctrl-C end every call of
the Python client that waits for the server, and raise the error of a failed
interrupt, as PySpark does
ed710bf1 is described below
commit ed710bf1d211ec016a0b02be5fe885130783e5f6
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:53:49 2026 +0900
[SPARK-61470][CONNECT][PYTHON] Let Ctrl-C end every call of the Python
client that waits for the server, and raise the error of a failed interrupt, as
PySpark does
### What changes were proposed in this pull request?
A follow-up of SPARK-61407 (#491), which let a Ctrl-C end a call that waits
for an unreachable or retrying server through `interruptible`:
- The calls of the Python client that still waited for the server with a
bare `py.detach` now wait through `interruptible`, or `until_signal` for the
transport stub methods. These are the conf
`get`/`set`/`unset`/`getAll`/`isModifiable`, `schema`, `columns`, `dtypes`,
`printSchema` and the other analyze-based properties and methods,
`persist`/`cache`, `explain`, `cloneSession`,
`interruptAll`/`interruptTag`/`interruptOperation`, the artifact upload, the
`RustConnectStub` methods, and [...]
- When the Interrupt sent for a signal fails, its error is raised in place
of the `KeyboardInterrupt`, with the `KeyboardInterrupt` as its `__context__`,
as PySpark's `interrupt_operation` raises out of the `except KeyboardInterrupt`
of an execution. The failure also ends the wait at once, so a held
`toLocalIterator` no longer ignores the first Ctrl-C. The done error of a
progress handler still takes precedence.
### Why are the changes needed?
Without the wait watch, a signal was not checked while these calls waited,
so a hung or unreachable server held them until the watchdog, 8 to 75 s.
PySpark raises `KeyboardInterrupt` about 1 s after the SIGINT:
```python
spark = SparkSession.builder.remote("sc://127.0.0.1:1").getOrCreate()
spark.conf.get("spark.sql.shuffle.partitions") # SIGINT at 0.5 s
# before: blocked until the watchdog; after (and PySpark 4.3.0):
KeyboardInterrupt at once
```
The same held for `conf.set`, `df.schema`, `addArtifacts`, `cloneSession`
and `interruptAll`, against a hung server (accepts the connection, never
answers) and an unreachable one.
With a server whose Interrupt answers `INTERNAL`, a blocked `collect`
raised `KeyboardInterrupt`, and a held `toLocalIterator` ignored the first
Ctrl-C while its job kept running. PySpark raises the
`SparkConnectGrpcException` (`INTERNAL`) of the interrupt at once.
A known gap is left. For `addArtifacts` and `copyFromLocalToFs`, a signal
ends the retry sleeps of the upload, but an AddArtifacts request that a server
accepts and never answers still waits for its deadline. The core does not abort
that await, and changing that belongs to the core retry and deadline code.
### Does this PR introduce _any_ user-facing change?
Yes. A Ctrl-C ends these calls at once against an unreachable or hung
server, and a failed interrupt raises its error with the `KeyboardInterrupt` as
context, as PySpark does.
### How was this patch tested?
- New offline tests in `python/tests/test_dropin_offline.py`, which fail on
master:
`test_sigint_ends_a_call_that_waits_for_the_server_at_once[unreachable|hung]`
(SIGINT at 0.5 s in a subprocess; `conf.get`, `conf.set`, `schema`,
`cloneSession` and `interruptAll` raise within 3 s, and `addArtifacts` does too
against the unreachable server),
`test_a_failed_interrupt_of_a_blocked_collect_is_raised_with_the_signal_as_context`,
and `test_a_failed_interrupt_of_a_held_local_iterator_is_rais [...]
- The small-stack tests of SPARK-61400 pass. The extra copy of the analyze
future that the wait watch made, which overflowed them, is gone since
SPARK-61469 (#522).
- The offline suite (1844 passed), the e2e suites `test_dropin_e2e.py`,
`test_arrow_e2e.py` and `test_ml_e2e.py` against a Spark 4.3.0 server, the Rust
library tests, the `--no-run` builds (with and without `wasm-udf`), `cargo fmt
--check`, `scripts/audit_no_stubs.sh` and the ruff gates.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #535 from HyukjinKwon/SPARK-61470-ctrlc-sweep.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/catalog.rs | 4 +-
crates/pyspark-rs/src/conf.rs | 55 +++++----
crates/pyspark-rs/src/dataframe.rs | 124 +++++++++----------
crates/pyspark-rs/src/errors.rs | 2 +-
crates/pyspark-rs/src/group.rs | 40 ++++--
crates/pyspark-rs/src/infer.rs | 16 ++-
crates/pyspark-rs/src/interrupt.rs | 35 +++++-
crates/pyspark-rs/src/observation.rs | 6 +-
crates/pyspark-rs/src/pipelines.rs | 16 ++-
crates/pyspark-rs/src/pyarrow_import.rs | 16 ++-
crates/pyspark-rs/src/session.rs | 213 ++++++++++++++------------------
crates/pyspark-rs/src/streaming.rs | 2 +-
crates/pyspark-rs/src/transport.rs | 23 ++--
crates/pyspark-rs/src/types.rs | 4 +-
python/tests/test_dropin_offline.py | 132 ++++++++++++++++++++
15 files changed, 415 insertions(+), 273 deletions(-)
diff --git a/crates/pyspark-rs/src/catalog.rs b/crates/pyspark-rs/src/catalog.rs
index 7d012f21..b1819950 100644
--- a/crates/pyspark-rs/src/catalog.rs
+++ b/crates/pyspark-rs/src/catalog.rs
@@ -9,7 +9,6 @@ use spark_connect::catalog::{
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`.
@@ -408,7 +407,7 @@ impl PyCatalog {
) -> PyResult<PyDataFrame> {
let schema = table_schema(schema)?;
let options = crate::options::str_kwargs_skip_none(options)?;
- py.detach(|| {
+ interruptible(py, self.catalog.spark_session(), || {
self.catalog
.create_table_with(
tableName,
@@ -421,7 +420,6 @@ impl PyCatalog {
.map_err(Box::new)
})
.map(PyDataFrame::new)
- .to_pyerr()
}
/// Create an external table from a data source: deprecated, as PySpark's,
which warns and
diff --git a/crates/pyspark-rs/src/conf.rs b/crates/pyspark-rs/src/conf.rs
index 7591dba1..5dce064f 100644
--- a/crates/pyspark-rs/src/conf.rs
+++ b/crates/pyspark-rs/src/conf.rs
@@ -2,8 +2,9 @@
use pyo3::prelude::*;
use spark_connect::conf::RuntimeConf;
+use spark_connect::session::SparkSession;
-use crate::errors::ResultExt;
+use crate::interrupt::interruptible;
/// Python wrapper for the session runtime configuration.
#[pyclass(
@@ -14,11 +15,17 @@ use crate::errors::ResultExt;
)]
pub struct PyRuntimeConf {
conf: RuntimeConf,
+ /// The session of the configuration, whose executions a signal of the
process interrupts
+ /// while a call of the configuration waits for the server.
+ session: SparkSession,
}
impl PyRuntimeConf {
- pub fn new(conf: RuntimeConf) -> Self {
- PyRuntimeConf { conf }
+ pub fn new(session: SparkSession) -> Self {
+ PyRuntimeConf {
+ conf: session.conf(),
+ session,
+ }
}
}
@@ -94,8 +101,9 @@ pub(crate) fn warn_all(py: Python<'_>, warnings: &[String])
-> PyResult<()> {
}
// Every method round-trips to the server
(`block_on(client.set_config/get_configs)`
-// in the core), so each releases the GIL across the RPC via `py.detach`;
otherwise a
-// Python thread stays blocked for the whole call.
+// in the core), so each waits through `interruptible`, which releases the GIL
across the
+// RPC and lets a signal end the wait; otherwise a Python thread stays blocked
for the
+// whole call.
#[pymethods]
impl PyRuntimeConf {
/// Set a configuration value, as PySpark's: a bool as "true" or "false",
an int as its
@@ -103,13 +111,11 @@ impl PyRuntimeConf {
/// warning of the server.
fn set(&self, py: Python<'_>, key: &str, value: &Bound<'_, PyAny>) ->
PyResult<()> {
let value = conf_value(value)?;
- let warnings = py
- .detach(|| {
- self.conf
- .set_pairs(&[(key, value.as_deref())], None)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let warnings = interruptible(py, &self.session, || {
+ self.conf
+ .set_pairs(&[(key, value.as_deref())], None)
+ .map_err(Box::new)
+ })?;
warn_all(py, &warnings)
}
@@ -133,25 +139,22 @@ impl PyRuntimeConf {
} else {
Some(checked_str(default, "default")?)
};
- py.detach(|| {
+ interruptible(py, &self.session, || {
self.conf
.get_with_default(&key, default.as_deref())
.map_err(Box::new)
})
- .to_pyerr()
}
- ConfDefault::Omitted => py
- .detach(|| self.conf.get(&key).map_err(Box::new))
- .to_pyerr(),
+ ConfDefault::Omitted => {
+ interruptible(py, &self.session, ||
self.conf.get(&key).map_err(Box::new))
+ }
}
}
/// Reset a configuration value to its default. Warns each warning of the
server, as
/// PySpark's.
fn unset(&self, py: Python<'_>, key: &str) -> PyResult<()> {
- let warnings = py
- .detach(|| self.conf.unset(key).map_err(Box::new))
- .to_pyerr()?;
+ let warnings = interruptible(py, &self.session, ||
self.conf.unset(key).map_err(Box::new))?;
warn_all(py, &warnings)
}
@@ -160,11 +163,10 @@ impl PyRuntimeConf {
/// `SparkConnectClient.get_configs`, which `SparkConnectClient` of the
connect import path
/// gives.
fn _get_many(&self, py: Python<'_>, keys: Vec<String>) ->
PyResult<Vec<Option<String>>> {
- py.detach(|| {
+ interruptible(py, &self.session, || {
let keys: Vec<&str> = keys.iter().map(String::as_str).collect();
self.conf.get_many(&keys).map_err(Box::new)
})
- .to_pyerr()
}
/// The values of the configurations of `pairs` of a key and its default,
in one request, as
@@ -174,25 +176,26 @@ impl PyRuntimeConf {
py: Python<'_>,
pairs: Vec<(String, Option<String>)>,
) -> PyResult<Vec<Option<String>>> {
- py.detach(|| {
+ interruptible(py, &self.session, || {
let pairs: Vec<(&str, Option<&str>)> = pairs
.iter()
.map(|(key, default)| (key.as_str(), default.as_deref()))
.collect();
self.conf.get_with_defaults(&pairs).map_err(Box::new)
})
- .to_pyerr()
}
#[pyo3(name = "isModifiable")]
fn is_modifiable(&self, py: Python<'_>, key: &str) -> PyResult<bool> {
- py.detach(|| self.conf.is_modifiable(key)).to_pyerr()
+ interruptible(py, &self.session, || {
+ self.conf.is_modifiable(key).map_err(Box::new)
+ })
}
/// All configuration values as a dict. Mirrors the `RuntimeConf.getAll`
property.
#[getter(getAll)]
fn get_all<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
pyo3::types::PyDict>> {
- let all = py.detach(|| self.conf.get_all()).to_pyerr()?;
+ let all = interruptible(py, &self.session, ||
self.conf.get_all().map_err(Box::new))?;
let dict = pyo3::types::PyDict::new(py);
for (k, v) in all {
dict.set_item(k, v)?;
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 845c0c66..b8dd7b85 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -108,19 +108,13 @@ impl PyDataFrame {
py: Python<'_>,
struct_handling_mode: Option<Bound<'_, PyAny>>,
) -> 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",
- ])
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let settings = interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.spark_session().conf().get_many(&[
+ "spark.sql.session.timeZone",
+ "spark.sql.execution.pandas.structHandlingMode",
+ "spark.sql.execution.arrow.pyspark.selfDestruct.enabled",
+ ])
+ })?;
let (batches, schema) = interruptible(py,
&self.dataframe.spark_session(), || {
self.dataframe
.collect_record_batches_with_schema()
@@ -215,10 +209,8 @@ impl PyDataFrame {
/// The number of rows and the truncation of the eager evaluation, as
PySpark's `int` of
/// 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).map_err(Box::new))
- .to_pyerr()?;
+ let session = self.dataframe.spark_session();
+ let values = interruptible(py, &session, ||
session.conf().get_many(&EAGER_EVAL))?;
if values[0].as_deref() != Some("true") {
return Ok(None);
}
@@ -1469,16 +1461,18 @@ impl PyDataFrame {
return Err(not_expected_type(other, "other", "DataFrame"));
}
let other = self.same_session(other)?.dataframe.clone();
- py.detach(|| self.dataframe.same_semantics(&other))
- .to_pyerr()
+ interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.same_semantics(&other)
+ })
}
/// The server-side hash of this DataFrame's logical plan, asked once, as
PySpark's.
#[pyo3(name = "semanticHash")]
fn semantic_hash(&self, py: Python<'_>) -> PyResult<i32> {
cached(&self.semantic_hash, || {
- py.detach(|| self.dataframe.semantic_hash().map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.semantic_hash().map_err(Box::new)
+ })
})
}
@@ -1555,7 +1549,7 @@ impl PyDataFrame {
fn cache<'py>(slf: PyRef<'py, Self>, py: Python<'py>) ->
PyResult<PyRef<'py, Self>> {
// As PySpark's, which returns the DataFrame itself.
let df = slf.dataframe.clone();
- py.detach(|| df.cache().map_err(Box::new)).to_pyerr()?;
+ interruptible(py, &df.spark_session(), ||
df.cache().map_err(Box::new))?;
Ok(slf)
}
@@ -1568,8 +1562,9 @@ impl PyDataFrame {
) -> PyResult<PyRef<'py, Self>> {
// As PySpark's, which returns the DataFrame itself.
let df = slf.dataframe.clone();
- py.detach(|| df.unpersist(blocking).map_err(Box::new))
- .to_pyerr()?;
+ interruptible(py, &df.spark_session(), || {
+ df.unpersist(blocking).map_err(Box::new)
+ })?;
Ok(slf)
}
@@ -1632,12 +1627,11 @@ impl PyDataFrame {
))
}
};
- py.detach(|| {
+ interruptible(py, &self.dataframe.spark_session(), || {
self.dataframe
.explain_string(&explain_mode)
.map_err(Box::new)
})
- .to_pyerr()
}
/// Register this DataFrame as a temporary view.
@@ -1993,24 +1987,27 @@ impl PyDataFrame {
#[pyo3(name = "inputFiles")]
fn input_files(&self, py: Python<'_>) -> PyResult<Vec<String>> {
cached(&self.input_files, || {
- py.detach(|| self.dataframe.input_files().map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.input_files().map_err(Box::new)
+ })
})
}
/// Whether the server answers that this DataFrame is local (a local
relation).
#[pyo3(name = "isLocal")]
fn is_local(&self, py: Python<'_>) -> PyResult<bool> {
- py.detach(|| self.dataframe.is_local_on_server().map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.is_local_on_server().map_err(Box::new)
+ })
}
/// Whether this (cached) DataFrame is cached.
#[pyo3(name = "is_cached")]
#[getter]
fn is_cached(&self, py: Python<'_>) -> PyResult<bool> {
- py.detach(|| self.dataframe.is_cached().map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.is_cached().map_err(Box::new)
+ })
}
/// Whether this DataFrame contains one or more sources that continuously
return data, asked
@@ -2019,8 +2016,9 @@ impl PyDataFrame {
#[getter]
fn is_streaming(&self, py: Python<'_>) -> PyResult<bool> {
cached(&self.is_streaming, || {
- py.detach(|| self.dataframe.is_streaming().map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.is_streaming().map_err(Box::new)
+ })
})
}
@@ -2028,9 +2026,9 @@ impl PyDataFrame {
#[pyo3(name = "storageLevel")]
#[getter]
fn storage_level(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
- let sl = py
- .detach(|| self.dataframe.storage_level().map_err(Box::new))
- .to_pyerr()?;
+ let sl = interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.storage_level().map_err(Box::new)
+ })?;
let cls = py.import("pyspark.storagelevel")?.getattr("StorageLevel")?;
Ok(cls
.call1((
@@ -2180,8 +2178,9 @@ impl PyDataFrame {
};
// As PySpark's, which returns the DataFrame itself.
let df = slf.dataframe.clone();
- py.detach(|| df.persist(level).map_err(Box::new))
- .to_pyerr()?;
+ interruptible(py, &df.spark_session(), || {
+ df.persist(level).map_err(Box::new)
+ })?;
Ok(slf)
}
@@ -2491,9 +2490,9 @@ 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().map_err(Box::new))
- .to_pyerr()?;
+ let schema = interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.schema()
+ })?;
check_nanosecond_timestamps(py, Some(&schema))?;
crate::types::data_type_to_py(py, &schema)
}
@@ -2542,9 +2541,10 @@ impl PyDataFrame {
#[getter]
fn columns(&self, py: Python<'_>) -> PyResult<Vec<String>> {
// The schema is cached, so the names come from it without another
request.
- let schema = py.detach(|| self.dataframe.schema()).to_pyerr()?;
+ let session = self.dataframe.spark_session();
+ let schema = interruptible(py, &session, || self.dataframe.schema())?;
check_nanosecond_timestamps(py, Some(&schema))?;
- py.detach(|| self.dataframe.columns().to_pyerr())
+ interruptible(py, &session, || self.dataframe.columns())
}
/// Get the last `num` rows as a list of Rows (eager, like pyspark `tail`).
@@ -2639,7 +2639,9 @@ impl PyDataFrame {
Some(level) if level.is_truthy()? => Some(level),
_ => None,
};
- let schema = py.detach(|| self.dataframe.schema().to_pyerr())?;
+ let schema = interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.schema()
+ })?;
check_nanosecond_timestamps(py, Some(&schema))?;
let depth = level
.map(crate::types::normalize_tree_depth)
@@ -2653,7 +2655,9 @@ impl PyDataFrame {
/// Get the schema as a list of (name, type) tuples.
#[getter]
fn dtypes(&self, py: Python<'_>) -> PyResult<Vec<(String, String)>> {
- let schema = py.detach(|| self.dataframe.schema().to_pyerr())?;
+ let schema = interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.schema()
+ })?;
check_nanosecond_timestamps(py, Some(&schema))?;
let spark_connect::types::DataType::Struct { fields } = schema else {
unreachable!("schema() validates struct responses")
@@ -2825,9 +2829,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().map_err(Box::new))
- .to_pyerr()?;
+ let cols = interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.columns()
+ })?;
let udf = build_map_udf(
py,
&self.dataframe.spark_session(),
@@ -2855,9 +2859,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().map_err(Box::new))
- .to_pyerr()?;
+ let cols = interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.columns()
+ })?;
let udf = build_map_udf(
py,
&self.dataframe.spark_session(),
@@ -4121,15 +4125,6 @@ impl<T: Clone> WriterState<T> {
}
}
-/// `f` without the GIL, as PySpark's requests to the server release it while
they wait, so
-/// that other Python threads run. `f` boxes its error, which keeps its result
small.
-pub(crate) fn detached<T: Send>(
- py: Python<'_>,
- f: impl FnOnce() -> Result<T, Box<spark_connect_core::error::SparkError>>
+ Send,
-) -> PyResult<T> {
- py.detach(f).to_pyerr()
-}
-
// ---- Shared helpers for closure-based (UDF) DataFrame/GroupedData methods
----
/// cloudpickle an arbitrary Python object to bytes (mirrors the scalar UDF
path,
@@ -4478,12 +4473,11 @@ fn check_collectable(
/// including when the server sends only an Arrow schema or the result has no
binary fields.
/// Collect reads it after execution; a local iterator snapshots it before its
first fetch.
fn read_binary_as_bytes(py: Python<'_>, dataframe: &DataFrame) ->
PyResult<bool> {
- let value = detached(py, || {
- dataframe
- .spark_session()
+ let session = dataframe.spark_session();
+ let value = interruptible(py, &session, || {
+ session
.conf()
.get_with_default("spark.sql.execution.pyspark.binaryAsBytes",
Some("true"))
- .map_err(Box::new)
})?;
Ok(value.is_some_and(|value| value.eq_ignore_ascii_case("true")))
}
diff --git a/crates/pyspark-rs/src/errors.rs b/crates/pyspark-rs/src/errors.rs
index b472aa64..3250860f 100644
--- a/crates/pyspark-rs/src/errors.rs
+++ b/crates/pyspark-rs/src/errors.rs
@@ -277,7 +277,7 @@ fn set_context(
/// `raised`, with `secondary` as its `__context__`: an exception that kept
the client from
/// raising a more specific exception than `raised` is not dropped, but
chained to the one that
/// is raised in its place, as Python chains an exception raised while another
is handled.
-fn with_context(py: Python<'_>, raised: PyErr, secondary: PyErr) -> PyErr {
+pub(crate) fn with_context(py: Python<'_>, raised: PyErr, secondary: PyErr) ->
PyErr {
set_context(py, raised.value(py), secondary);
raised
}
diff --git a/crates/pyspark-rs/src/group.rs b/crates/pyspark-rs/src/group.rs
index da2da7d2..5e258f3c 100644
--- a/crates/pyspark-rs/src/group.rs
+++ b/crates/pyspark-rs/src/group.rs
@@ -8,6 +8,7 @@ use crate::dataframe::{
build_map_udf, infer_group_map_eval_type, validate_map_function,
PyDataFrame,
};
use crate::errors::ResultExt;
+use crate::interrupt::interruptible;
/// As PySpark's `_check_same_session` of the DataFrames of grouped data:
`SESSION_NOT_SAME`
/// unless `other` is of the session of `this`.
@@ -95,9 +96,10 @@ impl PyGroupedData {
}
let refs: Vec<&str> = names.iter().map(String::as_str).collect();
let grouped = &self.grouped_data;
- py.detach(|| grouped.numeric_agg(function, refs).map_err(Box::new))
- .to_pyerr()
- .map(PyDataFrame::new)
+ interruptible(py, &grouped.spark_session(), || {
+ grouped.numeric_agg(function, refs)
+ })
+ .map(PyDataFrame::new)
}
}
@@ -116,9 +118,7 @@ impl PyGroupedData {
.map(|column| column.expression().render())
.collect();
let dataframe = self.grouped_data.dataframe().clone();
- let dtypes = py
- .detach(|| dataframe.dtypes().map_err(Box::new))
- .to_pyerr()?;
+ let dtypes = interruptible(py, &dataframe.spark_session(), ||
dataframe.dtypes())?;
let values: Vec<String> = dtypes
.iter()
.map(|(name, data_type)| format!("{name}: {data_type}"))
@@ -268,7 +268,9 @@ impl PyGroupedData {
eval_type::SQL_GROUPED_MAP_PANDAS_UDF,
)?;
validate_map_function(py, &func, eval_type_id)?;
- let cols = py.detach(|| self.grouped_data.input_columns()).to_pyerr()?;
+ let cols = interruptible(py, &self.grouped_data.spark_session(), || {
+ self.grouped_data.input_columns()
+ })?;
let session = self.grouped_data.spark_session();
let udf = build_map_udf(py, &session, &func, &schema, eval_type_id,
&cols)?;
Ok(PyDataFrame::new(self.grouped_data.apply_in_pandas(udf)))
@@ -325,7 +327,9 @@ impl PyGroupedData {
eval_type::SQL_GROUPED_MAP_ARROW_UDF,
)?;
validate_map_function(py, &func, eval_type_id)?;
- let cols = py.detach(|| self.grouped_data.input_columns()).to_pyerr()?;
+ let cols = interruptible(py, &self.grouped_data.spark_session(), || {
+ self.grouped_data.input_columns()
+ })?;
let session = self.grouped_data.spark_session();
let udf = build_map_udf(py, &session, &func, &schema, eval_type_id,
&cols)?;
Ok(PyDataFrame::new(self.grouped_data.apply_in_arrow(udf)))
@@ -353,7 +357,9 @@ impl PyGroupedData {
timeoutConf: &str,
) -> PyResult<PyDataFrame> {
validate_map_function(py, &func,
eval_type::SQL_GROUPED_MAP_PANDAS_UDF_WITH_STATE)?;
- let cols = py.detach(|| self.grouped_data.input_columns()).to_pyerr()?;
+ let cols = interruptible(py, &self.grouped_data.spark_session(), || {
+ self.grouped_data.input_columns()
+ })?;
let session = self.grouped_data.spark_session();
let udf = build_map_udf(
py,
@@ -401,7 +407,9 @@ impl PyGroupedData {
initialState.is_some(),
true,
)?;
- let cols = py.detach(|| self.grouped_data.input_columns()).to_pyerr()?;
+ let cols = interruptible(py, &self.grouped_data.spark_session(), || {
+ self.grouped_data.input_columns()
+ })?;
let session = self.grouped_data.spark_session();
let udf = build_map_udf(py, &session, &func, &outputStructType, et,
&cols)?;
// As PySpark's, which sends a DDL string as an `UnparsedDataType`,
for the server to
@@ -451,7 +459,9 @@ impl PyGroupedData {
initialState.is_some(),
false,
)?;
- let cols = py.detach(|| self.grouped_data.input_columns()).to_pyerr()?;
+ let cols = interruptible(py, &self.grouped_data.spark_session(), || {
+ self.grouped_data.input_columns()
+ })?;
let session = self.grouped_data.spark_session();
let udf = build_map_udf(py, &session, &func, &outputStructType, et,
&cols)?;
let etc =
(!eventTimeColumnName.is_empty()).then_some(eventTimeColumnName);
@@ -522,7 +532,9 @@ impl PyCoGroupedData {
schema: Bound<'_, PyAny>,
) -> PyResult<PyDataFrame> {
validate_map_function(py, &func,
eval_type::SQL_COGROUPED_MAP_PANDAS_UDF)?;
- let cols = py.detach(|| self.inner.input_columns()).to_pyerr()?;
+ let cols = interruptible(py, &self.inner.spark_session(), || {
+ self.inner.input_columns()
+ })?;
let udf = build_map_udf(
py,
&self.inner.spark_session(),
@@ -543,7 +555,9 @@ impl PyCoGroupedData {
schema: Bound<'_, PyAny>,
) -> PyResult<PyDataFrame> {
validate_map_function(py, &func,
eval_type::SQL_COGROUPED_MAP_ARROW_UDF)?;
- let cols = py.detach(|| self.inner.input_columns()).to_pyerr()?;
+ let cols = interruptible(py, &self.inner.spark_session(), || {
+ self.inner.input_columns()
+ })?;
let udf = build_map_udf(
py,
&self.inner.spark_session(),
diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index 44164610..ad635f05 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -17,12 +17,11 @@ use pyo3::types::{
IntoPyDict, PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyInt, PyList,
PyMemoryView,
PyString, PyTuple, PyType,
};
-use spark_connect::conf::RuntimeConf;
use spark_connect::row::{StructValue, Value};
+use spark_connect::session::SparkSession;
use spark_connect::types::{DataType, GeographyType, GeometryType, StructField};
use crate::column::raise_pyspark;
-use crate::errors::ResultExt;
use crate::values::{geography_class, geometry_class, variant_val_class};
static DECIMAL: PyOnceLock<Py<PyType>> = PyOnceLock::new();
@@ -236,14 +235,14 @@ struct Confs {
/// needs one. Only dicts, lists of more than one element and naive datetimes
depend on them,
/// so other data is inferred without a request, as without a server.
pub(crate) struct LazyConfs {
- conf: RuntimeConf,
+ session: SparkSession,
confs: OnceCell<Confs>,
}
impl LazyConfs {
- pub(crate) fn new(conf: RuntimeConf) -> Self {
+ pub(crate) fn new(session: SparkSession) -> Self {
LazyConfs {
- conf,
+ session,
confs: OnceCell::new(),
}
}
@@ -258,10 +257,9 @@ impl LazyConfs {
"spark.sql.pyspark.legacy.inferMapTypeFromFirstPair.enabled",
"spark.sql.timestampType",
];
- let conf = &self.conf;
- let values = py
- .detach(|| conf.get_many(&keys).map_err(Box::new))
- .to_pyerr()?;
+ let session = self.session.clone();
+ let values =
+ crate::interrupt::interruptible(py, &session, ||
session.conf().get_many(&keys))?;
let is =
|i: usize, expected: &str| values.get(i).and_then(|v|
v.as_deref()) == Some(expected);
Ok(self.confs.get_or_init(|| Confs {
diff --git a/crates/pyspark-rs/src/interrupt.rs
b/crates/pyspark-rs/src/interrupt.rs
index 7644aaaf..d58da085 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -24,9 +24,21 @@ struct SignalWatch {
interrupted: AtomicBool,
/// The exception of the first handler that raised, which the wait raises
once it has ended.
error: Mutex<Option<PyErr>>,
+ /// The error of the interrupt of the execution, if the server fails it.
The wait raises it
+ /// once it has ended, in place of the KeyboardInterrupt of the signal, as
PySpark's
+ /// `interrupt_operation` raises out of the `except KeyboardInterrupt` of
an execution.
+ interrupt_failure: Arc<Mutex<Option<SparkError>>>,
}
impl SignalWatch {
+ /// Whether the server has failed the interrupt of the execution.
+ fn interrupt_failure_is_set(&self) -> bool {
+ self.interrupt_failure
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .is_some()
+ }
+
fn poll(&self) -> Watch {
{
let mut error = self.error.lock().unwrap_or_else(|e|
e.into_inner());
@@ -37,6 +49,11 @@ impl SignalWatch {
Err(signal) => *error = Some(signal),
}
} else if self.interrupted.load(Ordering::SeqCst) {
+ // A failed interrupt ends the wait at once, as PySpark raises
the error of the
+ // interrupt without waiting for the server to end the
execution.
+ if self.interrupt_failure_is_set() {
+ return Watch::Abort;
+ }
// After the interrupt, a second signal ends the wait, as
PySpark's wait does.
return match Python::attach(|py| py.check_signals()) {
Ok(()) => Watch::Continue,
@@ -48,9 +65,11 @@ impl SignalWatch {
Some(operation_id) => {
self.interrupted.store(true, Ordering::SeqCst);
let session = self.session.clone();
+ let failure = Arc::clone(&self.interrupt_failure);
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;
+ if let Err(error) =
session.interrupt_operation_async(&operation_id).await {
+ *failure.lock().unwrap_or_else(|e| e.into_inner()) =
Some(error);
+ }
}))
}
// No execution to interrupt: a wait that can end before its
future, such as the
@@ -99,6 +118,7 @@ pub(crate) fn interruptible_outcome<T: Send, E: Send +
Into<Box<SparkError>>>(
session: session.clone(),
interrupted: AtomicBool::new(false),
error: Mutex::new(None),
+ interrupt_failure: Arc::new(Mutex::new(None)),
});
let poll: Arc<WaitWatch> = {
let watch = Arc::clone(&watch);
@@ -106,6 +126,11 @@ pub(crate) fn interruptible_outcome<T: Send, E: Send +
Into<Box<SparkError>>>(
};
let output = py.detach(|| with_wait_watch(poll, f));
let signal = watch.error.lock().unwrap_or_else(|e| e.into_inner()).take();
+ let interrupt_failure = watch
+ .interrupt_failure
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .take();
let output: Result<T, Box<SparkError>> = output.map_err(Into::into);
match signal {
Some(error) => {
@@ -121,6 +146,12 @@ pub(crate) fn interruptible_outcome<T: Send, E: Send +
Into<Box<SparkError>>>(
return Err(done);
}
}
+ // As PySpark's: the error of the interrupt replaces the
KeyboardInterrupt, which
+ // becomes its context, as `interrupt_operation` raises out of the
`except` clause.
+ if let Some(failure) = interrupt_failure {
+ let failure =
crate::errors::spark_error_to_py_exception(failure);
+ return Err(crate::errors::with_context(py, failure, error));
+ }
Err(error)
}
None => Ok(output),
diff --git a/crates/pyspark-rs/src/observation.rs
b/crates/pyspark-rs/src/observation.rs
index 43a1b4cc..a4a7c5ff 100644
--- a/crates/pyspark-rs/src/observation.rs
+++ b/crates/pyspark-rs/src/observation.rs
@@ -135,9 +135,9 @@ pub(crate) fn observe(
exprs: Vec<Expression>,
) -> PyResult<PyDataFrame> {
let inner = observation.borrow().inner.clone();
- let observed = py
- .detach(|| df.observe_with(&inner, exprs).map_err(Box::new))
- .to_pyerr()?;
+ let observed = crate::interrupt::interruptible(py, &df.spark_session(), ||
{
+ df.observe_with(&inner, exprs)
+ })?;
if let Some(name) = inner.name() {
let weak = PyWeakrefReference::new(observation)?.unbind();
let mut sessions = observations().lock().unwrap_or_else(|e|
e.into_inner());
diff --git a/crates/pyspark-rs/src/pipelines.rs
b/crates/pyspark-rs/src/pipelines.rs
index a1ef0555..eefee2a8 100644
--- a/crates/pyspark-rs/src/pipelines.rs
+++ b/crates/pyspark-rs/src/pipelines.rs
@@ -10,6 +10,7 @@ use pyo3::prelude::*;
use spark_connect::pipelines::{
self, OutputSpec, PipelineRunStream, SinkDetailsSpec, TableDetailsSpec,
};
+use spark_connect::session::SparkSession;
use spark_connect_proto as proto;
use crate::column::PyColumn;
@@ -284,6 +285,9 @@ pub fn pipeline_define_sql_graph_elements(
)]
pub struct PyPipelineRunStream {
inner: PipelineRunStream,
+ /// The session of the run, whose executions a signal of the process
interrupts while the
+ /// next response of the run is waited for.
+ session: SparkSession,
}
#[pymethods]
@@ -294,9 +298,10 @@ impl PyPipelineRunStream {
fn __next__(&mut self, py: Python<'_>) -> PyResult<Option<(String, i64)>> {
loop {
- let resp = py
- .detach(|| self.inner.next_response().map_err(Box::new))
- .to_pyerr()?;
+ let resp = crate::interrupt::interruptible_outcome(py,
&self.session, || {
+ self.inner.next_response()
+ })?
+ .to_pyerr()?;
let Some(resp) = resp else {
return Ok(None); // stream complete -> StopIteration
};
@@ -344,5 +349,8 @@ pub fn pipeline_start_run(
)
.map_err(Box::new)
})?;
- Ok(PyPipelineRunStream { inner })
+ Ok(PyPipelineRunStream {
+ inner,
+ session: sess,
+ })
}
diff --git a/crates/pyspark-rs/src/pyarrow_import.rs
b/crates/pyspark-rs/src/pyarrow_import.rs
index 769181be..afaf2b7c 100644
--- a/crates/pyspark-rs/src/pyarrow_import.rs
+++ b/crates/pyspark-rs/src/pyarrow_import.rs
@@ -23,7 +23,6 @@ use pyo3::prelude::*;
use spark_connect::session::SparkSession;
use crate::dataframe::PyDataFrame;
-use crate::errors::ResultExt;
/// The record batches of a pyarrow table, at least one, so that a table
without rows keeps its
/// schema, as PySpark's IPC stream does, for the relation to carry it.
@@ -60,7 +59,9 @@ pub(crate) fn create_dataframe(
let options = if empty {
None
} else {
- Some(py.detach(|| session.arrow_input_options().to_pyerr())?)
+ Some(crate::interrupt::interruptible(py, session, || {
+ session.arrow_input_options()
+ })?)
};
let result = helper.getattr("prepare_table")?.call1((
table,
@@ -82,14 +83,11 @@ pub(crate) fn create_dataframe(
} else {
table_batches(&normalized)?
};
- let dataframe = py.detach(|| {
- match options.as_ref() {
- Some(options) => {
- session.create_dataframe_from_arrow_with_options(batches,
spark_schema, options)
- }
- None => session.create_dataframe_from_arrow(batches, spark_schema),
+ let dataframe = crate::interrupt::interruptible(py, session, || match
options.as_ref() {
+ Some(options) => {
+ session.create_dataframe_from_arrow_with_options(batches,
spark_schema, options)
}
- .to_pyerr()
+ None => session.create_dataframe_from_arrow(batches, spark_schema),
})?;
// As in PySpark, column names are applied with toDF only when there are
any.
let dataframe = match names {
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 51e5bdc8..dd8fa238 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -352,9 +352,9 @@ impl PySparkSessionBuilder {
.map(|(key, value)| (key.as_str(), value.as_deref()))
.collect();
let conf = session.conf();
- let warnings = py
- .detach(|| conf.set_pairs(&pairs, Some(true)).map_err(Box::new))
- .to_pyerr()?;
+ let warnings = interruptible(py, session, || {
+ conf.set_pairs(&pairs, Some(true)).map_err(Box::new)
+ })?;
// As PySpark's `_set_all`, which warns each warning of the server.
crate::conf::warn_all(py, &warnings)
}
@@ -914,13 +914,11 @@ impl PySparkSession {
));
};
let schema = DataType::Struct { fields };
- let df = py
- .detach(|| {
- self.session
- .create_dataframe(Vec::new(), schema)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let df = interruptible(py, &self.session, || {
+ self.session
+ .create_dataframe(Vec::new(), schema)
+ .map_err(Box::new)
+ })?;
return Ok(PyDataFrame::new(df));
}
let mut items: Vec<Bound<'_, PyAny>> =
data.try_iter()?.collect::<PyResult<_>>()?;
@@ -952,7 +950,7 @@ impl PySparkSession {
Some(fields) => fields,
None => {
// The configurations are read only when a value depends on
them.
- let confs = infer::LazyConfs::new(self.session.conf());
+ let confs = infer::LazyConfs::new(self.session.clone());
let options = infer::Options::new(&confs);
let mut merged: Option<DataType> = None;
for item in &items {
@@ -1040,13 +1038,11 @@ impl PySparkSession {
.map(|values| StructValue::new(names.clone(), values).into())
.collect();
let schema = DataType::Struct { fields };
- let df = py
- .detach(|| {
- self.session
- .create_dataframe(rows, schema)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let df = interruptible(py, &self.session, || {
+ self.session
+ .create_dataframe(rows, schema)
+ .map_err(Box::new)
+ })?;
// As pyspark, column names are applied with toDF. The local relation
already carries
// them, so this only changes the plan, which the server resolves into
a Project that
// is not local; it keeps isLocal() as in pyspark and is not redundant.
@@ -1080,19 +1076,17 @@ impl PySparkSession {
{
return Ok(None);
}
- let options = py.detach(||
self.session.arrow_input_options().to_pyerr())?;
+ let options = interruptible(py, &self.session, ||
self.session.arrow_input_options())?;
// The option is always set, as the importer requires it.
let timezone = options.timezone().unwrap_or("UTC").to_owned();
let large = options.use_large_var_types() == Some("true");
- let safecheck = py
- .detach(|| {
- self.session
- .conf()
-
.get("spark.sql.execution.pandas.convertToArrowArraySafely")
- .map_err(Box::new)
- })
- .to_pyerr()?
- .as_deref()
+ let safecheck = interruptible(py, &self.session, || {
+ self.session
+ .conf()
+ .get("spark.sql.execution.pandas.convertToArrowArraySafely")
+ .map_err(Box::new)
+ })?
+ .as_deref()
== Some("true");
// The caller's StructType, which the guard checked, is converted as
given; a DDL
// string is parsed into the same fields.
@@ -1122,13 +1116,11 @@ impl PySparkSession {
// of the fields of a struct (DUPLICATED_FIELD_NAME_IN_ARROW_STRUCT).
let spark_schema = crate::types::py_to_data_type(schema_py.bind(py))?;
let batches = crate::pyarrow_import::table_batches(&table)?;
- let df = py
- .detach(|| {
- self.session
- .create_dataframe_from_arrow_with_options(batches,
Some(spark_schema), &options)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let df = interruptible(py, &self.session, || {
+ self.session
+ .create_dataframe_from_arrow_with_options(batches,
Some(spark_schema), &options)
+ .map_err(Box::new)
+ })?;
// As the other pandas paths, the explicit names are applied with toDF.
Ok(Some(PyDataFrame::new(df.to_df(
fields.iter().map(|field| field.name.as_str()).collect(),
@@ -1212,13 +1204,11 @@ impl PySparkSession {
));
}
let batches = crate::pyarrow_import::table_batches(&table)?;
- let df = py
- .detach(|| {
- self.session
- .create_dataframe_from_arrow_with_options(batches, None,
&settings.options)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let df = interruptible(py, &self.session, || {
+ self.session
+ .create_dataframe_from_arrow_with_options(batches, None,
&settings.options)
+ .map_err(Box::new)
+ })?;
Ok(Some(PyDataFrame::new(if columns.is_empty() {
df
} else {
@@ -1292,14 +1282,12 @@ impl PySparkSession {
return Err(axis_length_mismatch(expected));
}
let batches = crate::pyarrow_import::table_batches(&table)?;
- let options = py.detach(||
self.session.arrow_input_options().to_pyerr())?;
- let df = py
- .detach(|| {
- self.session
- .create_dataframe_from_arrow_with_options(batches, schema,
&options)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let options = interruptible(py, &self.session, ||
self.session.arrow_input_options())?;
+ let df = interruptible(py, &self.session, || {
+ self.session
+ .create_dataframe_from_arrow_with_options(batches, schema,
&options)
+ .map_err(Box::new)
+ })?;
Ok(PyDataFrame::new(df))
}
@@ -1691,7 +1679,7 @@ impl PySparkSession {
let settings = row_settings.ok_or_else(|| {
pyo3::exceptions::PyRuntimeError::new_err("missing pandas Row
Arrow options")
})?;
- py.detach(|| {
+ interruptible(py, &self.session, || {
self.session
.create_dataframe_from_arrow_with_options(
batches,
@@ -1699,15 +1687,13 @@ impl PySparkSession {
&settings.options,
)
.map_err(Box::new)
- })
- .to_pyerr()?
+ })?
} else {
- py.detach(|| {
+ interruptible(py, &self.session, || {
self.session
.create_dataframe(rows, schema)
.map_err(Box::new)
- })
- .to_pyerr()?
+ })?
};
Ok(PyDataFrame::new(match names {
Some(names) if !names.is_empty() => {
@@ -1722,10 +1708,9 @@ impl PySparkSession {
py: Python<'_>,
allow_dict_as_map: bool,
) -> PyResult<PandasArrowSettings> {
- let options = py.detach(||
self.session.arrow_input_options().to_pyerr())?;
+ let options = interruptible(py, &self.session, ||
self.session.arrow_input_options())?;
let conf = |key: &'static str| {
- py.detach(|| self.session.conf().get(key).map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.session, || self.session.conf().get(key))
.map(|value| value.as_deref() == Some("true"))
};
Ok(PandasArrowSettings {
@@ -1860,15 +1845,17 @@ impl PySparkSession {
);
// Row frames reuse the Arrow settings already read for the whole
frame. Other
// native frames retain their existing read-on-error behavior and
default.
- let safecheck = safecheck.unwrap_or_else(|| {
- py.detach(|| {
+ // A signal that ends the read raises its exception, which the default
does not replace.
+ let safecheck = match safecheck {
+ Some(safecheck) => safecheck,
+ None => crate::interrupt::interruptible_outcome(py, &self.session,
|| {
self.session
.conf()
.get("spark.sql.execution.pandas.convertToArrowArraySafely")
.map_err(Box::new)
- })
- .map_or(true, |value| value.is_none_or(|value| value == "true"))
- });
+ })?
+ .map_or(true, |value| value.is_none_or(|value| value == "true")),
+ };
if safecheck {
message.push_str(
" It can be caused by overflows or other unsafe conversions
warned by Arrow. \
@@ -2157,11 +2144,8 @@ impl PySparkSession {
let timezone = if aware {
None
} else {
- py.detach(|| {
- self.session
- .conf()
- .get("spark.sql.session.timeZone")
- .to_pyerr()
+ interruptible(py, &self.session, || {
+ self.session.conf().get("spark.sql.session.timeZone")
})?
};
let table = helper
@@ -2199,13 +2183,11 @@ impl PySparkSession {
fields: fields.clone(),
};
let ipc: Vec<u8> = ipc.extract()?;
- let frame = py
- .detach(|| {
- self.session
- .create_dataframe_from_inline_arrow_ipc(ipc,
schema)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let frame = interruptible(py, &self.session, || {
+ self.session
+ .create_dataframe_from_inline_arrow_ipc(ipc, schema)
+ .map_err(Box::new)
+ })?;
// Match pandas row input: explicit nonempty field names travel
// through toDF as well as the local relation's logical schema.
return Ok(PyDataFrame::new(
@@ -2245,13 +2227,11 @@ impl PySparkSession {
fields: fields.clone(),
};
let ipc: Vec<u8> = ipc.extract()?;
- let frame = py
- .detach(|| {
- self.session
- .create_dataframe_from_inline_arrow_ipc(ipc,
schema)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let frame = interruptible(py, &self.session, || {
+ self.session
+ .create_dataframe_from_inline_arrow_ipc(ipc, schema)
+ .map_err(Box::new)
+ })?;
// Match pandas row input: explicit nonempty field names travel
// through toDF as well as the local relation's logical schema.
return Ok(PyDataFrame::new(
@@ -2298,13 +2278,11 @@ impl PySparkSession {
let schema = DataType::Struct {
fields: fields.clone(),
};
- let df = py
- .detach(|| {
- self.session
- .create_dataframe_from_columns(columns,
schema)
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let df = interruptible(py, &self.session, || {
+ self.session
+ .create_dataframe_from_columns(columns, schema)
+ .map_err(Box::new)
+ })?;
return Ok(PyDataFrame::new(df));
}
}
@@ -2324,7 +2302,7 @@ impl PySparkSession {
#[getter]
#[pyo3(name = "conf")]
fn conf(&self) -> crate::conf::PyRuntimeConf {
- crate::conf::PyRuntimeConf::new(self.session.conf())
+ crate::conf::PyRuntimeConf::new(self.session.clone())
}
/// Table-valued functions namespace (`spark.tvf`).
@@ -2381,12 +2359,11 @@ impl PySparkSession {
"destination FS path must be an absolute path.",
));
}
- py.detach(|| {
+ interruptible(py, &self.session, || {
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
@@ -2722,8 +2699,7 @@ impl PySparkSession {
/// Release the session on the server, without stopping it, for
`client.release_session`.
fn _release_session(&self, py: Python<'_>) -> PyResult<()> {
let session = self.session.clone();
- py.detach(|| session.release_session().map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &session, ||
session.release_session().map_err(Box::new))
}
/// Close the session without releasing it on the server, for
`client.close`.
@@ -2929,9 +2905,7 @@ impl PySparkSession {
/// The type of the DDL string `ddl`, as the server parses it, as PySpark
Connect's
/// `SparkSession._parse_ddl`, of a `DDLParse` of an `AnalyzePlanRequest`.
fn _parse_ddl(&self, py: Python<'_>, ddl: &str) -> PyResult<Py<PyAny>> {
- let data_type = py
- .detach(|| self.session.parse_ddl(ddl).map_err(Box::new))
- .to_pyerr()?;
+ let data_type = interruptible(py, &self.session, ||
self.session.parse_ddl(ddl))?;
crate::dataframe::check_nanosecond_timestamps(py, Some(&data_type))?;
crate::types::data_type_to_py(py, &data_type)
}
@@ -3012,18 +2986,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(|| {
+ interruptible(py, &self.session, || {
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().map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.session, || {
+ self.session.version().map_err(Box::new)
+ })
}
/// The DataFrame of a table, as PySpark Connect's: `NOT_EXPECTED_TYPE`
for a name that is not
@@ -3063,20 +3037,23 @@ impl PySparkSession {
#[pyo3(name = "interruptAll")]
fn interrupt_all(&self, py: Python<'_>) -> PyResult<Vec<String>> {
- py.detach(|| self.session.interrupt_all().map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.session, || {
+ self.session.interrupt_all().map_err(Box::new)
+ })
}
#[pyo3(name = "interruptTag")]
fn interrupt_tag(&self, py: Python<'_>, tag: &str) ->
PyResult<Vec<String>> {
- py.detach(|| self.session.interrupt_tag(tag).map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &self.session, || {
+ self.session.interrupt_tag(tag).map_err(Box::new)
+ })
}
#[pyo3(name = "interruptOperation")]
fn interrupt_operation(&self, py: Python<'_>, op_id: &str) ->
PyResult<Vec<String>> {
- py.detach(|| self.session.interrupt_operation(op_id))
- .to_pyerr()
+ interruptible(py, &self.session, || {
+ self.session.interrupt_operation(op_id)
+ })
}
/// Add a tag of the current thread, with the errors of PySpark Connect's
tags: `CANNOT_BE_NONE`
@@ -3110,8 +3087,9 @@ impl PySparkSession {
fn to_ddl(&self, py: Python<'_>, r#struct: &Bound<'_, PyAny>) ->
PyResult<String> {
let json: String = r#struct.call_method0("json")?.extract()?;
let session = self.session.clone();
- py.detach(|| session.json_to_ddl(&json).map_err(Box::new))
- .to_pyerr()
+ interruptible(py, &session, || {
+ session.json_to_ddl(&json).map_err(Box::new)
+ })
}
/// The tags of the current thread, a set, as PySpark's `getTags`.
@@ -3193,12 +3171,11 @@ impl PySparkSession {
check_local_artifact(py, &name, &local, pyfile)?;
}
let refs: Vec<&str> = path.iter().map(|s| s.as_str()).collect();
- py.detach(|| {
+ interruptible(py, &self.session, || {
self.session
.add_artifacts_with(&refs, pyfile, archive, file)
.map_err(Box::new)
})
- .to_pyerr()
}
/// `addArtifact` is `addArtifacts`, as in PySpark.
@@ -3229,13 +3206,11 @@ impl PySparkSession {
py: Python<'_>,
new_session_id: Option<String>,
) -> PyResult<Py<PySparkSession>> {
- let session = py
- .detach(|| {
- self.session
- .clone_session_with_id(new_session_id.as_deref())
- .map_err(Box::new)
- })
- .to_pyerr()?;
+ let session = interruptible(py, &self.session, || {
+ self.session
+ .clone_session_with_id(new_session_id.as_deref())
+ .map_err(Box::new)
+ })?;
session_object(py, &session)
}
}
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index f52bc57d..1e5b2410 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -1184,7 +1184,7 @@ impl PyStreamingQuery {
#[getter]
fn isActive(&self, py: Python<'_>) -> PyResult<bool> {
- crate::dataframe::detached(py, ||
self.inner.is_active().map_err(Box::new))
+ interruptible(py, &self.inner.spark_session(), ||
self.inner.is_active())
}
/// The status of the query, as PySpark's: a dict of its `message`,
`isDataAvailable` and
diff --git a/crates/pyspark-rs/src/transport.rs
b/crates/pyspark-rs/src/transport.rs
index 2615f26f..ec42141d 100644
--- a/crates/pyspark-rs/src/transport.rs
+++ b/crates/pyspark-rs/src/transport.rs
@@ -196,9 +196,7 @@ impl RustConnectStub {
let builder = ChannelBuilder::parse(url).to_pyerr()?;
// Release the GIL during the connect handshake so a slow/unresponsive
server
// can't wedge the whole interpreter (incl. signal handling / Ctrl-C).
- let mut client = py
- .detach(|| block_on(SparkConnectClient::connect(&builder)))
- .to_pyerr()?;
+ let mut client = until_signal(py,
SparkConnectClient::connect(&builder))?.to_pyerr()?;
// This stub is a drop-in for the grpcio stub: a single RPC per call.
The reference
// client wraps calls in its own GrpcRetryHandler (per the client-side
retry
// policy), so retrying inside our client too would double-retry and
ignore that
@@ -259,8 +257,7 @@ impl RustConnectStub {
/// ReleaseExecute: unary.
fn release_execute<'py>(&self, py: Python<'py>, request: &[u8]) ->
PyResult<Py<PyBytes>> {
let req = proto::ReleaseExecuteRequest::decode(request).map_err(err)?;
- let resp = py
- .detach(|| block_on(self.client.release_execute(req)))
+ let resp = until_signal(py, self.client.release_execute(req))?
.map_err(|e| spark_err_to_py(py, e))?;
Ok(PyBytes::new(py, &resp.encode_to_vec()).unbind())
}
@@ -268,8 +265,7 @@ impl RustConnectStub {
/// AnalyzePlan: unary. Forwards raw request bytes (no prost decode) so
deeply
/// nested plans don't hit prost's recursion limit; returns raw response
bytes.
fn analyze_plan<'py>(&self, py: Python<'py>, request: &[u8]) ->
PyResult<Py<PyBytes>> {
- let resp = py
- .detach(||
block_on(self.client.analyze_plan_raw(request.to_vec())))
+ let resp = until_signal(py,
self.client.analyze_plan_raw(request.to_vec()))?
.map_err(|e| spark_err_to_py(py, e))?;
Ok(PyBytes::new(py, &resp).unbind())
}
@@ -277,18 +273,16 @@ impl RustConnectStub {
/// Config: unary.
fn config<'py>(&self, py: Python<'py>, request: &[u8]) ->
PyResult<Py<PyBytes>> {
let req = proto::ConfigRequest::decode(request).map_err(err)?;
- let resp = py
- .detach(|| block_on(self.client.config(req)))
- .map_err(|e| spark_err_to_py(py, e))?;
+ let resp =
+ until_signal(py, self.client.config(req))?.map_err(|e|
spark_err_to_py(py, e))?;
Ok(PyBytes::new(py, &resp.encode_to_vec()).unbind())
}
/// Interrupt: unary.
fn interrupt<'py>(&self, py: Python<'py>, request: &[u8]) ->
PyResult<Py<PyBytes>> {
let req = proto::InterruptRequest::decode(request).map_err(err)?;
- let resp = py
- .detach(|| block_on(self.client.interrupt(req)))
- .map_err(|e| spark_err_to_py(py, e))?;
+ let resp =
+ until_signal(py, self.client.interrupt(req))?.map_err(|e|
spark_err_to_py(py, e))?;
Ok(PyBytes::new(py, &resp.encode_to_vec()).unbind())
}
@@ -296,8 +290,7 @@ impl RustConnectStub {
/// the full server-side stack trace / message (needed for message-regex
assertions).
fn fetch_error_details<'py>(&self, py: Python<'py>, request: &[u8]) ->
PyResult<Py<PyBytes>> {
let req =
proto::FetchErrorDetailsRequest::decode(request).map_err(err)?;
- let resp = py
- .detach(|| block_on(self.client.fetch_error_details(req)))
+ let resp = until_signal(py, self.client.fetch_error_details(req))?
.map_err(|e| spark_err_to_py(py, e))?;
Ok(PyBytes::new(py, &resp.encode_to_vec()).unbind())
}
diff --git a/crates/pyspark-rs/src/types.rs b/crates/pyspark-rs/src/types.rs
index f6f51ed1..ec497dde 100644
--- a/crates/pyspark-rs/src/types.rs
+++ b/crates/pyspark-rs/src/types.rs
@@ -3889,9 +3889,7 @@ pub(crate) fn schema_data_type(
) -> PyResult<DataType> {
if schema.is_instance_of::<pyo3::types::PyString>() {
let ddl: String = schema.extract()?;
- let parsed = crate::errors::ResultExt::to_pyerr(
- py.detach(|| session.parse_ddl(&ddl).map_err(Box::new)),
- )?;
+ let parsed = crate::interrupt::interruptible(py, session, ||
session.parse_ddl(&ddl))?;
// As PySpark converts the parsed type from its proto, which fails for
a nanosecond timestamp.
crate::dataframe::check_nanosecond_timestamps(py, Some(&parsed))?;
return Ok(parsed);
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index b9e00192..9572fdad 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -19009,6 +19009,138 @@ def
test_sigint_raises_the_done_call_error_of_a_progress_handler_with_the_signal
assert isinstance(error.value.__context__, KeyboardInterrupt)
[email protected]("server", ["unreachable", "hung"])
+def test_sigint_ends_a_call_that_waits_for_the_server_at_once(server,
tmp_path):
+ # As PySpark's: the configuration, schema, artifact, clone and interrupt
calls that wait for
+ # the server raise KeyboardInterrupt about a second after the signal,
whether no server
+ # answers the address (the retries of the call sleep) or a server accepts
the connection and
+ # never answers (the call waits). Each call is made in turn, and each gets
its own signal.
+ import subprocess
+ import sys
+
+ artifact = tmp_path / "artifact.txt"
+ artifact.write_text("x")
+ code = """
+import os, signal, socket, sys, threading, time
+from pyspark.sql import SparkSession
+mode, artifact = sys.argv[1], sys.argv[2]
+if mode == "hung":
+ listener = socket.socket()
+ listener.bind(("127.0.0.1", 0))
+ # Listens and never accepts: the connection is made, and the server never
answers.
+ listener.listen(16)
+ remote = "sc://127.0.0.1:%d" % listener.getsockname()[1]
+else:
+ remote = "sc://127.0.0.1:1"
+spark = SparkSession.builder.remote(remote).getOrCreate()
+calls = {
+ "conf.get": lambda: spark.conf.get("spark.sql.shuffle.partitions"),
+ "conf.set": lambda: spark.conf.set("spark.sql.shuffle.partitions", "3"),
+ "schema": lambda: spark.range(3).schema,
+ "cloneSession": lambda: spark.cloneSession(),
+ "interruptAll": lambda: spark.interruptAll(),
+}
+# An unanswered AddArtifacts RPC is awaited by the core without a signal
check, so the upload is
+# only checked against the server that refuses the connection.
+if mode != "hung":
+ calls["addArtifacts"] = lambda: spark.addArtifacts(artifact, file=True)
+for name, call in calls.items():
+ timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ call()
+ outcome = "returned"
+ except KeyboardInterrupt:
+ outcome = "interrupted"
+ finally:
+ timer.cancel()
+ print(name, outcome, round(time.monotonic() - started, 2), flush=True)
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", code, server, str(artifact)],
+ env=dict(os.environ, TZ="UTC"),
+ capture_output=True,
+ text=True,
+ timeout=300,
+ )
+ assert result.returncode == 0, result.stderr
+ lines = [line.split() for line in result.stdout.splitlines()]
+ names = ["conf.get", "conf.set", "schema", "cloneSession", "interruptAll"]
+ if server != "hung":
+ names.append("addArtifacts")
+ assert [line[0] for line in lines] == names, result.stdout
+ for _name, outcome, seconds in lines:
+ assert outcome == "interrupted", result.stdout
+ assert float(seconds) < 3, result.stdout
+
+
+def
test_a_failed_interrupt_of_a_blocked_collect_is_raised_with_the_signal_as_context(mock_connect):
+ # As PySpark's: the Interrupt that the signal sends is an RPC whose error
is raised, as
+ # `interrupt_operation` raises out of the `except KeyboardInterrupt` of
the execution, with the
+ # KeyboardInterrupt as the context of the error.
+ import signal
+ import threading
+
+ from pyspark.errors.exceptions.connect import SparkConnectGrpcException
+
+ spark, service = mock_connect
+ service.block_execute = True
+ service.interrupt_failure = ("INTERNAL", "interrupt failed on the server")
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(BaseException) as error:
+ spark.range(3).collect()
+ elapsed = time.monotonic() - started
+ finally:
+ timer.cancel()
+ service.interrupt_failure = None
+ service.release_response()
+ assert elapsed < 3
+ assert isinstance(error.value, SparkConnectGrpcException),
repr(error.value)
+ assert isinstance(error.value.__context__, KeyboardInterrupt)
+ assert len(service.interrupt_requests) == 1
+
+
+def
test_a_failed_interrupt_of_a_held_local_iterator_is_raised_at_the_first_signal(mock_connect):
+ # As PySpark's: the Interrupt of the iterator that waits for the server is
raised, as the
+ # first signal interrupts it, instead of being dropped, so the job does
not run on.
+ import signal
+ import threading
+
+ from pyspark.errors.exceptions.connect import SparkConnectGrpcException
+
+ spark, service = mock_connect
+ _two_row_range_results(service)
+ service.block_result_complete = True
+ rows = spark.range(2).toLocalIterator()
+ assert next(rows).id == 0
+ assert next(rows).id == 1
+ service.interrupt_failure = ("INTERNAL", "interrupt failed on the server")
+ # Bounds the wait of a run that does not raise, as the server would end it
at its own limit.
+ release = threading.Timer(3.0, service.release_response)
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ release.start()
+ try:
+ with pytest.raises(BaseException) as error:
+ next(rows)
+ elapsed = time.monotonic() - started
+ finally:
+ timer.cancel()
+ release.cancel()
+ release.join()
+ service.interrupt_failure = None
+ service.release_response()
+ assert elapsed < 2.5
+ assert isinstance(error.value, SparkConnectGrpcException),
repr(error.value)
+ assert isinstance(error.value.__context__, KeyboardInterrupt)
+ assert len(service.interrupt_requests) == 1
+
+
def test_sigint_ends_a_call_to_an_unreachable_server_at_once_as_pyspark():
# As PySpark's: the Config lookup of the first plan of a session that no
server answers is
# retried, and a signal raises KeyboardInterrupt from its retry sleep. No
server is needed.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]