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
17 changes: 15 additions & 2 deletions src/c_abi/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -483,14 +483,27 @@ pub unsafe extern "C" fn kernel_init_logging(
// `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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — Moving the OFF handling out of init_logging and into an early return Success here changes two things worth noting:

  1. OFF no longer participates in the once-per-process "first-call-wins" contract. Previously init_logging(OFF) committed LOGGING_INITIALIZED to true, so a later kernel_init_logging("DEBUG", file) was a no-op. Now the OFF path returns before touching LOGGING_INITIALIZED, so a subsequent call with a real level will install a subscriber. In the pure C-ABI flow the is_some() gate in Session::open keeps OFF sticky for session opens, but two direct kernel_init_logging calls (OFF then a real level) now behave differently than before. This is likely an improvement, but it's an unannounced semantic change.

  2. The OFF short-circuit now runs before the file_path UTF-8 validation that the surrounding comment explicitly calls "NOT best-effort". Previously kernel_init_logging(OFF, <non-UTF-8 path>) surfaced the path error; now it returns Success and never validates the path. Defensible (logging is off, path is moot), but it's a change from prior behavior.

Separately, the LOGGING_INITIALIZED doc comment in src/logging.rs ("...or intentionally skipped for level=OFF") is now stale — init_logging no longer has any OFF handling. Consider updating it to reflect that OFF is handled at the C ABI.

}
// 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);
// `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,
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 { level, file }) {
if crate::logging::init_logging(&crate::logging::LogConfig { filter, file }) {
KernelStatusCode::Success
} else {
crate::c_abi::error::store_and_code(Error::new(
Expand Down
19 changes: 16 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1083,11 +1083,24 @@ impl ResultConfig {
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct LoggingConfig {
/// Log filter, e.g. `databricks_sql_kernel=debug`. If `None`, the
/// kernel honors `RUST_LOG` from the environment.
/// A full [`tracing_subscriber::EnvFilter`] directive, applied
/// **verbatim** on the direct-Rust `Session::open` path.
///
/// The kernel emits every event on the target
/// [`crate::KERNEL_LOG_TARGET`] = `databricks::sql::kernel`, and
/// `EnvFilter` matches by `::`-delimited segment prefix, so the
/// directive MUST name that target with `::` separators, e.g.
/// `databricks::sql::kernel=debug`. The underscore crate-name form
/// (`databricks_sql_kernel=debug`) matches **nothing** — the log file
/// is created but stays empty and no error is surfaced. If `None`, the
/// kernel honors `RUST_LOG` from the environment (falling back to
/// `databricks::sql::kernel=warn`).
pub filter: Option<String>,

/// File to write logs to. If `None`, logs go to stderr.
/// Destination for logs. If it names an existing directory (or ends
/// with a path separator), a `databricks-sql-kernel.log` file is
/// created *inside* it; otherwise it is taken as the log file path. If
/// `None`, logs go to stderr.
pub file: Option<PathBuf>,
}

Expand Down
117 changes: 14 additions & 103 deletions src/klog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
//! target is set via [`KERNEL_LOG_TARGET`] at the span site (see
//! `session.rs`).
//!
//! A `klog_targets_match` test in this module guards against drift.
//! The `tests/klog_bridge.rs` integration test guards against drift in
//! the emitted target (and structured-field propagation).

/// The single target string every kernel event carries.
///
Expand All @@ -54,8 +55,9 @@
/// chance of the two drifting apart. `pyo3_log` maps it to the Python
/// logger `databricks.sql.kernel` via its `::` -> `.` rule. This string
/// is an effectively-permanent public contract (customers configure
/// logging by this name); guarded by drift tests in this module, in
/// `pyo3/src/logging.rs`, and in the connector's `test_logging.py`.
/// logging by this name); guarded by drift tests in
/// `tests/klog_bridge.rs`, in `pyo3/src/logging.rs`, and in the
/// connector's `test_logging.py`.
pub const KERNEL_LOG_TARGET: &str = "databricks::sql::kernel";

// The macros are defined with `klog_`-prefixed names and re-exported
Expand Down Expand Up @@ -100,103 +102,12 @@ pub(crate) use {
klog_warn as warn,
};

#[cfg(test)]
mod tests {
use std::sync::{Mutex, OnceLock};

/// Captured `(target, rendered_message)` pairs. The message is what
/// `tracing`'s `log` feature renders — including any structured
/// fields appended as `key="value"` — so we can assert field
/// propagation, not just the target.
static CAPTURED: OnceLock<Mutex<Vec<(String, String)>>> = OnceLock::new();

struct Capture;
impl log::Log for Capture {
fn enabled(&self, _: &log::Metadata) -> bool {
true
}
fn log(&self, record: &log::Record) {
CAPTURED
.get_or_init(|| Mutex::new(Vec::new()))
.lock()
.unwrap()
.push((record.target().to_owned(), record.args().to_string()));
}
fn flush(&self) {}
}

/// The kernel is built with `tracing`'s `log` feature and installs no
/// `Subscriber` in tests, so each `klog::*` event also emits a
/// `log::Record`. Assert the record target is exactly the contract
/// string — this is the value `pyo3_log` turns into the
/// `databricks.sql.kernel` Python logger. If a future change routes
/// kernel logs through a different target, this fails loudly.
///
/// CONSTRAINT: this test installs a process-global `log` logger via
/// `set_boxed_logger`. There must be at most ONE such test per test
/// binary — `log` allows only one global logger, and a second
/// `set_boxed_logger` from a sibling test would no-op (its `Err` is
/// ignored), so whichever test runs first wins and the other would
/// silently capture into the wrong sink. If another global-logger
/// test is ever added to this crate's unit-test binary, move one of
/// them to an integration test (separate binary) or gate behind a
/// shared `Once`. Today this is the only one.
#[test]
fn klog_emits_contract_target() {
CAPTURED.get_or_init(|| Mutex::new(Vec::new()));
// Ignore error: tolerate a logger already set in this binary
// (see the CONSTRAINT note above — only one such test exists).
let _ = log::set_boxed_logger(Box::new(Capture));
log::set_max_level(log::LevelFilter::Trace);

crate::klog::warn!("probe message");
crate::klog::debug!(field = 1, "probe with field");

let got = CAPTURED.get().unwrap().lock().unwrap().clone();
assert!(
got.iter().any(|(t, _)| t == super::KERNEL_LOG_TARGET),
"expected a record with target {:?}, got {:?}",
super::KERNEL_LOG_TARGET,
got
);
assert_eq!(super::KERNEL_LOG_TARGET, "databricks::sql::kernel");
}

/// Guards correlation-field propagation: a `klog::*` call with a
/// structured field (e.g. `statement_id = …`) must carry that field
/// through `tracing`'s `log` feature into the `log::Record` — this is
/// what lets a customer correlate interleaved kernel logs to a
/// statement/session in a multi-session deployment.
///
/// The `tracing`→`log` bridge does NOT propagate enclosing *span*
/// fields, only the event's own fields, so reader/factory call sites
/// pass `statement_id` as an explicit event field rather than relying
/// on the session span. This test pins that mechanism: if the bridge
/// behaviour changed (fields stop rendering) or a refactor dropped
/// the field, the rendered message would no longer contain it.
///
/// Shares the single global logger with `klog_emits_contract_target`
/// (see the CONSTRAINT note above) — both read from `CAPTURED`, which
/// accumulates across tests in this binary, so this asserts on the
/// presence of *its own* distinctive record rather than on counts.
#[test]
fn klog_propagates_correlation_field() {
CAPTURED.get_or_init(|| Mutex::new(Vec::new()));
let _ = log::set_boxed_logger(Box::new(Capture));
log::set_max_level(log::LevelFilter::Trace);

let stmt = "stmt-correlation-probe-7f3a";
crate::klog::debug!(statement_id = stmt, "creating reader: {} bytes", 42);

let got = CAPTURED.get().unwrap().lock().unwrap().clone();
// The field renders into the message as `statement_id="…"`.
assert!(
got.iter()
.any(|(target, msg)| target == super::KERNEL_LOG_TARGET
&& msg.contains(stmt)
&& msg.contains("statement_id")),
"expected a kernel-target record whose rendered message carries \
the `statement_id` field {stmt:?}; got {got:?}"
);
}
}
// The `tracing`→`log` bridge contract for kernel log events (the target
// `pyo3_log` maps to `databricks.sql.kernel`, and structured-field
// propagation) is verified in the `tests/klog_bridge.rs` integration test.
// It cannot live here: those assertions require that NO `tracing`
// subscriber is installed in the process, but this crate's unit-test
// binary now installs one whenever a test opens a session
// (`Session::open` → `logging::init_logging`, issue #213), which suppresses
// the `log` bridge. A dedicated integration-test binary that opens no
// session keeps the bridge intact.
Loading
Loading