Skip to content
Draft
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
1 change: 1 addition & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions adbc/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))))
}
Expand Down Expand Up @@ -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());
Expand Down
2 changes: 2 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions pyo3/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self> {
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.
Expand Down Expand Up @@ -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(
Expand Down
17 changes: 2 additions & 15 deletions pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 ===
//
Expand Down
11 changes: 6 additions & 5 deletions src/util/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,12 @@ pub(crate) fn ambient_rust_min_stack() -> Option<usize> {
.and_then(|v| v.parse::<usize>().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();
Expand All @@ -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"))]
Expand Down
Loading