From ecd5a600e07754078a59ad46a276f89055423803 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 26 Nov 2026 21:49:34 +0000 Subject: [PATCH 1/3] fix: block SIGPIPE on kernel runtime threads std's TcpStream::write passes MSG_NOSIGNAL, but write_vectored is a plain writev, and rustls/hyper write TLS records through it. After a peer reset, the close_notify that hyper writes on connection shutdown raises SIGPIPE on a kernel runtime thread. Rust executables ignore SIGPIPE at startup, but a Go host sends a SIGPIPE raised on a non-Go thread to the default handler, so the process dies. Block SIGPIPE with on_thread_start on the C-ABI runtime and the shared telemetry runtime. The hook covers their workers and blocking pools. The write then fails with EPIPE, and the process-wide disposition is unchanged. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- Cargo.lock | 1 + Cargo.toml | 5 +++++ NEXT_CHANGELOG.md | 2 ++ adbc/Cargo.lock | 1 + napi/Cargo.lock | 1 + pyo3/Cargo.lock | 1 + src/c_abi/mod.rs | 12 +++++++++++- src/telemetry/client.rs | 12 +++++++++++- src/util/runtime.rs | 43 +++++++++++++++++++++++++++++++++++++++++ 9 files changed, 76 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d4992a7f..c4fa1986 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -664,6 +664,7 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", + "libc", "log", "lz4_flex", "moka", diff --git a/Cargo.toml b/Cargo.toml index 5a53e72c..66898c45 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -159,6 +159,11 @@ zeroize = "1.9" jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] } # JWT signing (RS256/384/512, PS256/384/512, ES256/384); use_pem = PEM key loading (adds pem + simple_asn1, no TLS) pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption +# `pthread_sigmask` for kernel-owned runtime threads (`src/util/runtime.rs`). +# Already in the graph through tokio, so no new crate is added. +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] } wiremock = "0.6" diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..f80d0401 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -17,6 +17,8 @@ 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. + --- *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/adbc/Cargo.lock b/adbc/Cargo.lock index dcaa4b65..fa0db928 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -666,6 +666,7 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", + "libc", "lz4_flex", "moka", "native-tls", diff --git a/napi/Cargo.lock b/napi/Cargo.lock index b3b4c36e..9446836c 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -625,6 +625,7 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", + "libc", "lz4_flex", "moka", "oauth2", diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index fa59876f..2faffe7c 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -621,6 +621,7 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", + "libc", "lz4_flex", "moka", "oauth2", diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index e4800480..9f6fc839 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -84,7 +84,9 @@ static RUNTIME: OnceLock = OnceLock::new(); // The kernel-owned worker stack floor lives in `crate::util::runtime` as a // single source of truth shared with the telemetry runtime; see that module // for the floor-not-cap semantics and the #326 / #328 history. -use crate::util::runtime::{ambient_rust_min_stack, runtime_thread_stack_size}; +use crate::util::runtime::{ + ambient_rust_min_stack, block_sigpipe_on_current_thread, runtime_thread_stack_size, +}; /// Fetch (initialising on first use) the process-wide C-ABI runtime. /// @@ -107,6 +109,7 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime:: .enable_all() .thread_name("kernel-c-abi") .thread_stack_size(runtime_thread_stack_size(ambient_rust_min_stack())) + .on_thread_start(block_sigpipe_on_current_thread) .build() .map_err(|e| { crate::kernel_error::Error::internal() @@ -557,4 +560,11 @@ mod tests { caller thread — see #276", ); } + + #[cfg(target_os = "linux")] + #[test] + fn c_abi_runtime_threads_block_sigpipe() { + let rt = runtime().expect("C-ABI runtime"); + crate::util::runtime::assert_runtime_threads_block_sigpipe(rt.handle()); + } } diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs index e86e5b1b..773a2eb0 100644 --- a/src/telemetry/client.rs +++ b/src/telemetry/client.rs @@ -191,7 +191,9 @@ impl TelemetryClient { // abort the process. The worker stack floor is shared with the C-ABI runtime // via `crate::util::runtime` (single source of truth); see that module for the // floor-not-cap semantics and the #326 / #328 history. -use crate::util::runtime::{ambient_rust_min_stack, runtime_thread_stack_size}; +use crate::util::runtime::{ + ambient_rust_min_stack, block_sigpipe_on_current_thread, runtime_thread_stack_size, +}; fn telemetry_runtime_handle() -> std::io::Result { // A host client can outlive the session that created it. Keep its timer, @@ -210,6 +212,7 @@ fn telemetry_runtime_handle() -> std::io::Result { .worker_threads(1) .thread_name("dbx-sql-telemetry") .thread_stack_size(runtime_thread_stack_size(ambient_rust_min_stack())) + .on_thread_start(block_sigpipe_on_current_thread) .enable_all() .build()?; let handle = built.handle().clone(); @@ -227,6 +230,13 @@ mod tests { // The pure floor-not-cap resolution (#326 / #328) is exercised once over // the shared helper in `crate::util::runtime`. + #[cfg(target_os = "linux")] + #[test] + fn telemetry_runtime_threads_block_sigpipe() { + let handle = telemetry_runtime_handle().expect("telemetry runtime"); + crate::util::runtime::assert_runtime_threads_block_sigpipe(&handle); + } + #[tokio::test] async fn batch_size_triggers_background_flush() { let exporter = CapturingTelemetryExporter::default(); diff --git a/src/util/runtime.rs b/src/util/runtime.rs index 82d0ec50..e37fd31f 100644 --- a/src/util/runtime.rs +++ b/src/util/runtime.rs @@ -149,6 +149,49 @@ 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. +#[cfg(unix)] +pub(crate) 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(); + libc::sigemptyset(&mut set); + libc::sigaddset(&mut set, libc::SIGPIPE); + libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut()); + } +} + +/// Windows has no SIGPIPE. +#[cfg(not(unix))] +pub(crate) fn block_sigpipe_on_current_thread() {} + +/// Whether SIGPIPE is in the calling thread's `SigBlk` mask. +#[cfg(all(test, 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(|l| l.strip_prefix("SigBlk:")) + .unwrap(); + let mask = u64::from_str_radix(mask.trim(), 16).unwrap(); + (mask & (1u64 << (libc::SIGPIPE - 1))) != 0 +} + +/// Asserts that a worker and a blocking-pool thread of `handle` block SIGPIPE. +#[cfg(all(test, target_os = "linux"))] +pub(crate) fn assert_runtime_threads_block_sigpipe(handle: &tokio::runtime::Handle) { + assert!(!sigpipe_blocked(), "caller already blocks SIGPIPE"); + let worker = handle.spawn(async { sigpipe_blocked() }); + let blocking = handle.spawn_blocking(sigpipe_blocked); + let on_worker = futures::executor::block_on(worker).unwrap(); + let on_blocking = futures::executor::block_on(blocking).unwrap(); + assert!(on_worker, "runtime worker must block SIGPIPE"); + assert!(on_blocking, "blocking-pool thread must block SIGPIPE"); +} + #[cfg(test)] mod tests { use super::*; From a5c94bc839ed89538e860ee23ac35b2016d5c82d Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 26 Nov 2026 23:10:03 +0000 Subject: [PATCH 2/3] test: check a write after peer reset on a C-ABI worker returns EPIPE A re-exec child sets SIGPIPE to its default action, reads ECONNRESET from a peer that closed with a zero linger, then writes with writev on a C-ABI worker. It asserts EPIPE, and the parent asserts the child was not killed by SIGPIPE. The log callback contract (Rust doc and C header) now says kernel threads run with SIGPIPE blocked and callbacks must not unblock it. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- include/databricks_kernel.h | 3 +- src/c_abi/mod.rs | 65 ++++++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..592a4527 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -404,7 +404,8 @@ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); * that kernel operation. Hosts that need asynchronous logging can copy the * record into their own bounded queue and return. Strings are valid only during * the callback. Calls may be concurrent; copy retained strings and synchronize - * the destination. `user_data` is the pointer supplied at initialization. */ + * the destination. `user_data` is the pointer supplied at initialization. + * Kernel threads run with SIGPIPE blocked; callbacks must not unblock it. */ typedef void (*KernelLogCallback)(const char* level, const char* target, const char* message, void* user_data); diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 9f6fc839..45c2f081 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -62,7 +62,8 @@ use std::sync::OnceLock; /// synchronous on the emitting thread, and callbacks may run concurrently on /// multiple kernel threads. Consumers must return promptly, copy any strings /// they retain, and synchronize their sink. A consumer that needs asynchronous -/// delivery can enqueue its own owned record before returning. +/// delivery can enqueue its own owned record before returning. Kernel threads +/// run with SIGPIPE blocked, and callbacks must not unblock it. pub type KernelLogCallback = unsafe extern "C" fn( level: *const c_char, target: *const c_char, @@ -567,4 +568,66 @@ mod tests { let rt = runtime().expect("C-ABI runtime"); crate::util::runtime::assert_runtime_threads_block_sigpipe(rt.handle()); } + + #[cfg(target_os = "linux")] + const SIGPIPE_CHILD: &str = "DATABRICKS_KERNEL_SIGPIPE_CHILD"; + + /// With SIGPIPE at its default action, as in a Go host, a write after a peer + /// reset on a C-ABI worker must fail with EPIPE instead of killing the process. + #[cfg(target_os = "linux")] + #[test] + fn c_abi_write_after_peer_reset_returns_epipe() { + let output = std::process::Command::new(std::env::current_exe().expect("test executable")) + .args([ + "--exact", + "c_abi::tests::c_abi_write_after_peer_reset_child", + "--nocapture", + ]) + .env(SIGPIPE_CHILD, "1") + .output() + .expect("launch SIGPIPE subprocess"); + + assert!( + output.status.success(), + "write after peer reset failed (status {}):\nstdout:\n{}\nstderr:\n{}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + } + + #[cfg(target_os = "linux")] + #[test] + fn c_abi_write_after_peer_reset_child() { + if std::env::var_os(SIGPIPE_CHILD).is_none() { + return; + } + // SAFETY: sets the process-wide default action; no handler is involved. + unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) }; + let kind = block_on_ffi(write_after_peer_reset).expect("C-ABI probe"); + assert_eq!(kind, std::io::ErrorKind::BrokenPipe); + } + + /// Reads ECONNRESET from a peer that reset the connection, then writes with + /// `write_vectored` (a plain `writev`) and returns the write's error kind. + #[cfg(target_os = "linux")] + #[allow(deprecated)] // `set_linger`: a zero linger resets on close without blocking + async fn write_after_peer_reset() -> crate::kernel_error::Result { + use std::time::Duration; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let mut client = TcpStream::connect(addr).await.unwrap(); + let (peer, _) = listener.accept().await.unwrap(); + peer.set_linger(Some(Duration::ZERO)).unwrap(); + drop(peer); + + let read = client.read(&mut [0u8; 1]).await.unwrap_err(); + assert_eq!(read.kind(), std::io::ErrorKind::ConnectionReset); + let bufs = [std::io::IoSlice::new(b"x")]; + let write = client.write_vectored(&bufs).await.unwrap_err(); + Ok(write.kind()) + } } From 2fd0635fdde7787ba4215a7ecfa0595b028f2a6e Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 26 Nov 2026 23:51:16 +0000 Subject: [PATCH 3/3] test: require the SIGPIPE child test to actually run The parent now also checks the child's libtest summary for "1 passed", so a filter that matches nothing can't pass silently. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/c_abi/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 45c2f081..70d52518 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -587,11 +587,13 @@ mod tests { .output() .expect("launch SIGPIPE subprocess"); + // "1 passed" guards against the filter matching nothing. + let stdout = String::from_utf8_lossy(&output.stdout); assert!( - output.status.success(), + output.status.success() && stdout.contains("1 passed"), "write after peer reset failed (status {}):\nstdout:\n{}\nstderr:\n{}", output.status, - String::from_utf8_lossy(&output.stdout), + stdout, String::from_utf8_lossy(&output.stderr), ); }