diff --git a/Cargo.lock b/Cargo.lock index 37ff26df..09f558c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -46,6 +46,15 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "arc-swap" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a3a1fd6f75306b68087b831f025c712524bcb19aad54e557b1129cfa0a2b207" +dependencies = [ + "rustversion", +] + [[package]] name = "arrow-array" version = "57.3.1" @@ -412,6 +421,7 @@ dependencies = [ "dashmap", "dirs", "futures", + "log", "lz4_flex", "oauth2", "open", @@ -438,8 +448,11 @@ dependencies = [ "arrow-schema", "chrono", "databricks-sql-kernel", + "log", "pyo3", + "pyo3-log", "tokio", + "tracing", ] [[package]] @@ -1576,6 +1589,17 @@ dependencies = [ "pyo3-build-config", ] +[[package]] +name = "pyo3-log" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26c2ec80932c5c3b2d4fbc578c9b56b2d4502098587edb8bef5b6bfcad43682e" +dependencies = [ + "arc-swap", + "log", + "pyo3", +] + [[package]] name = "pyo3-macros" version = "0.26.0" @@ -2354,6 +2378,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-attributes", "tracing-core", diff --git a/Cargo.toml b/Cargo.toml index 973bfb2f..95705342 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,14 @@ keywords = ["databricks", "arrow", "database", "sql"] categories = ["database"] [dependencies] -tracing = "0.1" +# The `log` feature makes `tracing::*` macros also emit `log::Record`s +# *when no tracing Subscriber is installed*. The pyo3 binding relies on +# this: it installs no Subscriber and instead routes those `log` records +# into Python's `logging` via `pyo3-log` (see `pyo3/src/logging.rs`). +# Direct-Rust / C-ABI consumers install the `fmt` Subscriber in +# `src/logging.rs` instead, which suppresses the `log` records — the two +# paths are mutually exclusive by construction. +tracing = { version = "0.1", features = ["log"] } tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } arrow-array = "57" @@ -93,6 +100,7 @@ dirs = "5" # Cross-platform config directory (~/.config/) tokio = { version = "1", features = ["rt-multi-thread", "macros"] } wiremock = "0.6" tempfile = "3" +log = "0.4" # TLS backend selection. # diff --git a/napi/Cargo.lock b/napi/Cargo.lock index cf129a0e..3a84b7e0 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -1980,6 +1980,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-attributes", "tracing-core", diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index bd61b58e..445e6c0a 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -60,3 +60,6 @@ arrow-pyarrow = "57" # kernel uses for its `TypedValue::Date` / `TypedValue::Timestamp` # variants — the parsed values flow directly into those. chrono = "0.4" +pyo3-log = "0.13" +log = "0.4" +tracing = "0.1" diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 60b4d0f2..cc07864a 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -80,6 +80,17 @@ fn attach_attrs( /// `err.code`, `err.message`, `err.sql_state`, etc.; `str(err)` is /// the kernel's message text. pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { + // Boundary-only breadcrumb: the kernel logged *what* failed; this + // records the kernel `Error` -> Python `KernelError` translation + // (and which code slug drove it), which is knowledge unique to the + // pyo3 layer. Helps explain "why did I get this exception type". + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + code = code_str(err.code), + retryable = err.retryable, + "mapping kernel error to KernelError: {}", + err.message + ); let py_err = KernelError::new_err(err.message.clone()); // Materialise the exception value so we can attach attributes. let bound = py_err.value(py); diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 212174ae..9a24d277 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -36,6 +36,7 @@ mod auth; mod errors; mod executed_async; mod fetch; +mod logging; mod metadata; mod params; mod result_stream; @@ -44,6 +45,35 @@ mod statement; use pyo3::prelude::*; +/// Route kernel logs into Python's `logging`. Idempotent — safe to call +/// more than once (later calls are no-ops). Returns `True` if this call +/// performed the install, `False` if logging was already initialized (by +/// an earlier call or because the host process owns the `log` logger). +/// +/// The connector calls this automatically when the kernel backend loads, +/// so `use_kernel=True` users need not call it themselves. +/// +/// Records are forwarded under per-crate logger names: the kernel's own +/// events under `databricks.sql.kernel` (and the pyo3 boundary under +/// `databricks.sql.kernel.pyo3`), plus the underlying HTTP stack +/// (`hyper_util.client…`, `reqwest.connect`, `rustls`, …). Each is gated +/// by its Python logger's level, so deps stay quiet until a customer +/// raises them — e.g. `logging.getLogger("databricks.sql").setLevel(DEBUG)` +/// for everything, or silence the wire chatter with +/// `logging.getLogger("hyper_util").setLevel(WARNING)`. +#[pyfunction] +fn init_logging(py: Python<'_>) -> bool { + logging::init_logging(py) +} + +/// Clear cached logger levels so a Python-side logging reconfiguration +/// applied *after* the first kernel log (e.g. raising +/// `databricks.sql.kernel` to DEBUG mid-session) takes effect. +#[pyfunction] +fn reset_logging() { + logging::reset_logging(); +} + #[pymodule] fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add("__version__", env!("CARGO_PKG_VERSION"))?; @@ -54,5 +84,16 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_function(wrap_pyfunction!(init_logging, m)?)?; + m.add_function(wrap_pyfunction!(reset_logging, m)?)?; + + // Install the log bridge at module import so *any* consumer of the + // bare wheel (the connector, integration tests, custom embedders) + // gets kernel logs in Python `logging` without an explicit + // `init_logging()` call. It's idempotent and never panics, so the + // connector's own call at kernel-backend load is a harmless no-op. + // Records still only surface once a customer raises the relevant + // logger's level, so this default-on install is silent until asked. + logging::init_logging(m.py()); Ok(()) } diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs new file mode 100644 index 00000000..8a96be6c --- /dev/null +++ b/pyo3/src/logging.rs @@ -0,0 +1,221 @@ +// 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. + +//! Bridge kernel logs into Python's `logging` module. +//! +//! ## How it works +//! +//! The kernel emits its diagnostics via the `tracing` crate, with every +//! event tagged with the target `databricks::sql::kernel` (see the +//! kernel's `klog` shim). The kernel is built with `tracing`'s `log` +//! feature and the Python path installs **no** `tracing` `Subscriber`, +//! so each `tracing` event is also emitted as a `log::Record` carrying +//! that target. +//! +//! [`pyo3_log`] is installed here as the `log` consumer. It maps the +//! record target into a Python logger name by replacing `::` with `.`, +//! so `databricks::sql::kernel` becomes the Python logger +//! **`databricks.sql.kernel`** — a child of the connector's +//! `databricks.sql` namespace. A customer therefore controls kernel +//! verbosity with the ordinary stdlib idiom, and a level set on the +//! connector root cascades to the kernel: +//! +//! ```python +//! import logging +//! logging.getLogger("databricks.sql").setLevel(logging.DEBUG) # connector + kernel +//! logging.getLogger("databricks.sql.kernel").setLevel(logging.DEBUG) # kernel only +//! ``` +//! +//! ## Filtering happens before the GIL +//! +//! Kernel events fire on tokio worker threads with the GIL released +//! (see `run_kernel!`). `pyo3_log` re-acquires the GIL per surviving +//! record, so we must drop below-threshold events *before* that +//! boundary. Two cheap gates do this: the global `log::max_level` +//! (set by `pyo3_log` from the Python loggers' effective levels) and +//! `pyo3_log`'s per-logger level cache. The customer's single knob +//! (`setLevel`) drives both — there is no separate Rust-side level +//! argument. +//! +//! ## Reconfiguration +//! +//! `pyo3_log` caches logger objects and their levels on first use. If a +//! customer changes levels *after* the first kernel log (e.g. raises a +//! logger to DEBUG mid-session), call [`reset_logging`] to clear the +//! cache so the new level takes effect. The connector calls this after +//! it adjusts logging; most customers configure logging before +//! connecting and never need it. + +use pyo3::prelude::*; +use pyo3_log::{Caching, Logger, ResetHandle}; +use std::sync::{Mutex, OnceLock}; + +/// Logger target the kernel tags every event with. Maps to the Python +/// logger `databricks.sql.kernel` via `pyo3_log`'s `::` -> `.` rule. +/// +/// Re-exported from the kernel crate (not a local literal) so the target +/// this crate filters on is *guaranteed* identical to the one the kernel +/// emits — the two cannot drift apart. +use databricks_sql_kernel::KERNEL_LOG_TARGET as KERNEL_TARGET; + +/// Target for breadcrumbs emitted at the pyo3 boundary itself (GIL +/// detach / call entry), distinct from the kernel core's events. Maps to +/// the Python logger `databricks.sql.kernel.pyo3` — a child of +/// `databricks.sql.kernel`, so the kernel-only scope filter (which keys +/// on the `databricks::sql::kernel` prefix) still forwards it, and a +/// customer can isolate boundary logs from core kernel logs by name. +pub(crate) const PYO3_LOG_TARGET: &str = "databricks::sql::kernel::pyo3"; + +/// One-time install state. Tristate (rather than `Option`) +/// so a *failed* install is sticky: we don't retry `Logger::install()` +/// — which re-walks construction + the global-logger set — on every +/// subsequent `init_logging` call. +enum LogState { + /// No install attempted yet. + NotInstalled, + /// Installed; handle retained for [`reset_logging`]. + Installed(ResetHandle), + /// Install was attempted and failed (or `Logger` construction + /// failed). Sticky — we won't try again this process. + Failed, +} + +/// Holds the install state so [`reset_logging`] can reach the +/// `ResetHandle` and repeated `init_logging` calls stay cheap. `Mutex` +/// poisoning is handled (`into_inner`) rather than `unwrap`-panicked — +/// a logging helper must never take down the process. +static LOG_STATE: OnceLock> = OnceLock::new(); + +/// Lock the state, recovering the guard if a previous holder panicked +/// while holding it (poisoned). Logging must never panic the caller, so +/// we never `unwrap` the lock. +fn lock_state() -> std::sync::MutexGuard<'static, LogState> { + LOG_STATE + .get_or_init(|| Mutex::new(LogState::NotInstalled)) + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// Install the `tracing`/`log` -> Python `logging` bridge. +/// +/// Idempotent: the first call installs `pyo3_log`; later calls are +/// no-ops (a process may only have one global `log` logger, and a +/// second install would error). Safe to call from every `Session` +/// construction — the connector calls it once at kernel-backend import. +/// +/// Forwards records from **all** Rust crates — the kernel's own events +/// (under `databricks.sql.kernel` / `…::pyo3`) *and* the HTTP stack it +/// depends on (`hyper_util.client…`, `reqwest.connect`, `rustls`, …), +/// each landing under its own Python logger name. This is intentional: +/// the verbosity is still gated by each Python logger's level, and the +/// dependency crates are near-silent above DEBUG — so normal operation +/// stays quiet, while a customer who turns on DEBUG to diagnose a +/// connectivity / TLS issue gets the full wire-level picture in one +/// shot, with no flag to flip and no support round-trip to ask for it. +/// The per-record GIL re-acquire cost of forwarding deps only +/// materializes when DEBUG is actually enabled on those loggers; a +/// customer can silence them with the standard +/// `logging.getLogger("hyper_util").setLevel(WARNING)`. +/// +/// Returns `true` if this call performed the install, `false` otherwise +/// (already installed, a prior attempt failed, `Logger` construction +/// failed, or another global `log` logger is already set). Never panics: +/// a logging helper must not be able to tear down the host process. +pub(crate) fn init_logging(py: Python<'_>) -> bool { + let mut state = lock_state(); + // Already installed, or a prior attempt failed — don't retry. Retry + // would re-run `Logger::install()`'s global-logger set, which is not + // free, on every Session construction. + if !matches!(*state, LogState::NotInstalled) { + return false; + } + + // `LoggersAndLevels` caching: resolve each Python logger object and + // its effective level once, then gate subsequent records cheaply + // without re-entering Python. The default filter forwards every + // target at `Trace`; the per-logger Python level does the real + // gating. The explicit kernel `filter_target` is redundant under a + // `Trace` default but documents the contract target and guards + // against a future default change silently dropping kernel records. + // + // `Logger::new` returns a `PyResult` — it can fail if the Python + // `logging` module can't be imported or the interpreter is mid + // shutdown. We must NOT `expect()` it: an unwinding panic across the + // pyo3/FFI boundary is undefined behavior and would tear down the + // process over a non-essential feature. Treat it as a sticky failure. + let logger = match Logger::new(py, Caching::LoggersAndLevels) { + Ok(l) => l, + Err(_) => { + *state = LogState::Failed; + return false; + } + }; + let handle = logger + .filter(log::LevelFilter::Trace) + .filter_target(KERNEL_TARGET.to_owned(), log::LevelFilter::Trace) + .install(); + + match handle { + Ok(h) => { + *state = LogState::Installed(h); + true + } + Err(_) => { + // A global `log` logger is already installed (e.g. the host + // application or another library set one up). We leave it in + // place; kernel records then flow to *that* logger (whatever + // sink it points at — e.g. env_logger to stderr), NOT to + // Python `logging`. Sticky so we don't retry the failing + // install on every call. + *state = LogState::Failed; + false + } + } +} + +/// Clear `pyo3_log`'s logger/level caches so a Python-side logging +/// reconfiguration (e.g. a `setLevel` call after the first kernel log) +/// takes effect. No-op if logging was never installed. Never panics. +pub(crate) fn reset_logging() { + if let LogState::Installed(handle) = &*lock_state() { + handle.reset(); + } +} + +#[cfg(test)] +mod tests { + use super::KERNEL_TARGET; + + /// Layer 2 of the logger-name drift guard (see also the kernel's + /// `klog::tests::klog_emits_contract_target` and the Python + /// `test_logging.py` end-to-end test). The Python logger name + /// customers configure — `databricks.sql.kernel` — is derived by + /// `pyo3_log` from this target via `::` -> `.`. The target the kernel + /// *emits* and the target this crate *filters on* must be the same + /// string, or kernel records would be filtered out / land on the + /// wrong logger. This pins both halves of that contract. + #[test] + fn kernel_target_matches_contract() { + // The exact string the kernel's `klog` shim stamps on every + // event (kept in sync with `databricks_sql_kernel`'s + // `klog::KERNEL_LOG_TARGET`). pyo3_log maps this to the Python + // logger `databricks.sql.kernel`. + assert_eq!(KERNEL_TARGET, "databricks::sql::kernel"); + assert_eq!( + KERNEL_TARGET.replace("::", "."), + "databricks.sql.kernel", + "pyo3_log's ::->. mapping must yield the documented Python logger name" + ); + } +} diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 12bc503e..d02709ba 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -170,6 +170,14 @@ impl Session { Some(t) => t.to_owned(), None if access_token.is_some() => "pat".to_owned(), None => { + // Boundary-only breadcrumb: this rejection happens in + // pyo3 *before* any kernel code runs, so the kernel emits + // nothing. Without this, a customer who turned on DEBUG to + // chase a connection failure would see an empty log. + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Session.__new__ rejected: no auth credentials provided" + ); return Err(pyo3::exceptions::PyValueError::new_err( "Session requires auth: pass access_token (PAT) or set \ auth_type to 'oauth-m2m' / 'oauth-u2m' with the matching \ @@ -270,6 +278,10 @@ impl Session { // `Session::open` is async and grabs the current tokio handle. // Drive it on the runtime; the macro detaches the GIL for the // I/O and maps kernel errors into `KernelError`. + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Session.__new__: opening kernel session (GIL released)" + ); let rt = runtime.clone(); let session = run_kernel!(py, rt, async { let mut builder = KSession::builder() @@ -337,6 +349,10 @@ impl Session { }; let SessionInner { session, runtime } = inner; let rt = runtime; + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Session.close: closing kernel session (GIL released)" + ); run_kernel!(py, rt, session.close())?; Ok(()) } diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 404f0939..a1c1c156 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -192,6 +192,10 @@ impl Statement { fn execute(&mut self, py: Python<'_>) -> PyResult { let inner = alive_mut!(self, "Statement"); let runtime = inner.runtime.clone(); + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Statement.execute: running statement synchronously (GIL released)" + ); let exec = run_kernel!(py, runtime, inner.stmt.execute())?; Ok(ExecutedStatement::new(exec, runtime)) } @@ -207,6 +211,10 @@ impl Statement { fn submit(&mut self, py: Python<'_>) -> PyResult { let inner = alive_mut!(self, "Statement"); let runtime = inner.runtime.clone(); + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Statement.submit: submitting statement async (GIL released)" + ); let exec = run_kernel!(py, runtime, inner.stmt.submit())?; Ok(ExecutedAsyncStatement::new(exec, runtime)) } diff --git a/src/auth/oauth/cache.rs b/src/auth/oauth/cache.rs index 1a03f26c..6d6ba35b 100644 --- a/src/auth/oauth/cache.rs +++ b/src/auth/oauth/cache.rs @@ -116,7 +116,7 @@ impl TokenCache { // Check if cache file exists if !cache_path.exists() { - tracing::debug!("Token cache miss: file does not exist at {:?}", cache_path); + crate::klog::debug!("Token cache miss: file does not exist at {:?}", cache_path); return None; } @@ -124,16 +124,20 @@ impl TokenCache { match fs::read_to_string(&cache_path) { Ok(contents) => match serde_json::from_str::(&contents) { Ok(token) => { - tracing::debug!("Token cache hit: loaded from {:?}", cache_path); + crate::klog::debug!("Token cache hit: loaded from {:?}", cache_path); Some(token) } Err(e) => { - tracing::warn!("Token cache corrupted at {:?}, ignoring: {}", cache_path, e); + crate::klog::warn!( + "Token cache corrupted at {:?}, ignoring: {}", + cache_path, + e + ); None } }, Err(e) => { - tracing::warn!("Failed to read token cache at {:?}: {}", cache_path, e); + crate::klog::warn!("Failed to read token cache at {:?}: {}", cache_path, e); None } } @@ -156,7 +160,7 @@ impl TokenCache { let cache_path = match Self::cache_file_path(host, client_id, scopes) { Some(path) => path, None => { - tracing::warn!("Cannot determine cache directory, token will not be cached"); + crate::klog::warn!("Cannot determine cache directory, token will not be cached"); return; } }; @@ -164,7 +168,7 @@ impl TokenCache { // Create cache directory if it doesn't exist, with 700 permissions (owner only) if let Some(parent) = cache_path.parent() { if let Err(e) = fs::create_dir_all(parent) { - tracing::warn!("Failed to create cache directory {:?}: {}", parent, e); + crate::klog::warn!("Failed to create cache directory {:?}: {}", parent, e); return; } // Tighten directory permissions to 700 (owner read/write/execute only) @@ -179,7 +183,7 @@ impl TokenCache { let json = match serde_json::to_string_pretty(token) { Ok(j) => j, Err(e) => { - tracing::warn!("Failed to serialize token for cache: {}", e); + crate::klog::warn!("Failed to serialize token for cache: {}", e); return; } }; @@ -191,13 +195,13 @@ impl TokenCache { match File::create(&temp_path) { Ok(mut file) => { if let Err(e) = file.write_all(json.as_bytes()) { - tracing::warn!("Failed to write token cache to {:?}: {}", temp_path, e); + crate::klog::warn!("Failed to write token cache to {:?}: {}", temp_path, e); let _ = fs::remove_file(&temp_path); // Clean up temp file return; } } Err(e) => { - tracing::warn!("Failed to create temp cache file {:?}: {}", temp_path, e); + crate::klog::warn!("Failed to create temp cache file {:?}: {}", temp_path, e); return; } } @@ -207,7 +211,7 @@ impl TokenCache { { use std::os::unix::fs::PermissionsExt; if let Err(e) = fs::set_permissions(&temp_path, fs::Permissions::from_mode(0o600)) { - tracing::warn!("Failed to set cache file permissions: {}", e); + crate::klog::warn!("Failed to set cache file permissions: {}", e); let _ = fs::remove_file(&temp_path); // Clean up temp file return; } @@ -215,7 +219,7 @@ impl TokenCache { // Atomically rename temp file to final cache file if let Err(e) = fs::rename(&temp_path, &cache_path) { - tracing::warn!( + crate::klog::warn!( "Failed to rename temp cache file {:?} to {:?}: {}", temp_path, cache_path, @@ -225,7 +229,7 @@ impl TokenCache { return; } - tracing::debug!("Token cached successfully at {:?}", cache_path); + crate::klog::debug!("Token cached successfully at {:?}", cache_path); } } diff --git a/src/auth/oauth/callback.rs b/src/auth/oauth/callback.rs index 4bec1104..97337780 100644 --- a/src/auth/oauth/callback.rs +++ b/src/auth/oauth/callback.rs @@ -256,13 +256,13 @@ impl CallbackServer { break; } Err(e) => { - tracing::warn!("Failed to handle callback request: {}", e); + crate::klog::warn!("Failed to handle callback request: {}", e); // Continue listening for another request } } } Err(e) => { - tracing::error!("Failed to accept connection: {}", e); + crate::klog::error!("Failed to accept connection: {}", e); break; } } diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 2d2e8b08..963397c3 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -226,16 +226,16 @@ impl AuthorizationCodeProvider { if let Some(cached_token) = TokenCache::load(host, client_id, &scopes) { // Check if the cached token has a refresh token if cached_token.refresh_token.is_some() { - tracing::debug!("Loaded cached token with refresh_token for U2M flow"); + crate::klog::debug!("Loaded cached token with refresh_token for U2M flow"); // Store the cached token - TokenStore will handle refresh if needed // We need to manually insert it since get_or_refresh expects to call the closure // Let's trigger a get_or_refresh with a closure that returns the cached token let _ = token_store.get_or_refresh(move || Ok(cached_token.clone())); } else { - tracing::debug!("Cached token has no refresh_token, will trigger browser flow"); + crate::klog::debug!("Cached token has no refresh_token, will trigger browser flow"); } } else { - tracing::debug!( + crate::klog::debug!( "No cached token found for U2M flow, will trigger browser flow on first auth" ); } @@ -316,7 +316,7 @@ impl AuthProvider for AuthorizationCodeProvider { if let Some(cached_token) = TokenCache::load(&host, &client_id, &scopes) { if let Some(ref refresh_token_str) = cached_token.refresh_token { // Try refreshing the token - tracing::debug!("Attempting to refresh token via refresh_token"); + crate::klog::debug!("Attempting to refresh token via refresh_token"); // Build OAuth client let oauth_client = BasicClient::new(ClientId::new(client_id.clone())) @@ -340,7 +340,7 @@ impl AuthProvider for AuthorizationCodeProvider { .await { Ok(token_response) => { - tracing::debug!("Token refresh successful"); + crate::klog::debug!("Token refresh successful"); // Convert to OAuthToken let access_token = token_response.access_token().secret().to_string(); @@ -376,7 +376,7 @@ impl AuthProvider for AuthorizationCodeProvider { return Ok(token); } Err(e) => { - tracing::warn!( + crate::klog::warn!( "Token refresh failed, falling back to browser flow: {}", e ); @@ -387,7 +387,7 @@ impl AuthProvider for AuthorizationCodeProvider { } // No cached token or refresh failed - trigger browser flow - tracing::debug!("Initiating browser-based authorization code flow"); + crate::klog::debug!("Initiating browser-based authorization code flow"); // Generate PKCE challenge let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256(); @@ -427,12 +427,12 @@ impl AuthProvider for AuthorizationCodeProvider { // Launch browser (unless suppressed for testing) if open_browser { - tracing::info!("Opening browser for OAuth authorization: {}", auth_url); + crate::klog::info!("Opening browser for OAuth authorization: {}", auth_url); if let Err(e) = open::that(auth_url.as_str()) { - tracing::warn!("Failed to automatically open browser: {}. Please manually navigate to: {}", e, auth_url); + crate::klog::warn!("Failed to automatically open browser: {}. Please manually navigate to: {}", e, auth_url); } } else { - tracing::debug!("Browser opening suppressed, authorization URL: {}", auth_url); + crate::klog::debug!("Browser opening suppressed, authorization URL: {}", auth_url); } // Wait for callback diff --git a/src/client/http.rs b/src/client/http.rs index 44def560..46f81942 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -27,12 +27,12 @@ use crate::client::retry::{ calculate_backoff, RequestCategory, RequestType, RetryConfig, RetryStrategy, }; use crate::kernel_error::{Error, Result}; +use crate::klog::{debug, warn}; use reqwest::{Client, NoProxy, Proxy, Request, Response}; use std::collections::HashMap; use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use tokio::time::sleep; -use tracing::{debug, warn}; /// Configuration for HTTP proxy. /// diff --git a/src/client/sea.rs b/src/client/sea.rs index 7864c657..a0161daf 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -23,6 +23,7 @@ use crate::client::{ InlineChunkFetchResult, SessionInfo, Transport, TransportConfig, }; use crate::kernel_error::{Error, Result}; +use crate::klog::{debug, warn}; use crate::metadata::sql::SqlCommandBuilder; use crate::reader::ResultReaderFactory; use crate::types::cloudfetch::CloudFetchLink; @@ -35,7 +36,6 @@ use reqwest::Method; use std::collections::HashMap; use std::sync::{Arc, OnceLock}; use tokio::runtime::Handle as RuntimeHandle; -use tracing::{debug, warn}; /// Internal terminal-outcome for a single SEA statement response. /// @@ -725,7 +725,7 @@ impl Transport for SeaRestTransport { .execute(request, RequestType::CloseSession) .await { - tracing::warn!( + crate::klog::warn!( session_id = %session_id, error = %e, "delete_session failed after HTTP retries; server-side session will be reclaimed by idle timeout" @@ -1005,7 +1005,7 @@ impl Transport for SeaRestTransport { .execute(request, RequestType::CloseStatement) .await { - tracing::warn!( + crate::klog::warn!( statement_id = %statement_id, error = %e, "close_statement failed after HTTP retries; surfacing to caller (Drop fallback close will run)" diff --git a/src/config.rs b/src/config.rs index 5d0ba400..d75cb4b6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -917,7 +917,7 @@ pub(crate) fn filter_session_conf( // the caller's casing and not uppercased. out.insert((*canonical).to_string(), v); } else { - tracing::warn!( + crate::klog::warn!( key = %k, "dropping unknown session_conf key (not in kernel allowlist); \ see https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-parameters" diff --git a/src/klog.rs b/src/klog.rs new file mode 100644 index 00000000..cec1fb97 --- /dev/null +++ b/src/klog.rs @@ -0,0 +1,202 @@ +// 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. + +//! Kernel logging shim — fixes every event's `tracing` target to +//! `databricks::sql::kernel`. +//! +//! ## Why this exists +//! +//! The pyo3 binding routes kernel logs into Python's `logging` via +//! `pyo3_log`, which derives the Python logger name from the record +//! `target` by replacing `::` with `.` (and nothing else — there is no +//! rename hook). The default `tracing` target is the module path +//! (`databricks_sql_kernel::session`, …), whose crate-root token has +//! underscores, so it would surface as the Python logger +//! `databricks_sql_kernel.*` — a *sibling* of the connector's +//! `databricks.sql.*` namespace, which `setLevel("databricks.sql")` +//! would not reach. +//! +//! By tagging every event with the explicit target +//! `databricks::sql::kernel`, records map to the Python logger +//! **`databricks.sql.kernel`** — a child of `databricks.sql`, so one +//! `setLevel` on the connector root cascades to the kernel. The logger +//! name is a public, effectively-permanent contract; this shim is what +//! keeps it correct without per-call-site `target:` annotations. +//! +//! ## Usage +//! +//! Replace `use tracing::{debug, warn};` with +//! `use crate::klog::{debug, warn};` in a module. Call sites are +//! unchanged — these macros accept the same forms as `tracing`'s +//! (message, format args, and structured fields). Span macros +//! (`info_span!`, `#[instrument]`) keep coming from `tracing`; their +//! 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 single target string every kernel event carries. +/// +/// `pub` (not `pub(crate)`) so binding crates can reference the *same* +/// constant instead of re-typing the literal — this is what lets the +/// pyo3 crate filter on exactly the target the kernel emits, with no +/// 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`. +pub const KERNEL_LOG_TARGET: &str = "databricks::sql::kernel"; + +// The macros are defined with `klog_`-prefixed names and re-exported +// under the bare `debug` / `info` / … names below. The indirection is +// needed because a `macro_rules! debug` (and `warn`) re-exported under +// its own name is `E0659`-ambiguous with the built-in attributes +// `debug` / `warn`; defining under a distinct name and re-exporting +// `as debug` sidesteps the clash while still letting call sites write +// `use crate::klog::{debug, warn};` and call `debug!(…)` unchanged. +macro_rules! klog_debug { + ($($arg:tt)*) => { + ::tracing::debug!(target: $crate::klog::KERNEL_LOG_TARGET, $($arg)*) + }; +} +macro_rules! klog_info { + ($($arg:tt)*) => { + ::tracing::info!(target: $crate::klog::KERNEL_LOG_TARGET, $($arg)*) + }; +} +macro_rules! klog_warn { + ($($arg:tt)*) => { + ::tracing::warn!(target: $crate::klog::KERNEL_LOG_TARGET, $($arg)*) + }; +} +macro_rules! klog_error { + ($($arg:tt)*) => { + ::tracing::error!(target: $crate::klog::KERNEL_LOG_TARGET, $($arg)*) + }; +} +// `trace!` is part of the logging surface for completeness; no call +// site uses it today, hence the allows. +#[allow(unused_macros)] +macro_rules! klog_trace { + ($($arg:tt)*) => { + ::tracing::trace!(target: $crate::klog::KERNEL_LOG_TARGET, $($arg)*) + }; +} + +#[allow(unused_imports)] +pub(crate) use { + klog_debug as debug, klog_error as error, klog_info as info, klog_trace as trace, + 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:?}" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index b9602956..f1559a13 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -92,6 +92,7 @@ compile_error!( pub mod auth; pub mod client; +pub(crate) mod klog; pub(crate) mod logging; pub mod metadata; pub mod reader; @@ -116,6 +117,11 @@ pub use config::{ ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TransportMode, }; pub use kernel_error::{Error, ErrorCode, Result}; +/// The `tracing` target string stamped on every kernel log event. +/// Binding crates (pyo3, napi) reference this constant directly so the +/// logger name they expose to users can never drift from what the +/// kernel actually emits. See [`klog::KERNEL_LOG_TARGET`]. +pub use klog::KERNEL_LOG_TARGET; pub use metadata_v0::{Identifier, LikePattern, Metadata}; pub use result_stream::{OwnedBatchIter, ResultBatch, ResultStream, Row, SchemaRef}; pub use session::{Session, SessionBuilder}; diff --git a/src/logging.rs b/src/logging.rs index bf92c931..15e9ee37 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -15,6 +15,7 @@ //! Logging configuration for the Databricks SQL Kernel. //! //! Initializes a `tracing-subscriber` with file or stderr output. +//! This path is for **direct-Rust and C-ABI (ODBC / Go) consumers**. //! //! ## Configuration priority //! @@ -28,6 +29,23 @@ //! # Via environment variable //! RUST_LOG=databricks_sql_kernel=debug ./my_app //! ``` +//! +//! ## Relationship to the pyo3 / Python path +//! +//! The Python binding does **not** install this subscriber. The +//! `tracing` crate is built with its `log` feature (see `Cargo.toml`), +//! so when no `tracing` `Subscriber` is installed, every `tracing::*` +//! event also emits a `log::Record`. The pyo3 crate installs +//! [`pyo3_log`] as the `log` consumer and forwards records into +//! Python's `logging` module under the `databricks.sql.kernel` logger +//! (see `pyo3/src/logging.rs`). +//! +//! These two paths are **mutually exclusive**: installing the +//! subscriber below *suppresses* the `log` records pyo3 relies on +//! (that is the documented behaviour of the `tracing/log` feature, as +//! opposed to `log-always`). A single process therefore uses exactly +//! one — `init_logging` here for embedded Rust, or `pyo3_log` for +//! Python. Do not call `init_logging` from the pyo3 crate. #![allow(dead_code)] diff --git a/src/reader/cloudfetch/chunk_downloader.rs b/src/reader/cloudfetch/chunk_downloader.rs index 1504f90e..b0aa8ac9 100644 --- a/src/reader/cloudfetch/chunk_downloader.rs +++ b/src/reader/cloudfetch/chunk_downloader.rs @@ -21,6 +21,7 @@ use crate::client::retry::RequestType; use crate::client::DatabricksHttpClient; use crate::kernel_error::{Error, Result}; +use crate::klog::{debug, warn}; use crate::reader::cloudfetch::arrow_parser::parse_arrow_ipc; use crate::types::cloudfetch::CloudFetchLink; use crate::types::sea::CompressionCodec; @@ -28,7 +29,6 @@ use arrow_array::RecordBatch; use reqwest::Method; use std::sync::Arc; use std::time::Instant; -use tracing::{debug, warn}; /// Downloads Arrow data from cloud storage presigned URLs. /// diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 3af8f5ed..85e0bbf4 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -42,13 +42,13 @@ use crate::client::{ChunkLinkFetchResult, Transport}; use crate::kernel_error::{Error, Result}; +use crate::klog::{debug, error}; use crate::types::cloudfetch::CloudFetchLink; use async_trait::async_trait; use dashmap::DashMap; use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; use std::sync::Arc; use tokio::sync::Mutex as TokioMutex; -use tracing::{debug, error}; /// Statement-scoped abstraction for fetching chunk links. /// @@ -479,7 +479,7 @@ impl SeaChunkLinkFetcher { /// remove the fallback path. fn warn_total_chunk_count_fallback(&self, site: &str) { if !self.fallback_warned.swap(true, Ordering::AcqRel) { - tracing::warn!( + crate::klog::warn!( statement_id = %self.statement_id, total_chunk_count = ?self.total_chunk_count_hint, "Server did not populate `external_links[].next_chunk_index` ({site}); \ @@ -498,7 +498,7 @@ impl SeaChunkLinkFetcher { /// truncates multi-batch results. fn warn_silent_eos(&self, site: &str) { if !self.silent_eos_warned.swap(true, Ordering::AcqRel) { - tracing::warn!( + crate::klog::warn!( statement_id = %self.statement_id, "Server emitted neither `next_chunk_index` nor `total_chunk_count` ({site}); \ assuming end-of-stream. If this query has more than one batch of links, \ @@ -521,7 +521,7 @@ impl SeaChunkLinkFetcher { last_chunk_index: i64, ) { if !self.non_monotonic_warned.swap(true, Ordering::AcqRel) { - tracing::warn!( + crate::klog::warn!( statement_id = %self.statement_id, server_next_chunk_index = server_emitted, last_chunk_index, @@ -541,7 +541,7 @@ impl SeaChunkLinkFetcher { /// bounded by `max_chunks_in_memory`; metadata is not). fn warn_runaway_prefetch(&self, site: &str, current_index: i64, ceiling: i64) { if !self.runaway_prefetch_warned.swap(true, Ordering::AcqRel) { - tracing::warn!( + crate::klog::warn!( statement_id = %self.statement_id, next_server_fetch_index = current_index, ceiling, @@ -559,7 +559,7 @@ impl SeaChunkLinkFetcher { /// server bug we want surfaced in production logs. fn warn_empty_with_has_more(&self, site: &str, advanced_from: i64, advanced_to: i64) { if !self.empty_with_has_more_warned.swap(true, Ordering::AcqRel) { - tracing::warn!( + crate::klog::warn!( statement_id = %self.statement_id, advanced_from, advanced_to, diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index d9a5c2d3..15c684ba 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -21,6 +21,7 @@ //! - Consumer API via RecordBatchReader trait use crate::kernel_error::{Error, Result}; +use crate::klog::{debug, error, info, warn}; use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; use crate::reader::cloudfetch::link_fetcher::ChunkLinkFetcher; use crate::types::cloudfetch::{ @@ -35,7 +36,6 @@ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use tokio::sync::Notify; use tokio_util::sync::CancellationToken; -use tracing::{debug, error, info, warn}; /// Merge a list of record batches into larger batches up to `target_rows` each. /// diff --git a/src/reader/inline/provider.rs b/src/reader/inline/provider.rs index 4449a290..d59b05c0 100644 --- a/src/reader/inline/provider.rs +++ b/src/reader/inline/provider.rs @@ -75,6 +75,11 @@ impl InlineArrowProvider { /// Decompresses (if needed) and parses the Arrow IPC stream into RecordBatches. /// /// # Arguments + /// * `statement_id` - SEA statement id, attached to this provider's + /// decode logs so they correlate to a statement in interleaved + /// multi-session logs (matches the CloudFetch streaming provider, + /// which stores `statement_id` for the same reason). Used for + /// logging only — not retained. /// * `attachment` - Raw Arrow IPC bytes (decoded from base64) /// * `compression` - Compression codec used (from manifest.result_compression) /// * `total_row_count` - Authoritative logical row count from @@ -93,19 +98,25 @@ impl InlineArrowProvider { /// - If decompression fails /// - If Arrow IPC parsing fails pub fn new( + statement_id: &str, attachment: Vec, compression: CompressionCodec, total_row_count: Option, ) -> Result { + // Correlate decode logs to the statement (see `statement_id` doc + // above) — matches `create_inline_reader` and the CloudFetch + // streaming provider so a customer filtering by `statement_id` + // sees the whole result lifecycle, decode internals included. if attachment.is_empty() { - tracing::debug!("Empty attachment, creating empty provider"); + crate::klog::debug!(statement_id, "Empty attachment, creating empty provider"); return Ok(Self { batches: VecDeque::new(), schema: None, }); } - tracing::debug!( + crate::klog::debug!( + statement_id, "Parsing inline Arrow data: {} bytes, compression={:?}", attachment.len(), compression @@ -120,7 +131,8 @@ impl InlineArrowProvider { let schema = batches.first().map(|b| b.schema()); - tracing::debug!( + crate::klog::debug!( + statement_id, "Parsed inline Arrow data: {} batches, {} total rows", batches.len(), batches.iter().map(|b| b.num_rows()).sum::() @@ -202,7 +214,7 @@ mod tests { let ipc_data = create_test_arrow_ipc(&[batch]); let mut provider = - InlineArrowProvider::new(ipc_data, CompressionCodec::None, None).unwrap(); + InlineArrowProvider::new("test-stmt", ipc_data, CompressionCodec::None, None).unwrap(); // Check schema assert!(provider.schema().is_some()); @@ -235,7 +247,8 @@ mod tests { } let mut provider = - InlineArrowProvider::new(compressed, CompressionCodec::Lz4Frame, None).unwrap(); + InlineArrowProvider::new("test-stmt", compressed, CompressionCodec::Lz4Frame, None) + .unwrap(); let batch = provider.next_batch().unwrap().unwrap(); assert_eq!(batch.num_rows(), 100); @@ -248,7 +261,7 @@ mod tests { let ipc_data = create_test_arrow_ipc(&[batch1, batch2]); let mut provider = - InlineArrowProvider::new(ipc_data, CompressionCodec::None, None).unwrap(); + InlineArrowProvider::new("test-stmt", ipc_data, CompressionCodec::None, None).unwrap(); // First batch let batch = provider.next_batch().unwrap().unwrap(); @@ -264,7 +277,8 @@ mod tests { #[test] fn test_inline_provider_with_empty_data() { - let provider = InlineArrowProvider::new(vec![], CompressionCodec::None, None).unwrap(); + let provider = + InlineArrowProvider::new("test-stmt", vec![], CompressionCodec::None, None).unwrap(); assert!(provider.schema().is_none()); assert!(!provider.has_more()); @@ -274,7 +288,8 @@ mod tests { fn test_inline_provider_with_invalid_data() { let invalid_data = b"this is not valid arrow ipc data".to_vec(); - let result = InlineArrowProvider::new(invalid_data, CompressionCodec::None, None); + let result = + InlineArrowProvider::new("test-stmt", invalid_data, CompressionCodec::None, None); assert!(result.is_err()); } @@ -313,7 +328,8 @@ mod tests { // exactly 10 rows (parity with Python use_sea and Thrift). let batch = create_test_batch(11); let ipc = create_test_arrow_ipc(&[batch]); - let mut provider = InlineArrowProvider::new(ipc, CompressionCodec::None, Some(10)).unwrap(); + let mut provider = + InlineArrowProvider::new("test-stmt", ipc, CompressionCodec::None, Some(10)).unwrap(); let mut total = 0; while let Some(b) = provider.next_batch().unwrap() { total += b.num_rows(); diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index a8d334f4..59909e2a 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -64,6 +64,7 @@ use crate::client::{InlineChunkFetchResult, Transport}; use crate::kernel_error::{Error, Result}; +use crate::klog::{debug, error}; use crate::reader::cloudfetch::parse_arrow_ipc; use crate::types::sea::CompressionCodec; use arrow_array::RecordBatch; @@ -72,7 +73,7 @@ use async_trait::async_trait; use std::sync::Arc; use tokio::sync::{mpsc, Mutex as TokioMutex}; use tokio::task::JoinHandle; -use tracing::{debug, error, instrument}; +use tracing::instrument; /// Narrow source trait for inline-chunk fetches. /// diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 3f7ab413..78aae840 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -121,7 +121,8 @@ impl ResultReaderFactory { ) -> Result> { // Log manifest info for debugging if let Some(ref manifest) = response.manifest { - tracing::debug!( + crate::klog::debug!( + statement_id, "Result manifest: total_chunks={:?}, total_rows={:?}, total_bytes={:?}, truncated={}", manifest.total_chunk_count, manifest.total_row_count, @@ -141,7 +142,8 @@ impl ResultReaderFactory { // Check result data for CloudFetch or inline results if let Some(ref result) = response.result { // Log what result data we have for debugging the decision path - tracing::debug!( + crate::klog::debug!( + statement_id, "Result data present: external_links={}, inline_arrow_data={} bytes, next_chunk_internal_link={}", result.external_links.as_ref().map(|l| l.len()).unwrap_or(0), result.inline_arrow_data.as_ref().map(|d| d.len()).unwrap_or(0), @@ -160,7 +162,8 @@ impl ResultReaderFactory { // the bridge logic. let total_chunk_count = response.manifest.as_ref().and_then(|m| m.total_chunk_count); - tracing::info!( + crate::klog::info!( + statement_id, "Using CloudFetch reader: {} initial external links, total_chunks={:?}", external_links.len(), total_chunk_count, @@ -249,7 +252,8 @@ impl ResultReaderFactory { cannot derive next-fetch row_offset safely", ) })?; - tracing::info!( + crate::klog::info!( + statement_id, "Using inline-Arrow streaming reader: {} bytes initial chunk, \ next_chunk_index={}", inline_data.len(), @@ -266,7 +270,8 @@ impl ResultReaderFactory { match Self::extract_schema_from_manifest(Some(m)) { Ok(s) => Some(s), Err(e) => { - tracing::warn!( + crate::klog::warn!( + statement_id, "Failed to extract manifest schema for inline-Arrow \ streaming fallback; proceeding without it: {e}" ); @@ -288,7 +293,8 @@ impl ResultReaderFactory { // Single-chunk inline: legacy fast path, parses // the whole result up front. - tracing::info!( + crate::klog::info!( + statement_id, "Using inline Arrow reader: {} bytes of Arrow IPC data", inline_data.len() ); @@ -298,7 +304,12 @@ impl ResultReaderFactory { // server appends when a row_limit truncates the result. let total_row_count = response.manifest.as_ref().and_then(|m| m.total_row_count); - return self.create_inline_reader(inline_data, compression, total_row_count); + return self.create_inline_reader( + statement_id, + inline_data, + compression, + total_row_count, + ); } } @@ -315,7 +326,8 @@ impl ResultReaderFactory { // Valid empty result set - extract schema from manifest // Note: Closed state is valid for inline results where the server delivers // the data (or empty result) and immediately closes the statement. - tracing::info!( + crate::klog::info!( + statement_id, "Using empty reader: no result data present for {:?} statement", response.status.state ); @@ -342,7 +354,7 @@ impl ResultReaderFactory { /// Falls back to an empty schema if no manifest is available. fn extract_schema_from_manifest(manifest: Option<&ResultManifest>) -> Result { let Some(manifest) = manifest else { - tracing::warn!("No manifest available for empty result set, using empty schema"); + crate::klog::warn!("No manifest available for empty result set, using empty schema"); return Ok(Arc::new(Schema::empty())); }; @@ -386,7 +398,8 @@ impl ResultReaderFactory { total_chunk_count: Option, compression: CompressionCodec, ) -> Result> { - tracing::debug!( + crate::klog::debug!( + statement_id, "Creating CloudFetch reader: {} initial links, prefetch_window={}, total_chunks={:?}", external_links.len(), self.config.link_prefetch_window, @@ -429,19 +442,25 @@ impl ResultReaderFactory { fn create_inline_reader( &self, + statement_id: &str, inline_data: &[u8], compression: CompressionCodec, total_row_count: Option, ) -> Result> { - tracing::debug!( + crate::klog::debug!( + statement_id, "Creating inline Arrow reader: {} bytes, compression={:?}, total_row_count={:?}", inline_data.len(), compression, total_row_count ); - let provider = - InlineArrowProvider::new(inline_data.to_vec(), compression, total_row_count)?; + let provider = InlineArrowProvider::new( + statement_id, + inline_data.to_vec(), + compression, + total_row_count, + )?; Ok(Box::new(InlineArrowReader::new(provider))) } @@ -467,7 +486,7 @@ impl ResultReaderFactory { compression: CompressionCodec, manifest_schema: Option, ) -> Result> { - tracing::debug!( + crate::klog::debug!( "Creating inline-Arrow streaming reader: stmt={}, initial_chunk={}, \ next_chunk={:?}, max_in_memory={}", statement_id, diff --git a/src/session.rs b/src/session.rs index 60da5460..58fb3494 100644 --- a/src/session.rs +++ b/src/session.rs @@ -60,13 +60,14 @@ use crate::config::{ ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TransportMode, }; use crate::kernel_error::{Error, Result}; +use crate::klog::debug; use crate::metadata_v0::Metadata; use crate::reader::ResultReaderFactory; use crate::statement::mutable::Statement; use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; -use tracing::{debug, info_span, Instrument, Span}; +use tracing::{info_span, Instrument, Span}; /// Crate-internal session state. Wrapped in `Arc` and shared with /// every child handle (`Statement`, `ExecutedStatement`, …) so the @@ -283,7 +284,7 @@ impl Session { let has_nonempty_user_value = session_conf .iter() .any(|(k, v)| k.eq_ignore_ascii_case("can_cloud_download") && !v.is_empty()); - tracing::debug!( + crate::klog::debug!( cloudfetch_enabled = false, user_value_present = has_nonempty_user_value, "evaluating can_cloud_download injection", @@ -305,8 +306,15 @@ impl Session { .await?; // 5. Tag the per-session tracing span. Future log lines - // inherit `session_id` automatically. - let log_span = info_span!("kernel.session", session_id = %session_info.session_id); + // 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`. + let log_span = info_span!( + target: crate::klog::KERNEL_LOG_TARGET, + "kernel.session", + session_id = %session_info.session_id + ); Ok(Session { inner: Arc::new(SessionInner { diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 32f5c375..b33a879c 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -29,6 +29,7 @@ //! separately. use crate::kernel_error::Result; +use crate::klog::warn; use crate::result_stream::{ResultStream, SchemaRef}; use crate::session::SessionInner; use crate::statement::handle::ExecutedStatementHandle; @@ -37,7 +38,7 @@ use crate::types::sea::StatementStatus as SeaStatementStatus; use async_trait::async_trait; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use tracing::{warn, Instrument}; +use tracing::Instrument; /// Sync-consumption executed handle. pub struct ExecutedStatement { diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index ed9ecb97..3b5e2ade 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -47,6 +47,7 @@ use crate::client::ExecuteResponse; use crate::kernel_error::Error; use crate::kernel_error::Result; +use crate::klog::warn; use crate::result_stream::ResultStream; use crate::session::SessionInner; use crate::statement::handle::ExecutedStatementHandle; @@ -55,7 +56,7 @@ use crate::types::sea::StatementState; use async_trait::async_trait; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use tracing::{warn, Instrument}; +use tracing::Instrument; /// Server-side execution status. /// diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 15411c9e..8b075d6c 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -55,6 +55,7 @@ //! `crate::statement::validity` for the flag implementation. use crate::kernel_error::{Error, Result}; +use crate::klog::warn; use crate::result_stream::ResultStream; use crate::session::SessionInner; use crate::statement::executed::ExecutedStatement; @@ -65,7 +66,7 @@ use crate::statement::validity::ValidityFlag; use crate::types::sea::{ExecuteParams, StatementState}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use tracing::{warn, Instrument}; +use tracing::Instrument; /// Resolve the SEA `(wait_timeout, on_wait_timeout)` pair for an execute / /// submit dispatch. Pure so the precedence rules are unit-testable without