diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index fb766388..3e4cabfe 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -336,20 +336,53 @@ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* con KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config, const char* name, const char* value); -/* Initialize kernel logging, process-wide and ONCE (first call wins; +/* Initialize kernel logging, process-wide and ONCE (first non-OFF call wins; * later calls are no-ops). `level` is OFF/ERROR/WARN/INFO/DEBUG/TRACE * (NULL → RUST_LOG, default warn); `file_path` NULL → stderr. Not tied to - * a session — lets a host route kernel logs into its own log file. - * - * A non-UTF-8 `file_path` returns InvalidArgument. Otherwise the result - * reflects the FIRST call's outcome (a later call's level/file have no - * effect and are not described by its return): Success when logging was - * installed against the request (or skipped for level OFF); Internal (with - * a stored last-error) when that install did not fully honour the request - * — the file could not be opened (falls back to stderr) or a global - * subscriber was already installed (no kernel subscriber installed). */ + * a session — lets a host route kernel logs into its own log file. OFF returns + * Success without installing a subscriber or consuming the once-only slot, so + * a later non-OFF initializer can still win. + * + * A non-UTF-8 `file_path` returns InvalidArgument. OFF behaves as described + * above. For a non-OFF call, the result reflects the first non-OFF call's + * outcome (a later call's level/file have no effect and are not described by + * its return): Success when logging was installed against the request; Internal + * (with a stored last-error) when that install did not fully honour the request + * — the file could not be opened (falls back to stderr), a callback sink from + * an earlier kernel_init_logging_callback already won (this file/stderr + * request had no effect), or another component already owns the global + * subscriber (no kernel subscriber installed). */ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); +/* One callback-delivered kernel log record. `message` contains the rendered + * event text and fields recorded directly on that event; fields attached only + * to enclosing spans are not included. Delivery is synchronous on the thread + * that emitted the record: the callback must return promptly, or it will delay + * that kernel operation. Hosts that need asynchronous logging can copy the + * record into their own bounded queue and return. Strings are valid only during + * the callback. Calls may be concurrent; copy retained strings and synchronize + * the destination. `user_data` is the pointer supplied at initialization. */ +typedef void (*KernelLogCallback)(const char* level, const char* target, + const char* message, void* user_data); + +/* Initialize kernel logging through a host callback. The level and process-wide + * first-non-OFF-call-wins behavior match kernel_init_logging. OFF returns + * Success without installing a subscriber or consuming the once-only slot, so + * a later non-OFF initializer can still win. The callback must remain valid for + * the process lifetime, return promptly, must not unwind, and must not re-enter + * the kernel C ABI. A NULL callback returns InvalidArgument. Returns Internal + * (with a stored last-error) when the callback was NOT installed because a + * file/stderr sink from an earlier + * kernel_init_logging already won, a different callback from an earlier + * kernel_init_logging_callback already won, or another component owns the global + * subscriber; Success means level OFF was requested (which installs nothing and + * does not consume the initialization slot) or this exact callback + user_data + * is the installed sink (a later call with the identical callback and user_data + * also succeeds). */ +KernelStatusCode kernel_init_logging_callback(const char* level, + KernelLogCallback callback, + void* user_data); + /* ─── Proxy / TLS (optional) ────────────────────────────────────────── * * All optional; defaults are: no explicit proxy (reqwest honours diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index fac4834e..f5243007 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -76,16 +76,16 @@ thread_local! { /// bytes with `?` so a message that happens to contain `\0` can't make /// `CString::new` fail (which would lose the error detail entirely). /// -/// Shared by the error-path `KernelError.query_id` and the success-path -/// `kernel_executed_statement_query_id`, so both accessors have identical -/// interior-NUL semantics (strip → `?`, never discard the whole value). +/// Shared by every Rust-to-C string path that accepts arbitrary Rust text, +/// including errors, statement IDs, and callback-delivered log records, so +/// they have identical interior-NUL semantics (`\0` → `?`). pub(crate) fn to_cstring_lossy(s: &str) -> CString { // Fast path: no interior NUL. match CString::new(s) { Ok(c) => c, Err(_) => { let sanitised: String = s.chars().map(|c| if c == '\0' { '?' } else { c }).collect(); - CString::new(sanitised).unwrap_or_else(|_| CString::new("").expect("empty CString")) + CString::new(sanitised).unwrap_or_default() } } } diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 8ee10802..8d57925d 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -51,8 +51,25 @@ pub mod result; pub mod session; pub mod statement; +use std::ffi::{c_char, c_void}; use std::sync::OnceLock; +/// Host callback invoked for one kernel log record. +/// +/// The message contains the rendered event text and fields recorded directly +/// on that event, not fields attached only to enclosing spans. String pointers +/// are non-null and valid only for the duration of the callback. Delivery is +/// synchronous on the emitting thread, and callbacks may run concurrently on +/// multiple kernel threads. Consumers must return promptly, copy any strings +/// they retain, and synchronize their sink. A consumer that needs asynchronous +/// delivery can enqueue its own owned record before returning. +pub type KernelLogCallback = unsafe extern "C" fn( + level: *const c_char, + target: *const c_char, + message: *const c_char, + user_data: *mut c_void, +); + /// Process-wide tokio runtime owned by the C ABI. /// /// Rust-crate consumers (PyO3 / napi-rs) own their own runtime and call diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 9467c97b..79dd2e4d 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -31,6 +31,7 @@ use crate::config::{ TlsConfig, TokenCacheConfig, }; use crate::kernel_error::Error; +use crate::logging::{LoggingOutcome, LoggingSink}; use crate::session::Session; use crate::telemetry::DriverSystemConfiguration; use std::collections::HashMap; @@ -765,28 +766,53 @@ pub unsafe extern "C" fn kernel_session_config_set_driver_system_configuration( }) } +#[derive(Debug, PartialEq, Eq)] +enum LogLevelResolution { + Off, + Filter(Option), +} + +/// Parse the C ABI's best-effort bare log level into the shared subscriber +/// filter representation. Invalid UTF-8 is treated like NULL and falls back to +/// `RUST_LOG`; OFF intentionally skips subscriber installation without +/// consuming the process-wide initialization slot. +unsafe fn resolve_log_level(level: *const c_char) -> LogLevelResolution { + let level = unsafe { optional_str(level, "log level") }.ok().flatten(); + if level + .as_deref() + .is_some_and(|value| value.eq_ignore_ascii_case("off")) + { + LogLevelResolution::Off + } else { + LogLevelResolution::Filter(level.as_deref().map(crate::logging::filter_from_level)) + } +} + /// Initialize kernel logging, **process-wide and once**. `level` is one /// of "OFF"/"ERROR"/"WARN"/"INFO"/"DEBUG"/"TRACE" (NULL ⇒ honour /// `RUST_LOG`, default `warn`); `file_path` is a log file (NULL ⇒ stderr). /// /// Idempotent: the underlying `tracing` subscriber can only be installed -/// once per process, so the **first** call wins and later calls are +/// once per process, so the **first non-OFF** call wins and later calls are /// no-ops (a driver that opens many connections calls this each time with -/// the same target — only the first takes effect). Not tied to a session; -/// call it before/around `kernel_session_open`. Lets an ODBC/Go host route -/// the kernel's logs into the same file it writes its own logs to. +/// the same target — only the first takes effect). `OFF` returns `Success` +/// without installing a subscriber or consuming that once-only slot, so a +/// later non-OFF initializer can still win. Not tied to a session; call it +/// before/around `kernel_session_open`. Lets an ODBC/Go host route the kernel's +/// logs into the same file it writes its own logs to. /// /// A non-UTF-8 `file_path` returns `InvalidArgument` (the requested path -/// can't be honoured). Otherwise returns `Success` when the FIRST call -/// installed logging against the requested destination (or was skipped for -/// level `OFF`), or `Internal` (with a stored last-error) when that first -/// install did not fully honour the request — the log file couldn't be -/// opened (logging fell back to stderr) or a global subscriber was already -/// installed (no kernel subscriber installed). Because init is -/// once-per-process, the Success/Internal result reflects the **first** -/// call's outcome, NOT a later call's `level`/`file_path` (which have no -/// effect). A caller that can't see stderr can use `Internal` to surface -/// the degradation. +/// can't be honoured). `OFF` behaves as described above. For a non-OFF call, +/// returns `Success` when the first non-OFF call installed file/stderr logging +/// against the requested destination, or `Internal` (with a stored last-error) +/// when that first install did not fully honour the request — the log file +/// couldn't be opened (logging fell back to stderr), a callback sink from an +/// earlier `kernel_init_logging_callback` already won (this file/stderr +/// request had no effect), or another component already owns the global +/// subscriber (no kernel subscriber installed). Because init is +/// once-per-process, the Success/Internal result reflects the **first non-OFF** +/// call's outcome, NOT a later call's `level`/`file_path` (which have no effect). +/// A caller that can't see stderr can use `Internal` to surface the degradation. /// /// # Safety /// `level` / `file_path`, if non-null, must be NUL-terminated C strings. @@ -796,22 +822,10 @@ pub unsafe extern "C" fn kernel_init_logging( file_path: *const c_char, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); - // `level` is best-effort: a non-UTF-8 or unrecognized value falls back - // to RUST_LOG / the default, so treat a bad level as absent. - let level = optional_str(level, "log level").ok().flatten(); - // Level "OFF" means "do not install a subscriber", but that is still an - // intentional, successful outcome. `init_logging` no longer special-cases - // it (it works on full EnvFilter directives), so honour OFF here before - // touching the file path. - if level - .as_deref() - .is_some_and(|l| l.eq_ignore_ascii_case("off")) - { - return KernelStatusCode::Success; - } - // The C ABI takes a BARE level; expand it to the full directive the - // shared installer expects (targeting the kernel's own log target). - let filter = level.as_deref().map(crate::logging::filter_from_level); + let filter = match unsafe { resolve_log_level(level) } { + LogLevelResolution::Off => return KernelStatusCode::Success, + LogLevelResolution::Filter(filter) => filter, + }; // `file_path` is NOT best-effort: a non-UTF-8 path is a real error (the // caller asked us to write there and we can't), so surface it rather // than silently dropping the path and reporting Success. @@ -819,15 +833,122 @@ pub unsafe extern "C" fn kernel_init_logging( Ok(f) => f.map(std::path::PathBuf::from), Err(e) => return crate::c_abi::error::store_and_code(e), }; - if crate::logging::init_logging(&crate::logging::LogConfig { filter, file }) { - KernelStatusCode::Success - } else { - crate::c_abi::error::store_and_code(Error::new( + match crate::logging::init_logging(&crate::logging::LogConfig { filter, file }) { + LoggingOutcome::Installed { + sink: LoggingSink::FileOrStderr, + file_honored: true, + } => KernelStatusCode::Success, + LoggingOutcome::Installed { + sink: LoggingSink::FileOrStderr, + file_honored: false, + } => crate::c_abi::error::store_and_code(Error::new( + crate::kernel_error::ErrorCode::Internal, + "kernel_init_logging: the requested log file could not be opened; kernel logs fell \ + back to stderr", + )), + LoggingOutcome::Installed { + sink: LoggingSink::Callback { .. }, + .. + } => crate::c_abi::error::store_and_code(Error::new( + crate::kernel_error::ErrorCode::Internal, + "kernel_init_logging: a callback log sink was already installed by an earlier \ + kernel_init_logging_callback; this file/stderr request had no effect (first \ + initializer wins)", + )), + LoggingOutcome::Foreign => crate::c_abi::error::store_and_code(Error::new( crate::kernel_error::ErrorCode::Internal, - "kernel_init_logging: logging was not fully initialized as requested (the log file \ - could not be opened, or a global subscriber was already installed); kernel logs may \ - go to stderr or not flow", - )) + "kernel_init_logging: a global tracing subscriber was already installed by another \ + component; no kernel subscriber was installed and kernel logs will not flow", + )), + } +} + +/// Initialize process-wide kernel logging through a host callback. +/// +/// This is the callback counterpart to [`kernel_init_logging`]. `level` has +/// the same OFF/ERROR/WARN/INFO/DEBUG/TRACE semantics (NULL honors `RUST_LOG`, +/// defaulting to WARN). The first non-OFF logging initializer in the process +/// wins; subsequent callback or file/stderr initializer calls are no-ops +/// reporting that first call's outcome. `OFF` returns `Success` without +/// installing a subscriber or consuming the once-only slot, so a later non-OFF +/// initializer can still win. +/// +/// The callback receives lower-case `level`, the tracing `target`, and the +/// rendered event message including fields recorded directly on that event. +/// Fields attached only to enclosing spans are not included. Delivery is +/// synchronous on the thread that emitted the record, so the callback must +/// return promptly; a host that needs asynchronous delivery can copy the record +/// into its own queue. String pointers are valid only until the callback returns, +/// and calls may be concurrent. The callback must not unwind, re-enter the kernel +/// C ABI, or emit another kernel tracing event. `user_data` is passed through +/// unchanged and must remain valid for the process lifetime. +/// +/// Returns `InvalidArgument` when `callback` is NULL. Returns `Internal` +/// (with a stored last-error) when the callback was not installed: a +/// file/stderr sink from an earlier `kernel_init_logging` already won, a +/// *different* callback from an earlier `kernel_init_logging_callback` already +/// won, or another component owns the process-global tracing slot (in every +/// case this callback receives no records). Because init is once-per-process, +/// this reflects the **first non-OFF** initializer's outcome. Thus `Success` +/// means either level `OFF` was requested (which installs nothing and does not +/// consume the initialization slot) or *this exact* callback + `user_data` is +/// the installed sink — a later call with the identical callback and +/// `user_data` also succeeds (it is that sink). +/// +/// # Safety +/// `level`, if non-null, must be a NUL-terminated C string. `callback` and +/// `user_data` must satisfy the lifetime and threading contract above. +#[no_mangle] +pub unsafe extern "C" fn kernel_init_logging_callback( + level: *const c_char, + callback: Option, + user_data: *mut std::ffi::c_void, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(callback) = callback else { + return crate::c_abi::error::store_and_code( + Error::invalid_argument().message("kernel log callback must not be NULL"), + ); + }; + + let filter = match unsafe { resolve_log_level(level) } { + LogLevelResolution::Off => return KernelStatusCode::Success, + LogLevelResolution::Filter(filter) => filter, + }; + + match crate::logging::init_callback_logging(filter, callback, user_data) { + // Success only when the installed callback sink is *this* exact + // registration (same function pointer + user_data). A later, different + // callback loses to the first-call-wins install and must not be told it + // is live — otherwise a host believes a callback that will never fire. + LoggingOutcome::Installed { + sink: + LoggingSink::Callback { + callback: won, + user_data: won_ud, + }, + .. + } if won == callback as usize && won_ud == user_data as usize => KernelStatusCode::Success, + LoggingOutcome::Installed { + sink: LoggingSink::Callback { .. }, + .. + } => crate::c_abi::error::store_and_code(Error::internal().message( + "kernel_init_logging_callback: a different callback sink was already installed by an \ + earlier kernel_init_logging_callback; this callback was NOT installed and will \ + receive no records (first initializer wins)", + )), + LoggingOutcome::Installed { + sink: LoggingSink::FileOrStderr, + .. + } => crate::c_abi::error::store_and_code(Error::internal().message( + "kernel_init_logging_callback: a file/stderr log sink was already installed by an \ + earlier kernel_init_logging; the callback was NOT installed and will receive no \ + records (first initializer wins)", + )), + LoggingOutcome::Foreign => crate::c_abi::error::store_and_code(Error::internal().message( + "kernel_init_logging_callback: a global tracing subscriber was already installed by \ + another component; the callback was NOT installed and will receive no records", + )), } } @@ -1895,6 +2016,29 @@ mod tests { } } + #[test] + fn resolve_log_level_preserves_shared_c_abi_semantics() { + let off = CString::new("oFf").unwrap(); + let debug = CString::new("DEBUG").unwrap(); + let invalid_utf8 = [0xff_u8, 0]; + + unsafe { + assert_eq!(resolve_log_level(off.as_ptr()), LogLevelResolution::Off); + assert_eq!( + resolve_log_level(debug.as_ptr()), + LogLevelResolution::Filter(Some("databricks::sql::kernel=debug".to_string())) + ); + assert_eq!( + resolve_log_level(std::ptr::null()), + LogLevelResolution::Filter(None) + ); + assert_eq!( + resolve_log_level(invalid_utf8.as_ptr().cast()), + LogLevelResolution::Filter(None) + ); + } + } + #[test] fn parse_scopes_trims_and_drops_empties() { assert_eq!( diff --git a/src/logging.rs b/src/logging.rs index e7196cfe..9d7024e9 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -52,21 +52,57 @@ #![allow(dead_code)] +use std::ffi::c_void; use std::path::{Path, PathBuf}; use std::sync::OnceLock; +use tracing::field::{Field, Visit}; +use tracing::{Event, Subscriber}; use tracing_subscriber::{ fmt::{self, time::SystemTime}, - layer::SubscriberExt, + layer::{Context, SubscriberExt}, + registry::LookupSpan, util::SubscriberInitExt, - EnvFilter, + EnvFilter, Layer, }; -/// Records the outcome of the first `init_logging` call: `true` if the -/// subscriber was installed (or intentionally skipped for level=OFF), -/// `false` if it could not be installed (e.g. the log file failed to -/// open). Later calls return this same first-call outcome ("first call -/// wins"). -static LOGGING_INITIALIZED: OnceLock = OnceLock::new(); +/// Which kind of sink the first `init_*` call installed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum LoggingSink { + /// A file (or stderr-fallback) `fmt` subscriber, from [`init_logging`]. + FileOrStderr, + /// A host-callback subscriber, from [`init_callback_logging`]. Carries the + /// winning callback's identity — the function-pointer and `user_data` + /// addresses — so a *later, different* callback registration can be told it + /// did not win (install is first-call-wins) instead of a misleading success + /// that would leave a host believing a dropped callback is live. A later + /// registration of the *same* identity is the installed sink, so it still + /// succeeds. + Callback { callback: usize, user_data: usize }, +} + +/// Outcome of the process-global logging install, recorded once by the +/// **first** `init_*` call ("first call wins") and returned verbatim to every +/// later call. Replaces a lossy `bool` so a later initializer can report +/// precisely what happened: whether *its* kind of sink won, whether a +/// *different* kernel sink already won (so its own request had no effect), or +/// whether another component owns the global tracing slot. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum LoggingOutcome { + /// The kernel installed a subscriber. `sink` is which kind; `file_honored` + /// is false only when a requested log file could not be opened and logging + /// fell back to stderr (meaningful for [`LoggingSink::FileOrStderr`]). + Installed { + sink: LoggingSink, + file_honored: bool, + }, + /// No kernel subscriber was installed: another component already owns the + /// process-global tracing slot. + Foreign, +} + +/// Records the outcome of the first `init_*` call; later calls return this +/// same first-call outcome ("first call wins"). +static LOGGING_INITIALIZED: OnceLock = OnceLock::new(); /// Default log file name created inside a destination that names a /// directory (see [`resolve_log_file`]). @@ -106,6 +142,12 @@ pub(crate) fn filter_from_level(level: &str) -> String { ) } +/// Resolve the shared default filter for every logging destination: honor +/// `RUST_LOG`, then fall back to warnings from the kernel target. +fn default_env_filter() -> EnvFilter { + EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(filter_from_level("warn"))) +} + /// Resolve a configured log destination to the actual file path to open. /// /// A destination that names an **existing directory**, or that ends with a @@ -143,23 +185,19 @@ pub(crate) fn resolve_log_file(path: &Path) -> PathBuf { /// filter / file — has no effect and its return does not describe its own /// arguments). /// -/// Returns `true` if the first call installed the subscriber against the -/// requested destination. Returns `false` if that install did not fully -/// honour the request — either the requested log file could not be opened -/// (logging fell back to stderr) or the global subscriber was already -/// installed by another component (so no kernel subscriber was installed). -/// Callers that cannot see stderr (GUI / BI hosts) can use `false` to -/// surface the degradation. -pub(crate) fn init_logging(config: &LogConfig) -> bool { +/// Returns the [`LoggingOutcome`] recorded by the **first** call: the +/// installed sink kind plus whether a requested file was honoured, or +/// [`LoggingOutcome::Foreign`] when another component already owns the global +/// tracing slot (so no kernel subscriber was installed). Callers that cannot +/// see stderr (GUI / BI hosts) can inspect it to surface a degradation. +pub(crate) fn init_logging(config: &LogConfig) -> LoggingOutcome { *LOGGING_INITIALIZED.get_or_init(|| { // Use the caller's full directive verbatim; otherwise fall back to // RUST_LOG, then to a warn default on the kernel's own target. let filter = if let Some(ref directive) = config.filter { EnvFilter::new(directive.clone()) } else { - EnvFilter::try_from_default_env().unwrap_or_else(|_| { - EnvFilter::new(format!("{}=warn", crate::klog::KERNEL_LOG_TARGET)) - }) + default_env_filter() }; // Resolve a directory-form destination to a file inside it, then try @@ -207,9 +245,167 @@ pub(crate) fn init_logging(config: &LogConfig) -> bool { .try_init() .is_ok() }; - // Success only if the subscriber installed AND the requested file - // (if any) was honoured. - installed && file_requested_ok + if installed { + LoggingOutcome::Installed { + sink: LoggingSink::FileOrStderr, + file_honored: file_requested_ok, + } + } else { + LoggingOutcome::Foreign + } + }) +} + +/// Collect a tracing event's message and event-local fields into one line. +#[derive(Default)] +struct CallbackMessageVisitor { + message: String, + fields: String, +} + +impl CallbackMessageVisitor { + 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 CallbackMessageVisitor { + 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()); + } + } +} + +struct CallbackLogLayer { + callback: crate::c_abi::KernelLogCallback, + user_data: usize, +} + +thread_local! { + /// Set while this thread is inside a callback delivery. If the host + /// callback re-enters the kernel logging path (emits a kernel tracing + /// event — a contract violation), the nested dispatch lands back in + /// [`CallbackLogLayer::on_event`] on the same thread; this flag lets it + /// drop the nested record instead of recursing without bound. + static IN_CALLBACK: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +impl Layer for CallbackLogLayer +where + S: Subscriber + for<'a> LookupSpan<'a>, +{ + fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { + // `on_event` runs inline on whatever thread emitted the record — + // including tokio workers driving async FFI calls — so an unwind here + // (a misbehaving callback, or a field `Debug` impl) would tear through + // tracing's dispatch and abort in-flight work. Catch it at this + // boundary, mirroring the `catch_ffi` / `block_on_ffi` guards on the + // C-ABI entry points. A caught panic is dropped: it cannot be logged + // from here without recursing into this same layer. + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + // Reentrancy guard (see `IN_CALLBACK`): drop a nested record rather + // than recurse. The `Drop` reset runs on the normal path and while + // unwinding, so the flag never sticks `true`. + if IN_CALLBACK.with(|active| active.replace(true)) { + return; + } + struct ResetOnDrop; + impl Drop for ResetOnDrop { + fn drop(&mut self) { + IN_CALLBACK.with(|active| active.set(false)); + } + } + let _reset = ResetOnDrop; + + let metadata = event.metadata(); + let mut visitor = CallbackMessageVisitor::default(); + event.record(&mut visitor); + + let level = crate::c_abi::error::to_cstring_lossy( + &metadata.level().to_string().to_ascii_lowercase(), + ); + let target = crate::c_abi::error::to_cstring_lossy(metadata.target()); + let message = crate::c_abi::error::to_cstring_lossy(&visitor.finish()); + + // Deliver inline so hosts that want the same synchronous sink + // semantics as their native logger do not lose or reorder records. + // A host that prefers asynchronous delivery can enqueue in its + // callback. SAFETY: the caller supplied a valid process-lifetime + // callback and user-data pointer under `kernel_init_logging_callback`'s + // contract. The C strings remain alive until the callback returns. + unsafe { + (self.callback)( + level.as_ptr(), + target.as_ptr(), + message.as_ptr(), + self.user_data as *mut c_void, + ); + } + })); + } +} + +/// Install a process-wide subscriber that forwards records to a host callback. +/// +/// Shares [`LOGGING_INITIALIZED`] with file/stderr logging, preserving the +/// existing first-call-wins contract across every C and direct-Rust entry +/// point. Returns the [`LoggingOutcome`] of the **first** initializer: when a +/// file/stderr sink already won, that outcome names [`LoggingSink::FileOrStderr`] +/// and this callback was **not** installed (it will receive no records), so the +/// caller must not report success. +pub(crate) fn init_callback_logging( + filter: Option, + callback: crate::c_abi::KernelLogCallback, + user_data: *mut c_void, +) -> LoggingOutcome { + *LOGGING_INITIALIZED.get_or_init(|| { + let filter = filter.map_or_else(default_env_filter, EnvFilter::new); + + let installed = tracing_subscriber::registry() + .with(filter) + .with(CallbackLogLayer { + callback, + user_data: user_data as usize, + }) + .try_init() + .is_ok(); + if installed { + LoggingOutcome::Installed { + sink: LoggingSink::Callback { + callback: callback as usize, + user_data: user_data as usize, + }, + file_honored: true, + } + } else { + LoggingOutcome::Foreign + } }) } @@ -297,7 +493,7 @@ mod tests { #[test] fn log_target_is_double_colon_delimited() { assert_eq!(crate::klog::KERNEL_LOG_TARGET, "databricks::sql::kernel"); - // The directive we build (see init_logging) must use this exact + // The directive we build (see default_env_filter) must use this exact // target, not an underscore-joined token. let directive = format!("{}=debug", crate::klog::KERNEL_LOG_TARGET); assert!(directive.starts_with("databricks::sql::kernel=")); diff --git a/src/session.rs b/src/session.rs index 167b8db1..5801182a 100644 --- a/src/session.rs +++ b/src/session.rs @@ -391,11 +391,10 @@ impl Session { .connection() .emit_operation(OperationType::CreateSession, create_elapsed, None); - // 5. Tag the per-session tracing span. Future log lines - // inherit `session_id` automatically. Target is pinned to the - // kernel log target so the span (and any `log` record derived - // from it) maps to the `databricks.sql.kernel` Python logger, - // consistent with `klog` events — see `crate::klog`. + // 5. Tag the per-session tracing span. Span-aware subscribers such as + // the file/stderr formatter attach `session_id` automatically; + // host bridges that forward only event-local fields do not. Pin the + // target so span-aware filtering stays consistent with `klog` events. let log_span = info_span!( target: crate::klog::KERNEL_LOG_TARGET, "kernel.session", diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 851005d9..0984106f 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -259,13 +259,31 @@ static void test_client_conf_setter(void) { CHECK(rc == KernelStatusCode_InvalidArgument, "set_client_conf(NULL cfg) → InvalidArgument"); } -/* kernel_init_logging is idempotent and null-tolerant. */ +static void capture_log(const char* level, const char* target, + const char* message, void* user_data) { + (void)level; + (void)target; + (void)message; + (void)user_data; +} + +/* Logging initialization is idempotent; callback registration rejects NULL. */ static void test_init_logging(void) { - KernelStatusCode rc = kernel_init_logging("WARN", NULL); + KernelStatusCode rc = kernel_init_logging_callback("WARN", NULL, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, + "init_logging_callback(NULL callback) rejects invalid input"); + + rc = kernel_init_logging("WARN", NULL); CHECK(rc == KernelStatusCode_Success, "init_logging(level, NULL file) succeeds"); /* Second call is a no-op (subscriber already installed) but still Success. */ rc = kernel_init_logging(NULL, NULL); CHECK(rc == KernelStatusCode_Success, "init_logging twice is safe"); + /* A callback initializer AFTER a file/stderr sink already won reports that + * the callback was NOT installed (first initializer wins) rather than a + * misleading Success, so a host never believes its callback is live. */ + rc = kernel_init_logging_callback(NULL, capture_log, NULL); + CHECK(rc == KernelStatusCode_Internal, + "init_logging_callback after file/stderr sink won → Internal (callback not installed)"); } /* is_open null-guards its args. (The true→false behavior is covered by the diff --git a/tests/c_abi_logging_callback.rs b/tests/c_abi_logging_callback.rs new file mode 100644 index 00000000..3a25dec4 --- /dev/null +++ b/tests/c_abi_logging_callback.rs @@ -0,0 +1,86 @@ +// 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. + +use databricks_sql_kernel::c_abi::session::kernel_init_logging_callback; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use databricks_sql_kernel::KERNEL_LOG_TARGET; +use std::ffi::{c_char, c_void, CStr, CString}; +use std::sync::Mutex; + +#[derive(Debug)] +struct Record { + level: String, + target: String, + message: String, + user_data: usize, +} + +static RECORDS: Mutex> = Mutex::new(Vec::new()); + +unsafe extern "C" fn capture_log( + level: *const c_char, + target: *const c_char, + message: *const c_char, + user_data: *mut c_void, +) { + // SAFETY: the callback contract guarantees non-null, NUL-terminated + // strings that remain valid for this invocation. + let level = unsafe { CStr::from_ptr(level) } + .to_string_lossy() + .into_owned(); + // SAFETY: same callback contract as above. + let target = unsafe { CStr::from_ptr(target) } + .to_string_lossy() + .into_owned(); + // SAFETY: same callback contract as above. + let message = unsafe { CStr::from_ptr(message) } + .to_string_lossy() + .into_owned(); + RECORDS.lock().unwrap().push(Record { + level, + target, + message, + user_data: user_data as usize, + }); +} + +#[test] +fn callback_receives_kernel_log_record() { + let level = CString::new("DEBUG").unwrap(); + let user_data = 0x1234usize as *mut c_void; + + // SAFETY: the callback and user-data sentinel remain valid for the process + // lifetime, and `level` is a valid NUL-terminated string. + let status = + unsafe { kernel_init_logging_callback(level.as_ptr(), Some(capture_log), user_data) }; + assert_eq!(status, KernelStatusCode::Success); + + tracing::debug!( + target: KERNEL_LOG_TARGET, + answer = 42, + "callback bridge smoke" + ); + + // Delivery is deliberately synchronous: when the tracing call returns, the + // host sink has accepted the record. Hosts that want buffering own that policy. + let records = RECORDS.lock().unwrap(); + let record = records + .iter() + .find(|record| record.message.contains("callback bridge smoke")) + .expect("kernel tracing record must reach the C callback"); + assert_eq!(record.level, "debug"); + assert_eq!(record.target, KERNEL_LOG_TARGET); + assert!(record.message.contains("answer=42")); + assert_eq!(record.user_data, 0x1234); +} diff --git a/tests/c_abi_logging_callback_conflict.rs b/tests/c_abi_logging_callback_conflict.rs new file mode 100644 index 00000000..59090f5c --- /dev/null +++ b/tests/c_abi_logging_callback_conflict.rs @@ -0,0 +1,100 @@ +// 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. + +//! First-call-wins identity for the callback log sink: a second, *different* +//! callback registration must report that it was NOT installed (`Internal`), +//! not a misleading `Success` that leaves a host believing a dropped callback +//! is live — and only the winning callback receives records. This is its own +//! test binary because the kernel tracing subscriber is process-wide and +//! installed exactly once per process. + +use databricks_sql_kernel::c_abi::session::kernel_init_logging_callback; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use databricks_sql_kernel::KERNEL_LOG_TARGET; +use std::ffi::{c_char, c_void, CString}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +static A_HITS: AtomicUsize = AtomicUsize::new(0); +static B_HITS: AtomicUsize = AtomicUsize::new(0); + +// Two callbacks with distinct bodies (different counters) and distinct +// user_data, so their identities differ even if the compiler folds identical +// function bodies — the registration is keyed on (callback, user_data). +unsafe extern "C" fn callback_a( + _level: *const c_char, + _target: *const c_char, + _message: *const c_char, + _user_data: *mut c_void, +) { + A_HITS.fetch_add(1, Ordering::SeqCst); +} + +unsafe extern "C" fn callback_b( + _level: *const c_char, + _target: *const c_char, + _message: *const c_char, + _user_data: *mut c_void, +) { + B_HITS.fetch_add(1, Ordering::SeqCst); +} + +#[test] +fn second_distinct_callback_registration_is_rejected() { + let level = CString::new("DEBUG").unwrap(); + let ud_a = 0xA_usize as *mut c_void; + let ud_b = 0xB_usize as *mut c_void; + + // A wins the process-global, first-call-wins install. + // SAFETY: `callback_a`/`ud_a` remain valid for the process lifetime and + // `level` is a valid NUL-terminated string. + let status_a = unsafe { kernel_init_logging_callback(level.as_ptr(), Some(callback_a), ud_a) }; + assert_eq!( + status_a, + KernelStatusCode::Success, + "the first callback must install" + ); + + // Re-registering the *identical* callback + user_data is idempotent: that + // identity IS the installed sink, so it still succeeds. + // SAFETY: same contract as above. + let status_a_again = + unsafe { kernel_init_logging_callback(level.as_ptr(), Some(callback_a), ud_a) }; + assert_eq!( + status_a_again, + KernelStatusCode::Success, + "re-registering the identical callback must stay Success" + ); + + // B is a *different* callback (and different user_data). It loses to the + // first-call-wins install and must be told so — not a misleading Success. + // SAFETY: same contract as above. + let status_b = unsafe { kernel_init_logging_callback(level.as_ptr(), Some(callback_b), ud_b) }; + assert_eq!( + status_b, + KernelStatusCode::Internal, + "a different second callback must report it was not installed" + ); + + // Delivery goes only to the winner: A receives the event, B never does. + tracing::debug!(target: KERNEL_LOG_TARGET, "callback identity probe"); + assert!( + A_HITS.load(Ordering::SeqCst) > 0, + "the winning callback must receive records" + ); + assert_eq!( + B_HITS.load(Ordering::SeqCst), + 0, + "the rejected callback must receive nothing" + ); +} diff --git a/tests/c_abi_logging_callback_panic.rs b/tests/c_abi_logging_callback_panic.rs new file mode 100644 index 00000000..381750f9 --- /dev/null +++ b/tests/c_abi_logging_callback_panic.rs @@ -0,0 +1,78 @@ +// 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. + +//! Panic-containment regression coverage for callback logging. This lives in a +//! separate test binary because the tracing subscriber is process-global. + +use databricks_sql_kernel::c_abi::session::kernel_init_logging_callback; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use databricks_sql_kernel::KERNEL_LOG_TARGET; +use std::ffi::{c_char, c_void, CString}; +use std::fmt; +use std::sync::atomic::{AtomicUsize, Ordering}; + +static CALLBACK_HITS: AtomicUsize = AtomicUsize::new(0); + +struct PanickingDebug; + +impl fmt::Debug for PanickingDebug { + fn fmt(&self, _formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + panic!("debug formatting panic probe"); + } +} + +unsafe extern "C" fn capture_callback( + _level: *const c_char, + _target: *const c_char, + _message: *const c_char, + _user_data: *mut c_void, +) { + CALLBACK_HITS.fetch_add(1, Ordering::SeqCst); +} + +#[test] +fn field_debug_panic_is_contained_and_delivery_resets() { + let level = CString::new("DEBUG").unwrap(); + + // SAFETY: the callback is process-lifetime and level is NUL-terminated. + let status = unsafe { + kernel_init_logging_callback(level.as_ptr(), Some(capture_callback), std::ptr::null_mut()) + }; + assert_eq!(status, KernelStatusCode::Success); + + let before_panic = CALLBACK_HITS.load(Ordering::SeqCst); + let emit_result = std::panic::catch_unwind(|| { + tracing::debug!( + target: KERNEL_LOG_TARGET, + panicking = ?PanickingDebug, + "panic containment probe" + ); + }); + assert!( + emit_result.is_ok(), + "a field Debug panic must not escape callback delivery" + ); + assert_eq!( + CALLBACK_HITS.load(Ordering::SeqCst), + before_panic, + "an event that fails during formatting must not be delivered" + ); + + tracing::debug!(target: KERNEL_LOG_TARGET, "post-panic reset probe"); + assert_eq!( + CALLBACK_HITS.load(Ordering::SeqCst), + before_panic + 1, + "delivery must resume after the contained panic" + ); +} diff --git a/tests/c_abi_logging_callback_reentrancy.rs b/tests/c_abi_logging_callback_reentrancy.rs new file mode 100644 index 00000000..6528858c --- /dev/null +++ b/tests/c_abi_logging_callback_reentrancy.rs @@ -0,0 +1,73 @@ +// 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. + +//! Reentrancy regression coverage for callback logging. This lives in a +//! separate test binary because the tracing subscriber is process-global. + +use databricks_sql_kernel::c_abi::session::kernel_init_logging_callback; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use databricks_sql_kernel::KERNEL_LOG_TARGET; +use std::ffi::{c_char, c_void, CStr, CString}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +static CALLBACK_HITS: AtomicUsize = AtomicUsize::new(0); + +unsafe extern "C" fn reentrant_callback( + _level: *const c_char, + _target: *const c_char, + message: *const c_char, + _user_data: *mut c_void, +) { + CALLBACK_HITS.fetch_add(1, Ordering::SeqCst); + + // SAFETY: the callback contract guarantees a valid NUL-terminated string + // for the duration of this call. + let message = unsafe { CStr::from_ptr(message) }.to_string_lossy(); + if message.contains("outer reentrancy probe") { + tracing::debug!( + target: KERNEL_LOG_TARGET, + "nested reentrancy probe must be dropped" + ); + } +} + +#[test] +fn callback_reemission_is_dropped_without_double_delivery() { + let level = CString::new("DEBUG").unwrap(); + + // SAFETY: the callback is process-lifetime and level is NUL-terminated. + let status = unsafe { + kernel_init_logging_callback( + level.as_ptr(), + Some(reentrant_callback), + std::ptr::null_mut(), + ) + }; + assert_eq!(status, KernelStatusCode::Success); + + let before_reentrancy = CALLBACK_HITS.load(Ordering::SeqCst); + tracing::debug!(target: KERNEL_LOG_TARGET, "outer reentrancy probe"); + assert_eq!( + CALLBACK_HITS.load(Ordering::SeqCst), + before_reentrancy + 1, + "the nested callback event must not be delivered recursively" + ); + + tracing::debug!(target: KERNEL_LOG_TARGET, "post-reentrancy reset probe"); + assert_eq!( + CALLBACK_HITS.load(Ordering::SeqCst), + before_reentrancy + 2, + "delivery must resume after the callback returns" + ); +}