Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 50 additions & 7 deletions pyo3/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ fn attach_attrs(
http_status: Option<u16>,
retryable: bool,
query_id: Option<&str>,
// Extended server-supplied status. These mirror the Thrift path's
// `displayMessage` / `diagnosticInfo` so the connector can populate
// `ServerOperationError.context["diagnostic-info"]` (the Spark stack
// trace) at parity. The kernel `Error` carries them but they were
// previously dropped here.
display_message: Option<&str>,
diagnostic_info: Option<&str>,
error_details_json: Option<&str>,
) -> PyResult<()> {
bound.setattr("code", code)?;
bound.setattr("message", message)?;
Expand All @@ -71,6 +79,28 @@ fn attach_attrs(
bound.setattr("http_status", http_status)?;
bound.setattr("retryable", retryable)?;
bound.setattr("query_id", query_id)?;
bound.setattr("display_message", display_message)?;
bound.setattr("diagnostic_info", diagnostic_info)?;
// ``error_details_json`` is documented (types/sea.rs) as a
// potentially multi-MB server blob, and the type-level doc requires
// wrappers to bound its size. Cap what we expose as a Python
// exception attribute so ``repr(e)`` / log lines can't pump
// multi-MB strings into a customer's centralized logging. The full
// blob remains server-side; this is the boundary's exposure cap.
const MAX_ERROR_DETAILS_JSON: usize = 64 * 1024;
let bounded_details = error_details_json.map(|s| {
if s.len() > MAX_ERROR_DETAILS_JSON {
// Truncate on a char boundary, with a marker.
let mut end = MAX_ERROR_DETAILS_JSON;
while !s.is_char_boundary(end) {
end -= 1;
}
format!("{}…[truncated {} bytes]", &s[..end], s.len() - end)
} else {
s.to_owned()
}
});
bound.setattr("error_details_json", bounded_details)?;
let _ = py; // silence unused-var warning if pyo3 ever drops the Python<'_> arg
Ok(())
}
Expand Down Expand Up @@ -105,14 +135,24 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr {
err.http_status,
err.retryable,
err.query_id.as_deref(),
err.display_message.as_deref(),
err.diagnostic_info.as_deref(),
err.error_details_json.as_deref(),
) {
// Attribute attachment is best-effort. If something goes
// wrong (extremely unlikely for plain string/int setattrs),
// surface that error so the caller sees it rather than a
// partially-populated exception. Fold the original kernel
// message into the new error so debugging context isn't
// lost.
return setattr_err;
// Attribute attachment is best-effort. If something goes wrong
// (extremely unlikely for plain string/int setattrs — but
// marginally less so now that `error_details_json` can be a
// large blob), don't let the partially-populated exception
// swallow the original kernel context: chain the kernel message
// into the setattr error's cause so debugging context survives.
// ``str(setattr_err)`` would otherwise be a generic Python
// internal error with no hint of the underlying SQL failure.
let chained = KernelError::new_err(format!(
"failed to attach kernel error attributes (original kernel error: {}): {}",
err.message, setattr_err
));
chained.set_cause(py, Some(setattr_err));
return chained;
}
py_err
}
Expand All @@ -139,6 +179,9 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr {
None,
false,
None,
None,
None,
None,
) {
return setattr_err;
}
Expand Down
1 change: 1 addition & 0 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<session::Session>()?;
m.add_class::<statement::Statement>()?;
m.add_class::<statement::ExecutedStatement>()?;
m.add_class::<statement::StatementCanceller>()?;
m.add_class::<executed_async::ExecutedAsyncStatement>()?;
m.add_class::<metadata::Metadata>()?;
m.add_class::<result_stream::ResultStream>()?;
Expand Down
53 changes: 53 additions & 0 deletions pyo3/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,59 @@ macro_rules! run_kernel {
}};
}

/// Like [`run_kernel!`], but periodically re-acquires the GIL to poll
/// Python signal handlers so a long-running blocking call (e.g. a sync
/// `execute()`) can be interrupted by `KeyboardInterrupt` (Ctrl-C).
///
/// The bare `py.detach(|| block_on(fut))` form runs the future to
/// completion with the GIL released; the main thread is parked in the
/// FFI call, so a SIGINT-set Python signal flag isn't observed until
/// the call returns. This variant instead drives the future in ~100ms
/// slices: each slice runs with the GIL released, and on each timeout
/// the GIL is re-acquired to call [`Python::check_signals`], which
/// raises (e.g. `KeyboardInterrupt`) if a handler is pending. On
/// interrupt the future is dropped — which fires the kernel's
/// mid-execute cancel guard, so the server-side statement is cancelled
/// too, not just abandoned.
///
/// `$runtime` must be a `&tokio::runtime::Runtime` (so the future can
/// be driven across slices). Expands to a `PyResult<T>` (the future's
/// `Ok` value), mapping kernel `Error`s via `to_py_err` and surfacing
/// any signal `PyErr` directly.
#[macro_export]
macro_rules! run_kernel_interruptible {
($py:expr, $runtime:expr, $future:expr) => {{
let py = $py;
let runtime = $runtime;
// 100ms balances interrupt latency against per-tick overhead.
const TICK: ::std::time::Duration = ::std::time::Duration::from_millis(100);
let mut fut = ::std::boxed::Box::pin($future);
loop {
let step = py.detach(|| {
runtime.block_on(async {
match ::tokio::time::timeout(TICK, &mut fut).await {
Ok(done) => Some(done),
Err(_elapsed) => None,
}
})
});
match step {
// Future completed within this slice.
Some(result) => break result.map_err(|e| $crate::errors::to_py_err(py, e)),
// Slice timed out: poll Python signals. A pending
// handler (e.g. KeyboardInterrupt) returns Err, which
// we propagate — dropping `fut` fires the kernel's
// mid-execute cancel guard.
None => {
if let Err(signal_err) = py.check_signals() {
break Err(signal_err);
}
}
}
}
}};
}

