From 1ba8401456c624b4d28674b16c56f0f215a5f1d3 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 20 Aug 2026 23:16:26 +0000 Subject: [PATCH 1/8] feat(c-abi): add callback logging bridge Signed-off-by: Vu Anh Phung --- include/databricks_kernel.h | 14 ++++ src/c_abi/mod.rs | 13 ++++ src/c_abi/session.rs | 54 ++++++++++++++ src/logging.rs | 123 +++++++++++++++++++++++++++++++- tests/c/session_smoke.c | 20 +++++- tests/c_abi_logging_callback.rs | 84 ++++++++++++++++++++++ 6 files changed, 304 insertions(+), 4 deletions(-) create mode 100644 tests/c_abi_logging_callback.rs diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index fb766388..7c43bc79 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -350,6 +350,20 @@ 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); +/* One callback-delivered kernel log record. 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-call-wins behavior match kernel_init_logging. The callback + * must remain valid for the process lifetime, return promptly, and must not + * re-enter the kernel C ABI. A NULL callback returns InvalidArgument. */ +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/mod.rs b/src/c_abi/mod.rs index 8ee10802..3296ae70 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -51,8 +51,21 @@ 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. +/// +/// String pointers are non-null and valid only for the duration of the +/// callback. The callback may run concurrently on multiple kernel threads; +/// consumers must copy any strings they retain and synchronize their sink. +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..a86b949c 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -831,6 +831,60 @@ pub unsafe extern "C" fn kernel_init_logging( } } +/// 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 logging initializer in the process wins; +/// subsequent callback or file/stderr initializer calls are no-ops reporting +/// that first call's outcome. +/// +/// The callback receives lower-case `level`, the tracing `target`, and the +/// rendered message including structured fields. String pointers are valid +/// only until the callback returns. It may be invoked concurrently from +/// multiple kernel threads and must return promptly. It must not 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` when +/// the first subscriber install fails because another subscriber already owns +/// the process-global tracing slot. +/// +/// # 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 level = optional_str(level, "log level").ok().flatten(); + if level + .as_deref() + .is_some_and(|value| value.eq_ignore_ascii_case("off")) + { + return KernelStatusCode::Success; + } + let filter = level.as_deref().map(crate::logging::filter_from_level); + + if crate::logging::init_callback_logging(filter, callback, user_data) { + KernelStatusCode::Success + } else { + crate::c_abi::error::store_and_code(Error::internal().message( + "kernel_init_logging_callback: logging was not initialized because a global \ + subscriber was already installed", + )) + } +} + /// Add (or overwrite) one server-bound session-conf entry. Unknown keys /// are filtered against the kernel allowlist at `open()` time, matching /// the Rust-crate path. diff --git a/src/logging.rs b/src/logging.rs index e7196cfe..8f84d490 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -52,13 +52,17 @@ #![allow(dead_code)] +use std::ffi::{c_void, CString}; 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 @@ -213,6 +217,121 @@ pub(crate) fn init_logging(config: &LogConfig) -> bool { }) } +/// Collect a tracing event's message and structured 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()); + } + } +} + +fn callback_cstring(value: &str) -> CString { + CString::new(value).unwrap_or_else(|_| { + let sanitized = value.replace('\0', "?"); + CString::new(sanitized).expect("replacing NUL produces a valid CString") + }) +} + +struct CallbackLogLayer { + callback: crate::c_abi::KernelLogCallback, + user_data: usize, +} + +impl Layer for CallbackLogLayer +where + S: Subscriber + for<'a> LookupSpan<'a>, +{ + fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { + let metadata = event.metadata(); + let mut visitor = CallbackMessageVisitor::default(); + event.record(&mut visitor); + + let level = callback_cstring(&metadata.level().to_string().to_ascii_lowercase()); + let target = callback_cstring(metadata.target()); + let message = callback_cstring(&visitor.finish()); + + // 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. +pub(crate) fn init_callback_logging( + filter: Option, + callback: crate::c_abi::KernelLogCallback, + user_data: *mut c_void, +) -> bool { + *LOGGING_INITIALIZED.get_or_init(|| { + let filter = filter.map_or_else( + || { + EnvFilter::try_from_default_env().unwrap_or_else(|_| { + EnvFilter::new(format!("{}=warn", crate::klog::KERNEL_LOG_TARGET)) + }) + }, + EnvFilter::new, + ); + + tracing_subscriber::registry() + .with(filter) + .with(CallbackLogLayer { + callback, + user_data: user_data as usize, + }) + .try_init() + .is_ok() + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 851005d9..1f12e519 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -259,13 +259,29 @@ 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"); + /* The alternate callback initializer links and shares the same no-op result. */ + rc = kernel_init_logging_callback(NULL, capture_log, NULL); + CHECK(rc == KernelStatusCode_Success, + "init_logging_callback after first install is a safe no-op"); } /* 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..8507c3e1 --- /dev/null +++ b/tests/c_abi_logging_callback.rs @@ -0,0 +1,84 @@ +// 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" + ); + + 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); +} From baacec0f01bc93f68422c5187098b77cd8e23c6b Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 21 Aug 2026 17:01:46 +0000 Subject: [PATCH 2/8] docs(c-abi): define synchronous log callback delivery Signed-off-by: Vu Anh Phung --- include/databricks_kernel.h | 14 +++++++++----- src/c_abi/mod.rs | 6 ++++-- src/c_abi/session.rs | 12 +++++++----- src/logging.rs | 9 ++++++--- tests/c_abi_logging_callback.rs | 2 ++ 5 files changed, 28 insertions(+), 15 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 7c43bc79..732ad8b9 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -350,16 +350,20 @@ 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); -/* One callback-delivered kernel log record. 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. */ +/* One callback-delivered kernel log record. 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-call-wins behavior match kernel_init_logging. The callback - * must remain valid for the process lifetime, return promptly, and must not - * re-enter the kernel C ABI. A NULL callback returns InvalidArgument. */ + * 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. */ KernelStatusCode kernel_init_logging_callback(const char* level, KernelLogCallback callback, void* user_data); diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 3296ae70..fcd95c3c 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -57,8 +57,10 @@ use std::sync::OnceLock; /// Host callback invoked for one kernel log record. /// /// String pointers are non-null and valid only for the duration of the -/// callback. The callback may run concurrently on multiple kernel threads; -/// consumers must copy any strings they retain and synchronize their sink. +/// 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, diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index a86b949c..2247853d 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -840,11 +840,13 @@ pub unsafe extern "C" fn kernel_init_logging( /// that first call's outcome. /// /// The callback receives lower-case `level`, the tracing `target`, and the -/// rendered message including structured fields. String pointers are valid -/// only until the callback returns. It may be invoked concurrently from -/// multiple kernel threads and must return promptly. It must not 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. +/// rendered message including structured fields. 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` when /// the first subscriber install fails because another subscriber already owns diff --git a/src/logging.rs b/src/logging.rs index 8f84d490..5f5c7daf 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -288,9 +288,12 @@ where let target = callback_cstring(metadata.target()); let message = callback_cstring(&visitor.finish()); - // 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. + // 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(), diff --git a/tests/c_abi_logging_callback.rs b/tests/c_abi_logging_callback.rs index 8507c3e1..3a25dec4 100644 --- a/tests/c_abi_logging_callback.rs +++ b/tests/c_abi_logging_callback.rs @@ -72,6 +72,8 @@ fn callback_receives_kernel_log_record() { "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() From 6284d5da5eaee67c17a3001c073112d78f6a763e Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 21 Aug 2026 17:42:00 +0000 Subject: [PATCH 3/8] docs(c-abi): clarify callback field scope Signed-off-by: Vu Anh Phung --- include/databricks_kernel.h | 8 +++++--- src/c_abi/mod.rs | 12 +++++++----- src/c_abi/session.rs | 15 ++++++++------- src/logging.rs | 2 +- src/session.rs | 9 ++++----- 5 files changed, 25 insertions(+), 21 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 732ad8b9..ed92df6e 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -350,9 +350,11 @@ 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); -/* One callback-delivered kernel log record. 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 +/* 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. */ diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index fcd95c3c..8d57925d 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -56,11 +56,13 @@ use std::sync::OnceLock; /// Host callback invoked for one kernel log record. /// -/// 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. +/// 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, diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 2247853d..5b55ce20 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -840,13 +840,14 @@ pub unsafe extern "C" fn kernel_init_logging( /// that first call's outcome. /// /// The callback receives lower-case `level`, the tracing `target`, and the -/// rendered message including structured fields. 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. +/// 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` when /// the first subscriber install fails because another subscriber already owns diff --git a/src/logging.rs b/src/logging.rs index 5f5c7daf..e54ab718 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -217,7 +217,7 @@ pub(crate) fn init_logging(config: &LogConfig) -> bool { }) } -/// Collect a tracing event's message and structured fields into one line. +/// Collect a tracing event's message and event-local fields into one line. #[derive(Default)] struct CallbackMessageVisitor { message: String, 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", From 07da76348fb7679089d8306997f44e217d9408da Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 21 Aug 2026 18:00:21 +0000 Subject: [PATCH 4/8] refactor(c-abi): share log level resolution Signed-off-by: Vu Anh Phung --- src/c_abi/session.rs | 76 ++++++++++++++++++++++++++++++-------------- 1 file changed, 52 insertions(+), 24 deletions(-) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 5b55ce20..ebfef911 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -765,6 +765,27 @@ 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. +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). @@ -796,22 +817,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. @@ -869,14 +878,10 @@ pub unsafe extern "C" fn kernel_init_logging_callback( ); }; - let level = optional_str(level, "log level").ok().flatten(); - if level - .as_deref() - .is_some_and(|value| value.eq_ignore_ascii_case("off")) - { - return KernelStatusCode::Success; - } - 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, + }; if crate::logging::init_callback_logging(filter, callback, user_data) { KernelStatusCode::Success @@ -1952,6 +1957,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!( From c730858d0aa4b08d6413106d64d0747a09faa2fe Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 21 Aug 2026 18:17:43 +0000 Subject: [PATCH 5/8] refactor(logging): share default environment filter Signed-off-by: Vu Anh Phung --- src/logging.rs | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/logging.rs b/src/logging.rs index e54ab718..e66e0a2e 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -110,6 +110,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 @@ -161,9 +167,7 @@ pub(crate) fn init_logging(config: &LogConfig) -> bool { 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 @@ -315,14 +319,7 @@ pub(crate) fn init_callback_logging( user_data: *mut c_void, ) -> bool { *LOGGING_INITIALIZED.get_or_init(|| { - let filter = filter.map_or_else( - || { - EnvFilter::try_from_default_env().unwrap_or_else(|_| { - EnvFilter::new(format!("{}=warn", crate::klog::KERNEL_LOG_TARGET)) - }) - }, - EnvFilter::new, - ); + let filter = filter.map_or_else(default_env_filter, EnvFilter::new); tracing_subscriber::registry() .with(filter) @@ -419,7 +416,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=")); From 48692b23325be84aa96cd9a3523648fa97d5dea3 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 24 Aug 2026 02:23:59 +0000 Subject: [PATCH 6/8] fix(c-abi): harden and disambiguate kernel log callback install MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review findings on the callback logging bridge (#278): - Replace the lossy `OnceLock` with a `LoggingOutcome` enum so a later initializer can tell whether *its own* sink actually won. `kernel_init_logging_callback` now returns `Internal` — not a misleading `Success` — whenever it did not install the sink: a file/stderr sink won first, or a *different* callback won first. The winning callback sink retains the callback + `user_data` identity, so a second, different registration is rejected (a host never believes a dropped callback is live) while re-registering the identical callback stays idempotent. File-open-failure, foreign-subscriber, and cross-sink cases each carry distinct, accurate messages (also fixing the prior "already installed" misreport after a log-file open error). - Guard `CallbackLogLayer::on_event` with `catch_unwind` so a panic on a tokio worker can't unwind through tracing dispatch and abort in-flight work, mirroring the `catch_ffi` / `block_on_ffi` guards on the C-ABI entry points. - Add a thread-local reentrancy guard so a callback that re-emits a kernel event drops the nested record instead of recursing without bound. Enclosing-span fields (e.g. `session_id`) remain intentionally excluded from the callback message, as documented. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- include/databricks_kernel.h | 13 +- src/c_abi/session.rs | 99 +++++++++---- src/logging.rs | 168 +++++++++++++++++------ tests/c/session_smoke.c | 8 +- tests/c_abi_logging_callback_conflict.rs | 100 ++++++++++++++ 5 files changed, 316 insertions(+), 72 deletions(-) create mode 100644 tests/c_abi_logging_callback_conflict.rs diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index ed92df6e..62528ed5 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -346,8 +346,10 @@ KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* co * 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). */ + * — 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 @@ -365,7 +367,12 @@ typedef void (*KernelLogCallback)(const char* level, const char* target, * process-wide first-call-wins behavior match kernel_init_logging. 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. */ + * 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 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); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index ebfef911..642d97bf 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; @@ -799,11 +800,13 @@ unsafe fn resolve_log_level(level: *const c_char) -> LogLevelResolution { /// /// 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 +/// installed file/stderr 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), 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** /// 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 @@ -828,15 +831,33 @@ 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: 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 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: a global tracing subscriber was already installed by another \ + component; no kernel subscriber was installed and kernel logs will not flow", + )), } } @@ -858,9 +879,15 @@ pub unsafe extern "C" fn kernel_init_logging( /// 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` when -/// the first subscriber install fails because another subscriber already owns -/// the process-global tracing slot. +/// 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** initializer's outcome, so `Success` here means +/// *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 @@ -883,13 +910,39 @@ pub unsafe extern "C" fn kernel_init_logging_callback( LogLevelResolution::Filter(filter) => filter, }; - if crate::logging::init_callback_logging(filter, callback, user_data) { - KernelStatusCode::Success - } else { - crate::c_abi::error::store_and_code(Error::internal().message( - "kernel_init_logging_callback: logging was not initialized because a global \ - subscriber was already installed", - )) + 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", + )), } } diff --git a/src/logging.rs b/src/logging.rs index e66e0a2e..a3359a35 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -65,12 +65,44 @@ use tracing_subscriber::{ 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`]). @@ -153,14 +185,12 @@ 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. @@ -215,9 +245,14 @@ 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 + } }) } @@ -279,56 +314,103 @@ struct CallbackLogLayer { 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>) { - let metadata = event.metadata(); - let mut visitor = CallbackMessageVisitor::default(); - event.record(&mut visitor); - - let level = callback_cstring(&metadata.level().to_string().to_ascii_lowercase()); - let target = callback_cstring(metadata.target()); - let message = callback_cstring(&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, - ); - } + // `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 = callback_cstring(&metadata.level().to_string().to_ascii_lowercase()); + let target = callback_cstring(metadata.target()); + let message = callback_cstring(&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. +/// 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, -) -> bool { +) -> LoggingOutcome { *LOGGING_INITIALIZED.get_or_init(|| { let filter = filter.map_or_else(default_env_filter, EnvFilter::new); - tracing_subscriber::registry() + let installed = tracing_subscriber::registry() .with(filter) .with(CallbackLogLayer { callback, user_data: user_data as usize, }) .try_init() - .is_ok() + .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 + } }) } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 1f12e519..0984106f 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -278,10 +278,12 @@ static void test_init_logging(void) { /* 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"); - /* The alternate callback initializer links and shares the same no-op result. */ + /* 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_Success, - "init_logging_callback after first install is a safe no-op"); + 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_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" + ); +} From c19440002f91920b2e79c75e455b93d51eba1ba3 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 24 Aug 2026 03:28:04 +0000 Subject: [PATCH 7/8] docs(c-abi): note level OFF returns Success without installing a callback `kernel_init_logging_callback` short-circuits on level `OFF` and returns `Success` without installing any callback sink (mirroring `kernel_init_logging`). The callback contract said "`Success` means this exact callback is the installed sink", omitting the OFF case that `kernel_init_logging`'s own docs already note. Add the "(or level OFF)" clause to the C header and the Rust doc-comment so the callback contract is as precise as the file/stderr one. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- include/databricks_kernel.h | 5 +++-- src/c_abi/session.rs | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 62528ed5..22dcacdf 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -371,8 +371,9 @@ typedef void (*KernelLogCallback)(const char* level, const char* target, * 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 this exact callback + user_data is the installed - * sink (a later call with the identical callback and user_data also succeeds). */ + * subscriber; Success means level OFF was requested (which installs nothing) 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); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 642d97bf..4dca44e5 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -886,8 +886,9 @@ pub unsafe extern "C" fn kernel_init_logging( /// 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** initializer's outcome, so `Success` here means -/// *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). +/// either level `OFF` was requested (which installs nothing) 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 From f4c3556d4f57642cf813aef56437214f26685dc4 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 24 Aug 2026 04:02:41 +0000 Subject: [PATCH 8/8] fix(c-abi): harden callback logging delivery Signed-off-by: Vu Anh Phung --- include/databricks_kernel.h | 39 ++++++----- src/c_abi/error.rs | 8 +-- src/c_abi/session.rs | 45 +++++++------ src/logging.rs | 17 ++--- tests/c_abi_logging_callback_panic.rs | 78 ++++++++++++++++++++++ tests/c_abi_logging_callback_reentrancy.rs | 73 ++++++++++++++++++++ 6 files changed, 208 insertions(+), 52 deletions(-) create mode 100644 tests/c_abi_logging_callback_panic.rs create mode 100644 tests/c_abi_logging_callback_reentrancy.rs diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 22dcacdf..3e4cabfe 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -336,16 +336,18 @@ 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 + * 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 @@ -363,17 +365,20 @@ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); 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-call-wins behavior match kernel_init_logging. 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 +/* 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) or - * this exact callback + user_data is the installed sink (a later call with the - * identical callback and user_data also succeeds). */ + * 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); 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/session.rs b/src/c_abi/session.rs index 4dca44e5..79dd2e4d 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -774,7 +774,8 @@ enum LogLevelResolution { /// 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. +/// `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 @@ -792,25 +793,26 @@ unsafe fn resolve_log_level(level: *const c_char) -> LogLevelResolution { /// `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 file/stderr 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 +/// 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** -/// 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. +/// 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. @@ -865,9 +867,11 @@ pub unsafe extern "C" fn kernel_init_logging( /// /// 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 logging initializer in the process wins; -/// subsequent callback or file/stderr initializer calls are no-ops reporting -/// that first call's outcome. +/// 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. @@ -885,10 +889,11 @@ pub unsafe extern "C" fn kernel_init_logging( /// *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** initializer's outcome, so `Success` here means -/// either level `OFF` was requested (which installs nothing) 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). +/// 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 diff --git a/src/logging.rs b/src/logging.rs index a3359a35..9d7024e9 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -52,7 +52,7 @@ #![allow(dead_code)] -use std::ffi::{c_void, CString}; +use std::ffi::c_void; use std::path::{Path, PathBuf}; use std::sync::OnceLock; use tracing::field::{Field, Visit}; @@ -302,13 +302,6 @@ impl Visit for CallbackMessageVisitor { } } -fn callback_cstring(value: &str) -> CString { - CString::new(value).unwrap_or_else(|_| { - let sanitized = value.replace('\0', "?"); - CString::new(sanitized).expect("replacing NUL produces a valid CString") - }) -} - struct CallbackLogLayer { callback: crate::c_abi::KernelLogCallback, user_data: usize, @@ -354,9 +347,11 @@ where let mut visitor = CallbackMessageVisitor::default(); event.record(&mut visitor); - let level = callback_cstring(&metadata.level().to_string().to_ascii_lowercase()); - let target = callback_cstring(metadata.target()); - let message = callback_cstring(&visitor.finish()); + 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. 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" + ); +}