diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index f80d0401..a6a18804 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -18,6 +18,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed - The C ABI and shared telemetry runtime threads now block SIGPIPE. A TLS write after a peer reset no longer kills a host that doesn't ignore SIGPIPE, such as a Go program linking the C ABI; the write fails with `EPIPE` and the request reports the connection error instead. +- The Rust ADBC driver's own runtime threads now block SIGPIPE too, so a Go program loading the driver through a cgo driver manager isn't killed by a write after a peer reset. Caller-injected runtimes are unchanged. --- *Note: When making changes, please add your change under the appropriate diff --git a/adbc/src/runtime.rs b/adbc/src/runtime.rs index f8f579c5..75b2abe1 100644 --- a/adbc/src/runtime.rs +++ b/adbc/src/runtime.rs @@ -37,6 +37,7 @@ impl RuntimeHandle { tokio::runtime::Builder::new_multi_thread() .worker_threads(DEFAULT_WORKER_THREADS) .enable_all() + .on_thread_start(databricks_sql_kernel::block_sigpipe_on_current_thread) .build() .map(|runtime| Arc::new(Self::Owned(Some(runtime)))) } @@ -164,6 +165,32 @@ mod tests { caller.block_on(async { drop(RuntimeHandle::create().unwrap()) }); } + /// Whether SIGPIPE (13 on Linux) is in the calling thread's `SigBlk` mask. + #[cfg(target_os = "linux")] + fn sigpipe_blocked() -> bool { + let path = "/proc/thread-self/status"; + let status = std::fs::read_to_string(path).unwrap(); + let mask = status + .lines() + .find_map(|line| line.strip_prefix("SigBlk:")) + .unwrap(); + let mask = u64::from_str_radix(mask.trim(), 16).unwrap(); + (mask & (1 << (13 - 1))) != 0 + } + + #[cfg(target_os = "linux")] + #[test] + fn owned_runtime_threads_block_sigpipe() { + assert!(!sigpipe_blocked(), "caller already blocks SIGPIPE"); + let runtime = RuntimeHandle::create().unwrap(); + let worker = runtime.spawn(async { sigpipe_blocked() }); + let blocking = runtime.spawn_blocking(sigpipe_blocked); + let on_worker = runtime.block_on(worker).unwrap(); + let on_blocking = runtime.block_on(blocking).unwrap(); + assert!(on_worker, "runtime worker must block SIGPIPE"); + assert!(on_blocking, "blocking-pool thread must block SIGPIPE"); + } + #[test] fn injected_runtime_is_not_shut_down_by_handle() { let runtime = Arc::new(private_runtime()); diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..818315f1 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -19,6 +19,8 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Fixed +- Session runtime threads now block SIGPIPE. A TLS write after a peer reset no longer kills a Python process that restored the default action (`signal.signal(signal.SIGPIPE, signal.SIG_DFL)`); the write fails with `EPIPE` instead. + --- *Note: When making changes, please add your change under the appropriate section with a brief description. At release time, move the entries here diff --git a/pyo3/src/runtime.rs b/pyo3/src/runtime.rs index a443b7c2..24744997 100644 --- a/pyo3/src/runtime.rs +++ b/pyo3/src/runtime.rs @@ -43,6 +43,22 @@ impl KernelRuntime { Self(Some(runtime)) } + /// Builds a session's runtime. Multi-thread so CloudFetch chunk downloads + /// can overlap with the main poll loop; worker count is tokio's default. + pub(crate) fn build() -> PyResult { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_name("dbx-sql-kernel") + .on_thread_start(databricks_sql_kernel::block_sigpipe_on_current_thread) + .build() + .map(Self::new) + .map_err(|e| { + pyo3::exceptions::PyRuntimeError::new_err(format!( + "failed to build tokio runtime: {e}" + )) + }) + } + /// Release a handle at the end of an explicit `close()`. If it was the /// last one, shut down and wait for the workers with the GIL released, /// so none is still logging into Python after `close()` returns. @@ -115,6 +131,32 @@ mod tests { .unwrap_or_else(|_| panic!("{what} deadlocked on a GIL-blocked worker")) } + /// Whether SIGPIPE (13 on Linux) is in the calling thread's `SigBlk` mask. + #[cfg(target_os = "linux")] + fn sigpipe_blocked() -> bool { + let path = "/proc/thread-self/status"; + let status = std::fs::read_to_string(path).unwrap(); + let mask = status + .lines() + .find_map(|line| line.strip_prefix("SigBlk:")) + .unwrap(); + let mask = u64::from_str_radix(mask.trim(), 16).unwrap(); + (mask & (1 << (13 - 1))) != 0 + } + + #[cfg(target_os = "linux")] + #[test] + fn session_runtime_threads_block_sigpipe() { + assert!(!sigpipe_blocked(), "caller already blocks SIGPIPE"); + let runtime = KernelRuntime::build().expect("build runtime"); + let worker = runtime.spawn(async { sigpipe_blocked() }); + let blocking = runtime.spawn_blocking(sigpipe_blocked); + let on_worker = runtime.block_on(worker).unwrap(); + let on_blocking = runtime.block_on(blocking).unwrap(); + assert!(on_worker, "runtime worker must block SIGPIPE"); + assert!(on_blocking, "blocking-pool thread must block SIGPIPE"); + } + #[test] fn drop_with_gil_held_does_not_wait_for_gil_blocked_worker() { run_attached( diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..1e773f4a 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -29,7 +29,6 @@ use databricks_sql_kernel::{GeospatialResultRepresentation, Session as KSession} use pyo3::prelude::*; use std::collections::HashMap; use std::sync::Arc; -use tokio::runtime::Builder; /// Python-facing session handle. /// @@ -603,20 +602,8 @@ impl Session { None }; - // One tokio runtime per session. Multi-thread so CloudFetch - // chunk downloads can overlap with the main poll loop. Worker - // count left to tokio's default (logical CPU count). - let runtime = Arc::new(KernelRuntime::new( - Builder::new_multi_thread() - .enable_all() - .thread_name("dbx-sql-kernel") - .build() - .map_err(|e| { - pyo3::exceptions::PyRuntimeError::new_err(format!( - "failed to build tokio runtime: {e}" - )) - })?, - )); + // One tokio runtime per session. + let runtime = Arc::new(KernelRuntime::build()?); // `Session::open` is async and grabs the current tokio handle. // Drive it on the runtime; the macro detaches the GIL for the diff --git a/src/lib.rs b/src/lib.rs index 00340e94..9b5ebb50 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -157,6 +157,10 @@ pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; pub use statement::{MAX_CLIENT_QUERY_TIMEOUT, MAX_CLIENT_QUERY_TIMEOUT_MS}; pub use telemetry::DriverSystemConfiguration; +/// `on_thread_start` hook that blocks SIGPIPE on runtime threads the ADBC and +/// pyo3 crates own. Not a supported API. +#[doc(hidden)] +pub use util::runtime::block_sigpipe_on_current_thread; // === Compile-time guarantees on auto-traits === // diff --git a/src/util/runtime.rs b/src/util/runtime.rs index e37fd31f..d42438b3 100644 --- a/src/util/runtime.rs +++ b/src/util/runtime.rs @@ -149,11 +149,12 @@ pub(crate) fn ambient_rust_min_stack() -> Option { .and_then(|v| v.parse::().ok()) } -/// `on_thread_start` hook for kernel-owned runtimes. std's `write_vectored` is a plain -/// `writev`, so a write after a peer reset raises SIGPIPE on this thread, and non-Rust hosts -/// that don't ignore it (Go) die. Only kernel threads change; the write still fails with EPIPE. +/// `on_thread_start` hook for kernel-owned runtimes, including the ADBC and pyo3 ones through +/// the crate-root re-export. std's `write_vectored` is a plain `writev`, so a write after a peer +/// reset raises SIGPIPE on this thread, and non-Rust hosts that don't ignore it (Go) die. Only +/// kernel threads change; the write still fails with EPIPE. #[cfg(unix)] -pub(crate) fn block_sigpipe_on_current_thread() { +pub fn block_sigpipe_on_current_thread() { // SAFETY: initialises a stack-local `sigset_t` and changes only this thread's mask. unsafe { let mut set: libc::sigset_t = std::mem::zeroed(); @@ -165,7 +166,7 @@ pub(crate) fn block_sigpipe_on_current_thread() { /// Windows has no SIGPIPE. #[cfg(not(unix))] -pub(crate) fn block_sigpipe_on_current_thread() {} +pub fn block_sigpipe_on_current_thread() {} /// Whether SIGPIPE is in the calling thread's `SigBlk` mask. #[cfg(all(test, target_os = "linux"))]