Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 43 additions & 10 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
vuanhphung marked this conversation as resolved.
Resolved

/* ─── Proxy / TLS (optional) ──────────────────────────────────────────
*
* All optional; defaults are: no explicit proxy (reqwest honours
Expand Down
8 changes: 4 additions & 4 deletions src/c_abi/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions src/c_abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
220 changes: 182 additions & 38 deletions src/c_abi/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>),
}

/// 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.
Expand All @@ -796,38 +822,133 @@ 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.
let file = match optional_str(file_path, "log file path") {
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<crate::c_abi::KernelLogCallback>,
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",
)),
}
}

Comment thread
vuanhphung marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -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!(
Expand Down
Loading
Loading