/// Variant that accepts a block expression — useful when the future
/// is constructed inline from borrowed state that can't escape the
/// `detach` closure cleanly with the simpler form. Same shape, same
Expand Down
62 changes: 59 additions & 3 deletions pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use arrow_pyarrow::ToPyArrow;
use arrow_schema::Schema;
use databricks_sql_kernel::{
Error as KError, ExecutedStatement as KExecutedStatement, ExecutedStatementHandle,
Statement as KStatement,
Statement as KStatement, StatementCanceller as KStatementCanceller,
};
use pyo3::prelude::*;
use std::collections::HashMap;
Expand Down Expand Up @@ -186,17 +186,39 @@ impl Statement {
Ok(())
}

/// Produce a detached [`StatementCanceller`] for the statement
/// about to run (or running) on this `Statement`.
///
/// The sync `execute()` blocks and consumes the statement, so a
/// second thread can't reach an `ExecutedStatement` to cancel a
/// *running* query (the default PEP-249 `cursor.cancel()` shape).
/// Obtain a canceller **before** calling `execute()`; once the
/// server issues the statement id mid-execute, `canceller.cancel()`
/// reaches it. Cheap; safe to call from another thread.
fn canceller(&self) -> PyResult<StatementCanceller> {
let inner = alive!(self, "Statement");
Ok(StatementCanceller {
inner: inner.stmt.canceller(),
runtime: inner.runtime.clone(),
})
}

/// Wait-for-result execution. Blocks until the kernel finishes
/// polling and returns an `ExecutedStatement` with the result
/// stream ready to drain.
///
/// The blocking drive is interruptible: a `KeyboardInterrupt`
/// (Ctrl-C) raised while this is running aborts the query — the
/// in-flight future is dropped, firing the kernel's mid-execute
/// cancel guard so the server-side statement is cancelled too.
fn execute(&mut self, py: Python<'_>) -> PyResult<ExecutedStatement> {
let inner = alive_mut!(self, "Statement");
let runtime = inner.runtime.clone();
tracing::debug!(
target: crate::logging::PYO3_LOG_TARGET,
"Statement.execute: running statement synchronously (GIL released)"
"Statement.execute: running statement synchronously (GIL released, interruptible)"
);
let exec = run_kernel!(py, runtime, inner.stmt.execute())?;
let exec = run_kernel_interruptible!(py, &runtime, inner.stmt.execute())?;
Ok(ExecutedStatement::new(exec, runtime))
}

Expand Down Expand Up @@ -361,3 +383,37 @@ impl ExecutedStatement {
)
}
}

/// Detached canceller for the statement in flight on a [`Statement`].
///
/// Obtained from [`Statement::canceller`] *before* the blocking
/// `execute()` so a second Python thread can cancel a running sync
/// query — the PEP-249 `cursor.cancel()`-from-another-thread shape.
/// Holds no borrow on the `Statement`; safe to call concurrently with
/// the `execute()` it targets.
#[pyclass(name = "StatementCanceller")]
pub(crate) struct StatementCanceller {
inner: KStatementCanceller,
runtime: Arc<Runtime>,
}

#[pymethods]
impl StatementCanceller {
/// Server-side cancel of the in-flight statement.
///
/// No-op if nothing has executed yet, or the query is still in its
/// initial submit round-trip (no statement id observed). Idempotent
/// against a server already in a terminal state. Releases the GIL
/// while the cancel RPC is in flight.
fn cancel(&self, py: Python<'_>) -> PyResult<()> {
let runtime = self.runtime.clone();
run_kernel!(py, runtime, self.inner.cancel())?;
Ok(())
}

/// The server-issued statement id this canceller targets, if one
/// has been observed yet (`None` before the server issues it).
fn statement_id(&self) -> Option<String> {
self.inner.statement_id()
}
}
11 changes: 11 additions & 0 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,17 @@ impl SeaRestTransport {
.await?;
let statement_id = response.statement_id.clone();

// Publish the server statement id to the caller's canceller
// slot NOW — before polling — so a concurrent
// `StatementCanceller::cancel()` can target a still-running
// sync query. (The initial POST returns within the server
// wait_timeout, ~10s, even for a long query.)
if let Some(observer) = params.inflight_id_observer.as_ref() {
if let Ok(mut slot) = observer.lock() {
*slot = Some(statement_id.clone());
}
}

let response = match self.wait_for_completion(response).await {
Ok(r) => r,
Err(e) => {
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ pub use statement::executed_async::{
AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus,
};
pub use statement::handle::ExecutedStatementHandle;
pub use statement::mutable::Statement;
pub use statement::mutable::{Statement, StatementCanceller};
pub use statement::params_codec::parse_typed_value;
pub use statement::spec::{ResultFormat, StatementSpec, TypedValue};

Expand Down
2 changes: 1 addition & 1 deletion src/statement/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@ pub(crate) mod validity;
pub use executed::ExecutedStatement;
pub use executed_async::{AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus};
pub use handle::ExecutedStatementHandle;
pub use mutable::Statement;
pub use mutable::{Statement, StatementCanceller};
pub use spec::{ResultFormat, StatementSpec, TypedValue};
Loading
Loading