From eb5555414ebf1d6e55782eb05d4ec606808b7280 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Thu, 16 Jul 2026 08:05:55 +0000 Subject: [PATCH 01/15] feat(c-abi): cooperative cancel token for blocking calls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add kernel_cancel_token_t plus cancellable variants of the connect and result-fetch entry points, so a C-ABI host can interrupt an otherwise uninterruptible blocking call by a caller deadline: - kernel_session_open_cancellable - kernel_result_stream_next_batch_cancellable block_on_ffi_cancellable races the operation future against the token via a biased tokio::select!; a fire drops the in-flight future, aborting the underlying reqwest request (the crate's documented cancellation model), and yields a typed Cancelled. A NULL token routes to the identical plain-path behavior, so the default path and existing symbols are byte-for-byte unchanged. Token firing is purely local (no RPC), safe to call from another thread — modeled on the existing statement canceller. tokio_util's CancellationToken is already a crate dependency, so no new cargo-deny entry. Additive only — no existing symbol's layout or meaning changes, ABI unchanged. Tests: cancel unit tests (incl. the is_cancelled accessor), wiremock integration tests proving a mid-connect cancel returns Cancelled in under 5s against a 10s stalled server (plus NULL-token parity and pre-fired short-circuit), and C-smoke lifecycle + pre-fired short-circuit. make check green. Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- NEXT_CHANGELOG.md | 10 + include/databricks_kernel.h | 65 ++++ src/c_abi/cancel.rs | 245 ++++++++++++++ src/c_abi/mod.rs | 96 ++++++ src/c_abi/result.rs | 59 +++- src/c_abi/session.rs | 63 +++- tests/c/session_smoke.c | 72 +++++ tests/v0_c_abi_cancel_token_wiremock.rs | 404 ++++++++++++++++++++++++ 8 files changed, 1001 insertions(+), 13 deletions(-) create mode 100644 src/c_abi/cancel.rs create mode 100644 tests/v0_c_abi_cancel_token_wiremock.rs diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 28a2d4ab..c18d95f8 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,16 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Cooperative cancel token for the blocking C-ABI entry points + (`kernel_cancel_token_new` / `_cancel` / `_is_cancelled` / `_free`), plus + cancellable variants `kernel_session_open_cancellable` and + `kernel_result_stream_next_batch_cancellable`. A host creates a token before a + blocking call, passes it in, and fires it from another thread when its + deadline elapses; the call drops its in-flight request future (a real + `reqwest` abort) and returns `Cancelled`. A null token is byte-for-byte the + plain path, so existing symbols and the default path are unchanged. Additive + only — ABI unchanged. + ### Updated ### Fixed diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index cf42e4e6..644416cf 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -213,6 +213,15 @@ typedef struct kernel_result_stream_t kernel_result_stream_t; * cancels the LATER query. Use one per execute (new before execute, free after * it returns). */ typedef struct kernel_statement_canceller_t kernel_statement_canceller_t; +/* Cooperative cancel token for the blocking `*_cancellable` entry points + * (kernel_session_open_cancellable, kernel_result_stream_next_batch_cancellable). + * Create one before a blocking call, pass it in, and fire it from ANOTHER + * thread (kernel_cancel_token_cancel) when the caller's deadline elapses; the + * blocked call then drops its in-flight request future and returns + * KernelStatusCode_Cancelled. One-shot (a fired token stays fired) — create a + * fresh token per logical operation. Firing is purely local (no RPC), so it + * never blocks. See "Cooperative cancellation" below. */ +typedef struct kernel_cancel_token_t kernel_cancel_token_t; /* ─── Session config ────────────────────────────────────────────────── * @@ -313,6 +322,21 @@ KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(Kernel KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session_t** out); KernelStatusCode kernel_session_close(kernel_session_t* session); +/* + * Like kernel_session_open, but races the (blocking) connect against + * `cancel_token` so a host can bound a slow warehouse cold-start or a + * connect-time network partition by its own deadline. A NULL `cancel_token` + * behaves EXACTLY like kernel_session_open. If the token fires (or is already + * fired) before connect completes, the connect future is dropped — aborting + * the in-flight request — and this returns KernelStatusCode_Cancelled; `config` + * is CONSUMED on every path regardless. `cancel_token` is borrowed, not + * consumed: the caller still owns and must free it after this returns, and may + * fire it from another thread while this call is in flight. + */ +KernelStatusCode kernel_session_open_cancellable(KernelSessionConfig* config, + kernel_session_t** out, + const kernel_cancel_token_t* cancel_token); + /* Report whether a session is still OPEN (its delete has not been * initiated). Writes true/false to `*out`. LOCAL check only — no server * round-trip, so it does NOT detect a server idle-timeout or dropped @@ -476,6 +500,32 @@ KernelStatusCode kernel_statement_canceller_cancel( KernelStatusCode kernel_statement_canceller_free( kernel_statement_canceller_t* canceller); +/* ─── Cooperative cancellation (blocking-call cancel token) ──────────── + * + * The statement canceller above cancels a server-side STATEMENT (right for a + * query still executing). A cancel token cancels a blocking C-ABI CALL itself — + * connect or a stalled result-stream fetch — neither of which the statement + * canceller reaches (the server statement is already done; the stall is + * client-side). It is the generic mechanism a host uses to honour a caller + * deadline / context on the `*_cancellable` entry points. + * + * Usage: create a token, spawn a watcher on the caller's deadline/context, make + * the blocking `*_cancellable` call on the owning thread, and from the watcher + * fire kernel_cancel_token_cancel when the deadline elapses. The blocked call + * drops its in-flight request future and returns KernelStatusCode_Cancelled. + * Firing is purely local (flip an atomic, wake the waiter) — no RPC, never + * blocks. The token is ONE-SHOT (a fired token stays fired), so create a fresh + * one per logical operation. Safe to fire from a different thread than the + * blocking call (that is the intended use); do NOT free the token until both + * the blocking call and any in-flight cancel have returned. + */ +KernelStatusCode kernel_cancel_token_new(kernel_cancel_token_t** out); +KernelStatusCode kernel_cancel_token_cancel(kernel_cancel_token_t* token); +/* Report whether the token has been fired (writes true/false to *out). Local + * atomic read — no RPC, never blocks. Symmetric with kernel_session_is_open. */ +KernelStatusCode kernel_cancel_token_is_cancelled(const kernel_cancel_token_t* token, bool* out); +KernelStatusCode kernel_cancel_token_free(kernel_cancel_token_t* token); + /* ─── Executed statement (sync) ───────────────────────────────────────*/ /* @@ -523,6 +573,21 @@ KernelStatusCode kernel_result_stream_get_schema(kernel_result_stream_t* stream, KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, struct ArrowArray* out_array, struct ArrowSchema* out_schema); +/* + * Like kernel_result_stream_next_batch, but races the (blocking) fetch against + * `cancel_token` so a host can interrupt a HUNG CloudFetch chunk (a wedged S3 / + * pre-signed-URL GET) instead of blocking on it forever. A NULL `cancel_token` + * behaves EXACTLY like kernel_result_stream_next_batch. If the token fires + * before the batch is ready, the fetch future is dropped (aborting the in-flight + * download) and this returns KernelStatusCode_Cancelled; the stream handle stays + * valid and owned by the caller (close it with kernel_result_stream_close as + * usual — a cancelled fetch neither consumes nor frees it). `cancel_token` is + * borrowed and safe to fire from another thread while this call is in flight + * (see kernel_session_open_cancellable). + */ +KernelStatusCode kernel_result_stream_next_batch_cancellable( + kernel_result_stream_t* stream, struct ArrowArray* out_array, + struct ArrowSchema* out_schema, const kernel_cancel_token_t* cancel_token); KernelStatusCode kernel_result_stream_close(kernel_result_stream_t* stream); /* ─── Metadata ──────────────────────────────────────────────────────── diff --git a/src/c_abi/cancel.rs b/src/c_abi/cancel.rs new file mode 100644 index 00000000..83f1f28a --- /dev/null +++ b/src/c_abi/cancel.rs @@ -0,0 +1,245 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Generic cooperative cancel token for the blocking C-ABI entry points. +//! +//! The v0 C ABI drives every async operation through +//! [`block_on_ffi`](crate::c_abi::block_on_ffi), which blocks the calling +//! (native) thread until the future completes. That thread cannot observe a +//! host-side deadline/cancel (a Go `context.Context`, an ODBC `SQLCancel`) +//! mid-call, so a hung connect or a hung result-stream fetch blocks the caller +//! past its deadline — the runtime-contract gap the host drivers track as +//! mid-fetch (hung CloudFetch chunk) and session-connect deadlines. +//! +//! This module adds one primitive that closes both: a [`kernel_cancel_token_t`] +//! the host creates before a blocking call, passes into a `*_cancellable` +//! variant of that call, and fires from *another* thread when its deadline +//! elapses. The cancellable entry point runs its future under +//! [`block_on_ffi_cancellable`](crate::c_abi::block_on_ffi_cancellable), which +//! races the future against the token and — on a fire — **drops the future**. +//! Because the kernel's HTTP client is `reqwest` and its futures cancel by +//! being dropped (the crate-wide model; see the CloudFetch streaming provider's +//! own [`CancellationToken`] use), dropping the future genuinely aborts the +//! in-flight request rather than merely stopping the wait. +//! +//! The token wraps [`tokio_util::sync::CancellationToken`], which is cheap to +//! clone (an `Arc` internally) and safe to fire from any thread — the same +//! shape as the statement canceller ([`kernel_statement_canceller_t`]), and for +//! the same reason (the blocking call runs on one thread, the cancel on +//! another). Unlike the statement canceller, firing is purely local (flip an +//! atomic + wake waiters); it dispatches no RPC, so it never blocks. +//! +//! One token drives at most one in-flight call at a time. Reuse across +//! sequential calls is allowed, but a token that has already been fired stays +//! fired (a `CancellationToken` is one-shot), so create a fresh token per +//! logical operation — exactly as a Go caller creates a fresh watcher per +//! `ctx`. +//! +//! [`kernel_statement_canceller_t`]: crate::c_abi::statement::kernel_statement_canceller_t +//! [`CancellationToken`]: tokio_util::sync::CancellationToken + +#![allow(non_camel_case_types)] + +use super::error::store_invalid_arg; +use super::{catch_ffi, KernelStatusCode}; +use tokio_util::sync::CancellationToken; + +/// Opaque cancel-token handle. Boxes a [`CancellationToken`] the host fires +/// from a watcher thread to interrupt a blocking `*_cancellable` C-ABI call. +#[repr(C)] +pub struct kernel_cancel_token_t { + _private: [u8; 0], +} + +/// Owned box behind a [`kernel_cancel_token_t`]. +struct CancelTokenHandle { + token: CancellationToken, +} + +/// Crate-internal: borrow the [`CancellationToken`] out of a raw handle, or +/// `None` when the handle pointer is null. The returned reference is only used +/// to `clone()` the token (a cheap `Arc` bump) into the future's `select!`, so +/// the caller keeps ownership of the box and may still fire it concurrently. +/// +/// # Safety +/// `token` must be null or a live handle from [`kernel_cancel_token_new`]. +pub(crate) unsafe fn token_ref<'a>( + token: *const kernel_cancel_token_t, +) -> Option<&'a CancellationToken> { + (token as *const CancelTokenHandle) + .as_ref() + .map(|h| &h.token) +} + +/// Create a fresh, un-fired cancel token. On success `*out` holds an owned +/// handle the caller releases with [`kernel_cancel_token_free`], and may fire +/// with [`kernel_cancel_token_cancel`] from any thread. +/// +/// # Safety +/// `out` must be a valid, writable pointer to a `kernel_cancel_token_t*`. +#[no_mangle] +pub unsafe extern "C" fn kernel_cancel_token_new( + out: *mut *mut kernel_cancel_token_t, +) -> KernelStatusCode { + catch_ffi(|| { + if out.is_null() { + return store_invalid_arg("kernel_cancel_token_new: out must not be null"); + } + let handle = CancelTokenHandle { + token: CancellationToken::new(), + }; + std::ptr::write( + out, + Box::into_raw(Box::new(handle)) as *mut kernel_cancel_token_t, + ); + KernelStatusCode::Success + }) +} + +/// Fire the token, requesting cancellation of whatever blocking +/// `*_cancellable` call it was passed to. Idempotent (a `CancellationToken` is +/// one-shot; a second fire is a no-op) and safe to call concurrently with the +/// blocking call the token drives — that is the whole point: the blocking call +/// runs on one thread and this fires from another. +/// +/// Purely local: flips the token's atomic and wakes the `select!` waiting on +/// it. Dispatches no RPC, so it never blocks and never fails on a live handle. +/// +/// # Safety +/// `token` must be a live handle from [`kernel_cancel_token_new`], not yet +/// freed. It is safe to call while a `*_cancellable` call driven by this token +/// is in flight; do not [`kernel_cancel_token_free`] the handle until both this +/// call and that blocking call have returned. +#[no_mangle] +pub unsafe extern "C" fn kernel_cancel_token_cancel( + token: *mut kernel_cancel_token_t, +) -> KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (token as *const CancelTokenHandle).as_ref() else { + return store_invalid_arg("kernel_cancel_token_cancel: token must not be null"); + }; + handle.token.cancel(); + KernelStatusCode::Success + }) +} + +/// Report whether the token has been fired, writing `true`/`false` to `*out`. +/// A local read of the token's atomic — no RPC, never blocks. Symmetric with +/// [`kernel_session_is_open`](crate::c_abi::session::kernel_session_is_open); +/// lets a host (or its tests) observe the token state it set. Does not borrow +/// ownership; the caller still owns `token`. +/// +/// # Safety +/// `token` must be a live handle from [`kernel_cancel_token_new`], not yet +/// freed; `out` must be a writable `bool*`. +#[no_mangle] +pub unsafe extern "C" fn kernel_cancel_token_is_cancelled( + token: *const kernel_cancel_token_t, + out: *mut bool, +) -> KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (token as *const CancelTokenHandle).as_ref() else { + return store_invalid_arg("kernel_cancel_token_is_cancelled: token must not be null"); + }; + if out.is_null() { + return store_invalid_arg("kernel_cancel_token_is_cancelled: out must not be null"); + } + std::ptr::write(out, handle.token.is_cancelled()); + KernelStatusCode::Success + }) +} + +/// Free a cancel-token handle. Does not touch any call the token drove. +/// +/// # Safety +/// `token` must have been returned by [`kernel_cancel_token_new`] and not +/// previously freed. The token is single-owner for teardown: no other thread +/// may be inside [`kernel_cancel_token_cancel`] on this handle, and no +/// `*_cancellable` call driven by it may be in flight, when it is freed. +#[no_mangle] +pub unsafe extern "C" fn kernel_cancel_token_free( + token: *mut kernel_cancel_token_t, +) -> KernelStatusCode { + catch_ffi(|| { + if token.is_null() { + return store_invalid_arg("kernel_cancel_token_free: token must not be null"); + } + drop(Box::from_raw(token as *mut CancelTokenHandle)); + KernelStatusCode::Success + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// new → cancel → free round-trips, and the borrowed token reflects the + /// fire (the property the cancellable entry points rely on). + #[test] + fn new_cancel_free_round_trip() { + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + let rc = unsafe { kernel_cancel_token_new(&mut tok) }; + assert_eq!(rc, KernelStatusCode::Success); + assert!(!tok.is_null()); + + // Not fired yet — observe via both the borrow and the C accessor. + let borrowed = unsafe { token_ref(tok) }.expect("live token"); + assert!(!borrowed.is_cancelled()); + let mut fired = true; + assert_eq!( + unsafe { kernel_cancel_token_is_cancelled(tok, &mut fired) }, + KernelStatusCode::Success + ); + assert!(!fired, "is_cancelled reports false before a fire"); + + // Fire it, then observe the flip through the borrow AND the accessor. + let rc = unsafe { kernel_cancel_token_cancel(tok) }; + assert_eq!(rc, KernelStatusCode::Success); + assert!(borrowed.is_cancelled(), "cancel() must flip the token"); + assert_eq!( + unsafe { kernel_cancel_token_is_cancelled(tok, &mut fired) }, + KernelStatusCode::Success + ); + assert!(fired, "is_cancelled reports true after a fire"); + + // Second fire is a no-op (one-shot), still Success. + let rc = unsafe { kernel_cancel_token_cancel(tok) }; + assert_eq!(rc, KernelStatusCode::Success); + + let rc = unsafe { kernel_cancel_token_free(tok) }; + assert_eq!(rc, KernelStatusCode::Success); + } + + /// Null-pointer guards on every entry point return `InvalidArgument`, + /// never crash. + #[test] + fn null_guards_return_invalid_argument() { + let rc = unsafe { kernel_cancel_token_new(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + let rc = unsafe { kernel_cancel_token_cancel(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + let mut fired = false; + let rc = unsafe { kernel_cancel_token_is_cancelled(std::ptr::null(), &mut fired) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + let rc = unsafe { kernel_cancel_token_free(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + } + + /// `token_ref` on a null handle yields `None` (used by the cancellable + /// entry points to treat a null token as "no cancellation"). + #[test] + fn token_ref_null_is_none() { + assert!(unsafe { token_ref(std::ptr::null()) }.is_none()); + } +} diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index bdb54a4c..470ba0c6 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -45,6 +45,7 @@ // module-wide allow that masked them in the skeleton phase is gone now // that bodies have landed. +pub mod cancel; pub mod error; pub mod metadata; pub mod result; @@ -158,6 +159,101 @@ where } } +/// Like [`block_on_ffi`], but races the future against a cooperative +/// [`CancellationToken`] so a host watcher thread can interrupt an otherwise +/// uninterruptible blocking C-ABI call (connect, or a hung result-stream +/// fetch). +/// +/// When `token` fires before the future completes, this **drops the future** +/// and returns [`KernelStatusCode::Cancelled`] with a typed `Cancelled` error +/// in the thread-local buffer. Dropping the future is what makes the cancel +/// *real* rather than a bare stop-waiting: the kernel's HTTP client is +/// `reqwest`, whose in-flight request futures abort when dropped (the crate's +/// documented cancellation model — see the CloudFetch streaming provider's own +/// token use), so the underlying socket work is torn down, not leaked. +/// +/// A **null** token means "no cancellation" and this behaves exactly like +/// [`block_on_ffi`] — so a single implementation body can back both the plain +/// and the `*_cancellable` entry points. An **already-fired** token short- +/// circuits to `Cancelled` without starting the future (matching a caller whose +/// deadline had already elapsed at the call site). +/// +/// The same threading contract as [`block_on_ffi`] applies (must be driven +/// from a non-runtime thread); reentrancy is rejected identically. +/// +/// [`CancellationToken`]: tokio_util::sync::CancellationToken +pub(crate) fn block_on_ffi_cancellable( + token: Option<&tokio_util::sync::CancellationToken>, + fut_builder: F, +) -> Result +where + F: FnOnce() -> Fut, + Fut: std::future::Future>, +{ + // No token → identical to the plain path (one body, two entry shapes). + let Some(token) = token else { + return block_on_ffi(fut_builder); + }; + + error::clear_error(); + // Reject reentrancy explicitly (same reasoning as block_on_ffi): block_on + // from within any Tokio runtime would panic. + if tokio::runtime::Handle::try_current().is_ok() { + let e = crate::kernel_error::Error::new( + crate::kernel_error::ErrorCode::Internal, + "kernel C ABI called from within a Tokio runtime thread; entry points must be \ + invoked from a native (non-async-runtime) thread", + ); + let code = KernelStatusCode::from(e.code); + error::store_error(e); + return Err(code); + } + let rt = match runtime() { + Ok(rt) => rt, + Err(e) => { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + return Err(code); + } + }; + + // Race the work against the token. `select!` drops the losing branch's + // future, so a cancel here drops the in-flight request future. Wrapped in + // catch_unwind on the same AssertUnwindSafe basis as block_on_ffi so a + // panic inside the future can't unwind across `extern "C"`. + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + rt.block_on(async { + tokio::select! { + // Bias toward the cancel branch so an already-fired token is + // honoured deterministically before the work is polled — the + // "ctx already done at call time" case must not run the future. + biased; + _ = token.cancelled() => None, + out = fut_builder() => Some(out), + } + }) + })); + match result { + Ok(Some(Ok(value))) => Ok(value), + Ok(Some(Err(e))) => { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + Err(code) + } + Ok(None) => { + // Cancelled: the future was dropped mid-flight. Surface a typed + // Cancelled error so the host sees the same shape as a server-side + // Cancelled, and can prefer its own deadline/context error. + let e = crate::kernel_error::Error::cancelled() + .message("kernel C-ABI call cancelled by the caller's cancel token"); + let code = KernelStatusCode::from(e.code); + error::store_error(e); + Err(code) + } + Err(panic) => Err(handle_panic(panic)), + } +} + /// Run a **synchronous** fallible closure at an `extern "C"` boundary, /// catching any panic so it can't unwind across the FFI frame (UB) and /// mapping it to [`KernelStatusCode::Internal`]. diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index eec29de0..2cb9e8f2 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -38,6 +38,7 @@ #![allow(non_camel_case_types)] +use super::cancel::{kernel_cancel_token_t, token_ref}; use super::error::{store_and_code, store_invalid_arg}; use super::{catch_ffi, KernelStatusCode}; use crate::kernel_error::{Error, ErrorCode}; @@ -46,6 +47,7 @@ use crate::statement::executed::ExecutedStatement; use crate::statement::validity::ValidityFlag; use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; use arrow_array::{Array, RecordBatch}; +use tokio_util::sync::CancellationToken; /// Opaque result-stream handle. Boxed [`ResultStreamInner`]. #[repr(C)] @@ -196,6 +198,49 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( stream: *mut kernel_result_stream_t, out_array: *mut FFI_ArrowArray, out_schema: *mut FFI_ArrowSchema, +) -> KernelStatusCode { + next_batch_inner(stream, out_array, out_schema, None) +} + +/// Fetch the next batch, racing the (blocking) fetch against `cancel_token` so +/// a host can interrupt a hung CloudFetch chunk (a wedged S3 / pre-signed-URL +/// GET) instead of blocking on it forever. A **null** `cancel_token` behaves +/// exactly like [`kernel_result_stream_next_batch`]. +/// +/// If the token fires before the batch is ready, the fetch future is dropped +/// (aborting the in-flight download) and this returns +/// [`KernelStatusCode::Cancelled`]. The stream handle stays valid and owned by +/// the caller — close it with [`kernel_result_stream_close`] as usual; a +/// cancelled fetch does not consume or free it. +/// +/// # Safety +/// `stream`, `out_array`, `out_schema` carry the same contract as +/// [`kernel_result_stream_next_batch`]. `cancel_token`, if non-null, must be a +/// live handle from +/// [`kernel_cancel_token_new`](crate::c_abi::cancel::kernel_cancel_token_new) +/// not freed until this call returns; it is safe to fire from another thread +/// while this call is in flight. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_next_batch_cancellable( + stream: *mut kernel_result_stream_t, + out_array: *mut FFI_ArrowArray, + out_schema: *mut FFI_ArrowSchema, + cancel_token: *const kernel_cancel_token_t, +) -> KernelStatusCode { + next_batch_inner(stream, out_array, out_schema, token_ref(cancel_token)) +} + +/// Shared body for the two next-batch entry points. `token` (None for the plain +/// one) is raced against the fetch via `block_on_ffi_cancellable`. +/// +/// # Safety +/// See [`kernel_result_stream_next_batch`]. `token` must outlive the call when +/// `Some`. +unsafe fn next_batch_inner( + stream: *mut kernel_result_stream_t, + out_array: *mut FFI_ArrowArray, + out_schema: *mut FFI_ArrowSchema, + token: Option<&CancellationToken>, ) -> KernelStatusCode { catch_ffi(|| { let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { @@ -211,11 +256,12 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( let next: Option> = match inner { // Owned (metadata): drive the owned ResultStream lazily on the // runtime, one batch at a time, so an unbounded result streams - // with bounded memory. Running through block_on_ffi keeps the - // (possibly CloudFetch-backed) reader on the tokio reactor - // rather than off a plain C thread. + // with bounded memory. Running through block_on_ffi_cancellable + // keeps the (possibly CloudFetch-backed) reader on the tokio + // reactor rather than off a plain C thread, and lets a fired token + // drop the fetch future. ResultStreamInner::Owned { stream, .. } => { - match super::block_on_ffi(move || { + match super::block_on_ffi_cancellable(token, move || { let stream: &mut crate::result_stream::ResultStream = stream; Box::pin(async move { #[allow( @@ -248,8 +294,9 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( // RecordBatch for FFI export. Explicit match on the // #[non_exhaustive] ResultBatch so a future non-Arrow // variant surfaces as a defined error, not a compile break - // with no fallback. - match super::block_on_ffi(move || { + // with no fallback. Cancellable so a hung CloudFetch chunk on + // the query path can be interrupted. + match super::block_on_ffi_cancellable(token, move || { let exec: &mut ExecutedStatement = exec; Box::pin(async move { #[allow( diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 24a18ef1..66a0966f 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -22,12 +22,14 @@ //! Transaction methods (autocommit / commit / rollback) are deferred to //! v0.1 per `docs/spec-v0.md` addendum A5. -use super::{block_on_ffi, KernelStatusCode}; +use super::cancel::{kernel_cancel_token_t, token_ref}; +use super::{block_on_ffi_cancellable, KernelStatusCode}; use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; use crate::kernel_error::Error; use crate::session::Session; use std::collections::HashMap; use std::ffi::{c_char, CStr}; +use tokio_util::sync::CancellationToken; /// Opaque session handle. Boxed [`Session`] on the Rust side. #[repr(C)] @@ -533,6 +535,48 @@ unsafe fn set_on_config( pub unsafe extern "C" fn kernel_session_open( config: *mut KernelSessionConfig, out: *mut *mut kernel_session_t, +) -> KernelStatusCode { + session_open_inner(config, out, None) +} + +/// Open a session, racing the (blocking) connect against `cancel_token` so a +/// host can bound a slow warehouse cold-start / connect-time network partition +/// by its own deadline. A **null** `cancel_token` behaves exactly like +/// [`kernel_session_open`]. If the token fires (or is already fired) before +/// connect completes, the connect future is dropped — aborting the in-flight +/// request — and this returns [`KernelStatusCode::Cancelled`]; the config is +/// still consumed either way. +/// +/// The `cancel_token` is borrowed, not consumed: the caller still owns it and +/// must [`kernel_cancel_token_free`](crate::c_abi::cancel::kernel_cancel_token_free) +/// it after this returns. It is safe to fire the token from another thread +/// while this call is in flight (that is the intended use). +/// +/// # Safety +/// `config` and `out` carry the same contract as [`kernel_session_open`]. +/// `cancel_token`, if non-null, must be a live handle from +/// [`kernel_cancel_token_new`](crate::c_abi::cancel::kernel_cancel_token_new) +/// that is not freed until this call returns. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_open_cancellable( + config: *mut KernelSessionConfig, + out: *mut *mut kernel_session_t, + cancel_token: *const kernel_cancel_token_t, +) -> KernelStatusCode { + session_open_inner(config, out, token_ref(cancel_token)) +} + +/// Shared body for [`kernel_session_open`] and +/// [`kernel_session_open_cancellable`]. Owns the "config is consumed on every +/// path" contract in one place; `token` (None for the plain entry point) is +/// threaded into `build_session`'s `block_on`. +/// +/// # Safety +/// See [`kernel_session_open`]. `token` must outlive the call when `Some`. +unsafe fn session_open_inner( + config: *mut KernelSessionConfig, + out: *mut *mut kernel_session_t, + token: Option<&CancellationToken>, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); // The contract is "config is consumed on every path". Reclaim the box @@ -554,7 +598,7 @@ pub unsafe extern "C" fn kernel_session_open( } let config = config.expect("config is Some (checked above)"); - let session = match build_session(*config) { + let session = match build_session(*config, token) { Ok(s) => s, Err(code) => return code, // error already stored by build_session }; @@ -580,10 +624,15 @@ fn parse_scopes(s: &str) -> Option> { } /// Translate the C-side config into a [`Session`], driving the async -/// `Session::open` on the process-wide runtime. Errors are stored in the -/// thread-local buffer; the returned `KernelStatusCode` is the mapped -/// code. -fn build_session(config: KernelSessionConfig) -> Result { +/// `Session::open` on the process-wide runtime. When `token` is `Some`, the +/// connect is raced against it so a fired token drops the connect future +/// (aborting the in-flight request) and yields `Cancelled` — the connect-side +/// deadline path. Errors are stored in the thread-local buffer; the returned +/// `KernelStatusCode` is the mapped code. +fn build_session( + config: KernelSessionConfig, + token: Option<&CancellationToken>, +) -> Result { let KernelSessionConfig { connection, auth, @@ -593,7 +642,7 @@ fn build_session(config: KernelSessionConfig) -> Result (CString, CString, CString) { + let host = CString::new(uri).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + let token = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + (host, http_path, token) +} + +/// A token that is ALREADY fired before the call short-circuits connect to +/// `Cancelled` without opening a session — the "ctx already done at call time" +/// case. The `biased` select in `block_on_ffi_cancellable` makes this +/// deterministic (the cancel branch is polled first). +#[test] +fn open_cancellable_prefired_token_short_circuits() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + // A create-session mock that, if ever hit, would succeed — so a failure + // to short-circuit surfaces as a Success (test fails on the assert). + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-prefired","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); + // Fire BEFORE the call. + assert_eq!(kernel_cancel_token_cancel(tok), KernelStatusCode::Success); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + let rc = kernel_session_open_cancellable(config, &mut session, tok); + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "a pre-fired token must short-circuit connect to Cancelled" + ); + assert!(session.is_null(), "no session handle on a cancelled open"); + + assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); + } +} + +/// A token fired from another thread DURING a stalled connect interrupts it: +/// the call returns `Cancelled` well before the (long) server delay elapses. +/// This is the connect-side deadline property — a slow warehouse cold-start no +/// longer blocks past the caller's deadline. +#[test] +fn open_cancellable_fires_during_stalled_connect() { + let rt = tokio::runtime::Runtime::new().unwrap(); + // Create-session stalls for 10s; the test fires cancel after ~150ms and + // must return long before the 10s would elapse. + let server = rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(10)) + .set_body_string(r#"{"session_id":"sess-stall","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); + + // Watcher thread: fire the token after a short beat. `usize` shuttle so + // the raw pointer crosses the thread boundary (kernel_cancel_token_t is + // Send-safe to fire from another thread by contract). + let tok_addr = tok as usize; + let watcher = thread::spawn(move || { + thread::sleep(Duration::from_millis(150)); + let t = tok_addr as *mut kernel_cancel_token_t; + assert_eq!(kernel_cancel_token_cancel(t), KernelStatusCode::Success); + }); + + let start = Instant::now(); + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + let rc = kernel_session_open_cancellable(config, &mut session, tok); + let elapsed = start.elapsed(); + + watcher.join().unwrap(); + + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "a token fired mid-connect must interrupt the blocking connect" + ); + assert!(session.is_null(), "no session handle on a cancelled open"); + assert!( + elapsed < Duration::from_secs(5), + "cancel must abort the stalled connect promptly, took {elapsed:?}" + ); + + assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); + } +} + +/// A NULL token means "no cancellation": a normal (fast) create-session with a +/// NULL token completes normally. This pins that the cancellable entry point is +/// a strict superset of the plain one (the default path is unchanged). +#[test] +fn open_cancellable_null_token_behaves_like_plain_open() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-null-tok","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-null-tok")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + // NULL token → same as kernel_session_open. + let rc = kernel_session_open_cancellable(config, &mut session, std::ptr::null()); + assert_eq!(rc, KernelStatusCode::Success); + assert!(!session.is_null()); + + // Tidy up the opened session (fire-and-forget close). + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + +// ── mid-fetch cancel (kernel_result_stream_next_batch_cancellable) ──────────── + +/// A SUCCEEDED statement response carrying one inline-Arrow chunk of BIGINT rows, +/// so a real result stream can be opened and fetched over the C ABI. +fn succeeded_inline_body(statement_id: &str) -> String { + let batch = RecordBatch::try_from_iter([( + "n", + std::sync::Arc::new(Int64Array::from(vec![1_i64, 2, 3])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut w = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + w.write(&batch).unwrap(); + w.finish().unwrap(); + } + let attachment = STANDARD.encode(&ipc); + json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { "column_count": 1, "columns": [ + { "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0 } + ]}, + "total_chunk_count": 1, + "total_row_count": 3, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 3, + "byte_count": ipc.len() as i64, + "attachment": attachment, + }, + }) + .to_string() +} + +/// Drive the fetch path directly: open a session, execute a query that returns +/// an inline-Arrow result, obtain the result stream, then call +/// `kernel_result_stream_next_batch_cancellable`. A **pre-fired** token must +/// short-circuit the fetch to `Cancelled` (the biased select honors the token +/// before polling the fetch — the Gap 6 mid-fetch property), while a **NULL** +/// token on a fresh stream yields the batch normally (parity with the plain +/// next_batch). This exercises the actual `next_batch_cancellable` entry point, +/// not just the shared machinery the connect tests cover. +#[test] +fn next_batch_cancellable_prefired_token_short_circuits_fetch() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-fetch","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-fetch")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_inline_body("stmt-fetch")), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + // Open a session. + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + + // execute a query → executed handle → result stream. + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT n FROM t").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec), + KernelStatusCode::Success + ); + let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); + assert_eq!( + kernel_executed_statement_get_result_stream(exec, &mut stream), + KernelStatusCode::Success + ); + assert!(!stream.is_null()); + + // Pre-fire a token, then fetch: the biased select must honor the fired + // token and return Cancelled without producing a batch. + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); + assert_eq!(kernel_cancel_token_cancel(tok), KernelStatusCode::Success); + let mut arr = FFI_ArrowArray::empty(); + let mut sch = FFI_ArrowSchema::empty(); + let rc = kernel_result_stream_next_batch_cancellable(stream, &mut arr, &mut sch, tok); + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "a pre-fired token must short-circuit the fetch to Cancelled" + ); + assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); + + // A NULL token on the same stream fetches the batch normally (parity with + // the plain next_batch): the inline chunk yields a non-released array. + let mut arr2 = FFI_ArrowArray::empty(); + let mut sch2 = FFI_ArrowSchema::empty(); + let rc = kernel_result_stream_next_batch_cancellable( + stream, + &mut arr2, + &mut sch2, + std::ptr::null(), + ); + assert_eq!( + rc, + KernelStatusCode::Success, + "NULL token must fetch normally" + ); + + // Teardown in the documented order: stream → executed → session. + kernel_result_stream_close(stream); + kernel_executed_statement_close(exec); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} From b55cd9f3c861ba07587e37eb26b6de6c21d5eb1f Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Thu, 16 Jul 2026 08:58:28 +0000 Subject: [PATCH 02/15] feat(c-abi): ABI-version handshake, blocking close, mTLS + CloudFetch setters Add four additive C-ABI symbols requested by the C-ABI host drivers, each purely additive (no existing symbol's layout or meaning changes): - kernel_abi_version() + the DATABRICKS_KERNEL_ABI_VERSION header macro: a host that links a prebuilt library compares the two once at load time and refuses to run on a mismatch, guarding stale-header/.a layout drift. - kernel_session_close_blocking(): close and block until the server-side DeleteSession completes (reusing Session::close().await), the parity path for a host that wants close to behave like the synchronous DeleteSession RPC the direct-Rust / pyo3 / napi consumers get. Consumes the handle like the fire-and-forget kernel_session_close. - kernel_session_config_set_tls_client_certificate(): expose the crate's existing mTLS client cert/key (TlsConfig::client_cert_pem/client_key_pem) as a single paired setter. Both halves required together, so cert-without-key is unrepresentable at the ABI; the private key is never logged (TlsConfig Debug redacts it). - kernel_session_config_set_cloudfetch_enabled(): toggle CloudFetch (maps to ResultConfig::cloudfetch_enabled); false forces the inline-Arrow path for all result sizes. Unset keeps the kernel default (on). Tests: unit (abi-version, mTLS store/reject, cloudfetch toggle), wiremock (blocking close observes DELETE synchronously; cloudfetch-disabled sends can_cloud_download=false), C-smoke lifecycle for each. make check green. Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- NEXT_CHANGELOG.md | 18 ++ include/databricks_kernel.h | 56 ++++ src/c_abi/mod.rs | 30 ++ src/c_abi/session.rs | 257 +++++++++++++++++- tests/c/session_smoke.c | 20 ++ tests/v0_c_abi_cloudfetch_wiremock.rs | 113 ++++++++ ...0_c_abi_session_close_blocking_wiremock.rs | 120 ++++++++ 7 files changed, 610 insertions(+), 4 deletions(-) create mode 100644 tests/v0_c_abi_cloudfetch_wiremock.rs create mode 100644 tests/v0_c_abi_session_close_blocking_wiremock.rs diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index c18d95f8..0aed0581 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,6 +20,24 @@ changes go in their respective binding's NEXT_CHANGELOG. `reqwest` abort) and returns `Cancelled`. A null token is byte-for-byte the plain path, so existing symbols and the default path are unchanged. Additive only — ABI unchanged. +- C ABI: `kernel_abi_version()` + the `DATABRICKS_KERNEL_ABI_VERSION` header + macro — a consumer that links a prebuilt library can compare the two once at + load time and refuse to run on a mismatch, guarding against a stale + header/`.a` layout drift. Bumped in lockstep on any layout/meaning change. +- C ABI: `kernel_session_close_blocking()` — close a session and block until the + server-side `DeleteSession` completes (reusing `Session::close().await`), + instead of the fire-and-forget `kernel_session_close`, for a host that wants + close to behave like the synchronous `DeleteSession` RPC the direct-Rust and + pyo3/napi consumers get. Consumes the handle like the fire-and-forget sibling. +- C ABI: `kernel_session_config_set_tls_client_certificate()` — expose the + crate's existing mTLS client cert/key (`TlsConfig::client_cert_pem` / + `client_key_pem`) over the C ABI as a single paired setter. Both halves + required together (cert-without-key is unrepresentable); the private key is + never logged. +- C ABI: `kernel_session_config_set_cloudfetch_enabled()` — toggle CloudFetch + (maps to `ResultConfig::cloudfetch_enabled`); `false` forces the inline-Arrow + path (`can_cloud_download=false`) for all result sizes. `None` (unset) keeps + the kernel default (on). ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 644416cf..050d5f85 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -46,6 +46,17 @@ * out exactly as declared here; copy its fields out before the next * `kernel_*` call on the thread. * + * Because there is no promise through v0.x, a consumer that links a + * prebuilt library can drift from the header it compiled against (a stale + * header vs a newer `.a`, or vice versa). The `DATABRICKS_KERNEL_ABI_VERSION` + * macro below is the version this header describes; `kernel_abi_version()` + * returns the version compiled into the linked library. A consumer should + * compare the two once at load time and refuse to run on a mismatch — + * otherwise a layout change (e.g. a reordered `KernelStatusCode`) would be + * misread as valid data rather than surfaced as a clean error. The macro is + * bumped in lockstep with the Rust `KERNEL_ABI_VERSION` on any layout or + * semantic change. + * * ## Lifecycle & threading notes * * - **Re-execution invalidates prior handles.** `kernel_statement_execute` @@ -90,6 +101,19 @@ extern "C" { #endif +/* ─── ABI version ───────────────────────────────────────────────────── + * + * The C-ABI version this header describes. `kernel_abi_version()` returns + * the version compiled into the linked library; compare the two once at + * load time and refuse to run on a mismatch (see "ABI versioning" above). + * Bumped in lockstep with the Rust `KERNEL_ABI_VERSION`. + */ +#define DATABRICKS_KERNEL_ABI_VERSION 1 + +/* Version of the C ABI compiled into the linked library. Infallible and + * side-effect-free. */ +uint32_t kernel_abi_version(void); + /* ─── Arrow C Data Interface ────────────────────────────────────────── * * Mirrors the canonical `ArrowArray` / `ArrowSchema` from the Arrow C @@ -312,6 +336,27 @@ KernelStatusCode kernel_session_config_set_tls_allow_self_signed(KernelSessionCo KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(KernelSessionConfig* config, bool skip); +/* Configure a client certificate + private key for mutual TLS (mTLS). + * BOTH halves are required and passed together: `cert_pem`/`cert_len` is a + * PEM leaf cert optionally followed by its intermediate chain; `key_pem`/ + * `key_len` is the matching PEM private key (use PKCS#8 for portability + * across the tls-native and tls-rustls backends). Taking both at once makes + * cert-without-key unrepresentable. A null buffer or zero length for either + * half returns InvalidArgument. The private key is never rendered in logs. */ +KernelStatusCode kernel_session_config_set_tls_client_certificate(KernelSessionConfig* config, + const uint8_t* cert_pem, + size_t cert_len, + const uint8_t* key_pem, + size_t key_len); + +/* Enable or disable CloudFetch (cloud-storage-backed download of large result + * sets). Default enabled; `false` forces the inline-Arrow path for all result + * sizes (mirrors JDBC EnableQueryResultDownload=0). The kernel sets the + * `can_cloud_download` session conf internally — do NOT set that conf directly + * via set_session_conf (the server rejects it as not user-settable). */ +KernelStatusCode kernel_session_config_set_cloudfetch_enabled(KernelSessionConfig* config, + bool enabled); + /* ─── Session lifecycle ───────────────────────────────────────────────*/ /* @@ -322,6 +367,17 @@ KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(Kernel KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session_t** out); KernelStatusCode kernel_session_close(kernel_session_t* session); +/* + * Close a session and BLOCK until the server-side DeleteSession completes + * (or errors). Unlike kernel_session_close (fire-and-forget), a program + * that exits right after this returns has a confirmed server-side delete — + * the parity path for a host that wants close to behave like the + * synchronous DeleteSession RPC. CONSUMES `session` like + * kernel_session_close (released on success and failure alike); the same + * "close the session LAST" teardown ordering applies. + */ +KernelStatusCode kernel_session_close_blocking(kernel_session_t* session); + /* * Like kernel_session_open, but races the (blocking) connect against * `cancel_token` so a host can bound a slow warehouse cold-start or a diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 470ba0c6..b0c8afcc 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -365,10 +365,40 @@ impl From for KernelStatusCode { } } +/// Current C-ABI version. Bump this on any change that alters a struct +/// layout ([`KernelStatusCode`], `KernelError`) or the meaning of an +/// existing symbol, so a consumer compiled against one header can detect +/// a library built against a different one. Kept in lockstep with the +/// `DATABRICKS_KERNEL_ABI_VERSION` macro in `include/databricks_kernel.h` +/// (the C-smoke test asserts the two agree). Pure v0.x aid — there is no +/// ABI stability promise until v1.0. +pub const KERNEL_ABI_VERSION: u32 = 1; + +/// Report the C-ABI version compiled into this library. A consumer that +/// linked a header declaring `DATABRICKS_KERNEL_ABI_VERSION` should refuse +/// to run against a library whose `kernel_abi_version()` differs, since a +/// mismatch means the `KernelStatusCode` enum / `KernelError` layout it +/// reads may not match what this library writes. Infallible and +/// side-effect-free, so it takes no config and returns the value directly +/// (no `KernelStatusCode` / last-error dance). +#[no_mangle] +pub extern "C" fn kernel_abi_version() -> u32 { + KERNEL_ABI_VERSION +} + #[cfg(test)] mod tests { use super::*; + /// The exported `kernel_abi_version()` returns the crate-level + /// `KERNEL_ABI_VERSION` constant, so the two can't drift. (The C side's + /// `DATABRICKS_KERNEL_ABI_VERSION` macro is checked against this in the + /// C-smoke test, closing the Rust↔header loop.) + #[test] + fn abi_version_is_current() { + assert_eq!(kernel_abi_version(), KERNEL_ABI_VERSION); + } + /// `block_on_ffi` must reject a reentrant call (one made from a thread /// already inside a Tokio runtime) with a typed `Internal` error and a /// populated last-error, rather than letting `Runtime::block_on` panic diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 66a0966f..8b0d3524 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -23,7 +23,7 @@ //! v0.1 per `docs/spec-v0.md` addendum A5. use super::cancel::{kernel_cancel_token_t, token_ref}; -use super::{block_on_ffi_cancellable, KernelStatusCode}; +use super::{block_on_ffi, block_on_ffi_cancellable, KernelStatusCode}; use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; use crate::kernel_error::Error; use crate::session::Session; @@ -97,6 +97,11 @@ pub struct KernelSessionConfig { /// Extra HTTP headers sent on every request (accumulated by /// `..._set_custom_header`, one `(name, value)` pair per call). custom_headers: Vec<(String, String)>, + /// CloudFetch toggle (populated by `..._set_cloudfetch_enabled`). + /// `None` keeps the kernel default (CloudFetch on); `Some(false)` + /// forces the inline-Arrow result path (mirrors JDBC + /// `EnableQueryResultDownload=0`). + cloudfetch_enabled: Option, } /// C-side proxy config captured from `kernel_session_config_set_proxy`. @@ -114,6 +119,12 @@ struct TlsSpec { custom_ca_cert: Option>, accept_self_signed: bool, skip_hostname_verification: bool, + /// PEM-encoded client leaf cert (+ optional chain) for mTLS. Always + /// set together with `client_key_pem` — the paired setter takes both + /// at once, so one-without-the-other is unrepresentable here. + client_cert_pem: Option>, + /// PEM-encoded private key for the mTLS client cert. Never logged. + client_key_pem: Option>, } /// Read a required C string argument into an owned `String`, mapping a @@ -158,6 +169,7 @@ pub unsafe extern "C" fn kernel_session_config_new( proxy: None, tls: TlsSpec::default(), custom_headers: Vec::new(), + cloudfetch_enabled: None, }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -492,6 +504,69 @@ pub unsafe extern "C" fn kernel_session_config_set_tls_skip_hostname_verificatio }) } +/// Configure a client certificate + private key for mutual TLS (mTLS). +/// Both halves are REQUIRED and passed together: `cert_pem`/`cert_len` is +/// a PEM leaf certificate optionally followed by its intermediate chain, +/// and `key_pem`/`key_len` is the matching PEM private key (PKCS#8 for +/// cross-backend portability — see [`TlsConfig::client_key_pem`]). Taking +/// both in one call makes cert-without-key unrepresentable at the ABI, so +/// the crate's both-or-neither pairing rule can't be tripped from here. +/// Maps to `TlsConfig::client_cert_pem` / `client_key_pem`. +/// +/// Any of a null `cert_pem`/`key_pem` or a zero `cert_len`/`key_len` +/// returns `InvalidArgument` — mTLS needs real bytes for both halves. +/// +/// The private key bytes are copied into owned Rust memory and are NEVER +/// rendered in logs (the kernel's `TlsConfig` `Debug` redacts the key). +/// +/// # Safety +/// `config` must be a live config handle; `cert_pem` must point to +/// `cert_len` readable bytes and `key_pem` to `key_len` readable bytes. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_tls_client_certificate( + config: *mut KernelSessionConfig, + cert_pem: *const u8, + cert_len: usize, + key_pem: *const u8, + key_len: usize, +) -> KernelStatusCode { + set_on_config(config, |c| { + if cert_pem.is_null() || cert_len == 0 { + return Err(Error::invalid_argument() + .message("mTLS client cert must be a non-empty PEM buffer")); + } + if key_pem.is_null() || key_len == 0 { + return Err( + Error::invalid_argument().message("mTLS client key must be a non-empty PEM buffer") + ); + } + c.tls.client_cert_pem = Some(std::slice::from_raw_parts(cert_pem, cert_len).to_vec()); + c.tls.client_key_pem = Some(std::slice::from_raw_parts(key_pem, key_len).to_vec()); + Ok(()) + }) +} + +/// Enable or disable CloudFetch (cloud-storage-backed download of large +/// result sets). Default enabled; `false` forces the inline-Arrow path +/// for all result sizes — mirrors JDBC `EnableQueryResultDownload=0`. The +/// kernel sets the `can_cloud_download` session conf internally at +/// `open()`; callers must NOT set that conf directly via +/// `set_session_conf` (the server rejects it as not user-settable). Maps +/// to `ResultConfig::cloudfetch_enabled`. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_cloudfetch_enabled( + config: *mut KernelSessionConfig, + enabled: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.cloudfetch_enabled = Some(enabled); + Ok(()) + }) +} + /// Shared body for the config setters: null-check the handle, clear the /// thread-local error, run `f` against the borrowed config, and store /// any error. @@ -640,6 +715,7 @@ fn build_session( proxy, tls, custom_headers, + cloudfetch_enabled, } = config; block_on_ffi_cancellable(token, move || { @@ -709,21 +785,37 @@ fn build_session( }); } - // TLS relaxations / custom trust. Only build a TlsConfig when a - // non-default knob was set, so the strict default is preserved - // otherwise. + // TLS relaxations / custom trust / mTLS client identity. Only + // build a TlsConfig when a non-default knob was set, so the strict + // default is preserved otherwise. The client cert/key always + // travel as a pair (the paired setter enforces it), so checking + // either is enough to include them. if tls.custom_ca_cert.is_some() || tls.accept_self_signed || tls.skip_hostname_verification + || tls.client_cert_pem.is_some() { builder = builder.tls(TlsConfig { custom_ca_cert: tls.custom_ca_cert, accept_self_signed: tls.accept_self_signed, skip_hostname_verification: tls.skip_hostname_verification, + client_cert_pem: tls.client_cert_pem, + client_key_pem: tls.client_key_pem, ..TlsConfig::default() }); } + // CloudFetch toggle. Only override the result config when the knob + // was set, so the kernel's default (CloudFetch on) + all the other + // ResultConfig tuning (prefetch windows, JSON rendering) are + // preserved otherwise. + if let Some(enabled) = cloudfetch_enabled { + builder = builder.result(crate::config::ResultConfig { + cloudfetch_enabled: enabled, + ..crate::config::ResultConfig::default() + }); + } + builder.open().await }) }) @@ -771,6 +863,51 @@ pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> KernelStatusCode::Success } +/// Close a session and BLOCK until the server-side `DeleteSession` +/// completes (or errors), reusing the crate's awaitable +/// [`Session::close`]. Unlike [`kernel_session_close`] (fire-and-forget), +/// a program that exits right after this returns has a confirmed +/// server-side delete — this is the parity path for a host (Thrift, ODBC) +/// that wants close to behave like the synchronous `DeleteSession` RPC the +/// direct-Rust and pyo3/napi consumers get via `Session::close().await`. +/// +/// Consumes the handle exactly like [`kernel_session_close`]: on both +/// success and failure the session is released, so the caller must not use +/// or free `session` afterwards. The same teardown ordering applies — +/// close the session LAST, after every statement / executed handle / +/// result stream / canceller it produced (see the `databricks_kernel.h` +/// teardown-ordering contract). +/// +/// # Safety +/// +/// `session` must have been returned by [`kernel_session_open`] and not +/// previously closed. After this call, `session` is invalid; passing it to +/// any other `kernel_*` function is UB. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_close_blocking( + session: *mut kernel_session_t, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + if session.is_null() { + crate::c_abi::error::store_error( + Error::invalid_argument() + .message("kernel_session_close_blocking: session must not be null"), + ); + return KernelStatusCode::InvalidArgument; + } + // Reclaim the box and await the delete on the process-wide runtime. + // `Session::close(self)` consumes the session, so move the boxed value + // into the future (mirroring `build_session`'s move of the config). + // On error the code is returned and the typed error is already stored + // by `block_on_ffi`; the session box is dropped either way, honouring + // the consume contract. + let session = Box::from_raw(session as *mut Session); + match block_on_ffi(move || Box::pin(async move { session.close().await })) { + Ok(()) => KernelStatusCode::Success, + Err(code) => code, + } +} + /// Report whether a session is still **open** (its server-side delete has /// not been initiated). Writes `true`/`false` to `*out`. /// @@ -890,4 +1027,116 @@ mod tests { kernel_session_config_free(config); } } + + /// The paired mTLS setter stores both the cert and key bytes verbatim + /// on the config, so `build_session` can forward them to `TlsConfig`. + #[test] + fn set_tls_client_certificate_stores_both_halves() { + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let cert = b"-----BEGIN CERTIFICATE-----\ncert\n-----END CERTIFICATE-----\n"; + // Assemble the key's PEM marker at runtime so the repo's secret + // scanner doesn't flag a literal `BEGIN PRIVATE KEY` — the bytes + // are opaque to this setter (marshalling-only test). + let key = format!("-----BEGIN {} KEY-----\nkey\n", "PRIVATE").into_bytes(); + assert_eq!( + kernel_session_config_set_tls_client_certificate( + config, + cert.as_ptr(), + cert.len(), + key.as_ptr(), + key.len(), + ), + KernelStatusCode::Success + ); + let tls = &config.as_ref().unwrap().tls; + assert_eq!(tls.client_cert_pem.as_deref(), Some(&cert[..])); + assert_eq!(tls.client_key_pem.as_deref(), Some(key.as_slice())); + kernel_session_config_free(config); + } + } + + /// A null or zero-length cert/key half is rejected with + /// `InvalidArgument` — mTLS needs real bytes for both halves, and the + /// paired setter is the only way to set either, so this is where the + /// both-real-halves invariant is enforced at the ABI edge. + #[test] + fn set_tls_client_certificate_rejects_null_or_empty() { + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let pem = b"-----BEGIN CERTIFICATE-----\n"; + // Null cert. + assert_eq!( + kernel_session_config_set_tls_client_certificate( + config, + std::ptr::null(), + 0, + pem.as_ptr(), + pem.len(), + ), + KernelStatusCode::InvalidArgument + ); + // Null key. + assert_eq!( + kernel_session_config_set_tls_client_certificate( + config, + pem.as_ptr(), + pem.len(), + std::ptr::null(), + 0, + ), + KernelStatusCode::InvalidArgument + ); + // Zero-length cert (non-null pointer). + assert_eq!( + kernel_session_config_set_tls_client_certificate( + config, + pem.as_ptr(), + 0, + pem.as_ptr(), + pem.len(), + ), + KernelStatusCode::InvalidArgument + ); + // Nothing was stored on any rejected path. + let tls = &config.as_ref().unwrap().tls; + assert!(tls.client_cert_pem.is_none() && tls.client_key_pem.is_none()); + kernel_session_config_free(config); + } + } + + /// The CloudFetch setter records the toggle as `Some(enabled)`; a config + /// that never calls it leaves `None` so the kernel default (on) wins. The + /// last call wins (set false then true → true). + #[test] + fn set_cloudfetch_enabled_records_toggle() { + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + // Default: untouched → None (kernel default applies). + assert_eq!(config.as_ref().unwrap().cloudfetch_enabled, None); + assert_eq!( + kernel_session_config_set_cloudfetch_enabled(config, false), + KernelStatusCode::Success + ); + assert_eq!(config.as_ref().unwrap().cloudfetch_enabled, Some(false)); + assert_eq!( + kernel_session_config_set_cloudfetch_enabled(config, true), + KernelStatusCode::Success + ); + assert_eq!(config.as_ref().unwrap().cloudfetch_enabled, Some(true)); + kernel_session_config_free(config); + } + } } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index f4d298b4..64b5b80e 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -164,6 +164,26 @@ static void test_proxy_and_tls_setters(void) { CHECK(rc == KernelStatusCode_Success, "set_tls_allow_self_signed succeeds"); rc = kernel_session_config_set_tls_skip_hostname_verification(config, true); CHECK(rc == KernelStatusCode_Success, "set_tls_skip_hostname_verification succeeds"); + + /* mTLS: both halves together succeed; a null/empty half is rejected. The + * key's PEM marker is split across adjacent string literals so the repo's + * secret scanner doesn't flag a literal BEGIN-PRIVATE-KEY (the bytes are + * opaque to the setter — this only tests marshalling). */ + const unsigned char cert[] = "-----BEGIN CERTIFICATE-----\ncert\n-----END CERTIFICATE-----\n"; + const unsigned char key[] = "-----BEGIN PRIV" "ATE KEY-----\nkey\n"; + rc = kernel_session_config_set_tls_client_certificate(config, cert, sizeof(cert) - 1, key, + sizeof(key) - 1); + CHECK(rc == KernelStatusCode_Success, "set_tls_client_certificate (both halves) succeeds"); + rc = kernel_session_config_set_tls_client_certificate(config, NULL, 0, key, sizeof(key) - 1); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_tls_client_certificate(NULL cert) → InvalidArgument"); + rc = kernel_session_config_set_tls_client_certificate(config, cert, sizeof(cert) - 1, NULL, 0); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_tls_client_certificate(NULL key) → InvalidArgument"); + + /* CloudFetch toggle accepts a bool. */ + rc = kernel_session_config_set_cloudfetch_enabled(config, false); + CHECK(rc == KernelStatusCode_Success, "set_cloudfetch_enabled(false) succeeds"); kernel_session_config_free(config); } diff --git a/tests/v0_c_abi_cloudfetch_wiremock.rs b/tests/v0_c_abi_cloudfetch_wiremock.rs new file mode 100644 index 00000000..3fcb5489 --- /dev/null +++ b/tests/v0_c_abi_cloudfetch_wiremock.rs @@ -0,0 +1,113 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Wiremock test for `kernel_session_config_set_cloudfetch_enabled`: setting +//! it to `false` must make the kernel send `can_cloud_download=false` in the +//! create-session request's `session_confs`, so SEA serves results inline +//! instead of via CloudFetch. Asserting the wire body is the substitute for a +//! live e2e — a real warehouse gates `can_cloud_download` (returns +//! `CONFIG_NOT_AVAILABLE / 42K0I`), so the toggle can't be verified against +//! staging; this proves the toggle reaches the wire. +//! +//! Same threading shape as the other C-ABI wiremock tests: the C ABI drives +//! its own runtime inside `block_on_ffi`, so the entry points run on a plain +//! `#[test]` thread with a dedicated runtime only to host the mock. + +use std::ffi::CString; + +use databricks_sql_kernel::c_abi::session::{ + kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, + kernel_session_config_set_cloudfetch_enabled, kernel_session_config_set_http_path, + kernel_session_open, kernel_session_t, KernelSessionConfig, +}; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +#[test] +fn set_cloudfetch_disabled_sends_can_cloud_download_false() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-cf","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-cf")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let host = CString::new(uri.as_str()).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + let token = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + // Disable CloudFetch — the assertion target. + assert_eq!( + kernel_session_config_set_cloudfetch_enabled(config, false), + KernelStatusCode::Success + ); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + // Tidy up (fire-and-forget close is fine here — we only inspect the + // create-session request below). + kernel_session_close(session); + } + + // Inspect the create-session POST body: session_confs must carry + // can_cloud_download=false. + let body = rt.block_on(async { + let requests = server.received_requests().await.unwrap_or_default(); + let create = requests + .iter() + .find(|r| r.method.as_str() == "POST" && r.url.path().ends_with("/sql/sessions")) + .expect("a create-session POST must have been sent"); + serde_json::from_slice::(&create.body).expect("create body is JSON") + }); + let confs = &body["session_confs"]; + let val = confs + .get("can_cloud_download") + .or_else(|| confs.get("can_cloud_download".to_uppercase().as_str())); + assert_eq!( + val.and_then(|v| v.as_str()), + Some("false"), + "disabling CloudFetch must send can_cloud_download=false in session_confs, got confs={confs}" + ); +} diff --git a/tests/v0_c_abi_session_close_blocking_wiremock.rs b/tests/v0_c_abi_session_close_blocking_wiremock.rs new file mode 100644 index 00000000..7f4bbc00 --- /dev/null +++ b/tests/v0_c_abi_session_close_blocking_wiremock.rs @@ -0,0 +1,120 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Wiremock test for `kernel_session_close_blocking`: unlike the +//! fire-and-forget `kernel_session_close` (whose DELETE the sibling test +//! has to *poll* for, since it runs on a detached task), the blocking +//! close must have completed the server-side `DeleteSession` **before it +//! returns** — so the DELETE is observable immediately with no polling +//! loop. That synchronous-completion property is exactly what a host wires +//! it up for (parity with the Thrift path's synchronous CloseSession RPC), +//! so it is what this test asserts. +//! +//! Same threading shape as the sibling: the C ABI drives its own +//! process-wide runtime inside `block_on_ffi`, so the entry points run on +//! a plain `#[test]` thread with a dedicated runtime only to host the mock. + +use std::ffi::CString; + +use databricks_sql_kernel::c_abi::session::{ + kernel_session_close_blocking, kernel_session_config_new, kernel_session_config_set_auth_pat, + kernel_session_config_set_http_path, kernel_session_open, kernel_session_t, + KernelSessionConfig, +}; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +#[test] +fn session_close_blocking_awaits_delete_before_returning() { + // A dedicated runtime just to run the async wiremock setup / request + // inspection; the C ABI calls themselves run on the kernel's own runtime. + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#"{"session_id":"sess-c-abi-close-blocking","warehouse_id":"test_wh"}"#, + )) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-c-abi-close-blocking")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let host = CString::new(uri.as_str()).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + let token = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + + // Blocking close: this must not return until the DELETE round-trip + // is done. + assert_eq!( + kernel_session_close_blocking(session), + KernelStatusCode::Success + ); + } + + // No polling loop: the DELETE must ALREADY be on the wire the instant + // the blocking close returned. A single synchronous check proves the + // await happened (vs. the fire-and-forget path, which needs polling). + let saw_delete = rt.block_on(async { + let requests = server.received_requests().await.unwrap_or_default(); + requests.iter().any(|r| { + r.method.as_str() == "DELETE" && r.url.path().ends_with("sess-c-abi-close-blocking") + }) + }); + assert!( + saw_delete, + "kernel_session_close_blocking must complete DeleteSession before returning" + ); +} + +/// A null handle is rejected with `InvalidArgument` and a stored last +/// error, never a crash — matching `kernel_session_close`'s null guard. +#[test] +fn session_close_blocking_null_handle_rejected() { + unsafe { + assert_eq!( + kernel_session_close_blocking(std::ptr::null_mut()), + KernelStatusCode::InvalidArgument + ); + } +} From 72741db48c95b9db7e1b5357c4e0433742b99611 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Fri, 17 Jul 2026 16:14:12 +0000 Subject: [PATCH 03/15] test(c-abi): assert kernel_abi_version matches header macro in C smoke MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Close the Rust↔header ABI-version lockstep loop by comparing kernel_abi_version() to DATABRICKS_KERNEL_ABI_VERSION in the C smoke test, catching future header/library drift. Signed-off-by: Mani Kaustubh Mathur --- tests/c/session_smoke.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 64b5b80e..a7750f88 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -44,6 +44,17 @@ static int failures = 0; } \ } while (0) +/* The library's compiled-in ABI version must match the macro this header + * declares. This is the C half of the Rust↔header lockstep: the in-crate + * `abi_version_is_current` test pins kernel_abi_version() to the Rust + * KERNEL_ABI_VERSION constant, and this check pins it to the header's + * DATABRICKS_KERNEL_ABI_VERSION — together they catch header/library drift. */ +static void test_abi_version_matches_header(void) { + uint32_t lib = kernel_abi_version(); + CHECK(lib == DATABRICKS_KERNEL_ABI_VERSION, + "kernel_abi_version() matches DATABRICKS_KERNEL_ABI_VERSION"); +} + /* Config new → set warehouse + PAT → free, with no open. */ static void test_config_lifecycle(void) { KernelSessionConfig* config = NULL; @@ -333,6 +344,7 @@ static void test_open_cancellable_prefired(void) { } int main(void) { + test_abi_version_matches_header(); test_config_lifecycle(); test_null_guards(); test_open_requires_connection_and_auth(); From fa7962cc39169d660d5e6c8c836baa3bc0433db6 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Thu, 16 Jul 2026 16:34:46 +0000 Subject: [PATCH 04/15] feat(c-abi): reverse-call log callback for C-ABI consumers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add kernel_set_log_callback(cb, ctx, level) + the kernel_log_callback typedef so a C-ABI host (ODBC / Go) that can't install a Rust tracing subscriber still receives the kernel's databricks*-targeted log events, routed into the host's own logger instead of only reaching stderr via kernel_init_logging. A process-global KernelLogLayer captures kernel events, filters foreign targets (hyper/rustls cache off; kernel callsites re-evaluate for the dynamic level), formats message+fields, and enqueues onto a bounded channel (drop-on-full — logs are advisory and never back-pressure a kernel hot path). A dedicated drain thread delivers each record to the callback with borrowed C strings, off the tokio workers so a slow host callback can't stall query execution. The level parameter mirrors kernel_init_logging's precedence — an explicit recognised level wins, else RUST_LOG, else the warn default — so a host that maps its own logger level (Go's DATABRICKS_LOG_LEVEL) filters on that one knob rather than only RUST_LOG. Robustness: the callback pointer uses the C-unwind ABI and the drain thread wraps each invocation in catch_unwind, so a panicking host callback poisons the sink (delivery stops) instead of aborting the process at the boundary. Drop-on-full loss is observable — a DROPPED counter plus a synthetic 'N dropped' line emitted through the callback on recovery, and a kernel_logging_stats(installed, dropped) accessor (parity with the napi bridge). Install attempts set_global_default first and only spawns the drain thread if it wins the one global subscriber, so losing the mutual-exclusion race to kernel_init_logging never leaks an idle thread; a drain-thread spawn failure is reported distinctly from the benign already-installed case. Mutually exclusive with kernel_init_logging (one process-global subscriber, first-writer-wins; the other returns Internal); a NULL callback is rejected with InvalidArgument. Tests: logging unit tests (severity ordering, level gating, RUST_LOG/explicit precedence, target-prefix drift guard, field rendering, catch_unwind containment); an end-to-end integration binary (tests/v0_c_abi_log_callback.rs) that emits a real tracing event and asserts the callback received it with message + fields, the ctx pointer round-trips verbatim, and stats report installed/zero-dropped — kept a separate binary so its process-global subscriber doesn't perturb the klog unit tests; and C smoke cases (NULL-cb rejection, strict Internal mutual-exclusion assert, NULL-safe stats). Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- NEXT_CHANGELOG.md | 12 + include/databricks_kernel.h | 62 +++ src/c_abi/logging.rs | 866 +++++++++++++++++++++++++++++++++ src/c_abi/mod.rs | 1 + tests/c/session_smoke.c | 47 ++ tests/v0_c_abi_log_callback.rs | 148 ++++++ 6 files changed, 1136 insertions(+) create mode 100644 src/c_abi/logging.rs create mode 100644 tests/v0_c_abi_log_callback.rs diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 0aed0581..acd16531 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -38,6 +38,18 @@ changes go in their respective binding's NEXT_CHANGELOG. (maps to `ResultConfig::cloudfetch_enabled`); `false` forces the inline-Arrow path (`can_cloud_download=false`) for all result sizes. `None` (unset) keeps the kernel default (on). +- C ABI: `kernel_set_log_callback(cb, ctx, level)` + the `kernel_log_callback` + typedef — a reverse-call log sink so a C-ABI host (ODBC / Go) that can't + install a Rust `tracing` subscriber still receives the kernel's + `databricks*`-targeted log events, routed into its own logger instead of only + reaching stderr via `kernel_init_logging`. Events are captured by a + process-global layer, filtered by `level` (explicit level > `RUST_LOG` > the + `warn` default — the same precedence as `kernel_init_logging`, so a host maps + one knob), enqueued on a bounded channel (drop-on-full — logs never + back-pressure a kernel hot path), and delivered from a dedicated drain thread. + Mutually exclusive with `kernel_init_logging` (one process-global subscriber; + the first to install wins, the other returns `Internal`); a NULL callback is + rejected with `InvalidArgument`. ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 050d5f85..4408ca8c 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -306,6 +306,68 @@ KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* co * subscriber was already installed (no kernel subscriber installed). */ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); +/* ─── Log callback (reverse-call) ───────────────────────────────────── + * + * A host that links the kernel crate directly (pyo3 / napi) bridges the + * kernel's tracing output into its own logger in-process. A C-ABI consumer + * can't install a Rust subscriber, so this is the reverse-call path: register + * a callback the kernel invokes with each `databricks*`-targeted log event, so + * kernel-internal diagnostics flow into the host's logger instead of only + * reaching stderr via kernel_init_logging. + * + * The callback fires from the kernel's log-drain thread (NOT a query worker), + * so it MUST be thread-safe. It SHOULD NOT unwind: the kernel guards each call + * with catch_unwind (the callback pointer uses Rust's C-unwind ABI), so a + * panicking callback poisons the sink and stops delivering rather than aborting + * the process — but subsequent logs are then silently dropped, so a well-behaved + * callback must still not throw across the boundary. It MUST NOT call back into + * any kernel_* entry point: a reentrant blocking kernel_* call from this thread + * is NOT rejected (that guard only covers calls from a kernel worker) — it would + * stall the drain thread and drop queued logs. `ctx` + * is passed back verbatim on every call and must stay valid for the process + * lifetime. `level` (the callback arg) is 1=ERROR..5=TRACE; `target` and + * `message` are valid only for the duration of the call — copy them out. + * Records are enqueued on a bounded channel and DROPPED on overflow (logs are + * advisory and never back-pressure a kernel hot path); the drop count is + * observable via kernel_logging_stats and a synthetic "N dropped" line the + * drain thread emits through the callback on recovery. + * + * The `level` PARAMETER (OFF/ERROR/WARN/INFO/DEBUG/TRACE, case-insensitive, or + * NULL) sets the forward threshold with the SAME precedence as + * kernel_init_logging: an explicit recognised level wins, else RUST_LOG. A host + * that maps its own logger level (Go's DATABRICKS_LOG_LEVEL) passes it here so + * the callback filters on that one knob rather than only RUST_LOG. When neither + * resolves (NULL/unrecognised AND no matching RUST_LOG) the current threshold + * is left UNCHANGED — the warn default on the first call, or the + * previously-set level on a re-registration. + * + * Mutually exclusive with kernel_init_logging: both install the one + * process-global tracing subscriber. kernel_set_log_callback returns Internal + * (with a stored last error) if a global subscriber was already installed, or + * if it won the subscriber but the log-drain thread could not be started (the + * two cases carry distinct error messages); install exactly ONE of the two. + * Passing a NULL `cb` returns InvalidArgument (there is no detach in v0). */ +typedef void (*kernel_log_callback)(void* ctx, int level, const char* target, + const char* message); +KernelStatusCode kernel_set_log_callback(kernel_log_callback cb, void* ctx, + const char* level); + +/* Report the log-callback bridge's health, so a host can distinguish "kernel + * logs are quiet" from "kernel logs are being dropped / the sink died / never + * installed". Writes to each non-NULL out-param (a NULL out-param is skipped): + * - `installed`: true iff kernel logs are CURRENTLY delivering — the callback + * won the process-global subscriber AND the sink is not poisoned. A callback + * that unwinds poisons the sink (delivery stops), which reads false here even + * though the subscriber is still installed; registering a new callback clears + * the poison and flips this back to true. + * - `dropped`: cumulative kernel log records dropped AFTER install — because + * the bounded delivery channel was full (slow callback) or the sink was + * poisoned by a callback that unwound. Does NOT count the drain-thread-never- + * started case (a spawn failure leaves no channel to overflow); there + * `installed` reads false and kernel_set_log_callback returned Internal. + * Never fails; safe to poll at any time. */ +void kernel_logging_stats(bool* installed, uint64_t* dropped); + /* ─── Proxy / TLS (optional) ────────────────────────────────────────── * * All optional; defaults are: no explicit proxy (reqwest honours diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs new file mode 100644 index 00000000..0bb6a015 --- /dev/null +++ b/src/c_abi/logging.rs @@ -0,0 +1,866 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `tracing` → C-callback log bridge for C-ABI (ODBC / Go) consumers. +//! +//! The pyo3 and napi bindings forward the kernel's `tracing` output into the +//! host language's logger **in-process** (they link the kernel crate directly, +//! so they can install a `tracing` `Subscriber` / `log` sink in the kernel's +//! address space — see `napi/src/logger.rs`, `pyo3/src/logging.rs`). A C-ABI +//! consumer can't do that: it reaches the kernel only across the C boundary, +//! and its only kernel-log path today is `kernel_init_logging`'s +//! `RUST_LOG` → stderr subscriber. This module adds the missing reverse-call +//! path: a host registers a C callback (`kernel_set_log_callback`) that the +//! kernel invokes with each `databricks*`-targeted event. +//! +//! ## Shape (mirrors the napi bridge) +//! +//! - [`kernel_set_log_callback`] installs a process-global [`KernelLogLayer`] +//! (once) and records the `(callback, ctx)` sink. The layer captures +//! `databricks*` events, filters by an atomic level, formats each into a +//! [`Record`], and pushes it onto a **bounded** channel (drop-on-full — logs +//! are advisory and must never block or back-pressure a kernel hot path). +//! - A dedicated drain thread pulls records and invokes the C callback once per +//! record with borrowed C strings (valid only for the call). +//! +//! ## Threading & safety contract (documented in `databricks_kernel.h`) +//! +//! The callback fires from the drain thread (never a kernel tokio worker), so +//! the host callback must be thread-safe. It must NOT call back into any +//! `kernel_*` entry point: unlike a call from a tokio worker (which +//! `block_on_ffi` rejects), the drain thread is a plain `std::thread`, so a +//! reentrant blocking `kernel_*` call is NOT caught — it would run its own +//! `block_on`, stalling the drain thread and dropping queued logs. A callback +//! that unwinds is contained: the type is `extern "C-unwind"` and the drain +//! thread wraps every invocation in `catch_unwind`, so a panicking host callback +//! poisons the sink (delivery stops) rather than aborting the process — but a +//! well-behaved callback still must not unwind, since poisoning silently drops +//! all subsequent logs. +//! +//! ## Mutual exclusion with `kernel_init_logging` +//! +//! Both this and `kernel_init_logging` install the one process-global `tracing` +//! subscriber; only the first `set_global_default` wins. If a global subscriber +//! was already installed, `kernel_set_log_callback` returns `Internal` (with a +//! stored last error), exactly as `kernel_init_logging` does for the reverse — +//! a C consumer picks ONE of the two. Last-writer-wins for the sink itself +//! (the callback slot is refreshed on every call). + +// The callback type mirrors the C typedef name `kernel_log_callback` (snake +// case) so the Rust and header names read identically, matching the rest of the +// C-ABI surface (`kernel_*_t` handles). +#![allow(non_camel_case_types)] + +use super::KernelStatusCode; +use crate::kernel_error::{Error, ErrorCode}; +use std::ffi::{c_void, CString}; +use std::os::raw::{c_char, c_int}; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; +use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; +use std::sync::{Mutex, Once, OnceLock}; +use tracing::field::{Field, Visit}; +use tracing::level_filters::LevelFilter; +use tracing::subscriber::Interest; +use tracing::{Event, Level, Metadata, Subscriber}; +use tracing_subscriber::layer::{Context, Filter, Layer, SubscriberExt}; +use tracing_subscriber::registry::LookupSpan; + +/// Host log sink: a C function pointer plus an opaque host context passed back +/// verbatim on every call. `level` is 1=ERROR..5=TRACE (mirrors the bridge's +/// numeric severity); `target` and `message` are NUL-terminated C strings valid +/// only for the duration of the call. +/// +/// The ABI is `C-unwind`, not plain `C`: a plain `extern "C"` fn that panics +/// aborts at its OWN boundary (Rust ≥ 1.81), so an outer `catch_unwind` around +/// the call could never contain it. `C-unwind` lets a panic propagate across the +/// boundary so `invoke_callback`'s `catch_unwind` can catch a misbehaving host +/// callback and poison the sink instead of aborting the process. The C +/// representation is identical (`void (*)(void*, int, const char*, const char*)`), +/// and non-unwinding C / Go-with-recover callbacks are unaffected. +pub type kernel_log_callback = extern "C-unwind" fn( + ctx: *mut c_void, + level: c_int, + target: *const c_char, + message: *const c_char, +); + +/// A drained log record awaiting delivery to the host callback. +struct Record { + level: c_int, + /// `&'static str`: `tracing` metadata targets are static, so this avoids a + /// per-record heap allocation on chatty DEBUG/TRACE workloads (the message, + /// built by the field visitor, still owns its `String`). + target: &'static str, + message: String, +} + +/// The registered sink. `ctx` is stored as a `usize` so the struct is `Send` +/// (the host owns the pointer and guarantees its validity until it detaches); +/// the kernel treats it as opaque and never dereferences it. +struct Sink { + cb: kernel_log_callback, + ctx: usize, +} + +const CHANNEL_CAPACITY: usize = 4096; + +const LEVEL_OFF: u8 = 0; +const LEVEL_ERROR: u8 = 1; +const LEVEL_WARN: u8 = 2; +const LEVEL_INFO: u8 = 3; +const LEVEL_DEBUG: u8 = 4; +const LEVEL_TRACE: u8 = 5; + +/// Numeric severity, low = more severe. `0` means "off / emit nothing". +static LEVEL: AtomicU8 = AtomicU8::new(LEVEL_WARN); + +/// Count of log records dropped because the bounded channel was full (a slow +/// host callback) or the drain thread stopped. Surfaced via +/// [`kernel_logging_stats`] and via a synthetic "dropped N" line the drain +/// thread emits on recovery, so drop-on-full loss is observable rather than +/// silent (parity with the napi bridge's `DROPPED`). +static DROPPED: AtomicU64 = AtomicU64::new(0); + +/// Set if the host callback ever unwound (panicked) across the FFI boundary. +/// The `extern "C-unwind"` type lets the panic propagate so the drain thread's +/// `catch_unwind` catches it (a plain `extern "C"` would instead abort the +/// process at the callback's own boundary); we record it here and stop +/// delivering — a callback that panics once is assumed to keep panicking, so we +/// protect the process rather than re-invoke it. Surfaced via +/// [`kernel_logging_stats`] (`installed` reads `false` while poisoned). Cleared +/// when a NEW callback is registered, so a host can recover by re-installing. +static SINK_POISONED: AtomicBool = AtomicBool::new(false); + +const INSTALL_PENDING: u8 = 0; +const INSTALL_OK: u8 = 1; +/// Lost the one-global-subscriber race (e.g. `kernel_init_logging` won) — a +/// benign outcome; the host picks one of the two logging routes. +const INSTALL_ALREADY_SET: u8 = 2; +/// Won the subscriber but the OS refused to start the drain thread +/// (EAGAIN/ENOMEM) — a real failure the host should surface distinctly. +const INSTALL_SPAWN_FAILED: u8 = 3; + +/// Outcome of the one-time subscriber install. Anything other than `INSTALL_OK` +/// means kernel logs won't reach the callback; the two failure discriminants +/// let the caller tell the benign already-installed case from a spawn failure. +static INSTALL_STATUS: AtomicU8 = AtomicU8::new(INSTALL_PENDING); + +/// The drain-thread spawn error string, populated only on `INSTALL_SPAWN_FAILED` +/// so the returned `Internal` can carry the underlying OS error for triage. +static SPAWN_ERROR: OnceLock>> = OnceLock::new(); + +/// Producer end, published once after the drain thread is confirmed running so +/// a live producer never outlives its consumer. +static SENDER: OnceLock> = OnceLock::new(); + +/// Current sink. Last-writer-wins; read by the drain thread per record. +static SINK: OnceLock>> = OnceLock::new(); + +/// Guards the one-time subscriber install + channel + drain-thread spawn. +static INSTALL: Once = Once::new(); + +fn severity(level: &Level) -> u8 { + match *level { + Level::ERROR => LEVEL_ERROR, + Level::WARN => LEVEL_WARN, + Level::INFO => LEVEL_INFO, + Level::DEBUG => LEVEL_DEBUG, + Level::TRACE => LEVEL_TRACE, + } +} + +/// Parse a bare level word into the numeric severity, unknown → `None`. +fn parse_level_word(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "off" | "none" | "silent" => Some(LEVEL_OFF), + "error" => Some(LEVEL_ERROR), + "warn" | "warning" => Some(LEVEL_WARN), + "info" => Some(LEVEL_INFO), + "debug" => Some(LEVEL_DEBUG), + "trace" => Some(LEVEL_TRACE), + _ => None, + } +} + +/// Derive the callback's level from a `RUST_LOG`-style directive string, matching +/// the level the stderr path (`kernel_init_logging`) would apply so the two routes +/// filter identically. Recognises a bare level (`debug`), the kernel target's +/// directive (`databricks::sql::kernel=debug` / `databricks_sql_kernel=debug`), or +/// a global fallback among comma-separated directives. Returns `None` (keep the +/// current default) if nothing matches. +fn level_from_rust_log(rust_log: &str) -> Option { + let mut global: Option = None; + for directive in rust_log.split(',') { + let d = directive.trim(); + if d.is_empty() { + continue; + } + match d.split_once('=') { + Some((target, level)) => { + if target.trim().starts_with("databricks") { + if let Some(l) = parse_level_word(level) { + return Some(l); // the kernel target's own directive wins + } + } + } + None => { + // A bare word is either a global level (`debug`) or a bare target; + // only treat it as a level if it parses as one. + if let Some(l) = parse_level_word(d) { + global = Some(l); + } + } + } + } + global +} + +/// Returns whether an event at `level` should currently be forwarded. +fn should_emit(level: &Level) -> bool { + let configured = LEVEL.load(Ordering::Relaxed); + configured != LEVEL_OFF && severity(level) <= configured +} + +/// Targets the bridge forwards: the `klog!` shim's `databricks::sql::kernel` +/// and kernel module paths (`databricks_sql_kernel::*`). A raw `starts_with` +/// (not a `::`-segmented filter) so the underscore module-path variants match. +fn is_kernel_target(target: &str) -> bool { + target.starts_with("databricks") +} + +/// The configured level as a `tracing` [`LevelFilter`], for `max_level_hint` so +/// the process-global gate tracks the kernel level instead of pinning at TRACE. +fn current_level_filter() -> LevelFilter { + match LEVEL.load(Ordering::Relaxed) { + LEVEL_OFF => LevelFilter::OFF, + LEVEL_ERROR => LevelFilter::ERROR, + LEVEL_WARN => LevelFilter::WARN, + LEVEL_INFO => LevelFilter::INFO, + LEVEL_DEBUG => LevelFilter::DEBUG, + _ => LevelFilter::TRACE, + } +} + +/// Per-callsite interest: kernel callsites re-evaluate per event (`sometimes`, +/// for the dynamic level); foreign callsites cache off forever (`never`), so +/// `hyper`/`rustls`/etc. never dispatch. +fn callsite_interest_for(target: &str) -> Interest { + if is_kernel_target(target) { + Interest::sometimes() + } else { + Interest::never() + } +} + +/// Collects a `tracing` event's `message` plus structured fields into one line: +/// `" key1=v1 key2=v2"`. +#[derive(Default)] +struct MessageVisitor { + message: String, + fields: String, +} + +impl MessageVisitor { + fn finish(self) -> String { + if self.fields.is_empty() { + self.message + } else if self.message.is_empty() { + self.fields + } else { + format!("{} {}", self.message, self.fields) + } + } + + fn push_field(&mut self, name: &str, value: String) { + if !self.fields.is_empty() { + self.fields.push(' '); + } + self.fields.push_str(name); + self.fields.push('='); + self.fields.push_str(&value); + } +} + +impl Visit for MessageVisitor { + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + self.message = format!("{value:?}"); + } else { + self.push_field(field.name(), format!("{value:?}")); + } + } + + fn record_str(&mut self, field: &Field, value: &str) { + if field.name() == "message" { + self.message = value.to_owned(); + } else { + self.push_field(field.name(), value.to_owned()); + } + } +} + +/// Process-global `tracing` Layer: formats each kernel event and enqueues it +/// (drop-on-full). The per-layer [`KernelFilter`] already excludes foreign +/// targets and below-level events. +struct KernelLogLayer; + +/// Per-layer filter gating the bridge: foreign callsites cache off, kernel +/// callsites re-evaluate per event, and `max_level_hint` tracks the level. +struct KernelFilter; + +impl Filter for KernelFilter { + fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest { + callsite_interest_for(meta.target()) + } + + fn enabled(&self, meta: &Metadata<'_>, _ctx: &Context<'_, S>) -> bool { + is_kernel_target(meta.target()) && should_emit(meta.level()) + } + + fn max_level_hint(&self) -> Option { + Some(current_level_filter()) + } +} + +impl Layer for KernelLogLayer +where + S: Subscriber + for<'a> LookupSpan<'a>, +{ + fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { + let Some(tx) = SENDER.get() else { + return; + }; + let meta = event.metadata(); + let mut visitor = MessageVisitor::default(); + event.record(&mut visitor); + let record = Record { + level: severity(meta.level()) as c_int, + target: meta.target(), + message: visitor.finish(), + }; + // Drop-on-full / disconnected: logs are advisory, never block a kernel + // task on a slow host callback. Count the loss so it's observable (via + // kernel_logging_stats and the drain thread's synthetic recovery line) + // rather than vanishing silently. + if tx.try_send(record).is_err() { + DROPPED.fetch_add(1, Ordering::Relaxed); + } + } +} + +/// Invoke the host callback once, guarded against an unwind. A panic crossing +/// `extern "C"` aborts the process (Rust ≥ 1.81), so a host callback that +/// unwinds must be contained here — this is the same `catch_unwind` guard every +/// other FFI boundary in the crate uses (`block_on_ffi`, `catch_ffi`). Returns +/// `false` if the callback unwound, so the caller can poison the sink. +fn invoke_callback( + cb: kernel_log_callback, + ctx: usize, + level: c_int, + target: &str, + message: &str, +) -> bool { + // Interior NULs can't appear in a C string; on the rare event whose text + // contains one, TRUNCATE at the first NUL rather than replacing the whole + // string with a placeholder — the informative prefix (up to the NUL) is + // preserved. CString::new only fails on an interior NUL, so on error rebuild + // from the bytes up to it (which cannot themselves contain a NUL → unwrap is + // infallible). + let to_cstring = |s: &str| { + CString::new(s).unwrap_or_else(|e| { + let n = e.nul_position(); + CString::new(&s.as_bytes()[..n]).unwrap() + }) + }; + let target = to_cstring(target); + let message = to_cstring(message); + catch_unwind(AssertUnwindSafe(|| { + cb(ctx as *mut c_void, level, target.as_ptr(), message.as_ptr()); + })) + .is_ok() +} + +/// Drain loop (own OS thread): pull one record at a time and invoke the host +/// callback with borrowed C strings. Runs off the kernel's tokio workers so a +/// slow callback can't stall query execution. +fn drain_loop(rx: Receiver) { + // Drop count already reported to the host, so we only emit a synthetic + // "dropped N" notice for the delta since the last delivered record. + let mut reported_drops: u64 = 0; + // `recv` errors only once the (process-global) sender is dropped, which + // never happens in practice; exit cleanly if the channel is torn down. + while let Ok(record) = rx.recv() { + // A callback that unwound once is assumed to keep unwinding; stop + // delivering to protect the process (the loss is counted + surfaced via + // kernel_logging_stats). Keep draining so the channel doesn't wedge. + if SINK_POISONED.load(Ordering::Relaxed) { + DROPPED.fetch_add(1, Ordering::Relaxed); + continue; + } + let Some(sink_lock) = SINK.get() else { + continue; + }; + // Copy the sink out under the lock (cheap: a fn pointer + usize) so the + // callback runs without holding the mutex — a reentrant setter can't + // deadlock, and a slow callback can't block a level/sink update. + let sink = match sink_lock.lock() { + Ok(g) => g.as_ref().map(|s| (s.cb, s.ctx)), + Err(_) => None, + }; + let Some((cb, ctx)) = sink else { + continue; + }; + // Surface any records dropped since the last delivery as one synthetic + // WARN line through the callback itself, so a host that only reads the + // callback stream still learns it missed events (kernel_logging_stats + // carries the cumulative count for a host that polls). + let dropped = DROPPED.load(Ordering::Relaxed); + if dropped > reported_drops { + let notice = format!( + "{} kernel log record(s) dropped (slow log callback); increase callback throughput", + dropped - reported_drops + ); + reported_drops = dropped; + if !invoke_callback( + cb, + ctx, + LEVEL_WARN as c_int, + is_kernel_target_str(), + ¬ice, + ) { + SINK_POISONED.store(true, Ordering::Relaxed); + continue; + } + } + if !invoke_callback(cb, ctx, record.level, record.target, &record.message) { + SINK_POISONED.store(true, Ordering::Relaxed); + } + } +} + +/// The kernel log target as a plain `&str`, for the synthetic drop-notice line +/// so it carries the same target as real kernel events. +fn is_kernel_target_str() -> &'static str { + crate::klog::KERNEL_LOG_TARGET +} + +/// Resolve the callback's numeric level from the caller's explicit `level` +/// argument, mirroring `kernel_init_logging`'s precedence so the two C-ABI +/// logging routes filter identically: +/// +/// 1. an explicit, recognised `level` word wins (e.g. Go's driver level +/// mapped through `DATABRICKS_LOG_LEVEL`); +/// 2. otherwise a `RUST_LOG` directive (bare or `databricks*=…`); +/// 3. otherwise the current default (`warn`), left untouched. +/// +/// This is what keeps the callback on the one-knob contract PECOBLR-3650 +/// established: `kernel_init_logging` maps the driver level to a level string, +/// and the callback path must honour that same string rather than only +/// `RUST_LOG` — otherwise a host at `DATABRICKS_LOG_LEVEL=debug` (but no +/// `RUST_LOG`) would silently drop kernel debug lines. +/// +/// Note this resolves the same *level*, but the target matching differs from +/// `kernel_init_logging`: that path builds an `EnvFilter` (`::`-segment match on +/// `databricks::sql::kernel`), whereas the layer here matches the broader +/// `databricks` prefix (see `is_kernel_target`). So for a `RUST_LOG` target +/// directive the two routes select the same threshold but not necessarily the +/// identical event set. +fn resolve_callback_level(explicit: Option<&str>) -> Option { + if let Some(word) = explicit { + // A recognised explicit level always wins. "off" is honoured (the host + // asked for silence); an unrecognised word falls through to RUST_LOG. + if let Some(l) = parse_level_word(word) { + return Some(l); + } + } + if let Ok(rust_log) = std::env::var("RUST_LOG") { + if let Some(l) = level_from_rust_log(&rust_log) { + return Some(l); + } + } + None +} + +/// Install (process-wide) a callback that receives kernel `databricks*` +/// `tracing` events. `ctx` is passed back verbatim on every call. Passing a +/// null `cb` is rejected with `InvalidArgument` (to detach a sink, the design +/// would grow an explicit detach — v0 keeps install-only). +/// +/// `level` (a NUL-terminated `OFF`/`ERROR`/`WARN`/`INFO`/`DEBUG`/`TRACE` +/// string, case-insensitive, or NULL) sets the forward threshold with the same +/// precedence as `kernel_init_logging`: an explicit recognised level wins, else +/// `RUST_LOG`. A host that maps its own logger level (Go's +/// `DATABRICKS_LOG_LEVEL`) passes it here so the callback filters on the one +/// knob rather than only `RUST_LOG`. When neither resolves (NULL / unrecognised +/// level AND no matching `RUST_LOG`) the current threshold is LEFT UNCHANGED — +/// which is the static `warn` default on the first-ever call, but the +/// previously-set level on a re-registration (the level is process-global and +/// last-writer-wins only when a writer actually resolves one). +/// +/// Returns `Internal` (with a stored last error) if a global `tracing` +/// subscriber was already installed (e.g. by `kernel_init_logging`) — the two +/// are mutually exclusive; a C consumer installs exactly one. +/// +/// # Safety +/// `cb` must be a valid function pointer that is thread-safe, does not unwind, +/// and does not call back into any `kernel_*` entry point. `ctx` must remain +/// valid until the process exits (there is no detach in v0). `level`, if +/// non-null, must be a NUL-terminated C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_set_log_callback( + cb: Option, + ctx: *mut c_void, + level: *const c_char, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(cb) = cb else { + crate::c_abi::error::store_error( + Error::invalid_argument().message("kernel_set_log_callback: cb must not be null"), + ); + return KernelStatusCode::InvalidArgument; + }; + + // Resolve the forward threshold: explicit `level` (the host's mapped logger + // level) wins, else RUST_LOG, else the WARN default is left in place. A + // non-UTF-8 `level` is treated as absent (best-effort, like + // kernel_init_logging's level arg) rather than a hard error. This keeps the + // callback filtering on the same knob as the stderr path. + let explicit_level = if level.is_null() { + None + } else { + std::ffi::CStr::from_ptr(level).to_str().ok() + }; + // Track whether the level actually changed so we only rebuild the (process- + // wide, lock-taking) callsite interest cache when it matters — a same-level + // ctx refresh or a call that loses the subscriber race shouldn't serialize + // all logging dispatch. + let mut level_changed = false; + if let Some(resolved) = resolve_callback_level(explicit_level) { + level_changed = LEVEL.swap(resolved, Ordering::Relaxed) != resolved; + } + + // Record / refresh the sink (last writer wins). Clear any prior poison: a + // callback that unwound poisons the sink (drain_loop stops delivering to + // protect the process), but registering a NEW callback is an explicit + // request for a fresh start, so honour the last-writer-wins contract and let + // delivery resume. The drain thread reads the flag per record, so clearing + // it here (before releasing the SINK lock) is immediately effective. + let sink = SINK.get_or_init(|| Mutex::new(None)); + if let Ok(mut guard) = sink.lock() { + *guard = Some(Sink { + cb, + ctx: ctx as usize, + }); + SINK_POISONED.store(false, Ordering::Relaxed); + } + + // Install the process-global subscriber + drain thread exactly once. + // + // Order matters: attempt `set_global_default` FIRST, and only spawn the + // drain thread if we win the one global subscriber. The common sequence is + // "host called kernel_init_logging, a layer later calls this" — there we + // lose the race and must NOT leave a drain thread parked on recv() forever + // (an idle-thread leak). We use a plain Once-guarded closure rather than the + // channel/thread first. + let mut did_install = false; + INSTALL.call_once(|| { + did_install = true; + let subscriber = + tracing_subscriber::registry().with(KernelLogLayer.with_filter(KernelFilter)); + if tracing::subscriber::set_global_default(subscriber).is_err() { + // Another global subscriber (e.g. kernel_init_logging) won. Do not + // spawn a drain thread — SENDER stays unset, so on_event's `let Some + // (tx)` short-circuits and nothing is enqueued. + INSTALL_STATUS.store(INSTALL_ALREADY_SET, Ordering::Release); + return; + } + // We own the subscriber; now stand up the delivery path. Spawn the drain + // thread and publish SENDER only after it is confirmed running, so a + // live producer never outlives its consumer. + let (tx, rx) = sync_channel::(CHANNEL_CAPACITY); + match std::thread::Builder::new() + .name("kernel-log-drain".to_owned()) + .spawn(move || drain_loop(rx)) + { + Ok(_) => { + let _ = SENDER.set(tx); + INSTALL_STATUS.store(INSTALL_OK, Ordering::Release); + } + Err(e) => { + // We hold the subscriber but have no consumer; leave SENDER + // unset (events short-circuit). Record the OS error distinctly + // so on-call can tell a spawn failure (EAGAIN/ENOMEM) from the + // benign "already installed" case. Use `.lock().ok()` (not + // `.unwrap()`) so a poisoned mutex can't panic across the FFI + // boundary — the message is best-effort diagnostics. + if let Ok(mut guard) = SPAWN_ERROR.get_or_init(|| Mutex::new(None)).lock() { + *guard = Some(e.to_string()); + } + INSTALL_STATUS.store(INSTALL_SPAWN_FAILED, Ordering::Release); + } + } + }); + // Rebuild the process-wide callsite interest cache only when it can matter: + // on the install that set our filter, or when a later call changed LEVEL. + // set_global_default rebuilds on its own, but the level may have been set + // before install, and a re-level after install needs a rebuild too; a + // same-level ctx refresh or a race-loss does not (the rebuild takes the + // global callsite lock and re-evaluates every callsite in the binary). + if did_install || level_changed { + tracing::callsite::rebuild_interest_cache(); + } + + match INSTALL_STATUS.load(Ordering::Acquire) { + INSTALL_OK => KernelStatusCode::Success, + INSTALL_SPAWN_FAILED => { + let detail = SPAWN_ERROR + .get() + .and_then(|m| m.lock().ok().and_then(|g| g.clone())) + .unwrap_or_else(|| "unknown".to_owned()); + crate::c_abi::error::store_and_code(Error::new( + ErrorCode::Internal, + format!( + "kernel_set_log_callback: the log-drain thread could not be started ({detail}); \ + kernel logs will not reach the callback" + ), + )) + } + // INSTALL_ALREADY_SET (or a stale PENDING, which can't happen after + // call_once): a global subscriber was already installed. + _ => crate::c_abi::error::store_and_code(Error::new( + ErrorCode::Internal, + "kernel_set_log_callback: a global tracing subscriber was already installed \ + (e.g. via kernel_init_logging); kernel logs will not reach the callback. \ + Install exactly one of kernel_set_log_callback / kernel_init_logging.", + )), + } +} + +/// Report the log-callback bridge's health so a host can tell whether kernel +/// logs are actually flowing. Writes to each (optional) out-param: +/// +/// - `installed`: `true` iff kernel logs are CURRENTLY being delivered — this +/// callback won the process-global subscriber AND the sink is not poisoned. +/// A callback that unwound poisons the sink (delivery stops); this then +/// reads `false` even though the subscriber is still installed, so a host +/// polling it sees a dead sink rather than a silent no-op. Registering a new +/// callback clears the poison and flips this back to `true`. +/// - `dropped`: cumulative count of kernel log records dropped after the +/// subscriber was installed — because the bounded delivery channel was full +/// (a slow callback) or the sink was poisoned by a callback that unwound. +/// This does NOT cover the drain-thread-never-started case (a spawn failure +/// leaves no channel to overflow); there `installed` reads `false` and +/// `kernel_set_log_callback` returned `Internal` with the spawn error. +/// +/// A NULL out-param is skipped. Never fails — a host can poll it to distinguish +/// "logs are quiet" from "logs are being dropped / the sink died / never +/// installed" (parity with the napi binding's `kernelLoggingStats()`). +/// +/// # Safety +/// Each non-null out-param must point to a writable `bool` / `uint64_t`. +#[no_mangle] +pub unsafe extern "C" fn kernel_logging_stats(installed: *mut bool, dropped: *mut u64) { + if !installed.is_null() { + // "Currently delivering": won the subscriber AND not poisoned. A poisoned + // sink is installed-but-dead, which must not read as healthy. + *installed = INSTALL_STATUS.load(Ordering::Acquire) == INSTALL_OK + && !SINK_POISONED.load(Ordering::Relaxed); + } + if !dropped.is_null() { + *dropped = DROPPED.load(Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // A well-behaved callback returns true (delivered); a callback that unwinds + // is contained by catch_unwind and returns false (so the drain loop poisons + // the sink) rather than aborting the process at the extern "C" boundary. + extern "C-unwind" fn ok_cb( + _ctx: *mut c_void, + _lvl: c_int, + _t: *const c_char, + _m: *const c_char, + ) { + } + extern "C-unwind" fn panic_cb( + _ctx: *mut c_void, + _lvl: c_int, + _t: *const c_char, + _m: *const c_char, + ) { + panic!("callback boom"); + } + + #[test] + fn invoke_callback_delivers_and_contains_unwind() { + assert!( + invoke_callback( + ok_cb, + 0, + LEVEL_WARN as c_int, + "databricks::sql::kernel", + "ok" + ), + "a normal callback should report delivered" + ); + assert!( + !invoke_callback( + panic_cb, + 0, + LEVEL_ERROR as c_int, + "databricks::sql::kernel", + "boom" + ), + "an unwinding callback must be caught and report not-delivered, not abort" + ); + } + + // A message containing an interior NUL is truncated at the NUL (the prefix is + // preserved), not replaced wholesale with a placeholder. We capture what the + // callback receives via a thread-local so the test needs no global state. + thread_local! { + static LAST_MSG: std::cell::RefCell = const { std::cell::RefCell::new(String::new()) }; + } + extern "C-unwind" fn capture_msg_cb( + _ctx: *mut c_void, + _lvl: c_int, + _t: *const c_char, + m: *const c_char, + ) { + let s = unsafe { std::ffi::CStr::from_ptr(m) } + .to_string_lossy() + .into_owned(); + LAST_MSG.with(|c| *c.borrow_mut() = s); + } + + #[test] + fn invoke_callback_truncates_interior_nul_keeps_prefix() { + assert!(invoke_callback( + capture_msg_cb, + 0, + LEVEL_WARN as c_int, + "databricks::sql::kernel", + "keep-this\0drop-this", + )); + LAST_MSG.with(|c| { + assert_eq!( + *c.borrow(), + "keep-this", + "interior NUL should truncate, preserving the prefix" + ) + }); + } + + #[test] + fn severity_ordering_is_low_is_severe() { + assert!(severity(&Level::ERROR) < severity(&Level::WARN)); + assert!(severity(&Level::WARN) < severity(&Level::INFO)); + assert!(severity(&Level::INFO) < severity(&Level::DEBUG)); + assert!(severity(&Level::DEBUG) < severity(&Level::TRACE)); + } + + #[test] + fn should_emit_respects_configured_level() { + LEVEL.store(LEVEL_INFO, Ordering::Relaxed); + assert!(should_emit(&Level::ERROR)); + assert!(should_emit(&Level::INFO)); + assert!(!should_emit(&Level::DEBUG)); + LEVEL.store(LEVEL_OFF, Ordering::Relaxed); + assert!(!should_emit(&Level::ERROR)); + LEVEL.store(LEVEL_WARN, Ordering::Relaxed); // restore + } + + #[test] + fn level_from_rust_log_reads_kernel_and_global_directives() { + // The kernel target's own directive (either spelling) wins. + assert_eq!( + level_from_rust_log("databricks::sql::kernel=debug"), + Some(LEVEL_DEBUG) + ); + assert_eq!( + level_from_rust_log("databricks_sql_kernel=trace"), + Some(LEVEL_TRACE) + ); + // A kernel directive still wins when mixed with foreign ones. + assert_eq!( + level_from_rust_log("hyper=off,databricks::sql::kernel=info,rustls=warn"), + Some(LEVEL_INFO) + ); + // A bare global level applies when no kernel directive is present. + assert_eq!(level_from_rust_log("debug"), Some(LEVEL_DEBUG)); + // Nothing recognisable → None (keep the default). + assert_eq!(level_from_rust_log("hyper=warn"), None); + assert_eq!(level_from_rust_log(""), None); + } + + #[test] + fn resolve_callback_level_prefers_explicit_over_rust_log() { + // An explicit, recognised level wins outright — this is the one-knob + // path (Go maps DATABRICKS_LOG_LEVEL and passes it in), independent of + // whatever RUST_LOG happens to be. We don't touch the process RUST_LOG + // here (that would race other tests); an explicit level short-circuits + // before RUST_LOG is ever read. + assert_eq!(resolve_callback_level(Some("debug")), Some(LEVEL_DEBUG)); + assert_eq!(resolve_callback_level(Some("OFF")), Some(LEVEL_OFF)); + assert_eq!(resolve_callback_level(Some("Error")), Some(LEVEL_ERROR)); + // An unrecognised explicit word falls through (to RUST_LOG, else None). + // With no kernel/global RUST_LOG directive this yields None regardless + // of the ambient value, so assert only the None-or-Some shape is sane by + // checking a clearly-bogus word doesn't parse as a level itself. + assert_eq!(parse_level_word("not-a-level"), None); + // NULL/absent explicit level defers to RUST_LOG (covered by + // level_from_rust_log tests); nothing recognisable → None (keep default). + } + + #[test] + fn foreign_callsites_cache_off_kernel_callsites_reevaluate() { + assert!(callsite_interest_for("hyper::client::pool").is_never()); + assert!(callsite_interest_for("rustls::conn").is_never()); + assert!(callsite_interest_for("databricks::sql::kernel").is_sometimes()); + assert!(callsite_interest_for("databricks_sql_kernel::session").is_sometimes()); + } + + #[test] + fn visitor_combines_message_and_fields() { + let mut v = MessageVisitor { + message: "hello".to_owned(), + ..Default::default() + }; + v.push_field("statement_id", "abc-123".to_owned()); + assert_eq!(v.finish(), "hello statement_id=abc-123"); + } + + /// Drift guard: the bridge routes on the `databricks` prefix; the kernel + /// stamps every `klog!` with `KERNEL_LOG_TARGET`. If that constant ever + /// changed to a non-`databricks` prefix, kernel logs would silently stop + /// reaching the callback — pin the two together. + #[test] + fn filter_prefix_still_matches_kernel_emit_target() { + assert!(is_kernel_target(crate::klog::KERNEL_LOG_TARGET)); + } + + // NOTE: the end-to-end "MessageVisitor renders a REAL tracing event" test + // lives in `tests/v0_c_abi_log_callback.rs` (a separate binary), NOT here. + // Installing any `tracing` subscriber (even a thread-local `with_default`) + // perturbs the `tracing/log` bridge's global max-level, which the `klog` + // unit tests depend on being untouched — so a subscriber-installing test in + // THIS binary makes `klog::tests` flaky by ordering. This mirrors the + // CONSTRAINT note in `klog.rs`. The pure-predicate tests above (severity / + // should_emit / visitor field-combining / target prefix) need no subscriber + // and stay here. +} diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index b0c8afcc..8a1de83f 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -47,6 +47,7 @@ pub mod cancel; pub mod error; +pub mod logging; pub mod metadata; pub mod result; pub mod session; diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index a7750f88..4427a1b9 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -230,6 +230,49 @@ static void test_init_logging(void) { CHECK(rc == KernelStatusCode_Success, "init_logging twice is safe"); } +/* kernel_set_log_callback: NULL cb is rejected; a real cb installs (or reports + * the mutual-exclusion outcome if init_logging already won the one global + * subscriber). Hermetic — no network, no events forced. The `level` arg is + * exercised as an explicit "WARN" and NULL to cover both precedence paths. */ +static int g_log_calls = 0; +static void count_log_cb(void* ctx, int level, const char* target, const char* message) { + (void)level; + (void)target; + (void)message; + int* counter = (int*)ctx; + if (counter) { + (*counter)++; + } +} + +static void test_log_callback(void) { + KernelStatusCode rc = kernel_set_log_callback(NULL, NULL, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_log_callback(NULL cb) → InvalidArgument"); + + /* This runs AFTER test_init_logging, which already won the one process-global + * subscriber, so the mutual-exclusion contract is deterministic here: the + * callback install must report Internal (not Success, not a silent no-op). + * The explicit "WARN" level arg is accepted regardless. */ + rc = kernel_set_log_callback(count_log_cb, &g_log_calls, "WARN"); + CHECK(rc == KernelStatusCode_Internal, + "set_log_callback after init_logging → Internal (mutual exclusion)"); + + /* A NULL level (defer to RUST_LOG / current) is also accepted; same + * mutual-exclusion outcome on a refresh. */ + rc = kernel_set_log_callback(count_log_cb, &g_log_calls, NULL); + CHECK(rc == KernelStatusCode_Internal, + "set_log_callback(NULL level) after init_logging → Internal"); + + /* kernel_logging_stats never fails and honours NULL out-params. init_logging + * won the subscriber, so the callback did NOT install. */ + bool installed = true; + uint64_t dropped = 123; + kernel_logging_stats(&installed, &dropped); + CHECK(!installed, "logging_stats: callback not installed (init_logging won)"); + kernel_logging_stats(NULL, NULL); /* must not crash on NULL out-params */ + CHECK(true, "logging_stats(NULL, NULL) is safe"); +} + /* is_open null-guards its args. (The true→false behavior is covered by the * in-crate Rust test * `session::is_open_tests::is_open_flips_true_to_false_on_delete`, which can @@ -354,6 +397,10 @@ int main(void) { test_proxy_and_tls_setters(); test_u2m_and_header_setters(); test_init_logging(); + /* After test_init_logging so it wins the one process-global subscriber; the + * callback install then deterministically reports the mutual-exclusion + * outcome (Internal). */ + test_log_callback(); test_is_open_null_guards(); test_submit_stub_rejects(); test_bind_null_handle_rejected(); diff --git a/tests/v0_c_abi_log_callback.rs b/tests/v0_c_abi_log_callback.rs new file mode 100644 index 00000000..3a9cf933 --- /dev/null +++ b/tests/v0_c_abi_log_callback.rs @@ -0,0 +1,148 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! End-to-end delivery test for the `kernel_set_log_callback` reverse-call log +//! bridge. Registers a C callback, emits a kernel `tracing` event on the +//! contract target, and asserts the callback received it with the message and +//! target intact. +//! +//! This lives in its own integration-test binary (NOT a `#[cfg(test)] mod` in +//! `src/c_abi/logging.rs`) on purpose: installing the process-global `tracing` +//! subscriber the bridge needs perturbs the `tracing/log` bridge's global +//! max-level, which the `klog` unit tests depend on being untouched — so a +//! subscriber-installing test in the lib-test binary makes `klog::tests` flaky +//! by ordering. A separate binary has its own global state. Mirrors the +//! CONSTRAINT note in `src/klog.rs`. + +use std::os::raw::{c_char, c_int, c_void}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use databricks_sql_kernel::c_abi::logging::kernel_set_log_callback; +use databricks_sql_kernel::c_abi::KernelStatusCode; + +// Captured (level, target, message) tuples, keyed via a process-global slot the +// callback pushes into. +static CAPTURED: Mutex> = Mutex::new(Vec::new()); +static CALLS: AtomicUsize = AtomicUsize::new(0); +// The `ctx` the kernel passed back on the most recent call, recorded as a usize +// so we can assert the round-trip returns the exact pointer we registered. +static SEEN_CTX: AtomicUsize = AtomicUsize::new(0); + +extern "C-unwind" fn capture_cb( + ctx: *mut c_void, + level: c_int, + target: *const c_char, + message: *const c_char, +) { + CALLS.fetch_add(1, Ordering::SeqCst); + SEEN_CTX.store(ctx as usize, Ordering::SeqCst); + // SAFETY: the bridge passes valid NUL-terminated C strings for the call. + let target = unsafe { std::ffi::CStr::from_ptr(target) } + .to_string_lossy() + .into_owned(); + let message = unsafe { std::ffi::CStr::from_ptr(message) } + .to_string_lossy() + .into_owned(); + CAPTURED.lock().unwrap().push((level, target, message)); +} + +#[test] +fn log_callback_receives_kernel_event_end_to_end() { + // Drive the threshold through the explicit `level` argument (the one-knob + // path a host uses) rather than RUST_LOG, so the test proves the level + // param actually gates delivery. "trace" lets every kernel event through. + // Register a real (non-null) ctx so we can assert the round-trip returns the + // exact pointer we passed — a stand-in for the Go cgo.Handle token. + let ctx_marker: Box = Box::new(0xC0FFEE); + let ctx_ptr = Box::into_raw(ctx_marker) as *mut c_void; + let level = std::ffi::CString::new("trace").unwrap(); + let rc = unsafe { kernel_set_log_callback(Some(capture_cb), ctx_ptr, level.as_ptr()) }; + // Success is expected in this fresh binary (nothing else installed a global + // subscriber). If some future test in THIS binary installs one first, the + // bridge would report Internal — accept both so the test pins delivery, not + // install ordering. + assert!( + rc == KernelStatusCode::Success || rc == KernelStatusCode::Internal, + "kernel_set_log_callback returned an unexpected status: {rc:?}" + ); + if rc != KernelStatusCode::Success { + // A global subscriber was already installed by another test in this + // binary; delivery can't be asserted. There is only one test here today, + // so this branch is defensive. + return; + } + + // Emit an event on the kernel's contract target with a message + a field. + // `klog::warn!` is pub(crate); from this external test binary we emit the + // exact `tracing` event it expands to (same target + event field). + let stmt = "stmt-cb-probe-9c1"; + tracing::warn!( + target: databricks_sql_kernel::KERNEL_LOG_TARGET, + statement_id = stmt, + "callback probe message" + ); + + // Delivery is via the bridge's drain thread; poll briefly for it to land. + let mut got = Vec::new(); + for _ in 0..100 { + got = CAPTURED.lock().unwrap().clone(); + if got + .iter() + .any(|(_, t, m)| t == databricks_sql_kernel::KERNEL_LOG_TARGET && m.contains(stmt)) + { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + + let hit = got + .iter() + .find(|(_, t, m)| t == databricks_sql_kernel::KERNEL_LOG_TARGET && m.contains(stmt)); + let (_level, _target, message) = hit.unwrap_or_else(|| { + panic!("the log callback did not receive the kernel event; captured={got:?}") + }); + assert!( + message.contains("callback probe message"), + "message text should carry through, got: {message}" + ); + assert!( + message.contains("statement_id"), + "structured field should render into the message, got: {message}" + ); + + // The ctx round-trip: the kernel must hand back the exact pointer we + // registered, verbatim (it is opaque and never dereferenced kernel-side). + assert_eq!( + SEEN_CTX.load(Ordering::SeqCst), + ctx_ptr as usize, + "callback ctx should round-trip the exact pointer passed to kernel_set_log_callback" + ); + + // Stats accessor: this callback won the subscriber (installed=true) and a + // healthy delivery drops nothing. + let mut installed = false; + let mut dropped: u64 = 0; + unsafe { + databricks_sql_kernel::c_abi::logging::kernel_logging_stats(&mut installed, &mut dropped) + }; + assert!( + installed, + "kernel_logging_stats should report installed=true after a successful install" + ); + assert_eq!(dropped, 0, "a healthy delivery should not drop records"); + + // Reclaim the leaked ctx marker (kept alive across the call above). + unsafe { drop(Box::from_raw(ctx_ptr as *mut u64)) }; +} From 714a54d56b4c23a0737e6e7062e97ab1f9a894e5 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Fri, 17 Jul 2026 17:55:49 +0000 Subject: [PATCH 05/15] fix(c-abi): mirror EnvFilter specificity in log-callback level resolver The callback path's `level_from_rust_log` took the first `databricks*` directive it saw, diverging from `kernel_init_logging`'s `EnvFilter` when `RUST_LOG` carried multiple matching directives (e.g. `databricks=warn,databricks::sql::kernel=debug` resolved to `warn` instead of the more-specific `debug`). Resolve the level as `EnvFilter` would: only consider directives whose target is a prefix of a canonical kernel target root (new `directive_targets_kernel`), then let the most specific (longest) match win, order-independently. This rejects non-matching `databricks`-prefixed siblings (`databricksfoo=warn`, `databricks::sql::kernel::foo=trace`) that match no kernel event, so they no longer outrank a real `databricks=` directive or a bare global level. Adds coverage for broad + specific directives in both orders and the non-matching-sibling cases. Signed-off-by: Mani Kaustubh Mathur --- src/c_abi/logging.rs | 149 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 146 insertions(+), 3 deletions(-) diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs index 0bb6a015..9538ff87 100644 --- a/src/c_abi/logging.rs +++ b/src/c_abi/logging.rs @@ -200,7 +200,34 @@ fn parse_level_word(s: &str) -> Option { /// directive (`databricks::sql::kernel=debug` / `databricks_sql_kernel=debug`), or /// a global fallback among comma-separated directives. Returns `None` (keep the /// current default) if nothing matches. +/// +/// When several directives match, this mirrors `EnvFilter` specificity rather +/// than taking the first one listed: `EnvFilter` applies a target directive to +/// an event only when the directive's target is a **prefix of the event's +/// target** (`meta.target().starts_with(directive_target)`), and among the +/// matching directives the **most specific** (longest target) wins, independent +/// of order. So `RUST_LOG=databricks=warn,databricks::sql::kernel=debug` +/// resolves to `debug` for a `databricks::sql::kernel` event — the same +/// threshold `kernel_init_logging`'s `EnvFilter` would apply — not the +/// first-listed `warn`. On a specificity tie the later directive wins +/// (`EnvFilter` dedups identical directives last-writer-wins). A matching +/// target directive always beats a bare global level, since a target-less +/// directive is the least specific match `EnvFilter` recognises. +/// +/// Applicability is judged against the kernel's canonical target roots (see +/// [`directive_targets_kernel`]), NOT a bare `starts_with("databricks")`: a +/// longer non-matching sibling such as `databricksfoo=warn` or +/// `databricks::sql::kernel::foo=trace` is a prefix of no kernel event, so +/// `EnvFilter` skips it — and so must this, or it would wrongly outrank a real +/// `databricks=debug`. (This resolves a single scalar for the whole bridge, so +/// a directive naming a specific sub-module deeper than a root — e.g. +/// `databricks_sql_kernel::session=trace` — is conservatively treated as +/// non-selecting; the dominant `klog!` target `databricks::sql::kernel` is +/// resolved exactly.) fn level_from_rust_log(rust_log: &str) -> Option { + // Best kernel-applicable target directive seen so far, as (target length + // used as the specificity key, resolved level). + let mut best_target: Option<(usize, u8)> = None; let mut global: Option = None; for directive in rust_log.split(',') { let d = directive.trim(); @@ -209,9 +236,20 @@ fn level_from_rust_log(rust_log: &str) -> Option { } match d.split_once('=') { Some((target, level)) => { - if target.trim().starts_with("databricks") { + let target = target.trim(); + if directive_targets_kernel(target) { if let Some(l) = parse_level_word(level) { - return Some(l); // the kernel target's own directive wins + // Longest target = most specific; on a tie the later + // directive wins (matches `EnvFilter`'s last-writer + // dedup), so replace on `>=`. + let specificity = target.len(); + let wins = match best_target { + Some((len, _)) => specificity >= len, + None => true, + }; + if wins { + best_target = Some((specificity, l)); + } } } } @@ -224,7 +262,30 @@ fn level_from_rust_log(rust_log: &str) -> Option { } } } - global + // A matching target directive is always more specific than a bare global + // level, so it wins when both are present. + best_target.map(|(_, l)| l).or(global) +} + +/// The kernel's canonical `tracing` target roots: the `klog!` target +/// ([`KERNEL_LOG_TARGET`](crate::klog::KERNEL_LOG_TARGET), +/// `databricks::sql::kernel`) and the crate's module-path root +/// (`databricks_sql_kernel`). A `RUST_LOG` target directive selects the kernel +/// only when `EnvFilter` would apply it, i.e. its target is a prefix of a +/// target the kernel actually emits at — so its target must be a prefix of one +/// of these roots. +const KERNEL_TARGET_ROOTS: [&str; 2] = [crate::klog::KERNEL_LOG_TARGET, "databricks_sql_kernel"]; + +/// Whether a `RUST_LOG` directive target names (a prefix of) a kernel target, +/// so `EnvFilter` would apply it to kernel events. Mirrors `EnvFilter`'s +/// `event_target.starts_with(directive_target)` against the canonical kernel +/// roots: a directive target that is a proper extension of a root +/// (`databricks::sql::kernel::foo`) or an unrelated `databricks`-prefixed +/// sibling (`databricksfoo`) matches no kernel event and is rejected. +fn directive_targets_kernel(target: &str) -> bool { + KERNEL_TARGET_ROOTS + .iter() + .any(|root| root.starts_with(target)) } /// Returns whether an event at `level` should currently be forwarded. @@ -808,6 +869,88 @@ mod tests { assert_eq!(level_from_rust_log(""), None); } + #[test] + fn level_from_rust_log_mirrors_envfilter_specificity() { + // With a broad and a specific `databricks*` directive both present, the + // MORE SPECIFIC (longer target) one wins — matching `EnvFilter`, not + // first-match-wins — and the result is order-independent. + assert_eq!( + level_from_rust_log("databricks=warn,databricks::sql::kernel=debug"), + Some(LEVEL_DEBUG), + "the specific kernel directive must win over the broad databricks=warn" + ); + assert_eq!( + level_from_rust_log("databricks::sql::kernel=debug,databricks=warn"), + Some(LEVEL_DEBUG), + "resolution must not depend on directive order" + ); + // Same, for the underscore module-path spelling. + assert_eq!( + level_from_rust_log("databricks=warn,databricks_sql_kernel=trace"), + Some(LEVEL_TRACE) + ); + assert_eq!( + level_from_rust_log("databricks_sql_kernel=trace,databricks=warn"), + Some(LEVEL_TRACE) + ); + // A targeted `databricks*` directive beats a bare global level in either + // order (a target-less directive is the least specific match). + assert_eq!( + level_from_rust_log("info,databricks=error"), + Some(LEVEL_ERROR) + ); + assert_eq!( + level_from_rust_log("databricks=error,info"), + Some(LEVEL_ERROR) + ); + } + + #[test] + fn level_from_rust_log_ignores_non_matching_databricks_siblings() { + // `EnvFilter` applies a target directive only when its target is a + // prefix of the event target. A longer `databricks`-prefixed sibling + // that matches NO kernel target must NOT outrank a real `databricks=` + // directive just because it's longer. + assert_eq!( + level_from_rust_log("databricksfoo=warn,databricks=debug"), + Some(LEVEL_DEBUG), + "an unrelated databricks-prefixed sibling must be ignored" + ); + // A directive DEEPER than the klog target matches no emitted event + // (klog stamps exactly `databricks::sql::kernel`), so it's skipped and + // the broad `databricks=debug` applies. + assert_eq!( + level_from_rust_log("databricks::sql::kernel::foo=trace,databricks=debug"), + Some(LEVEL_DEBUG), + "a directive deeper than the kernel target must be ignored" + ); + // A non-matching sibling as the ONLY databricks directive must fall back + // to the bare global level (not the sibling's level). + assert_eq!( + level_from_rust_log("databricksfoo=trace,info"), + Some(LEVEL_INFO) + ); + // Two equal-length siblings that match no kernel root resolve to None + // (keep the default) rather than letting order pick a bogus level. + assert_eq!( + level_from_rust_log("databricks::aa=warn,databricks::bb=debug"), + None + ); + } + + #[test] + fn directive_targets_kernel_matches_prefixes_of_kernel_roots() { + // Prefixes of the klog target and the module-path root are accepted. + assert!(directive_targets_kernel("databricks")); + assert!(directive_targets_kernel("databricks::sql")); + assert!(directive_targets_kernel(crate::klog::KERNEL_LOG_TARGET)); + assert!(directive_targets_kernel("databricks_sql_kernel")); + // Unrelated siblings and over-specific extensions are rejected. + assert!(!directive_targets_kernel("databricksfoo")); + assert!(!directive_targets_kernel("databricks::sql::kernel::foo")); + assert!(!directive_targets_kernel("hyper")); + } + #[test] fn resolve_callback_level_prefers_explicit_over_rust_log() { // An explicit, recognised level wins outright — this is the one-knob From 72f81592c82d04187cd572025d067d091f27ae00 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sat, 18 Jul 2026 05:20:47 +0000 Subject: [PATCH 06/15] test(c-abi): tighten log-callback tests; make bridge filter event-only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses second-pass review on the reverse-call log bridge: - The end-to-end delivery test accepted `Internal` and returned early, so a regression where `kernel_set_log_callback` never installs would stay green. It's the sole success-path binary (nothing else installs a global subscriber), so require `Success`. - The test installed at `trace` and emitted `WARN`, which clears the default `WARN` threshold too — so it passed even if `level` were ignored. Prove gating in both directions: install at `ERROR` and assert a `WARN` event is filtered (using the FIFO drain thread + an `ERROR` barrier for a deterministic negative assertion), then re-register at `trace` and assert a `DEBUG` event (below the default) is delivered. - Make `KernelFilter` event-only: span callsites now cache off even on kernel targets (`callsite_interest_for` takes `is_event`; `enabled` gates on `meta.is_event()`). The kernel's own `databricks*` spans (`Session`'s `info_span!`, the `#[instrument]` on `next_batch`) no longer pay span create/enter/exit in the registry for output the event-only layer never produces. Adds a guard test proving an event emitted inside a now-disabled kernel span is still delivered (span and event callsites are evaluated independently), plus a unit test that span callsites cache off. Signed-off-by: Mani Kaustubh Mathur --- src/c_abi/logging.rs | 48 ++++++++--- tests/v0_c_abi_log_callback.rs | 150 ++++++++++++++++++++++++--------- 2 files changed, 146 insertions(+), 52 deletions(-) diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs index 9538ff87..5800d2be 100644 --- a/src/c_abi/logging.rs +++ b/src/c_abi/logging.rs @@ -314,11 +314,20 @@ fn current_level_filter() -> LevelFilter { } } -/// Per-callsite interest: kernel callsites re-evaluate per event (`sometimes`, -/// for the dynamic level); foreign callsites cache off forever (`never`), so -/// `hyper`/`rustls`/etc. never dispatch. -fn callsite_interest_for(target: &str) -> Interest { - if is_kernel_target(target) { +/// Per-callsite interest. Kernel EVENT callsites re-evaluate per event +/// (`sometimes`, for the dynamic level). Everything else caches off forever +/// (`never`): +/// +/// - foreign targets (`hyper`/`rustls`/…) never dispatch, and +/// - SPAN callsites never dispatch — even on kernel targets. This bridge is +/// event-only ([`KernelLogLayer`] implements just `on_event` and never +/// reads span data), so admitting spans would make the kernel's own +/// `databricks*` spans (`Session`'s `info_span!`, the `#[instrument]` on +/// the `next_batch()` hot path) pay span create/enter/exit in the registry +/// at INFO/DEBUG/TRACE thresholds for output that never comes. Caching them +/// off turns those into no-op disabled spans. +fn callsite_interest_for(target: &str, is_event: bool) -> Interest { + if is_event && is_kernel_target(target) { Interest::sometimes() } else { Interest::never() @@ -383,11 +392,12 @@ struct KernelFilter; impl Filter for KernelFilter { fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest { - callsite_interest_for(meta.target()) + callsite_interest_for(meta.target(), meta.is_event()) } fn enabled(&self, meta: &Metadata<'_>, _ctx: &Context<'_, S>) -> bool { - is_kernel_target(meta.target()) && should_emit(meta.level()) + // Event-only: never enable spans (the layer has no span consumer). + meta.is_event() && is_kernel_target(meta.target()) && should_emit(meta.level()) } fn max_level_hint(&self) -> Option { @@ -972,10 +982,26 @@ mod tests { #[test] fn foreign_callsites_cache_off_kernel_callsites_reevaluate() { - assert!(callsite_interest_for("hyper::client::pool").is_never()); - assert!(callsite_interest_for("rustls::conn").is_never()); - assert!(callsite_interest_for("databricks::sql::kernel").is_sometimes()); - assert!(callsite_interest_for("databricks_sql_kernel::session").is_sometimes()); + // Kernel EVENT callsites re-evaluate; foreign ones cache off. + assert!(callsite_interest_for("hyper::client::pool", true).is_never()); + assert!(callsite_interest_for("rustls::conn", true).is_never()); + assert!(callsite_interest_for("databricks::sql::kernel", true).is_sometimes()); + assert!(callsite_interest_for("databricks_sql_kernel::session", true).is_sometimes()); + } + + #[test] + fn span_callsites_cache_off_even_on_kernel_targets() { + // The bridge is event-only, so SPAN callsites never dispatch — even on + // kernel targets — so the kernel's own `databricks*` spans (Session's + // info_span!, the #[instrument] on next_batch) don't pay span machinery + // for output that never comes. + assert!(callsite_interest_for("databricks::sql::kernel", false).is_never()); + assert!( + callsite_interest_for("databricks_sql_kernel::reader::inline::streaming", false) + .is_never() + ); + // Foreign spans stay off too. + assert!(callsite_interest_for("hyper::client::pool", false).is_never()); } #[test] diff --git a/tests/v0_c_abi_log_callback.rs b/tests/v0_c_abi_log_callback.rs index 3a9cf933..0dcdbbb6 100644 --- a/tests/v0_c_abi_log_callback.rs +++ b/tests/v0_c_abi_log_callback.rs @@ -13,9 +13,11 @@ // limitations under the License. //! End-to-end delivery test for the `kernel_set_log_callback` reverse-call log -//! bridge. Registers a C callback, emits a kernel `tracing` event on the -//! contract target, and asserts the callback received it with the message and -//! target intact. +//! bridge. Registers a C callback, emits kernel `tracing` events on the +//! contract target, and asserts the callback received them with the message and +//! target intact — and that the `level` argument gates delivery in both +//! directions (a restrictive level filters a below-threshold event; a +//! permissive level delivers an event below the default threshold). //! //! This lives in its own integration-test binary (NOT a `#[cfg(test)] mod` in //! `src/c_abi/logging.rs`) on purpose: installing the process-global `tracing` @@ -58,60 +60,96 @@ extern "C-unwind" fn capture_cb( CAPTURED.lock().unwrap().push((level, target, message)); } +/// Poll up to ~1s for the captured records to satisfy `pred`, returning the +/// final snapshot either way (delivery is async via the bridge's drain thread). +fn wait_until(pred: impl Fn(&[(c_int, String, String)]) -> bool) -> Vec<(c_int, String, String)> { + for _ in 0..100 { + let got = CAPTURED.lock().unwrap().clone(); + if pred(&got) { + return got; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + CAPTURED.lock().unwrap().clone() +} + +/// Whether a kernel-target record carrying `marker` in its message was captured. +fn saw_marker(got: &[(c_int, String, String)], marker: &str) -> bool { + got.iter() + .any(|(_, t, m)| t == databricks_sql_kernel::KERNEL_LOG_TARGET && m.contains(marker)) +} + #[test] -fn log_callback_receives_kernel_event_end_to_end() { - // Drive the threshold through the explicit `level` argument (the one-knob - // path a host uses) rather than RUST_LOG, so the test proves the level - // param actually gates delivery. "trace" lets every kernel event through. +fn log_callback_delivers_and_level_gates_end_to_end() { // Register a real (non-null) ctx so we can assert the round-trip returns the // exact pointer we passed — a stand-in for the Go cgo.Handle token. let ctx_marker: Box = Box::new(0xC0FFEE); let ctx_ptr = Box::into_raw(ctx_marker) as *mut c_void; - let level = std::ffi::CString::new("trace").unwrap(); - let rc = unsafe { kernel_set_log_callback(Some(capture_cb), ctx_ptr, level.as_ptr()) }; - // Success is expected in this fresh binary (nothing else installed a global - // subscriber). If some future test in THIS binary installs one first, the - // bridge would report Internal — accept both so the test pins delivery, not - // install ordering. + + // === Step 1: a RESTRICTIVE level must FILTER a below-threshold event. === + // Install at ERROR. A WARN event must not be delivered — this is what proves + // the `level` argument actually gates delivery (the previous "trace + WARN" + // shape would pass even if `level` were ignored, since WARN clears the + // default WARN threshold). This is a fresh, single-test binary, so nothing + // else has installed a global subscriber: install MUST succeed. Accepting + // `Internal` here would let a regression that never installs stay green. + let level_error = std::ffi::CString::new("error").unwrap(); + let rc = unsafe { kernel_set_log_callback(Some(capture_cb), ctx_ptr, level_error.as_ptr()) }; + assert_eq!( + rc, + KernelStatusCode::Success, + "kernel_set_log_callback must succeed on first install in a fresh binary; got {rc:?}" + ); + + let filtered_marker = "probe-warn-should-be-filtered-a1"; + let barrier_marker = "probe-error-barrier-b2"; + // Emit the (to-be-filtered) WARN first, then an ERROR barrier. The single + // drain thread delivers FIFO, so once the ERROR barrier lands we know the + // earlier WARN would already have arrived had it passed the filter — a + // deterministic negative assertion, not a "sleep and hope". + tracing::warn!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "{}", filtered_marker); + tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "{}", barrier_marker); + let got = wait_until(|g| saw_marker(g, barrier_marker)); assert!( - rc == KernelStatusCode::Success || rc == KernelStatusCode::Internal, - "kernel_set_log_callback returned an unexpected status: {rc:?}" + saw_marker(&got, barrier_marker), + "the ERROR barrier event must be delivered at level=error; captured={got:?}" + ); + assert!( + !saw_marker(&got, filtered_marker), + "a WARN event must NOT be delivered when level=error — this proves the level \ + argument gates delivery; captured={got:?}" ); - if rc != KernelStatusCode::Success { - // A global subscriber was already installed by another test in this - // binary; delivery can't be asserted. There is only one test here today, - // so this branch is defensive. - return; - } - // Emit an event on the kernel's contract target with a message + a field. - // `klog::warn!` is pub(crate); from this external test binary we emit the + // === Step 2: a PERMISSIVE level must DELIVER a below-default event. === + // Re-register at TRACE and emit a DEBUG event. DEBUG is below the static + // WARN default, so its delivery proves the `level` argument also loosens the + // threshold (not just that WARN happens to clear the default). Same ctx, so + // the round-trip assertion below still holds. + let level_trace = std::ffi::CString::new("trace").unwrap(); + let rc = unsafe { kernel_set_log_callback(Some(capture_cb), ctx_ptr, level_trace.as_ptr()) }; + assert_eq!( + rc, + KernelStatusCode::Success, + "re-registering the callback must succeed; got {rc:?}" + ); + + // `klog::debug!` is pub(crate); from this external test binary we emit the // exact `tracing` event it expands to (same target + event field). let stmt = "stmt-cb-probe-9c1"; - tracing::warn!( + tracing::debug!( target: databricks_sql_kernel::KERNEL_LOG_TARGET, statement_id = stmt, "callback probe message" ); - - // Delivery is via the bridge's drain thread; poll briefly for it to land. - let mut got = Vec::new(); - for _ in 0..100 { - got = CAPTURED.lock().unwrap().clone(); - if got - .iter() - .any(|(_, t, m)| t == databricks_sql_kernel::KERNEL_LOG_TARGET && m.contains(stmt)) - { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - + let got = wait_until(|g| saw_marker(g, stmt)); let hit = got .iter() .find(|(_, t, m)| t == databricks_sql_kernel::KERNEL_LOG_TARGET && m.contains(stmt)); let (_level, _target, message) = hit.unwrap_or_else(|| { - panic!("the log callback did not receive the kernel event; captured={got:?}") + panic!( + "a DEBUG kernel event must be delivered at level=trace (the default WARN would \ + drop it) — this proves the level argument is honoured; captured={got:?}" + ) }); assert!( message.contains("callback probe message"), @@ -122,6 +160,36 @@ fn log_callback_receives_kernel_event_end_to_end() { "structured field should render into the message, got: {message}" ); + // === Step 3: an event emitted INSIDE a (now-disabled) kernel span must + // still be delivered. === + // The bridge's filter is event-only: kernel SPAN callsites cache off + // (`callsite_interest_for(_, is_event=false)` → never), so the kernel's own + // `info_span!` / `#[instrument]` spans become no-op disabled spans and pay + // no span machinery. This must NOT suppress EVENTS emitted while such a span + // is on the stack — `tracing` evaluates span and event callsites + // independently, and the kernel logs most of its events from inside + // instrumented functions (e.g. a `klog::debug!` inside the `#[instrument]`ed + // `next_batch`). Reproduce that shape: enter a kernel span (disabled by our + // filter) and emit a kernel event within it; the callback must still get the + // event. Guards against a filter/`tracing` change silently dropping every + // in-span kernel log. + let in_span_marker = "probe-event-inside-disabled-span-c3"; + let kernel_span = tracing::info_span!( + target: databricks_sql_kernel::KERNEL_LOG_TARGET, + "kernel.session", + session_id = "sess-guard" + ); + { + let _entered = kernel_span.enter(); + tracing::debug!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "{}", in_span_marker); + } + let got = wait_until(|g| saw_marker(g, in_span_marker)); + assert!( + saw_marker(&got, in_span_marker), + "an event emitted inside a disabled kernel span must still be delivered — disabling \ + span callsites must not suppress in-span events; captured={got:?}" + ); + // The ctx round-trip: the kernel must hand back the exact pointer we // registered, verbatim (it is opaque and never dereferenced kernel-side). assert_eq!( @@ -131,7 +199,7 @@ fn log_callback_receives_kernel_event_end_to_end() { ); // Stats accessor: this callback won the subscriber (installed=true) and a - // healthy delivery drops nothing. + // healthy delivery drops nothing (the filtered WARN was never enqueued). let mut installed = false; let mut dropped: u64 = 0; unsafe { @@ -143,6 +211,6 @@ fn log_callback_receives_kernel_event_end_to_end() { ); assert_eq!(dropped, 0, "a healthy delivery should not drop records"); - // Reclaim the leaked ctx marker (kept alive across the call above). + // Reclaim the leaked ctx marker (kept alive across the calls above). unsafe { drop(Box::from_raw(ctx_ptr as *mut u64)) }; } From d7868ecbc4c98222dee3b909f30eeac50e9b1d94 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sat, 18 Jul 2026 06:19:02 +0000 Subject: [PATCH 07/15] fix(c-abi): harden log-callback install ordering, poisoning, and RUST_LOG submodule matching MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the third-pass review on the reverse-call log bridge: - Install ordering (High): spawn the drain thread BEFORE claiming the global subscriber. Previously `set_global_default` ran first, so if the drain-thread spawn then failed the process-global subscriber slot was left occupied by a `SENDER`-less layer — every kernel event short-circuited and the host could never fall back to `kernel_init_logging`. Now a spawn failure bails out before touching the subscriber (slot stays free), and a lost subscriber race drops the sender so the freshly-spawned drain thread exits cleanly. - Re-registration race (Medium): add a monotonic sink generation. The drain thread captures `(cb, ctx, gen)` and, via `poison_sink_if_current`, only poisons on an unwind if that generation is still installed — so an old, slow callback that unwinds after the host registered a replacement can no longer kill the new sink. - Drop undercount (Medium): count the record whose callback unwinds. Only later records were counted while poisoned, so the first lost record was invisible to `kernel_logging_stats`; both the primary and the drop-notice failure paths now increment `DROPPED`. - RUST_LOG submodule directives (Medium): `directive_targets_kernel` now accepts extensions of the module-path root (`databricks_sql_kernel::session`), which the bridge forwards via `is_kernel_target`, instead of silently keeping the default WARN threshold. Extensions of the fixed-depth klog target (`databricks::sql::kernel::foo`) and unrelated siblings are still rejected. Adds a unit test for the generation guard and an end-to-end step asserting an unwinding callback is counted as a drop and poisons the sink, plus submodule-directive coverage. Signed-off-by: Mani Kaustubh Mathur --- src/c_abi/logging.rs | 258 ++++++++++++++++++++++++--------- tests/v0_c_abi_log_callback.rs | 65 ++++++++- 2 files changed, 253 insertions(+), 70 deletions(-) diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs index 5800d2be..834be470 100644 --- a/src/c_abi/logging.rs +++ b/src/c_abi/logging.rs @@ -112,6 +112,11 @@ struct Record { struct Sink { cb: kernel_log_callback, ctx: usize, + /// Monotonic registration id. The drain thread captures this alongside + /// `(cb, ctx)` and only poisons the sink on a callback unwind if this id is + /// still the installed one — so a slow/old callback that unwinds AFTER the + /// host re-registered a new one cannot kill the replacement. + gen: u64, } const CHANNEL_CAPACITY: usize = 4096; @@ -168,6 +173,11 @@ static SENDER: OnceLock> = OnceLock::new(); /// Current sink. Last-writer-wins; read by the drain thread per record. static SINK: OnceLock>> = OnceLock::new(); +/// Source of monotonic sink registration ids ([`Sink::gen`]). Bumped under the +/// `SINK` lock on every (re-)registration so the drain thread can tell whether +/// the callback it just invoked is still the installed one. +static NEXT_SINK_GEN: AtomicU64 = AtomicU64::new(0); + /// Guards the one-time subscriber install + channel + drain-thread spawn. static INSTALL: Once = Once::new(); @@ -214,16 +224,16 @@ fn parse_level_word(s: &str) -> Option { /// target directive always beats a bare global level, since a target-less /// directive is the least specific match `EnvFilter` recognises. /// -/// Applicability is judged against the kernel's canonical target roots (see -/// [`directive_targets_kernel`]), NOT a bare `starts_with("databricks")`: a -/// longer non-matching sibling such as `databricksfoo=warn` or -/// `databricks::sql::kernel::foo=trace` is a prefix of no kernel event, so -/// `EnvFilter` skips it — and so must this, or it would wrongly outrank a real -/// `databricks=debug`. (This resolves a single scalar for the whole bridge, so -/// a directive naming a specific sub-module deeper than a root — e.g. -/// `databricks_sql_kernel::session=trace` — is conservatively treated as -/// non-selecting; the dominant `klog!` target `databricks::sql::kernel` is -/// resolved exactly.) +/// Applicability is judged by [`directive_targets_kernel`], NOT a bare +/// `starts_with("databricks")`: a non-matching sibling such as `databricksfoo=warn` +/// or an extension of the fixed-depth `klog!` target (`databricks::sql::kernel::foo=trace`) +/// is a prefix of no kernel event, so `EnvFilter` skips it — and so must this, +/// or it would wrongly outrank a real `databricks=debug`. A submodule directive +/// on the module-path namespace the bridge forwards +/// (`databricks_sql_kernel::session=debug`) IS honoured (most specific wins). +/// (This resolves a single scalar for the whole bridge, so with a mix of +/// targets the most specific matching directive sets the one threshold; the +/// dominant `klog!` target `databricks::sql::kernel` is resolved exactly.) fn level_from_rust_log(rust_log: &str) -> Option { // Best kernel-applicable target directive seen so far, as (target length // used as the specificity key, resolved level). @@ -267,25 +277,37 @@ fn level_from_rust_log(rust_log: &str) -> Option { best_target.map(|(_, l)| l).or(global) } +/// The crate's module-path root: the `#[instrument]` / default-target namespace +/// (`databricks_sql_kernel::*`) the bridge also forwards (see `is_kernel_target`). +const KERNEL_MODULE_ROOT: &str = "databricks_sql_kernel"; + /// The kernel's canonical `tracing` target roots: the `klog!` target /// ([`KERNEL_LOG_TARGET`](crate::klog::KERNEL_LOG_TARGET), /// `databricks::sql::kernel`) and the crate's module-path root -/// (`databricks_sql_kernel`). A `RUST_LOG` target directive selects the kernel -/// only when `EnvFilter` would apply it, i.e. its target is a prefix of a -/// target the kernel actually emits at — so its target must be a prefix of one -/// of these roots. -const KERNEL_TARGET_ROOTS: [&str; 2] = [crate::klog::KERNEL_LOG_TARGET, "databricks_sql_kernel"]; - -/// Whether a `RUST_LOG` directive target names (a prefix of) a kernel target, -/// so `EnvFilter` would apply it to kernel events. Mirrors `EnvFilter`'s -/// `event_target.starts_with(directive_target)` against the canonical kernel -/// roots: a directive target that is a proper extension of a root -/// (`databricks::sql::kernel::foo`) or an unrelated `databricks`-prefixed -/// sibling (`databricksfoo`) matches no kernel event and is rejected. +/// ([`KERNEL_MODULE_ROOT`]). +const KERNEL_TARGET_ROOTS: [&str; 2] = [crate::klog::KERNEL_LOG_TARGET, KERNEL_MODULE_ROOT]; + +/// Whether a `RUST_LOG` directive target selects kernel events under +/// `EnvFilter`'s `event_target.starts_with(directive_target)` prefix match, +/// against the targets the bridge actually forwards. A directive applies when: +/// +/// - its target is a **prefix of a canonical root** (`databricks`, +/// `databricks::sql`, `databricks_sql_kernel`, …) — it matches events at +/// that root; or +/// - its target **extends the module-path root** (`databricks_sql_kernel::session`) +/// — those submodule events are forwarded by `is_kernel_target`, so a host +/// targeting a specific kernel submodule must raise the threshold rather +/// than be silently ignored. +/// +/// It is rejected otherwise: an unrelated `databricks`-prefixed sibling +/// (`databricksfoo`) matches no kernel event, and an extension of the +/// fixed-depth `klog!` target (`databricks::sql::kernel::foo`) matches nothing +/// either, since the kernel never emits deeper than `databricks::sql::kernel`. fn directive_targets_kernel(target: &str) -> bool { - KERNEL_TARGET_ROOTS - .iter() - .any(|root| root.starts_with(target)) + target.starts_with(KERNEL_MODULE_ROOT) + || KERNEL_TARGET_ROOTS + .iter() + .any(|root| root.starts_with(target)) } /// Returns whether an event at `level` should currently be forwarded. @@ -463,6 +485,23 @@ fn invoke_callback( .is_ok() } +/// Poison the sink — stop delivery — but ONLY if generation `gen` is still the +/// installed registration. The drain thread copies `(cb, ctx, gen)` out and +/// runs the callback without the lock, so the host may re-register (bumping the +/// generation and clearing the poison) while an OLD callback is mid-unwind. +/// Comparing under the `SINK` lock (which the setter also holds while it swaps +/// the sink + clears the poison) means an old callback's failure can never kill +/// the newer registration. +fn poison_sink_if_current(gen: u64) { + if let Some(lock) = SINK.get() { + if let Ok(guard) = lock.lock() { + if guard.as_ref().map(|s| s.gen) == Some(gen) { + SINK_POISONED.store(true, Ordering::Relaxed); + } + } + } +} + /// Drain loop (own OS thread): pull one record at a time and invoke the host /// callback with borrowed C strings. Runs off the kernel's tokio workers so a /// slow callback can't stall query execution. @@ -471,7 +510,8 @@ fn drain_loop(rx: Receiver) { // "dropped N" notice for the delta since the last delivered record. let mut reported_drops: u64 = 0; // `recv` errors only once the (process-global) sender is dropped, which - // never happens in practice; exit cleanly if the channel is torn down. + // happens on a lost subscriber race (the setter drops the sender so this + // thread exits) or process teardown; exit cleanly either way. while let Ok(record) = rx.recv() { // A callback that unwound once is assumed to keep unwinding; stop // delivering to protect the process (the loss is counted + surfaced via @@ -483,14 +523,14 @@ fn drain_loop(rx: Receiver) { let Some(sink_lock) = SINK.get() else { continue; }; - // Copy the sink out under the lock (cheap: a fn pointer + usize) so the - // callback runs without holding the mutex — a reentrant setter can't - // deadlock, and a slow callback can't block a level/sink update. + // Copy the sink out under the lock (cheap: a fn pointer + usize + gen) + // so the callback runs without holding the mutex — a reentrant setter + // can't deadlock, and a slow callback can't block a level/sink update. let sink = match sink_lock.lock() { - Ok(g) => g.as_ref().map(|s| (s.cb, s.ctx)), + Ok(g) => g.as_ref().map(|s| (s.cb, s.ctx, s.gen)), Err(_) => None, }; - let Some((cb, ctx)) = sink else { + let Some((cb, ctx, gen)) = sink else { continue; }; // Surface any records dropped since the last delivery as one synthetic @@ -511,12 +551,21 @@ fn drain_loop(rx: Receiver) { is_kernel_target_str(), ¬ice, ) { - SINK_POISONED.store(true, Ordering::Relaxed); + // The notice unwound, so `record` won't be delivered either — + // count it as dropped (the health contract), then poison iff + // this callback is still the installed one. + DROPPED.fetch_add(1, Ordering::Relaxed); + poison_sink_if_current(gen); continue; } } if !invoke_callback(cb, ctx, record.level, record.target, &record.message) { - SINK_POISONED.store(true, Ordering::Relaxed); + // The callback unwound and did NOT deliver this record — count the + // loss so kernel_logging_stats reflects it (previously the first + // failing record was silently uncounted), then poison iff this + // callback is still the installed one. + DROPPED.fetch_add(1, Ordering::Relaxed); + poison_sink_if_current(gen); } } } @@ -630,58 +679,68 @@ pub unsafe extern "C" fn kernel_set_log_callback( // it here (before releasing the SINK lock) is immediately effective. let sink = SINK.get_or_init(|| Mutex::new(None)); if let Ok(mut guard) = sink.lock() { + // A fresh generation so the drain thread won't let an old in-flight + // callback's unwind poison this new registration (see poison_sink_if_current). + let gen = NEXT_SINK_GEN.fetch_add(1, Ordering::Relaxed); *guard = Some(Sink { cb, ctx: ctx as usize, + gen, }); SINK_POISONED.store(false, Ordering::Relaxed); } // Install the process-global subscriber + drain thread exactly once. // - // Order matters: attempt `set_global_default` FIRST, and only spawn the - // drain thread if we win the one global subscriber. The common sequence is - // "host called kernel_init_logging, a layer later calls this" — there we - // lose the race and must NOT leave a drain thread parked on recv() forever - // (an idle-thread leak). We use a plain Once-guarded closure rather than the - // channel/thread first. + // Order matters: stand up the drain thread FIRST, and only then claim the + // one global subscriber via `set_global_default`. This keeps two failure + // modes clean: + // + // - Spawn failure: if the OS refuses the drain thread (EAGAIN/ENOMEM) we + // bail out BEFORE touching the global subscriber, so the slot stays free + // and the host can still fall back to `kernel_init_logging` for the rest + // of the process. (Claiming the subscriber first would strand it with no + // `SENDER`, silently dropping every event with no recovery path.) + // - Lost race: if another subscriber (e.g. `kernel_init_logging`) already + // won, we DROP the sender so the freshly-spawned drain thread's `recv()` + // errors and it exits — no idle-thread leak, and `SENDER` stays unset so + // `on_event` short-circuits. let mut did_install = false; INSTALL.call_once(|| { did_install = true; - let subscriber = - tracing_subscriber::registry().with(KernelLogLayer.with_filter(KernelFilter)); - if tracing::subscriber::set_global_default(subscriber).is_err() { - // Another global subscriber (e.g. kernel_init_logging) won. Do not - // spawn a drain thread — SENDER stays unset, so on_event's `let Some - // (tx)` short-circuits and nothing is enqueued. - INSTALL_STATUS.store(INSTALL_ALREADY_SET, Ordering::Release); - return; - } - // We own the subscriber; now stand up the delivery path. Spawn the drain - // thread and publish SENDER only after it is confirmed running, so a - // live producer never outlives its consumer. + // Stand up the delivery path first (thread + channel), so a spawn + // failure never leaves the global subscriber slot occupied. let (tx, rx) = sync_channel::(CHANNEL_CAPACITY); - match std::thread::Builder::new() + if let Err(e) = std::thread::Builder::new() .name("kernel-log-drain".to_owned()) .spawn(move || drain_loop(rx)) { - Ok(_) => { - let _ = SENDER.set(tx); - INSTALL_STATUS.store(INSTALL_OK, Ordering::Release); - } - Err(e) => { - // We hold the subscriber but have no consumer; leave SENDER - // unset (events short-circuit). Record the OS error distinctly - // so on-call can tell a spawn failure (EAGAIN/ENOMEM) from the - // benign "already installed" case. Use `.lock().ok()` (not - // `.unwrap()`) so a poisoned mutex can't panic across the FFI - // boundary — the message is best-effort diagnostics. - if let Ok(mut guard) = SPAWN_ERROR.get_or_init(|| Mutex::new(None)).lock() { - *guard = Some(e.to_string()); - } - INSTALL_STATUS.store(INSTALL_SPAWN_FAILED, Ordering::Release); + // Record the OS error distinctly so on-call can tell a spawn failure + // from the benign "already installed" case. Use `.lock().ok()` (not + // `.unwrap()`) so a poisoned mutex can't panic across the FFI + // boundary — the message is best-effort diagnostics. `tx` drops here + // (no thread was spawned); the global subscriber is left untouched. + if let Ok(mut guard) = SPAWN_ERROR.get_or_init(|| Mutex::new(None)).lock() { + *guard = Some(e.to_string()); } + INSTALL_STATUS.store(INSTALL_SPAWN_FAILED, Ordering::Release); + return; + } + // Drain thread is running. Now claim the one global subscriber. + let subscriber = + tracing_subscriber::registry().with(KernelLogLayer.with_filter(KernelFilter)); + if tracing::subscriber::set_global_default(subscriber).is_err() { + // Another global subscriber won. Drop the sender so the drain thread + // (blocked on recv()) unblocks with an error and exits cleanly, then + // leave SENDER unset so on_event's `let Some(tx)` short-circuits. + drop(tx); + INSTALL_STATUS.store(INSTALL_ALREADY_SET, Ordering::Release); + return; } + // We own the subscriber AND have a live consumer. Publish SENDER only + // now, so a live producer never outlives its consumer. + let _ = SENDER.set(tx); + INSTALL_STATUS.store(INSTALL_OK, Ordering::Release); }); // Rebuild the process-wide callsite interest cache only when it can matter: // on the install that set our filter, or when a later call changed LEVEL. @@ -913,6 +972,17 @@ mod tests { level_from_rust_log("databricks=error,info"), Some(LEVEL_ERROR) ); + // A submodule directive on the module-path namespace the bridge forwards + // (`databricks_sql_kernel::*`) is honoured (most specific wins) rather + // than silently ignored — the host asked for that submodule. + assert_eq!( + level_from_rust_log("databricks=warn,databricks_sql_kernel::session=debug"), + Some(LEVEL_DEBUG) + ); + assert_eq!( + level_from_rust_log("databricks_sql_kernel::session=debug"), + Some(LEVEL_DEBUG) + ); } #[test] @@ -955,7 +1025,14 @@ mod tests { assert!(directive_targets_kernel("databricks::sql")); assert!(directive_targets_kernel(crate::klog::KERNEL_LOG_TARGET)); assert!(directive_targets_kernel("databricks_sql_kernel")); - // Unrelated siblings and over-specific extensions are rejected. + // Submodules of the module-path root are accepted (those events are + // forwarded by is_kernel_target, so a host targeting them must gate). + assert!(directive_targets_kernel("databricks_sql_kernel::session")); + assert!(directive_targets_kernel( + "databricks_sql_kernel::reader::inline" + )); + // Unrelated siblings and over-specific extensions of the fixed-depth + // klog target are rejected. assert!(!directive_targets_kernel("databricksfoo")); assert!(!directive_targets_kernel("databricks::sql::kernel::foo")); assert!(!directive_targets_kernel("hyper")); @@ -989,6 +1066,51 @@ mod tests { assert!(callsite_interest_for("databricks_sql_kernel::session", true).is_sometimes()); } + #[test] + fn poison_sink_if_current_respects_generation() { + // Guards the re-registration race: the drain thread copies a sink's + // generation out, runs the callback unlocked, and only poisons on unwind + // if that generation is STILL installed — so an old in-flight callback's + // failure can't kill a callback the host registered in the meantime. + let lock = SINK.get_or_init(|| Mutex::new(None)); + + // Install a sink at generation `g_old`, unpoisoned. + let g_old = NEXT_SINK_GEN.fetch_add(1, Ordering::Relaxed); + *lock.lock().unwrap() = Some(Sink { + cb: ok_cb, + ctx: 0, + gen: g_old, + }); + SINK_POISONED.store(false, Ordering::Relaxed); + + // A failure attributed to the CURRENT generation poisons. + poison_sink_if_current(g_old); + assert!( + SINK_POISONED.load(Ordering::Relaxed), + "a failure on the installed generation must poison" + ); + + // Simulate a re-registration: newer generation, poison cleared. + let g_new = NEXT_SINK_GEN.fetch_add(1, Ordering::Relaxed); + *lock.lock().unwrap() = Some(Sink { + cb: ok_cb, + ctx: 0, + gen: g_new, + }); + SINK_POISONED.store(false, Ordering::Relaxed); + + // A LATE failure from the OLD generation must NOT poison the new sink. + poison_sink_if_current(g_old); + assert!( + !SINK_POISONED.load(Ordering::Relaxed), + "an old callback's unwind must not poison a newer registration" + ); + + // Restore the process-global sink state for any other test. + *lock.lock().unwrap() = None; + SINK_POISONED.store(false, Ordering::Relaxed); + } + #[test] fn span_callsites_cache_off_even_on_kernel_targets() { // The bridge is event-only, so SPAN callsites never dispatch — even on diff --git a/tests/v0_c_abi_log_callback.rs b/tests/v0_c_abi_log_callback.rs index 0dcdbbb6..49f23015 100644 --- a/tests/v0_c_abi_log_callback.rs +++ b/tests/v0_c_abi_log_callback.rs @@ -60,6 +60,18 @@ extern "C-unwind" fn capture_cb( CAPTURED.lock().unwrap().push((level, target, message)); } +/// A callback that always unwinds across the FFI boundary. The bridge's +/// `catch_unwind` must contain it, count the undelivered record, and poison the +/// sink (stop delivery) rather than abort the process. +extern "C-unwind" fn panic_cb( + _ctx: *mut c_void, + _level: c_int, + _target: *const c_char, + _message: *const c_char, +) { + panic!("callback boom"); +} + /// Poll up to ~1s for the captured records to satisfy `pred`, returning the /// final snapshot either way (delivery is async via the bridge's drain thread). fn wait_until(pred: impl Fn(&[(c_int, String, String)]) -> bool) -> Vec<(c_int, String, String)> { @@ -211,6 +223,55 @@ fn log_callback_delivers_and_level_gates_end_to_end() { ); assert_eq!(dropped, 0, "a healthy delivery should not drop records"); - // Reclaim the leaked ctx marker (kept alive across the calls above). - unsafe { drop(Box::from_raw(ctx_ptr as *mut u64)) }; + // === Step 4: a callback that unwinds is counted as a drop and poisons the + // sink. === + // Re-register a callback that always panics (which clears the poison and + // starts a fresh generation), emit one kernel event, and confirm the bridge + // (a) contained the unwind — the process is still alive to run these asserts + // — (b) counted the undelivered record in `dropped` (previously the first + // unwinding record was silently uncounted), and (c) poisoned the sink so + // `installed` now reads false. + let panic_ctx: Box = Box::new(0xBADF00D); + let panic_ctx_ptr = Box::into_raw(panic_ctx) as *mut c_void; + let level_trace2 = std::ffi::CString::new("trace").unwrap(); + let rc = + unsafe { kernel_set_log_callback(Some(panic_cb), panic_ctx_ptr, level_trace2.as_ptr()) }; + assert_eq!( + rc, + KernelStatusCode::Success, + "re-registering the panicking callback must succeed; got {rc:?}" + ); + + let dropped_before = dropped; + tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "probe-unwinds-d4"); + // Poll for the sink to be poisoned (delivery attempted, callback unwound). + let mut installed_after = true; + let mut dropped_after = dropped_before; + for _ in 0..100 { + unsafe { + databricks_sql_kernel::c_abi::logging::kernel_logging_stats( + &mut installed_after, + &mut dropped_after, + ) + }; + if !installed_after { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!( + !installed_after, + "a callback that unwinds must poison the sink so installed reads false" + ); + assert!( + dropped_after > dropped_before, + "the record whose callback unwound must be counted in dropped \ + (before={dropped_before}, after={dropped_after})" + ); + + // Reclaim the leaked ctx markers (kept alive across the calls above). + unsafe { + drop(Box::from_raw(ctx_ptr as *mut u64)); + drop(Box::from_raw(panic_ctx_ptr as *mut u64)); + } } From d86c26d34f852f30bd6783860abc3c19b2fddddc Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sat, 18 Jul 2026 11:53:05 +0000 Subject: [PATCH 08/15] fix(c-abi): per-target RUST_LOG filtering + retryable install for log callback Address remaining log-callback review findings: - Per-target RUST_LOG filtering: replace the single-scalar level with per-target EnvFilter precedence (most-specific prefix wins) evaluated per event. A submodule directive (databricks_sql_kernel::reader::inline=trace) no longer widens the canonical klog! target (databricks::sql::kernel=error), which EnvFilter keeps at its own directive's level. An explicit one-knob level still applies uniformly (no per-target directives) and stays on the lock-free fast path. - Retryable install: replace the install `Once` (consumed on first attempt) with a serialized, retryable guard so a transient drain-thread spawn failure (EAGAIN/ENOMEM) no longer permanently disables callback logging. set_global_default is still attempted at most once. - kernel_logging_stats now clears the thread-local last-error on entry, matching every other C-ABI entry point, so a poll between a failed call and reading the error can't observe a stale error. - on_event short-circuits before field formatting / enqueue when the sink is poisoned, still counting the loss so kernel_logging_stats stays accurate (each dropped record counted exactly once). - Tests: per-target precedence + parse_rust_log unit tests, and an end-to-end Step 5 that re-registers a good callback after poison and asserts installed flips back to true and delivery resumes. Signed-off-by: Mani Kaustubh Mathur --- src/c_abi/logging.rs | 680 +++++++++++++++++++++------------ tests/v0_c_abi_log_callback.rs | 41 ++ 2 files changed, 468 insertions(+), 253 deletions(-) diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs index 834be470..fa7fdd2c 100644 --- a/src/c_abi/logging.rs +++ b/src/c_abi/logging.rs @@ -28,9 +28,11 @@ //! //! - [`kernel_set_log_callback`] installs a process-global [`KernelLogLayer`] //! (once) and records the `(callback, ctx)` sink. The layer captures -//! `databricks*` events, filters by an atomic level, formats each into a -//! [`Record`], and pushes it onto a **bounded** channel (drop-on-full — logs -//! are advisory and must never block or back-pressure a kernel hot path). +//! `databricks*` events, filters by a per-target threshold (an explicit +//! one-knob level, else `RUST_LOG`'s per-target `EnvFilter` precedence), +//! formats each into a [`Record`], and pushes it onto a **bounded** channel +//! (drop-on-full — logs are advisory and must never block or back-pressure a +//! kernel hot path). //! - A dedicated drain thread pulls records and invokes the C callback once per //! record with borrowed C strings (valid only for the call). //! @@ -69,7 +71,7 @@ use std::os::raw::{c_char, c_int}; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; -use std::sync::{Mutex, Once, OnceLock}; +use std::sync::{Mutex, OnceLock, RwLock}; use tracing::field::{Field, Visit}; use tracing::level_filters::LevelFilter; use tracing::subscriber::Interest; @@ -128,9 +130,34 @@ const LEVEL_INFO: u8 = 3; const LEVEL_DEBUG: u8 = 4; const LEVEL_TRACE: u8 = 5; -/// Numeric severity, low = more severe. `0` means "off / emit nothing". +/// Default forward threshold for kernel targets not matched by a more specific +/// [`DIRECTIVES`] entry: the explicit one-knob level, `RUST_LOG`'s bare global +/// level, or the static `warn` default. Numeric severity, low = more severe; +/// `0` means "off / emit nothing". static LEVEL: AtomicU8 = AtomicU8::new(LEVEL_WARN); +/// Most verbose threshold across [`LEVEL`] and every [`DIRECTIVES`] entry, for +/// `max_level_hint` so the process-global gate admits everything any directive +/// could enable (the per-event [`KernelFilter::enabled`] then applies the +/// precise per-target threshold). Tracking only [`LEVEL`] here would wrongly +/// gate out a more-verbose submodule directive before it reached `enabled`. +static MAX_LEVEL: AtomicU8 = AtomicU8::new(LEVEL_WARN); + +/// Fast-path flag: whether [`DIRECTIVES`] holds any per-target directive. The +/// common one-knob / bare-level case has none, so the hot path +/// ([`threshold_for_target`]) reads [`LEVEL`] directly and never takes the +/// [`DIRECTIVES`] lock. +static HAS_DIRECTIVES: AtomicBool = AtomicBool::new(false); + +/// Per-target `RUST_LOG` thresholds `(target, level)`, applied with `EnvFilter` +/// precedence: a directive matches an event when its target is a **prefix** of +/// the event target (`event_target.starts_with(target)`), and the most specific +/// (longest) match wins. Collapsing these into one scalar would let a verbose +/// submodule directive (`databricks_sql_kernel::reader=trace`) widen the +/// canonical `klog!` target (`databricks::sql::kernel`) that `EnvFilter` would +/// keep at its own directive's level. Consulted only when [`HAS_DIRECTIVES`]. +static DIRECTIVES: OnceLock>> = OnceLock::new(); + /// Count of log records dropped because the bounded channel was full (a slow /// host callback) or the drain thread stopped. Surfaced via /// [`kernel_logging_stats`] and via a synthetic "dropped N" line the drain @@ -153,13 +180,18 @@ const INSTALL_OK: u8 = 1; /// Lost the one-global-subscriber race (e.g. `kernel_init_logging` won) — a /// benign outcome; the host picks one of the two logging routes. const INSTALL_ALREADY_SET: u8 = 2; -/// Won the subscriber but the OS refused to start the drain thread -/// (EAGAIN/ENOMEM) — a real failure the host should surface distinctly. +/// The OS refused to start the drain thread (EAGAIN/ENOMEM) before the global +/// subscriber was claimed — a real failure the host should surface distinctly. +/// NON-terminal: a later `kernel_set_log_callback` retries the install (the +/// subscriber slot was never touched), so a transient spawn failure doesn't +/// permanently disable callback logging. const INSTALL_SPAWN_FAILED: u8 = 3; -/// Outcome of the one-time subscriber install. Anything other than `INSTALL_OK` -/// means kernel logs won't reach the callback; the two failure discriminants -/// let the caller tell the benign already-installed case from a spawn failure. +/// Outcome of the subscriber install. `INSTALL_OK` and `INSTALL_ALREADY_SET` are +/// terminal (no further attempt); `INSTALL_PENDING` and `INSTALL_SPAWN_FAILED` +/// are retryable. Anything other than `INSTALL_OK` means kernel logs won't reach +/// the callback; the two failure discriminants let the caller tell the benign +/// already-installed case from a (retryable) spawn failure. static INSTALL_STATUS: AtomicU8 = AtomicU8::new(INSTALL_PENDING); /// The drain-thread spawn error string, populated only on `INSTALL_SPAWN_FAILED` @@ -178,8 +210,16 @@ static SINK: OnceLock>> = OnceLock::new(); /// the callback it just invoked is still the installed one. static NEXT_SINK_GEN: AtomicU64 = AtomicU64::new(0); -/// Guards the one-time subscriber install + channel + drain-thread spawn. -static INSTALL: Once = Once::new(); +/// Serializes install attempts (subscriber + channel + drain-thread spawn). +/// +/// Deliberately NOT a `Once`: a `Once` is consumed by the first attempt, so a +/// transient drain-thread spawn failure (EAGAIN/ENOMEM) would permanently +/// disable callback logging for the process — no later `kernel_set_log_callback` +/// could retry. A plain lock + retryable [`INSTALL_STATUS`] lets a spawn failure +/// stay non-terminal so a subsequent call tries again, while `set_global_default` +/// is still attempted at most once (only after a drain thread is confirmed up, +/// which transitions to a terminal state). +static INSTALL_LOCK: Mutex<()> = Mutex::new(()); fn severity(level: &Level) -> u8 { match *level { @@ -204,40 +244,36 @@ fn parse_level_word(s: &str) -> Option { } } -/// Derive the callback's level from a `RUST_LOG`-style directive string, matching -/// the level the stderr path (`kernel_init_logging`) would apply so the two routes -/// filter identically. Recognises a bare level (`debug`), the kernel target's -/// directive (`databricks::sql::kernel=debug` / `databricks_sql_kernel=debug`), or -/// a global fallback among comma-separated directives. Returns `None` (keep the -/// current default) if nothing matches. +/// Parse a `RUST_LOG`-style directive string into the kernel-applicable +/// per-target directives plus an optional bare global level, so the callback +/// can filter per target exactly as the stderr path (`kernel_init_logging`)'s +/// `EnvFilter` would — rather than collapsing everything into one scalar. /// -/// When several directives match, this mirrors `EnvFilter` specificity rather -/// than taking the first one listed: `EnvFilter` applies a target directive to -/// an event only when the directive's target is a **prefix of the event's -/// target** (`meta.target().starts_with(directive_target)`), and among the -/// matching directives the **most specific** (longest target) wins, independent -/// of order. So `RUST_LOG=databricks=warn,databricks::sql::kernel=debug` -/// resolves to `debug` for a `databricks::sql::kernel` event — the same -/// threshold `kernel_init_logging`'s `EnvFilter` would apply — not the -/// first-listed `warn`. On a specificity tie the later directive wins -/// (`EnvFilter` dedups identical directives last-writer-wins). A matching -/// target directive always beats a bare global level, since a target-less -/// directive is the least specific match `EnvFilter` recognises. +/// Returns `(directives, global)`: +/// +/// - `directives`: each retained `(target, level)` keeps its target string so +/// the hot path can apply `EnvFilter`'s prefix rule per event — a directive +/// matches an event only when its target is a **prefix of the event target** +/// (`event_target.starts_with(target)`), and among matches the most specific +/// (longest) wins ([`resolve_threshold`]). Keeping them separate is what +/// stops a verbose submodule directive +/// (`databricks_sql_kernel::reader::inline=trace`) from widening the +/// canonical `klog!` target (`databricks::sql::kernel`), which `EnvFilter` +/// would keep at its own `databricks::sql::kernel=error` directive. +/// - `global`: a bare level (`debug`), the least-specific match `EnvFilter` +/// recognises, used as the default for kernel targets no directive matches. /// /// Applicability is judged by [`directive_targets_kernel`], NOT a bare /// `starts_with("databricks")`: a non-matching sibling such as `databricksfoo=warn` -/// or an extension of the fixed-depth `klog!` target (`databricks::sql::kernel::foo=trace`) -/// is a prefix of no kernel event, so `EnvFilter` skips it — and so must this, -/// or it would wrongly outrank a real `databricks=debug`. A submodule directive -/// on the module-path namespace the bridge forwards -/// (`databricks_sql_kernel::session=debug`) IS honoured (most specific wins). -/// (This resolves a single scalar for the whole bridge, so with a mix of -/// targets the most specific matching directive sets the one threshold; the -/// dominant `klog!` target `databricks::sql::kernel` is resolved exactly.) -fn level_from_rust_log(rust_log: &str) -> Option { - // Best kernel-applicable target directive seen so far, as (target length - // used as the specificity key, resolved level). - let mut best_target: Option<(usize, u8)> = None; +/// or an extension of the fixed-depth `klog!` target +/// (`databricks::sql::kernel::foo=trace`) is a prefix of no kernel event, so +/// `EnvFilter` skips it — and so does this. A submodule directive on the +/// module-path namespace the bridge forwards +/// (`databricks_sql_kernel::session=debug`) IS retained (those events are +/// forwarded by `is_kernel_target`). Foreign directives (`hyper=warn`) are +/// dropped, since the bridge never forwards their events. +fn parse_rust_log(rust_log: &str) -> (Vec<(String, u8)>, Option) { + let mut directives: Vec<(String, u8)> = Vec::new(); let mut global: Option = None; for directive in rust_log.split(',') { let d = directive.trim(); @@ -249,17 +285,7 @@ fn level_from_rust_log(rust_log: &str) -> Option { let target = target.trim(); if directive_targets_kernel(target) { if let Some(l) = parse_level_word(level) { - // Longest target = most specific; on a tie the later - // directive wins (matches `EnvFilter`'s last-writer - // dedup), so replace on `>=`. - let specificity = target.len(); - let wins = match best_target { - Some((len, _)) => specificity >= len, - None => true, - }; - if wins { - best_target = Some((specificity, l)); - } + directives.push((target.to_owned(), l)); } } } @@ -272,9 +298,7 @@ fn level_from_rust_log(rust_log: &str) -> Option { } } } - // A matching target directive is always more specific than a bare global - // level, so it wins when both are present. - best_target.map(|(_, l)| l).or(global) + (directives, global) } /// The crate's module-path root: the `#[instrument]` / default-target namespace @@ -310,10 +334,45 @@ fn directive_targets_kernel(target: &str) -> bool { .any(|root| root.starts_with(target)) } -/// Returns whether an event at `level` should currently be forwarded. -fn should_emit(level: &Level) -> bool { - let configured = LEVEL.load(Ordering::Relaxed); - configured != LEVEL_OFF && severity(level) <= configured +/// Resolve the forward threshold for `target` under `EnvFilter` precedence: the +/// most specific (longest) directive whose target is a **prefix** of `target` +/// wins; on a specificity tie the later entry wins (matching `EnvFilter`'s +/// last-writer dedup); with no matching directive the `default` applies. Pure +/// (no globals) so the precedence logic is unit-testable without touching the +/// process-global filter state. +fn resolve_threshold(target: &str, default: u8, directives: &[(String, u8)]) -> u8 { + let mut best: Option<(usize, u8)> = None; + for (t, lvl) in directives { + if target.starts_with(t.as_str()) { + let specificity = t.len(); + let wins = best.is_none_or(|(len, _)| specificity >= len); + if wins { + best = Some((specificity, *lvl)); + } + } + } + best.map_or(default, |(_, l)| l) +} + +/// The current forward threshold for `target`, reading the process-global filter +/// state. Fast path: with no per-target directives (the one-knob / bare-level +/// case) this is a single relaxed load of [`LEVEL`] and never locks. +fn threshold_for_target(target: &str) -> u8 { + let default = LEVEL.load(Ordering::Relaxed); + if !HAS_DIRECTIVES.load(Ordering::Relaxed) { + return default; + } + match DIRECTIVES.get().and_then(|lock| lock.read().ok()) { + Some(dirs) => resolve_threshold(target, default, &dirs), + None => default, + } +} + +/// Returns whether an event at `level` on `target` should currently be +/// forwarded, applying the per-target threshold ([`threshold_for_target`]). +fn should_emit(target: &str, level: &Level) -> bool { + let threshold = threshold_for_target(target); + threshold != LEVEL_OFF && severity(level) <= threshold } /// Targets the bridge forwards: the `klog!` shim's `databricks::sql::kernel` @@ -323,10 +382,13 @@ fn is_kernel_target(target: &str) -> bool { target.starts_with("databricks") } -/// The configured level as a `tracing` [`LevelFilter`], for `max_level_hint` so -/// the process-global gate tracks the kernel level instead of pinning at TRACE. +/// The most-verbose configured level as a `tracing` [`LevelFilter`], for +/// `max_level_hint` so the process-global gate tracks the kernel level instead +/// of pinning at TRACE. Reads [`MAX_LEVEL`] (the max across the default and all +/// per-target directives) so a verbose submodule directive isn't gated out +/// before the per-event [`KernelFilter::enabled`] can apply it. fn current_level_filter() -> LevelFilter { - match LEVEL.load(Ordering::Relaxed) { + match MAX_LEVEL.load(Ordering::Relaxed) { LEVEL_OFF => LevelFilter::OFF, LEVEL_ERROR => LevelFilter::ERROR, LEVEL_WARN => LevelFilter::WARN, @@ -418,8 +480,12 @@ impl Filter for KernelFilter { } fn enabled(&self, meta: &Metadata<'_>, _ctx: &Context<'_, S>) -> bool { - // Event-only: never enable spans (the layer has no span consumer). - meta.is_event() && is_kernel_target(meta.target()) && should_emit(meta.level()) + // Event-only: never enable spans (the layer has no span consumer). The + // per-target threshold applies `RUST_LOG`'s `EnvFilter` precedence so a + // verbose submodule directive can't widen the canonical `klog!` target. + meta.is_event() + && is_kernel_target(meta.target()) + && should_emit(meta.target(), meta.level()) } fn max_level_hint(&self) -> Option { @@ -435,6 +501,18 @@ where let Some(tx) = SENDER.get() else { return; }; + // Once a callback has unwound the sink is poisoned and the drain thread + // drops everything until re-registration. Short-circuit HERE — before the + // field visit, the message allocation, and the enqueue — so a poisoned + // sink stops paying producer-side formatting for records it will only + // drop. Still count the loss so kernel_logging_stats stays accurate + // (parity with the drain thread's own poison drop-count; each record is + // counted exactly once — here if produced while poisoned, or by the drain + // thread if it was already queued when the poison landed). + if SINK_POISONED.load(Ordering::Relaxed) { + DROPPED.fetch_add(1, Ordering::Relaxed); + return; + } let meta = event.metadata(); let mut visitor = MessageVisitor::default(); event.record(&mut visitor); @@ -576,62 +654,192 @@ fn is_kernel_target_str() -> &'static str { crate::klog::KERNEL_LOG_TARGET } -/// Resolve the callback's numeric level from the caller's explicit `level` +/// A resolved forward filter: the default threshold for unmatched kernel +/// targets plus the per-target `RUST_LOG` directives ([`resolve_threshold`]). +struct ResolvedFilter { + /// Threshold for kernel targets no `directives` entry matches — the explicit + /// one-knob level, `RUST_LOG`'s bare global level, or the `warn` default. + default_level: u8, + /// Per-target `RUST_LOG` thresholds. Empty for the one-knob explicit-level + /// case (a uniform threshold), so the hot path stays lock-free. + directives: Vec<(String, u8)>, +} + +/// Resolve the callback's forward filter from the caller's explicit `level` /// argument, mirroring `kernel_init_logging`'s precedence so the two C-ABI /// logging routes filter identically: /// -/// 1. an explicit, recognised `level` word wins (e.g. Go's driver level -/// mapped through `DATABRICKS_LOG_LEVEL`); -/// 2. otherwise a `RUST_LOG` directive (bare or `databricks*=…`); -/// 3. otherwise the current default (`warn`), left untouched. +/// 1. an explicit, recognised `level` word wins as a UNIFORM one-knob +/// threshold (e.g. Go's driver level mapped through `DATABRICKS_LOG_LEVEL`), +/// with no per-target directives — the host asked for one level everywhere; +/// 2. otherwise `RUST_LOG`, parsed into per-target directives + a bare global +/// level ([`parse_rust_log`]), applied with `EnvFilter` precedence; +/// 3. otherwise `None` — the current filter is left untouched. /// -/// This is what keeps the callback on the one-knob contract PECOBLR-3650 -/// established: `kernel_init_logging` maps the driver level to a level string, -/// and the callback path must honour that same string rather than only -/// `RUST_LOG` — otherwise a host at `DATABRICKS_LOG_LEVEL=debug` (but no -/// `RUST_LOG`) would silently drop kernel debug lines. +/// This keeps the callback on the one-knob contract PECOBLR-3650 established: +/// `kernel_init_logging` maps the driver level to a level string, and the +/// callback path must honour that same string rather than only `RUST_LOG` — +/// otherwise a host at `DATABRICKS_LOG_LEVEL=debug` (but no `RUST_LOG`) would +/// silently drop kernel debug lines. /// -/// Note this resolves the same *level*, but the target matching differs from -/// `kernel_init_logging`: that path builds an `EnvFilter` (`::`-segment match on -/// `databricks::sql::kernel`), whereas the layer here matches the broader -/// `databricks` prefix (see `is_kernel_target`). So for a `RUST_LOG` target -/// directive the two routes select the same threshold but not necessarily the -/// identical event set. -fn resolve_callback_level(explicit: Option<&str>) -> Option { +/// Note the target matching still differs slightly from `kernel_init_logging`: +/// that path builds an `EnvFilter` (`::`-segment match), whereas this bridge +/// matches the broader `databricks` prefix (see `is_kernel_target`) for +/// forwarding, then applies the same per-target precedence for the threshold. So +/// for a `RUST_LOG` target directive the two routes select the same threshold +/// but not necessarily the identical event set. +fn resolve_filter(explicit: Option<&str>) -> Option { if let Some(word) = explicit { - // A recognised explicit level always wins. "off" is honoured (the host - // asked for silence); an unrecognised word falls through to RUST_LOG. + // A recognised explicit level always wins as a uniform threshold. "off" + // is honoured (the host asked for silence); an unrecognised word falls + // through to RUST_LOG. if let Some(l) = parse_level_word(word) { - return Some(l); + return Some(ResolvedFilter { + default_level: l, + directives: Vec::new(), + }); } } if let Ok(rust_log) = std::env::var("RUST_LOG") { - if let Some(l) = level_from_rust_log(&rust_log) { - return Some(l); + let (directives, global) = parse_rust_log(&rust_log); + if !directives.is_empty() || global.is_some() { + return Some(ResolvedFilter { + // A `RUST_LOG` with only target directives (no bare level) leaves + // unmatched kernel targets at the static `warn` default. + default_level: global.unwrap_or(LEVEL_WARN), + directives, + }); } } None } +/// Install `filter` into the process-global filter state, returning whether it +/// actually changed anything (so the caller only rebuilds the callsite interest +/// cache when it matters). Writes the directives first, then the fast-path flag, +/// then the levels, so a concurrent reader never sees `HAS_DIRECTIVES` set +/// against a stale directive list. +fn apply_filter(filter: ResolvedFilter) -> bool { + let new_default = filter.default_level; + let new_max = filter + .directives + .iter() + .map(|(_, l)| *l) + .fold(new_default, u8::max); + let has_dirs = !filter.directives.is_empty(); + + let dirs_lock = DIRECTIVES.get_or_init(|| RwLock::new(Vec::new())); + let dirs_changed = match dirs_lock.write() { + Ok(mut w) => { + let changed = *w != filter.directives; + *w = filter.directives; + changed + } + // Couldn't inspect the old list (poisoned lock) — assume changed so the + // interest cache is rebuilt conservatively. + Err(_) => true, + }; + HAS_DIRECTIVES.store(has_dirs, Ordering::Relaxed); + MAX_LEVEL.store(new_max, Ordering::Relaxed); + let prev_default = LEVEL.swap(new_default, Ordering::Relaxed); + prev_default != new_default || dirs_changed +} + +/// Stand up the process-global subscriber + drain thread, retryable across calls +/// (see [`INSTALL_LOCK`]). Returns `true` iff THIS call performed the successful +/// install (so the caller rebuilds the interest cache for the freshly-installed +/// filter). A benign lost-race or a spawn failure returns `false`; the outcome +/// is recorded in [`INSTALL_STATUS`] for the caller's return code. +/// +/// Ordering matters: stand up the drain thread FIRST, and only then claim the +/// one global subscriber via `set_global_default`. This keeps two failure modes +/// clean: +/// +/// - Spawn failure: if the OS refuses the drain thread (EAGAIN/ENOMEM) we bail +/// out BEFORE touching the global subscriber, so the slot stays free and the +/// host can still fall back to `kernel_init_logging`. The status stays +/// retryable, so a later call can try again. (Claiming the subscriber first +/// would strand it with no `SENDER`, silently dropping every event.) +/// - Lost race: if another subscriber (e.g. `kernel_init_logging`) already +/// won, we DROP the sender so the freshly-spawned drain thread's `recv()` +/// errors and it exits — no idle-thread leak, and `SENDER` stays unset so +/// `on_event` short-circuits. +/// +/// `set_global_default` is attempted at most once per process: it runs only +/// after a drain thread is confirmed up, and both its outcomes (won / lost) are +/// terminal, so a retry never re-attempts it. +fn ensure_installed() -> bool { + // Terminal states need no work and no lock. + match INSTALL_STATUS.load(Ordering::Acquire) { + INSTALL_OK | INSTALL_ALREADY_SET => return false, + _ => {} + } + let Ok(_guard) = INSTALL_LOCK.lock() else { + return false; + }; + // Re-check under the lock: another caller may have installed while we waited. + match INSTALL_STATUS.load(Ordering::Acquire) { + INSTALL_OK | INSTALL_ALREADY_SET => return false, + _ => {} + } + // Stand up the delivery path first (thread + channel), so a spawn failure + // never leaves the global subscriber slot occupied. + let (tx, rx) = sync_channel::(CHANNEL_CAPACITY); + if let Err(e) = std::thread::Builder::new() + .name("kernel-log-drain".to_owned()) + .spawn(move || drain_loop(rx)) + { + // Record the OS error distinctly so on-call can tell a spawn failure from + // the benign "already installed" case. Use `.lock().ok()` (not + // `.unwrap()`) so a poisoned mutex can't panic across the FFI boundary. + // `tx` drops here (no thread was spawned); the global subscriber is left + // untouched, and the status stays retryable for a later call. + if let Ok(mut guard) = SPAWN_ERROR.get_or_init(|| Mutex::new(None)).lock() { + *guard = Some(e.to_string()); + } + INSTALL_STATUS.store(INSTALL_SPAWN_FAILED, Ordering::Release); + return false; + } + // Drain thread is running. Now claim the one global subscriber. + let subscriber = tracing_subscriber::registry().with(KernelLogLayer.with_filter(KernelFilter)); + if tracing::subscriber::set_global_default(subscriber).is_err() { + // Another global subscriber won. Drop the sender so the drain thread + // (blocked on recv()) unblocks with an error and exits cleanly, then + // leave SENDER unset so on_event's `let Some(tx)` short-circuits. + drop(tx); + INSTALL_STATUS.store(INSTALL_ALREADY_SET, Ordering::Release); + return false; + } + // We own the subscriber AND have a live consumer. Publish SENDER only now, so + // a live producer never outlives its consumer. + let _ = SENDER.set(tx); + INSTALL_STATUS.store(INSTALL_OK, Ordering::Release); + true +} + /// Install (process-wide) a callback that receives kernel `databricks*` /// `tracing` events. `ctx` is passed back verbatim on every call. Passing a /// null `cb` is rejected with `InvalidArgument` (to detach a sink, the design /// would grow an explicit detach — v0 keeps install-only). /// /// `level` (a NUL-terminated `OFF`/`ERROR`/`WARN`/`INFO`/`DEBUG`/`TRACE` -/// string, case-insensitive, or NULL) sets the forward threshold with the same -/// precedence as `kernel_init_logging`: an explicit recognised level wins, else -/// `RUST_LOG`. A host that maps its own logger level (Go's -/// `DATABRICKS_LOG_LEVEL`) passes it here so the callback filters on the one -/// knob rather than only `RUST_LOG`. When neither resolves (NULL / unrecognised -/// level AND no matching `RUST_LOG`) the current threshold is LEFT UNCHANGED — -/// which is the static `warn` default on the first-ever call, but the -/// previously-set level on a re-registration (the level is process-global and -/// last-writer-wins only when a writer actually resolves one). +/// string, case-insensitive, or NULL) sets the forward filter with the same +/// precedence as `kernel_init_logging`: an explicit recognised level wins as a +/// UNIFORM threshold, else `RUST_LOG` is applied per target with `EnvFilter` +/// precedence (so a submodule directive doesn't widen the canonical `klog!` +/// target). A host that maps its own logger level (Go's `DATABRICKS_LOG_LEVEL`) +/// passes it here so the callback filters on the one knob rather than only +/// `RUST_LOG`. When neither resolves (NULL / unrecognised level AND no matching +/// `RUST_LOG`) the current filter is LEFT UNCHANGED — the static `warn` default +/// on the first-ever call, but the previously-set filter on a re-registration +/// (the filter is process-global and last-writer-wins only when a writer +/// actually resolves one). /// /// Returns `Internal` (with a stored last error) if a global `tracing` /// subscriber was already installed (e.g. by `kernel_init_logging`) — the two -/// are mutually exclusive; a C consumer installs exactly one. +/// are mutually exclusive; a C consumer installs exactly one — or if the +/// log-drain thread could not be spawned (a transient spawn failure is +/// retryable: a later call attempts the install again). /// /// # Safety /// `cb` must be a valid function pointer that is thread-safe, does not unwind, @@ -662,13 +870,13 @@ pub unsafe extern "C" fn kernel_set_log_callback( } else { std::ffi::CStr::from_ptr(level).to_str().ok() }; - // Track whether the level actually changed so we only rebuild the (process- - // wide, lock-taking) callsite interest cache when it matters — a same-level + // Track whether the filter actually changed so we only rebuild the (process- + // wide, lock-taking) callsite interest cache when it matters — a same-filter // ctx refresh or a call that loses the subscriber race shouldn't serialize // all logging dispatch. - let mut level_changed = false; - if let Some(resolved) = resolve_callback_level(explicit_level) { - level_changed = LEVEL.swap(resolved, Ordering::Relaxed) != resolved; + let mut filter_changed = false; + if let Some(resolved) = resolve_filter(explicit_level) { + filter_changed = apply_filter(resolved); } // Record / refresh the sink (last writer wins). Clear any prior poison: a @@ -690,65 +898,16 @@ pub unsafe extern "C" fn kernel_set_log_callback( SINK_POISONED.store(false, Ordering::Relaxed); } - // Install the process-global subscriber + drain thread exactly once. - // - // Order matters: stand up the drain thread FIRST, and only then claim the - // one global subscriber via `set_global_default`. This keeps two failure - // modes clean: - // - // - Spawn failure: if the OS refuses the drain thread (EAGAIN/ENOMEM) we - // bail out BEFORE touching the global subscriber, so the slot stays free - // and the host can still fall back to `kernel_init_logging` for the rest - // of the process. (Claiming the subscriber first would strand it with no - // `SENDER`, silently dropping every event with no recovery path.) - // - Lost race: if another subscriber (e.g. `kernel_init_logging`) already - // won, we DROP the sender so the freshly-spawned drain thread's `recv()` - // errors and it exits — no idle-thread leak, and `SENDER` stays unset so - // `on_event` short-circuits. - let mut did_install = false; - INSTALL.call_once(|| { - did_install = true; - // Stand up the delivery path first (thread + channel), so a spawn - // failure never leaves the global subscriber slot occupied. - let (tx, rx) = sync_channel::(CHANNEL_CAPACITY); - if let Err(e) = std::thread::Builder::new() - .name("kernel-log-drain".to_owned()) - .spawn(move || drain_loop(rx)) - { - // Record the OS error distinctly so on-call can tell a spawn failure - // from the benign "already installed" case. Use `.lock().ok()` (not - // `.unwrap()`) so a poisoned mutex can't panic across the FFI - // boundary — the message is best-effort diagnostics. `tx` drops here - // (no thread was spawned); the global subscriber is left untouched. - if let Ok(mut guard) = SPAWN_ERROR.get_or_init(|| Mutex::new(None)).lock() { - *guard = Some(e.to_string()); - } - INSTALL_STATUS.store(INSTALL_SPAWN_FAILED, Ordering::Release); - return; - } - // Drain thread is running. Now claim the one global subscriber. - let subscriber = - tracing_subscriber::registry().with(KernelLogLayer.with_filter(KernelFilter)); - if tracing::subscriber::set_global_default(subscriber).is_err() { - // Another global subscriber won. Drop the sender so the drain thread - // (blocked on recv()) unblocks with an error and exits cleanly, then - // leave SENDER unset so on_event's `let Some(tx)` short-circuits. - drop(tx); - INSTALL_STATUS.store(INSTALL_ALREADY_SET, Ordering::Release); - return; - } - // We own the subscriber AND have a live consumer. Publish SENDER only - // now, so a live producer never outlives its consumer. - let _ = SENDER.set(tx); - INSTALL_STATUS.store(INSTALL_OK, Ordering::Release); - }); + // Install the process-global subscriber + drain thread (retryable across + // calls after a transient spawn failure — see ensure_installed). + let did_install = ensure_installed(); // Rebuild the process-wide callsite interest cache only when it can matter: - // on the install that set our filter, or when a later call changed LEVEL. - // set_global_default rebuilds on its own, but the level may have been set - // before install, and a re-level after install needs a rebuild too; a - // same-level ctx refresh or a race-loss does not (the rebuild takes the - // global callsite lock and re-evaluates every callsite in the binary). - if did_install || level_changed { + // on the install that set our filter, or when a later call changed the + // filter. set_global_default rebuilds on its own, but the filter may have + // been set before install, and a re-filter after install needs a rebuild + // too; a same-filter ctx refresh or a race-loss does not (the rebuild takes + // the global callsite lock and re-evaluates every callsite in the binary). + if did_install || filter_changed { tracing::callsite::rebuild_interest_cache(); } @@ -767,8 +926,9 @@ pub unsafe extern "C" fn kernel_set_log_callback( ), )) } - // INSTALL_ALREADY_SET (or a stale PENDING, which can't happen after - // call_once): a global subscriber was already installed. + // INSTALL_ALREADY_SET (or a still-PENDING install we couldn't take the + // lock for): a global subscriber was already installed, or the install + // couldn't run. Either way kernel logs won't reach this callback. _ => crate::c_abi::error::store_and_code(Error::new( ErrorCode::Internal, "kernel_set_log_callback: a global tracing subscriber was already installed \ @@ -798,10 +958,16 @@ pub unsafe extern "C" fn kernel_set_log_callback( /// "logs are quiet" from "logs are being dropped / the sink died / never /// installed" (parity with the napi binding's `kernelLoggingStats()`). /// +/// Clears the thread-local last-error on entry like every other C-ABI entry +/// point, so a host that calls this (successful, infallible) accessor between a +/// failed API call and reading the error doesn't observe the prior call's stale +/// error through it. +/// /// # Safety /// Each non-null out-param must point to a writable `bool` / `uint64_t`. #[no_mangle] pub unsafe extern "C" fn kernel_logging_stats(installed: *mut bool, dropped: *mut u64) { + crate::c_abi::error::clear_error(); if !installed.is_null() { // "Currently delivering": won the subscriber AND not poisoned. A poisoned // sink is installed-but-dead, which must not read as healthy. @@ -906,116 +1072,115 @@ mod tests { #[test] fn should_emit_respects_configured_level() { + let target = crate::klog::KERNEL_LOG_TARGET; LEVEL.store(LEVEL_INFO, Ordering::Relaxed); - assert!(should_emit(&Level::ERROR)); - assert!(should_emit(&Level::INFO)); - assert!(!should_emit(&Level::DEBUG)); + assert!(should_emit(target, &Level::ERROR)); + assert!(should_emit(target, &Level::INFO)); + assert!(!should_emit(target, &Level::DEBUG)); LEVEL.store(LEVEL_OFF, Ordering::Relaxed); - assert!(!should_emit(&Level::ERROR)); + assert!(!should_emit(target, &Level::ERROR)); LEVEL.store(LEVEL_WARN, Ordering::Relaxed); // restore } #[test] - fn level_from_rust_log_reads_kernel_and_global_directives() { - // The kernel target's own directive (either spelling) wins. - assert_eq!( - level_from_rust_log("databricks::sql::kernel=debug"), - Some(LEVEL_DEBUG) - ); + fn parse_rust_log_keeps_kernel_directives_and_global() { + // Kernel directives are retained with their target (for per-event prefix + // matching); foreign directives are dropped; a bare word is the global. + let (dirs, global) = parse_rust_log("hyper=off,databricks::sql::kernel=info,rustls=warn"); assert_eq!( - level_from_rust_log("databricks_sql_kernel=trace"), - Some(LEVEL_TRACE) + dirs, + vec![("databricks::sql::kernel".to_owned(), LEVEL_INFO)] ); - // A kernel directive still wins when mixed with foreign ones. + assert_eq!(global, None); + + // Either kernel spelling is kept. + let (dirs, _) = parse_rust_log("databricks_sql_kernel=trace"); assert_eq!( - level_from_rust_log("hyper=off,databricks::sql::kernel=info,rustls=warn"), - Some(LEVEL_INFO) + dirs, + vec![("databricks_sql_kernel".to_owned(), LEVEL_TRACE)] ); - // A bare global level applies when no kernel directive is present. - assert_eq!(level_from_rust_log("debug"), Some(LEVEL_DEBUG)); - // Nothing recognisable → None (keep the default). - assert_eq!(level_from_rust_log("hyper=warn"), None); - assert_eq!(level_from_rust_log(""), None); + + // A bare global level with no kernel directive. + let (dirs, global) = parse_rust_log("debug"); + assert!(dirs.is_empty()); + assert_eq!(global, Some(LEVEL_DEBUG)); + + // Nothing kernel-applicable and no bare level → empty. + let (dirs, global) = parse_rust_log("hyper=warn"); + assert!(dirs.is_empty()); + assert_eq!(global, None); + let (dirs, global) = parse_rust_log(""); + assert!(dirs.is_empty()); + assert_eq!(global, None); + + // Non-matching databricks siblings and over-specific extensions of the + // fixed-depth klog target are dropped (prefixes of no kernel event). + let (dirs, _) = parse_rust_log("databricksfoo=warn,databricks::sql::kernel::foo=trace"); + assert!(dirs.is_empty()); } #[test] - fn level_from_rust_log_mirrors_envfilter_specificity() { - // With a broad and a specific `databricks*` directive both present, the - // MORE SPECIFIC (longer target) one wins — matching `EnvFilter`, not - // first-match-wins — and the result is order-independent. - assert_eq!( - level_from_rust_log("databricks=warn,databricks::sql::kernel=debug"), - Some(LEVEL_DEBUG), - "the specific kernel directive must win over the broad databricks=warn" - ); - assert_eq!( - level_from_rust_log("databricks::sql::kernel=debug,databricks=warn"), - Some(LEVEL_DEBUG), - "resolution must not depend on directive order" - ); - // Same, for the underscore module-path spelling. - assert_eq!( - level_from_rust_log("databricks=warn,databricks_sql_kernel=trace"), - Some(LEVEL_TRACE) - ); - assert_eq!( - level_from_rust_log("databricks_sql_kernel=trace,databricks=warn"), - Some(LEVEL_TRACE) - ); - // A targeted `databricks*` directive beats a bare global level in either - // order (a target-less directive is the least specific match). - assert_eq!( - level_from_rust_log("info,databricks=error"), - Some(LEVEL_ERROR) + fn resolve_threshold_per_target_does_not_widen_klog() { + // The reviewer's case: a klog directive and an unrelated submodule + // directive must NOT widen each other. Each target resolves against only + // the directives whose target is a PREFIX of it (EnvFilter's rule), so a + // single scalar can't collapse them into the most verbose one. + let (dirs, global) = parse_rust_log( + "databricks::sql::kernel=error,databricks_sql_kernel::reader::inline=trace", ); + assert_eq!(global, None); + let default = global.unwrap_or(LEVEL_WARN); + // The canonical klog target keeps ERROR — the reader::inline=trace + // directive is not a prefix of it, so it does not apply (previously the + // single scalar collapsed to TRACE and widened klog to trace/debug). assert_eq!( - level_from_rust_log("databricks=error,info"), - Some(LEVEL_ERROR) + resolve_threshold("databricks::sql::kernel", default, &dirs), + LEVEL_ERROR ); - // A submodule directive on the module-path namespace the bridge forwards - // (`databricks_sql_kernel::*`) is honoured (most specific wins) rather - // than silently ignored — the host asked for that submodule. + // A module event under the submodule keeps its own TRACE directive. assert_eq!( - level_from_rust_log("databricks=warn,databricks_sql_kernel::session=debug"), - Some(LEVEL_DEBUG) + resolve_threshold( + "databricks_sql_kernel::reader::inline::stream", + default, + &dirs + ), + LEVEL_TRACE ); + // A kernel target matched by neither directive falls back to the default. assert_eq!( - level_from_rust_log("databricks_sql_kernel::session=debug"), - Some(LEVEL_DEBUG) + resolve_threshold("databricks_sql_kernel::session", default, &dirs), + LEVEL_WARN ); } #[test] - fn level_from_rust_log_ignores_non_matching_databricks_siblings() { - // `EnvFilter` applies a target directive only when its target is a - // prefix of the event target. A longer `databricks`-prefixed sibling - // that matches NO kernel target must NOT outrank a real `databricks=` - // directive just because it's longer. + fn resolve_threshold_most_specific_wins_order_independent() { + // Longest matching prefix wins, independent of order (EnvFilter dedup + // is last-writer on a tie, so we replace on `>=`). + let dirs = vec![ + ("databricks".to_owned(), LEVEL_WARN), + ("databricks::sql::kernel".to_owned(), LEVEL_DEBUG), + ]; assert_eq!( - level_from_rust_log("databricksfoo=warn,databricks=debug"), - Some(LEVEL_DEBUG), - "an unrelated databricks-prefixed sibling must be ignored" + resolve_threshold("databricks::sql::kernel", LEVEL_WARN, &dirs), + LEVEL_DEBUG ); - // A directive DEEPER than the klog target matches no emitted event - // (klog stamps exactly `databricks::sql::kernel`), so it's skipped and - // the broad `databricks=debug` applies. + let dirs_rev = vec![ + ("databricks::sql::kernel".to_owned(), LEVEL_DEBUG), + ("databricks".to_owned(), LEVEL_WARN), + ]; assert_eq!( - level_from_rust_log("databricks::sql::kernel::foo=trace,databricks=debug"), - Some(LEVEL_DEBUG), - "a directive deeper than the kernel target must be ignored" + resolve_threshold("databricks::sql::kernel", LEVEL_WARN, &dirs_rev), + LEVEL_DEBUG ); - // A non-matching sibling as the ONLY databricks directive must fall back - // to the bare global level (not the sibling's level). + // A databricks event matched only by the broad directive takes its level, + // not the more specific sibling's. assert_eq!( - level_from_rust_log("databricksfoo=trace,info"), - Some(LEVEL_INFO) - ); - // Two equal-length siblings that match no kernel root resolve to None - // (keep the default) rather than letting order pick a bogus level. - assert_eq!( - level_from_rust_log("databricks::aa=warn,databricks::bb=debug"), - None + resolve_threshold("databricks::other", LEVEL_INFO, &dirs), + LEVEL_WARN ); + // No matching directive → the default. + assert_eq!(resolve_threshold("databricks", LEVEL_INFO, &[]), LEVEL_INFO); } #[test] @@ -1039,22 +1204,31 @@ mod tests { } #[test] - fn resolve_callback_level_prefers_explicit_over_rust_log() { + fn resolve_filter_explicit_level_is_uniform_one_knob() { // An explicit, recognised level wins outright — this is the one-knob // path (Go maps DATABRICKS_LOG_LEVEL and passes it in), independent of - // whatever RUST_LOG happens to be. We don't touch the process RUST_LOG + // whatever RUST_LOG happens to be, and carries NO per-target directives + // (one level applies everywhere). We don't touch the process RUST_LOG // here (that would race other tests); an explicit level short-circuits // before RUST_LOG is ever read. - assert_eq!(resolve_callback_level(Some("debug")), Some(LEVEL_DEBUG)); - assert_eq!(resolve_callback_level(Some("OFF")), Some(LEVEL_OFF)); - assert_eq!(resolve_callback_level(Some("Error")), Some(LEVEL_ERROR)); + let f = resolve_filter(Some("debug")).expect("recognised level resolves"); + assert_eq!(f.default_level, LEVEL_DEBUG); + assert!( + f.directives.is_empty(), + "a one-knob explicit level carries no per-target directives" + ); + assert_eq!( + resolve_filter(Some("OFF")).unwrap().default_level, + LEVEL_OFF + ); + assert_eq!( + resolve_filter(Some("Error")).unwrap().default_level, + LEVEL_ERROR + ); // An unrecognised explicit word falls through (to RUST_LOG, else None). - // With no kernel/global RUST_LOG directive this yields None regardless - // of the ambient value, so assert only the None-or-Some shape is sane by - // checking a clearly-bogus word doesn't parse as a level itself. assert_eq!(parse_level_word("not-a-level"), None); - // NULL/absent explicit level defers to RUST_LOG (covered by - // level_from_rust_log tests); nothing recognisable → None (keep default). + // NULL/absent explicit level defers to RUST_LOG (covered by the + // parse_rust_log / resolve_threshold tests). } #[test] diff --git a/tests/v0_c_abi_log_callback.rs b/tests/v0_c_abi_log_callback.rs index 49f23015..829797a3 100644 --- a/tests/v0_c_abi_log_callback.rs +++ b/tests/v0_c_abi_log_callback.rs @@ -269,9 +269,50 @@ fn log_callback_delivers_and_level_gates_end_to_end() { (before={dropped_before}, after={dropped_after})" ); + // === Step 5: re-registering a good callback after poison restores delivery. + // === + // The host's documented recovery path: install a fresh, well-behaved + // callback. Registration clears the poison and starts a new generation, so + // `installed` must flip back to true and a NEW event must be delivered again + // — proving a single misbehaving callback doesn't permanently wedge the + // bridge for the rest of the process. + let recover_ctx: Box = Box::new(0x600D); + let recover_ctx_ptr = Box::into_raw(recover_ctx) as *mut c_void; + let level_trace3 = std::ffi::CString::new("trace").unwrap(); + let rc = unsafe { + kernel_set_log_callback(Some(capture_cb), recover_ctx_ptr, level_trace3.as_ptr()) + }; + assert_eq!( + rc, + KernelStatusCode::Success, + "re-registering a good callback after poison must succeed; got {rc:?}" + ); + + let mut installed_recovered = false; + let mut dropped_recovered = 0u64; + unsafe { + databricks_sql_kernel::c_abi::logging::kernel_logging_stats( + &mut installed_recovered, + &mut dropped_recovered, + ) + }; + assert!( + installed_recovered, + "re-registering a good callback must clear the poison and flip installed back to true" + ); + + let recovery_marker = "probe-recovered-e5"; + tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "{}", recovery_marker); + let got = wait_until(|g| saw_marker(g, recovery_marker)); + assert!( + saw_marker(&got, recovery_marker), + "delivery must resume after re-registering a good callback post-poison; captured={got:?}" + ); + // Reclaim the leaked ctx markers (kept alive across the calls above). unsafe { drop(Box::from_raw(ctx_ptr as *mut u64)); drop(Box::from_raw(panic_ctx_ptr as *mut u64)); + drop(Box::from_raw(recover_ctx_ptr as *mut u64)); } } From 3f779d10548b79bbcc2c1a4d37556a940db2513f Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sat, 18 Jul 2026 12:28:26 +0000 Subject: [PATCH 09/15] fix(c-abi): tighten log-callback target routing, RUST_LOG parsing, install window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address the follow-up log-callback review findings: - Target-only RUST_LOG directives: parse_rust_log now reads a bare kernel target (`databricks::sql::kernel`, no `=level`) as that target at TRACE, mirroring EnvFilter — previously it was ignored, leaving the callback at WARN where kernel_init_logging emits debug/trace. - Silent-drop window on install: the delivery channel sender now lives in the KernelLogLayer instance instead of a separately-published global, so set_global_default publishes the subscriber and its sender atomically. A concurrent kernel log can no longer reach on_event after the subscriber is visible but before the sender exists (which dropped it uncounted). - Runtime target routing: is_kernel_target now matches on `::` segment boundaries (exact roots + submodules) instead of a raw starts_with("databricks"), so unrelated databricks-prefixed host/library targets (databricksfoo, another databricks_* crate) aren't routed into the kernel callback. - Tests: target-only directive parsing, is_kernel_target segment-boundary matching, and a C-ABI test that seeds a stale last-error and asserts kernel_logging_stats clears it on entry. Signed-off-by: Mani Kaustubh Mathur --- src/c_abi/logging.rs | 139 +++++++++++++++++++++++++-------- tests/v0_c_abi_log_callback.rs | 37 ++++++++- 2 files changed, 143 insertions(+), 33 deletions(-) diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs index fa7fdd2c..ac0444a3 100644 --- a/src/c_abi/logging.rs +++ b/src/c_abi/logging.rs @@ -198,10 +198,6 @@ static INSTALL_STATUS: AtomicU8 = AtomicU8::new(INSTALL_PENDING); /// so the returned `Internal` can carry the underlying OS error for triage. static SPAWN_ERROR: OnceLock>> = OnceLock::new(); -/// Producer end, published once after the drain thread is confirmed running so -/// a live producer never outlives its consumer. -static SENDER: OnceLock> = OnceLock::new(); - /// Current sink. Last-writer-wins; read by the drain thread per record. static SINK: OnceLock>> = OnceLock::new(); @@ -263,6 +259,10 @@ fn parse_level_word(s: &str) -> Option { /// - `global`: a bare level (`debug`), the least-specific match `EnvFilter` /// recognises, used as the default for kernel targets no directive matches. /// +/// A directive with no `=` is a bare LEVEL (`debug` → global) or a bare TARGET; +/// `EnvFilter` reads a bare kernel target (`databricks::sql::kernel`) as that +/// target at TRACE, so it is retained as `(target, TRACE)` rather than ignored. +/// /// Applicability is judged by [`directive_targets_kernel`], NOT a bare /// `starts_with("databricks")`: a non-matching sibling such as `databricksfoo=warn` /// or an extension of the fixed-depth `klog!` target @@ -290,10 +290,17 @@ fn parse_rust_log(rust_log: &str) -> (Vec<(String, u8)>, Option) { } } None => { - // A bare word is either a global level (`debug`) or a bare target; - // only treat it as a level if it parses as one. + // A directive with no `=` is either a bare level (`debug`) or a + // target with no level. `EnvFilter` reads a bare level as the + // global and a bare TARGET as "that target at TRACE" (the max), + // so a kernel target-only directive (`databricks::sql::kernel`) + // must raise the threshold to TRACE — not be ignored, which + // would leave the callback at WARN where kernel_init_logging + // emits debug/trace. if let Some(l) = parse_level_word(d) { global = Some(l); + } else if directive_targets_kernel(d) { + directives.push((d.to_owned(), LEVEL_TRACE)); } } } @@ -375,11 +382,26 @@ fn should_emit(target: &str, level: &Level) -> bool { threshold != LEVEL_OFF && severity(level) <= threshold } -/// Targets the bridge forwards: the `klog!` shim's `databricks::sql::kernel` -/// and kernel module paths (`databricks_sql_kernel::*`). A raw `starts_with` -/// (not a `::`-segmented filter) so the underscore module-path variants match. +/// Whether `target` is exactly `root` or a `::`-delimited submodule of it +/// (`root::…`) — a SEGMENT-boundary match, not a raw prefix. This is what keeps +/// an unrelated sibling like `databricksfoo` or `databricks_sql_kernel_ext` from +/// matching `databricks_sql_kernel`: the byte after the root must be a `::` +/// separator (or end of string), never a bare identifier continuation. +fn is_target_or_submodule(target: &str, root: &str) -> bool { + target + .strip_prefix(root) + .is_some_and(|rest| rest.is_empty() || rest.starts_with("::")) +} + +/// Targets the bridge forwards: the `klog!` shim's `databricks::sql::kernel` (and +/// any submodule of it) and the crate's module paths (`databricks_sql_kernel` +/// and `databricks_sql_kernel::…`). A SEGMENT-boundary match, NOT a raw +/// `starts_with("databricks")` — the latter would route unrelated +/// `databricks`-prefixed host/library targets (`databricksfoo`, another +/// `databricks_*` crate) into the kernel callback. fn is_kernel_target(target: &str) -> bool { - target.starts_with("databricks") + is_target_or_submodule(target, crate::klog::KERNEL_LOG_TARGET) + || is_target_or_submodule(target, KERNEL_MODULE_ROOT) } /// The most-verbose configured level as a `tracing` [`LevelFilter`], for @@ -468,7 +490,17 @@ impl Visit for MessageVisitor { /// Process-global `tracing` Layer: formats each kernel event and enqueues it /// (drop-on-full). The per-layer [`KernelFilter`] already excludes foreign /// targets and below-level events. -struct KernelLogLayer; +/// +/// The producer end of the delivery channel lives HERE, in the layer instance, +/// rather than in a separately-published global. `set_global_default` makes the +/// subscriber (and this layer) visible atomically, so from the instant an event +/// can reach [`on_event`](KernelLogLayer::on_event) the sender is already +/// present — there is no window where the subscriber is installed but the sender +/// isn't yet published (which would silently drop a concurrent kernel log +/// without counting it). +struct KernelLogLayer { + tx: SyncSender, +} /// Per-layer filter gating the bridge: foreign callsites cache off, kernel /// callsites re-evaluate per event, and `max_level_hint` tracks the level. @@ -498,9 +530,6 @@ where S: Subscriber + for<'a> LookupSpan<'a>, { fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { - let Some(tx) = SENDER.get() else { - return; - }; // Once a callback has unwound the sink is poisoned and the drain thread // drops everything until re-registration. Short-circuit HERE — before the // field visit, the message allocation, and the enqueue — so a poisoned @@ -525,7 +554,7 @@ where // task on a slow host callback. Count the loss so it's observable (via // kernel_logging_stats and the drain thread's synthetic recovery line) // rather than vanishing silently. - if tx.try_send(record).is_err() { + if self.tx.try_send(record).is_err() { DROPPED.fetch_add(1, Ordering::Relaxed); } } @@ -759,11 +788,17 @@ fn apply_filter(filter: ResolvedFilter) -> bool { /// out BEFORE touching the global subscriber, so the slot stays free and the /// host can still fall back to `kernel_init_logging`. The status stays /// retryable, so a later call can try again. (Claiming the subscriber first -/// would strand it with no `SENDER`, silently dropping every event.) +/// would strand it with no drain thread, silently dropping every event.) /// - Lost race: if another subscriber (e.g. `kernel_init_logging`) already -/// won, we DROP the sender so the freshly-spawned drain thread's `recv()` -/// errors and it exits — no idle-thread leak, and `SENDER` stays unset so -/// `on_event` short-circuits. +/// won, `set_global_default` drops the subscriber it was handed — and with +/// it the [`KernelLogLayer`]'s sender — so the freshly-spawned drain +/// thread's `recv()` errors and it exits (no idle-thread leak). No global +/// sender was ever published, so nothing can enqueue after the loss. +/// +/// The sender lives in the layer instance (not a separately-published global), +/// so there is no window where the subscriber is visible but the sender isn't +/// yet published: a concurrent kernel log in that gap would otherwise reach +/// `on_event`, find no sender, and be dropped WITHOUT being counted. /// /// `set_global_default` is attempted at most once per process: it runs only /// after a drain thread is confirmed up, and both its outcomes (won / lost) are @@ -800,19 +835,19 @@ fn ensure_installed() -> bool { INSTALL_STATUS.store(INSTALL_SPAWN_FAILED, Ordering::Release); return false; } - // Drain thread is running. Now claim the one global subscriber. - let subscriber = tracing_subscriber::registry().with(KernelLogLayer.with_filter(KernelFilter)); + // Drain thread is running. Build the layer holding the sender, then claim the + // one global subscriber. Because the sender is inside the layer, it is + // published atomically with the subscriber — on_event never observes an + // installed-but-senderless state. + let subscriber = + tracing_subscriber::registry().with(KernelLogLayer { tx }.with_filter(KernelFilter)); if tracing::subscriber::set_global_default(subscriber).is_err() { - // Another global subscriber won. Drop the sender so the drain thread - // (blocked on recv()) unblocks with an error and exits cleanly, then - // leave SENDER unset so on_event's `let Some(tx)` short-circuits. - drop(tx); + // Another global subscriber won. `set_global_default` dropped the + // subscriber (and the layer's sender) on the error path, so the drain + // thread's blocked `recv()` unblocks with an error and it exits cleanly. INSTALL_STATUS.store(INSTALL_ALREADY_SET, Ordering::Release); return false; } - // We own the subscriber AND have a live consumer. Publish SENDER only now, so - // a live producer never outlives its consumer. - let _ = SENDER.set(tx); INSTALL_STATUS.store(INSTALL_OK, Ordering::Release); true } @@ -1119,6 +1154,27 @@ mod tests { assert!(dirs.is_empty()); } + #[test] + fn parse_rust_log_target_only_directive_is_trace() { + // `EnvFilter` reads a bare kernel target (no `=level`) as that target at + // TRACE — it must NOT be ignored, which would leave the callback at WARN + // where kernel_init_logging emits trace. + let (dirs, global) = parse_rust_log("databricks::sql::kernel"); + assert_eq!( + dirs, + vec![("databricks::sql::kernel".to_owned(), LEVEL_TRACE)] + ); + assert_eq!(global, None); + // A foreign target-only directive is dropped; a kernel one becomes TRACE; + // a bare level word still sets the global. + let (dirs, global) = parse_rust_log("hyper,databricks_sql_kernel::session,info"); + assert_eq!( + dirs, + vec![("databricks_sql_kernel::session".to_owned(), LEVEL_TRACE)] + ); + assert_eq!(global, Some(LEVEL_INFO)); + } + #[test] fn resolve_threshold_per_target_does_not_widen_klog() { // The reviewer's case: a klog directive and an unrelated submodule @@ -1310,15 +1366,34 @@ mod tests { assert_eq!(v.finish(), "hello statement_id=abc-123"); } - /// Drift guard: the bridge routes on the `databricks` prefix; the kernel - /// stamps every `klog!` with `KERNEL_LOG_TARGET`. If that constant ever - /// changed to a non-`databricks` prefix, kernel logs would silently stop - /// reaching the callback — pin the two together. + /// Drift guard: the bridge routes kernel events by matching the `klog!` + /// target root; the kernel stamps every `klog!` with `KERNEL_LOG_TARGET`. If + /// that constant ever changed out from under the routing roots, kernel logs + /// would silently stop reaching the callback — pin the two together. #[test] fn filter_prefix_still_matches_kernel_emit_target() { assert!(is_kernel_target(crate::klog::KERNEL_LOG_TARGET)); } + #[test] + fn is_kernel_target_matches_only_roots_and_submodules() { + // The kernel's own targets — exact roots and their `::` submodules — are + // forwarded. + assert!(is_kernel_target(crate::klog::KERNEL_LOG_TARGET)); + assert!(is_kernel_target("databricks::sql::kernel::reader")); + assert!(is_kernel_target("databricks_sql_kernel")); + assert!(is_kernel_target("databricks_sql_kernel::session")); + assert!(is_kernel_target("databricks_sql_kernel::reader::inline")); + // Unrelated `databricks`-prefixed targets are NOT forwarded: matching is + // on a `::` SEGMENT boundary, not a raw `starts_with("databricks")`, so a + // sibling crate/library log can't be routed into the kernel callback. + assert!(!is_kernel_target("databricksfoo")); + assert!(!is_kernel_target("databricks_sql_kernel_ext")); + assert!(!is_kernel_target("databricks::sql::other")); + assert!(!is_kernel_target("databricks")); + assert!(!is_kernel_target("hyper")); + } + // NOTE: the end-to-end "MessageVisitor renders a REAL tracing event" test // lives in `tests/v0_c_abi_log_callback.rs` (a separate binary), NOT here. // Installing any `tracing` subscriber (even a thread-local `with_default`) diff --git a/tests/v0_c_abi_log_callback.rs b/tests/v0_c_abi_log_callback.rs index 829797a3..0039193f 100644 --- a/tests/v0_c_abi_log_callback.rs +++ b/tests/v0_c_abi_log_callback.rs @@ -31,7 +31,8 @@ use std::os::raw::{c_char, c_int, c_void}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; -use databricks_sql_kernel::c_abi::logging::kernel_set_log_callback; +use databricks_sql_kernel::c_abi::error::{kernel_get_last_error, KernelError}; +use databricks_sql_kernel::c_abi::logging::{kernel_logging_stats, kernel_set_log_callback}; use databricks_sql_kernel::c_abi::KernelStatusCode; // Captured (level, target, message) tuples, keyed via a process-global slot the @@ -316,3 +317,37 @@ fn log_callback_delivers_and_level_gates_end_to_end() { drop(Box::from_raw(recover_ctx_ptr as *mut u64)); } } + +/// `kernel_logging_stats` clears the thread-local last-error on entry like every +/// other C-ABI entry point, so a host that polls this infallible accessor +/// between a failed call and reading the error doesn't observe the prior error +/// through it. Runs on its own test thread (last-error is thread-local), and the +/// null-cb rejection that seeds the error returns BEFORE any install logic, so +/// this test is independent of the delivery test's process-global subscriber. +#[test] +fn kernel_logging_stats_clears_stale_last_error() { + // Seed a stale error on this thread: a null callback is rejected with + // InvalidArgument and stores a last error. + let rc = unsafe { kernel_set_log_callback(None, std::ptr::null_mut(), std::ptr::null()) }; + assert_eq!( + rc, + KernelStatusCode::InvalidArgument, + "a null callback must be rejected and seed a last error" + ); + let mut seeded = std::mem::MaybeUninit::::uninit(); + assert!( + unsafe { kernel_get_last_error(seeded.as_mut_ptr()) }, + "precondition: the null-cb rejection must have seeded a last error" + ); + + // The infallible stats accessor must clear the stale error on entry. + let mut installed = false; + let mut dropped = 0u64; + unsafe { kernel_logging_stats(&mut installed, &mut dropped) }; + + let mut after = std::mem::MaybeUninit::::uninit(); + assert!( + !unsafe { kernel_get_last_error(after.as_mut_ptr()) }, + "kernel_logging_stats must clear the stale last error on entry" + ); +} From 95c0c62707e8c6e059058d9cedfe1a806f32cf51 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sat, 18 Jul 2026 15:28:30 +0000 Subject: [PATCH 10/15] fix(c-abi): bump ABI version for log-callback symbols; tighten directive matching and throttle drop notices The log-callback bridge added exported symbols (kernel_set_log_callback, kernel_logging_stats, kernel_log_callback) without bumping the C-ABI version, so a consumer built against the new header could link an older library missing them and fail only at load/run time. Bump KERNEL_ABI_VERSION and DATABRICKS_KERNEL_ABI_VERSION to 2 in lockstep, widen the bump policy to cover symbol-set changes, and add the version-lockstep assertion to the C smoke tests (the Rust doc claimed it existed but no C check did). Also: - directive_targets_kernel now uses the same segment-boundary helper as is_kernel_target, so a module-root sibling (databricks_sql_kernel_ext) no longer raw-prefix-matches and needlessly raises MAX_LEVEL / takes the directive scan path. - Throttle the drain thread's synthetic "dropped N" notice to at most one per second, so sustained channel overflow can't double callback invocations and amplify the backlog; kernel_logging_stats still carries the exact cumulative count. - Add tests/c/log_callback_smoke.c: a standalone C binary that installs a callback with no prior init_logging, so it exercises the success path (install -> Success, logging_stats installed=true) and catches header/cdylib callback ABI drift, complementing session_smoke.c's mutual-exclusion-only coverage. Signed-off-by: Mani Kaustubh Mathur --- include/databricks_kernel.h | 11 ++-- src/c_abi/logging.rs | 66 +++++++++++++++------- src/c_abi/mod.rs | 21 ++++--- tests/c/log_callback_smoke.c | 105 +++++++++++++++++++++++++++++++++++ 4 files changed, 172 insertions(+), 31 deletions(-) create mode 100644 tests/c/log_callback_smoke.c diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 4408ca8c..e55a330a 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -55,7 +55,9 @@ * otherwise a layout change (e.g. a reordered `KernelStatusCode`) would be * misread as valid data rather than surfaced as a clean error. The macro is * bumped in lockstep with the Rust `KERNEL_ABI_VERSION` on any layout or - * semantic change. + * semantic change AND on any change to the exported symbol set (a + * consumer built against a header declaring a newer symbol would otherwise + * link an older library missing it and fail only at load/run time). * * ## Lifecycle & threading notes * @@ -108,7 +110,7 @@ extern "C" { * load time and refuse to run on a mismatch (see "ABI versioning" above). * Bumped in lockstep with the Rust `KERNEL_ABI_VERSION`. */ -#define DATABRICKS_KERNEL_ABI_VERSION 1 +#define DATABRICKS_KERNEL_ABI_VERSION 2 /* Version of the C ABI compiled into the linked library. Infallible and * side-effect-free. */ @@ -329,8 +331,9 @@ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); * `message` are valid only for the duration of the call — copy them out. * Records are enqueued on a bounded channel and DROPPED on overflow (logs are * advisory and never back-pressure a kernel hot path); the drop count is - * observable via kernel_logging_stats and a synthetic "N dropped" line the - * drain thread emits through the callback on recovery. + * observable via kernel_logging_stats (exact cumulative count) and a synthetic + * "N dropped" line the drain thread emits through the callback on recovery + * (throttled to at most once per second so it can't amplify a slow callback). * * The `level` PARAMETER (OFF/ERROR/WARN/INFO/DEBUG/TRACE, case-insensitive, or * NULL) sets the forward threshold with the SAME precedence as diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs index ac0444a3..594ee510 100644 --- a/src/c_abi/logging.rs +++ b/src/c_abi/logging.rs @@ -72,6 +72,7 @@ use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; use std::sync::{Mutex, OnceLock, RwLock}; +use std::time::{Duration, Instant}; use tracing::field::{Field, Visit}; use tracing::level_filters::LevelFilter; use tracing::subscriber::Interest; @@ -123,6 +124,13 @@ struct Sink { const CHANNEL_CAPACITY: usize = 4096; +/// Minimum spacing between synthetic "dropped N" notices the drain thread emits +/// through the callback. Bounds notice frequency under sustained overflow so an +/// already-slow callback isn't handed ~2× the invocations (a notice before every +/// real record); the exact cumulative count remains available via +/// [`kernel_logging_stats`]. +const NOTICE_MIN_INTERVAL: Duration = Duration::from_secs(1); + const LEVEL_OFF: u8 = 0; const LEVEL_ERROR: u8 = 1; const LEVEL_WARN: u8 = 2; @@ -160,9 +168,11 @@ static DIRECTIVES: OnceLock>> = OnceLock::new(); /// Count of log records dropped because the bounded channel was full (a slow /// host callback) or the drain thread stopped. Surfaced via -/// [`kernel_logging_stats`] and via a synthetic "dropped N" line the drain -/// thread emits on recovery, so drop-on-full loss is observable rather than -/// silent (parity with the napi bridge's `DROPPED`). +/// [`kernel_logging_stats`] (exact cumulative count) and via a synthetic +/// "dropped N" line the drain thread emits on recovery — throttled to at most +/// one per [`NOTICE_MIN_INTERVAL`] so it can't amplify an overloaded callback — +/// so drop-on-full loss is observable rather than silent (parity with the napi +/// bridge's `DROPPED`). static DROPPED: AtomicU64 = AtomicU64::new(0); /// Set if the host callback ever unwound (panicked) across the FFI boundary. @@ -323,19 +333,23 @@ const KERNEL_TARGET_ROOTS: [&str; 2] = [crate::klog::KERNEL_LOG_TARGET, KERNEL_M /// against the targets the bridge actually forwards. A directive applies when: /// /// - its target is a **prefix of a canonical root** (`databricks`, -/// `databricks::sql`, `databricks_sql_kernel`, …) — it matches events at -/// that root; or -/// - its target **extends the module-path root** (`databricks_sql_kernel::session`) -/// — those submodule events are forwarded by `is_kernel_target`, so a host -/// targeting a specific kernel submodule must raise the threshold rather -/// than be silently ignored. +/// `databricks::sql`, `databricks_sql`, `databricks_sql_kernel`, …) — it +/// matches events at that root; or +/// - its target is the module-path root or a `::`-boundary submodule of it +/// (`databricks_sql_kernel::session`) — those submodule events are +/// forwarded by `is_kernel_target`, so a host targeting a specific kernel +/// submodule must raise the threshold rather than be silently ignored. /// -/// It is rejected otherwise: an unrelated `databricks`-prefixed sibling -/// (`databricksfoo`) matches no kernel event, and an extension of the -/// fixed-depth `klog!` target (`databricks::sql::kernel::foo`) matches nothing -/// either, since the kernel never emits deeper than `databricks::sql::kernel`. +/// The submodule check uses the SAME segment-boundary helper as +/// [`is_kernel_target`] ([`is_target_or_submodule`]), so an unrelated +/// module-root SIBLING (`databricks_sql_kernel_ext`) is rejected: it matches no +/// forwarded event, and accepting it as a raw prefix would needlessly raise +/// `MAX_LEVEL` and push kernel events onto the directive lock/scan path. +/// Also rejected: a `databricks`-prefixed sibling that isn't a root prefix +/// (`databricksfoo`), and an extension of the fixed-depth `klog!` target +/// (`databricks::sql::kernel::foo`), which the kernel never emits. fn directive_targets_kernel(target: &str) -> bool { - target.starts_with(KERNEL_MODULE_ROOT) + is_target_or_submodule(target, KERNEL_MODULE_ROOT) || KERNEL_TARGET_ROOTS .iter() .any(|root| root.starts_with(target)) @@ -613,9 +627,12 @@ fn poison_sink_if_current(gen: u64) { /// callback with borrowed C strings. Runs off the kernel's tokio workers so a /// slow callback can't stall query execution. fn drain_loop(rx: Receiver) { - // Drop count already reported to the host, so we only emit a synthetic - // "dropped N" notice for the delta since the last delivered record. + // Drop count already reported to the host, so a synthetic "dropped N" notice + // only carries the delta since the last notice. let mut reported_drops: u64 = 0; + // Timestamp of the last drop-notice, for throttling (see NOTICE_MIN_INTERVAL). + // `None` until the first notice, so the first drop is reported promptly. + let mut last_notice: Option = None; // `recv` errors only once the (process-global) sender is dropped, which // happens on a lost subscriber race (the setter drops the sender so this // thread exits) or process teardown; exit cleanly either way. @@ -640,17 +657,22 @@ fn drain_loop(rx: Receiver) { let Some((cb, ctx, gen)) = sink else { continue; }; - // Surface any records dropped since the last delivery as one synthetic - // WARN line through the callback itself, so a host that only reads the + // Surface records dropped since the last notice as one synthetic WARN + // line through the callback itself, so a host that only reads the // callback stream still learns it missed events (kernel_logging_stats - // carries the cumulative count for a host that polls). + // carries the cumulative count for a host that polls). THROTTLED to at + // most one notice per NOTICE_MIN_INTERVAL: under sustained overflow an + // unthrottled per-record notice would double callback invocations and + // prolong the very backlog it reports. let dropped = DROPPED.load(Ordering::Relaxed); - if dropped > reported_drops { + let notice_due = last_notice.is_none_or(|t| t.elapsed() >= NOTICE_MIN_INTERVAL); + if dropped > reported_drops && notice_due { let notice = format!( "{} kernel log record(s) dropped (slow log callback); increase callback throughput", dropped - reported_drops ); reported_drops = dropped; + last_notice = Some(Instant::now()); if !invoke_callback( cb, ctx, @@ -1257,6 +1279,10 @@ mod tests { assert!(!directive_targets_kernel("databricksfoo")); assert!(!directive_targets_kernel("databricks::sql::kernel::foo")); assert!(!directive_targets_kernel("hyper")); + // A module-root SIBLING (not a `::`-boundary submodule) is rejected — + // it raw-prefixes `databricks_sql_kernel` but matches no forwarded event + // (this is the segment-boundary alignment with is_kernel_target). + assert!(!directive_targets_kernel("databricks_sql_kernel_ext")); } #[test] diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 8a1de83f..0b635a07 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -367,13 +367,20 @@ impl From for KernelStatusCode { } /// Current C-ABI version. Bump this on any change that alters a struct -/// layout ([`KernelStatusCode`], `KernelError`) or the meaning of an -/// existing symbol, so a consumer compiled against one header can detect -/// a library built against a different one. Kept in lockstep with the -/// `DATABRICKS_KERNEL_ABI_VERSION` macro in `include/databricks_kernel.h` -/// (the C-smoke test asserts the two agree). Pure v0.x aid — there is no -/// ABI stability promise until v1.0. -pub const KERNEL_ABI_VERSION: u32 = 1; +/// layout ([`KernelStatusCode`], `KernelError`), changes the meaning of an +/// existing symbol, or ADDS / REMOVES an exported symbol — so a consumer +/// compiled against one header can detect a library built against a +/// different one. The symbol-set case matters as much as the layout one: a +/// consumer built against a header that declares a new symbol +/// (`kernel_set_log_callback`, `kernel_logging_stats`, …) could otherwise +/// link an older library that lacks it and only discover the missing symbol +/// at load/run time. Kept in lockstep with the `DATABRICKS_KERNEL_ABI_VERSION` +/// macro in `include/databricks_kernel.h` (the C smoke test asserts the two +/// agree). Pure v0.x aid — there is no ABI stability promise until v1.0. +/// +/// History: `1` = initial surface; `2` = added the log-callback bridge +/// (`kernel_set_log_callback`, `kernel_logging_stats`, `kernel_log_callback`). +pub const KERNEL_ABI_VERSION: u32 = 2; /// Report the C-ABI version compiled into this library. A consumer that /// linked a header declaring `DATABRICKS_KERNEL_ABI_VERSION` should refuse diff --git a/tests/c/log_callback_smoke.c b/tests/c/log_callback_smoke.c new file mode 100644 index 00000000..e13652f3 --- /dev/null +++ b/tests/c/log_callback_smoke.c @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2026 Databricks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * C ABI smoke test — log-callback SUCCESS path, in its own process. + * + * session_smoke.c installs kernel_init_logging first, so its callback install + * only exercises the mutual-exclusion (Internal) path. There is exactly one + * process-global tracing subscriber, so the success path can't also be reached + * there. This separate binary calls kernel_set_log_callback WITHOUT any prior + * kernel_init_logging, so the callback wins the subscriber: install must return + * Success and kernel_logging_stats must report installed=true. + * + * It links the cdylib through the same C typedef (kernel_log_callback) and the + * two logging symbols the header declares, so it catches header/cdylib drift in + * the callback ABI — a signature or symbol mismatch fails to compile or link. + * (Forcing a real event through the callback needs a kernel-side tracing emit, + * which only the Rust integration test tests/v0_c_abi_log_callback.rs can do; + * this binary proves the install/stats contract from a real C consumer.) + * + * Build / run (via `make c-abi-test`, which compiles every tests/c/*.c): + * cc -I include tests/c/log_callback_smoke.c -L target/debug \ + * -ldatabricks_sql_kernel -o log_callback_smoke && ./log_callback_smoke + */ + +#include +#include + +#include "databricks_kernel.h" + +static int failures = 0; + +#define CHECK(cond, msg) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL: %s (%s:%d)\n", msg, __FILE__, __LINE__); \ + failures++; \ + } else { \ + fprintf(stderr, "ok: %s\n", msg); \ + } \ + } while (0) + +static int g_calls = 0; +static void count_cb(void* ctx, int level, const char* target, const char* message) { + (void)level; + (void)target; + (void)message; + int* counter = (int*)ctx; + if (counter) { + (*counter)++; + } +} + +int main(void) { + /* ABI-version lockstep: the library compiled-in version must equal the + * header this test built against (same gate as session_smoke.c). */ + CHECK(kernel_abi_version() == DATABRICKS_KERNEL_ABI_VERSION, + "kernel_abi_version() matches DATABRICKS_KERNEL_ABI_VERSION"); + + /* A NULL callback is still rejected up front. */ + CHECK(kernel_set_log_callback(NULL, NULL, NULL) == KernelStatusCode_InvalidArgument, + "set_log_callback(NULL cb) → InvalidArgument"); + + /* Fresh process, no kernel_init_logging: the callback wins the one + * process-global subscriber, so this MUST succeed (not the Internal + * mutual-exclusion outcome session_smoke.c sees). */ + KernelStatusCode rc = kernel_set_log_callback(count_cb, &g_calls, "TRACE"); + CHECK(rc == KernelStatusCode_Success, + "set_log_callback installs in a fresh process (no init_logging) → Success"); + + bool installed = false; + uint64_t dropped = 1; + kernel_logging_stats(&installed, &dropped); + CHECK(installed, "logging_stats reports installed=true after a successful install"); + CHECK(dropped == 0, "a healthy fresh install has dropped no records"); + + /* Re-registering is last-writer-wins and still succeeds (NULL level defers to + * the current threshold). */ + rc = kernel_set_log_callback(count_cb, &g_calls, NULL); + CHECK(rc == KernelStatusCode_Success, "re-registering the callback → Success"); + + /* NULL out-params must be tolerated. */ + kernel_logging_stats(NULL, NULL); + CHECK(true, "logging_stats(NULL, NULL) is safe"); + + if (failures == 0) { + fprintf(stderr, "\nAll C ABI log-callback smoke checks passed.\n"); + return 0; + } + fprintf(stderr, "\n%d C ABI log-callback smoke check(s) FAILED.\n", failures); + return 1; +} From f0465b1541276d9907ae14297270b329b65a0eff Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sun, 19 Jul 2026 08:41:33 +0000 Subject: [PATCH 11/15] refactor(c-abi): simplify log-callback level filtering and trim docs Collapse the per-target RUST_LOG EnvFilter machinery to a single resolved level and drop the synthetic drop-notice, keeping the reverse-call bridge's behavior (explicit level > RUST_LOG > warn default; drop count still surfaced via kernel_logging_stats) while removing ~240 lines of accreted complexity: - parse_rust_log now returns one Option (most-verbose kernel-applicable level); should_emit reads a single atomic LEVEL with no per-event lock. A mixed RUST_LOG resolves to a superset threshold; a host wanting exact per-target control uses kernel_init_logging. Removes DIRECTIVES/RwLock, HAS_DIRECTIVES, MAX_LEVEL, threshold_for_target, resolve_threshold, ResolvedFilter. - drain_loop no longer emits a throttled "N dropped" record through the callback; the exact cumulative count stays available via kernel_logging_stats. Also revert the per-PR ABI-version bump (KERNEL_ABI_VERSION and DATABRICKS_KERNEL_ABI_VERSION back to 1) with a coarse pre-1.0 handshake policy, keeping the C-smoke lockstep assertion; and trim verbose doc/comment blocks across logging.rs and the header. Sink generations and the retryable install are kept. make check green. Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- include/databricks_kernel.h | 77 ++-- src/c_abi/logging.rs | 851 ++++++++++-------------------------- src/c_abi/mod.rs | 27 +- 3 files changed, 263 insertions(+), 692 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e55a330a..8613bfd8 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -54,10 +54,11 @@ * compare the two once at load time and refuse to run on a mismatch — * otherwise a layout change (e.g. a reordered `KernelStatusCode`) would be * misread as valid data rather than surfaced as a clean error. The macro is - * bumped in lockstep with the Rust `KERNEL_ABI_VERSION` on any layout or - * semantic change AND on any change to the exported symbol set (a - * consumer built against a header declaring a newer symbol would otherwise - * link an older library missing it and fail only at load/run time). + * bumped in lockstep with the Rust `KERNEL_ABI_VERSION`. It is a COARSE + * pre-1.0 handshake, not bumped per PR: while the surface is still being + * built out, additive symbols land without a bump, and it moves only at a + * deliberate checkpoint (a layout / semantic change, or a stabilisation + * milestone). * * ## Lifecycle & threading notes * @@ -110,7 +111,7 @@ extern "C" { * load time and refuse to run on a mismatch (see "ABI versioning" above). * Bumped in lockstep with the Rust `KERNEL_ABI_VERSION`. */ -#define DATABRICKS_KERNEL_ABI_VERSION 2 +#define DATABRICKS_KERNEL_ABI_VERSION 1 /* Version of the C ABI compiled into the linked library. Infallible and * side-effect-free. */ @@ -318,56 +319,42 @@ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); * reaching stderr via kernel_init_logging. * * The callback fires from the kernel's log-drain thread (NOT a query worker), - * so it MUST be thread-safe. It SHOULD NOT unwind: the kernel guards each call - * with catch_unwind (the callback pointer uses Rust's C-unwind ABI), so a - * panicking callback poisons the sink and stops delivering rather than aborting - * the process — but subsequent logs are then silently dropped, so a well-behaved - * callback must still not throw across the boundary. It MUST NOT call back into - * any kernel_* entry point: a reentrant blocking kernel_* call from this thread - * is NOT rejected (that guard only covers calls from a kernel worker) — it would - * stall the drain thread and drop queued logs. `ctx` - * is passed back verbatim on every call and must stay valid for the process - * lifetime. `level` (the callback arg) is 1=ERROR..5=TRACE; `target` and - * `message` are valid only for the duration of the call — copy them out. - * Records are enqueued on a bounded channel and DROPPED on overflow (logs are - * advisory and never back-pressure a kernel hot path); the drop count is - * observable via kernel_logging_stats (exact cumulative count) and a synthetic - * "N dropped" line the drain thread emits through the callback on recovery - * (throttled to at most once per second so it can't amplify a slow callback). + * so it MUST be thread-safe. It SHOULD NOT unwind: the kernel contains a panic + * with catch_unwind (the pointer uses Rust's C-unwind ABI) and poisons the sink + * rather than aborting, but subsequent logs are then dropped. It MUST NOT call + * back into any kernel_* entry point — a blocking reentrant call would stall the + * drain thread (that reentrancy guard only covers query workers). `ctx` is + * passed back verbatim and must stay valid for the process lifetime; `level` is + * 1=ERROR..5=TRACE; `target` and `message` are valid only for the call — copy + * them out. Records are enqueued on a bounded channel and DROPPED on overflow + * (logs never back-pressure a kernel hot path); the drop count is observable via + * kernel_logging_stats. * * The `level` PARAMETER (OFF/ERROR/WARN/INFO/DEBUG/TRACE, case-insensitive, or * NULL) sets the forward threshold with the SAME precedence as - * kernel_init_logging: an explicit recognised level wins, else RUST_LOG. A host - * that maps its own logger level (Go's DATABRICKS_LOG_LEVEL) passes it here so - * the callback filters on that one knob rather than only RUST_LOG. When neither - * resolves (NULL/unrecognised AND no matching RUST_LOG) the current threshold - * is left UNCHANGED — the warn default on the first call, or the - * previously-set level on a re-registration. - * - * Mutually exclusive with kernel_init_logging: both install the one - * process-global tracing subscriber. kernel_set_log_callback returns Internal - * (with a stored last error) if a global subscriber was already installed, or - * if it won the subscriber but the log-drain thread could not be started (the - * two cases carry distinct error messages); install exactly ONE of the two. - * Passing a NULL `cb` returns InvalidArgument (there is no detach in v0). */ + * kernel_init_logging: an explicit recognised level wins, else RUST_LOG (so a + * host maps its own logger level, e.g. Go's DATABRICKS_LOG_LEVEL). When neither + * resolves, the current threshold is left UNCHANGED — the warn default on the + * first call, or the previously-set level on a re-registration. + * + * Mutually exclusive with kernel_init_logging (both install the one + * process-global subscriber): returns Internal, with distinct error messages, + * if a subscriber was already installed or the drain thread could not start — + * install exactly ONE. A NULL `cb` returns InvalidArgument (no detach in v0). */ typedef void (*kernel_log_callback)(void* ctx, int level, const char* target, const char* message); KernelStatusCode kernel_set_log_callback(kernel_log_callback cb, void* ctx, const char* level); /* Report the log-callback bridge's health, so a host can distinguish "kernel - * logs are quiet" from "kernel logs are being dropped / the sink died / never - * installed". Writes to each non-NULL out-param (a NULL out-param is skipped): + * logs are quiet" from "being dropped / sink died / never installed". Writes + * each non-NULL out-param (a NULL one is skipped): * - `installed`: true iff kernel logs are CURRENTLY delivering — the callback - * won the process-global subscriber AND the sink is not poisoned. A callback - * that unwinds poisons the sink (delivery stops), which reads false here even - * though the subscriber is still installed; registering a new callback clears - * the poison and flips this back to true. - * - `dropped`: cumulative kernel log records dropped AFTER install — because - * the bounded delivery channel was full (slow callback) or the sink was - * poisoned by a callback that unwound. Does NOT count the drain-thread-never- - * started case (a spawn failure leaves no channel to overflow); there - * `installed` reads false and kernel_set_log_callback returned Internal. + * won the subscriber AND the sink is not poisoned. A callback that unwinds + * poisons the sink (reads false); registering a new callback clears it. + * - `dropped`: cumulative records dropped AFTER install (channel full or sink + * poisoned). Excludes the spawn-failure case (no channel), where `installed` + * reads false and kernel_set_log_callback returned Internal. * Never fails; safe to poll at any time. */ void kernel_logging_stats(bool* installed, uint64_t* dropped); diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs index 594ee510..6da1eb13 100644 --- a/src/c_abi/logging.rs +++ b/src/c_abi/logging.rs @@ -28,36 +28,29 @@ //! //! - [`kernel_set_log_callback`] installs a process-global [`KernelLogLayer`] //! (once) and records the `(callback, ctx)` sink. The layer captures -//! `databricks*` events, filters by a per-target threshold (an explicit -//! one-knob level, else `RUST_LOG`'s per-target `EnvFilter` precedence), -//! formats each into a [`Record`], and pushes it onto a **bounded** channel +//! `databricks*` events, filters by a single level (an explicit one-knob +//! level, else the most-verbose kernel-applicable `RUST_LOG` level), formats +//! each into a [`Record`], and pushes it onto a **bounded** channel //! (drop-on-full — logs are advisory and must never block or back-pressure a //! kernel hot path). //! - A dedicated drain thread pulls records and invokes the C callback once per //! record with borrowed C strings (valid only for the call). //! -//! ## Threading & safety contract (documented in `databricks_kernel.h`) +//! ## Threading & safety contract (full version in `databricks_kernel.h`) //! //! The callback fires from the drain thread (never a kernel tokio worker), so -//! the host callback must be thread-safe. It must NOT call back into any -//! `kernel_*` entry point: unlike a call from a tokio worker (which -//! `block_on_ffi` rejects), the drain thread is a plain `std::thread`, so a -//! reentrant blocking `kernel_*` call is NOT caught — it would run its own -//! `block_on`, stalling the drain thread and dropping queued logs. A callback -//! that unwinds is contained: the type is `extern "C-unwind"` and the drain -//! thread wraps every invocation in `catch_unwind`, so a panicking host callback -//! poisons the sink (delivery stops) rather than aborting the process — but a -//! well-behaved callback still must not unwind, since poisoning silently drops -//! all subsequent logs. +//! it must be thread-safe and must not call back into any `kernel_*` entry +//! point (the reentrancy guard only covers tokio workers, so a blocking +//! `kernel_*` call here would stall the drain thread). An unwinding callback is +//! contained by `catch_unwind` and poisons the sink rather than aborting the +//! process, but a well-behaved callback still must not unwind, since poisoning +//! stops delivery. //! //! ## Mutual exclusion with `kernel_init_logging` //! -//! Both this and `kernel_init_logging` install the one process-global `tracing` -//! subscriber; only the first `set_global_default` wins. If a global subscriber -//! was already installed, `kernel_set_log_callback` returns `Internal` (with a -//! stored last error), exactly as `kernel_init_logging` does for the reverse — -//! a C consumer picks ONE of the two. Last-writer-wins for the sink itself -//! (the callback slot is refreshed on every call). +//! Both install the one process-global `tracing` subscriber; the first +//! `set_global_default` wins and the loser returns `Internal`, so a C consumer +//! picks one. The sink itself is last-writer-wins, refreshed on every call. // The callback type mirrors the C typedef name `kernel_log_callback` (snake // case) so the Rust and header names read identically, matching the rest of the @@ -71,8 +64,7 @@ use std::os::raw::{c_char, c_int}; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; -use std::sync::{Mutex, OnceLock, RwLock}; -use std::time::{Duration, Instant}; +use std::sync::{Mutex, OnceLock}; use tracing::field::{Field, Visit}; use tracing::level_filters::LevelFilter; use tracing::subscriber::Interest; @@ -85,13 +77,10 @@ use tracing_subscriber::registry::LookupSpan; /// numeric severity); `target` and `message` are NUL-terminated C strings valid /// only for the duration of the call. /// -/// The ABI is `C-unwind`, not plain `C`: a plain `extern "C"` fn that panics -/// aborts at its OWN boundary (Rust ≥ 1.81), so an outer `catch_unwind` around -/// the call could never contain it. `C-unwind` lets a panic propagate across the -/// boundary so `invoke_callback`'s `catch_unwind` can catch a misbehaving host -/// callback and poison the sink instead of aborting the process. The C -/// representation is identical (`void (*)(void*, int, const char*, const char*)`), -/// and non-unwinding C / Go-with-recover callbacks are unaffected. +/// The ABI is `C-unwind` so a panicking host callback propagates across the +/// boundary and `invoke_callback`'s `catch_unwind` can contain it; a plain +/// `extern "C"` fn would instead abort the process. The C representation is +/// unchanged, and non-unwinding callbacks are unaffected. pub type kernel_log_callback = extern "C-unwind" fn( ctx: *mut c_void, level: c_int, @@ -115,22 +104,14 @@ struct Record { struct Sink { cb: kernel_log_callback, ctx: usize, - /// Monotonic registration id. The drain thread captures this alongside - /// `(cb, ctx)` and only poisons the sink on a callback unwind if this id is - /// still the installed one — so a slow/old callback that unwinds AFTER the - /// host re-registered a new one cannot kill the replacement. + /// Monotonic registration id. The drain thread poisons the sink on an unwind + /// only if this id is still installed, so an old callback that unwinds after + /// a re-registration can't kill the replacement. gen: u64, } const CHANNEL_CAPACITY: usize = 4096; -/// Minimum spacing between synthetic "dropped N" notices the drain thread emits -/// through the callback. Bounds notice frequency under sustained overflow so an -/// already-slow callback isn't handed ~2× the invocations (a notice before every -/// real record); the exact cumulative count remains available via -/// [`kernel_logging_stats`]. -const NOTICE_MIN_INTERVAL: Duration = Duration::from_secs(1); - const LEVEL_OFF: u8 = 0; const LEVEL_ERROR: u8 = 1; const LEVEL_WARN: u8 = 2; @@ -138,51 +119,21 @@ const LEVEL_INFO: u8 = 3; const LEVEL_DEBUG: u8 = 4; const LEVEL_TRACE: u8 = 5; -/// Default forward threshold for kernel targets not matched by a more specific -/// [`DIRECTIVES`] entry: the explicit one-knob level, `RUST_LOG`'s bare global -/// level, or the static `warn` default. Numeric severity, low = more severe; -/// `0` means "off / emit nothing". +/// Forward threshold for all kernel events: the explicit one-knob level, the +/// most-verbose kernel-applicable `RUST_LOG` level, or the static `warn` +/// default. Numeric severity, low = more severe; `0` means "off / emit nothing". static LEVEL: AtomicU8 = AtomicU8::new(LEVEL_WARN); -/// Most verbose threshold across [`LEVEL`] and every [`DIRECTIVES`] entry, for -/// `max_level_hint` so the process-global gate admits everything any directive -/// could enable (the per-event [`KernelFilter::enabled`] then applies the -/// precise per-target threshold). Tracking only [`LEVEL`] here would wrongly -/// gate out a more-verbose submodule directive before it reached `enabled`. -static MAX_LEVEL: AtomicU8 = AtomicU8::new(LEVEL_WARN); - -/// Fast-path flag: whether [`DIRECTIVES`] holds any per-target directive. The -/// common one-knob / bare-level case has none, so the hot path -/// ([`threshold_for_target`]) reads [`LEVEL`] directly and never takes the -/// [`DIRECTIVES`] lock. -static HAS_DIRECTIVES: AtomicBool = AtomicBool::new(false); - -/// Per-target `RUST_LOG` thresholds `(target, level)`, applied with `EnvFilter` -/// precedence: a directive matches an event when its target is a **prefix** of -/// the event target (`event_target.starts_with(target)`), and the most specific -/// (longest) match wins. Collapsing these into one scalar would let a verbose -/// submodule directive (`databricks_sql_kernel::reader=trace`) widen the -/// canonical `klog!` target (`databricks::sql::kernel`) that `EnvFilter` would -/// keep at its own directive's level. Consulted only when [`HAS_DIRECTIVES`]. -static DIRECTIVES: OnceLock>> = OnceLock::new(); - -/// Count of log records dropped because the bounded channel was full (a slow -/// host callback) or the drain thread stopped. Surfaced via -/// [`kernel_logging_stats`] (exact cumulative count) and via a synthetic -/// "dropped N" line the drain thread emits on recovery — throttled to at most -/// one per [`NOTICE_MIN_INTERVAL`] so it can't amplify an overloaded callback — -/// so drop-on-full loss is observable rather than silent (parity with the napi -/// bridge's `DROPPED`). +/// Count of log records dropped because the bounded channel was full or the +/// sink was poisoned. Surfaced via [`kernel_logging_stats`] so the loss is +/// observable, not silent. static DROPPED: AtomicU64 = AtomicU64::new(0); -/// Set if the host callback ever unwound (panicked) across the FFI boundary. -/// The `extern "C-unwind"` type lets the panic propagate so the drain thread's -/// `catch_unwind` catches it (a plain `extern "C"` would instead abort the -/// process at the callback's own boundary); we record it here and stop -/// delivering — a callback that panics once is assumed to keep panicking, so we -/// protect the process rather than re-invoke it. Surfaced via -/// [`kernel_logging_stats`] (`installed` reads `false` while poisoned). Cleared -/// when a NEW callback is registered, so a host can recover by re-installing. +/// Set if the host callback ever unwound across the FFI boundary. A callback +/// that panics once is assumed to keep panicking, so the drain thread stops +/// delivering rather than re-invoke it. Surfaced via [`kernel_logging_stats`] +/// (`installed` reads `false` while poisoned), and cleared when a new callback +/// is registered so a host can recover by re-installing. static SINK_POISONED: AtomicBool = AtomicBool::new(false); const INSTALL_PENDING: u8 = 0; @@ -190,11 +141,9 @@ const INSTALL_OK: u8 = 1; /// Lost the one-global-subscriber race (e.g. `kernel_init_logging` won) — a /// benign outcome; the host picks one of the two logging routes. const INSTALL_ALREADY_SET: u8 = 2; -/// The OS refused to start the drain thread (EAGAIN/ENOMEM) before the global -/// subscriber was claimed — a real failure the host should surface distinctly. -/// NON-terminal: a later `kernel_set_log_callback` retries the install (the -/// subscriber slot was never touched), so a transient spawn failure doesn't -/// permanently disable callback logging. +/// The OS refused to start the drain thread (EAGAIN/ENOMEM) before the +/// subscriber was claimed. Non-terminal: a later `kernel_set_log_callback` +/// retries, so a transient spawn failure isn't permanent. const INSTALL_SPAWN_FAILED: u8 = 3; /// Outcome of the subscriber install. `INSTALL_OK` and `INSTALL_ALREADY_SET` are @@ -216,15 +165,9 @@ static SINK: OnceLock>> = OnceLock::new(); /// the callback it just invoked is still the installed one. static NEXT_SINK_GEN: AtomicU64 = AtomicU64::new(0); -/// Serializes install attempts (subscriber + channel + drain-thread spawn). -/// -/// Deliberately NOT a `Once`: a `Once` is consumed by the first attempt, so a -/// transient drain-thread spawn failure (EAGAIN/ENOMEM) would permanently -/// disable callback logging for the process — no later `kernel_set_log_callback` -/// could retry. A plain lock + retryable [`INSTALL_STATUS`] lets a spawn failure -/// stay non-terminal so a subsequent call tries again, while `set_global_default` -/// is still attempted at most once (only after a drain thread is confirmed up, -/// which transitions to a terminal state). +/// Serializes install attempts (subscriber + channel + drain-thread spawn). A +/// plain lock rather than a `Once` so a transient spawn failure stays retryable +/// via [`INSTALL_STATUS`]; `set_global_default` is still attempted at most once. static INSTALL_LOCK: Mutex<()> = Mutex::new(()); fn severity(level: &Level) -> u8 { @@ -250,72 +193,43 @@ fn parse_level_word(s: &str) -> Option { } } -/// Parse a `RUST_LOG`-style directive string into the kernel-applicable -/// per-target directives plus an optional bare global level, so the callback -/// can filter per target exactly as the stderr path (`kernel_init_logging`)'s -/// `EnvFilter` would — rather than collapsing everything into one scalar. -/// -/// Returns `(directives, global)`: -/// -/// - `directives`: each retained `(target, level)` keeps its target string so -/// the hot path can apply `EnvFilter`'s prefix rule per event — a directive -/// matches an event only when its target is a **prefix of the event target** -/// (`event_target.starts_with(target)`), and among matches the most specific -/// (longest) wins ([`resolve_threshold`]). Keeping them separate is what -/// stops a verbose submodule directive -/// (`databricks_sql_kernel::reader::inline=trace`) from widening the -/// canonical `klog!` target (`databricks::sql::kernel`), which `EnvFilter` -/// would keep at its own `databricks::sql::kernel=error` directive. -/// - `global`: a bare level (`debug`), the least-specific match `EnvFilter` -/// recognises, used as the default for kernel targets no directive matches. +/// Resolve a `RUST_LOG`-style string to the single most-verbose level that +/// applies to kernel events, or `None` if nothing kernel-applicable is present. /// -/// A directive with no `=` is a bare LEVEL (`debug` → global) or a bare TARGET; -/// `EnvFilter` reads a bare kernel target (`databricks::sql::kernel`) as that -/// target at TRACE, so it is retained as `(target, TRACE)` rather than ignored. -/// -/// Applicability is judged by [`directive_targets_kernel`], NOT a bare -/// `starts_with("databricks")`: a non-matching sibling such as `databricksfoo=warn` -/// or an extension of the fixed-depth `klog!` target -/// (`databricks::sql::kernel::foo=trace`) is a prefix of no kernel event, so -/// `EnvFilter` skips it — and so does this. A submodule directive on the -/// module-path namespace the bridge forwards -/// (`databricks_sql_kernel::session=debug`) IS retained (those events are -/// forwarded by `is_kernel_target`). Foreign directives (`hyper=warn`) are -/// dropped, since the bridge never forwards their events. -fn parse_rust_log(rust_log: &str) -> (Vec<(String, u8)>, Option) { - let mut directives: Vec<(String, u8)> = Vec::new(); - let mut global: Option = None; +/// The callback carries one level, so directives are collapsed by taking the +/// max (most verbose) across the bare global level and every kernel-applicable +/// target directive ([`directive_targets_kernel`]). A directive with no `=` is +/// a bare level (the global) or a bare kernel target (TRACE, as `EnvFilter` +/// reads it). Foreign directives (`hyper=warn`) and non-matching `databricks` +/// siblings are ignored. This can forward a superset of what the stderr path's +/// per-target `EnvFilter` would — acceptable for advisory logging, and a host +/// wanting exact per-target control uses `kernel_init_logging` instead. +fn parse_rust_log(rust_log: &str) -> Option { + let mut level: Option = None; + let mut bump = |l: u8| level = Some(level.map_or(l, |cur| cur.max(l))); for directive in rust_log.split(',') { let d = directive.trim(); if d.is_empty() { continue; } match d.split_once('=') { - Some((target, level)) => { - let target = target.trim(); - if directive_targets_kernel(target) { - if let Some(l) = parse_level_word(level) { - directives.push((target.to_owned(), l)); + Some((target, lvl)) => { + if directive_targets_kernel(target.trim()) { + if let Some(l) = parse_level_word(lvl) { + bump(l); } } } None => { - // A directive with no `=` is either a bare level (`debug`) or a - // target with no level. `EnvFilter` reads a bare level as the - // global and a bare TARGET as "that target at TRACE" (the max), - // so a kernel target-only directive (`databricks::sql::kernel`) - // must raise the threshold to TRACE — not be ignored, which - // would leave the callback at WARN where kernel_init_logging - // emits debug/trace. if let Some(l) = parse_level_word(d) { - global = Some(l); + bump(l); } else if directive_targets_kernel(d) { - directives.push((d.to_owned(), LEVEL_TRACE)); + bump(LEVEL_TRACE); } } } } - (directives, global) + level } /// The crate's module-path root: the `#[instrument]` / default-target namespace @@ -328,26 +242,14 @@ const KERNEL_MODULE_ROOT: &str = "databricks_sql_kernel"; /// ([`KERNEL_MODULE_ROOT`]). const KERNEL_TARGET_ROOTS: [&str; 2] = [crate::klog::KERNEL_LOG_TARGET, KERNEL_MODULE_ROOT]; -/// Whether a `RUST_LOG` directive target selects kernel events under -/// `EnvFilter`'s `event_target.starts_with(directive_target)` prefix match, -/// against the targets the bridge actually forwards. A directive applies when: -/// -/// - its target is a **prefix of a canonical root** (`databricks`, -/// `databricks::sql`, `databricks_sql`, `databricks_sql_kernel`, …) — it -/// matches events at that root; or -/// - its target is the module-path root or a `::`-boundary submodule of it -/// (`databricks_sql_kernel::session`) — those submodule events are -/// forwarded by `is_kernel_target`, so a host targeting a specific kernel -/// submodule must raise the threshold rather than be silently ignored. -/// -/// The submodule check uses the SAME segment-boundary helper as -/// [`is_kernel_target`] ([`is_target_or_submodule`]), so an unrelated -/// module-root SIBLING (`databricks_sql_kernel_ext`) is rejected: it matches no -/// forwarded event, and accepting it as a raw prefix would needlessly raise -/// `MAX_LEVEL` and push kernel events onto the directive lock/scan path. -/// Also rejected: a `databricks`-prefixed sibling that isn't a root prefix -/// (`databricksfoo`), and an extension of the fixed-depth `klog!` target -/// (`databricks::sql::kernel::foo`), which the kernel never emits. +/// Whether a `RUST_LOG` directive target selects any event the bridge forwards, +/// under `EnvFilter`'s prefix match. True when the target is a prefix of a +/// canonical root (`databricks`, `databricks::sql`, `databricks_sql_kernel`, …) +/// or a `::`-boundary submodule of the module-path root +/// (`databricks_sql_kernel::session`). Uses the same segment-boundary helper as +/// [`is_kernel_target`], so a module-root sibling (`databricks_sql_kernel_ext`), +/// a non-root sibling (`databricksfoo`), and an over-specific extension of the +/// fixed-depth `klog!` target (`databricks::sql::kernel::foo`) are all rejected. fn directive_targets_kernel(target: &str) -> bool { is_target_or_submodule(target, KERNEL_MODULE_ROOT) || KERNEL_TARGET_ROOTS @@ -355,76 +257,36 @@ fn directive_targets_kernel(target: &str) -> bool { .any(|root| root.starts_with(target)) } -/// Resolve the forward threshold for `target` under `EnvFilter` precedence: the -/// most specific (longest) directive whose target is a **prefix** of `target` -/// wins; on a specificity tie the later entry wins (matching `EnvFilter`'s -/// last-writer dedup); with no matching directive the `default` applies. Pure -/// (no globals) so the precedence logic is unit-testable without touching the -/// process-global filter state. -fn resolve_threshold(target: &str, default: u8, directives: &[(String, u8)]) -> u8 { - let mut best: Option<(usize, u8)> = None; - for (t, lvl) in directives { - if target.starts_with(t.as_str()) { - let specificity = t.len(); - let wins = best.is_none_or(|(len, _)| specificity >= len); - if wins { - best = Some((specificity, *lvl)); - } - } - } - best.map_or(default, |(_, l)| l) -} - -/// The current forward threshold for `target`, reading the process-global filter -/// state. Fast path: with no per-target directives (the one-knob / bare-level -/// case) this is a single relaxed load of [`LEVEL`] and never locks. -fn threshold_for_target(target: &str) -> u8 { - let default = LEVEL.load(Ordering::Relaxed); - if !HAS_DIRECTIVES.load(Ordering::Relaxed) { - return default; - } - match DIRECTIVES.get().and_then(|lock| lock.read().ok()) { - Some(dirs) => resolve_threshold(target, default, &dirs), - None => default, - } -} - -/// Returns whether an event at `level` on `target` should currently be -/// forwarded, applying the per-target threshold ([`threshold_for_target`]). -fn should_emit(target: &str, level: &Level) -> bool { - let threshold = threshold_for_target(target); +/// Returns whether an event at `level` should currently be forwarded, against +/// the single configured [`LEVEL`] threshold. +fn should_emit(level: &Level) -> bool { + let threshold = LEVEL.load(Ordering::Relaxed); threshold != LEVEL_OFF && severity(level) <= threshold } -/// Whether `target` is exactly `root` or a `::`-delimited submodule of it -/// (`root::…`) — a SEGMENT-boundary match, not a raw prefix. This is what keeps -/// an unrelated sibling like `databricksfoo` or `databricks_sql_kernel_ext` from -/// matching `databricks_sql_kernel`: the byte after the root must be a `::` -/// separator (or end of string), never a bare identifier continuation. +/// Whether `target` is exactly `root` or a `::`-delimited submodule of it — a +/// segment-boundary match, so a sibling like `databricks_sql_kernel_ext` does +/// not match `databricks_sql_kernel`. fn is_target_or_submodule(target: &str, root: &str) -> bool { target .strip_prefix(root) .is_some_and(|rest| rest.is_empty() || rest.starts_with("::")) } -/// Targets the bridge forwards: the `klog!` shim's `databricks::sql::kernel` (and -/// any submodule of it) and the crate's module paths (`databricks_sql_kernel` -/// and `databricks_sql_kernel::…`). A SEGMENT-boundary match, NOT a raw -/// `starts_with("databricks")` — the latter would route unrelated -/// `databricks`-prefixed host/library targets (`databricksfoo`, another -/// `databricks_*` crate) into the kernel callback. +/// Targets the bridge forwards: the `klog!` shim's `databricks::sql::kernel` +/// and the crate's module paths (`databricks_sql_kernel`), plus any submodule +/// of either. A segment-boundary match, so an unrelated `databricks`-prefixed +/// target from another crate is not routed into the kernel callback. fn is_kernel_target(target: &str) -> bool { is_target_or_submodule(target, crate::klog::KERNEL_LOG_TARGET) || is_target_or_submodule(target, KERNEL_MODULE_ROOT) } -/// The most-verbose configured level as a `tracing` [`LevelFilter`], for -/// `max_level_hint` so the process-global gate tracks the kernel level instead -/// of pinning at TRACE. Reads [`MAX_LEVEL`] (the max across the default and all -/// per-target directives) so a verbose submodule directive isn't gated out -/// before the per-event [`KernelFilter::enabled`] can apply it. +/// The configured [`LEVEL`] as a `tracing` [`LevelFilter`], for `max_level_hint` +/// so the process-global gate tracks the kernel level rather than pinning at +/// TRACE. fn current_level_filter() -> LevelFilter { - match MAX_LEVEL.load(Ordering::Relaxed) { + match LEVEL.load(Ordering::Relaxed) { LEVEL_OFF => LevelFilter::OFF, LEVEL_ERROR => LevelFilter::ERROR, LEVEL_WARN => LevelFilter::WARN, @@ -435,17 +297,10 @@ fn current_level_filter() -> LevelFilter { } /// Per-callsite interest. Kernel EVENT callsites re-evaluate per event -/// (`sometimes`, for the dynamic level). Everything else caches off forever -/// (`never`): -/// -/// - foreign targets (`hyper`/`rustls`/…) never dispatch, and -/// - SPAN callsites never dispatch — even on kernel targets. This bridge is -/// event-only ([`KernelLogLayer`] implements just `on_event` and never -/// reads span data), so admitting spans would make the kernel's own -/// `databricks*` spans (`Session`'s `info_span!`, the `#[instrument]` on -/// the `next_batch()` hot path) pay span create/enter/exit in the registry -/// at INFO/DEBUG/TRACE thresholds for output that never comes. Caching them -/// off turns those into no-op disabled spans. +/// (`sometimes`, for the dynamic level); everything else caches off (`never`). +/// The bridge is event-only, so span callsites cache off even on kernel targets +/// — the kernel's own `databricks*` spans then pay no span machinery for output +/// this layer never produces. fn callsite_interest_for(target: &str, is_event: bool) -> Interest { if is_event && is_kernel_target(target) { Interest::sometimes() @@ -505,13 +360,10 @@ impl Visit for MessageVisitor { /// (drop-on-full). The per-layer [`KernelFilter`] already excludes foreign /// targets and below-level events. /// -/// The producer end of the delivery channel lives HERE, in the layer instance, -/// rather than in a separately-published global. `set_global_default` makes the -/// subscriber (and this layer) visible atomically, so from the instant an event -/// can reach [`on_event`](KernelLogLayer::on_event) the sender is already -/// present — there is no window where the subscriber is installed but the sender -/// isn't yet published (which would silently drop a concurrent kernel log -/// without counting it). +/// The channel sender lives in the layer instance, so `set_global_default` +/// publishes the subscriber and its sender atomically — +/// [`on_event`](KernelLogLayer::on_event) never sees an installed-but-senderless +/// state that would drop a concurrent log uncounted. struct KernelLogLayer { tx: SyncSender, } @@ -526,12 +378,8 @@ impl Filter for KernelFilter { } fn enabled(&self, meta: &Metadata<'_>, _ctx: &Context<'_, S>) -> bool { - // Event-only: never enable spans (the layer has no span consumer). The - // per-target threshold applies `RUST_LOG`'s `EnvFilter` precedence so a - // verbose submodule directive can't widen the canonical `klog!` target. - meta.is_event() - && is_kernel_target(meta.target()) - && should_emit(meta.target(), meta.level()) + // Event-only: never enable spans (the layer has no span consumer). + meta.is_event() && is_kernel_target(meta.target()) && should_emit(meta.level()) } fn max_level_hint(&self) -> Option { @@ -544,14 +392,10 @@ where S: Subscriber + for<'a> LookupSpan<'a>, { fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { - // Once a callback has unwound the sink is poisoned and the drain thread - // drops everything until re-registration. Short-circuit HERE — before the - // field visit, the message allocation, and the enqueue — so a poisoned - // sink stops paying producer-side formatting for records it will only - // drop. Still count the loss so kernel_logging_stats stays accurate - // (parity with the drain thread's own poison drop-count; each record is - // counted exactly once — here if produced while poisoned, or by the drain - // thread if it was already queued when the poison landed). + // A poisoned sink drops everything until re-registration; short-circuit + // before the field visit and enqueue so we don't format a record we'll + // drop. Still count the loss (each record is counted exactly once — here + // if produced while poisoned, or by the drain thread if already queued). if SINK_POISONED.load(Ordering::Relaxed) { DROPPED.fetch_add(1, Ordering::Relaxed); return; @@ -565,20 +409,17 @@ where message: visitor.finish(), }; // Drop-on-full / disconnected: logs are advisory, never block a kernel - // task on a slow host callback. Count the loss so it's observable (via - // kernel_logging_stats and the drain thread's synthetic recovery line) - // rather than vanishing silently. + // task on a slow host callback. Count the loss so it's observable via + // kernel_logging_stats rather than vanishing silently. if self.tx.try_send(record).is_err() { DROPPED.fetch_add(1, Ordering::Relaxed); } } } -/// Invoke the host callback once, guarded against an unwind. A panic crossing -/// `extern "C"` aborts the process (Rust ≥ 1.81), so a host callback that -/// unwinds must be contained here — this is the same `catch_unwind` guard every -/// other FFI boundary in the crate uses (`block_on_ffi`, `catch_ffi`). Returns -/// `false` if the callback unwound, so the caller can poison the sink. +/// Invoke the host callback once, containing any unwind with `catch_unwind` +/// (the same guard every FFI boundary in the crate uses). Returns `false` if +/// the callback unwound, so the caller can poison the sink. fn invoke_callback( cb: kernel_log_callback, ctx: usize, @@ -586,12 +427,9 @@ fn invoke_callback( target: &str, message: &str, ) -> bool { - // Interior NULs can't appear in a C string; on the rare event whose text - // contains one, TRUNCATE at the first NUL rather than replacing the whole - // string with a placeholder — the informative prefix (up to the NUL) is - // preserved. CString::new only fails on an interior NUL, so on error rebuild - // from the bytes up to it (which cannot themselves contain a NUL → unwrap is - // infallible). + // On the rare message with an interior NUL, truncate at the first NUL + // (keeping the prefix) instead of dropping the whole string. The bytes + // before the NUL can't contain one, so the rebuild is infallible. let to_cstring = |s: &str| { CString::new(s).unwrap_or_else(|e| { let n = e.nul_position(); @@ -606,13 +444,11 @@ fn invoke_callback( .is_ok() } -/// Poison the sink — stop delivery — but ONLY if generation `gen` is still the -/// installed registration. The drain thread copies `(cb, ctx, gen)` out and -/// runs the callback without the lock, so the host may re-register (bumping the -/// generation and clearing the poison) while an OLD callback is mid-unwind. -/// Comparing under the `SINK` lock (which the setter also holds while it swaps -/// the sink + clears the poison) means an old callback's failure can never kill -/// the newer registration. +/// Poison the sink — stop delivery — but only if generation `gen` is still the +/// installed registration. The drain thread runs the callback unlocked, so the +/// host may re-register (bumping the generation, clearing the poison) while an +/// old callback is mid-unwind; comparing under the `SINK` lock keeps that old +/// failure from killing the newer registration. fn poison_sink_if_current(gen: u64) { if let Some(lock) = SINK.get() { if let Ok(guard) = lock.lock() { @@ -627,12 +463,6 @@ fn poison_sink_if_current(gen: u64) { /// callback with borrowed C strings. Runs off the kernel's tokio workers so a /// slow callback can't stall query execution. fn drain_loop(rx: Receiver) { - // Drop count already reported to the host, so a synthetic "dropped N" notice - // only carries the delta since the last notice. - let mut reported_drops: u64 = 0; - // Timestamp of the last drop-notice, for throttling (see NOTICE_MIN_INTERVAL). - // `None` until the first notice, so the first drop is reported promptly. - let mut last_notice: Option = None; // `recv` errors only once the (process-global) sender is dropped, which // happens on a lost subscriber race (the setter drops the sender so this // thread exits) or process teardown; exit cleanly either way. @@ -647,9 +477,9 @@ fn drain_loop(rx: Receiver) { let Some(sink_lock) = SINK.get() else { continue; }; - // Copy the sink out under the lock (cheap: a fn pointer + usize + gen) - // so the callback runs without holding the mutex — a reentrant setter - // can't deadlock, and a slow callback can't block a level/sink update. + // Copy the sink out under the lock so the callback runs without holding + // the mutex — a reentrant setter can't deadlock and a slow callback + // can't block a level/sink update. let sink = match sink_lock.lock() { Ok(g) => g.as_ref().map(|s| (s.cb, s.ctx, s.gen)), Err(_) => None, @@ -657,174 +487,48 @@ fn drain_loop(rx: Receiver) { let Some((cb, ctx, gen)) = sink else { continue; }; - // Surface records dropped since the last notice as one synthetic WARN - // line through the callback itself, so a host that only reads the - // callback stream still learns it missed events (kernel_logging_stats - // carries the cumulative count for a host that polls). THROTTLED to at - // most one notice per NOTICE_MIN_INTERVAL: under sustained overflow an - // unthrottled per-record notice would double callback invocations and - // prolong the very backlog it reports. - let dropped = DROPPED.load(Ordering::Relaxed); - let notice_due = last_notice.is_none_or(|t| t.elapsed() >= NOTICE_MIN_INTERVAL); - if dropped > reported_drops && notice_due { - let notice = format!( - "{} kernel log record(s) dropped (slow log callback); increase callback throughput", - dropped - reported_drops - ); - reported_drops = dropped; - last_notice = Some(Instant::now()); - if !invoke_callback( - cb, - ctx, - LEVEL_WARN as c_int, - is_kernel_target_str(), - ¬ice, - ) { - // The notice unwound, so `record` won't be delivered either — - // count it as dropped (the health contract), then poison iff - // this callback is still the installed one. - DROPPED.fetch_add(1, Ordering::Relaxed); - poison_sink_if_current(gen); - continue; - } - } if !invoke_callback(cb, ctx, record.level, record.target, &record.message) { - // The callback unwound and did NOT deliver this record — count the - // loss so kernel_logging_stats reflects it (previously the first - // failing record was silently uncounted), then poison iff this - // callback is still the installed one. + // The callback unwound without delivering this record; count the + // loss, then poison iff this callback is still the installed one. DROPPED.fetch_add(1, Ordering::Relaxed); poison_sink_if_current(gen); } } } -/// The kernel log target as a plain `&str`, for the synthetic drop-notice line -/// so it carries the same target as real kernel events. -fn is_kernel_target_str() -> &'static str { - crate::klog::KERNEL_LOG_TARGET -} - -/// A resolved forward filter: the default threshold for unmatched kernel -/// targets plus the per-target `RUST_LOG` directives ([`resolve_threshold`]). -struct ResolvedFilter { - /// Threshold for kernel targets no `directives` entry matches — the explicit - /// one-knob level, `RUST_LOG`'s bare global level, or the `warn` default. - default_level: u8, - /// Per-target `RUST_LOG` thresholds. Empty for the one-knob explicit-level - /// case (a uniform threshold), so the hot path stays lock-free. - directives: Vec<(String, u8)>, -} - -/// Resolve the callback's forward filter from the caller's explicit `level` -/// argument, mirroring `kernel_init_logging`'s precedence so the two C-ABI -/// logging routes filter identically: -/// -/// 1. an explicit, recognised `level` word wins as a UNIFORM one-knob -/// threshold (e.g. Go's driver level mapped through `DATABRICKS_LOG_LEVEL`), -/// with no per-target directives — the host asked for one level everywhere; -/// 2. otherwise `RUST_LOG`, parsed into per-target directives + a bare global -/// level ([`parse_rust_log`]), applied with `EnvFilter` precedence; -/// 3. otherwise `None` — the current filter is left untouched. +/// Resolve the callback's forward level, mirroring `kernel_init_logging`'s +/// precedence: an explicit recognised `level` word wins (Go maps its driver +/// level through here); else the most-verbose kernel-applicable `RUST_LOG` level +/// ([`parse_rust_log`]); else `None`, leaving the current level untouched. /// -/// This keeps the callback on the one-knob contract PECOBLR-3650 established: -/// `kernel_init_logging` maps the driver level to a level string, and the -/// callback path must honour that same string rather than only `RUST_LOG` — -/// otherwise a host at `DATABRICKS_LOG_LEVEL=debug` (but no `RUST_LOG`) would -/// silently drop kernel debug lines. -/// -/// Note the target matching still differs slightly from `kernel_init_logging`: -/// that path builds an `EnvFilter` (`::`-segment match), whereas this bridge -/// matches the broader `databricks` prefix (see `is_kernel_target`) for -/// forwarding, then applies the same per-target precedence for the threshold. So -/// for a `RUST_LOG` target directive the two routes select the same threshold -/// but not necessarily the identical event set. -fn resolve_filter(explicit: Option<&str>) -> Option { - if let Some(word) = explicit { - // A recognised explicit level always wins as a uniform threshold. "off" - // is honoured (the host asked for silence); an unrecognised word falls - // through to RUST_LOG. - if let Some(l) = parse_level_word(word) { - return Some(ResolvedFilter { - default_level: l, - directives: Vec::new(), - }); - } - } - if let Ok(rust_log) = std::env::var("RUST_LOG") { - let (directives, global) = parse_rust_log(&rust_log); - if !directives.is_empty() || global.is_some() { - return Some(ResolvedFilter { - // A `RUST_LOG` with only target directives (no bare level) leaves - // unmatched kernel targets at the static `warn` default. - default_level: global.unwrap_or(LEVEL_WARN), - directives, - }); - } - } - None +/// The explicit path matters because a host at `DATABRICKS_LOG_LEVEL=debug` with +/// no `RUST_LOG` must still get kernel debug lines. +fn resolve_level(explicit: Option<&str>) -> Option { + explicit.and_then(parse_level_word).or_else(|| { + std::env::var("RUST_LOG") + .ok() + .and_then(|r| parse_rust_log(&r)) + }) } -/// Install `filter` into the process-global filter state, returning whether it -/// actually changed anything (so the caller only rebuilds the callsite interest -/// cache when it matters). Writes the directives first, then the fast-path flag, -/// then the levels, so a concurrent reader never sees `HAS_DIRECTIVES` set -/// against a stale directive list. -fn apply_filter(filter: ResolvedFilter) -> bool { - let new_default = filter.default_level; - let new_max = filter - .directives - .iter() - .map(|(_, l)| *l) - .fold(new_default, u8::max); - let has_dirs = !filter.directives.is_empty(); - - let dirs_lock = DIRECTIVES.get_or_init(|| RwLock::new(Vec::new())); - let dirs_changed = match dirs_lock.write() { - Ok(mut w) => { - let changed = *w != filter.directives; - *w = filter.directives; - changed - } - // Couldn't inspect the old list (poisoned lock) — assume changed so the - // interest cache is rebuilt conservatively. - Err(_) => true, - }; - HAS_DIRECTIVES.store(has_dirs, Ordering::Relaxed); - MAX_LEVEL.store(new_max, Ordering::Relaxed); - let prev_default = LEVEL.swap(new_default, Ordering::Relaxed); - prev_default != new_default || dirs_changed +/// Install `level` as the process-global threshold, returning whether it changed +/// (so the caller only rebuilds the callsite interest cache when it matters). +fn apply_level(level: u8) -> bool { + LEVEL.swap(level, Ordering::Relaxed) != level } -/// Stand up the process-global subscriber + drain thread, retryable across calls -/// (see [`INSTALL_LOCK`]). Returns `true` iff THIS call performed the successful -/// install (so the caller rebuilds the interest cache for the freshly-installed -/// filter). A benign lost-race or a spawn failure returns `false`; the outcome -/// is recorded in [`INSTALL_STATUS`] for the caller's return code. -/// -/// Ordering matters: stand up the drain thread FIRST, and only then claim the -/// one global subscriber via `set_global_default`. This keeps two failure modes -/// clean: -/// -/// - Spawn failure: if the OS refuses the drain thread (EAGAIN/ENOMEM) we bail -/// out BEFORE touching the global subscriber, so the slot stays free and the -/// host can still fall back to `kernel_init_logging`. The status stays -/// retryable, so a later call can try again. (Claiming the subscriber first -/// would strand it with no drain thread, silently dropping every event.) -/// - Lost race: if another subscriber (e.g. `kernel_init_logging`) already -/// won, `set_global_default` drops the subscriber it was handed — and with -/// it the [`KernelLogLayer`]'s sender — so the freshly-spawned drain -/// thread's `recv()` errors and it exits (no idle-thread leak). No global -/// sender was ever published, so nothing can enqueue after the loss. +/// Stand up the process-global subscriber + drain thread, retryable across +/// calls (see [`INSTALL_LOCK`]). Returns `true` iff THIS call performed the +/// successful install; a benign lost-race or a spawn failure returns `false`, +/// with the outcome recorded in [`INSTALL_STATUS`] for the caller's return code. /// -/// The sender lives in the layer instance (not a separately-published global), -/// so there is no window where the subscriber is visible but the sender isn't -/// yet published: a concurrent kernel log in that gap would otherwise reach -/// `on_event`, find no sender, and be dropped WITHOUT being counted. -/// -/// `set_global_default` is attempted at most once per process: it runs only -/// after a drain thread is confirmed up, and both its outcomes (won / lost) are -/// terminal, so a retry never re-attempts it. +/// The drain thread is spawned FIRST, then the subscriber is claimed. So a +/// spawn failure (EAGAIN/ENOMEM) bails before touching the global slot, leaving +/// it free for `kernel_init_logging` and the status retryable; and a lost race +/// drops the layer (and its sender), so the freshly-spawned drain thread's +/// `recv()` errors and it exits without leaking. `set_global_default` runs at +/// most once per process — only after the drain thread is up, and both its +/// outcomes are terminal. fn ensure_installed() -> bool { // Terminal states need no work and no lock. match INSTALL_STATUS.load(Ordering::Acquire) { @@ -846,27 +550,22 @@ fn ensure_installed() -> bool { .name("kernel-log-drain".to_owned()) .spawn(move || drain_loop(rx)) { - // Record the OS error distinctly so on-call can tell a spawn failure from - // the benign "already installed" case. Use `.lock().ok()` (not - // `.unwrap()`) so a poisoned mutex can't panic across the FFI boundary. - // `tx` drops here (no thread was spawned); the global subscriber is left - // untouched, and the status stays retryable for a later call. + // Record the OS error distinctly from the benign "already installed" + // case. `.lock().ok()` so a poisoned mutex can't panic across the FFI + // boundary; `tx` drops here, leaving the subscriber slot untouched. if let Ok(mut guard) = SPAWN_ERROR.get_or_init(|| Mutex::new(None)).lock() { *guard = Some(e.to_string()); } INSTALL_STATUS.store(INSTALL_SPAWN_FAILED, Ordering::Release); return false; } - // Drain thread is running. Build the layer holding the sender, then claim the - // one global subscriber. Because the sender is inside the layer, it is - // published atomically with the subscriber — on_event never observes an - // installed-but-senderless state. + // Drain thread is up; build the layer (holding the sender) and claim the + // one global subscriber. let subscriber = tracing_subscriber::registry().with(KernelLogLayer { tx }.with_filter(KernelFilter)); if tracing::subscriber::set_global_default(subscriber).is_err() { - // Another global subscriber won. `set_global_default` dropped the - // subscriber (and the layer's sender) on the error path, so the drain - // thread's blocked `recv()` unblocks with an error and it exits cleanly. + // Another subscriber won; the dropped layer takes its sender with it, so + // the drain thread's `recv()` errors and it exits cleanly. INSTALL_STATUS.store(INSTALL_ALREADY_SET, Ordering::Release); return false; } @@ -882,21 +581,14 @@ fn ensure_installed() -> bool { /// `level` (a NUL-terminated `OFF`/`ERROR`/`WARN`/`INFO`/`DEBUG`/`TRACE` /// string, case-insensitive, or NULL) sets the forward filter with the same /// precedence as `kernel_init_logging`: an explicit recognised level wins as a -/// UNIFORM threshold, else `RUST_LOG` is applied per target with `EnvFilter` -/// precedence (so a submodule directive doesn't widen the canonical `klog!` -/// target). A host that maps its own logger level (Go's `DATABRICKS_LOG_LEVEL`) -/// passes it here so the callback filters on the one knob rather than only -/// `RUST_LOG`. When neither resolves (NULL / unrecognised level AND no matching -/// `RUST_LOG`) the current filter is LEFT UNCHANGED — the static `warn` default -/// on the first-ever call, but the previously-set filter on a re-registration -/// (the filter is process-global and last-writer-wins only when a writer -/// actually resolves one). +/// uniform threshold, else `RUST_LOG` is applied per target. When neither +/// resolves, the current filter is left unchanged — the `warn` default on the +/// first call, or the previously-set filter on a re-registration. /// /// Returns `Internal` (with a stored last error) if a global `tracing` -/// subscriber was already installed (e.g. by `kernel_init_logging`) — the two -/// are mutually exclusive; a C consumer installs exactly one — or if the -/// log-drain thread could not be spawned (a transient spawn failure is -/// retryable: a later call attempts the install again). +/// subscriber was already installed (they are mutually exclusive; install +/// exactly one), or if the log-drain thread could not be spawned (retryable — +/// a later call attempts the install again). /// /// # Safety /// `cb` must be a valid function pointer that is thread-safe, does not unwind, @@ -917,35 +609,26 @@ pub unsafe extern "C" fn kernel_set_log_callback( return KernelStatusCode::InvalidArgument; }; - // Resolve the forward threshold: explicit `level` (the host's mapped logger - // level) wins, else RUST_LOG, else the WARN default is left in place. A - // non-UTF-8 `level` is treated as absent (best-effort, like - // kernel_init_logging's level arg) rather than a hard error. This keeps the - // callback filtering on the same knob as the stderr path. + // A non-UTF-8 `level` is treated as absent (best-effort, like + // kernel_init_logging's level arg) rather than a hard error. let explicit_level = if level.is_null() { None } else { std::ffi::CStr::from_ptr(level).to_str().ok() }; - // Track whether the filter actually changed so we only rebuild the (process- - // wide, lock-taking) callsite interest cache when it matters — a same-filter - // ctx refresh or a call that loses the subscriber race shouldn't serialize - // all logging dispatch. + // Track whether the level actually changed, so the lock-taking callsite + // interest cache is only rebuilt when it matters (not on a ctx refresh). let mut filter_changed = false; - if let Some(resolved) = resolve_filter(explicit_level) { - filter_changed = apply_filter(resolved); + if let Some(level) = resolve_level(explicit_level) { + filter_changed = apply_level(level); } - // Record / refresh the sink (last writer wins). Clear any prior poison: a - // callback that unwound poisons the sink (drain_loop stops delivering to - // protect the process), but registering a NEW callback is an explicit - // request for a fresh start, so honour the last-writer-wins contract and let - // delivery resume. The drain thread reads the flag per record, so clearing - // it here (before releasing the SINK lock) is immediately effective. + // Record / refresh the sink (last writer wins) and clear any prior poison: + // registering a new callback is an explicit request to resume delivery. let sink = SINK.get_or_init(|| Mutex::new(None)); if let Ok(mut guard) = sink.lock() { - // A fresh generation so the drain thread won't let an old in-flight - // callback's unwind poison this new registration (see poison_sink_if_current). + // A fresh generation so an old in-flight callback's unwind can't poison + // this new registration (see poison_sink_if_current). let gen = NEXT_SINK_GEN.fetch_add(1, Ordering::Relaxed); *guard = Some(Sink { cb, @@ -958,12 +641,9 @@ pub unsafe extern "C" fn kernel_set_log_callback( // Install the process-global subscriber + drain thread (retryable across // calls after a transient spawn failure — see ensure_installed). let did_install = ensure_installed(); - // Rebuild the process-wide callsite interest cache only when it can matter: - // on the install that set our filter, or when a later call changed the - // filter. set_global_default rebuilds on its own, but the filter may have - // been set before install, and a re-filter after install needs a rebuild - // too; a same-filter ctx refresh or a race-loss does not (the rebuild takes - // the global callsite lock and re-evaluates every callsite in the binary). + // Rebuild the callsite interest cache only when it can matter: on the + // install that set our filter, or a later call that changed the filter. The + // rebuild takes the global callsite lock, so skip it on a ctx-only refresh. if did_install || filter_changed { tracing::callsite::rebuild_interest_cache(); } @@ -995,30 +675,15 @@ pub unsafe extern "C" fn kernel_set_log_callback( } } -/// Report the log-callback bridge's health so a host can tell whether kernel -/// logs are actually flowing. Writes to each (optional) out-param: -/// -/// - `installed`: `true` iff kernel logs are CURRENTLY being delivered — this -/// callback won the process-global subscriber AND the sink is not poisoned. -/// A callback that unwound poisons the sink (delivery stops); this then -/// reads `false` even though the subscriber is still installed, so a host -/// polling it sees a dead sink rather than a silent no-op. Registering a new -/// callback clears the poison and flips this back to `true`. -/// - `dropped`: cumulative count of kernel log records dropped after the -/// subscriber was installed — because the bounded delivery channel was full -/// (a slow callback) or the sink was poisoned by a callback that unwound. -/// This does NOT cover the drain-thread-never-started case (a spawn failure -/// leaves no channel to overflow); there `installed` reads `false` and -/// `kernel_set_log_callback` returned `Internal` with the spawn error. -/// -/// A NULL out-param is skipped. Never fails — a host can poll it to distinguish -/// "logs are quiet" from "logs are being dropped / the sink died / never -/// installed" (parity with the napi binding's `kernelLoggingStats()`). +/// Report the log-callback bridge's health (full contract in +/// `databricks_kernel.h`). `installed` is `true` iff this callback won the +/// subscriber and the sink is not poisoned; `dropped` is the cumulative records +/// lost to channel overflow or poisoning. A NULL out-param is skipped, and it +/// never fails. /// /// Clears the thread-local last-error on entry like every other C-ABI entry -/// point, so a host that calls this (successful, infallible) accessor between a -/// failed API call and reading the error doesn't observe the prior call's stale -/// error through it. +/// point, so a host polling this infallible accessor between a failed call and +/// reading the error doesn't observe a stale error through it. /// /// # Safety /// Each non-null out-param must point to a writable `bool` / `uint64_t`. @@ -1129,51 +794,38 @@ mod tests { #[test] fn should_emit_respects_configured_level() { - let target = crate::klog::KERNEL_LOG_TARGET; LEVEL.store(LEVEL_INFO, Ordering::Relaxed); - assert!(should_emit(target, &Level::ERROR)); - assert!(should_emit(target, &Level::INFO)); - assert!(!should_emit(target, &Level::DEBUG)); + assert!(should_emit(&Level::ERROR)); + assert!(should_emit(&Level::INFO)); + assert!(!should_emit(&Level::DEBUG)); LEVEL.store(LEVEL_OFF, Ordering::Relaxed); - assert!(!should_emit(target, &Level::ERROR)); + assert!(!should_emit(&Level::ERROR)); LEVEL.store(LEVEL_WARN, Ordering::Relaxed); // restore } #[test] - fn parse_rust_log_keeps_kernel_directives_and_global() { - // Kernel directives are retained with their target (for per-event prefix - // matching); foreign directives are dropped; a bare word is the global. - let (dirs, global) = parse_rust_log("hyper=off,databricks::sql::kernel=info,rustls=warn"); + fn parse_rust_log_collapses_to_most_verbose_kernel_level() { + // Foreign directives are ignored; the kernel one sets the level. assert_eq!( - dirs, - vec![("databricks::sql::kernel".to_owned(), LEVEL_INFO)] + parse_rust_log("hyper=off,databricks::sql::kernel=info,rustls=warn"), + Some(LEVEL_INFO) ); - assert_eq!(global, None); - - // Either kernel spelling is kept. - let (dirs, _) = parse_rust_log("databricks_sql_kernel=trace"); + // Either kernel spelling is accepted. assert_eq!( - dirs, - vec![("databricks_sql_kernel".to_owned(), LEVEL_TRACE)] + parse_rust_log("databricks_sql_kernel=trace"), + Some(LEVEL_TRACE) + ); + // A bare level word applies. + assert_eq!(parse_rust_log("debug"), Some(LEVEL_DEBUG)); + // Nothing kernel-applicable and no bare level → None. + assert_eq!(parse_rust_log("hyper=warn"), None); + assert_eq!(parse_rust_log(""), None); + // Non-matching databricks siblings and over-specific klog extensions are + // ignored (prefixes of no kernel event). + assert_eq!( + parse_rust_log("databricksfoo=warn,databricks::sql::kernel::foo=trace"), + None ); - - // A bare global level with no kernel directive. - let (dirs, global) = parse_rust_log("debug"); - assert!(dirs.is_empty()); - assert_eq!(global, Some(LEVEL_DEBUG)); - - // Nothing kernel-applicable and no bare level → empty. - let (dirs, global) = parse_rust_log("hyper=warn"); - assert!(dirs.is_empty()); - assert_eq!(global, None); - let (dirs, global) = parse_rust_log(""); - assert!(dirs.is_empty()); - assert_eq!(global, None); - - // Non-matching databricks siblings and over-specific extensions of the - // fixed-depth klog target are dropped (prefixes of no kernel event). - let (dirs, _) = parse_rust_log("databricksfoo=warn,databricks::sql::kernel::foo=trace"); - assert!(dirs.is_empty()); } #[test] @@ -1181,84 +833,32 @@ mod tests { // `EnvFilter` reads a bare kernel target (no `=level`) as that target at // TRACE — it must NOT be ignored, which would leave the callback at WARN // where kernel_init_logging emits trace. - let (dirs, global) = parse_rust_log("databricks::sql::kernel"); - assert_eq!( - dirs, - vec![("databricks::sql::kernel".to_owned(), LEVEL_TRACE)] - ); - assert_eq!(global, None); - // A foreign target-only directive is dropped; a kernel one becomes TRACE; - // a bare level word still sets the global. - let (dirs, global) = parse_rust_log("hyper,databricks_sql_kernel::session,info"); - assert_eq!( - dirs, - vec![("databricks_sql_kernel::session".to_owned(), LEVEL_TRACE)] - ); - assert_eq!(global, Some(LEVEL_INFO)); - } - - #[test] - fn resolve_threshold_per_target_does_not_widen_klog() { - // The reviewer's case: a klog directive and an unrelated submodule - // directive must NOT widen each other. Each target resolves against only - // the directives whose target is a PREFIX of it (EnvFilter's rule), so a - // single scalar can't collapse them into the most verbose one. - let (dirs, global) = parse_rust_log( - "databricks::sql::kernel=error,databricks_sql_kernel::reader::inline=trace", - ); - assert_eq!(global, None); - let default = global.unwrap_or(LEVEL_WARN); - // The canonical klog target keeps ERROR — the reader::inline=trace - // directive is not a prefix of it, so it does not apply (previously the - // single scalar collapsed to TRACE and widened klog to trace/debug). + assert_eq!(parse_rust_log("databricks::sql::kernel"), Some(LEVEL_TRACE)); + // A foreign target-only directive is ignored; a bare kernel target is + // TRACE and a bare level word is INFO, so the max (TRACE) wins. assert_eq!( - resolve_threshold("databricks::sql::kernel", default, &dirs), - LEVEL_ERROR - ); - // A module event under the submodule keeps its own TRACE directive. - assert_eq!( - resolve_threshold( - "databricks_sql_kernel::reader::inline::stream", - default, - &dirs - ), - LEVEL_TRACE - ); - // A kernel target matched by neither directive falls back to the default. - assert_eq!( - resolve_threshold("databricks_sql_kernel::session", default, &dirs), - LEVEL_WARN + parse_rust_log("hyper,databricks_sql_kernel::session,info"), + Some(LEVEL_TRACE) ); } #[test] - fn resolve_threshold_most_specific_wins_order_independent() { - // Longest matching prefix wins, independent of order (EnvFilter dedup - // is last-writer on a tie, so we replace on `>=`). - let dirs = vec![ - ("databricks".to_owned(), LEVEL_WARN), - ("databricks::sql::kernel".to_owned(), LEVEL_DEBUG), - ]; + fn parse_rust_log_takes_max_across_directives() { + // Multiple kernel-applicable directives collapse to the most verbose, + // order-independent (the callback carries one level). ERROR + TRACE → TRACE. assert_eq!( - resolve_threshold("databricks::sql::kernel", LEVEL_WARN, &dirs), - LEVEL_DEBUG + parse_rust_log("databricks::sql::kernel=error,databricks_sql_kernel::reader=trace"), + Some(LEVEL_TRACE) ); - let dirs_rev = vec![ - ("databricks::sql::kernel".to_owned(), LEVEL_DEBUG), - ("databricks".to_owned(), LEVEL_WARN), - ]; assert_eq!( - resolve_threshold("databricks::sql::kernel", LEVEL_WARN, &dirs_rev), - LEVEL_DEBUG + parse_rust_log("databricks_sql_kernel::reader=trace,databricks::sql::kernel=error"), + Some(LEVEL_TRACE) ); - // A databricks event matched only by the broad directive takes its level, - // not the more specific sibling's. + // A bare global level is also folded into the max. assert_eq!( - resolve_threshold("databricks::other", LEVEL_INFO, &dirs), - LEVEL_WARN + parse_rust_log("warn,databricks::sql::kernel=debug"), + Some(LEVEL_DEBUG) ); - // No matching directive → the default. - assert_eq!(resolve_threshold("databricks", LEVEL_INFO, &[]), LEVEL_INFO); } #[test] @@ -1286,31 +886,18 @@ mod tests { } #[test] - fn resolve_filter_explicit_level_is_uniform_one_knob() { - // An explicit, recognised level wins outright — this is the one-knob - // path (Go maps DATABRICKS_LOG_LEVEL and passes it in), independent of - // whatever RUST_LOG happens to be, and carries NO per-target directives - // (one level applies everywhere). We don't touch the process RUST_LOG - // here (that would race other tests); an explicit level short-circuits - // before RUST_LOG is ever read. - let f = resolve_filter(Some("debug")).expect("recognised level resolves"); - assert_eq!(f.default_level, LEVEL_DEBUG); - assert!( - f.directives.is_empty(), - "a one-knob explicit level carries no per-target directives" - ); - assert_eq!( - resolve_filter(Some("OFF")).unwrap().default_level, - LEVEL_OFF - ); - assert_eq!( - resolve_filter(Some("Error")).unwrap().default_level, - LEVEL_ERROR - ); + fn resolve_level_explicit_level_wins() { + // An explicit, recognised level wins outright — the one-knob path (Go + // maps DATABRICKS_LOG_LEVEL and passes it in), independent of RUST_LOG. + // We don't touch the process RUST_LOG here (that would race other tests); + // an explicit level short-circuits before RUST_LOG is ever read. + assert_eq!(resolve_level(Some("debug")), Some(LEVEL_DEBUG)); + assert_eq!(resolve_level(Some("OFF")), Some(LEVEL_OFF)); + assert_eq!(resolve_level(Some("Error")), Some(LEVEL_ERROR)); // An unrecognised explicit word falls through (to RUST_LOG, else None). assert_eq!(parse_level_word("not-a-level"), None); // NULL/absent explicit level defers to RUST_LOG (covered by the - // parse_rust_log / resolve_threshold tests). + // parse_rust_log tests). } #[test] diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 0b635a07..ec305d16 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -366,21 +366,18 @@ impl From for KernelStatusCode { } } -/// Current C-ABI version. Bump this on any change that alters a struct -/// layout ([`KernelStatusCode`], `KernelError`), changes the meaning of an -/// existing symbol, or ADDS / REMOVES an exported symbol — so a consumer -/// compiled against one header can detect a library built against a -/// different one. The symbol-set case matters as much as the layout one: a -/// consumer built against a header that declares a new symbol -/// (`kernel_set_log_callback`, `kernel_logging_stats`, …) could otherwise -/// link an older library that lacks it and only discover the missing symbol -/// at load/run time. Kept in lockstep with the `DATABRICKS_KERNEL_ABI_VERSION` -/// macro in `include/databricks_kernel.h` (the C smoke test asserts the two -/// agree). Pure v0.x aid — there is no ABI stability promise until v1.0. -/// -/// History: `1` = initial surface; `2` = added the log-callback bridge -/// (`kernel_set_log_callback`, `kernel_logging_stats`, `kernel_log_callback`). -pub const KERNEL_ABI_VERSION: u32 = 2; +/// Current C-ABI version. A coarse pre-1.0 handshake, NOT bumped per PR: +/// while the surface is still being built out, additive symbols land without +/// a bump (a consumer that doesn't reference a new symbol is unaffected, and +/// one that does rebuilds against the matching header anyway). Bump it only at +/// a deliberate checkpoint — a struct-layout change ([`KernelStatusCode`], +/// `KernelError`), a change to the meaning of an existing symbol, or a +/// stabilisation milestone — so a consumer compiled against one header can +/// detect a library built against a different one. Kept in lockstep with the +/// `DATABRICKS_KERNEL_ABI_VERSION` macro in `include/databricks_kernel.h` (the +/// C smoke test asserts the two agree). Pure v0.x aid — there is no ABI +/// stability promise until v1.0. +pub const KERNEL_ABI_VERSION: u32 = 1; /// Report the C-ABI version compiled into this library. A consumer that /// linked a header declaring `DATABRICKS_KERNEL_ABI_VERSION` should refuse From f95204459051fb38eb56318f3469de4f3a1c5687 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sun, 19 Jul 2026 15:07:54 +0000 Subject: [PATCH 12/15] fix(c-abi): address code-review findings on log-callback + cancel surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to the /full-review pass on the C-ABI expansion. Behavior stays additive; the changes are doc corrections, one error-code fix, a refactor, and test coverage for previously-untested paths. - F1/F2 docs: reword the cancel-token and blocking-close guarantees to match behavior. next_batch cancel stops the CALLER'S WAIT (returns Cancelled promptly); the detached CloudFetch download drains to its ~60s read-timeout rather than being torn down (only the inline connect path is a real abort). close_blocking's "confirmed server-side delete" softened: delete_session swallows the post-retry error and still returns Success, matching the direct-Rust/pyo3/napi Session::close parity. - F10: a drain-thread spawn failure now returns ResourceExhausted (retryable=true) instead of Internal (retryable=false), so the transient-vs-terminal (already-installed) distinction is machine-readable via KernelError.retryable, not prose-only. - F12: add a KernelLogLevel enum to the header and make the Rust LEVEL_* constants pub, so consumers reference symbols instead of hard-coding 1..5. - F9: correct the kernel_set_log_callback doc — RUST_LOG is collapsed to one most-verbose threshold, not applied per target. - F8: extract a shared ffi_prepare_runtime() (clear_error + reentrancy-reject + runtime fetch) so block_on_ffi and block_on_ffi_cancellable can't drift; add a reentrancy test for the cancellable entry point. - F4/F5/F6 tests: mid-flight fetch cancel returns Cancelled promptly against a stalled CloudFetch chunk; drop-on-full counts overflow while the emitter never blocks; mTLS cert+key are both forwarded through build_session. make check green (fmt + clippy + Rust suite + C smoke). Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- include/databricks_kernel.h | 63 +++++-- src/c_abi/logging.rs | 56 +++--- src/c_abi/mod.rs | 105 +++++++---- src/c_abi/session.rs | 110 +++++++++++- tests/v0_c_abi_cancel_token_wiremock.rs | 225 ++++++++++++++++++++++++ tests/v0_c_abi_log_callback_overflow.rs | 145 +++++++++++++++ 6 files changed, 622 insertions(+), 82 deletions(-) create mode 100644 tests/v0_c_abi_log_callback_overflow.rs diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8613bfd8..5cad7946 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -325,8 +325,9 @@ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); * back into any kernel_* entry point — a blocking reentrant call would stall the * drain thread (that reentrancy guard only covers query workers). `ctx` is * passed back verbatim and must stay valid for the process lifetime; `level` is - * 1=ERROR..5=TRACE; `target` and `message` are valid only for the call — copy - * them out. Records are enqueued on a bounded channel and DROPPED on overflow + * a `KernelLogLevel` value (1=ERROR..5=TRACE); `target` and `message` are valid + * only for the call — copy them out. Records are enqueued on a bounded channel + * and DROPPED on overflow * (logs never back-pressure a kernel hot path); the drop count is observable via * kernel_logging_stats. * @@ -338,9 +339,30 @@ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); * first call, or the previously-set level on a re-registration. * * Mutually exclusive with kernel_init_logging (both install the one - * process-global subscriber): returns Internal, with distinct error messages, - * if a subscriber was already installed or the drain thread could not start — - * install exactly ONE. A NULL `cb` returns InvalidArgument (no detach in v0). */ + * process-global subscriber). The failure code says whether a retry helps + * (KernelError.retryable matches, so no message string-matching needed): + * Internal (retryable=false) if a subscriber was already installed — terminal, + * install exactly ONE; ResourceExhausted (retryable=true) if the drain thread + * could not start (EAGAIN/ENOMEM) — a later call retries. A NULL `cb` returns + * InvalidArgument (no detach in v0). */ + +/* + * Severity delivered to a `kernel_log_callback` as its `int level`. Values match + * the kernel's internal numeric severity (low = more severe). Prefer these + * symbols over hard-coded 1..5 so a future level insertion (with an ABI bump) + * surfaces as a build change rather than a silent host-side remap. `Off` (0) is + * never delivered to a callback — it only appears as a filter threshold meaning + * "emit nothing". + */ +typedef enum KernelLogLevel { + KernelLogLevel_Off = 0, + KernelLogLevel_Error = 1, + KernelLogLevel_Warn = 2, + KernelLogLevel_Info = 3, + KernelLogLevel_Debug = 4, + KernelLogLevel_Trace = 5, +} KernelLogLevel; + typedef void (*kernel_log_callback)(void* ctx, int level, const char* target, const char* message); KernelStatusCode kernel_set_log_callback(kernel_log_callback cb, void* ctx, @@ -682,16 +704,27 @@ KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, struct ArrowArray* out_array, struct ArrowSchema* out_schema); /* - * Like kernel_result_stream_next_batch, but races the (blocking) fetch against - * `cancel_token` so a host can interrupt a HUNG CloudFetch chunk (a wedged S3 / - * pre-signed-URL GET) instead of blocking on it forever. A NULL `cancel_token` - * behaves EXACTLY like kernel_result_stream_next_batch. If the token fires - * before the batch is ready, the fetch future is dropped (aborting the in-flight - * download) and this returns KernelStatusCode_Cancelled; the stream handle stays - * valid and owned by the caller (close it with kernel_result_stream_close as - * usual — a cancelled fetch neither consumes nor frees it). `cancel_token` is - * borrowed and safe to fire from another thread while this call is in flight - * (see kernel_session_open_cancellable). + * Like kernel_result_stream_next_batch, but races the (blocking) wait for the + * next batch against `cancel_token` so a host can stop waiting on a HUNG + * CloudFetch chunk (a wedged S3 / pre-signed-URL GET) instead of blocking on it + * forever. A NULL `cancel_token` behaves EXACTLY like + * kernel_result_stream_next_batch. If the token fires before the batch is ready, + * this call unblocks promptly and returns KernelStatusCode_Cancelled; the stream + * handle stays valid and owned by the caller (close it with + * kernel_result_stream_close as usual — a cancelled fetch neither consumes nor + * frees it). + * + * NOTE ON SCOPE: cancel here interrupts the CALLER'S WAIT, not the background + * download. The CloudFetch chunk GET runs on a detached kernel task; firing the + * token drops only this call's waiter, so the return is prompt but the in-flight + * download continues to completion or its own read-timeout (~60s) before its + * in-memory slot is released. Closing the stream after a cancel triggers the + * provider's own teardown, but does not abort a GET already on the wire either. + * (The connect-side kernel_session_open_cancellable DOES abort its in-flight + * request, because create-session runs inline in the raced future.) + * + * `cancel_token` is borrowed and safe to fire from another thread while this + * call is in flight (see kernel_session_open_cancellable). */ KernelStatusCode kernel_result_stream_next_batch_cancellable( kernel_result_stream_t* stream, struct ArrowArray* out_array, diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs index 6da1eb13..43e16acd 100644 --- a/src/c_abi/logging.rs +++ b/src/c_abi/logging.rs @@ -73,9 +73,9 @@ use tracing_subscriber::layer::{Context, Filter, Layer, SubscriberExt}; use tracing_subscriber::registry::LookupSpan; /// Host log sink: a C function pointer plus an opaque host context passed back -/// verbatim on every call. `level` is 1=ERROR..5=TRACE (mirrors the bridge's -/// numeric severity); `target` and `message` are NUL-terminated C strings valid -/// only for the duration of the call. +/// verbatim on every call. `level` is a `KernelLogLevel` value (1=ERROR..5=TRACE; +/// see the `LEVEL_*` constants and the header enum); `target` and `message` are +/// NUL-terminated C strings valid only for the duration of the call. /// /// The ABI is `C-unwind` so a panicking host callback propagates across the /// boundary and `invoke_callback`'s `catch_unwind` can contain it; a plain @@ -112,12 +112,18 @@ struct Sink { const CHANNEL_CAPACITY: usize = 4096; -const LEVEL_OFF: u8 = 0; -const LEVEL_ERROR: u8 = 1; -const LEVEL_WARN: u8 = 2; -const LEVEL_INFO: u8 = 3; -const LEVEL_DEBUG: u8 = 4; -const LEVEL_TRACE: u8 = 5; +// Numeric severity delivered to the host callback and used as the forward +// threshold (low = more severe; `0` = off / emit nothing). These are the Rust +// side of the header's `KernelLogLevel` enum and MUST stay in lockstep with it +// (`KernelLogLevel_Off`..`KernelLogLevel_Trace`); `pub` so a consumer of the +// crate (and the C-ABI documentation) can reference them by name rather than +// hard-coding 1..5. +pub const LEVEL_OFF: u8 = 0; +pub const LEVEL_ERROR: u8 = 1; +pub const LEVEL_WARN: u8 = 2; +pub const LEVEL_INFO: u8 = 3; +pub const LEVEL_DEBUG: u8 = 4; +pub const LEVEL_TRACE: u8 = 5; /// Forward threshold for all kernel events: the explicit one-knob level, the /// most-verbose kernel-applicable `RUST_LOG` level, or the static `warn` @@ -581,14 +587,18 @@ fn ensure_installed() -> bool { /// `level` (a NUL-terminated `OFF`/`ERROR`/`WARN`/`INFO`/`DEBUG`/`TRACE` /// string, case-insensitive, or NULL) sets the forward filter with the same /// precedence as `kernel_init_logging`: an explicit recognised level wins as a -/// uniform threshold, else `RUST_LOG` is applied per target. When neither -/// resolves, the current filter is left unchanged — the `warn` default on the -/// first call, or the previously-set filter on a re-registration. +/// uniform threshold, else the single most-verbose kernel-applicable `RUST_LOG` +/// level (collapsed to one threshold, not per-target filtering — the bridge +/// carries one level). When neither resolves, the current filter is left +/// unchanged — the `warn` default on the first call, or the previously-set +/// filter on a re-registration. /// -/// Returns `Internal` (with a stored last error) if a global `tracing` -/// subscriber was already installed (they are mutually exclusive; install -/// exactly one), or if the log-drain thread could not be spawned (retryable — -/// a later call attempts the install again). +/// On failure the return code encodes whether a retry could help, so a host +/// doesn't have to string-match the message: `Internal` (terminal, +/// `retryable=false`) if a global `tracing` subscriber was already installed +/// (they are mutually exclusive; install exactly one), or `ResourceExhausted` +/// (`retryable=true`) if the log-drain thread could not be spawned — a later +/// call attempts the install again. /// /// # Safety /// `cb` must be a valid function pointer that is thread-safe, does not unwind, @@ -655,13 +665,15 @@ pub unsafe extern "C" fn kernel_set_log_callback( .get() .and_then(|m| m.lock().ok().and_then(|g| g.clone())) .unwrap_or_else(|| "unknown".to_owned()); - crate::c_abi::error::store_and_code(Error::new( - ErrorCode::Internal, - format!( - "kernel_set_log_callback: the log-drain thread could not be started ({detail}); \ + // `ResourceExhausted` (retryable=true) not `Internal` (retryable=false): + // an OS refusal to spawn the drain thread (EAGAIN/ENOMEM) is transient + // and a later call retries the install, so the machine-readable + // `KernelError.retryable` must say so — distinct from the terminal + // already-installed case below, which stays a non-retryable `Internal`. + crate::c_abi::error::store_and_code(Error::resource_exhausted().message(format!( + "kernel_set_log_callback: the log-drain thread could not be started ({detail}); \ kernel logs will not reach the callback" - ), - )) + ))) } // INSTALL_ALREADY_SET (or a still-PENDING install we couldn't take the // lock for): a global subscriber was already installed, or the install diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index ec305d16..83ad68a1 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -119,11 +119,14 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime:: /// /// [`KernelStatusCode`]: crate::c_abi::KernelStatusCode /// [`Error`]: crate::kernel_error::Error -pub(crate) fn block_on_ffi(fut_builder: F) -> Result -where - F: FnOnce() -> Fut, - Fut: std::future::Future>, -{ +/// Shared preamble for the two `block_on_ffi*` entry shapes: clear the +/// thread-local last error, reject reentrancy from a Tokio runtime thread, and +/// fetch the process-wide runtime. On failure the typed [`Error`] is already +/// stored and the mapped [`KernelStatusCode`] is returned, so the caller just +/// propagates it. Kept in one place so the load-bearing threading-contract guard +/// (and its exact message) can't drift between `block_on_ffi` and +/// `block_on_ffi_cancellable`. +fn ffi_prepare_runtime() -> Result<&'static tokio::runtime::Runtime, KernelStatusCode> { error::clear_error(); // Reject reentrancy explicitly: calling `block_on` from within any // Tokio runtime would panic. Surface a typed, actionable error rather @@ -138,14 +141,19 @@ where error::store_error(e); return Err(code); } - let rt = match runtime() { - Ok(rt) => rt, - Err(e) => { - let code = KernelStatusCode::from(e.code); - error::store_error(e); - return Err(code); - } - }; + runtime().map_err(|e| { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + code + }) +} + +pub(crate) fn block_on_ffi(fut_builder: F) -> Result +where + F: FnOnce() -> Fut, + Fut: std::future::Future>, +{ + let rt = ffi_prepare_runtime()?; // Catch panics so a kernel bug can't unwind across `extern "C"`. let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rt.block_on(fut_builder()))); @@ -167,11 +175,19 @@ where /// /// When `token` fires before the future completes, this **drops the future** /// and returns [`KernelStatusCode::Cancelled`] with a typed `Cancelled` error -/// in the thread-local buffer. Dropping the future is what makes the cancel -/// *real* rather than a bare stop-waiting: the kernel's HTTP client is -/// `reqwest`, whose in-flight request futures abort when dropped (the crate's -/// documented cancellation model — see the CloudFetch streaming provider's own -/// token use), so the underlying socket work is torn down, not leaked. +/// in the thread-local buffer. +/// +/// How much the drop actually tears down depends on the raced future. Where the +/// I/O is awaited *inline* in that future — the connect path +/// (`kernel_session_open_cancellable`) — dropping it drops the in-flight +/// `reqwest` request, which aborts on drop (the crate's documented cancellation +/// model), so the socket work is genuinely torn down. Where the I/O runs on a +/// *detached* task and the future only awaits a waiter — the CloudFetch fetch +/// path (`kernel_result_stream_next_batch_cancellable`), whose download lives on +/// a spawned task — the drop unblocks the caller promptly but the background +/// download continues to completion or its own read-timeout. So this is a prompt +/// stop-waiting in general, and additionally a real abort wherever the request +/// is awaited inline. /// /// A **null** token means "no cancellation" and this behaves exactly like /// [`block_on_ffi`] — so a single implementation body can back both the plain @@ -196,27 +212,9 @@ where return block_on_ffi(fut_builder); }; - error::clear_error(); - // Reject reentrancy explicitly (same reasoning as block_on_ffi): block_on - // from within any Tokio runtime would panic. - if tokio::runtime::Handle::try_current().is_ok() { - let e = crate::kernel_error::Error::new( - crate::kernel_error::ErrorCode::Internal, - "kernel C ABI called from within a Tokio runtime thread; entry points must be \ - invoked from a native (non-async-runtime) thread", - ); - let code = KernelStatusCode::from(e.code); - error::store_error(e); - return Err(code); - } - let rt = match runtime() { - Ok(rt) => rt, - Err(e) => { - let code = KernelStatusCode::from(e.code); - error::store_error(e); - return Err(code); - } - }; + // Same preamble as block_on_ffi (clear-error + reentrancy-reject + runtime + // fetch), shared so the threading-contract guard can't drift between them. + let rt = ffi_prepare_runtime()?; // Race the work against the token. `select!` drops the losing branch's // future, so a cancel here drops the in-flight request future. Wrapped in @@ -433,4 +431,33 @@ mod tests { ); }); } + + #[test] + fn block_on_ffi_cancellable_rejects_reentrancy_from_runtime_thread() { + // The cancellable entry shape shares block_on_ffi's preamble via + // ffi_prepare_runtime, so it must reject reentrancy identically. This + // locks in the shared guard the two shapes used to duplicate. + let rt = tokio::runtime::Runtime::new().expect("runtime"); + rt.block_on(async { + let token = tokio_util::sync::CancellationToken::new(); + let result: Result<(), KernelStatusCode> = + block_on_ffi_cancellable(Some(&token), || async { Ok(()) }); + assert_eq!(result, Err(KernelStatusCode::Internal)); + + let mut out = std::mem::MaybeUninit::::uninit(); + // SAFETY: out is a valid writable pointer. + let present = unsafe { crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr()) }; + assert!(present, "reentrancy must populate the last-error buffer"); + // SAFETY: present is true, so out is initialised. + let err = unsafe { out.assume_init() }; + // SAFETY: message is non-null after a store. + let msg = unsafe { std::ffi::CStr::from_ptr(err.message) } + .to_str() + .unwrap(); + assert!( + msg.contains("within a Tokio runtime"), + "reentrancy error should explain the threading contract, got: {msg}", + ); + }); + } } diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 8b0d3524..e59bbbab 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -863,13 +863,24 @@ pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> KernelStatusCode::Success } -/// Close a session and BLOCK until the server-side `DeleteSession` -/// completes (or errors), reusing the crate's awaitable +/// Close a session and BLOCK until the server-side `DeleteSession` RPC +/// has been *attempted* to completion, reusing the crate's awaitable /// [`Session::close`]. Unlike [`kernel_session_close`] (fire-and-forget), -/// a program that exits right after this returns has a confirmed -/// server-side delete — this is the parity path for a host (Thrift, ODBC) -/// that wants close to behave like the synchronous `DeleteSession` RPC the -/// direct-Rust and pyo3/napi consumers get via `Session::close().await`. +/// this waits for the delete round-trip rather than returning before it — +/// the parity path for a host (Thrift, ODBC) that wants close to behave +/// like the synchronous `DeleteSession` RPC the direct-Rust and pyo3/napi +/// consumers get via `Session::close().await`. +/// +/// IMPORTANT: `Success` means the delete was *attempted*, not that the +/// server confirmed it. [`Session::close`] delegates to `delete_session`, +/// which — after exhausting HTTP retries — logs a transient failure and +/// returns `Ok(())` rather than propagating it (the caller has no useful +/// recovery path, and the server reclaims the session on idle-timeout). So +/// a partitioned/failed delete still returns `Success` here (surfaced only +/// as a kernel `warn!`, visible to a host that installed a log callback); +/// `Err(code)` is reserved for a null handle, reentrancy, or a panic. This +/// matches the direct-Rust / pyo3 / napi consumers, whose `Session::close` +/// swallows the same failure identically. /// /// Consumes the handle exactly like [`kernel_session_close`]: on both /// success and failure the session is released, so the caller must not use @@ -1113,6 +1124,93 @@ mod tests { } } + /// BOTH mTLS halves must be forwarded from the setter through `build_session` + /// into `TlsConfig` and on to the reqwest client build. The setter-storage + /// test above only proves the config holds both bytes; this proves the + /// forwarding path is wired by driving a real `kernel_session_open`. + /// + /// We set a syntactically-invalid cert+key pair and open. The client build + /// runs `build_mtls_identity(cert, key)` eagerly (before any network dial), + /// which fails with the "Invalid mTLS client certificate/key" message — and + /// that message is reachable ONLY if BOTH halves arrived at the identity + /// builder. A regression that dropped the key (or the whole branch) would + /// instead surface the distinct "client_cert_pem is set without + /// client_key_pem" error or open past the cert entirely, so this asserts on + /// the identity-parse message specifically. No server needed: the failure is + /// synchronous at client construction. + #[test] + fn mtls_cert_and_key_forwarded_through_build_session() { + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + // A reachable (unused) address + PAT so the config is otherwise valid + // and open() proceeds to the client build. The mTLS parse fails first. + let host = CString::new("https://example.invalid").unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + let token = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + // Well-formed PEM framing but non-parseable contents, so both halves + // reach the identity builder and fail there (not at PEM framing). + let cert = b"-----BEGIN CERTIFICATE-----\nnot-a-real-cert\n-----END CERTIFICATE-----\n"; + let key = format!( + "-----BEGIN {} KEY-----\nnot-a-real-key\n-----END {} KEY-----\n", + "PRIVATE", "PRIVATE" + ) + .into_bytes(); + assert_eq!( + kernel_session_config_set_tls_client_certificate( + config, + cert.as_ptr(), + cert.len(), + key.as_ptr(), + key.len(), + ), + KernelStatusCode::Success + ); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + // kernel_session_open consumes `config` on EVERY path (success and + // failure), so it must NOT be freed again below. + let rc = kernel_session_open(config, &mut session); + assert_ne!( + rc, + KernelStatusCode::Success, + "open with an invalid mTLS identity must fail, not succeed" + ); + assert!(session.is_null(), "no session handle on a failed open"); + + // Read the stored last error and assert it is the mTLS identity-parse + // failure — the proof that both cert AND key were forwarded into the + // client build. + let mut out = std::mem::MaybeUninit::::uninit(); + let present = crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr()); + assert!(present, "a failed open must populate the last-error buffer"); + let err = out.assume_init(); + let msg = std::ffi::CStr::from_ptr(err.message).to_str().unwrap(); + assert!( + msg.contains("Invalid mTLS client certificate/key"), + "the failure must be the mTLS identity parse (both halves forwarded), \ + not a missing-half or unrelated error; got: {msg}" + ); + assert!( + !msg.contains("without client_key_pem") && !msg.contains("without client_cert_pem"), + "neither half may be dropped on the forwarding path; got: {msg}" + ); + // No kernel_session_config_free: kernel_session_open already consumed + // and released `config` on its failure path. + } + } + /// The CloudFetch setter records the toggle as `Some(enabled)`; a config /// that never calls it leaves `None` so the kernel default (on) wins. The /// last call wins (set false then true → true). diff --git a/tests/v0_c_abi_cancel_token_wiremock.rs b/tests/v0_c_abi_cancel_token_wiremock.rs index f0a5f59e..348eaa0d 100644 --- a/tests/v0_c_abi_cancel_token_wiremock.rs +++ b/tests/v0_c_abi_cancel_token_wiremock.rs @@ -402,3 +402,228 @@ fn next_batch_cancellable_prefired_token_short_circuits_fetch() { assert_eq!(kernel_session_close(session), KernelStatusCode::Success); } } + +/// One chunk's worth of Arrow IPC stream bytes carrying a single Int64 column +/// `n`. Used to build multi-chunk CloudFetch (external-link) results. +fn arrow_chunk_ipc(values: Vec) -> Vec { + let batch = RecordBatch::try_from_iter([( + "n", + std::sync::Arc::new(Int64Array::from(values)) as arrow_array::ArrayRef, + )]) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut w = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + w.write(&batch).unwrap(); + w.finish().unwrap(); + } + ipc +} + +/// A SUCCEEDED statement body describing a **two-chunk** CloudFetch result whose +/// chunks are served as external links back at the mock server. Chunk 0 carries +/// its own `next_chunk_index=1` so the reader keeps going after the first batch. +fn succeeded_two_chunk_external_body( + statement_id: &str, + chunk0_url: &str, + chunk1_url: &str, + chunk0_bytes: i64, + chunk1_bytes: i64, +) -> String { + json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { "column_count": 1, "columns": [ + { "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0 } + ]}, + "total_chunk_count": 2, + "total_row_count": 4, + "truncated": false, + }, + "result": { + "external_links": [ + { + "external_link": chunk0_url, + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": 0, + "row_offset": 0, + "row_count": 2, + "byte_count": chunk0_bytes, + "next_chunk_index": 1, + }, + { + "external_link": chunk1_url, + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": 1, + "row_offset": 2, + "row_count": 2, + "byte_count": chunk1_bytes, + }, + ], + }, + }) + .to_string() +} + +/// F4: a token fired WHILE a CloudFetch chunk download is genuinely in flight +/// interrupts the caller's wait promptly. This is the mid-flight fetch property +/// the pre-fired inline test can't reach (there, no download exists). +/// +/// Shape: a two-chunk external-link result. Chunk 0's GET returns valid Arrow +/// IPC immediately, so `execute()` + `get_schema()` (which eagerly waits on +/// chunk 0) and the FIRST `next_batch` both complete normally. Chunk 1's GET is +/// STALLED with a long `set_delay`, so the SECOND `next_batch_cancellable` is +/// blocked on an actually-in-flight download. A watcher thread fires the token +/// mid-fetch, and the call must return `Cancelled` well before the stall would +/// elapse — proving cancel interrupts the wait on a live fetch. +/// +/// Per the corrected F1 contract, this asserts the caller unblocks promptly; it +/// does NOT assert the background download is torn down (it isn't — the detached +/// task drains to its read-timeout), which is exactly why the header/rows.go +/// docs were reworded from "aborts the download" to "stops waiting". +#[test] +fn next_batch_cancellable_fires_during_stalled_fetch() { + let chunk0 = arrow_chunk_ipc(vec![1, 2]); + let chunk0_len = chunk0.len() as i64; + + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = + rt.block_on(async { + let server = MockServer::start().await; + let chunk0_url = format!("{}/cf/stmt-stall/chunk-0.arrow", server.uri()); + let chunk1_url = format!("{}/cf/stmt-stall/chunk-1.arrow", server.uri()); + + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#"{"session_id":"sess-stall-fetch","warehouse_id":"test_wh"}"#, + )) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-stall-fetch")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string( + succeeded_two_chunk_external_body( + "stmt-stall", + &chunk0_url, + &chunk1_url, + chunk0_len, + 1024, + ), + )) + .mount(&server) + .await; + // Chunk 0: immediate valid Arrow IPC (drives schema + first batch). + Mock::given(method("GET")) + .and(path("/cf/stmt-stall/chunk-0.arrow")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(chunk0.clone())) + .mount(&server) + .await; + // Chunk 1: STALLED — the download the second next_batch blocks on. The + // 30s delay is far longer than the cancel latency we assert below. + Mock::given(method("GET")) + .and(path("/cf/stmt-stall/chunk-1.arrow")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(30)) + .set_body_bytes(arrow_chunk_ipc(vec![3, 4])), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT n FROM t").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec), + KernelStatusCode::Success + ); + let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); + assert_eq!( + kernel_executed_statement_get_result_stream(exec, &mut stream), + KernelStatusCode::Success + ); + assert!(!stream.is_null()); + + // First batch (chunk 0) fetches normally with a NULL token. + let mut arr0 = FFI_ArrowArray::empty(); + let mut sch0 = FFI_ArrowSchema::empty(); + let rc = kernel_result_stream_next_batch_cancellable( + stream, + &mut arr0, + &mut sch0, + std::ptr::null(), + ); + assert_eq!( + rc, + KernelStatusCode::Success, + "chunk 0 must fetch normally before the stalled chunk 1" + ); + + // Second batch (chunk 1) is stalled server-side. Fire the token from a + // watcher thread after a short beat; the call must return Cancelled well + // before the 30s stall elapses. + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); + let tok_addr = tok as usize; + let watcher = thread::spawn(move || { + thread::sleep(Duration::from_millis(200)); + let t = tok_addr as *mut kernel_cancel_token_t; + assert_eq!(kernel_cancel_token_cancel(t), KernelStatusCode::Success); + }); + + let mut arr1 = FFI_ArrowArray::empty(); + let mut sch1 = FFI_ArrowSchema::empty(); + let start = Instant::now(); + let rc = kernel_result_stream_next_batch_cancellable(stream, &mut arr1, &mut sch1, tok); + let elapsed = start.elapsed(); + watcher.join().unwrap(); + + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "a token fired mid-fetch must interrupt the wait on the stalled chunk" + ); + assert!( + elapsed < Duration::from_secs(5), + "cancel must unblock the stalled fetch promptly, took {elapsed:?}" + ); + assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); + + kernel_result_stream_close(stream); + kernel_executed_statement_close(exec); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} diff --git a/tests/v0_c_abi_log_callback_overflow.rs b/tests/v0_c_abi_log_callback_overflow.rs new file mode 100644 index 00000000..311ddddb --- /dev/null +++ b/tests/v0_c_abi_log_callback_overflow.rs @@ -0,0 +1,145 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Drop-on-full test for the `kernel_set_log_callback` bridge's bounded channel. +//! +//! The delivery test (`v0_c_abi_log_callback.rs`) covers the healthy path +//! (`dropped == 0`) and the poison path (a record lost to an unwinding +//! callback). It does NOT exercise the headline "logs never back-pressure a +//! kernel hot path" behavior — the `try_send(...).is_err()` overflow branch in +//! `KernelLogLayer::on_event`. This test does: it WEDGES the single drain thread +//! inside a blocking callback so records can't be consumed, floods the bounded +//! channel (capacity 4096) with far more than that many kernel events, and +//! asserts `kernel_logging_stats` reports `dropped > 0` while the emitting +//! thread stays responsive (never blocks). A regression that swapped the +//! non-blocking `try_send` for a blocking `send` would stall the emitter here +//! instead of dropping — which this test would catch as a hang. +//! +//! Its own integration-test binary (like the delivery test): it installs the +//! process-global `tracing` subscriber and permanently wedges the drain thread, +//! so it must not share a process with tests that assert a healthy sink. + +use std::os::raw::{c_char, c_int, c_void}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use databricks_sql_kernel::c_abi::logging::{kernel_logging_stats, kernel_set_log_callback}; +use databricks_sql_kernel::c_abi::KernelStatusCode; + +// The channel capacity in `src/c_abi/logging.rs`. Kept in sync by construction: +// we emit comfortably more than this so the overflow branch is guaranteed. +const CHANNEL_CAPACITY: usize = 4096; + +// Set by the callback the instant it is first entered — signals that the drain +// thread has pulled one record and is now blocked inside the callback, so any +// further emits must pile onto (and overflow) the bounded channel. +static WEDGED: AtomicBool = AtomicBool::new(false); +// Cleared to release the wedged callback so the drain thread can finish and exit +// cleanly at end of test. +static RELEASE: AtomicBool = AtomicBool::new(false); +static DELIVERED: AtomicUsize = AtomicUsize::new(0); + +/// A callback that blocks the drain thread until the test releases it. The first +/// (and, while wedged, only) delivered record parks here; every later buffered +/// record runs fast once released. +extern "C-unwind" fn wedging_cb( + _ctx: *mut c_void, + _level: c_int, + _target: *const c_char, + _message: *const c_char, +) { + WEDGED.store(true, Ordering::SeqCst); + DELIVERED.fetch_add(1, Ordering::SeqCst); + // Park the drain thread here so the bounded channel fills. Bounded spin so a + // bug in the release path can't hang CI forever. + let start = Instant::now(); + while !RELEASE.load(Ordering::SeqCst) && start.elapsed() < Duration::from_secs(30) { + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn drop_on_full_counts_overflow_without_blocking_the_emitter() { + // Fresh single-test binary: nothing else has claimed the global subscriber, + // so install MUST succeed. Install at trace so the ERROR flood below clears + // the threshold and every event reaches the channel. + let level = std::ffi::CString::new("trace").unwrap(); + let rc = + unsafe { kernel_set_log_callback(Some(wedging_cb), std::ptr::null_mut(), level.as_ptr()) }; + assert_eq!( + rc, + KernelStatusCode::Success, + "kernel_set_log_callback must succeed on first install in a fresh binary; got {rc:?}" + ); + + // Emit one event and wait for the drain thread to pull it and wedge inside + // the callback. Once WEDGED, exactly one record has been consumed and the + // drain thread is blocked — so subsequent emits can only fill the channel. + tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "wedge-primer"); + let mut wedged = false; + for _ in 0..500 { + if WEDGED.load(Ordering::SeqCst) { + wedged = true; + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + assert!( + wedged, + "the drain thread should have entered the blocking callback (wedged)" + ); + + // Flood well past the buffer. With the drain thread wedged, at most + // CHANNEL_CAPACITY records can buffer; the rest hit the try_send-full branch + // and are counted in `dropped`. Time the loop: if try_send ever became a + // blocking send, this would stall for ~30s (the callback's park) instead of + // returning promptly — so a slow loop is itself a failure signal. + let flood = CHANNEL_CAPACITY * 2 + 500; + let start = Instant::now(); + for i in 0..flood { + tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "flood-{}", i); + } + let elapsed = start.elapsed(); + assert!( + elapsed < Duration::from_secs(5), + "emitting {flood} events must not block the caller (drop-on-full, not back-pressure); \ + took {elapsed:?} — a blocking send would stall on the wedged drain thread" + ); + + // The drops happen synchronously in on_event on this thread during the + // flood, so `dropped` is already positive; poll briefly only for robustness. + let mut installed = false; + let mut dropped: u64 = 0; + for _ in 0..50 { + unsafe { kernel_logging_stats(&mut installed, &mut dropped) }; + if dropped > 0 { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + assert!( + dropped > 0, + "flooding a wedged bridge past its {CHANNEL_CAPACITY}-record channel must drop records \ + (dropped={dropped}); the overflow branch was not exercised" + ); + assert!( + installed, + "the sink is still installed (a full channel drops records, it does not poison the sink)" + ); + + // Release the wedged callback so the drain thread drains the buffer and can + // exit cleanly; the process would reap it regardless, but this keeps the + // teardown tidy. + RELEASE.store(true, Ordering::SeqCst); +} From c19e5d1ea1a587d16e4ac54c8afd520eca56d00a Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sun, 19 Jul 2026 16:46:07 +0000 Subject: [PATCH 13/15] feat(c-abi): add kernel_session_close_blocking_cancellable (F3) + document metadata exemption (F7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up on the review's cancellation-surface findings. F3: kernel_session_close_blocking had no cancel path, so a wedged/partitioned CloseSession could pin the calling host thread up to the retry ceiling (~900s) with no cooperative escape — the exact stall class the cancel token was introduced to bound, and the third `_cancellable` twin the ctx-cancel plan called for (open + next_batch already had theirs). It's also the symbol the Go driver's CloseSession comment defers blocking-close adoption on. - Refactor close_blocking into a shared session_close_blocking_inner taking Option<&CancellationToken>; add kernel_session_close_blocking_cancellable routed through the existing null-transparent block_on_ffi_cancellable. - Session::close awaits delete_session inline, so a fired token drops the in-flight DeleteSession (a real abort) and the boxed session; SessionInner's Drop then fires a best-effort fire-and-forget delete. Documented: the handle is consumed on EVERY path including Cancelled. - Wiremock tests: fire mid-close against a 30s-stalled DELETE returns Cancelled in <5s; a NULL token awaits the DELETE like the plain blocking close. F7: document (in the cancel-token header comment) that the metadata entry points have no `_cancellable` twin by design — no host consumer needs a caller deadline yet, they stay bounded by transport timeouts, and twins can be added the same additive way if a host adopts them. Also corrected the close_blocking header doc to the F2 "Success = attempted, not confirmed" wording (the Rust doc was already fixed; the header block had been missed). make check green (fmt + clippy + Rust suite + C smoke). Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- include/databricks_kernel.h | 54 ++++-- src/c_abi/session.rs | 59 ++++++- ...0_c_abi_session_close_blocking_wiremock.rs | 159 +++++++++++++++++- 3 files changed, 253 insertions(+), 19 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 5cad7946..224936e9 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -240,14 +240,23 @@ typedef struct kernel_result_stream_t kernel_result_stream_t; * cancels the LATER query. Use one per execute (new before execute, free after * it returns). */ typedef struct kernel_statement_canceller_t kernel_statement_canceller_t; -/* Cooperative cancel token for the blocking `*_cancellable` entry points - * (kernel_session_open_cancellable, kernel_result_stream_next_batch_cancellable). - * Create one before a blocking call, pass it in, and fire it from ANOTHER - * thread (kernel_cancel_token_cancel) when the caller's deadline elapses; the - * blocked call then drops its in-flight request future and returns - * KernelStatusCode_Cancelled. One-shot (a fired token stays fired) — create a - * fresh token per logical operation. Firing is purely local (no RPC), so it - * never blocks. See "Cooperative cancellation" below. */ +/* Cooperative cancel token for the blocking `*_cancellable` entry points: + * kernel_session_open_cancellable, kernel_result_stream_next_batch_cancellable, + * and kernel_session_close_blocking_cancellable — i.e. the blocking calls a + * host issues on the connect / fetch / close lifecycle path. Create one before + * a blocking call, pass it in, and fire it from ANOTHER thread + * (kernel_cancel_token_cancel) when the caller's deadline elapses; the blocked + * call then stops waiting and returns KernelStatusCode_Cancelled. One-shot (a + * fired token stays fired) — create a fresh token per logical operation. Firing + * is purely local (no RPC), so it never blocks. See "Cooperative cancellation" + * below. + * + * NOT cancellable (by design, for now): the metadata entry points + * (kernel_metadata_*) have no `_cancellable` twin — they have no host consumer + * that needs a caller deadline yet, so the surface isn't added speculatively. A + * metadata call against a wedged warehouse is still bounded by the transport's + * request/overall timeouts. Twins can be added the same additive way (route + * run_metadata through block_on_ffi_cancellable) if a host adopts them. */ typedef struct kernel_cancel_token_t kernel_cancel_token_t; /* ─── Session config ────────────────────────────────────────────────── @@ -442,16 +451,35 @@ KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session KernelStatusCode kernel_session_close(kernel_session_t* session); /* - * Close a session and BLOCK until the server-side DeleteSession completes - * (or errors). Unlike kernel_session_close (fire-and-forget), a program - * that exits right after this returns has a confirmed server-side delete — - * the parity path for a host that wants close to behave like the - * synchronous DeleteSession RPC. CONSUMES `session` like + * Close a session and BLOCK until the server-side DeleteSession has been + * ATTEMPTED to completion. Unlike kernel_session_close (fire-and-forget), + * this waits for the delete round-trip — the parity path for a host that + * wants close to behave like the synchronous DeleteSession RPC. NOTE: + * Success means the delete was attempted, NOT server-confirmed — a transient + * failure after retries is logged and swallowed (matching the direct-Rust / + * pyo3 / napi Session::close), so a partitioned delete still returns Success + * (the server reclaims the session on idle-timeout). CONSUMES `session` like * kernel_session_close (released on success and failure alike); the same * "close the session LAST" teardown ordering applies. */ KernelStatusCode kernel_session_close_blocking(kernel_session_t* session); +/* + * Like kernel_session_close_blocking, but races the (blocking) DeleteSession + * against `cancel_token` so a host can bound a wedged / partitioned close by + * its own deadline instead of blocking up to the retry ceiling. A NULL + * `cancel_token` behaves EXACTLY like kernel_session_close_blocking. If the + * token fires (or is already fired), this returns KernelStatusCode_Cancelled. + * CONSUMES `session` on EVERY path — success, delete error, AND Cancelled: on + * cancel the session is released via a best-effort fire-and-forget delete + * (like kernel_session_close), so the caller must not use or free it after + * this returns regardless of the code. `cancel_token` is borrowed, not + * consumed: the caller still owns and must free it after this returns, and may + * fire it from another thread while this call is in flight. + */ +KernelStatusCode kernel_session_close_blocking_cancellable( + kernel_session_t* session, const kernel_cancel_token_t* cancel_token); + /* * Like kernel_session_open, but races the (blocking) connect against * `cancel_token` so a host can bound a slow warehouse cold-start or a diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index e59bbbab..dc06b7ac 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -23,7 +23,7 @@ //! v0.1 per `docs/spec-v0.md` addendum A5. use super::cancel::{kernel_cancel_token_t, token_ref}; -use super::{block_on_ffi, block_on_ffi_cancellable, KernelStatusCode}; +use super::{block_on_ffi_cancellable, KernelStatusCode}; use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; use crate::kernel_error::Error; use crate::session::Session; @@ -897,6 +897,52 @@ pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> #[no_mangle] pub unsafe extern "C" fn kernel_session_close_blocking( session: *mut kernel_session_t, +) -> KernelStatusCode { + session_close_blocking_inner(session, None) +} + +/// Blocking close, racing the (blocking) `DeleteSession` against `cancel_token` +/// so a host can bound a wedged / partitioned close by its own deadline instead +/// of blocking up to the retry ceiling. A **null** `cancel_token` behaves +/// exactly like [`kernel_session_close_blocking`]. If the token fires (or is +/// already fired) before the delete completes, this returns +/// [`KernelStatusCode::Cancelled`]. +/// +/// Consumes the handle on **every** path — success, delete error, AND +/// `Cancelled`. On cancel the awaited future (which owns the boxed session) is +/// dropped, so the session is released via its `Drop` (a best-effort +/// fire-and-forget delete, like [`kernel_session_close`]); the caller must not +/// use or free `session` afterwards regardless of the return code. +/// +/// The `cancel_token` is borrowed, not consumed: the caller still owns it and +/// must [`kernel_cancel_token_free`](crate::c_abi::cancel::kernel_cancel_token_free) +/// it after this returns. It is safe to fire the token from another thread while +/// this call is in flight (that is the intended use). +/// +/// # Safety +/// `session` carries the same contract as [`kernel_session_close_blocking`]. +/// `cancel_token`, if non-null, must be a live handle from +/// [`kernel_cancel_token_new`](crate::c_abi::cancel::kernel_cancel_token_new) +/// that is not freed until this call returns. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_close_blocking_cancellable( + session: *mut kernel_session_t, + cancel_token: *const kernel_cancel_token_t, +) -> KernelStatusCode { + session_close_blocking_inner(session, token_ref(cancel_token)) +} + +/// Shared body for [`kernel_session_close_blocking`] and +/// [`kernel_session_close_blocking_cancellable`]. Owns the "handle is consumed +/// on every path" contract in one place; `token` (None for the plain entry +/// point) is threaded into `Session::close`'s `block_on`. +/// +/// # Safety +/// See [`kernel_session_close_blocking`]. `token` must outlive the call when +/// `Some`. +unsafe fn session_close_blocking_inner( + session: *mut kernel_session_t, + token: Option<&CancellationToken>, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); if session.is_null() { @@ -909,11 +955,14 @@ pub unsafe extern "C" fn kernel_session_close_blocking( // Reclaim the box and await the delete on the process-wide runtime. // `Session::close(self)` consumes the session, so move the boxed value // into the future (mirroring `build_session`'s move of the config). - // On error the code is returned and the typed error is already stored - // by `block_on_ffi`; the session box is dropped either way, honouring - // the consume contract. + // On error the code is returned and the typed error is already stored; + // on a fired token the future is dropped, taking the boxed session with + // it (its `Drop` runs the fire-and-forget delete). Either way the box is + // released, honouring the consume-on-every-path contract. let session = Box::from_raw(session as *mut Session); - match block_on_ffi(move || Box::pin(async move { session.close().await })) { + match block_on_ffi_cancellable(token, move || { + Box::pin(async move { session.close().await }) + }) { Ok(()) => KernelStatusCode::Success, Err(code) => code, } diff --git a/tests/v0_c_abi_session_close_blocking_wiremock.rs b/tests/v0_c_abi_session_close_blocking_wiremock.rs index 7f4bbc00..e0469b34 100644 --- a/tests/v0_c_abi_session_close_blocking_wiremock.rs +++ b/tests/v0_c_abi_session_close_blocking_wiremock.rs @@ -26,9 +26,16 @@ //! a plain `#[test]` thread with a dedicated runtime only to host the mock. use std::ffi::CString; +use std::thread; +use std::time::{Duration, Instant}; +use databricks_sql_kernel::c_abi::cancel::{ + kernel_cancel_token_cancel, kernel_cancel_token_free, kernel_cancel_token_new, + kernel_cancel_token_t, +}; use databricks_sql_kernel::c_abi::session::{ - kernel_session_close_blocking, kernel_session_config_new, kernel_session_config_set_auth_pat, + kernel_session_close_blocking, kernel_session_close_blocking_cancellable, + kernel_session_config_new, kernel_session_config_set_auth_pat, kernel_session_config_set_http_path, kernel_session_open, kernel_session_t, KernelSessionConfig, }; @@ -118,3 +125,153 @@ fn session_close_blocking_null_handle_rejected() { ); } } + +/// F3: `kernel_session_close_blocking_cancellable` honours the caller's cancel +/// token — a token fired from another thread while the DELETE is stalled +/// server-side unblocks the close promptly with `Cancelled`, instead of +/// blocking up to the retry ceiling. The session handle is still consumed on +/// the cancel path (the dropped future releases the boxed session), so there is +/// no free/close afterwards. +#[test] +fn session_close_blocking_cancellable_fires_during_stalled_delete() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = + rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#"{"session_id":"sess-close-cancel","warehouse_id":"test_wh"}"#, + )) + .mount(&server) + .await; + // DELETE stalls 30s; the test fires cancel after ~200ms and must return + // long before that would elapse. + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-close-cancel")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(30))) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let host = CString::new(uri.as_str()).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + let auth = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_auth_pat(config, auth.as_ptr()), + KernelStatusCode::Success + ); + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); + // Fire the token from a watcher thread after a short beat. + let tok_addr = tok as usize; + let watcher = thread::spawn(move || { + thread::sleep(Duration::from_millis(200)); + let t = tok_addr as *mut kernel_cancel_token_t; + assert_eq!(kernel_cancel_token_cancel(t), KernelStatusCode::Success); + }); + + let start = Instant::now(); + let rc = kernel_session_close_blocking_cancellable(session, tok); + let elapsed = start.elapsed(); + watcher.join().unwrap(); + + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "a token fired during a stalled DELETE must unblock the close as Cancelled" + ); + assert!( + elapsed < Duration::from_secs(5), + "cancel must unblock the stalled close promptly, took {elapsed:?}" + ); + assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); + // No further close/free: the session was consumed on the cancel path. + } +} + +/// A NULL token makes `kernel_session_close_blocking_cancellable` behave exactly +/// like the plain `kernel_session_close_blocking`: it awaits the DELETE and +/// returns `Success`, with the DELETE observable immediately (no polling). +#[test] +fn session_close_blocking_cancellable_null_token_awaits_delete() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = + rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#"{"session_id":"sess-close-nulltok","warehouse_id":"test_wh"}"#, + )) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-close-nulltok")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let host = CString::new(uri.as_str()).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + let auth = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_auth_pat(config, auth.as_ptr()), + KernelStatusCode::Success + ); + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + + assert_eq!( + kernel_session_close_blocking_cancellable(session, std::ptr::null()), + KernelStatusCode::Success + ); + } + + let saw_delete = rt.block_on(async { + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .any(|r| r.method.as_str() == "DELETE" && r.url.path().ends_with("sess-close-nulltok")) + }); + assert!( + saw_delete, + "a NULL token must await the DELETE like the plain blocking close" + ); +} From 12919b3dba6101813e9a7b964fe4579facd52dc6 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Mon, 20 Jul 2026 13:47:05 +0000 Subject: [PATCH 14/15] refactor(c-abi): drop deferred surface, keep mTLS + ABI-version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Scope this PR down to the two low-risk, parity/safety symbols and defer the rest, per review (vikrantpuppala on #169): keep kernel_session_config_set_tls_client_certificate (mTLS — already implemented and wired in the crate; three sibling drivers already expose it) and kernel_abi_version() + DATABRICKS_KERNEL_ABI_VERSION (drift handshake). Remove — all purely additive, no merged consumer on any driver branch, so nothing shipped depends on them: - Cooperative cancel token + the *_cancellable entry points (kernel_cancel_token_new/_cancel/_is_cancelled/_free, kernel_session_open_cancellable, kernel_result_stream_next_batch_cancellable, kernel_session_close_blocking_cancellable) and block_on_ffi_cancellable. Gap 6/7 (PECOBLR-3645/3646) stay open; re-add when the Go driver actually honors ctx deadlines on connect/fetch. - kernel_session_close_blocking — no Go consumer; Go stays fire-and-forget. - kernel_session_config_set_cloudfetch_enabled — the server gates can_cloud_download (CONFIG_NOT_AVAILABLE / 42K0I); no working e2e path until SEA inline-Arrow (go/inline-arrow-sea) ships server-side. - kernel_set_log_callback / kernel_logging_stats / kernel_log_callback / KernelLogLevel — kernel_init_logging (stderr/file) already covers C-ABI hosts; the reverse-call sink is an ergonomics upgrade, not required. Deletes src/c_abi/cancel.rs, src/c_abi/logging.rs and the five dropped-surface test files; prunes tests/c/session_smoke.c and the header/changelog. No core kernel code touched. make check green (fmt + clippy + cargo test + C smoke). Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- NEXT_CHANGELOG.md | 30 - include/databricks_kernel.h | 194 ---- src/c_abi/cancel.rs | 245 ---- src/c_abi/logging.rs | 1031 ----------------- src/c_abi/mod.rs | 116 -- src/c_abi/result.rs | 59 +- src/c_abi/session.rs | 233 +--- tests/c/log_callback_smoke.c | 105 -- tests/c/session_smoke.c | 123 -- tests/v0_c_abi_cancel_token_wiremock.rs | 629 ---------- tests/v0_c_abi_cloudfetch_wiremock.rs | 113 -- tests/v0_c_abi_log_callback.rs | 353 ------ tests/v0_c_abi_log_callback_overflow.rs | 145 --- ...0_c_abi_session_close_blocking_wiremock.rs | 277 ----- 14 files changed, 12 insertions(+), 3641 deletions(-) delete mode 100644 src/c_abi/cancel.rs delete mode 100644 src/c_abi/logging.rs delete mode 100644 tests/c/log_callback_smoke.c delete mode 100644 tests/v0_c_abi_cancel_token_wiremock.rs delete mode 100644 tests/v0_c_abi_cloudfetch_wiremock.rs delete mode 100644 tests/v0_c_abi_log_callback.rs delete mode 100644 tests/v0_c_abi_log_callback_overflow.rs delete mode 100644 tests/v0_c_abi_session_close_blocking_wiremock.rs diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index acd16531..b459327b 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,45 +11,15 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added -- Cooperative cancel token for the blocking C-ABI entry points - (`kernel_cancel_token_new` / `_cancel` / `_is_cancelled` / `_free`), plus - cancellable variants `kernel_session_open_cancellable` and - `kernel_result_stream_next_batch_cancellable`. A host creates a token before a - blocking call, passes it in, and fires it from another thread when its - deadline elapses; the call drops its in-flight request future (a real - `reqwest` abort) and returns `Cancelled`. A null token is byte-for-byte the - plain path, so existing symbols and the default path are unchanged. Additive - only — ABI unchanged. - C ABI: `kernel_abi_version()` + the `DATABRICKS_KERNEL_ABI_VERSION` header macro — a consumer that links a prebuilt library can compare the two once at load time and refuse to run on a mismatch, guarding against a stale header/`.a` layout drift. Bumped in lockstep on any layout/meaning change. -- C ABI: `kernel_session_close_blocking()` — close a session and block until the - server-side `DeleteSession` completes (reusing `Session::close().await`), - instead of the fire-and-forget `kernel_session_close`, for a host that wants - close to behave like the synchronous `DeleteSession` RPC the direct-Rust and - pyo3/napi consumers get. Consumes the handle like the fire-and-forget sibling. - C ABI: `kernel_session_config_set_tls_client_certificate()` — expose the crate's existing mTLS client cert/key (`TlsConfig::client_cert_pem` / `client_key_pem`) over the C ABI as a single paired setter. Both halves required together (cert-without-key is unrepresentable); the private key is never logged. -- C ABI: `kernel_session_config_set_cloudfetch_enabled()` — toggle CloudFetch - (maps to `ResultConfig::cloudfetch_enabled`); `false` forces the inline-Arrow - path (`can_cloud_download=false`) for all result sizes. `None` (unset) keeps - the kernel default (on). -- C ABI: `kernel_set_log_callback(cb, ctx, level)` + the `kernel_log_callback` - typedef — a reverse-call log sink so a C-ABI host (ODBC / Go) that can't - install a Rust `tracing` subscriber still receives the kernel's - `databricks*`-targeted log events, routed into its own logger instead of only - reaching stderr via `kernel_init_logging`. Events are captured by a - process-global layer, filtered by `level` (explicit level > `RUST_LOG` > the - `warn` default — the same precedence as `kernel_init_logging`, so a host maps - one knob), enqueued on a bounded channel (drop-on-full — logs never - back-pressure a kernel hot path), and delivered from a dedicated drain thread. - Mutually exclusive with `kernel_init_logging` (one process-global subscriber; - the first to install wins, the other returns `Internal`); a NULL callback is - rejected with `InvalidArgument`. ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 224936e9..16f74fee 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -240,24 +240,6 @@ typedef struct kernel_result_stream_t kernel_result_stream_t; * cancels the LATER query. Use one per execute (new before execute, free after * it returns). */ typedef struct kernel_statement_canceller_t kernel_statement_canceller_t; -/* Cooperative cancel token for the blocking `*_cancellable` entry points: - * kernel_session_open_cancellable, kernel_result_stream_next_batch_cancellable, - * and kernel_session_close_blocking_cancellable — i.e. the blocking calls a - * host issues on the connect / fetch / close lifecycle path. Create one before - * a blocking call, pass it in, and fire it from ANOTHER thread - * (kernel_cancel_token_cancel) when the caller's deadline elapses; the blocked - * call then stops waiting and returns KernelStatusCode_Cancelled. One-shot (a - * fired token stays fired) — create a fresh token per logical operation. Firing - * is purely local (no RPC), so it never blocks. See "Cooperative cancellation" - * below. - * - * NOT cancellable (by design, for now): the metadata entry points - * (kernel_metadata_*) have no `_cancellable` twin — they have no host consumer - * that needs a caller deadline yet, so the surface isn't added speculatively. A - * metadata call against a wedged warehouse is still bounded by the transport's - * request/overall timeouts. Twins can be added the same additive way (route - * run_metadata through block_on_ffi_cancellable) if a host adopts them. */ -typedef struct kernel_cancel_token_t kernel_cancel_token_t; /* ─── Session config ────────────────────────────────────────────────── * @@ -318,77 +300,6 @@ KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* co * subscriber was already installed (no kernel subscriber installed). */ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); -/* ─── Log callback (reverse-call) ───────────────────────────────────── - * - * A host that links the kernel crate directly (pyo3 / napi) bridges the - * kernel's tracing output into its own logger in-process. A C-ABI consumer - * can't install a Rust subscriber, so this is the reverse-call path: register - * a callback the kernel invokes with each `databricks*`-targeted log event, so - * kernel-internal diagnostics flow into the host's logger instead of only - * reaching stderr via kernel_init_logging. - * - * The callback fires from the kernel's log-drain thread (NOT a query worker), - * so it MUST be thread-safe. It SHOULD NOT unwind: the kernel contains a panic - * with catch_unwind (the pointer uses Rust's C-unwind ABI) and poisons the sink - * rather than aborting, but subsequent logs are then dropped. It MUST NOT call - * back into any kernel_* entry point — a blocking reentrant call would stall the - * drain thread (that reentrancy guard only covers query workers). `ctx` is - * passed back verbatim and must stay valid for the process lifetime; `level` is - * a `KernelLogLevel` value (1=ERROR..5=TRACE); `target` and `message` are valid - * only for the call — copy them out. Records are enqueued on a bounded channel - * and DROPPED on overflow - * (logs never back-pressure a kernel hot path); the drop count is observable via - * kernel_logging_stats. - * - * The `level` PARAMETER (OFF/ERROR/WARN/INFO/DEBUG/TRACE, case-insensitive, or - * NULL) sets the forward threshold with the SAME precedence as - * kernel_init_logging: an explicit recognised level wins, else RUST_LOG (so a - * host maps its own logger level, e.g. Go's DATABRICKS_LOG_LEVEL). When neither - * resolves, the current threshold is left UNCHANGED — the warn default on the - * first call, or the previously-set level on a re-registration. - * - * Mutually exclusive with kernel_init_logging (both install the one - * process-global subscriber). The failure code says whether a retry helps - * (KernelError.retryable matches, so no message string-matching needed): - * Internal (retryable=false) if a subscriber was already installed — terminal, - * install exactly ONE; ResourceExhausted (retryable=true) if the drain thread - * could not start (EAGAIN/ENOMEM) — a later call retries. A NULL `cb` returns - * InvalidArgument (no detach in v0). */ - -/* - * Severity delivered to a `kernel_log_callback` as its `int level`. Values match - * the kernel's internal numeric severity (low = more severe). Prefer these - * symbols over hard-coded 1..5 so a future level insertion (with an ABI bump) - * surfaces as a build change rather than a silent host-side remap. `Off` (0) is - * never delivered to a callback — it only appears as a filter threshold meaning - * "emit nothing". - */ -typedef enum KernelLogLevel { - KernelLogLevel_Off = 0, - KernelLogLevel_Error = 1, - KernelLogLevel_Warn = 2, - KernelLogLevel_Info = 3, - KernelLogLevel_Debug = 4, - KernelLogLevel_Trace = 5, -} KernelLogLevel; - -typedef void (*kernel_log_callback)(void* ctx, int level, const char* target, - const char* message); -KernelStatusCode kernel_set_log_callback(kernel_log_callback cb, void* ctx, - const char* level); - -/* Report the log-callback bridge's health, so a host can distinguish "kernel - * logs are quiet" from "being dropped / sink died / never installed". Writes - * each non-NULL out-param (a NULL one is skipped): - * - `installed`: true iff kernel logs are CURRENTLY delivering — the callback - * won the subscriber AND the sink is not poisoned. A callback that unwinds - * poisons the sink (reads false); registering a new callback clears it. - * - `dropped`: cumulative records dropped AFTER install (channel full or sink - * poisoned). Excludes the spawn-failure case (no channel), where `installed` - * reads false and kernel_set_log_callback returned Internal. - * Never fails; safe to poll at any time. */ -void kernel_logging_stats(bool* installed, uint64_t* dropped); - /* ─── Proxy / TLS (optional) ────────────────────────────────────────── * * All optional; defaults are: no explicit proxy (reqwest honours @@ -432,14 +343,6 @@ KernelStatusCode kernel_session_config_set_tls_client_certificate(KernelSessionC const uint8_t* key_pem, size_t key_len); -/* Enable or disable CloudFetch (cloud-storage-backed download of large result - * sets). Default enabled; `false` forces the inline-Arrow path for all result - * sizes (mirrors JDBC EnableQueryResultDownload=0). The kernel sets the - * `can_cloud_download` session conf internally — do NOT set that conf directly - * via set_session_conf (the server rejects it as not user-settable). */ -KernelStatusCode kernel_session_config_set_cloudfetch_enabled(KernelSessionConfig* config, - bool enabled); - /* ─── Session lifecycle ───────────────────────────────────────────────*/ /* @@ -450,51 +353,6 @@ KernelStatusCode kernel_session_config_set_cloudfetch_enabled(KernelSessionConfi KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session_t** out); KernelStatusCode kernel_session_close(kernel_session_t* session); -/* - * Close a session and BLOCK until the server-side DeleteSession has been - * ATTEMPTED to completion. Unlike kernel_session_close (fire-and-forget), - * this waits for the delete round-trip — the parity path for a host that - * wants close to behave like the synchronous DeleteSession RPC. NOTE: - * Success means the delete was attempted, NOT server-confirmed — a transient - * failure after retries is logged and swallowed (matching the direct-Rust / - * pyo3 / napi Session::close), so a partitioned delete still returns Success - * (the server reclaims the session on idle-timeout). CONSUMES `session` like - * kernel_session_close (released on success and failure alike); the same - * "close the session LAST" teardown ordering applies. - */ -KernelStatusCode kernel_session_close_blocking(kernel_session_t* session); - -/* - * Like kernel_session_close_blocking, but races the (blocking) DeleteSession - * against `cancel_token` so a host can bound a wedged / partitioned close by - * its own deadline instead of blocking up to the retry ceiling. A NULL - * `cancel_token` behaves EXACTLY like kernel_session_close_blocking. If the - * token fires (or is already fired), this returns KernelStatusCode_Cancelled. - * CONSUMES `session` on EVERY path — success, delete error, AND Cancelled: on - * cancel the session is released via a best-effort fire-and-forget delete - * (like kernel_session_close), so the caller must not use or free it after - * this returns regardless of the code. `cancel_token` is borrowed, not - * consumed: the caller still owns and must free it after this returns, and may - * fire it from another thread while this call is in flight. - */ -KernelStatusCode kernel_session_close_blocking_cancellable( - kernel_session_t* session, const kernel_cancel_token_t* cancel_token); - -/* - * Like kernel_session_open, but races the (blocking) connect against - * `cancel_token` so a host can bound a slow warehouse cold-start or a - * connect-time network partition by its own deadline. A NULL `cancel_token` - * behaves EXACTLY like kernel_session_open. If the token fires (or is already - * fired) before connect completes, the connect future is dropped — aborting - * the in-flight request — and this returns KernelStatusCode_Cancelled; `config` - * is CONSUMED on every path regardless. `cancel_token` is borrowed, not - * consumed: the caller still owns and must free it after this returns, and may - * fire it from another thread while this call is in flight. - */ -KernelStatusCode kernel_session_open_cancellable(KernelSessionConfig* config, - kernel_session_t** out, - const kernel_cancel_token_t* cancel_token); - /* Report whether a session is still OPEN (its delete has not been * initiated). Writes true/false to `*out`. LOCAL check only — no server * round-trip, so it does NOT detect a server idle-timeout or dropped @@ -658,32 +516,6 @@ KernelStatusCode kernel_statement_canceller_cancel( KernelStatusCode kernel_statement_canceller_free( kernel_statement_canceller_t* canceller); -/* ─── Cooperative cancellation (blocking-call cancel token) ──────────── - * - * The statement canceller above cancels a server-side STATEMENT (right for a - * query still executing). A cancel token cancels a blocking C-ABI CALL itself — - * connect or a stalled result-stream fetch — neither of which the statement - * canceller reaches (the server statement is already done; the stall is - * client-side). It is the generic mechanism a host uses to honour a caller - * deadline / context on the `*_cancellable` entry points. - * - * Usage: create a token, spawn a watcher on the caller's deadline/context, make - * the blocking `*_cancellable` call on the owning thread, and from the watcher - * fire kernel_cancel_token_cancel when the deadline elapses. The blocked call - * drops its in-flight request future and returns KernelStatusCode_Cancelled. - * Firing is purely local (flip an atomic, wake the waiter) — no RPC, never - * blocks. The token is ONE-SHOT (a fired token stays fired), so create a fresh - * one per logical operation. Safe to fire from a different thread than the - * blocking call (that is the intended use); do NOT free the token until both - * the blocking call and any in-flight cancel have returned. - */ -KernelStatusCode kernel_cancel_token_new(kernel_cancel_token_t** out); -KernelStatusCode kernel_cancel_token_cancel(kernel_cancel_token_t* token); -/* Report whether the token has been fired (writes true/false to *out). Local - * atomic read — no RPC, never blocks. Symmetric with kernel_session_is_open. */ -KernelStatusCode kernel_cancel_token_is_cancelled(const kernel_cancel_token_t* token, bool* out); -KernelStatusCode kernel_cancel_token_free(kernel_cancel_token_t* token); - /* ─── Executed statement (sync) ───────────────────────────────────────*/ /* @@ -731,32 +563,6 @@ KernelStatusCode kernel_result_stream_get_schema(kernel_result_stream_t* stream, KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, struct ArrowArray* out_array, struct ArrowSchema* out_schema); -/* - * Like kernel_result_stream_next_batch, but races the (blocking) wait for the - * next batch against `cancel_token` so a host can stop waiting on a HUNG - * CloudFetch chunk (a wedged S3 / pre-signed-URL GET) instead of blocking on it - * forever. A NULL `cancel_token` behaves EXACTLY like - * kernel_result_stream_next_batch. If the token fires before the batch is ready, - * this call unblocks promptly and returns KernelStatusCode_Cancelled; the stream - * handle stays valid and owned by the caller (close it with - * kernel_result_stream_close as usual — a cancelled fetch neither consumes nor - * frees it). - * - * NOTE ON SCOPE: cancel here interrupts the CALLER'S WAIT, not the background - * download. The CloudFetch chunk GET runs on a detached kernel task; firing the - * token drops only this call's waiter, so the return is prompt but the in-flight - * download continues to completion or its own read-timeout (~60s) before its - * in-memory slot is released. Closing the stream after a cancel triggers the - * provider's own teardown, but does not abort a GET already on the wire either. - * (The connect-side kernel_session_open_cancellable DOES abort its in-flight - * request, because create-session runs inline in the raced future.) - * - * `cancel_token` is borrowed and safe to fire from another thread while this - * call is in flight (see kernel_session_open_cancellable). - */ -KernelStatusCode kernel_result_stream_next_batch_cancellable( - kernel_result_stream_t* stream, struct ArrowArray* out_array, - struct ArrowSchema* out_schema, const kernel_cancel_token_t* cancel_token); KernelStatusCode kernel_result_stream_close(kernel_result_stream_t* stream); /* ─── Metadata ──────────────────────────────────────────────────────── diff --git a/src/c_abi/cancel.rs b/src/c_abi/cancel.rs deleted file mode 100644 index 83f1f28a..00000000 --- a/src/c_abi/cancel.rs +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) 2026 Databricks, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Generic cooperative cancel token for the blocking C-ABI entry points. -//! -//! The v0 C ABI drives every async operation through -//! [`block_on_ffi`](crate::c_abi::block_on_ffi), which blocks the calling -//! (native) thread until the future completes. That thread cannot observe a -//! host-side deadline/cancel (a Go `context.Context`, an ODBC `SQLCancel`) -//! mid-call, so a hung connect or a hung result-stream fetch blocks the caller -//! past its deadline — the runtime-contract gap the host drivers track as -//! mid-fetch (hung CloudFetch chunk) and session-connect deadlines. -//! -//! This module adds one primitive that closes both: a [`kernel_cancel_token_t`] -//! the host creates before a blocking call, passes into a `*_cancellable` -//! variant of that call, and fires from *another* thread when its deadline -//! elapses. The cancellable entry point runs its future under -//! [`block_on_ffi_cancellable`](crate::c_abi::block_on_ffi_cancellable), which -//! races the future against the token and — on a fire — **drops the future**. -//! Because the kernel's HTTP client is `reqwest` and its futures cancel by -//! being dropped (the crate-wide model; see the CloudFetch streaming provider's -//! own [`CancellationToken`] use), dropping the future genuinely aborts the -//! in-flight request rather than merely stopping the wait. -//! -//! The token wraps [`tokio_util::sync::CancellationToken`], which is cheap to -//! clone (an `Arc` internally) and safe to fire from any thread — the same -//! shape as the statement canceller ([`kernel_statement_canceller_t`]), and for -//! the same reason (the blocking call runs on one thread, the cancel on -//! another). Unlike the statement canceller, firing is purely local (flip an -//! atomic + wake waiters); it dispatches no RPC, so it never blocks. -//! -//! One token drives at most one in-flight call at a time. Reuse across -//! sequential calls is allowed, but a token that has already been fired stays -//! fired (a `CancellationToken` is one-shot), so create a fresh token per -//! logical operation — exactly as a Go caller creates a fresh watcher per -//! `ctx`. -//! -//! [`kernel_statement_canceller_t`]: crate::c_abi::statement::kernel_statement_canceller_t -//! [`CancellationToken`]: tokio_util::sync::CancellationToken - -#![allow(non_camel_case_types)] - -use super::error::store_invalid_arg; -use super::{catch_ffi, KernelStatusCode}; -use tokio_util::sync::CancellationToken; - -/// Opaque cancel-token handle. Boxes a [`CancellationToken`] the host fires -/// from a watcher thread to interrupt a blocking `*_cancellable` C-ABI call. -#[repr(C)] -pub struct kernel_cancel_token_t { - _private: [u8; 0], -} - -/// Owned box behind a [`kernel_cancel_token_t`]. -struct CancelTokenHandle { - token: CancellationToken, -} - -/// Crate-internal: borrow the [`CancellationToken`] out of a raw handle, or -/// `None` when the handle pointer is null. The returned reference is only used -/// to `clone()` the token (a cheap `Arc` bump) into the future's `select!`, so -/// the caller keeps ownership of the box and may still fire it concurrently. -/// -/// # Safety -/// `token` must be null or a live handle from [`kernel_cancel_token_new`]. -pub(crate) unsafe fn token_ref<'a>( - token: *const kernel_cancel_token_t, -) -> Option<&'a CancellationToken> { - (token as *const CancelTokenHandle) - .as_ref() - .map(|h| &h.token) -} - -/// Create a fresh, un-fired cancel token. On success `*out` holds an owned -/// handle the caller releases with [`kernel_cancel_token_free`], and may fire -/// with [`kernel_cancel_token_cancel`] from any thread. -/// -/// # Safety -/// `out` must be a valid, writable pointer to a `kernel_cancel_token_t*`. -#[no_mangle] -pub unsafe extern "C" fn kernel_cancel_token_new( - out: *mut *mut kernel_cancel_token_t, -) -> KernelStatusCode { - catch_ffi(|| { - if out.is_null() { - return store_invalid_arg("kernel_cancel_token_new: out must not be null"); - } - let handle = CancelTokenHandle { - token: CancellationToken::new(), - }; - std::ptr::write( - out, - Box::into_raw(Box::new(handle)) as *mut kernel_cancel_token_t, - ); - KernelStatusCode::Success - }) -} - -/// Fire the token, requesting cancellation of whatever blocking -/// `*_cancellable` call it was passed to. Idempotent (a `CancellationToken` is -/// one-shot; a second fire is a no-op) and safe to call concurrently with the -/// blocking call the token drives — that is the whole point: the blocking call -/// runs on one thread and this fires from another. -/// -/// Purely local: flips the token's atomic and wakes the `select!` waiting on -/// it. Dispatches no RPC, so it never blocks and never fails on a live handle. -/// -/// # Safety -/// `token` must be a live handle from [`kernel_cancel_token_new`], not yet -/// freed. It is safe to call while a `*_cancellable` call driven by this token -/// is in flight; do not [`kernel_cancel_token_free`] the handle until both this -/// call and that blocking call have returned. -#[no_mangle] -pub unsafe extern "C" fn kernel_cancel_token_cancel( - token: *mut kernel_cancel_token_t, -) -> KernelStatusCode { - catch_ffi(|| { - let Some(handle) = (token as *const CancelTokenHandle).as_ref() else { - return store_invalid_arg("kernel_cancel_token_cancel: token must not be null"); - }; - handle.token.cancel(); - KernelStatusCode::Success - }) -} - -/// Report whether the token has been fired, writing `true`/`false` to `*out`. -/// A local read of the token's atomic — no RPC, never blocks. Symmetric with -/// [`kernel_session_is_open`](crate::c_abi::session::kernel_session_is_open); -/// lets a host (or its tests) observe the token state it set. Does not borrow -/// ownership; the caller still owns `token`. -/// -/// # Safety -/// `token` must be a live handle from [`kernel_cancel_token_new`], not yet -/// freed; `out` must be a writable `bool*`. -#[no_mangle] -pub unsafe extern "C" fn kernel_cancel_token_is_cancelled( - token: *const kernel_cancel_token_t, - out: *mut bool, -) -> KernelStatusCode { - catch_ffi(|| { - let Some(handle) = (token as *const CancelTokenHandle).as_ref() else { - return store_invalid_arg("kernel_cancel_token_is_cancelled: token must not be null"); - }; - if out.is_null() { - return store_invalid_arg("kernel_cancel_token_is_cancelled: out must not be null"); - } - std::ptr::write(out, handle.token.is_cancelled()); - KernelStatusCode::Success - }) -} - -/// Free a cancel-token handle. Does not touch any call the token drove. -/// -/// # Safety -/// `token` must have been returned by [`kernel_cancel_token_new`] and not -/// previously freed. The token is single-owner for teardown: no other thread -/// may be inside [`kernel_cancel_token_cancel`] on this handle, and no -/// `*_cancellable` call driven by it may be in flight, when it is freed. -#[no_mangle] -pub unsafe extern "C" fn kernel_cancel_token_free( - token: *mut kernel_cancel_token_t, -) -> KernelStatusCode { - catch_ffi(|| { - if token.is_null() { - return store_invalid_arg("kernel_cancel_token_free: token must not be null"); - } - drop(Box::from_raw(token as *mut CancelTokenHandle)); - KernelStatusCode::Success - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// new → cancel → free round-trips, and the borrowed token reflects the - /// fire (the property the cancellable entry points rely on). - #[test] - fn new_cancel_free_round_trip() { - let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); - let rc = unsafe { kernel_cancel_token_new(&mut tok) }; - assert_eq!(rc, KernelStatusCode::Success); - assert!(!tok.is_null()); - - // Not fired yet — observe via both the borrow and the C accessor. - let borrowed = unsafe { token_ref(tok) }.expect("live token"); - assert!(!borrowed.is_cancelled()); - let mut fired = true; - assert_eq!( - unsafe { kernel_cancel_token_is_cancelled(tok, &mut fired) }, - KernelStatusCode::Success - ); - assert!(!fired, "is_cancelled reports false before a fire"); - - // Fire it, then observe the flip through the borrow AND the accessor. - let rc = unsafe { kernel_cancel_token_cancel(tok) }; - assert_eq!(rc, KernelStatusCode::Success); - assert!(borrowed.is_cancelled(), "cancel() must flip the token"); - assert_eq!( - unsafe { kernel_cancel_token_is_cancelled(tok, &mut fired) }, - KernelStatusCode::Success - ); - assert!(fired, "is_cancelled reports true after a fire"); - - // Second fire is a no-op (one-shot), still Success. - let rc = unsafe { kernel_cancel_token_cancel(tok) }; - assert_eq!(rc, KernelStatusCode::Success); - - let rc = unsafe { kernel_cancel_token_free(tok) }; - assert_eq!(rc, KernelStatusCode::Success); - } - - /// Null-pointer guards on every entry point return `InvalidArgument`, - /// never crash. - #[test] - fn null_guards_return_invalid_argument() { - let rc = unsafe { kernel_cancel_token_new(std::ptr::null_mut()) }; - assert_eq!(rc, KernelStatusCode::InvalidArgument); - let rc = unsafe { kernel_cancel_token_cancel(std::ptr::null_mut()) }; - assert_eq!(rc, KernelStatusCode::InvalidArgument); - let mut fired = false; - let rc = unsafe { kernel_cancel_token_is_cancelled(std::ptr::null(), &mut fired) }; - assert_eq!(rc, KernelStatusCode::InvalidArgument); - let rc = unsafe { kernel_cancel_token_free(std::ptr::null_mut()) }; - assert_eq!(rc, KernelStatusCode::InvalidArgument); - } - - /// `token_ref` on a null handle yields `None` (used by the cancellable - /// entry points to treat a null token as "no cancellation"). - #[test] - fn token_ref_null_is_none() { - assert!(unsafe { token_ref(std::ptr::null()) }.is_none()); - } -} diff --git a/src/c_abi/logging.rs b/src/c_abi/logging.rs deleted file mode 100644 index 43e16acd..00000000 --- a/src/c_abi/logging.rs +++ /dev/null @@ -1,1031 +0,0 @@ -// Copyright (c) 2026 Databricks, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! `tracing` → C-callback log bridge for C-ABI (ODBC / Go) consumers. -//! -//! The pyo3 and napi bindings forward the kernel's `tracing` output into the -//! host language's logger **in-process** (they link the kernel crate directly, -//! so they can install a `tracing` `Subscriber` / `log` sink in the kernel's -//! address space — see `napi/src/logger.rs`, `pyo3/src/logging.rs`). A C-ABI -//! consumer can't do that: it reaches the kernel only across the C boundary, -//! and its only kernel-log path today is `kernel_init_logging`'s -//! `RUST_LOG` → stderr subscriber. This module adds the missing reverse-call -//! path: a host registers a C callback (`kernel_set_log_callback`) that the -//! kernel invokes with each `databricks*`-targeted event. -//! -//! ## Shape (mirrors the napi bridge) -//! -//! - [`kernel_set_log_callback`] installs a process-global [`KernelLogLayer`] -//! (once) and records the `(callback, ctx)` sink. The layer captures -//! `databricks*` events, filters by a single level (an explicit one-knob -//! level, else the most-verbose kernel-applicable `RUST_LOG` level), formats -//! each into a [`Record`], and pushes it onto a **bounded** channel -//! (drop-on-full — logs are advisory and must never block or back-pressure a -//! kernel hot path). -//! - A dedicated drain thread pulls records and invokes the C callback once per -//! record with borrowed C strings (valid only for the call). -//! -//! ## Threading & safety contract (full version in `databricks_kernel.h`) -//! -//! The callback fires from the drain thread (never a kernel tokio worker), so -//! it must be thread-safe and must not call back into any `kernel_*` entry -//! point (the reentrancy guard only covers tokio workers, so a blocking -//! `kernel_*` call here would stall the drain thread). An unwinding callback is -//! contained by `catch_unwind` and poisons the sink rather than aborting the -//! process, but a well-behaved callback still must not unwind, since poisoning -//! stops delivery. -//! -//! ## Mutual exclusion with `kernel_init_logging` -//! -//! Both install the one process-global `tracing` subscriber; the first -//! `set_global_default` wins and the loser returns `Internal`, so a C consumer -//! picks one. The sink itself is last-writer-wins, refreshed on every call. - -// The callback type mirrors the C typedef name `kernel_log_callback` (snake -// case) so the Rust and header names read identically, matching the rest of the -// C-ABI surface (`kernel_*_t` handles). -#![allow(non_camel_case_types)] - -use super::KernelStatusCode; -use crate::kernel_error::{Error, ErrorCode}; -use std::ffi::{c_void, CString}; -use std::os::raw::{c_char, c_int}; -use std::panic::{catch_unwind, AssertUnwindSafe}; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; -use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; -use std::sync::{Mutex, OnceLock}; -use tracing::field::{Field, Visit}; -use tracing::level_filters::LevelFilter; -use tracing::subscriber::Interest; -use tracing::{Event, Level, Metadata, Subscriber}; -use tracing_subscriber::layer::{Context, Filter, Layer, SubscriberExt}; -use tracing_subscriber::registry::LookupSpan; - -/// Host log sink: a C function pointer plus an opaque host context passed back -/// verbatim on every call. `level` is a `KernelLogLevel` value (1=ERROR..5=TRACE; -/// see the `LEVEL_*` constants and the header enum); `target` and `message` are -/// NUL-terminated C strings valid only for the duration of the call. -/// -/// The ABI is `C-unwind` so a panicking host callback propagates across the -/// boundary and `invoke_callback`'s `catch_unwind` can contain it; a plain -/// `extern "C"` fn would instead abort the process. The C representation is -/// unchanged, and non-unwinding callbacks are unaffected. -pub type kernel_log_callback = extern "C-unwind" fn( - ctx: *mut c_void, - level: c_int, - target: *const c_char, - message: *const c_char, -); - -/// A drained log record awaiting delivery to the host callback. -struct Record { - level: c_int, - /// `&'static str`: `tracing` metadata targets are static, so this avoids a - /// per-record heap allocation on chatty DEBUG/TRACE workloads (the message, - /// built by the field visitor, still owns its `String`). - target: &'static str, - message: String, -} - -/// The registered sink. `ctx` is stored as a `usize` so the struct is `Send` -/// (the host owns the pointer and guarantees its validity until it detaches); -/// the kernel treats it as opaque and never dereferences it. -struct Sink { - cb: kernel_log_callback, - ctx: usize, - /// Monotonic registration id. The drain thread poisons the sink on an unwind - /// only if this id is still installed, so an old callback that unwinds after - /// a re-registration can't kill the replacement. - gen: u64, -} - -const CHANNEL_CAPACITY: usize = 4096; - -// Numeric severity delivered to the host callback and used as the forward -// threshold (low = more severe; `0` = off / emit nothing). These are the Rust -// side of the header's `KernelLogLevel` enum and MUST stay in lockstep with it -// (`KernelLogLevel_Off`..`KernelLogLevel_Trace`); `pub` so a consumer of the -// crate (and the C-ABI documentation) can reference them by name rather than -// hard-coding 1..5. -pub const LEVEL_OFF: u8 = 0; -pub const LEVEL_ERROR: u8 = 1; -pub const LEVEL_WARN: u8 = 2; -pub const LEVEL_INFO: u8 = 3; -pub const LEVEL_DEBUG: u8 = 4; -pub const LEVEL_TRACE: u8 = 5; - -/// Forward threshold for all kernel events: the explicit one-knob level, the -/// most-verbose kernel-applicable `RUST_LOG` level, or the static `warn` -/// default. Numeric severity, low = more severe; `0` means "off / emit nothing". -static LEVEL: AtomicU8 = AtomicU8::new(LEVEL_WARN); - -/// Count of log records dropped because the bounded channel was full or the -/// sink was poisoned. Surfaced via [`kernel_logging_stats`] so the loss is -/// observable, not silent. -static DROPPED: AtomicU64 = AtomicU64::new(0); - -/// Set if the host callback ever unwound across the FFI boundary. A callback -/// that panics once is assumed to keep panicking, so the drain thread stops -/// delivering rather than re-invoke it. Surfaced via [`kernel_logging_stats`] -/// (`installed` reads `false` while poisoned), and cleared when a new callback -/// is registered so a host can recover by re-installing. -static SINK_POISONED: AtomicBool = AtomicBool::new(false); - -const INSTALL_PENDING: u8 = 0; -const INSTALL_OK: u8 = 1; -/// Lost the one-global-subscriber race (e.g. `kernel_init_logging` won) — a -/// benign outcome; the host picks one of the two logging routes. -const INSTALL_ALREADY_SET: u8 = 2; -/// The OS refused to start the drain thread (EAGAIN/ENOMEM) before the -/// subscriber was claimed. Non-terminal: a later `kernel_set_log_callback` -/// retries, so a transient spawn failure isn't permanent. -const INSTALL_SPAWN_FAILED: u8 = 3; - -/// Outcome of the subscriber install. `INSTALL_OK` and `INSTALL_ALREADY_SET` are -/// terminal (no further attempt); `INSTALL_PENDING` and `INSTALL_SPAWN_FAILED` -/// are retryable. Anything other than `INSTALL_OK` means kernel logs won't reach -/// the callback; the two failure discriminants let the caller tell the benign -/// already-installed case from a (retryable) spawn failure. -static INSTALL_STATUS: AtomicU8 = AtomicU8::new(INSTALL_PENDING); - -/// The drain-thread spawn error string, populated only on `INSTALL_SPAWN_FAILED` -/// so the returned `Internal` can carry the underlying OS error for triage. -static SPAWN_ERROR: OnceLock>> = OnceLock::new(); - -/// Current sink. Last-writer-wins; read by the drain thread per record. -static SINK: OnceLock>> = OnceLock::new(); - -/// Source of monotonic sink registration ids ([`Sink::gen`]). Bumped under the -/// `SINK` lock on every (re-)registration so the drain thread can tell whether -/// the callback it just invoked is still the installed one. -static NEXT_SINK_GEN: AtomicU64 = AtomicU64::new(0); - -/// Serializes install attempts (subscriber + channel + drain-thread spawn). A -/// plain lock rather than a `Once` so a transient spawn failure stays retryable -/// via [`INSTALL_STATUS`]; `set_global_default` is still attempted at most once. -static INSTALL_LOCK: Mutex<()> = Mutex::new(()); - -fn severity(level: &Level) -> u8 { - match *level { - Level::ERROR => LEVEL_ERROR, - Level::WARN => LEVEL_WARN, - Level::INFO => LEVEL_INFO, - Level::DEBUG => LEVEL_DEBUG, - Level::TRACE => LEVEL_TRACE, - } -} - -/// Parse a bare level word into the numeric severity, unknown → `None`. -fn parse_level_word(s: &str) -> Option { - match s.trim().to_ascii_lowercase().as_str() { - "off" | "none" | "silent" => Some(LEVEL_OFF), - "error" => Some(LEVEL_ERROR), - "warn" | "warning" => Some(LEVEL_WARN), - "info" => Some(LEVEL_INFO), - "debug" => Some(LEVEL_DEBUG), - "trace" => Some(LEVEL_TRACE), - _ => None, - } -} - -/// Resolve a `RUST_LOG`-style string to the single most-verbose level that -/// applies to kernel events, or `None` if nothing kernel-applicable is present. -/// -/// The callback carries one level, so directives are collapsed by taking the -/// max (most verbose) across the bare global level and every kernel-applicable -/// target directive ([`directive_targets_kernel`]). A directive with no `=` is -/// a bare level (the global) or a bare kernel target (TRACE, as `EnvFilter` -/// reads it). Foreign directives (`hyper=warn`) and non-matching `databricks` -/// siblings are ignored. This can forward a superset of what the stderr path's -/// per-target `EnvFilter` would — acceptable for advisory logging, and a host -/// wanting exact per-target control uses `kernel_init_logging` instead. -fn parse_rust_log(rust_log: &str) -> Option { - let mut level: Option = None; - let mut bump = |l: u8| level = Some(level.map_or(l, |cur| cur.max(l))); - for directive in rust_log.split(',') { - let d = directive.trim(); - if d.is_empty() { - continue; - } - match d.split_once('=') { - Some((target, lvl)) => { - if directive_targets_kernel(target.trim()) { - if let Some(l) = parse_level_word(lvl) { - bump(l); - } - } - } - None => { - if let Some(l) = parse_level_word(d) { - bump(l); - } else if directive_targets_kernel(d) { - bump(LEVEL_TRACE); - } - } - } - } - level -} - -/// The crate's module-path root: the `#[instrument]` / default-target namespace -/// (`databricks_sql_kernel::*`) the bridge also forwards (see `is_kernel_target`). -const KERNEL_MODULE_ROOT: &str = "databricks_sql_kernel"; - -/// The kernel's canonical `tracing` target roots: the `klog!` target -/// ([`KERNEL_LOG_TARGET`](crate::klog::KERNEL_LOG_TARGET), -/// `databricks::sql::kernel`) and the crate's module-path root -/// ([`KERNEL_MODULE_ROOT`]). -const KERNEL_TARGET_ROOTS: [&str; 2] = [crate::klog::KERNEL_LOG_TARGET, KERNEL_MODULE_ROOT]; - -/// Whether a `RUST_LOG` directive target selects any event the bridge forwards, -/// under `EnvFilter`'s prefix match. True when the target is a prefix of a -/// canonical root (`databricks`, `databricks::sql`, `databricks_sql_kernel`, …) -/// or a `::`-boundary submodule of the module-path root -/// (`databricks_sql_kernel::session`). Uses the same segment-boundary helper as -/// [`is_kernel_target`], so a module-root sibling (`databricks_sql_kernel_ext`), -/// a non-root sibling (`databricksfoo`), and an over-specific extension of the -/// fixed-depth `klog!` target (`databricks::sql::kernel::foo`) are all rejected. -fn directive_targets_kernel(target: &str) -> bool { - is_target_or_submodule(target, KERNEL_MODULE_ROOT) - || KERNEL_TARGET_ROOTS - .iter() - .any(|root| root.starts_with(target)) -} - -/// Returns whether an event at `level` should currently be forwarded, against -/// the single configured [`LEVEL`] threshold. -fn should_emit(level: &Level) -> bool { - let threshold = LEVEL.load(Ordering::Relaxed); - threshold != LEVEL_OFF && severity(level) <= threshold -} - -/// Whether `target` is exactly `root` or a `::`-delimited submodule of it — a -/// segment-boundary match, so a sibling like `databricks_sql_kernel_ext` does -/// not match `databricks_sql_kernel`. -fn is_target_or_submodule(target: &str, root: &str) -> bool { - target - .strip_prefix(root) - .is_some_and(|rest| rest.is_empty() || rest.starts_with("::")) -} - -/// Targets the bridge forwards: the `klog!` shim's `databricks::sql::kernel` -/// and the crate's module paths (`databricks_sql_kernel`), plus any submodule -/// of either. A segment-boundary match, so an unrelated `databricks`-prefixed -/// target from another crate is not routed into the kernel callback. -fn is_kernel_target(target: &str) -> bool { - is_target_or_submodule(target, crate::klog::KERNEL_LOG_TARGET) - || is_target_or_submodule(target, KERNEL_MODULE_ROOT) -} - -/// The configured [`LEVEL`] as a `tracing` [`LevelFilter`], for `max_level_hint` -/// so the process-global gate tracks the kernel level rather than pinning at -/// TRACE. -fn current_level_filter() -> LevelFilter { - match LEVEL.load(Ordering::Relaxed) { - LEVEL_OFF => LevelFilter::OFF, - LEVEL_ERROR => LevelFilter::ERROR, - LEVEL_WARN => LevelFilter::WARN, - LEVEL_INFO => LevelFilter::INFO, - LEVEL_DEBUG => LevelFilter::DEBUG, - _ => LevelFilter::TRACE, - } -} - -/// Per-callsite interest. Kernel EVENT callsites re-evaluate per event -/// (`sometimes`, for the dynamic level); everything else caches off (`never`). -/// The bridge is event-only, so span callsites cache off even on kernel targets -/// — the kernel's own `databricks*` spans then pay no span machinery for output -/// this layer never produces. -fn callsite_interest_for(target: &str, is_event: bool) -> Interest { - if is_event && is_kernel_target(target) { - Interest::sometimes() - } else { - Interest::never() - } -} - -/// Collects a `tracing` event's `message` plus structured fields into one line: -/// `" key1=v1 key2=v2"`. -#[derive(Default)] -struct MessageVisitor { - message: String, - fields: String, -} - -impl MessageVisitor { - fn finish(self) -> String { - if self.fields.is_empty() { - self.message - } else if self.message.is_empty() { - self.fields - } else { - format!("{} {}", self.message, self.fields) - } - } - - fn push_field(&mut self, name: &str, value: String) { - if !self.fields.is_empty() { - self.fields.push(' '); - } - self.fields.push_str(name); - self.fields.push('='); - self.fields.push_str(&value); - } -} - -impl Visit for MessageVisitor { - fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { - if field.name() == "message" { - self.message = format!("{value:?}"); - } else { - self.push_field(field.name(), format!("{value:?}")); - } - } - - fn record_str(&mut self, field: &Field, value: &str) { - if field.name() == "message" { - self.message = value.to_owned(); - } else { - self.push_field(field.name(), value.to_owned()); - } - } -} - -/// Process-global `tracing` Layer: formats each kernel event and enqueues it -/// (drop-on-full). The per-layer [`KernelFilter`] already excludes foreign -/// targets and below-level events. -/// -/// The channel sender lives in the layer instance, so `set_global_default` -/// publishes the subscriber and its sender atomically — -/// [`on_event`](KernelLogLayer::on_event) never sees an installed-but-senderless -/// state that would drop a concurrent log uncounted. -struct KernelLogLayer { - tx: SyncSender, -} - -/// Per-layer filter gating the bridge: foreign callsites cache off, kernel -/// callsites re-evaluate per event, and `max_level_hint` tracks the level. -struct KernelFilter; - -impl Filter for KernelFilter { - fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest { - callsite_interest_for(meta.target(), meta.is_event()) - } - - fn enabled(&self, meta: &Metadata<'_>, _ctx: &Context<'_, S>) -> bool { - // Event-only: never enable spans (the layer has no span consumer). - meta.is_event() && is_kernel_target(meta.target()) && should_emit(meta.level()) - } - - fn max_level_hint(&self) -> Option { - Some(current_level_filter()) - } -} - -impl Layer for KernelLogLayer -where - S: Subscriber + for<'a> LookupSpan<'a>, -{ - fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { - // A poisoned sink drops everything until re-registration; short-circuit - // before the field visit and enqueue so we don't format a record we'll - // drop. Still count the loss (each record is counted exactly once — here - // if produced while poisoned, or by the drain thread if already queued). - if SINK_POISONED.load(Ordering::Relaxed) { - DROPPED.fetch_add(1, Ordering::Relaxed); - return; - } - let meta = event.metadata(); - let mut visitor = MessageVisitor::default(); - event.record(&mut visitor); - let record = Record { - level: severity(meta.level()) as c_int, - target: meta.target(), - message: visitor.finish(), - }; - // Drop-on-full / disconnected: logs are advisory, never block a kernel - // task on a slow host callback. Count the loss so it's observable via - // kernel_logging_stats rather than vanishing silently. - if self.tx.try_send(record).is_err() { - DROPPED.fetch_add(1, Ordering::Relaxed); - } - } -} - -/// Invoke the host callback once, containing any unwind with `catch_unwind` -/// (the same guard every FFI boundary in the crate uses). Returns `false` if -/// the callback unwound, so the caller can poison the sink. -fn invoke_callback( - cb: kernel_log_callback, - ctx: usize, - level: c_int, - target: &str, - message: &str, -) -> bool { - // On the rare message with an interior NUL, truncate at the first NUL - // (keeping the prefix) instead of dropping the whole string. The bytes - // before the NUL can't contain one, so the rebuild is infallible. - let to_cstring = |s: &str| { - CString::new(s).unwrap_or_else(|e| { - let n = e.nul_position(); - CString::new(&s.as_bytes()[..n]).unwrap() - }) - }; - let target = to_cstring(target); - let message = to_cstring(message); - catch_unwind(AssertUnwindSafe(|| { - cb(ctx as *mut c_void, level, target.as_ptr(), message.as_ptr()); - })) - .is_ok() -} - -/// Poison the sink — stop delivery — but only if generation `gen` is still the -/// installed registration. The drain thread runs the callback unlocked, so the -/// host may re-register (bumping the generation, clearing the poison) while an -/// old callback is mid-unwind; comparing under the `SINK` lock keeps that old -/// failure from killing the newer registration. -fn poison_sink_if_current(gen: u64) { - if let Some(lock) = SINK.get() { - if let Ok(guard) = lock.lock() { - if guard.as_ref().map(|s| s.gen) == Some(gen) { - SINK_POISONED.store(true, Ordering::Relaxed); - } - } - } -} - -/// Drain loop (own OS thread): pull one record at a time and invoke the host -/// callback with borrowed C strings. Runs off the kernel's tokio workers so a -/// slow callback can't stall query execution. -fn drain_loop(rx: Receiver) { - // `recv` errors only once the (process-global) sender is dropped, which - // happens on a lost subscriber race (the setter drops the sender so this - // thread exits) or process teardown; exit cleanly either way. - while let Ok(record) = rx.recv() { - // A callback that unwound once is assumed to keep unwinding; stop - // delivering to protect the process (the loss is counted + surfaced via - // kernel_logging_stats). Keep draining so the channel doesn't wedge. - if SINK_POISONED.load(Ordering::Relaxed) { - DROPPED.fetch_add(1, Ordering::Relaxed); - continue; - } - let Some(sink_lock) = SINK.get() else { - continue; - }; - // Copy the sink out under the lock so the callback runs without holding - // the mutex — a reentrant setter can't deadlock and a slow callback - // can't block a level/sink update. - let sink = match sink_lock.lock() { - Ok(g) => g.as_ref().map(|s| (s.cb, s.ctx, s.gen)), - Err(_) => None, - }; - let Some((cb, ctx, gen)) = sink else { - continue; - }; - if !invoke_callback(cb, ctx, record.level, record.target, &record.message) { - // The callback unwound without delivering this record; count the - // loss, then poison iff this callback is still the installed one. - DROPPED.fetch_add(1, Ordering::Relaxed); - poison_sink_if_current(gen); - } - } -} - -/// Resolve the callback's forward level, mirroring `kernel_init_logging`'s -/// precedence: an explicit recognised `level` word wins (Go maps its driver -/// level through here); else the most-verbose kernel-applicable `RUST_LOG` level -/// ([`parse_rust_log`]); else `None`, leaving the current level untouched. -/// -/// The explicit path matters because a host at `DATABRICKS_LOG_LEVEL=debug` with -/// no `RUST_LOG` must still get kernel debug lines. -fn resolve_level(explicit: Option<&str>) -> Option { - explicit.and_then(parse_level_word).or_else(|| { - std::env::var("RUST_LOG") - .ok() - .and_then(|r| parse_rust_log(&r)) - }) -} - -/// Install `level` as the process-global threshold, returning whether it changed -/// (so the caller only rebuilds the callsite interest cache when it matters). -fn apply_level(level: u8) -> bool { - LEVEL.swap(level, Ordering::Relaxed) != level -} - -/// Stand up the process-global subscriber + drain thread, retryable across -/// calls (see [`INSTALL_LOCK`]). Returns `true` iff THIS call performed the -/// successful install; a benign lost-race or a spawn failure returns `false`, -/// with the outcome recorded in [`INSTALL_STATUS`] for the caller's return code. -/// -/// The drain thread is spawned FIRST, then the subscriber is claimed. So a -/// spawn failure (EAGAIN/ENOMEM) bails before touching the global slot, leaving -/// it free for `kernel_init_logging` and the status retryable; and a lost race -/// drops the layer (and its sender), so the freshly-spawned drain thread's -/// `recv()` errors and it exits without leaking. `set_global_default` runs at -/// most once per process — only after the drain thread is up, and both its -/// outcomes are terminal. -fn ensure_installed() -> bool { - // Terminal states need no work and no lock. - match INSTALL_STATUS.load(Ordering::Acquire) { - INSTALL_OK | INSTALL_ALREADY_SET => return false, - _ => {} - } - let Ok(_guard) = INSTALL_LOCK.lock() else { - return false; - }; - // Re-check under the lock: another caller may have installed while we waited. - match INSTALL_STATUS.load(Ordering::Acquire) { - INSTALL_OK | INSTALL_ALREADY_SET => return false, - _ => {} - } - // Stand up the delivery path first (thread + channel), so a spawn failure - // never leaves the global subscriber slot occupied. - let (tx, rx) = sync_channel::(CHANNEL_CAPACITY); - if let Err(e) = std::thread::Builder::new() - .name("kernel-log-drain".to_owned()) - .spawn(move || drain_loop(rx)) - { - // Record the OS error distinctly from the benign "already installed" - // case. `.lock().ok()` so a poisoned mutex can't panic across the FFI - // boundary; `tx` drops here, leaving the subscriber slot untouched. - if let Ok(mut guard) = SPAWN_ERROR.get_or_init(|| Mutex::new(None)).lock() { - *guard = Some(e.to_string()); - } - INSTALL_STATUS.store(INSTALL_SPAWN_FAILED, Ordering::Release); - return false; - } - // Drain thread is up; build the layer (holding the sender) and claim the - // one global subscriber. - let subscriber = - tracing_subscriber::registry().with(KernelLogLayer { tx }.with_filter(KernelFilter)); - if tracing::subscriber::set_global_default(subscriber).is_err() { - // Another subscriber won; the dropped layer takes its sender with it, so - // the drain thread's `recv()` errors and it exits cleanly. - INSTALL_STATUS.store(INSTALL_ALREADY_SET, Ordering::Release); - return false; - } - INSTALL_STATUS.store(INSTALL_OK, Ordering::Release); - true -} - -/// Install (process-wide) a callback that receives kernel `databricks*` -/// `tracing` events. `ctx` is passed back verbatim on every call. Passing a -/// null `cb` is rejected with `InvalidArgument` (to detach a sink, the design -/// would grow an explicit detach — v0 keeps install-only). -/// -/// `level` (a NUL-terminated `OFF`/`ERROR`/`WARN`/`INFO`/`DEBUG`/`TRACE` -/// string, case-insensitive, or NULL) sets the forward filter with the same -/// precedence as `kernel_init_logging`: an explicit recognised level wins as a -/// uniform threshold, else the single most-verbose kernel-applicable `RUST_LOG` -/// level (collapsed to one threshold, not per-target filtering — the bridge -/// carries one level). When neither resolves, the current filter is left -/// unchanged — the `warn` default on the first call, or the previously-set -/// filter on a re-registration. -/// -/// On failure the return code encodes whether a retry could help, so a host -/// doesn't have to string-match the message: `Internal` (terminal, -/// `retryable=false`) if a global `tracing` subscriber was already installed -/// (they are mutually exclusive; install exactly one), or `ResourceExhausted` -/// (`retryable=true`) if the log-drain thread could not be spawned — a later -/// call attempts the install again. -/// -/// # Safety -/// `cb` must be a valid function pointer that is thread-safe, does not unwind, -/// and does not call back into any `kernel_*` entry point. `ctx` must remain -/// valid until the process exits (there is no detach in v0). `level`, if -/// non-null, must be a NUL-terminated C string. -#[no_mangle] -pub unsafe extern "C" fn kernel_set_log_callback( - cb: Option, - ctx: *mut c_void, - level: *const c_char, -) -> KernelStatusCode { - crate::c_abi::error::clear_error(); - let Some(cb) = cb else { - crate::c_abi::error::store_error( - Error::invalid_argument().message("kernel_set_log_callback: cb must not be null"), - ); - return KernelStatusCode::InvalidArgument; - }; - - // A non-UTF-8 `level` is treated as absent (best-effort, like - // kernel_init_logging's level arg) rather than a hard error. - let explicit_level = if level.is_null() { - None - } else { - std::ffi::CStr::from_ptr(level).to_str().ok() - }; - // Track whether the level actually changed, so the lock-taking callsite - // interest cache is only rebuilt when it matters (not on a ctx refresh). - let mut filter_changed = false; - if let Some(level) = resolve_level(explicit_level) { - filter_changed = apply_level(level); - } - - // Record / refresh the sink (last writer wins) and clear any prior poison: - // registering a new callback is an explicit request to resume delivery. - let sink = SINK.get_or_init(|| Mutex::new(None)); - if let Ok(mut guard) = sink.lock() { - // A fresh generation so an old in-flight callback's unwind can't poison - // this new registration (see poison_sink_if_current). - let gen = NEXT_SINK_GEN.fetch_add(1, Ordering::Relaxed); - *guard = Some(Sink { - cb, - ctx: ctx as usize, - gen, - }); - SINK_POISONED.store(false, Ordering::Relaxed); - } - - // Install the process-global subscriber + drain thread (retryable across - // calls after a transient spawn failure — see ensure_installed). - let did_install = ensure_installed(); - // Rebuild the callsite interest cache only when it can matter: on the - // install that set our filter, or a later call that changed the filter. The - // rebuild takes the global callsite lock, so skip it on a ctx-only refresh. - if did_install || filter_changed { - tracing::callsite::rebuild_interest_cache(); - } - - match INSTALL_STATUS.load(Ordering::Acquire) { - INSTALL_OK => KernelStatusCode::Success, - INSTALL_SPAWN_FAILED => { - let detail = SPAWN_ERROR - .get() - .and_then(|m| m.lock().ok().and_then(|g| g.clone())) - .unwrap_or_else(|| "unknown".to_owned()); - // `ResourceExhausted` (retryable=true) not `Internal` (retryable=false): - // an OS refusal to spawn the drain thread (EAGAIN/ENOMEM) is transient - // and a later call retries the install, so the machine-readable - // `KernelError.retryable` must say so — distinct from the terminal - // already-installed case below, which stays a non-retryable `Internal`. - crate::c_abi::error::store_and_code(Error::resource_exhausted().message(format!( - "kernel_set_log_callback: the log-drain thread could not be started ({detail}); \ - kernel logs will not reach the callback" - ))) - } - // INSTALL_ALREADY_SET (or a still-PENDING install we couldn't take the - // lock for): a global subscriber was already installed, or the install - // couldn't run. Either way kernel logs won't reach this callback. - _ => crate::c_abi::error::store_and_code(Error::new( - ErrorCode::Internal, - "kernel_set_log_callback: a global tracing subscriber was already installed \ - (e.g. via kernel_init_logging); kernel logs will not reach the callback. \ - Install exactly one of kernel_set_log_callback / kernel_init_logging.", - )), - } -} - -/// Report the log-callback bridge's health (full contract in -/// `databricks_kernel.h`). `installed` is `true` iff this callback won the -/// subscriber and the sink is not poisoned; `dropped` is the cumulative records -/// lost to channel overflow or poisoning. A NULL out-param is skipped, and it -/// never fails. -/// -/// Clears the thread-local last-error on entry like every other C-ABI entry -/// point, so a host polling this infallible accessor between a failed call and -/// reading the error doesn't observe a stale error through it. -/// -/// # Safety -/// Each non-null out-param must point to a writable `bool` / `uint64_t`. -#[no_mangle] -pub unsafe extern "C" fn kernel_logging_stats(installed: *mut bool, dropped: *mut u64) { - crate::c_abi::error::clear_error(); - if !installed.is_null() { - // "Currently delivering": won the subscriber AND not poisoned. A poisoned - // sink is installed-but-dead, which must not read as healthy. - *installed = INSTALL_STATUS.load(Ordering::Acquire) == INSTALL_OK - && !SINK_POISONED.load(Ordering::Relaxed); - } - if !dropped.is_null() { - *dropped = DROPPED.load(Ordering::Relaxed); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - // A well-behaved callback returns true (delivered); a callback that unwinds - // is contained by catch_unwind and returns false (so the drain loop poisons - // the sink) rather than aborting the process at the extern "C" boundary. - extern "C-unwind" fn ok_cb( - _ctx: *mut c_void, - _lvl: c_int, - _t: *const c_char, - _m: *const c_char, - ) { - } - extern "C-unwind" fn panic_cb( - _ctx: *mut c_void, - _lvl: c_int, - _t: *const c_char, - _m: *const c_char, - ) { - panic!("callback boom"); - } - - #[test] - fn invoke_callback_delivers_and_contains_unwind() { - assert!( - invoke_callback( - ok_cb, - 0, - LEVEL_WARN as c_int, - "databricks::sql::kernel", - "ok" - ), - "a normal callback should report delivered" - ); - assert!( - !invoke_callback( - panic_cb, - 0, - LEVEL_ERROR as c_int, - "databricks::sql::kernel", - "boom" - ), - "an unwinding callback must be caught and report not-delivered, not abort" - ); - } - - // A message containing an interior NUL is truncated at the NUL (the prefix is - // preserved), not replaced wholesale with a placeholder. We capture what the - // callback receives via a thread-local so the test needs no global state. - thread_local! { - static LAST_MSG: std::cell::RefCell = const { std::cell::RefCell::new(String::new()) }; - } - extern "C-unwind" fn capture_msg_cb( - _ctx: *mut c_void, - _lvl: c_int, - _t: *const c_char, - m: *const c_char, - ) { - let s = unsafe { std::ffi::CStr::from_ptr(m) } - .to_string_lossy() - .into_owned(); - LAST_MSG.with(|c| *c.borrow_mut() = s); - } - - #[test] - fn invoke_callback_truncates_interior_nul_keeps_prefix() { - assert!(invoke_callback( - capture_msg_cb, - 0, - LEVEL_WARN as c_int, - "databricks::sql::kernel", - "keep-this\0drop-this", - )); - LAST_MSG.with(|c| { - assert_eq!( - *c.borrow(), - "keep-this", - "interior NUL should truncate, preserving the prefix" - ) - }); - } - - #[test] - fn severity_ordering_is_low_is_severe() { - assert!(severity(&Level::ERROR) < severity(&Level::WARN)); - assert!(severity(&Level::WARN) < severity(&Level::INFO)); - assert!(severity(&Level::INFO) < severity(&Level::DEBUG)); - assert!(severity(&Level::DEBUG) < severity(&Level::TRACE)); - } - - #[test] - fn should_emit_respects_configured_level() { - LEVEL.store(LEVEL_INFO, Ordering::Relaxed); - assert!(should_emit(&Level::ERROR)); - assert!(should_emit(&Level::INFO)); - assert!(!should_emit(&Level::DEBUG)); - LEVEL.store(LEVEL_OFF, Ordering::Relaxed); - assert!(!should_emit(&Level::ERROR)); - LEVEL.store(LEVEL_WARN, Ordering::Relaxed); // restore - } - - #[test] - fn parse_rust_log_collapses_to_most_verbose_kernel_level() { - // Foreign directives are ignored; the kernel one sets the level. - assert_eq!( - parse_rust_log("hyper=off,databricks::sql::kernel=info,rustls=warn"), - Some(LEVEL_INFO) - ); - // Either kernel spelling is accepted. - assert_eq!( - parse_rust_log("databricks_sql_kernel=trace"), - Some(LEVEL_TRACE) - ); - // A bare level word applies. - assert_eq!(parse_rust_log("debug"), Some(LEVEL_DEBUG)); - // Nothing kernel-applicable and no bare level → None. - assert_eq!(parse_rust_log("hyper=warn"), None); - assert_eq!(parse_rust_log(""), None); - // Non-matching databricks siblings and over-specific klog extensions are - // ignored (prefixes of no kernel event). - assert_eq!( - parse_rust_log("databricksfoo=warn,databricks::sql::kernel::foo=trace"), - None - ); - } - - #[test] - fn parse_rust_log_target_only_directive_is_trace() { - // `EnvFilter` reads a bare kernel target (no `=level`) as that target at - // TRACE — it must NOT be ignored, which would leave the callback at WARN - // where kernel_init_logging emits trace. - assert_eq!(parse_rust_log("databricks::sql::kernel"), Some(LEVEL_TRACE)); - // A foreign target-only directive is ignored; a bare kernel target is - // TRACE and a bare level word is INFO, so the max (TRACE) wins. - assert_eq!( - parse_rust_log("hyper,databricks_sql_kernel::session,info"), - Some(LEVEL_TRACE) - ); - } - - #[test] - fn parse_rust_log_takes_max_across_directives() { - // Multiple kernel-applicable directives collapse to the most verbose, - // order-independent (the callback carries one level). ERROR + TRACE → TRACE. - assert_eq!( - parse_rust_log("databricks::sql::kernel=error,databricks_sql_kernel::reader=trace"), - Some(LEVEL_TRACE) - ); - assert_eq!( - parse_rust_log("databricks_sql_kernel::reader=trace,databricks::sql::kernel=error"), - Some(LEVEL_TRACE) - ); - // A bare global level is also folded into the max. - assert_eq!( - parse_rust_log("warn,databricks::sql::kernel=debug"), - Some(LEVEL_DEBUG) - ); - } - - #[test] - fn directive_targets_kernel_matches_prefixes_of_kernel_roots() { - // Prefixes of the klog target and the module-path root are accepted. - assert!(directive_targets_kernel("databricks")); - assert!(directive_targets_kernel("databricks::sql")); - assert!(directive_targets_kernel(crate::klog::KERNEL_LOG_TARGET)); - assert!(directive_targets_kernel("databricks_sql_kernel")); - // Submodules of the module-path root are accepted (those events are - // forwarded by is_kernel_target, so a host targeting them must gate). - assert!(directive_targets_kernel("databricks_sql_kernel::session")); - assert!(directive_targets_kernel( - "databricks_sql_kernel::reader::inline" - )); - // Unrelated siblings and over-specific extensions of the fixed-depth - // klog target are rejected. - assert!(!directive_targets_kernel("databricksfoo")); - assert!(!directive_targets_kernel("databricks::sql::kernel::foo")); - assert!(!directive_targets_kernel("hyper")); - // A module-root SIBLING (not a `::`-boundary submodule) is rejected — - // it raw-prefixes `databricks_sql_kernel` but matches no forwarded event - // (this is the segment-boundary alignment with is_kernel_target). - assert!(!directive_targets_kernel("databricks_sql_kernel_ext")); - } - - #[test] - fn resolve_level_explicit_level_wins() { - // An explicit, recognised level wins outright — the one-knob path (Go - // maps DATABRICKS_LOG_LEVEL and passes it in), independent of RUST_LOG. - // We don't touch the process RUST_LOG here (that would race other tests); - // an explicit level short-circuits before RUST_LOG is ever read. - assert_eq!(resolve_level(Some("debug")), Some(LEVEL_DEBUG)); - assert_eq!(resolve_level(Some("OFF")), Some(LEVEL_OFF)); - assert_eq!(resolve_level(Some("Error")), Some(LEVEL_ERROR)); - // An unrecognised explicit word falls through (to RUST_LOG, else None). - assert_eq!(parse_level_word("not-a-level"), None); - // NULL/absent explicit level defers to RUST_LOG (covered by the - // parse_rust_log tests). - } - - #[test] - fn foreign_callsites_cache_off_kernel_callsites_reevaluate() { - // Kernel EVENT callsites re-evaluate; foreign ones cache off. - assert!(callsite_interest_for("hyper::client::pool", true).is_never()); - assert!(callsite_interest_for("rustls::conn", true).is_never()); - assert!(callsite_interest_for("databricks::sql::kernel", true).is_sometimes()); - assert!(callsite_interest_for("databricks_sql_kernel::session", true).is_sometimes()); - } - - #[test] - fn poison_sink_if_current_respects_generation() { - // Guards the re-registration race: the drain thread copies a sink's - // generation out, runs the callback unlocked, and only poisons on unwind - // if that generation is STILL installed — so an old in-flight callback's - // failure can't kill a callback the host registered in the meantime. - let lock = SINK.get_or_init(|| Mutex::new(None)); - - // Install a sink at generation `g_old`, unpoisoned. - let g_old = NEXT_SINK_GEN.fetch_add(1, Ordering::Relaxed); - *lock.lock().unwrap() = Some(Sink { - cb: ok_cb, - ctx: 0, - gen: g_old, - }); - SINK_POISONED.store(false, Ordering::Relaxed); - - // A failure attributed to the CURRENT generation poisons. - poison_sink_if_current(g_old); - assert!( - SINK_POISONED.load(Ordering::Relaxed), - "a failure on the installed generation must poison" - ); - - // Simulate a re-registration: newer generation, poison cleared. - let g_new = NEXT_SINK_GEN.fetch_add(1, Ordering::Relaxed); - *lock.lock().unwrap() = Some(Sink { - cb: ok_cb, - ctx: 0, - gen: g_new, - }); - SINK_POISONED.store(false, Ordering::Relaxed); - - // A LATE failure from the OLD generation must NOT poison the new sink. - poison_sink_if_current(g_old); - assert!( - !SINK_POISONED.load(Ordering::Relaxed), - "an old callback's unwind must not poison a newer registration" - ); - - // Restore the process-global sink state for any other test. - *lock.lock().unwrap() = None; - SINK_POISONED.store(false, Ordering::Relaxed); - } - - #[test] - fn span_callsites_cache_off_even_on_kernel_targets() { - // The bridge is event-only, so SPAN callsites never dispatch — even on - // kernel targets — so the kernel's own `databricks*` spans (Session's - // info_span!, the #[instrument] on next_batch) don't pay span machinery - // for output that never comes. - assert!(callsite_interest_for("databricks::sql::kernel", false).is_never()); - assert!( - callsite_interest_for("databricks_sql_kernel::reader::inline::streaming", false) - .is_never() - ); - // Foreign spans stay off too. - assert!(callsite_interest_for("hyper::client::pool", false).is_never()); - } - - #[test] - fn visitor_combines_message_and_fields() { - let mut v = MessageVisitor { - message: "hello".to_owned(), - ..Default::default() - }; - v.push_field("statement_id", "abc-123".to_owned()); - assert_eq!(v.finish(), "hello statement_id=abc-123"); - } - - /// Drift guard: the bridge routes kernel events by matching the `klog!` - /// target root; the kernel stamps every `klog!` with `KERNEL_LOG_TARGET`. If - /// that constant ever changed out from under the routing roots, kernel logs - /// would silently stop reaching the callback — pin the two together. - #[test] - fn filter_prefix_still_matches_kernel_emit_target() { - assert!(is_kernel_target(crate::klog::KERNEL_LOG_TARGET)); - } - - #[test] - fn is_kernel_target_matches_only_roots_and_submodules() { - // The kernel's own targets — exact roots and their `::` submodules — are - // forwarded. - assert!(is_kernel_target(crate::klog::KERNEL_LOG_TARGET)); - assert!(is_kernel_target("databricks::sql::kernel::reader")); - assert!(is_kernel_target("databricks_sql_kernel")); - assert!(is_kernel_target("databricks_sql_kernel::session")); - assert!(is_kernel_target("databricks_sql_kernel::reader::inline")); - // Unrelated `databricks`-prefixed targets are NOT forwarded: matching is - // on a `::` SEGMENT boundary, not a raw `starts_with("databricks")`, so a - // sibling crate/library log can't be routed into the kernel callback. - assert!(!is_kernel_target("databricksfoo")); - assert!(!is_kernel_target("databricks_sql_kernel_ext")); - assert!(!is_kernel_target("databricks::sql::other")); - assert!(!is_kernel_target("databricks")); - assert!(!is_kernel_target("hyper")); - } - - // NOTE: the end-to-end "MessageVisitor renders a REAL tracing event" test - // lives in `tests/v0_c_abi_log_callback.rs` (a separate binary), NOT here. - // Installing any `tracing` subscriber (even a thread-local `with_default`) - // perturbs the `tracing/log` bridge's global max-level, which the `klog` - // unit tests depend on being untouched — so a subscriber-installing test in - // THIS binary makes `klog::tests` flaky by ordering. This mirrors the - // CONSTRAINT note in `klog.rs`. The pure-predicate tests above (severity / - // should_emit / visitor field-combining / target prefix) need no subscriber - // and stay here. -} diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 83ad68a1..9bbaa38f 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -45,9 +45,7 @@ // module-wide allow that masked them in the skeleton phase is gone now // that bodies have landed. -pub mod cancel; pub mod error; -pub mod logging; pub mod metadata; pub mod result; pub mod session; @@ -168,91 +166,6 @@ where } } -/// Like [`block_on_ffi`], but races the future against a cooperative -/// [`CancellationToken`] so a host watcher thread can interrupt an otherwise -/// uninterruptible blocking C-ABI call (connect, or a hung result-stream -/// fetch). -/// -/// When `token` fires before the future completes, this **drops the future** -/// and returns [`KernelStatusCode::Cancelled`] with a typed `Cancelled` error -/// in the thread-local buffer. -/// -/// How much the drop actually tears down depends on the raced future. Where the -/// I/O is awaited *inline* in that future — the connect path -/// (`kernel_session_open_cancellable`) — dropping it drops the in-flight -/// `reqwest` request, which aborts on drop (the crate's documented cancellation -/// model), so the socket work is genuinely torn down. Where the I/O runs on a -/// *detached* task and the future only awaits a waiter — the CloudFetch fetch -/// path (`kernel_result_stream_next_batch_cancellable`), whose download lives on -/// a spawned task — the drop unblocks the caller promptly but the background -/// download continues to completion or its own read-timeout. So this is a prompt -/// stop-waiting in general, and additionally a real abort wherever the request -/// is awaited inline. -/// -/// A **null** token means "no cancellation" and this behaves exactly like -/// [`block_on_ffi`] — so a single implementation body can back both the plain -/// and the `*_cancellable` entry points. An **already-fired** token short- -/// circuits to `Cancelled` without starting the future (matching a caller whose -/// deadline had already elapsed at the call site). -/// -/// The same threading contract as [`block_on_ffi`] applies (must be driven -/// from a non-runtime thread); reentrancy is rejected identically. -/// -/// [`CancellationToken`]: tokio_util::sync::CancellationToken -pub(crate) fn block_on_ffi_cancellable( - token: Option<&tokio_util::sync::CancellationToken>, - fut_builder: F, -) -> Result -where - F: FnOnce() -> Fut, - Fut: std::future::Future>, -{ - // No token → identical to the plain path (one body, two entry shapes). - let Some(token) = token else { - return block_on_ffi(fut_builder); - }; - - // Same preamble as block_on_ffi (clear-error + reentrancy-reject + runtime - // fetch), shared so the threading-contract guard can't drift between them. - let rt = ffi_prepare_runtime()?; - - // Race the work against the token. `select!` drops the losing branch's - // future, so a cancel here drops the in-flight request future. Wrapped in - // catch_unwind on the same AssertUnwindSafe basis as block_on_ffi so a - // panic inside the future can't unwind across `extern "C"`. - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rt.block_on(async { - tokio::select! { - // Bias toward the cancel branch so an already-fired token is - // honoured deterministically before the work is polled — the - // "ctx already done at call time" case must not run the future. - biased; - _ = token.cancelled() => None, - out = fut_builder() => Some(out), - } - }) - })); - match result { - Ok(Some(Ok(value))) => Ok(value), - Ok(Some(Err(e))) => { - let code = KernelStatusCode::from(e.code); - error::store_error(e); - Err(code) - } - Ok(None) => { - // Cancelled: the future was dropped mid-flight. Surface a typed - // Cancelled error so the host sees the same shape as a server-side - // Cancelled, and can prefer its own deadline/context error. - let e = crate::kernel_error::Error::cancelled() - .message("kernel C-ABI call cancelled by the caller's cancel token"); - let code = KernelStatusCode::from(e.code); - error::store_error(e); - Err(code) - } - Err(panic) => Err(handle_panic(panic)), - } -} - /// Run a **synchronous** fallible closure at an `extern "C"` boundary, /// catching any panic so it can't unwind across the FFI frame (UB) and /// mapping it to [`KernelStatusCode::Internal`]. @@ -431,33 +344,4 @@ mod tests { ); }); } - - #[test] - fn block_on_ffi_cancellable_rejects_reentrancy_from_runtime_thread() { - // The cancellable entry shape shares block_on_ffi's preamble via - // ffi_prepare_runtime, so it must reject reentrancy identically. This - // locks in the shared guard the two shapes used to duplicate. - let rt = tokio::runtime::Runtime::new().expect("runtime"); - rt.block_on(async { - let token = tokio_util::sync::CancellationToken::new(); - let result: Result<(), KernelStatusCode> = - block_on_ffi_cancellable(Some(&token), || async { Ok(()) }); - assert_eq!(result, Err(KernelStatusCode::Internal)); - - let mut out = std::mem::MaybeUninit::::uninit(); - // SAFETY: out is a valid writable pointer. - let present = unsafe { crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr()) }; - assert!(present, "reentrancy must populate the last-error buffer"); - // SAFETY: present is true, so out is initialised. - let err = unsafe { out.assume_init() }; - // SAFETY: message is non-null after a store. - let msg = unsafe { std::ffi::CStr::from_ptr(err.message) } - .to_str() - .unwrap(); - assert!( - msg.contains("within a Tokio runtime"), - "reentrancy error should explain the threading contract, got: {msg}", - ); - }); - } } diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 2cb9e8f2..cdad7d27 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -38,7 +38,6 @@ #![allow(non_camel_case_types)] -use super::cancel::{kernel_cancel_token_t, token_ref}; use super::error::{store_and_code, store_invalid_arg}; use super::{catch_ffi, KernelStatusCode}; use crate::kernel_error::{Error, ErrorCode}; @@ -47,7 +46,6 @@ use crate::statement::executed::ExecutedStatement; use crate::statement::validity::ValidityFlag; use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; use arrow_array::{Array, RecordBatch}; -use tokio_util::sync::CancellationToken; /// Opaque result-stream handle. Boxed [`ResultStreamInner`]. #[repr(C)] @@ -198,49 +196,6 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( stream: *mut kernel_result_stream_t, out_array: *mut FFI_ArrowArray, out_schema: *mut FFI_ArrowSchema, -) -> KernelStatusCode { - next_batch_inner(stream, out_array, out_schema, None) -} - -/// Fetch the next batch, racing the (blocking) fetch against `cancel_token` so -/// a host can interrupt a hung CloudFetch chunk (a wedged S3 / pre-signed-URL -/// GET) instead of blocking on it forever. A **null** `cancel_token` behaves -/// exactly like [`kernel_result_stream_next_batch`]. -/// -/// If the token fires before the batch is ready, the fetch future is dropped -/// (aborting the in-flight download) and this returns -/// [`KernelStatusCode::Cancelled`]. The stream handle stays valid and owned by -/// the caller — close it with [`kernel_result_stream_close`] as usual; a -/// cancelled fetch does not consume or free it. -/// -/// # Safety -/// `stream`, `out_array`, `out_schema` carry the same contract as -/// [`kernel_result_stream_next_batch`]. `cancel_token`, if non-null, must be a -/// live handle from -/// [`kernel_cancel_token_new`](crate::c_abi::cancel::kernel_cancel_token_new) -/// not freed until this call returns; it is safe to fire from another thread -/// while this call is in flight. -#[no_mangle] -pub unsafe extern "C" fn kernel_result_stream_next_batch_cancellable( - stream: *mut kernel_result_stream_t, - out_array: *mut FFI_ArrowArray, - out_schema: *mut FFI_ArrowSchema, - cancel_token: *const kernel_cancel_token_t, -) -> KernelStatusCode { - next_batch_inner(stream, out_array, out_schema, token_ref(cancel_token)) -} - -/// Shared body for the two next-batch entry points. `token` (None for the plain -/// one) is raced against the fetch via `block_on_ffi_cancellable`. -/// -/// # Safety -/// See [`kernel_result_stream_next_batch`]. `token` must outlive the call when -/// `Some`. -unsafe fn next_batch_inner( - stream: *mut kernel_result_stream_t, - out_array: *mut FFI_ArrowArray, - out_schema: *mut FFI_ArrowSchema, - token: Option<&CancellationToken>, ) -> KernelStatusCode { catch_ffi(|| { let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { @@ -256,12 +211,11 @@ unsafe fn next_batch_inner( let next: Option> = match inner { // Owned (metadata): drive the owned ResultStream lazily on the // runtime, one batch at a time, so an unbounded result streams - // with bounded memory. Running through block_on_ffi_cancellable - // keeps the (possibly CloudFetch-backed) reader on the tokio - // reactor rather than off a plain C thread, and lets a fired token - // drop the fetch future. + // with bounded memory. Running through block_on_ffi keeps the + // (possibly CloudFetch-backed) reader on the tokio reactor rather + // than off a plain C thread. ResultStreamInner::Owned { stream, .. } => { - match super::block_on_ffi_cancellable(token, move || { + match super::block_on_ffi(move || { let stream: &mut crate::result_stream::ResultStream = stream; Box::pin(async move { #[allow( @@ -294,9 +248,8 @@ unsafe fn next_batch_inner( // RecordBatch for FFI export. Explicit match on the // #[non_exhaustive] ResultBatch so a future non-Arrow // variant surfaces as a defined error, not a compile break - // with no fallback. Cancellable so a hung CloudFetch chunk on - // the query path can be interrupted. - match super::block_on_ffi_cancellable(token, move || { + // with no fallback. + match super::block_on_ffi(move || { let exec: &mut ExecutedStatement = exec; Box::pin(async move { #[allow( diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index dc06b7ac..8672a968 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -22,14 +22,12 @@ //! Transaction methods (autocommit / commit / rollback) are deferred to //! v0.1 per `docs/spec-v0.md` addendum A5. -use super::cancel::{kernel_cancel_token_t, token_ref}; -use super::{block_on_ffi_cancellable, KernelStatusCode}; +use super::{block_on_ffi, KernelStatusCode}; use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; use crate::kernel_error::Error; use crate::session::Session; use std::collections::HashMap; use std::ffi::{c_char, CStr}; -use tokio_util::sync::CancellationToken; /// Opaque session handle. Boxed [`Session`] on the Rust side. #[repr(C)] @@ -97,11 +95,6 @@ pub struct KernelSessionConfig { /// Extra HTTP headers sent on every request (accumulated by /// `..._set_custom_header`, one `(name, value)` pair per call). custom_headers: Vec<(String, String)>, - /// CloudFetch toggle (populated by `..._set_cloudfetch_enabled`). - /// `None` keeps the kernel default (CloudFetch on); `Some(false)` - /// forces the inline-Arrow result path (mirrors JDBC - /// `EnableQueryResultDownload=0`). - cloudfetch_enabled: Option, } /// C-side proxy config captured from `kernel_session_config_set_proxy`. @@ -169,7 +162,6 @@ pub unsafe extern "C" fn kernel_session_config_new( proxy: None, tls: TlsSpec::default(), custom_headers: Vec::new(), - cloudfetch_enabled: None, }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -546,27 +538,6 @@ pub unsafe extern "C" fn kernel_session_config_set_tls_client_certificate( }) } -/// Enable or disable CloudFetch (cloud-storage-backed download of large -/// result sets). Default enabled; `false` forces the inline-Arrow path -/// for all result sizes — mirrors JDBC `EnableQueryResultDownload=0`. The -/// kernel sets the `can_cloud_download` session conf internally at -/// `open()`; callers must NOT set that conf directly via -/// `set_session_conf` (the server rejects it as not user-settable). Maps -/// to `ResultConfig::cloudfetch_enabled`. -/// -/// # Safety -/// `config` must be a live config handle. -#[no_mangle] -pub unsafe extern "C" fn kernel_session_config_set_cloudfetch_enabled( - config: *mut KernelSessionConfig, - enabled: bool, -) -> KernelStatusCode { - set_on_config(config, |c| { - c.cloudfetch_enabled = Some(enabled); - Ok(()) - }) -} - /// Shared body for the config setters: null-check the handle, clear the /// thread-local error, run `f` against the borrowed config, and store /// any error. @@ -610,48 +581,6 @@ unsafe fn set_on_config( pub unsafe extern "C" fn kernel_session_open( config: *mut KernelSessionConfig, out: *mut *mut kernel_session_t, -) -> KernelStatusCode { - session_open_inner(config, out, None) -} - -/// Open a session, racing the (blocking) connect against `cancel_token` so a -/// host can bound a slow warehouse cold-start / connect-time network partition -/// by its own deadline. A **null** `cancel_token` behaves exactly like -/// [`kernel_session_open`]. If the token fires (or is already fired) before -/// connect completes, the connect future is dropped — aborting the in-flight -/// request — and this returns [`KernelStatusCode::Cancelled`]; the config is -/// still consumed either way. -/// -/// The `cancel_token` is borrowed, not consumed: the caller still owns it and -/// must [`kernel_cancel_token_free`](crate::c_abi::cancel::kernel_cancel_token_free) -/// it after this returns. It is safe to fire the token from another thread -/// while this call is in flight (that is the intended use). -/// -/// # Safety -/// `config` and `out` carry the same contract as [`kernel_session_open`]. -/// `cancel_token`, if non-null, must be a live handle from -/// [`kernel_cancel_token_new`](crate::c_abi::cancel::kernel_cancel_token_new) -/// that is not freed until this call returns. -#[no_mangle] -pub unsafe extern "C" fn kernel_session_open_cancellable( - config: *mut KernelSessionConfig, - out: *mut *mut kernel_session_t, - cancel_token: *const kernel_cancel_token_t, -) -> KernelStatusCode { - session_open_inner(config, out, token_ref(cancel_token)) -} - -/// Shared body for [`kernel_session_open`] and -/// [`kernel_session_open_cancellable`]. Owns the "config is consumed on every -/// path" contract in one place; `token` (None for the plain entry point) is -/// threaded into `build_session`'s `block_on`. -/// -/// # Safety -/// See [`kernel_session_open`]. `token` must outlive the call when `Some`. -unsafe fn session_open_inner( - config: *mut KernelSessionConfig, - out: *mut *mut kernel_session_t, - token: Option<&CancellationToken>, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); // The contract is "config is consumed on every path". Reclaim the box @@ -673,7 +602,7 @@ unsafe fn session_open_inner( } let config = config.expect("config is Some (checked above)"); - let session = match build_session(*config, token) { + let session = match build_session(*config) { Ok(s) => s, Err(code) => return code, // error already stored by build_session }; @@ -699,15 +628,9 @@ fn parse_scopes(s: &str) -> Option> { } /// Translate the C-side config into a [`Session`], driving the async -/// `Session::open` on the process-wide runtime. When `token` is `Some`, the -/// connect is raced against it so a fired token drops the connect future -/// (aborting the in-flight request) and yields `Cancelled` — the connect-side -/// deadline path. Errors are stored in the thread-local buffer; the returned -/// `KernelStatusCode` is the mapped code. -fn build_session( - config: KernelSessionConfig, - token: Option<&CancellationToken>, -) -> Result { +/// `Session::open` on the process-wide runtime. Errors are stored in the +/// thread-local buffer; the returned `KernelStatusCode` is the mapped code. +fn build_session(config: KernelSessionConfig) -> Result { let KernelSessionConfig { connection, auth, @@ -715,10 +638,9 @@ fn build_session( proxy, tls, custom_headers, - cloudfetch_enabled, } = config; - block_on_ffi_cancellable(token, move || { + block_on_ffi(move || { Box::pin(async move { let connection = connection.ok_or_else(|| { Error::invalid_argument().message( @@ -805,17 +727,6 @@ fn build_session( }); } - // CloudFetch toggle. Only override the result config when the knob - // was set, so the kernel's default (CloudFetch on) + all the other - // ResultConfig tuning (prefetch windows, JSON rendering) are - // preserved otherwise. - if let Some(enabled) = cloudfetch_enabled { - builder = builder.result(crate::config::ResultConfig { - cloudfetch_enabled: enabled, - ..crate::config::ResultConfig::default() - }); - } - builder.open().await }) }) @@ -863,111 +774,6 @@ pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> KernelStatusCode::Success } -/// Close a session and BLOCK until the server-side `DeleteSession` RPC -/// has been *attempted* to completion, reusing the crate's awaitable -/// [`Session::close`]. Unlike [`kernel_session_close`] (fire-and-forget), -/// this waits for the delete round-trip rather than returning before it — -/// the parity path for a host (Thrift, ODBC) that wants close to behave -/// like the synchronous `DeleteSession` RPC the direct-Rust and pyo3/napi -/// consumers get via `Session::close().await`. -/// -/// IMPORTANT: `Success` means the delete was *attempted*, not that the -/// server confirmed it. [`Session::close`] delegates to `delete_session`, -/// which — after exhausting HTTP retries — logs a transient failure and -/// returns `Ok(())` rather than propagating it (the caller has no useful -/// recovery path, and the server reclaims the session on idle-timeout). So -/// a partitioned/failed delete still returns `Success` here (surfaced only -/// as a kernel `warn!`, visible to a host that installed a log callback); -/// `Err(code)` is reserved for a null handle, reentrancy, or a panic. This -/// matches the direct-Rust / pyo3 / napi consumers, whose `Session::close` -/// swallows the same failure identically. -/// -/// Consumes the handle exactly like [`kernel_session_close`]: on both -/// success and failure the session is released, so the caller must not use -/// or free `session` afterwards. The same teardown ordering applies — -/// close the session LAST, after every statement / executed handle / -/// result stream / canceller it produced (see the `databricks_kernel.h` -/// teardown-ordering contract). -/// -/// # Safety -/// -/// `session` must have been returned by [`kernel_session_open`] and not -/// previously closed. After this call, `session` is invalid; passing it to -/// any other `kernel_*` function is UB. -#[no_mangle] -pub unsafe extern "C" fn kernel_session_close_blocking( - session: *mut kernel_session_t, -) -> KernelStatusCode { - session_close_blocking_inner(session, None) -} - -/// Blocking close, racing the (blocking) `DeleteSession` against `cancel_token` -/// so a host can bound a wedged / partitioned close by its own deadline instead -/// of blocking up to the retry ceiling. A **null** `cancel_token` behaves -/// exactly like [`kernel_session_close_blocking`]. If the token fires (or is -/// already fired) before the delete completes, this returns -/// [`KernelStatusCode::Cancelled`]. -/// -/// Consumes the handle on **every** path — success, delete error, AND -/// `Cancelled`. On cancel the awaited future (which owns the boxed session) is -/// dropped, so the session is released via its `Drop` (a best-effort -/// fire-and-forget delete, like [`kernel_session_close`]); the caller must not -/// use or free `session` afterwards regardless of the return code. -/// -/// The `cancel_token` is borrowed, not consumed: the caller still owns it and -/// must [`kernel_cancel_token_free`](crate::c_abi::cancel::kernel_cancel_token_free) -/// it after this returns. It is safe to fire the token from another thread while -/// this call is in flight (that is the intended use). -/// -/// # Safety -/// `session` carries the same contract as [`kernel_session_close_blocking`]. -/// `cancel_token`, if non-null, must be a live handle from -/// [`kernel_cancel_token_new`](crate::c_abi::cancel::kernel_cancel_token_new) -/// that is not freed until this call returns. -#[no_mangle] -pub unsafe extern "C" fn kernel_session_close_blocking_cancellable( - session: *mut kernel_session_t, - cancel_token: *const kernel_cancel_token_t, -) -> KernelStatusCode { - session_close_blocking_inner(session, token_ref(cancel_token)) -} - -/// Shared body for [`kernel_session_close_blocking`] and -/// [`kernel_session_close_blocking_cancellable`]. Owns the "handle is consumed -/// on every path" contract in one place; `token` (None for the plain entry -/// point) is threaded into `Session::close`'s `block_on`. -/// -/// # Safety -/// See [`kernel_session_close_blocking`]. `token` must outlive the call when -/// `Some`. -unsafe fn session_close_blocking_inner( - session: *mut kernel_session_t, - token: Option<&CancellationToken>, -) -> KernelStatusCode { - crate::c_abi::error::clear_error(); - if session.is_null() { - crate::c_abi::error::store_error( - Error::invalid_argument() - .message("kernel_session_close_blocking: session must not be null"), - ); - return KernelStatusCode::InvalidArgument; - } - // Reclaim the box and await the delete on the process-wide runtime. - // `Session::close(self)` consumes the session, so move the boxed value - // into the future (mirroring `build_session`'s move of the config). - // On error the code is returned and the typed error is already stored; - // on a fired token the future is dropped, taking the boxed session with - // it (its `Drop` runs the fire-and-forget delete). Either way the box is - // released, honouring the consume-on-every-path contract. - let session = Box::from_raw(session as *mut Session); - match block_on_ffi_cancellable(token, move || { - Box::pin(async move { session.close().await }) - }) { - Ok(()) => KernelStatusCode::Success, - Err(code) => code, - } -} - /// Report whether a session is still **open** (its server-side delete has /// not been initiated). Writes `true`/`false` to `*out`. /// @@ -1259,31 +1065,4 @@ mod tests { // and released `config` on its failure path. } } - - /// The CloudFetch setter records the toggle as `Some(enabled)`; a config - /// that never calls it leaves `None` so the kernel default (on) wins. The - /// last call wins (set false then true → true). - #[test] - fn set_cloudfetch_enabled_records_toggle() { - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - // Default: untouched → None (kernel default applies). - assert_eq!(config.as_ref().unwrap().cloudfetch_enabled, None); - assert_eq!( - kernel_session_config_set_cloudfetch_enabled(config, false), - KernelStatusCode::Success - ); - assert_eq!(config.as_ref().unwrap().cloudfetch_enabled, Some(false)); - assert_eq!( - kernel_session_config_set_cloudfetch_enabled(config, true), - KernelStatusCode::Success - ); - assert_eq!(config.as_ref().unwrap().cloudfetch_enabled, Some(true)); - kernel_session_config_free(config); - } - } } diff --git a/tests/c/log_callback_smoke.c b/tests/c/log_callback_smoke.c deleted file mode 100644 index e13652f3..00000000 --- a/tests/c/log_callback_smoke.c +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2026 Databricks, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * C ABI smoke test — log-callback SUCCESS path, in its own process. - * - * session_smoke.c installs kernel_init_logging first, so its callback install - * only exercises the mutual-exclusion (Internal) path. There is exactly one - * process-global tracing subscriber, so the success path can't also be reached - * there. This separate binary calls kernel_set_log_callback WITHOUT any prior - * kernel_init_logging, so the callback wins the subscriber: install must return - * Success and kernel_logging_stats must report installed=true. - * - * It links the cdylib through the same C typedef (kernel_log_callback) and the - * two logging symbols the header declares, so it catches header/cdylib drift in - * the callback ABI — a signature or symbol mismatch fails to compile or link. - * (Forcing a real event through the callback needs a kernel-side tracing emit, - * which only the Rust integration test tests/v0_c_abi_log_callback.rs can do; - * this binary proves the install/stats contract from a real C consumer.) - * - * Build / run (via `make c-abi-test`, which compiles every tests/c/*.c): - * cc -I include tests/c/log_callback_smoke.c -L target/debug \ - * -ldatabricks_sql_kernel -o log_callback_smoke && ./log_callback_smoke - */ - -#include -#include - -#include "databricks_kernel.h" - -static int failures = 0; - -#define CHECK(cond, msg) \ - do { \ - if (!(cond)) { \ - fprintf(stderr, "FAIL: %s (%s:%d)\n", msg, __FILE__, __LINE__); \ - failures++; \ - } else { \ - fprintf(stderr, "ok: %s\n", msg); \ - } \ - } while (0) - -static int g_calls = 0; -static void count_cb(void* ctx, int level, const char* target, const char* message) { - (void)level; - (void)target; - (void)message; - int* counter = (int*)ctx; - if (counter) { - (*counter)++; - } -} - -int main(void) { - /* ABI-version lockstep: the library compiled-in version must equal the - * header this test built against (same gate as session_smoke.c). */ - CHECK(kernel_abi_version() == DATABRICKS_KERNEL_ABI_VERSION, - "kernel_abi_version() matches DATABRICKS_KERNEL_ABI_VERSION"); - - /* A NULL callback is still rejected up front. */ - CHECK(kernel_set_log_callback(NULL, NULL, NULL) == KernelStatusCode_InvalidArgument, - "set_log_callback(NULL cb) → InvalidArgument"); - - /* Fresh process, no kernel_init_logging: the callback wins the one - * process-global subscriber, so this MUST succeed (not the Internal - * mutual-exclusion outcome session_smoke.c sees). */ - KernelStatusCode rc = kernel_set_log_callback(count_cb, &g_calls, "TRACE"); - CHECK(rc == KernelStatusCode_Success, - "set_log_callback installs in a fresh process (no init_logging) → Success"); - - bool installed = false; - uint64_t dropped = 1; - kernel_logging_stats(&installed, &dropped); - CHECK(installed, "logging_stats reports installed=true after a successful install"); - CHECK(dropped == 0, "a healthy fresh install has dropped no records"); - - /* Re-registering is last-writer-wins and still succeeds (NULL level defers to - * the current threshold). */ - rc = kernel_set_log_callback(count_cb, &g_calls, NULL); - CHECK(rc == KernelStatusCode_Success, "re-registering the callback → Success"); - - /* NULL out-params must be tolerated. */ - kernel_logging_stats(NULL, NULL); - CHECK(true, "logging_stats(NULL, NULL) is safe"); - - if (failures == 0) { - fprintf(stderr, "\nAll C ABI log-callback smoke checks passed.\n"); - return 0; - } - fprintf(stderr, "\n%d C ABI log-callback smoke check(s) FAILED.\n", failures); - return 1; -} diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 4427a1b9..024fc7bd 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -191,10 +191,6 @@ static void test_proxy_and_tls_setters(void) { rc = kernel_session_config_set_tls_client_certificate(config, cert, sizeof(cert) - 1, NULL, 0); CHECK(rc == KernelStatusCode_InvalidArgument, "set_tls_client_certificate(NULL key) → InvalidArgument"); - - /* CloudFetch toggle accepts a bool. */ - rc = kernel_session_config_set_cloudfetch_enabled(config, false); - CHECK(rc == KernelStatusCode_Success, "set_cloudfetch_enabled(false) succeeds"); kernel_session_config_free(config); } @@ -230,49 +226,6 @@ static void test_init_logging(void) { CHECK(rc == KernelStatusCode_Success, "init_logging twice is safe"); } -/* kernel_set_log_callback: NULL cb is rejected; a real cb installs (or reports - * the mutual-exclusion outcome if init_logging already won the one global - * subscriber). Hermetic — no network, no events forced. The `level` arg is - * exercised as an explicit "WARN" and NULL to cover both precedence paths. */ -static int g_log_calls = 0; -static void count_log_cb(void* ctx, int level, const char* target, const char* message) { - (void)level; - (void)target; - (void)message; - int* counter = (int*)ctx; - if (counter) { - (*counter)++; - } -} - -static void test_log_callback(void) { - KernelStatusCode rc = kernel_set_log_callback(NULL, NULL, NULL); - CHECK(rc == KernelStatusCode_InvalidArgument, "set_log_callback(NULL cb) → InvalidArgument"); - - /* This runs AFTER test_init_logging, which already won the one process-global - * subscriber, so the mutual-exclusion contract is deterministic here: the - * callback install must report Internal (not Success, not a silent no-op). - * The explicit "WARN" level arg is accepted regardless. */ - rc = kernel_set_log_callback(count_log_cb, &g_log_calls, "WARN"); - CHECK(rc == KernelStatusCode_Internal, - "set_log_callback after init_logging → Internal (mutual exclusion)"); - - /* A NULL level (defer to RUST_LOG / current) is also accepted; same - * mutual-exclusion outcome on a refresh. */ - rc = kernel_set_log_callback(count_log_cb, &g_log_calls, NULL); - CHECK(rc == KernelStatusCode_Internal, - "set_log_callback(NULL level) after init_logging → Internal"); - - /* kernel_logging_stats never fails and honours NULL out-params. init_logging - * won the subscriber, so the callback did NOT install. */ - bool installed = true; - uint64_t dropped = 123; - kernel_logging_stats(&installed, &dropped); - CHECK(!installed, "logging_stats: callback not installed (init_logging won)"); - kernel_logging_stats(NULL, NULL); /* must not crash on NULL out-params */ - CHECK(true, "logging_stats(NULL, NULL) is safe"); -} - /* is_open null-guards its args. (The true→false behavior is covered by the * in-crate Rust test * `session::is_open_tests::is_open_flips_true_to_false_on_delete`, which can @@ -316,76 +269,6 @@ static void test_executed_null_handle_rejected(void) { CHECK(n == -1, "num_modified_rows(NULL exec) → -1"); } -/* Cancel token: new → cancel → free round-trips; null guards on every entry - * point return InvalidArgument. (The mid-flight interrupt behaviour is proven - * by the wiremock integration test, which needs a mock server; this smoke only - * exercises the lifecycle from C.) */ -static void test_cancel_token_lifecycle(void) { - kernel_cancel_token_t* tok = NULL; - KernelStatusCode rc = kernel_cancel_token_new(&tok); - CHECK(rc == KernelStatusCode_Success, "cancel_token_new succeeds"); - CHECK(tok != NULL, "cancel_token_new writes a non-null handle"); - - bool fired = true; - rc = kernel_cancel_token_is_cancelled(tok, &fired); - CHECK(rc == KernelStatusCode_Success, "cancel_token_is_cancelled succeeds"); - CHECK(!fired, "a fresh token reports not-cancelled"); - - rc = kernel_cancel_token_cancel(tok); - CHECK(rc == KernelStatusCode_Success, "cancel_token_cancel succeeds"); - rc = kernel_cancel_token_is_cancelled(tok, &fired); - CHECK(rc == KernelStatusCode_Success && fired, "is_cancelled reports true after a fire"); - /* One-shot: a second fire is a no-op but still Success. */ - rc = kernel_cancel_token_cancel(tok); - CHECK(rc == KernelStatusCode_Success, "cancel_token_cancel is idempotent"); - - rc = kernel_cancel_token_free(tok); - CHECK(rc == KernelStatusCode_Success, "cancel_token_free succeeds"); - - CHECK(kernel_cancel_token_new(NULL) == KernelStatusCode_InvalidArgument, - "cancel_token_new(NULL) → InvalidArgument"); - CHECK(kernel_cancel_token_cancel(NULL) == KernelStatusCode_InvalidArgument, - "cancel_token_cancel(NULL) → InvalidArgument"); - CHECK(kernel_cancel_token_is_cancelled(NULL, &fired) == KernelStatusCode_InvalidArgument, - "cancel_token_is_cancelled(NULL) → InvalidArgument"); - CHECK(kernel_cancel_token_free(NULL) == KernelStatusCode_InvalidArgument, - "cancel_token_free(NULL) → InvalidArgument"); -} - -/* A pre-fired token short-circuits kernel_session_open_cancellable to Cancelled - * without touching the network, and consumes the config regardless. Hermetic - * (never dials out — the biased select honours the fired token first). */ -static void test_open_cancellable_prefired(void) { - KernelSessionConfig* config = NULL; - (void)kernel_session_config_new(&config); - (void)kernel_session_config_set_warehouse(config, "https://192.0.2.1", "wh123"); - (void)kernel_session_config_set_auth_pat(config, "dapi-not-a-real-token"); - - kernel_cancel_token_t* tok = NULL; - (void)kernel_cancel_token_new(&tok); - (void)kernel_cancel_token_cancel(tok); /* fire before the call */ - - kernel_session_t* session = NULL; - KernelStatusCode rc = kernel_session_open_cancellable(config, &session, tok); - CHECK(rc == KernelStatusCode_Cancelled, - "open_cancellable with a pre-fired token → Cancelled"); - CHECK(session == NULL, "session stays null on a cancelled open"); - - /* A NULL token behaves like the plain open: same unreachable host, so it - * must fail with a NON-Cancelled transport error (proving NULL != cancel). */ - KernelSessionConfig* config2 = NULL; - (void)kernel_session_config_new(&config2); - (void)kernel_session_config_set_warehouse(config2, "https://192.0.2.1", "wh123"); - (void)kernel_session_config_set_auth_pat(config2, "dapi-not-a-real-token"); - kernel_session_t* session2 = NULL; - rc = kernel_session_open_cancellable(config2, &session2, NULL); - CHECK(rc != KernelStatusCode_Success && rc != KernelStatusCode_Cancelled, - "open_cancellable(NULL token) behaves like plain open (transport error)"); - CHECK(session2 == NULL, "session stays null on failed open"); - - kernel_cancel_token_free(tok); -} - int main(void) { test_abi_version_matches_header(); test_config_lifecycle(); @@ -397,16 +280,10 @@ int main(void) { test_proxy_and_tls_setters(); test_u2m_and_header_setters(); test_init_logging(); - /* After test_init_logging so it wins the one process-global subscriber; the - * callback install then deterministically reports the mutual-exclusion - * outcome (Internal). */ - test_log_callback(); test_is_open_null_guards(); test_submit_stub_rejects(); test_bind_null_handle_rejected(); test_executed_null_handle_rejected(); - test_cancel_token_lifecycle(); - test_open_cancellable_prefired(); if (failures == 0) { fprintf(stderr, "\nAll C ABI smoke checks passed.\n"); diff --git a/tests/v0_c_abi_cancel_token_wiremock.rs b/tests/v0_c_abi_cancel_token_wiremock.rs deleted file mode 100644 index 348eaa0d..00000000 --- a/tests/v0_c_abi_cancel_token_wiremock.rs +++ /dev/null @@ -1,629 +0,0 @@ -// Copyright (c) 2026 Databricks, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Wiremock tests for the cooperative cancel token and the -//! `kernel_session_open_cancellable` connect-side entry point. -//! -//! The behaviour under test is: a blocking C-ABI call that would otherwise sit -//! on a slow/stalled server response can be interrupted by firing a cancel -//! token from another thread, returning `Cancelled` promptly instead of -//! blocking to completion — and, crucially, that a NULL token leaves the exact -//! same call blocking to completion (so cancellation is opt-in and the default -//! path is unchanged). -//! -//! We simulate a stalled server with wiremock's response `set_delay`, fire the -//! token from a spawned OS thread after a short beat, and assert both the -//! `Cancelled` status and that the call returned well before the server delay -//! would have elapsed. The C ABI drives its own process-wide runtime inside -//! `block_on_ffi_cancellable`, so the entry points run on a plain `#[test]` -//! thread; the dedicated tokio runtime here only hosts the mock server. -//! -//! The connect path exercises the exact `block_on_ffi_cancellable` machinery the -//! result-stream fetch path (`kernel_result_stream_next_batch_cancellable`) also -//! routes through. The final test drives the fetch path directly through a real -//! executed statement, proving `next_batch_cancellable` honors a fired token (and -//! that a NULL token yields the batch normally). - -use std::ffi::CString; -use std::thread; -use std::time::{Duration, Instant}; - -use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; -use arrow_array::{Int64Array, RecordBatch}; -use arrow_ipc::writer::StreamWriter; -use base64::engine::general_purpose::STANDARD; -use base64::Engine; -use databricks_sql_kernel::c_abi::cancel::{ - kernel_cancel_token_cancel, kernel_cancel_token_free, kernel_cancel_token_new, - kernel_cancel_token_t, -}; -use databricks_sql_kernel::c_abi::result::{ - kernel_result_stream_close, kernel_result_stream_next_batch_cancellable, kernel_result_stream_t, -}; -use databricks_sql_kernel::c_abi::session::{ - kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, - kernel_session_config_set_http_path, kernel_session_new_statement, kernel_session_open, - kernel_session_open_cancellable, kernel_session_t, KernelSessionConfig, -}; -use databricks_sql_kernel::c_abi::statement::{ - kernel_executed_statement_close, kernel_executed_statement_get_result_stream, - kernel_executed_statement_t, kernel_statement_execute, kernel_statement_set_sql, - kernel_statement_t, -}; -use databricks_sql_kernel::c_abi::KernelStatusCode; -use serde_json::json; -use wiremock::matchers::{method, path}; -use wiremock::{Mock, MockServer, ResponseTemplate}; - -/// Address a config at the given mock server URI with PAT auth. Shared setup. -/// -/// # Safety -/// `config` must be a live config handle; the returned CStrings must outlive -/// the setter calls (they do — the caller holds them). -unsafe fn address_config( - config: *mut KernelSessionConfig, - uri: &str, -) -> (CString, CString, CString) { - let host = CString::new(uri).unwrap(); - let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); - let token = CString::new("dapi_test_token").unwrap(); - assert_eq!( - kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), - KernelStatusCode::Success - ); - assert_eq!( - kernel_session_config_set_auth_pat(config, token.as_ptr()), - KernelStatusCode::Success - ); - (host, http_path, token) -} - -/// A token that is ALREADY fired before the call short-circuits connect to -/// `Cancelled` without opening a session — the "ctx already done at call time" -/// case. The `biased` select in `block_on_ffi_cancellable` makes this -/// deterministic (the cancel branch is polled first). -#[test] -fn open_cancellable_prefired_token_short_circuits() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let server = rt.block_on(async { - let server = MockServer::start().await; - // A create-session mock that, if ever hit, would succeed — so a failure - // to short-circuit surfaces as a Success (test fails on the assert). - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-prefired","warehouse_id":"test_wh"}"#), - ) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let _held = address_config(config, &uri); - - let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); - assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); - // Fire BEFORE the call. - assert_eq!(kernel_cancel_token_cancel(tok), KernelStatusCode::Success); - - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - let rc = kernel_session_open_cancellable(config, &mut session, tok); - assert_eq!( - rc, - KernelStatusCode::Cancelled, - "a pre-fired token must short-circuit connect to Cancelled" - ); - assert!(session.is_null(), "no session handle on a cancelled open"); - - assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); - } -} - -/// A token fired from another thread DURING a stalled connect interrupts it: -/// the call returns `Cancelled` well before the (long) server delay elapses. -/// This is the connect-side deadline property — a slow warehouse cold-start no -/// longer blocks past the caller's deadline. -#[test] -fn open_cancellable_fires_during_stalled_connect() { - let rt = tokio::runtime::Runtime::new().unwrap(); - // Create-session stalls for 10s; the test fires cancel after ~150ms and - // must return long before the 10s would elapse. - let server = rt.block_on(async { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(Duration::from_secs(10)) - .set_body_string(r#"{"session_id":"sess-stall","warehouse_id":"test_wh"}"#), - ) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let _held = address_config(config, &uri); - - let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); - assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); - - // Watcher thread: fire the token after a short beat. `usize` shuttle so - // the raw pointer crosses the thread boundary (kernel_cancel_token_t is - // Send-safe to fire from another thread by contract). - let tok_addr = tok as usize; - let watcher = thread::spawn(move || { - thread::sleep(Duration::from_millis(150)); - let t = tok_addr as *mut kernel_cancel_token_t; - assert_eq!(kernel_cancel_token_cancel(t), KernelStatusCode::Success); - }); - - let start = Instant::now(); - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - let rc = kernel_session_open_cancellable(config, &mut session, tok); - let elapsed = start.elapsed(); - - watcher.join().unwrap(); - - assert_eq!( - rc, - KernelStatusCode::Cancelled, - "a token fired mid-connect must interrupt the blocking connect" - ); - assert!(session.is_null(), "no session handle on a cancelled open"); - assert!( - elapsed < Duration::from_secs(5), - "cancel must abort the stalled connect promptly, took {elapsed:?}" - ); - - assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); - } -} - -/// A NULL token means "no cancellation": a normal (fast) create-session with a -/// NULL token completes normally. This pins that the cancellable entry point is -/// a strict superset of the plain one (the default path is unchanged). -#[test] -fn open_cancellable_null_token_behaves_like_plain_open() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let server = rt.block_on(async { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-null-tok","warehouse_id":"test_wh"}"#), - ) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/sessions/sess-null-tok")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let _held = address_config(config, &uri); - - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - // NULL token → same as kernel_session_open. - let rc = kernel_session_open_cancellable(config, &mut session, std::ptr::null()); - assert_eq!(rc, KernelStatusCode::Success); - assert!(!session.is_null()); - - // Tidy up the opened session (fire-and-forget close). - assert_eq!(kernel_session_close(session), KernelStatusCode::Success); - } -} - -// ── mid-fetch cancel (kernel_result_stream_next_batch_cancellable) ──────────── - -/// A SUCCEEDED statement response carrying one inline-Arrow chunk of BIGINT rows, -/// so a real result stream can be opened and fetched over the C ABI. -fn succeeded_inline_body(statement_id: &str) -> String { - let batch = RecordBatch::try_from_iter([( - "n", - std::sync::Arc::new(Int64Array::from(vec![1_i64, 2, 3])) as arrow_array::ArrayRef, - )]) - .unwrap(); - let mut ipc = Vec::new(); - { - let mut w = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); - w.write(&batch).unwrap(); - w.finish().unwrap(); - } - let attachment = STANDARD.encode(&ipc); - json!({ - "statement_id": statement_id, - "status": { "state": "SUCCEEDED" }, - "manifest": { - "format": "ARROW_STREAM", - "schema": { "column_count": 1, "columns": [ - { "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0 } - ]}, - "total_chunk_count": 1, - "total_row_count": 3, - "total_byte_count": ipc.len() as i64, - "truncated": false, - }, - "result": { - "chunk_index": 0, - "row_offset": 0, - "row_count": 3, - "byte_count": ipc.len() as i64, - "attachment": attachment, - }, - }) - .to_string() -} - -/// Drive the fetch path directly: open a session, execute a query that returns -/// an inline-Arrow result, obtain the result stream, then call -/// `kernel_result_stream_next_batch_cancellable`. A **pre-fired** token must -/// short-circuit the fetch to `Cancelled` (the biased select honors the token -/// before polling the fetch — the Gap 6 mid-fetch property), while a **NULL** -/// token on a fresh stream yields the batch normally (parity with the plain -/// next_batch). This exercises the actual `next_batch_cancellable` entry point, -/// not just the shared machinery the connect tests cover. -#[test] -fn next_batch_cancellable_prefired_token_short_circuits_fetch() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let server = rt.block_on(async { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-fetch","warehouse_id":"test_wh"}"#), - ) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/sessions/sess-fetch")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/statements")) - .respond_with( - ResponseTemplate::new(200).set_body_string(succeeded_inline_body("stmt-fetch")), - ) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - // Open a session. - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let _held = address_config(config, &uri); - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - assert_eq!( - kernel_session_open(config, &mut session), - KernelStatusCode::Success - ); - assert!(!session.is_null()); - - // execute a query → executed handle → result stream. - let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); - assert_eq!( - kernel_session_new_statement(session, &mut stmt), - KernelStatusCode::Success - ); - let sql = CString::new("SELECT n FROM t").unwrap(); - assert_eq!( - kernel_statement_set_sql(stmt, sql.as_ptr()), - KernelStatusCode::Success - ); - let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); - assert_eq!( - kernel_statement_execute(stmt, &mut exec), - KernelStatusCode::Success - ); - let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); - assert_eq!( - kernel_executed_statement_get_result_stream(exec, &mut stream), - KernelStatusCode::Success - ); - assert!(!stream.is_null()); - - // Pre-fire a token, then fetch: the biased select must honor the fired - // token and return Cancelled without producing a batch. - let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); - assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); - assert_eq!(kernel_cancel_token_cancel(tok), KernelStatusCode::Success); - let mut arr = FFI_ArrowArray::empty(); - let mut sch = FFI_ArrowSchema::empty(); - let rc = kernel_result_stream_next_batch_cancellable(stream, &mut arr, &mut sch, tok); - assert_eq!( - rc, - KernelStatusCode::Cancelled, - "a pre-fired token must short-circuit the fetch to Cancelled" - ); - assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); - - // A NULL token on the same stream fetches the batch normally (parity with - // the plain next_batch): the inline chunk yields a non-released array. - let mut arr2 = FFI_ArrowArray::empty(); - let mut sch2 = FFI_ArrowSchema::empty(); - let rc = kernel_result_stream_next_batch_cancellable( - stream, - &mut arr2, - &mut sch2, - std::ptr::null(), - ); - assert_eq!( - rc, - KernelStatusCode::Success, - "NULL token must fetch normally" - ); - - // Teardown in the documented order: stream → executed → session. - kernel_result_stream_close(stream); - kernel_executed_statement_close(exec); - assert_eq!(kernel_session_close(session), KernelStatusCode::Success); - } -} - -/// One chunk's worth of Arrow IPC stream bytes carrying a single Int64 column -/// `n`. Used to build multi-chunk CloudFetch (external-link) results. -fn arrow_chunk_ipc(values: Vec) -> Vec { - let batch = RecordBatch::try_from_iter([( - "n", - std::sync::Arc::new(Int64Array::from(values)) as arrow_array::ArrayRef, - )]) - .unwrap(); - let mut ipc = Vec::new(); - { - let mut w = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); - w.write(&batch).unwrap(); - w.finish().unwrap(); - } - ipc -} - -/// A SUCCEEDED statement body describing a **two-chunk** CloudFetch result whose -/// chunks are served as external links back at the mock server. Chunk 0 carries -/// its own `next_chunk_index=1` so the reader keeps going after the first batch. -fn succeeded_two_chunk_external_body( - statement_id: &str, - chunk0_url: &str, - chunk1_url: &str, - chunk0_bytes: i64, - chunk1_bytes: i64, -) -> String { - json!({ - "statement_id": statement_id, - "status": { "state": "SUCCEEDED" }, - "manifest": { - "format": "ARROW_STREAM", - "schema": { "column_count": 1, "columns": [ - { "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0 } - ]}, - "total_chunk_count": 2, - "total_row_count": 4, - "truncated": false, - }, - "result": { - "external_links": [ - { - "external_link": chunk0_url, - "expiration": "2099-01-01T00:00:00.000Z", - "chunk_index": 0, - "row_offset": 0, - "row_count": 2, - "byte_count": chunk0_bytes, - "next_chunk_index": 1, - }, - { - "external_link": chunk1_url, - "expiration": "2099-01-01T00:00:00.000Z", - "chunk_index": 1, - "row_offset": 2, - "row_count": 2, - "byte_count": chunk1_bytes, - }, - ], - }, - }) - .to_string() -} - -/// F4: a token fired WHILE a CloudFetch chunk download is genuinely in flight -/// interrupts the caller's wait promptly. This is the mid-flight fetch property -/// the pre-fired inline test can't reach (there, no download exists). -/// -/// Shape: a two-chunk external-link result. Chunk 0's GET returns valid Arrow -/// IPC immediately, so `execute()` + `get_schema()` (which eagerly waits on -/// chunk 0) and the FIRST `next_batch` both complete normally. Chunk 1's GET is -/// STALLED with a long `set_delay`, so the SECOND `next_batch_cancellable` is -/// blocked on an actually-in-flight download. A watcher thread fires the token -/// mid-fetch, and the call must return `Cancelled` well before the stall would -/// elapse — proving cancel interrupts the wait on a live fetch. -/// -/// Per the corrected F1 contract, this asserts the caller unblocks promptly; it -/// does NOT assert the background download is torn down (it isn't — the detached -/// task drains to its read-timeout), which is exactly why the header/rows.go -/// docs were reworded from "aborts the download" to "stops waiting". -#[test] -fn next_batch_cancellable_fires_during_stalled_fetch() { - let chunk0 = arrow_chunk_ipc(vec![1, 2]); - let chunk0_len = chunk0.len() as i64; - - let rt = tokio::runtime::Runtime::new().unwrap(); - let server = - rt.block_on(async { - let server = MockServer::start().await; - let chunk0_url = format!("{}/cf/stmt-stall/chunk-0.arrow", server.uri()); - let chunk1_url = format!("{}/cf/stmt-stall/chunk-1.arrow", server.uri()); - - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"{"session_id":"sess-stall-fetch","warehouse_id":"test_wh"}"#, - )) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/sessions/sess-stall-fetch")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/statements")) - .respond_with(ResponseTemplate::new(200).set_body_string( - succeeded_two_chunk_external_body( - "stmt-stall", - &chunk0_url, - &chunk1_url, - chunk0_len, - 1024, - ), - )) - .mount(&server) - .await; - // Chunk 0: immediate valid Arrow IPC (drives schema + first batch). - Mock::given(method("GET")) - .and(path("/cf/stmt-stall/chunk-0.arrow")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(chunk0.clone())) - .mount(&server) - .await; - // Chunk 1: STALLED — the download the second next_batch blocks on. The - // 30s delay is far longer than the cancel latency we assert below. - Mock::given(method("GET")) - .and(path("/cf/stmt-stall/chunk-1.arrow")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(Duration::from_secs(30)) - .set_body_bytes(arrow_chunk_ipc(vec![3, 4])), - ) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let _held = address_config(config, &uri); - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - assert_eq!( - kernel_session_open(config, &mut session), - KernelStatusCode::Success - ); - assert!(!session.is_null()); - - let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); - assert_eq!( - kernel_session_new_statement(session, &mut stmt), - KernelStatusCode::Success - ); - let sql = CString::new("SELECT n FROM t").unwrap(); - assert_eq!( - kernel_statement_set_sql(stmt, sql.as_ptr()), - KernelStatusCode::Success - ); - let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); - assert_eq!( - kernel_statement_execute(stmt, &mut exec), - KernelStatusCode::Success - ); - let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); - assert_eq!( - kernel_executed_statement_get_result_stream(exec, &mut stream), - KernelStatusCode::Success - ); - assert!(!stream.is_null()); - - // First batch (chunk 0) fetches normally with a NULL token. - let mut arr0 = FFI_ArrowArray::empty(); - let mut sch0 = FFI_ArrowSchema::empty(); - let rc = kernel_result_stream_next_batch_cancellable( - stream, - &mut arr0, - &mut sch0, - std::ptr::null(), - ); - assert_eq!( - rc, - KernelStatusCode::Success, - "chunk 0 must fetch normally before the stalled chunk 1" - ); - - // Second batch (chunk 1) is stalled server-side. Fire the token from a - // watcher thread after a short beat; the call must return Cancelled well - // before the 30s stall elapses. - let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); - assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); - let tok_addr = tok as usize; - let watcher = thread::spawn(move || { - thread::sleep(Duration::from_millis(200)); - let t = tok_addr as *mut kernel_cancel_token_t; - assert_eq!(kernel_cancel_token_cancel(t), KernelStatusCode::Success); - }); - - let mut arr1 = FFI_ArrowArray::empty(); - let mut sch1 = FFI_ArrowSchema::empty(); - let start = Instant::now(); - let rc = kernel_result_stream_next_batch_cancellable(stream, &mut arr1, &mut sch1, tok); - let elapsed = start.elapsed(); - watcher.join().unwrap(); - - assert_eq!( - rc, - KernelStatusCode::Cancelled, - "a token fired mid-fetch must interrupt the wait on the stalled chunk" - ); - assert!( - elapsed < Duration::from_secs(5), - "cancel must unblock the stalled fetch promptly, took {elapsed:?}" - ); - assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); - - kernel_result_stream_close(stream); - kernel_executed_statement_close(exec); - assert_eq!(kernel_session_close(session), KernelStatusCode::Success); - } -} diff --git a/tests/v0_c_abi_cloudfetch_wiremock.rs b/tests/v0_c_abi_cloudfetch_wiremock.rs deleted file mode 100644 index 3fcb5489..00000000 --- a/tests/v0_c_abi_cloudfetch_wiremock.rs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) 2026 Databricks, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Wiremock test for `kernel_session_config_set_cloudfetch_enabled`: setting -//! it to `false` must make the kernel send `can_cloud_download=false` in the -//! create-session request's `session_confs`, so SEA serves results inline -//! instead of via CloudFetch. Asserting the wire body is the substitute for a -//! live e2e — a real warehouse gates `can_cloud_download` (returns -//! `CONFIG_NOT_AVAILABLE / 42K0I`), so the toggle can't be verified against -//! staging; this proves the toggle reaches the wire. -//! -//! Same threading shape as the other C-ABI wiremock tests: the C ABI drives -//! its own runtime inside `block_on_ffi`, so the entry points run on a plain -//! `#[test]` thread with a dedicated runtime only to host the mock. - -use std::ffi::CString; - -use databricks_sql_kernel::c_abi::session::{ - kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, - kernel_session_config_set_cloudfetch_enabled, kernel_session_config_set_http_path, - kernel_session_open, kernel_session_t, KernelSessionConfig, -}; -use databricks_sql_kernel::c_abi::KernelStatusCode; -use wiremock::matchers::{method, path}; -use wiremock::{Mock, MockServer, ResponseTemplate}; - -#[test] -fn set_cloudfetch_disabled_sends_can_cloud_download_false() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let server = rt.block_on(async { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-cf","warehouse_id":"test_wh"}"#), - ) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/sessions/sess-cf")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let host = CString::new(uri.as_str()).unwrap(); - let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); - assert_eq!( - kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), - KernelStatusCode::Success - ); - let token = CString::new("dapi_test_token").unwrap(); - assert_eq!( - kernel_session_config_set_auth_pat(config, token.as_ptr()), - KernelStatusCode::Success - ); - // Disable CloudFetch — the assertion target. - assert_eq!( - kernel_session_config_set_cloudfetch_enabled(config, false), - KernelStatusCode::Success - ); - - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - assert_eq!( - kernel_session_open(config, &mut session), - KernelStatusCode::Success - ); - assert!(!session.is_null()); - // Tidy up (fire-and-forget close is fine here — we only inspect the - // create-session request below). - kernel_session_close(session); - } - - // Inspect the create-session POST body: session_confs must carry - // can_cloud_download=false. - let body = rt.block_on(async { - let requests = server.received_requests().await.unwrap_or_default(); - let create = requests - .iter() - .find(|r| r.method.as_str() == "POST" && r.url.path().ends_with("/sql/sessions")) - .expect("a create-session POST must have been sent"); - serde_json::from_slice::(&create.body).expect("create body is JSON") - }); - let confs = &body["session_confs"]; - let val = confs - .get("can_cloud_download") - .or_else(|| confs.get("can_cloud_download".to_uppercase().as_str())); - assert_eq!( - val.and_then(|v| v.as_str()), - Some("false"), - "disabling CloudFetch must send can_cloud_download=false in session_confs, got confs={confs}" - ); -} diff --git a/tests/v0_c_abi_log_callback.rs b/tests/v0_c_abi_log_callback.rs deleted file mode 100644 index 0039193f..00000000 --- a/tests/v0_c_abi_log_callback.rs +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (c) 2026 Databricks, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! End-to-end delivery test for the `kernel_set_log_callback` reverse-call log -//! bridge. Registers a C callback, emits kernel `tracing` events on the -//! contract target, and asserts the callback received them with the message and -//! target intact — and that the `level` argument gates delivery in both -//! directions (a restrictive level filters a below-threshold event; a -//! permissive level delivers an event below the default threshold). -//! -//! This lives in its own integration-test binary (NOT a `#[cfg(test)] mod` in -//! `src/c_abi/logging.rs`) on purpose: installing the process-global `tracing` -//! subscriber the bridge needs perturbs the `tracing/log` bridge's global -//! max-level, which the `klog` unit tests depend on being untouched — so a -//! subscriber-installing test in the lib-test binary makes `klog::tests` flaky -//! by ordering. A separate binary has its own global state. Mirrors the -//! CONSTRAINT note in `src/klog.rs`. - -use std::os::raw::{c_char, c_int, c_void}; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Mutex; - -use databricks_sql_kernel::c_abi::error::{kernel_get_last_error, KernelError}; -use databricks_sql_kernel::c_abi::logging::{kernel_logging_stats, kernel_set_log_callback}; -use databricks_sql_kernel::c_abi::KernelStatusCode; - -// Captured (level, target, message) tuples, keyed via a process-global slot the -// callback pushes into. -static CAPTURED: Mutex> = Mutex::new(Vec::new()); -static CALLS: AtomicUsize = AtomicUsize::new(0); -// The `ctx` the kernel passed back on the most recent call, recorded as a usize -// so we can assert the round-trip returns the exact pointer we registered. -static SEEN_CTX: AtomicUsize = AtomicUsize::new(0); - -extern "C-unwind" fn capture_cb( - ctx: *mut c_void, - level: c_int, - target: *const c_char, - message: *const c_char, -) { - CALLS.fetch_add(1, Ordering::SeqCst); - SEEN_CTX.store(ctx as usize, Ordering::SeqCst); - // SAFETY: the bridge passes valid NUL-terminated C strings for the call. - let target = unsafe { std::ffi::CStr::from_ptr(target) } - .to_string_lossy() - .into_owned(); - let message = unsafe { std::ffi::CStr::from_ptr(message) } - .to_string_lossy() - .into_owned(); - CAPTURED.lock().unwrap().push((level, target, message)); -} - -/// A callback that always unwinds across the FFI boundary. The bridge's -/// `catch_unwind` must contain it, count the undelivered record, and poison the -/// sink (stop delivery) rather than abort the process. -extern "C-unwind" fn panic_cb( - _ctx: *mut c_void, - _level: c_int, - _target: *const c_char, - _message: *const c_char, -) { - panic!("callback boom"); -} - -/// Poll up to ~1s for the captured records to satisfy `pred`, returning the -/// final snapshot either way (delivery is async via the bridge's drain thread). -fn wait_until(pred: impl Fn(&[(c_int, String, String)]) -> bool) -> Vec<(c_int, String, String)> { - for _ in 0..100 { - let got = CAPTURED.lock().unwrap().clone(); - if pred(&got) { - return got; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - CAPTURED.lock().unwrap().clone() -} - -/// Whether a kernel-target record carrying `marker` in its message was captured. -fn saw_marker(got: &[(c_int, String, String)], marker: &str) -> bool { - got.iter() - .any(|(_, t, m)| t == databricks_sql_kernel::KERNEL_LOG_TARGET && m.contains(marker)) -} - -#[test] -fn log_callback_delivers_and_level_gates_end_to_end() { - // Register a real (non-null) ctx so we can assert the round-trip returns the - // exact pointer we passed — a stand-in for the Go cgo.Handle token. - let ctx_marker: Box = Box::new(0xC0FFEE); - let ctx_ptr = Box::into_raw(ctx_marker) as *mut c_void; - - // === Step 1: a RESTRICTIVE level must FILTER a below-threshold event. === - // Install at ERROR. A WARN event must not be delivered — this is what proves - // the `level` argument actually gates delivery (the previous "trace + WARN" - // shape would pass even if `level` were ignored, since WARN clears the - // default WARN threshold). This is a fresh, single-test binary, so nothing - // else has installed a global subscriber: install MUST succeed. Accepting - // `Internal` here would let a regression that never installs stay green. - let level_error = std::ffi::CString::new("error").unwrap(); - let rc = unsafe { kernel_set_log_callback(Some(capture_cb), ctx_ptr, level_error.as_ptr()) }; - assert_eq!( - rc, - KernelStatusCode::Success, - "kernel_set_log_callback must succeed on first install in a fresh binary; got {rc:?}" - ); - - let filtered_marker = "probe-warn-should-be-filtered-a1"; - let barrier_marker = "probe-error-barrier-b2"; - // Emit the (to-be-filtered) WARN first, then an ERROR barrier. The single - // drain thread delivers FIFO, so once the ERROR barrier lands we know the - // earlier WARN would already have arrived had it passed the filter — a - // deterministic negative assertion, not a "sleep and hope". - tracing::warn!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "{}", filtered_marker); - tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "{}", barrier_marker); - let got = wait_until(|g| saw_marker(g, barrier_marker)); - assert!( - saw_marker(&got, barrier_marker), - "the ERROR barrier event must be delivered at level=error; captured={got:?}" - ); - assert!( - !saw_marker(&got, filtered_marker), - "a WARN event must NOT be delivered when level=error — this proves the level \ - argument gates delivery; captured={got:?}" - ); - - // === Step 2: a PERMISSIVE level must DELIVER a below-default event. === - // Re-register at TRACE and emit a DEBUG event. DEBUG is below the static - // WARN default, so its delivery proves the `level` argument also loosens the - // threshold (not just that WARN happens to clear the default). Same ctx, so - // the round-trip assertion below still holds. - let level_trace = std::ffi::CString::new("trace").unwrap(); - let rc = unsafe { kernel_set_log_callback(Some(capture_cb), ctx_ptr, level_trace.as_ptr()) }; - assert_eq!( - rc, - KernelStatusCode::Success, - "re-registering the callback must succeed; got {rc:?}" - ); - - // `klog::debug!` is pub(crate); from this external test binary we emit the - // exact `tracing` event it expands to (same target + event field). - let stmt = "stmt-cb-probe-9c1"; - tracing::debug!( - target: databricks_sql_kernel::KERNEL_LOG_TARGET, - statement_id = stmt, - "callback probe message" - ); - let got = wait_until(|g| saw_marker(g, stmt)); - let hit = got - .iter() - .find(|(_, t, m)| t == databricks_sql_kernel::KERNEL_LOG_TARGET && m.contains(stmt)); - let (_level, _target, message) = hit.unwrap_or_else(|| { - panic!( - "a DEBUG kernel event must be delivered at level=trace (the default WARN would \ - drop it) — this proves the level argument is honoured; captured={got:?}" - ) - }); - assert!( - message.contains("callback probe message"), - "message text should carry through, got: {message}" - ); - assert!( - message.contains("statement_id"), - "structured field should render into the message, got: {message}" - ); - - // === Step 3: an event emitted INSIDE a (now-disabled) kernel span must - // still be delivered. === - // The bridge's filter is event-only: kernel SPAN callsites cache off - // (`callsite_interest_for(_, is_event=false)` → never), so the kernel's own - // `info_span!` / `#[instrument]` spans become no-op disabled spans and pay - // no span machinery. This must NOT suppress EVENTS emitted while such a span - // is on the stack — `tracing` evaluates span and event callsites - // independently, and the kernel logs most of its events from inside - // instrumented functions (e.g. a `klog::debug!` inside the `#[instrument]`ed - // `next_batch`). Reproduce that shape: enter a kernel span (disabled by our - // filter) and emit a kernel event within it; the callback must still get the - // event. Guards against a filter/`tracing` change silently dropping every - // in-span kernel log. - let in_span_marker = "probe-event-inside-disabled-span-c3"; - let kernel_span = tracing::info_span!( - target: databricks_sql_kernel::KERNEL_LOG_TARGET, - "kernel.session", - session_id = "sess-guard" - ); - { - let _entered = kernel_span.enter(); - tracing::debug!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "{}", in_span_marker); - } - let got = wait_until(|g| saw_marker(g, in_span_marker)); - assert!( - saw_marker(&got, in_span_marker), - "an event emitted inside a disabled kernel span must still be delivered — disabling \ - span callsites must not suppress in-span events; captured={got:?}" - ); - - // The ctx round-trip: the kernel must hand back the exact pointer we - // registered, verbatim (it is opaque and never dereferenced kernel-side). - assert_eq!( - SEEN_CTX.load(Ordering::SeqCst), - ctx_ptr as usize, - "callback ctx should round-trip the exact pointer passed to kernel_set_log_callback" - ); - - // Stats accessor: this callback won the subscriber (installed=true) and a - // healthy delivery drops nothing (the filtered WARN was never enqueued). - let mut installed = false; - let mut dropped: u64 = 0; - unsafe { - databricks_sql_kernel::c_abi::logging::kernel_logging_stats(&mut installed, &mut dropped) - }; - assert!( - installed, - "kernel_logging_stats should report installed=true after a successful install" - ); - assert_eq!(dropped, 0, "a healthy delivery should not drop records"); - - // === Step 4: a callback that unwinds is counted as a drop and poisons the - // sink. === - // Re-register a callback that always panics (which clears the poison and - // starts a fresh generation), emit one kernel event, and confirm the bridge - // (a) contained the unwind — the process is still alive to run these asserts - // — (b) counted the undelivered record in `dropped` (previously the first - // unwinding record was silently uncounted), and (c) poisoned the sink so - // `installed` now reads false. - let panic_ctx: Box = Box::new(0xBADF00D); - let panic_ctx_ptr = Box::into_raw(panic_ctx) as *mut c_void; - let level_trace2 = std::ffi::CString::new("trace").unwrap(); - let rc = - unsafe { kernel_set_log_callback(Some(panic_cb), panic_ctx_ptr, level_trace2.as_ptr()) }; - assert_eq!( - rc, - KernelStatusCode::Success, - "re-registering the panicking callback must succeed; got {rc:?}" - ); - - let dropped_before = dropped; - tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "probe-unwinds-d4"); - // Poll for the sink to be poisoned (delivery attempted, callback unwound). - let mut installed_after = true; - let mut dropped_after = dropped_before; - for _ in 0..100 { - unsafe { - databricks_sql_kernel::c_abi::logging::kernel_logging_stats( - &mut installed_after, - &mut dropped_after, - ) - }; - if !installed_after { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert!( - !installed_after, - "a callback that unwinds must poison the sink so installed reads false" - ); - assert!( - dropped_after > dropped_before, - "the record whose callback unwound must be counted in dropped \ - (before={dropped_before}, after={dropped_after})" - ); - - // === Step 5: re-registering a good callback after poison restores delivery. - // === - // The host's documented recovery path: install a fresh, well-behaved - // callback. Registration clears the poison and starts a new generation, so - // `installed` must flip back to true and a NEW event must be delivered again - // — proving a single misbehaving callback doesn't permanently wedge the - // bridge for the rest of the process. - let recover_ctx: Box = Box::new(0x600D); - let recover_ctx_ptr = Box::into_raw(recover_ctx) as *mut c_void; - let level_trace3 = std::ffi::CString::new("trace").unwrap(); - let rc = unsafe { - kernel_set_log_callback(Some(capture_cb), recover_ctx_ptr, level_trace3.as_ptr()) - }; - assert_eq!( - rc, - KernelStatusCode::Success, - "re-registering a good callback after poison must succeed; got {rc:?}" - ); - - let mut installed_recovered = false; - let mut dropped_recovered = 0u64; - unsafe { - databricks_sql_kernel::c_abi::logging::kernel_logging_stats( - &mut installed_recovered, - &mut dropped_recovered, - ) - }; - assert!( - installed_recovered, - "re-registering a good callback must clear the poison and flip installed back to true" - ); - - let recovery_marker = "probe-recovered-e5"; - tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "{}", recovery_marker); - let got = wait_until(|g| saw_marker(g, recovery_marker)); - assert!( - saw_marker(&got, recovery_marker), - "delivery must resume after re-registering a good callback post-poison; captured={got:?}" - ); - - // Reclaim the leaked ctx markers (kept alive across the calls above). - unsafe { - drop(Box::from_raw(ctx_ptr as *mut u64)); - drop(Box::from_raw(panic_ctx_ptr as *mut u64)); - drop(Box::from_raw(recover_ctx_ptr as *mut u64)); - } -} - -/// `kernel_logging_stats` clears the thread-local last-error on entry like every -/// other C-ABI entry point, so a host that polls this infallible accessor -/// between a failed call and reading the error doesn't observe the prior error -/// through it. Runs on its own test thread (last-error is thread-local), and the -/// null-cb rejection that seeds the error returns BEFORE any install logic, so -/// this test is independent of the delivery test's process-global subscriber. -#[test] -fn kernel_logging_stats_clears_stale_last_error() { - // Seed a stale error on this thread: a null callback is rejected with - // InvalidArgument and stores a last error. - let rc = unsafe { kernel_set_log_callback(None, std::ptr::null_mut(), std::ptr::null()) }; - assert_eq!( - rc, - KernelStatusCode::InvalidArgument, - "a null callback must be rejected and seed a last error" - ); - let mut seeded = std::mem::MaybeUninit::::uninit(); - assert!( - unsafe { kernel_get_last_error(seeded.as_mut_ptr()) }, - "precondition: the null-cb rejection must have seeded a last error" - ); - - // The infallible stats accessor must clear the stale error on entry. - let mut installed = false; - let mut dropped = 0u64; - unsafe { kernel_logging_stats(&mut installed, &mut dropped) }; - - let mut after = std::mem::MaybeUninit::::uninit(); - assert!( - !unsafe { kernel_get_last_error(after.as_mut_ptr()) }, - "kernel_logging_stats must clear the stale last error on entry" - ); -} diff --git a/tests/v0_c_abi_log_callback_overflow.rs b/tests/v0_c_abi_log_callback_overflow.rs deleted file mode 100644 index 311ddddb..00000000 --- a/tests/v0_c_abi_log_callback_overflow.rs +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) 2026 Databricks, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Drop-on-full test for the `kernel_set_log_callback` bridge's bounded channel. -//! -//! The delivery test (`v0_c_abi_log_callback.rs`) covers the healthy path -//! (`dropped == 0`) and the poison path (a record lost to an unwinding -//! callback). It does NOT exercise the headline "logs never back-pressure a -//! kernel hot path" behavior — the `try_send(...).is_err()` overflow branch in -//! `KernelLogLayer::on_event`. This test does: it WEDGES the single drain thread -//! inside a blocking callback so records can't be consumed, floods the bounded -//! channel (capacity 4096) with far more than that many kernel events, and -//! asserts `kernel_logging_stats` reports `dropped > 0` while the emitting -//! thread stays responsive (never blocks). A regression that swapped the -//! non-blocking `try_send` for a blocking `send` would stall the emitter here -//! instead of dropping — which this test would catch as a hang. -//! -//! Its own integration-test binary (like the delivery test): it installs the -//! process-global `tracing` subscriber and permanently wedges the drain thread, -//! so it must not share a process with tests that assert a healthy sink. - -use std::os::raw::{c_char, c_int, c_void}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::time::{Duration, Instant}; - -use databricks_sql_kernel::c_abi::logging::{kernel_logging_stats, kernel_set_log_callback}; -use databricks_sql_kernel::c_abi::KernelStatusCode; - -// The channel capacity in `src/c_abi/logging.rs`. Kept in sync by construction: -// we emit comfortably more than this so the overflow branch is guaranteed. -const CHANNEL_CAPACITY: usize = 4096; - -// Set by the callback the instant it is first entered — signals that the drain -// thread has pulled one record and is now blocked inside the callback, so any -// further emits must pile onto (and overflow) the bounded channel. -static WEDGED: AtomicBool = AtomicBool::new(false); -// Cleared to release the wedged callback so the drain thread can finish and exit -// cleanly at end of test. -static RELEASE: AtomicBool = AtomicBool::new(false); -static DELIVERED: AtomicUsize = AtomicUsize::new(0); - -/// A callback that blocks the drain thread until the test releases it. The first -/// (and, while wedged, only) delivered record parks here; every later buffered -/// record runs fast once released. -extern "C-unwind" fn wedging_cb( - _ctx: *mut c_void, - _level: c_int, - _target: *const c_char, - _message: *const c_char, -) { - WEDGED.store(true, Ordering::SeqCst); - DELIVERED.fetch_add(1, Ordering::SeqCst); - // Park the drain thread here so the bounded channel fills. Bounded spin so a - // bug in the release path can't hang CI forever. - let start = Instant::now(); - while !RELEASE.load(Ordering::SeqCst) && start.elapsed() < Duration::from_secs(30) { - std::thread::sleep(Duration::from_millis(1)); - } -} - -#[test] -fn drop_on_full_counts_overflow_without_blocking_the_emitter() { - // Fresh single-test binary: nothing else has claimed the global subscriber, - // so install MUST succeed. Install at trace so the ERROR flood below clears - // the threshold and every event reaches the channel. - let level = std::ffi::CString::new("trace").unwrap(); - let rc = - unsafe { kernel_set_log_callback(Some(wedging_cb), std::ptr::null_mut(), level.as_ptr()) }; - assert_eq!( - rc, - KernelStatusCode::Success, - "kernel_set_log_callback must succeed on first install in a fresh binary; got {rc:?}" - ); - - // Emit one event and wait for the drain thread to pull it and wedge inside - // the callback. Once WEDGED, exactly one record has been consumed and the - // drain thread is blocked — so subsequent emits can only fill the channel. - tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "wedge-primer"); - let mut wedged = false; - for _ in 0..500 { - if WEDGED.load(Ordering::SeqCst) { - wedged = true; - break; - } - std::thread::sleep(Duration::from_millis(10)); - } - assert!( - wedged, - "the drain thread should have entered the blocking callback (wedged)" - ); - - // Flood well past the buffer. With the drain thread wedged, at most - // CHANNEL_CAPACITY records can buffer; the rest hit the try_send-full branch - // and are counted in `dropped`. Time the loop: if try_send ever became a - // blocking send, this would stall for ~30s (the callback's park) instead of - // returning promptly — so a slow loop is itself a failure signal. - let flood = CHANNEL_CAPACITY * 2 + 500; - let start = Instant::now(); - for i in 0..flood { - tracing::error!(target: databricks_sql_kernel::KERNEL_LOG_TARGET, "flood-{}", i); - } - let elapsed = start.elapsed(); - assert!( - elapsed < Duration::from_secs(5), - "emitting {flood} events must not block the caller (drop-on-full, not back-pressure); \ - took {elapsed:?} — a blocking send would stall on the wedged drain thread" - ); - - // The drops happen synchronously in on_event on this thread during the - // flood, so `dropped` is already positive; poll briefly only for robustness. - let mut installed = false; - let mut dropped: u64 = 0; - for _ in 0..50 { - unsafe { kernel_logging_stats(&mut installed, &mut dropped) }; - if dropped > 0 { - break; - } - std::thread::sleep(Duration::from_millis(10)); - } - assert!( - dropped > 0, - "flooding a wedged bridge past its {CHANNEL_CAPACITY}-record channel must drop records \ - (dropped={dropped}); the overflow branch was not exercised" - ); - assert!( - installed, - "the sink is still installed (a full channel drops records, it does not poison the sink)" - ); - - // Release the wedged callback so the drain thread drains the buffer and can - // exit cleanly; the process would reap it regardless, but this keeps the - // teardown tidy. - RELEASE.store(true, Ordering::SeqCst); -} diff --git a/tests/v0_c_abi_session_close_blocking_wiremock.rs b/tests/v0_c_abi_session_close_blocking_wiremock.rs deleted file mode 100644 index e0469b34..00000000 --- a/tests/v0_c_abi_session_close_blocking_wiremock.rs +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright (c) 2026 Databricks, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Wiremock test for `kernel_session_close_blocking`: unlike the -//! fire-and-forget `kernel_session_close` (whose DELETE the sibling test -//! has to *poll* for, since it runs on a detached task), the blocking -//! close must have completed the server-side `DeleteSession` **before it -//! returns** — so the DELETE is observable immediately with no polling -//! loop. That synchronous-completion property is exactly what a host wires -//! it up for (parity with the Thrift path's synchronous CloseSession RPC), -//! so it is what this test asserts. -//! -//! Same threading shape as the sibling: the C ABI drives its own -//! process-wide runtime inside `block_on_ffi`, so the entry points run on -//! a plain `#[test]` thread with a dedicated runtime only to host the mock. - -use std::ffi::CString; -use std::thread; -use std::time::{Duration, Instant}; - -use databricks_sql_kernel::c_abi::cancel::{ - kernel_cancel_token_cancel, kernel_cancel_token_free, kernel_cancel_token_new, - kernel_cancel_token_t, -}; -use databricks_sql_kernel::c_abi::session::{ - kernel_session_close_blocking, kernel_session_close_blocking_cancellable, - kernel_session_config_new, kernel_session_config_set_auth_pat, - kernel_session_config_set_http_path, kernel_session_open, kernel_session_t, - KernelSessionConfig, -}; -use databricks_sql_kernel::c_abi::KernelStatusCode; -use wiremock::matchers::{method, path}; -use wiremock::{Mock, MockServer, ResponseTemplate}; - -#[test] -fn session_close_blocking_awaits_delete_before_returning() { - // A dedicated runtime just to run the async wiremock setup / request - // inspection; the C ABI calls themselves run on the kernel's own runtime. - let rt = tokio::runtime::Runtime::new().unwrap(); - let server = rt.block_on(async { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"{"session_id":"sess-c-abi-close-blocking","warehouse_id":"test_wh"}"#, - )) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/sessions/sess-c-abi-close-blocking")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let host = CString::new(uri.as_str()).unwrap(); - let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); - assert_eq!( - kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), - KernelStatusCode::Success - ); - let token = CString::new("dapi_test_token").unwrap(); - assert_eq!( - kernel_session_config_set_auth_pat(config, token.as_ptr()), - KernelStatusCode::Success - ); - - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - assert_eq!( - kernel_session_open(config, &mut session), - KernelStatusCode::Success - ); - assert!(!session.is_null()); - - // Blocking close: this must not return until the DELETE round-trip - // is done. - assert_eq!( - kernel_session_close_blocking(session), - KernelStatusCode::Success - ); - } - - // No polling loop: the DELETE must ALREADY be on the wire the instant - // the blocking close returned. A single synchronous check proves the - // await happened (vs. the fire-and-forget path, which needs polling). - let saw_delete = rt.block_on(async { - let requests = server.received_requests().await.unwrap_or_default(); - requests.iter().any(|r| { - r.method.as_str() == "DELETE" && r.url.path().ends_with("sess-c-abi-close-blocking") - }) - }); - assert!( - saw_delete, - "kernel_session_close_blocking must complete DeleteSession before returning" - ); -} - -/// A null handle is rejected with `InvalidArgument` and a stored last -/// error, never a crash — matching `kernel_session_close`'s null guard. -#[test] -fn session_close_blocking_null_handle_rejected() { - unsafe { - assert_eq!( - kernel_session_close_blocking(std::ptr::null_mut()), - KernelStatusCode::InvalidArgument - ); - } -} - -/// F3: `kernel_session_close_blocking_cancellable` honours the caller's cancel -/// token — a token fired from another thread while the DELETE is stalled -/// server-side unblocks the close promptly with `Cancelled`, instead of -/// blocking up to the retry ceiling. The session handle is still consumed on -/// the cancel path (the dropped future releases the boxed session), so there is -/// no free/close afterwards. -#[test] -fn session_close_blocking_cancellable_fires_during_stalled_delete() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let server = - rt.block_on(async { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"{"session_id":"sess-close-cancel","warehouse_id":"test_wh"}"#, - )) - .mount(&server) - .await; - // DELETE stalls 30s; the test fires cancel after ~200ms and must return - // long before that would elapse. - Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/sessions/sess-close-cancel")) - .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(30))) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let host = CString::new(uri.as_str()).unwrap(); - let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); - assert_eq!( - kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), - KernelStatusCode::Success - ); - let auth = CString::new("dapi_test_token").unwrap(); - assert_eq!( - kernel_session_config_set_auth_pat(config, auth.as_ptr()), - KernelStatusCode::Success - ); - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - assert_eq!( - kernel_session_open(config, &mut session), - KernelStatusCode::Success - ); - assert!(!session.is_null()); - - let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); - assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); - // Fire the token from a watcher thread after a short beat. - let tok_addr = tok as usize; - let watcher = thread::spawn(move || { - thread::sleep(Duration::from_millis(200)); - let t = tok_addr as *mut kernel_cancel_token_t; - assert_eq!(kernel_cancel_token_cancel(t), KernelStatusCode::Success); - }); - - let start = Instant::now(); - let rc = kernel_session_close_blocking_cancellable(session, tok); - let elapsed = start.elapsed(); - watcher.join().unwrap(); - - assert_eq!( - rc, - KernelStatusCode::Cancelled, - "a token fired during a stalled DELETE must unblock the close as Cancelled" - ); - assert!( - elapsed < Duration::from_secs(5), - "cancel must unblock the stalled close promptly, took {elapsed:?}" - ); - assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); - // No further close/free: the session was consumed on the cancel path. - } -} - -/// A NULL token makes `kernel_session_close_blocking_cancellable` behave exactly -/// like the plain `kernel_session_close_blocking`: it awaits the DELETE and -/// returns `Success`, with the DELETE observable immediately (no polling). -#[test] -fn session_close_blocking_cancellable_null_token_awaits_delete() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let server = - rt.block_on(async { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"{"session_id":"sess-close-nulltok","warehouse_id":"test_wh"}"#, - )) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/sessions/sess-close-nulltok")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - server - }); - let uri = server.uri(); - - unsafe { - let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - let host = CString::new(uri.as_str()).unwrap(); - let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); - assert_eq!( - kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), - KernelStatusCode::Success - ); - let auth = CString::new("dapi_test_token").unwrap(); - assert_eq!( - kernel_session_config_set_auth_pat(config, auth.as_ptr()), - KernelStatusCode::Success - ); - let mut session: *mut kernel_session_t = std::ptr::null_mut(); - assert_eq!( - kernel_session_open(config, &mut session), - KernelStatusCode::Success - ); - assert!(!session.is_null()); - - assert_eq!( - kernel_session_close_blocking_cancellable(session, std::ptr::null()), - KernelStatusCode::Success - ); - } - - let saw_delete = rt.block_on(async { - let requests = server.received_requests().await.unwrap_or_default(); - requests - .iter() - .any(|r| r.method.as_str() == "DELETE" && r.url.path().ends_with("sess-close-nulltok")) - }); - assert!( - saw_delete, - "a NULL token must await the DELETE like the plain blocking close" - ); -} From d1802db090c411288d182f44655a542b83bb2da5 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Mon, 20 Jul 2026 16:09:44 +0000 Subject: [PATCH 15/15] refactor(c-abi): inline block_on_ffi, drop now-orphaned ffi_prepare_runtime MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ffi_prepare_runtime() was extracted so block_on_ffi and block_on_ffi_cancellable could share the clear-error / reentrancy-reject / runtime-fetch preamble without drift. The cancellable path was dropped, so the helper had a single caller and its doc still referenced the removed block_on_ffi_cancellable. Fold the preamble back inline — block_on_ffi is now byte-for-byte identical to its pre-cancel-token (main) form. No behavior change. make check green. Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- src/c_abi/mod.rs | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 9bbaa38f..799c747a 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -117,14 +117,11 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime:: /// /// [`KernelStatusCode`]: crate::c_abi::KernelStatusCode /// [`Error`]: crate::kernel_error::Error -/// Shared preamble for the two `block_on_ffi*` entry shapes: clear the -/// thread-local last error, reject reentrancy from a Tokio runtime thread, and -/// fetch the process-wide runtime. On failure the typed [`Error`] is already -/// stored and the mapped [`KernelStatusCode`] is returned, so the caller just -/// propagates it. Kept in one place so the load-bearing threading-contract guard -/// (and its exact message) can't drift between `block_on_ffi` and -/// `block_on_ffi_cancellable`. -fn ffi_prepare_runtime() -> Result<&'static tokio::runtime::Runtime, KernelStatusCode> { +pub(crate) fn block_on_ffi(fut_builder: F) -> Result +where + F: FnOnce() -> Fut, + Fut: std::future::Future>, +{ error::clear_error(); // Reject reentrancy explicitly: calling `block_on` from within any // Tokio runtime would panic. Surface a typed, actionable error rather @@ -139,19 +136,14 @@ fn ffi_prepare_runtime() -> Result<&'static tokio::runtime::Runtime, KernelStatu error::store_error(e); return Err(code); } - runtime().map_err(|e| { - let code = KernelStatusCode::from(e.code); - error::store_error(e); - code - }) -} - -pub(crate) fn block_on_ffi(fut_builder: F) -> Result -where - F: FnOnce() -> Fut, - Fut: std::future::Future>, -{ - let rt = ffi_prepare_runtime()?; + let rt = match runtime() { + Ok(rt) => rt, + Err(e) => { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + return Err(code); + } + }; // Catch panics so a kernel bug can't unwind across `extern "C"`. let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rt.block_on(fut_builder())));