diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index ef52396a..724bd6a4 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -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; + } + // 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( diff --git a/src/config.rs b/src/config.rs index 9b59ee07..b53c5487 100644 --- a/src/config.rs +++ b/src/config.rs @@ -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, - /// 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, } diff --git a/src/klog.rs b/src/klog.rs index cec1fb97..780e7e7e 100644 --- a/src/klog.rs +++ b/src/klog.rs @@ -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. /// @@ -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 @@ -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>> = 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. diff --git a/src/logging.rs b/src/logging.rs index 24fd61e8..e7196cfe 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -26,8 +26,11 @@ //! ## Usage //! //! ```bash -//! # Via environment variable -//! RUST_LOG=databricks_sql_kernel=debug ./my_app +//! # Via environment variable. The kernel emits on the `::`-delimited +//! # target `databricks::sql::kernel`; `EnvFilter` matches by +//! # `::`-delimited segment prefix, so the underscore crate-name form +//! # (`databricks_sql_kernel=debug`) would match nothing. +//! RUST_LOG=databricks::sql::kernel=debug ./my_app //! ``` //! //! ## Relationship to the pyo3 / Python path @@ -49,6 +52,7 @@ #![allow(dead_code)] +use std::path::{Path, PathBuf}; use std::sync::OnceLock; use tracing_subscriber::{ fmt::{self, time::SystemTime}, @@ -64,13 +68,70 @@ use tracing_subscriber::{ /// wins"). static LOGGING_INITIALIZED: OnceLock = OnceLock::new(); -/// Logging configuration passed via ADBC database options. +/// Default log file name created inside a destination that names a +/// directory (see [`resolve_log_file`]). +const DEFAULT_LOG_FILE_NAME: &str = "databricks-sql-kernel.log"; + +/// Resolved logging configuration. +/// +/// `filter` is a **complete `EnvFilter` directive** (e.g. +/// `databricks::sql::kernel=debug`) — NOT a bare level. The two entry +/// points build it differently: the public `LoggingConfig.filter` already +/// carries a directive and is used verbatim, while the C ABI's bare level +/// is expanded to `{KERNEL_LOG_TARGET}={level}` by +/// [`filter_from_level`] before it reaches here. #[derive(Debug, Clone, Default)] pub(crate) struct LogConfig { - /// Log level: "OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE". - pub level: Option, - /// Log file path. If unset, logs go to stderr. - pub file: Option, + /// Full `EnvFilter` directive. If unset, the kernel honours `RUST_LOG`, + /// falling back to `{KERNEL_LOG_TARGET}=warn`. + pub filter: Option, + /// Log destination. If it names an existing directory (or ends with a + /// path separator), a log file is created *inside* it; otherwise it is + /// taken as the log file path. If unset, logs go to stderr. + pub file: Option, +} + +/// Expand a bare level ("OFF"/"ERROR"/"WARN"/"INFO"/"DEBUG"/"TRACE") into a +/// full `EnvFilter` directive targeting the kernel's own log target. +/// +/// The directive MUST target `KERNEL_LOG_TARGET` ("databricks::sql::kernel") +/// verbatim — `EnvFilter` matches by `::`-delimited segment prefix, so a +/// single token like "databricks_sql_kernel" would match NOTHING and +/// silently drop every kernel event. +pub(crate) fn filter_from_level(level: &str) -> String { + format!( + "{}={}", + crate::klog::KERNEL_LOG_TARGET, + level.to_lowercase() + ) +} + +/// Resolve a configured log destination to the actual file path to open. +/// +/// A destination that names an **existing directory**, or that ends with a +/// path separator (a caller's directory-form intent even if the directory +/// does not exist yet), resolves to `/databricks-sql-kernel.log` +/// rather than being opened as a file — opening a directory as a file +/// would fail. This mirrors the reference driver's `LogPath` (directory) +/// vs `LogFile` (file) semantics on the kernel's single `file` field. +/// +/// Any other value is returned unchanged and taken as the log file path. +pub(crate) fn resolve_log_file(path: &Path) -> PathBuf { + // A trailing separator is a directory-form signal that survives even + // when the directory does not exist yet: `Path::is_dir` would be false, + // but the caller clearly meant "a directory". `components()` drops a + // trailing separator, so a path like `/var/log/` yields a final + // component of `log` — detect the raw trailing separator on the string. + let has_trailing_sep = path + .to_str() + .map(|s| s.ends_with(std::path::MAIN_SEPARATOR) || s.ends_with('/')) + .unwrap_or(false); + + if path.is_dir() || has_trailing_sep { + path.join(DEFAULT_LOG_FILE_NAME) + } else { + path.to_path_buf() + } } /// Initialize the tracing subscriber. @@ -79,49 +140,39 @@ pub(crate) struct LogConfig { /// **first** call configures logging and installs the subscriber; every /// later call is a no-op that returns that **first call's** outcome (the /// subscriber can only be installed once, so a later call's `config` — its -/// level / file — has no effect and its return does not describe its own +/// 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 (or was intentionally skipped for level `OFF`). -/// 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. +/// 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 { *LOGGING_INITIALIZED.get_or_init(|| { - // Check if the configured level is "OFF" — skip initialization - // entirely, but treat it as a successful (intentional) outcome. - if let Some(ref level) = config.level { - if level.eq_ignore_ascii_case("off") { - return true; - } - } - - // The filter directive MUST target the same string the kernel's - // log macros emit with — `KERNEL_LOG_TARGET` ("databricks::sql::kernel"). - // `EnvFilter` matches by `::`-delimited segment prefix, so a - // single token like "databricks_sql_kernel" would match NOTHING - // and silently drop every kernel event. - let filter = if let Some(ref level) = config.level { - EnvFilter::new(format!("{}={}", crate::klog::KERNEL_LOG_TARGET, level.to_lowercase())) + // Use the caller's full directive verbatim; otherwise fall back to + // RUST_LOG, then to a warn default on the kernel's own target. + let filter = if let Some(ref directive) = config.filter { + EnvFilter::new(directive.clone()) } else { - // Fall back to RUST_LOG env var, default to warn EnvFilter::try_from_default_env().unwrap_or_else(|_| { EnvFilter::new(format!("{}=warn", crate::klog::KERNEL_LOG_TARGET)) }) }; - // Try the requested file; on failure fall back to stderr WITHIN - // this same call so logging still works (rather than committing the - // OnceLock with no subscriber and locking out all later attempts). - // Return `false` only to signal the requested file wasn't honoured. + // Resolve a directory-form destination to a file inside it, then try + // to open it; on failure fall back to stderr WITHIN this same call so + // logging still works (rather than committing the OnceLock with no + // subscriber and locking out all later attempts). Return `false` only + // to signal the requested file wasn't honoured. let file = config.file.as_ref().and_then(|path| { - match std::fs::OpenOptions::new().create(true).append(true).open(path) { + let resolved = resolve_log_file(path); + match std::fs::OpenOptions::new().create(true).append(true).open(&resolved) { Ok(f) => Some(f), Err(e) => { - eprintln!("databricks-sql-kernel: failed to open log file {path}: {e}; falling back to stderr"); + eprintln!("databricks-sql-kernel: failed to open log file {}: {e}; falling back to stderr", resolved.display()); None } } @@ -169,18 +220,71 @@ mod tests { #[test] fn test_log_config_default() { let config = LogConfig::default(); - assert!(config.level.is_none()); + assert!(config.filter.is_none()); assert!(config.file.is_none()); } #[test] fn test_log_config_with_values() { let config = LogConfig { - level: Some("DEBUG".to_string()), - file: Some("/tmp/test.log".to_string()), + filter: Some("databricks::sql::kernel=debug".to_string()), + file: Some(PathBuf::from("/tmp/test.log")), }; - assert_eq!(config.level.as_deref(), Some("DEBUG")); - assert_eq!(config.file.as_deref(), Some("/tmp/test.log")); + assert_eq!( + config.filter.as_deref(), + Some("databricks::sql::kernel=debug") + ); + assert_eq!(config.file.as_deref(), Some(Path::new("/tmp/test.log"))); + } + + /// A bare level expands to a full directive targeting the kernel's own + /// log target — not an underscore-joined token that would match nothing. + #[test] + fn filter_from_level_targets_kernel_log_target() { + assert_eq!(filter_from_level("DEBUG"), "databricks::sql::kernel=debug"); + assert_eq!(filter_from_level("warn"), "databricks::sql::kernel=warn"); + // The result must be a directive EnvFilter accepts. + let _filter = EnvFilter::new(filter_from_level("INFO")); + } + + /// A destination that names an existing directory resolves to a log + /// file created inside it, not opened as a file. + #[test] + fn resolve_log_file_directory_resolves_inside() { + let dir = std::env::temp_dir().join(format!( + "kt_logtest_dir_{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).expect("create temp log dir"); + + let resolved = resolve_log_file(&dir); + assert_eq!(resolved, dir.join(DEFAULT_LOG_FILE_NAME)); + + let _ = std::fs::remove_dir_all(&dir); + } + + /// A path with a trailing separator is treated as a directory even when + /// it does not exist yet (the caller's directory-form intent). + #[test] + fn resolve_log_file_trailing_separator_resolves_inside() { + let base = std::env::temp_dir().join("kt_logtest_nonexistent_dir"); + let with_sep = PathBuf::from(format!("{}{}", base.display(), std::path::MAIN_SEPARATOR)); + let resolved = resolve_log_file(&with_sep); + assert!( + resolved.ends_with(DEFAULT_LOG_FILE_NAME), + "trailing-separator destination must resolve to a file inside it, got {resolved:?}" + ); + } + + /// A plain file path (no trailing separator, not an existing directory) + /// is taken verbatim as the log file. + #[test] + fn resolve_log_file_file_path_unchanged() { + let file = std::env::temp_dir().join("kt_logtest_explicit.log"); + assert_eq!(resolve_log_file(&file), file); } /// The filter directive must be built from `KERNEL_LOG_TARGET` so it @@ -201,27 +305,13 @@ mod tests { let _filter = EnvFilter::new(directive); } - /// `init_logging` is idempotent in its return value: because the - /// subscriber installs once per process, every call returns the SAME - /// (first-call) outcome. We assert only that invariant — not a - /// specific true/false — because the absolute value depends on whether - /// some other test in the shared binary installed the global - /// subscriber first (which would make this call's try_init fail). The - /// first-call-installs-cleanly case is exercised end-to-end by the - /// wiremock session tests. - #[test] - fn init_logging_return_is_idempotent() { - let cfg = LogConfig { - level: Some("warn".to_string()), - file: None, - }; - let first = init_logging(&cfg); - // A later call with a different config must still return the first - // outcome (its own args have no effect). - let second = init_logging(&LogConfig { - level: Some("debug".to_string()), - file: Some("/nonexistent/dir/should-not-matter.log".to_string()), - }); - assert_eq!(first, second, "later calls return the first-call outcome"); - } + // NOTE: `init_logging`'s once-per-process idempotency is NOT asserted + // as a unit test here. Calling `init_logging` installs a global + // `tracing` subscriber for the whole test binary, which suppresses the + // `log`-bridge records the `klog` tests (in `klog::tests`, same binary) + // depend on — a subscriber-installing unit test races those tests for + // process-global logging state (see the CONSTRAINT note in + // `klog::tests`). The idempotency invariant is instead exercised through + // the public `Session::open` path in the `v0_logging_wiremock` + // integration test, whose own binary is free to install a subscriber. } diff --git a/src/session.rs b/src/session.rs index 36bde53e..921314b3 100644 --- a/src/session.rs +++ b/src/session.rs @@ -247,6 +247,41 @@ impl Session { )) })?; + // Install the tracing subscriber from the caller's LoggingConfig — + // but ONLY when they explicitly configured a filter or a + // destination. This is the direct-Rust counterpart to the C ABI's + // `kernel_init_logging`: without it, a caller's `logging(...)` is + // accepted and stored but never consumed, so a configured log + // destination silently produces nothing (issue #213). + // + // The `is_some()` gate is load-bearing, NOT an optimisation. The + // pyo3 binding opens sessions through this same path and NEVER sets + // a `LoggingConfig`; it relies on the `tracing`→`log` bridge (the + // crate's `tracing/log` feature) so `pyo3_log` can forward records + // into Python's `logging`. Installing ANY subscriber here — even the + // `RUST_LOG`/warn default an empty config would fall through to — + // suppresses that bridge and breaks all kernel logging into Python. + // So an unconfigured `LoggingConfig` must remain a true no-op, + // preserving the "direct-Rust vs pyo3 are mutually exclusive" + // invariant documented in `src/logging.rs`. It also keeps a C ABI + // `kernel_init_logging(OFF, …)` — which intentionally installs + // nothing — from being overridden by a stray `warn` subscriber on + // the next `Session::open`. + // + // Idempotent and process-wide (`OnceLock`): the first configured + // install (here or via `kernel_init_logging`) wins; later calls are + // no-ops. The return value only signals whether the requested + // destination was fully honoured; a `false` (log file unopenable, or + // a subscriber already installed by the host) is a logging + // degradation, not a reason to fail `open()`, so it is not + // propagated as an error. + if config.logging.filter.is_some() || config.logging.file.is_some() { + let _ = crate::logging::init_logging(&crate::logging::LogConfig { + filter: config.logging.filter.clone(), + file: config.logging.file.clone(), + }); + } + // Fold client-only result knobs (e.g. cloudfetch_max_chunks_in_memory) // carried in session_conf into the typed ResultConfig and strip them // from session_conf, before either the reader factory reads diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index e7889ef0..0102aa74 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -826,7 +826,7 @@ impl StatementCanceller { async { // Log both outcomes at the decision point so a host debugging a // cancel can tell "raced ahead of the id" (no-op) from "wired to - // the wrong handle" in one `RUST_LOG=databricks_sql_kernel=debug` + // the wrong handle" in one `RUST_LOG=databricks::sql::kernel=debug` // stream — the no-op branch returns before the transport, which // is the only other place a cancel is logged. let Some(id) = id else { diff --git a/tests/klog_bridge.rs b/tests/klog_bridge.rs new file mode 100644 index 00000000..2652cbed --- /dev/null +++ b/tests/klog_bridge.rs @@ -0,0 +1,205 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `tracing`→`log` bridge contract for kernel log events. +//! +//! The kernel is built with `tracing`'s `log` feature, so — **when no +//! `tracing` `Subscriber` is installed** — every `tracing::*` event also +//! emits a `log::Record`. The pyo3 binding relies on exactly this: it +//! installs no subscriber and routes those `log` records into Python's +//! `logging` via `pyo3_log`, deriving the logger name from the record +//! `target` (`::` → `.`). These tests pin that the kernel's log target is +//! the contract string `pyo3_log` turns into the `databricks.sql.kernel` +//! Python logger, and that structured fields survive the bridge. +//! +//! ## Why this is a separate integration-test binary +//! +//! The assertions depend on the `log` bridge being live, which requires +//! that **no `tracing` subscriber is installed in this process**. The +//! kernel's own unit-test binary can no longer satisfy that: any +//! `Session::open` (and several unit tests open sessions against a mock) +//! installs a process-global subscriber via `logging::init_logging` +//! (issue #213 wired that in), which suppresses the `log` bridge. A +//! dedicated integration-test binary that opens no session keeps the +//! bridge intact, so these are hosted here rather than in `klog::tests`. +//! +//! The kernel's internal `klog::{debug,warn}` macros are `pub(crate)` and +//! unreachable from an integration test, but they are thin wrappers that +//! emit `tracing::debug!(target: KERNEL_LOG_TARGET, …)`. Emitting on that +//! public target directly is behaviourally identical for the bridge, so +//! these tests exercise the exact same contract. + +use std::sync::{Mutex, OnceLock}; + +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, HttpConfig, LoggingConfig, Session, KERNEL_LOG_TARGET, +}; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +/// 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>> = 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) {} +} + +/// Install the single process-global `log` logger for this binary, once. +/// `log` allows only one global logger, so both tests share this capture +/// sink (and both read from `CAPTURED`, which accumulates across them). +fn install_capture() { + static INIT: OnceLock<()> = OnceLock::new(); + INIT.get_or_init(|| { + CAPTURED.get_or_init(|| Mutex::new(Vec::new())); + // Ignore error: tolerate a logger already installed by a sibling + // test in this binary — there is exactly one capture sink. + let _ = log::set_boxed_logger(Box::new(Capture)); + log::set_max_level(log::LevelFilter::Trace); + }); +} + +/// The kernel's log events emit a `log::Record` whose 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. +#[test] +fn klog_emits_contract_target() { + install_capture(); + + // Equivalent to the crate-internal `klog::{warn,debug}!` macros, which + // wrap `tracing::{warn,debug}!(target: KERNEL_LOG_TARGET, …)`. + tracing::warn!(target: KERNEL_LOG_TARGET, "probe message"); + tracing::debug!(target: KERNEL_LOG_TARGET, field = 1, "probe with field"); + + let got = CAPTURED.get().unwrap().lock().unwrap().clone(); + assert!( + got.iter().any(|(t, _)| t == KERNEL_LOG_TARGET), + "expected a record with target {KERNEL_LOG_TARGET:?}, got {got:?}" + ); + assert_eq!(KERNEL_LOG_TARGET, "databricks::sql::kernel"); +} + +/// A kernel log 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` — +/// 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() { + install_capture(); + + let stmt = "stmt-correlation-probe-7f3a"; + tracing::debug!(target: KERNEL_LOG_TARGET, 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 == 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:?}" + ); +} + +/// GATE REGRESSION (issue #213 follow-up): opening a session with an +/// UNCONFIGURED `LoggingConfig` must NOT install a `tracing` subscriber, +/// so the `tracing`→`log` bridge that `pyo3_log` depends on stays live. +/// +/// `Session::open` now consumes `LoggingConfig` (issue #213), but only +/// when the caller explicitly set a `filter` or `file`. The pyo3 binding +/// opens sessions through this same path and never sets logging — if +/// `open()` installed a subscriber for the empty/default config, it would +/// suppress the bridge and silently break all kernel logging into Python. +/// +/// This test proves the gate holds: after a default-logging `open()`, a +/// kernel-target event still reaches the `log` capture sink (which only +/// happens while no subscriber is installed). A regression that dropped +/// the `is_some()` gate would install the `RUST_LOG`/warn default here and +/// this probe would stop being captured. +#[tokio::test] +async fn empty_logging_config_open_does_not_install_subscriber() { + install_capture(); + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-gate-213","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + + let mut http = HttpConfig::default(); + http.retry_max_retries = 0; + + // No `.logging(...)` — the default (pyo3-equivalent) case. + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + }) + .http(http) + .open() + .await + .expect("Session::open with default logging must succeed"); + assert_eq!(session.session_id(), "sess-gate-213"); + + // Sanity: an explicitly-empty LoggingConfig is the same no-op path. + let _empty = LoggingConfig::default(); + + // The bridge must still be live: a kernel-target event AFTER open() + // still produces a `log::Record` captured by our sink. + let probe = "gate-probe-after-open-4d21"; + tracing::warn!(target: KERNEL_LOG_TARGET, probe = probe, "post-open bridge probe"); + + let got = CAPTURED.get().unwrap().lock().unwrap().clone(); + assert!( + got.iter() + .any(|(target, msg)| target == KERNEL_LOG_TARGET && msg.contains(probe)), + "issue #213 gate: after a default-logging Session::open, the tracing→log bridge must \ + still be live (no subscriber installed), but the post-open probe {probe:?} was not \ + captured — Session::open installed a subscriber for an unconfigured LoggingConfig, \ + which breaks pyo3_log. got {got:?}" + ); +} diff --git a/tests/v0_logging_wiremock.rs b/tests/v0_logging_wiremock.rs new file mode 100644 index 00000000..77edda6f --- /dev/null +++ b/tests/v0_logging_wiremock.rs @@ -0,0 +1,132 @@ +// 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. + +//! Regression test for issue #213 (CONNPROP-004): a `LoggingConfig` +//! configured on a `SessionBuilder` must actually produce log output on +//! the **direct-Rust** `Session::open` path. +//! +//! Before the fix, `SessionBuilder::logging(LoggingConfig)` was accepted +//! and stored on `SessionConfig::logging` but never consumed — the +//! subscriber installer (`logging::init_logging`) was reachable only +//! through the C ABI's `kernel_init_logging`. So a direct-Rust caller's +//! configured log destination was a silent no-op. `Session::open` now +//! installs the subscriber from `LoggingConfig`, matching the C ABI path. +//! +//! ## Why this lives in its own test binary +//! +//! The tracing subscriber installs at most once per process (`OnceLock`, +//! first-call-wins), and every `Session::open` now calls `init_logging`. +//! If this assertion shared a binary with any other test that opened a +//! session first, that earlier open would install a subscriber with **no** +//! log file and this file-backed install would be a no-op. Isolating it in +//! its own integration-test file guarantees this is the first (and only) +//! `init_logging` call in its process, so the file destination wins. + +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, HttpConfig, LoggingConfig, Session, KERNEL_LOG_TARGET, +}; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +/// Mount a successful CreateSession stub. +async fn mock_create_session_ok(server: &MockServer) { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-log-213","warehouse_id":"test_wh"}"#), + ) + .mount(server) + .await; +} + +/// CONNPROP-004 — a configured log destination actually produces log +/// output on the direct-Rust `Session::open` path. +/// +/// Opening a session emits a `debug!` "creating session" record on the +/// kernel's own log target, so a `debug`-level filter plus a file +/// destination must leave a non-empty log file behind. +#[tokio::test] +async fn logging_config_file_destination_is_written() { + let server = MockServer::start().await; + mock_create_session_ok(&server).await; + + let log_file = std::env::temp_dir().join(format!( + "kt213_logging_{}.log", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + + // `LoggingConfig` is `#[non_exhaustive]`: build from default and assign. + let mut logging = LoggingConfig::default(); + logging.filter = Some(format!("{KERNEL_LOG_TARGET}=debug")); + logging.file = Some(log_file.clone()); + + let mut http = HttpConfig::default(); + http.retry_max_retries = 0; + + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + }) + .http(http) + .logging(logging) + .open() + .await + .expect("Session::open with a log destination configured must succeed"); + + assert_eq!(session.session_id(), "sess-log-213"); + + // The subscriber is installed and the "creating session" debug record + // has been emitted synchronously during open(); the file must exist and + // be non-empty. + let size = std::fs::metadata(&log_file).map(|m| m.len()).unwrap_or(0); + let _ = std::fs::remove_file(&log_file); + + assert!( + size > 0, + "issue #213: the configured log destination {log_file:?} was not written (size {size}); \ + Session::open must install a subscriber from LoggingConfig, not leave it inert" + ); + + // Idempotency: a second Session::open in the same process re-invokes + // init_logging, which must be a harmless no-op (the subscriber installs + // once per process, first-call-wins) — not an error that fails open(). + // This exercises the once-per-process invariant through the public path. + let mut logging2 = LoggingConfig::default(); + logging2.filter = Some(format!("{KERNEL_LOG_TARGET}=debug")); + logging2.file = Some(std::env::temp_dir().join("kt213_second_open_should_be_noop.log")); + let mut http2 = HttpConfig::default(); + http2.retry_max_retries = 0; + let session2 = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + }) + .http(http2) + .logging(logging2) + .open() + .await + .expect("a second Session::open must succeed; re-init of logging is a no-op"); + assert_eq!(session2.session_id(), "sess-log-213"); +}