From 883d2b9dc040228cb46b570c6ba839620240589d Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Tue, 7 Jul 2026 10:27:00 +0000 Subject: [PATCH 1/3] [PECOBLR-2096] C ABI: expose OAuth U2M, custom headers, session validity, logging init MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds four C ABI entry points for capabilities the kernel already implements natively but did not surface over the C ABI — the biggest Private Preview unblock for the ODBC (and Go) consumers. - kernel_session_config_set_auth_u2m(client_id?, redirect_port, scopes?) — OAuth U2M (auth code + PKCE, browser flow) + transparent token caching/refresh. New AuthSpec::OAuthU2M variant maps to the existing native AuthConfig::oauth_u2m; all args optional (NULL client_id → databricks-cli, port 0 → 8020, NULL scopes → all-apis+offline_access). - kernel_session_config_set_custom_header(name, value) — append an HTTP header sent on every request; accumulated on the config and applied via HttpConfig.custom_headers in build_session. - kernel_session_is_valid(session, *bool) — local liveness check (session not closed / delete not initiated); no server round-trip. Backs SQLGetConnectAttr(SQL_ATTR_CONNECTION_DEAD). Adds Session::is_valid. - kernel_init_logging(level, file_path) — process-wide, once (OnceLock); wraps the existing init_logging so a host can route kernel `tracing` logs into its own log file. Header declarations with contracts (U2M is interactive; is_valid is local-only; init_logging is once-per-process). C smoke tests cover all four (valid input, NULL-arg rejection, idempotent init). No behavior change to existing paths. cargo fmt / clippy --all-targets clean; 673 lib tests + C smoke pass. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 32 ++++++- src/c_abi/session.rs | 168 +++++++++++++++++++++++++++++++++++- src/session.rs | 12 +++ tests/c/session_smoke.c | 46 ++++++++++ 4 files changed, 255 insertions(+), 3 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8e9cc8d3..eedf990a 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -202,8 +202,8 @@ typedef struct kernel_result_stream_t kernel_result_stream_t; * * Build a config, set exactly one connection form and exactly one auth * form, then hand it to `kernel_session_open` (which consumes it). Only - * PAT and OAuth M2M auth are exposed over the C ABI in v0; OAuth U2M - * (interactive browser flow) is Rust-crate-only. + * PAT, OAuth M2M, and OAuth U2M (interactive browser flow) auth are + * exposed over the C ABI. */ KernelStatusCode kernel_session_config_new(KernelSessionConfig** out); void kernel_session_config_free(KernelSessionConfig* config); @@ -222,12 +222,34 @@ KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, KernelStatusCode kernel_session_config_set_auth_m2m(KernelSessionConfig* config, const char* client_id, const char* client_secret); +/* OAuth U2M (user-to-machine: authorization code + PKCE, browser flow). + * All args optional: `client_id` NULL → public `databricks-cli` client; + * `redirect_port` 0 → kernel default (8020); `scopes` (comma-separated) + * NULL → kernel default (`all-apis`,`offline_access`; `offline_access` + * yields a cached, auto-refreshed refresh token). INTERACTIVE: opening the + * session starts a localhost listener and opens the user's browser. */ +KernelStatusCode kernel_session_config_set_auth_u2m(KernelSessionConfig* config, + const char* client_id, + uint16_t redirect_port, + const char* scopes); /* Add (or overwrite) one server-bound session-conf entry. */ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* config, const char* key, const char* value); +/* Append one HTTP header sent on every request. Call once per header + * (order preserved); `name` and `value` are both required. */ +KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config, + const char* name, const char* value); + +/* Initialize kernel logging, process-wide and ONCE (first call wins; + * later calls are no-ops). `level` is OFF/ERROR/WARN/INFO/DEBUG/TRACE + * (NULL → RUST_LOG, default warn); `file_path` NULL → stderr. Not tied to + * a session — lets a host route kernel logs into its own log file. Always + * returns Success. */ +KernelStatusCode kernel_init_logging(const char* level, const char* file_path); + /* ─── Proxy / TLS (optional) ────────────────────────────────────────── * * All optional; defaults are: no explicit proxy (reqwest honours @@ -268,6 +290,12 @@ KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(Kernel KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session_t** out); KernelStatusCode kernel_session_close(kernel_session_t* session); +/* Report whether a session is still valid (not closed). Writes true/false + * to `*out`. LOCAL check only — no server round-trip, so it does not + * detect a server idle-timeout or dropped link; it reports whether the + * handle has been closed/superseded. Does not take ownership. */ +KernelStatusCode kernel_session_is_valid(const kernel_session_t* session, bool* out); + /* Construct a new mutable statement bound to this session. */ KernelStatusCode kernel_session_new_statement(kernel_session_t* session, kernel_statement_t** out); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 005261d5..ba2e654b 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -24,7 +24,7 @@ //! v0.1 per `docs/spec-v0.md` addendum A5. use super::{block_on_ffi, KernelStatusCode}; -use crate::config::{AuthConfig, ConnectionConfig, ProxyConfig, TlsConfig}; +use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; use crate::kernel_error::Error; use crate::session::Session; use std::collections::HashMap; @@ -60,6 +60,16 @@ enum AuthSpec { client_id: String, client_secret: String, }, + /// OAuth user-to-machine (authorization code + PKCE, browser flow). + /// All fields optional — the kernel fills `databricks-cli` / + /// port 8020 / default scopes when omitted. + OAuthU2M { + client_id: Option, + redirect_port: Option, + /// Comma-separated scopes (split at build time). `None` ⇒ kernel + /// default (`all-apis`, `offline_access`). + scopes: Option, + }, } /// C-side session config builder state. @@ -83,6 +93,9 @@ pub struct KernelSessionConfig { /// TLS relaxations / custom trust (populated by the `..._set_tls_*` /// setters). Defaults to the kernel's strict validation. tls: TlsSpec, + /// Extra HTTP headers sent on every request (accumulated by + /// `..._set_custom_header`, one `(name, value)` pair per call). + custom_headers: Vec<(String, String)>, } /// C-side proxy config captured from `kernel_session_config_set_proxy`. @@ -143,6 +156,7 @@ pub unsafe extern "C" fn kernel_session_config_new( session_conf: HashMap::new(), proxy: None, tls: TlsSpec::default(), + custom_headers: Vec::new(), }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -249,6 +263,94 @@ pub unsafe extern "C" fn kernel_session_config_set_auth_m2m( }) } +/// Set OAuth U2M (user-to-machine: authorization code + PKCE, browser +/// flow) authentication. Mutually exclusive with the other `set_auth_*` +/// setters — the last one called wins. +/// +/// All args are optional (pass NULL to omit): `client_id` defaults to the +/// public `databricks-cli` client, `redirect_port` to 8020, and `scopes` +/// (a comma-separated list) to the kernel default (`all-apis`, +/// `offline_access`). `offline_access` yields a refresh token, which the +/// kernel caches and refreshes transparently. +/// +/// **Behaviour:** opening a session with U2M is interactive — at +/// `kernel_session_open` the kernel starts a localhost listener on the +/// redirect port and opens the user's browser to the workspace authorize +/// endpoint. Only use from an interactive context. +/// +/// # Safety +/// `config` must be a live config handle; the optional args, if non-null, +/// must be NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_auth_u2m( + config: *mut KernelSessionConfig, + client_id: *const c_char, + redirect_port: u16, + scopes: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.auth = Some(AuthSpec::OAuthU2M { + client_id: optional_str(client_id, "client_id")?, + // 0 is the "unset" sentinel → kernel default (8020). + redirect_port: (redirect_port != 0).then_some(redirect_port), + scopes: optional_str(scopes, "scopes")?, + }); + Ok(()) + }) +} + +/// Append one HTTP header sent on every request (e.g. a partner-supplied +/// `X-…` header). Call once per header; order is preserved. Both `name` +/// and `value` are required. Maps to the kernel's `custom_headers`. +/// +/// # Safety +/// `config` must be a live config handle; `name` / `value` must be +/// NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_custom_header( + config: *mut KernelSessionConfig, + name: *const c_char, + value: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + let name = required_str(name, "header name")?; + let value = required_str(value, "header value")?; + c.custom_headers.push((name, value)); + Ok(()) + }) +} + +/// Initialize kernel logging, **process-wide and once**. `level` is one +/// of "OFF"/"ERROR"/"WARN"/"INFO"/"DEBUG"/"TRACE" (NULL ⇒ honour +/// `RUST_LOG`, default `warn`); `file_path` is a log file (NULL ⇒ stderr). +/// +/// Idempotent: the underlying `tracing` subscriber can only be installed +/// once per process, so the **first** call wins and later calls are +/// no-ops (a driver that opens many connections calls this each time with +/// the same target — only the first takes effect). Not tied to a session; +/// call it before/around `kernel_session_open`. Lets an ODBC/Go host route +/// the kernel's logs into the same file it writes its own logs to. +/// +/// Always returns `KernelStatusCode::Success` (a bad path is reported to +/// stderr by the logging layer, not surfaced as an error, to match the +/// crate's best-effort logging-init contract). +/// +/// # Safety +/// `level` / `file_path`, if non-null, must be NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_init_logging( + level: *const c_char, + file_path: *const c_char, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + // Best-effort: a non-UTF-8 arg is treated as absent rather than an + // error, matching the layer's own tolerance. + let level = optional_str(level, "log level").ok().flatten(); + let file = optional_str(file_path, "log file path").ok().flatten(); + crate::logging::init_logging(&crate::logging::LogConfig { level, file }); + KernelStatusCode::Success +} + /// Add (or overwrite) one server-bound session-conf entry. Unknown keys /// are filtered against the kernel allowlist at `open()` time, matching /// the Rust-crate path. @@ -454,6 +556,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result AuthConfig::oauth_m2m(Some(client_id), Some(client_secret), None, None)?, + AuthSpec::OAuthU2M { + client_id, + redirect_port, + scopes, + } => { + // Split the comma-separated scope string; empty ⇒ None + // (kernel default scopes). + let scopes = scopes.and_then(|s| { + let v: Vec = s + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect(); + (!v.is_empty()).then_some(v) + }); + AuthConfig::oauth_u2m(client_id, redirect_port, scopes, None, None) + } }; let mut builder = Session::builder() @@ -491,6 +612,15 @@ fn build_session(config: KernelSessionConfig) -> Result KernelStatusCode::Success } +/// Report whether a session is still valid. Writes `true` to `*out` when +/// the session has not been closed (its server-side delete has not been +/// initiated), `false` otherwise. +/// +/// This is a **local** liveness check — it does NOT round-trip to the +/// server, so it won't detect a server-side idle timeout or a dropped +/// network link. It answers "is this handle still usable" (not +/// closed/superseded), which is what `SQLGetConnectAttr( +/// SQL_ATTR_CONNECTION_DEAD)` needs to avoid driving an already-deleted +/// session. Does not borrow ownership; the caller still owns `session`. +/// +/// # Safety +/// `session` must be a live handle from [`kernel_session_open`] (not yet +/// closed via [`kernel_session_close`]); `out` must be a writable `bool*`. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_is_valid( + session: *const kernel_session_t, + out: *mut bool, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(session) = (session as *const Session).as_ref() else { + crate::c_abi::error::store_error( + Error::invalid_argument().message("kernel_session_is_valid: session must not be null"), + ); + return KernelStatusCode::InvalidArgument; + }; + if out.is_null() { + crate::c_abi::error::store_error( + Error::invalid_argument().message("kernel_session_is_valid: out must not be null"), + ); + return KernelStatusCode::InvalidArgument; + } + std::ptr::write(out, session.is_valid()); + KernelStatusCode::Success +} + /// Construct a new mutable statement bound to this session. On success, /// `*out` holds an owned `kernel_statement_t` the caller releases with /// `kernel_statement_close`. diff --git a/src/session.rs b/src/session.rs index ce6ac4e0..75e54c33 100644 --- a/src/session.rs +++ b/src/session.rs @@ -374,6 +374,18 @@ impl Session { self.inner.initiate_delete(); } + /// Whether this session is still valid — i.e. its server-side delete + /// has not been initiated (via [`Session::close`] or + /// [`Session::initiate_delete`]). This is a **local** liveness signal, + /// not a server round-trip: it reports that the handle has not been + /// closed/superseded, so a subsequent operation won't drive an + /// already-deleted session. It does not detect a server-side idle + /// timeout or a dropped network link. Used by the C ABI's + /// `kernel_session_is_valid`. + pub(crate) fn is_valid(&self) -> bool { + !self.inner.closed.load(std::sync::atomic::Ordering::Acquire) + } + /// Adopt an already-submitted server statement by its id, producing /// an [`ExecutedAsyncStatement`] that can poll [`status`] / await /// results / cancel — without having been the handle that submitted diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index e1f0b588..0cc4cf4b 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -167,6 +167,49 @@ static void test_proxy_and_tls_setters(void) { kernel_session_config_free(config); } +/* U2M + custom-header setters accept valid input; header requires args. */ +static void test_u2m_and_header_setters(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + + /* All U2M args optional — NULL client_id / 0 port / NULL scopes → kernel + * defaults. This only populates the config; it does not open a session, + * so no browser is launched. */ + KernelStatusCode rc = kernel_session_config_set_auth_u2m(config, NULL, 0, NULL); + CHECK(rc == KernelStatusCode_Success, "set_auth_u2m (all defaults) succeeds"); + rc = kernel_session_config_set_auth_u2m(config, "my-client", 8020, "all-apis,offline_access"); + CHECK(rc == KernelStatusCode_Success, "set_auth_u2m (explicit) succeeds"); + + rc = kernel_session_config_set_custom_header(config, "X-Trace-Id", "abc123"); + CHECK(rc == KernelStatusCode_Success, "set_custom_header succeeds"); + rc = kernel_session_config_set_custom_header(config, NULL, "v"); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_custom_header(NULL name) → InvalidArgument"); + rc = kernel_session_config_set_custom_header(config, "X-Foo", NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_custom_header(NULL value) → InvalidArgument"); + + kernel_session_config_free(config); +} + +/* kernel_init_logging is idempotent and null-tolerant. */ +static void test_init_logging(void) { + KernelStatusCode rc = kernel_init_logging("WARN", NULL); + CHECK(rc == KernelStatusCode_Success, "init_logging(level, NULL file) succeeds"); + /* Second call is a no-op (subscriber already installed) but still Success. */ + rc = kernel_init_logging(NULL, NULL); + CHECK(rc == KernelStatusCode_Success, "init_logging twice is safe"); +} + +/* is_valid null-guards its args. */ +static void test_is_valid_null_guards(void) { + bool valid = true; + KernelStatusCode rc = kernel_session_is_valid(NULL, &valid); + CHECK(rc == KernelStatusCode_InvalidArgument, "is_valid(NULL session) → InvalidArgument"); + /* A non-null-but-bogus session pointer is UB per the contract, so we only + * exercise the null-out guard against a null session (checked first). */ + rc = kernel_session_is_valid(NULL, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "is_valid(NULL, NULL) → InvalidArgument"); +} + /* The async submit path is a deferred stub → InvalidArgument, no network. */ static void test_submit_stub_rejects(void) { kernel_executed_async_statement_t* out = NULL; @@ -193,6 +236,9 @@ int main(void) { test_http_path_and_m2m_setters(); test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); + test_u2m_and_header_setters(); + test_init_logging(); + test_is_valid_null_guards(); test_submit_stub_rejects(); test_bind_null_handle_rejected(); From 4aeccce2faf0ba155e3fa4de8fd0e135230c07ff Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 8 Jul 2026 05:13:55 +0000 Subject: [PATCH 2/3] =?UTF-8?q?[PECOBLR-2096]=20C=20ABI:=20fix=20logging?= =?UTF-8?q?=20filter=20target,=20rename=20is=5Fvalid=E2=86=92is=5Fopen,=20?= =?UTF-8?q?add=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the self-review (Code Review Squad) findings on this PR. [F1 Critical] Logging filter never matched. init_logging built the EnvFilter as `databricks_sql_kernel=`, but every kernel log macro emits with target `databricks::sql::kernel` (klog::KERNEL_LOG_TARGET). EnvFilter matches by `::`-delimited prefix, so the underscore token matched nothing and ZERO kernel events passed — the feature was a silent no-op. Now build the directive from KERNEL_LOG_TARGET. [F5] First-call-wins locked out logging on a bad first config. A file-open failure (or level=OFF) committed the OnceLock with no subscriber installed, permanently disabling logging. Now on file-open failure we fall back to stderr within the same call (so logging still works), and init_logging returns a bool; kernel_init_logging maps false → Internal (with a stored error) so a host that can't see stderr learns the requested file wasn't honoured. [is_valid → is_open] Renamed kernel_session_is_valid → kernel_session_is_open (and Session::is_valid → is_open). Over the C ABI the only path that sets `closed` also frees the handle, so a legal probe of a live handle always saw not-closed → the old name over-promised "validity". The honest contract: a LOCAL not-closed check that does not detect a server idle-timeout; the header tells a SQL_ATTR_CONNECTION_DEAD consumer to read true as "not known-dead". [F9/F10] Updated the stale module doc (U2M is now exposed) and the no-auth error message (now lists set_auth_u2m). Tests: extracted parse_scopes (unit-tested: "a, ,b," → [a,b], blanks → None); custom-header ordered/duplicate accumulation; is_open==true on a freshly-opened session (wiremock); init_logging return signal + idempotency; a pin that the filter target is `::`-delimited. cargo fmt / clippy --all-targets clean; 677 lib tests + C smoke + wiremock pass. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 23 ++-- src/c_abi/session.rs | 152 +++++++++++++++++------ src/logging.rs | 106 ++++++++++++---- src/session.rs | 15 ++- tests/c/session_smoke.c | 17 +-- tests/v0_c_abi_session_close_wiremock.rs | 16 ++- 6 files changed, 236 insertions(+), 93 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index eedf990a..6a625c26 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -244,10 +244,13 @@ KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* co const char* name, const char* value); /* Initialize kernel logging, process-wide and ONCE (first call wins; - * later calls are no-ops). `level` is OFF/ERROR/WARN/INFO/DEBUG/TRACE - * (NULL → RUST_LOG, default warn); `file_path` NULL → stderr. Not tied to - * a session — lets a host route kernel logs into its own log file. Always - * returns Success. */ + * later calls are no-ops returning the first call's outcome). `level` is + * OFF/ERROR/WARN/INFO/DEBUG/TRACE (NULL → RUST_LOG, default warn); + * `file_path` NULL → stderr. Not tied to a session — lets a host route + * kernel logs into its own log file. Returns Success when logging was + * installed (or skipped for level OFF); returns Internal (with a stored + * last-error) when the requested `file_path` could not be opened — in + * that case logging falls back to stderr so it still functions. */ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); /* ─── Proxy / TLS (optional) ────────────────────────────────────────── @@ -290,11 +293,13 @@ KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(Kernel KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session_t** out); KernelStatusCode kernel_session_close(kernel_session_t* session); -/* Report whether a session is still valid (not closed). Writes true/false - * to `*out`. LOCAL check only — no server round-trip, so it does not - * detect a server idle-timeout or dropped link; it reports whether the - * handle has been closed/superseded. Does not take ownership. */ -KernelStatusCode kernel_session_is_valid(const kernel_session_t* session, bool* out); +/* Report whether a session is still OPEN (its delete has not been + * initiated). Writes true/false to `*out`. LOCAL check only — no server + * round-trip, so it does NOT detect a server idle-timeout or dropped + * link; it reports only whether the handle has been closed/superseded. + * A host backing SQL_ATTR_CONNECTION_DEAD should read `true` as + * "not known-dead", not a positive liveness guarantee. No ownership. */ +KernelStatusCode kernel_session_is_open(const kernel_session_t* session, bool* out); /* Construct a new mutable statement bound to this session. */ KernelStatusCode kernel_session_new_statement(kernel_session_t* session, diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index ba2e654b..62b1a261 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -14,11 +14,10 @@ //! Session FFI — config marshalling, open / close / new_statement. //! -//! Auth in the v0 C ABI is **PAT + OAuth M2M** only; OAuth U2M -//! (interactive browser flow) is Rust-crate-only per the migration -//! plan §6 ("OAuth U2M and the C ABI"). ODBC / Go consumers use PAT or -//! M2M, or drive their own token flow and inject it (not yet exposed -//! over the C ABI in v0). +//! Auth over the C ABI: **PAT, OAuth M2M, and OAuth U2M** (interactive +//! browser flow) are all exposed (`set_auth_pat` / `set_auth_m2m` / +//! `set_auth_u2m`). A host may also drive its own token flow and inject +//! it via PAT. //! //! Transaction methods (autocommit / commit / rollback) are deferred to //! v0.1 per `docs/spec-v0.md` addendum A5. @@ -331,9 +330,13 @@ pub unsafe extern "C" fn kernel_session_config_set_custom_header( /// call it before/around `kernel_session_open`. Lets an ODBC/Go host route /// the kernel's logs into the same file it writes its own logs to. /// -/// Always returns `KernelStatusCode::Success` (a bad path is reported to -/// stderr by the logging layer, not surfaced as an error, to match the -/// crate's best-effort logging-init contract). +/// Returns `KernelStatusCode::Success` when logging was installed (or +/// intentionally skipped for level `OFF`). Returns +/// `KernelStatusCode::Internal` (with a stored last-error) when the +/// subscriber could not be installed — currently only when the requested +/// `file_path` fails to open — so a caller that can't see stderr (GUI / +/// BI host) can surface the failure or fall back deliberately. Because +/// init is once-per-process, this reflects the FIRST call's outcome. /// /// # Safety /// `level` / `file_path`, if non-null, must be NUL-terminated C strings. @@ -343,12 +346,18 @@ pub unsafe extern "C" fn kernel_init_logging( file_path: *const c_char, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); - // Best-effort: a non-UTF-8 arg is treated as absent rather than an - // error, matching the layer's own tolerance. + // Best-effort on the args: a non-UTF-8 arg is treated as absent rather + // than an error, matching the layer's own tolerance. let level = optional_str(level, "log level").ok().flatten(); let file = optional_str(file_path, "log file path").ok().flatten(); - crate::logging::init_logging(&crate::logging::LogConfig { level, file }); - KernelStatusCode::Success + if crate::logging::init_logging(&crate::logging::LogConfig { level, file }) { + KernelStatusCode::Success + } else { + crate::c_abi::error::store_and_code(Error::new( + crate::kernel_error::ErrorCode::Internal, + "kernel_init_logging: failed to install the logging subscriber (log file could not be opened)", + )) + } } /// Add (or overwrite) one server-bound session-conf entry. Unknown keys @@ -545,6 +554,19 @@ pub unsafe extern "C" fn kernel_session_open( KernelStatusCode::Success } +/// Split a comma-separated OAuth scope string into a scope list. Trims +/// each entry and drops empties; an all-empty / blank input yields `None` +/// so the kernel applies its default scopes. E.g. `"a, ,b,"` → `["a","b"]`. +fn parse_scopes(s: &str) -> Option> { + let v: Vec = s + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect(); + (!v.is_empty()).then_some(v) +} + /// Translate the C-side config into a [`Session`], driving the async /// `Session::open` on the process-wide runtime. Errors are stored in the /// thread-local buffer; the returned `KernelStatusCode` is the mapped @@ -568,8 +590,9 @@ fn build_session(config: KernelSessionConfig) -> Result Result { - // Split the comma-separated scope string; empty ⇒ None - // (kernel default scopes). - let scopes = scopes.and_then(|s| { - let v: Vec = s - .split(',') - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_owned) - .collect(); - (!v.is_empty()).then_some(v) - }); - AuthConfig::oauth_u2m(client_id, redirect_port, scopes, None, None) - } + } => AuthConfig::oauth_u2m( + client_id, + redirect_port, + scopes.and_then(|s| parse_scopes(&s)), + None, + None, + ), }; let mut builder = Session::builder() @@ -694,39 +710,38 @@ pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> KernelStatusCode::Success } -/// Report whether a session is still valid. Writes `true` to `*out` when -/// the session has not been closed (its server-side delete has not been -/// initiated), `false` otherwise. +/// Report whether a session is still **open** (its server-side delete has +/// not been initiated). Writes `true`/`false` to `*out`. /// -/// This is a **local** liveness check — it does NOT round-trip to the -/// server, so it won't detect a server-side idle timeout or a dropped -/// network link. It answers "is this handle still usable" (not -/// closed/superseded), which is what `SQLGetConnectAttr( -/// SQL_ATTR_CONNECTION_DEAD)` needs to avoid driving an already-deleted -/// session. Does not borrow ownership; the caller still owns `session`. +/// This is a **local** check — it does NOT round-trip to the server, so it +/// will NOT detect a server-side idle timeout or a dropped network link. +/// It answers only "has this handle been closed/superseded". A host using +/// it to back `SQLGetConnectAttr(SQL_ATTR_CONNECTION_DEAD)` should treat a +/// `true` result as "not known-dead" rather than a positive liveness +/// guarantee. Does not borrow ownership; the caller still owns `session`. /// /// # Safety /// `session` must be a live handle from [`kernel_session_open`] (not yet /// closed via [`kernel_session_close`]); `out` must be a writable `bool*`. #[no_mangle] -pub unsafe extern "C" fn kernel_session_is_valid( +pub unsafe extern "C" fn kernel_session_is_open( session: *const kernel_session_t, out: *mut bool, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); let Some(session) = (session as *const Session).as_ref() else { crate::c_abi::error::store_error( - Error::invalid_argument().message("kernel_session_is_valid: session must not be null"), + Error::invalid_argument().message("kernel_session_is_open: session must not be null"), ); return KernelStatusCode::InvalidArgument; }; if out.is_null() { crate::c_abi::error::store_error( - Error::invalid_argument().message("kernel_session_is_valid: out must not be null"), + Error::invalid_argument().message("kernel_session_is_open: out must not be null"), ); return KernelStatusCode::InvalidArgument; } - std::ptr::write(out, session.is_valid()); + std::ptr::write(out, session.is_open()); KernelStatusCode::Success } @@ -760,3 +775,58 @@ pub unsafe extern "C" fn kernel_session_new_statement( // pub unsafe extern "C" fn kernel_session_set_autocommit(...) -> KernelStatusCode; // pub unsafe extern "C" fn kernel_session_commit(...) -> KernelStatusCode; // pub unsafe extern "C" fn kernel_session_rollback(...) -> KernelStatusCode; + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::CString; + + #[test] + fn parse_scopes_trims_and_drops_empties() { + assert_eq!( + parse_scopes("a, ,b,"), + Some(vec!["a".to_string(), "b".to_string()]) + ); + assert_eq!( + parse_scopes("all-apis,offline_access"), + Some(vec!["all-apis".to_string(), "offline_access".to_string()]) + ); + // All-empty / blank → None so the kernel applies its defaults. + assert_eq!(parse_scopes(""), None); + assert_eq!(parse_scopes(" , , "), None); + } + + /// Custom headers accumulate in call order and are NOT deduped (the + /// contract is append/ordered, unlike session_conf's overwrite map). + /// Guards against a refactor to a dedup'ing map silently dropping + /// repeated header names. + #[test] + fn custom_headers_accumulate_in_order_with_duplicates() { + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let pairs = [("X-A", "1"), ("X-B", "2"), ("X-A", "3")]; + for (n, v) in pairs { + let name = CString::new(n).unwrap(); + let value = CString::new(v).unwrap(); + assert_eq!( + kernel_session_config_set_custom_header(config, name.as_ptr(), value.as_ptr()), + KernelStatusCode::Success + ); + } + let got = &config.as_ref().unwrap().custom_headers; + let expected: Vec<(String, String)> = pairs + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect(); + assert_eq!( + *got, expected, + "headers must be appended in order, duplicates kept" + ); + kernel_session_config_free(config); + } + } +} diff --git a/src/logging.rs b/src/logging.rs index 15e9ee37..9f0e0bcd 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -57,7 +57,12 @@ use tracing_subscriber::{ EnvFilter, }; -static LOGGING_INITIALIZED: OnceLock<()> = OnceLock::new(); +/// Records the outcome of the first `init_logging` call: `true` if the +/// subscriber was installed (or intentionally skipped for level=OFF), +/// `false` if it could not be installed (e.g. the log file failed to +/// open). Later calls return this same first-call outcome ("first call +/// wins"). +static LOGGING_INITIALIZED: OnceLock = OnceLock::new(); /// Logging configuration passed via ADBC database options. #[derive(Debug, Clone, Default)] @@ -70,42 +75,56 @@ pub(crate) struct LogConfig { /// Initialize the tracing subscriber. /// -/// Uses `OnceLock` to ensure this is called at most once per process. -/// The first `Database::new_connection()` call configures logging; -/// subsequent calls are no-ops. -pub(crate) fn init_logging(config: &LogConfig) { - LOGGING_INITIALIZED.get_or_init(|| { - // Check if the configured level is "OFF" — skip initialization entirely +/// Uses `OnceLock` to ensure this runs at most once per process — the +/// first call configures logging and subsequent calls are no-ops that +/// return the first call's outcome. +/// +/// Returns `true` if the subscriber was installed (or intentionally +/// skipped because the level is `OFF`), `false` if it could not be +/// installed — currently only when the requested log file fails to open. +/// Callers that cannot see stderr (GUI / BI hosts) can use the `false` +/// return to surface the failure their own way instead of assuming logs +/// are flowing. +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; + 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!("databricks_sql_kernel={}", level.to_lowercase())) + EnvFilter::new(format!("{}={}", crate::klog::KERNEL_LOG_TARGET, level.to_lowercase())) } else { // Fall back to RUST_LOG env var, default to warn - EnvFilter::try_from_default_env() - .unwrap_or_else(|_| EnvFilter::new("databricks_sql_kernel=warn")) + EnvFilter::try_from_default_env().unwrap_or_else(|_| { + EnvFilter::new(format!("{}=warn", crate::klog::KERNEL_LOG_TARGET)) + }) }; - if let Some(ref path) = config.file { - let file = match std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(path) - { - Ok(f) => f, + // 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. + let file = config.file.as_ref().and_then(|path| { + match std::fs::OpenOptions::new().create(true).append(true).open(path) { + Ok(f) => Some(f), Err(e) => { - eprintln!( - "databricks-sql-kernel: failed to open log file {}: {}", - path, e - ); - return; + eprintln!("databricks-sql-kernel: failed to open log file {path}: {e}; falling back to stderr"); + None } - }; + } + }); + let file_requested_ok = config.file.is_none() || file.is_some(); + if let Some(file) = file { tracing_subscriber::registry() .with(filter) .with( @@ -129,7 +148,8 @@ pub(crate) fn init_logging(config: &LogConfig) { .try_init() .ok(); } - }); + file_requested_ok + }) } #[cfg(test)] @@ -152,4 +172,40 @@ mod tests { assert_eq!(config.level.as_deref(), Some("DEBUG")); assert_eq!(config.file.as_deref(), Some("/tmp/test.log")); } + + /// The filter directive must be built from `KERNEL_LOG_TARGET` so it + /// actually matches the target the kernel's log macros emit with. + /// A single-token filter like "databricks_sql_kernel" would match + /// nothing (EnvFilter uses `::`-delimited prefix matching), silently + /// dropping every kernel event. This pins the target string the + /// filter is derived from so a regression to the wrong token is caught + /// without depending on installing the process-global subscriber. + #[test] + fn log_target_is_double_colon_delimited() { + assert_eq!(crate::klog::KERNEL_LOG_TARGET, "databricks::sql::kernel"); + // The directive we build (see init_logging) must use this exact + // target, not an underscore-joined token. + let directive = format!("{}=debug", crate::klog::KERNEL_LOG_TARGET); + assert!(directive.starts_with("databricks::sql::kernel=")); + // EnvFilter must accept the directive we construct. + let _filter = EnvFilter::new(directive); + } + + /// `init_logging` returns a bool signal and is idempotent in its + /// return value. (The subscriber is process-global, so we assert the + /// contract via the return rather than installing/observing output, + /// which would be order-dependent across the shared test binary.) + #[test] + fn init_logging_returns_signal_and_is_idempotent() { + // stderr config always succeeds; a second call returns the same + // (first-call-wins) outcome. + let cfg = LogConfig { + level: Some("warn".to_string()), + file: None, + }; + let first = init_logging(&cfg); + let second = init_logging(&cfg); + assert!(first, "stderr logging should install successfully"); + assert_eq!(first, second, "later calls return the first-call outcome"); + } } diff --git a/src/session.rs b/src/session.rs index 75e54c33..dc40bfb2 100644 --- a/src/session.rs +++ b/src/session.rs @@ -374,15 +374,14 @@ impl Session { self.inner.initiate_delete(); } - /// Whether this session is still valid — i.e. its server-side delete + /// Whether this session is still open — i.e. its server-side delete /// has not been initiated (via [`Session::close`] or - /// [`Session::initiate_delete`]). This is a **local** liveness signal, - /// not a server round-trip: it reports that the handle has not been - /// closed/superseded, so a subsequent operation won't drive an - /// already-deleted session. It does not detect a server-side idle - /// timeout or a dropped network link. Used by the C ABI's - /// `kernel_session_is_valid`. - pub(crate) fn is_valid(&self) -> bool { + /// [`Session::initiate_delete`]). This is a **local** check, not a + /// server round-trip: it reports whether the handle has been + /// closed/superseded, so a caller doesn't drive an already-deleted + /// session. It does **not** detect a server-side idle timeout or a + /// dropped network link. Backs the C ABI's `kernel_session_is_open`. + pub(crate) fn is_open(&self) -> bool { !self.inner.closed.load(std::sync::atomic::Ordering::Acquire) } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 0cc4cf4b..5a895fb9 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -199,15 +199,16 @@ static void test_init_logging(void) { CHECK(rc == KernelStatusCode_Success, "init_logging twice is safe"); } -/* is_valid null-guards its args. */ -static void test_is_valid_null_guards(void) { - bool valid = true; - KernelStatusCode rc = kernel_session_is_valid(NULL, &valid); - CHECK(rc == KernelStatusCode_InvalidArgument, "is_valid(NULL session) → InvalidArgument"); +/* is_open null-guards its args. (The true→false behavior is covered by a + * Rust unit test that can build and close a Session without a network.) */ +static void test_is_open_null_guards(void) { + bool open = true; + KernelStatusCode rc = kernel_session_is_open(NULL, &open); + CHECK(rc == KernelStatusCode_InvalidArgument, "is_open(NULL session) → InvalidArgument"); /* A non-null-but-bogus session pointer is UB per the contract, so we only * exercise the null-out guard against a null session (checked first). */ - rc = kernel_session_is_valid(NULL, NULL); - CHECK(rc == KernelStatusCode_InvalidArgument, "is_valid(NULL, NULL) → InvalidArgument"); + rc = kernel_session_is_open(NULL, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "is_open(NULL, NULL) → InvalidArgument"); } /* The async submit path is a deferred stub → InvalidArgument, no network. */ @@ -238,7 +239,7 @@ int main(void) { test_proxy_and_tls_setters(); test_u2m_and_header_setters(); test_init_logging(); - test_is_valid_null_guards(); + test_is_open_null_guards(); test_submit_stub_rejects(); test_bind_null_handle_rejected(); diff --git a/tests/v0_c_abi_session_close_wiremock.rs b/tests/v0_c_abi_session_close_wiremock.rs index 8559d8cf..f78332b6 100644 --- a/tests/v0_c_abi_session_close_wiremock.rs +++ b/tests/v0_c_abi_session_close_wiremock.rs @@ -31,8 +31,8 @@ use std::time::Duration; use databricks_sql_kernel::c_abi::session::{ kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, - kernel_session_config_set_http_path, kernel_session_new_statement, kernel_session_open, - kernel_session_t, KernelSessionConfig, + kernel_session_config_set_http_path, kernel_session_is_open, kernel_session_new_statement, + kernel_session_open, kernel_session_t, KernelSessionConfig, }; use databricks_sql_kernel::c_abi::statement::{kernel_statement_close, kernel_statement_t}; use databricks_sql_kernel::c_abi::KernelStatusCode; @@ -90,6 +90,18 @@ fn session_close_initiates_delete_with_statement_still_open() { ); assert!(!session.is_null()); + // A freshly-opened session reports open (guards against an inverted + // or hardcoded-false is_open). The false case can't be probed over + // the C ABI — kernel_session_close frees the handle in the same + // call — so it's covered by the crate-internal Session::is_open + // path instead. + let mut is_open = false; + assert_eq!( + kernel_session_is_open(session, &mut is_open), + KernelStatusCode::Success + ); + assert!(is_open, "a freshly-opened session must report open"); + // Mint a statement — it holds an Arc clone, so the // session's inner won't drop when we close the session below. let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); From 4f95cb15cd117eaa73ca89bf6ccc75e656caa96c Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 9 Jul 2026 08:58:15 +0000 Subject: [PATCH 3/3] [PECOBLR-2096] C ABI: real is_open false-path test + correct init_logging return contract MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses gopalldb's review on #162. [MAJOR] is_open false path untested; comments falsely claimed coverage. The only assertion was is_open==true on a fresh session; the true→false branch had no test, yet comments claimed a Rust unit test covered it (none existed). An inverted/hardcoded-true is_open would have passed. Added an in-crate wiremock test (session::is_open_tests::is_open_flips_true_to_false_on_delete) that opens a session, asserts is_open()==true, calls initiate_delete(), asserts false — the false path is only reachable in-crate (the C ABI frees the handle on close). Corrected the misleading comments in the wiremock test and session_smoke.c to point at it. [MINOR] Non-UTF-8 log file_path was swallowed to Success. kernel_init_logging used optional_str(file_path).ok().flatten(), collapsing the UTF-8 error to None and returning Success while dropping the path. Now a non-UTF-8 file_path returns InvalidArgument (with a stored error); level stays best-effort. [MINOR] try_init failure was swallowed. init_logging discarded try_init() with .ok(), so if a global subscriber was already installed (no kernel subscriber installed) it still returned true → Success. try_init's result now folds into the returned bool. [MINOR] Return-value semantics clarified. The bool is computed in the get_or_init closure, so it necessarily reflects the FIRST (installing) call — a later call's level/file have no effect. Docs (header + Rust) now state this explicitly rather than implying the return describes the current call's file argument. cargo fmt / clippy --all-targets clean; 678 lib tests + C smoke + wiremock pass. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 18 ++++--- src/c_abi/session.rs | 34 +++++++++----- src/logging.rs | 60 +++++++++++++++--------- src/session.rs | 55 ++++++++++++++++++++++ tests/c/session_smoke.c | 7 ++- tests/v0_c_abi_session_close_wiremock.rs | 4 +- 6 files changed, 134 insertions(+), 44 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 6a625c26..969bedda 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -244,13 +244,17 @@ KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* co const char* name, const char* value); /* Initialize kernel logging, process-wide and ONCE (first call wins; - * later calls are no-ops returning the first call's outcome). `level` is - * OFF/ERROR/WARN/INFO/DEBUG/TRACE (NULL → RUST_LOG, default warn); - * `file_path` NULL → stderr. Not tied to a session — lets a host route - * kernel logs into its own log file. Returns Success when logging was - * installed (or skipped for level OFF); returns Internal (with a stored - * last-error) when the requested `file_path` could not be opened — in - * that case logging falls back to stderr so it still functions. */ + * later calls are no-ops). `level` is OFF/ERROR/WARN/INFO/DEBUG/TRACE + * (NULL → RUST_LOG, default warn); `file_path` NULL → stderr. Not tied to + * a session — lets a host route kernel logs into its own log file. + * + * A non-UTF-8 `file_path` returns InvalidArgument. Otherwise the result + * reflects the FIRST call's outcome (a later call's level/file have no + * effect and are not described by its return): Success when logging was + * installed against the request (or skipped for level OFF); Internal (with + * a stored last-error) when that install did not fully honour the request + * — the file could not be opened (falls back to stderr) or a global + * subscriber was already installed (no kernel subscriber installed). */ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); /* ─── Proxy / TLS (optional) ────────────────────────────────────────── diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 62b1a261..24a18ef1 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -330,13 +330,17 @@ pub unsafe extern "C" fn kernel_session_config_set_custom_header( /// call it before/around `kernel_session_open`. Lets an ODBC/Go host route /// the kernel's logs into the same file it writes its own logs to. /// -/// Returns `KernelStatusCode::Success` when logging was installed (or -/// intentionally skipped for level `OFF`). Returns -/// `KernelStatusCode::Internal` (with a stored last-error) when the -/// subscriber could not be installed — currently only when the requested -/// `file_path` fails to open — so a caller that can't see stderr (GUI / -/// BI host) can surface the failure or fall back deliberately. Because -/// init is once-per-process, this reflects the FIRST call's outcome. +/// A non-UTF-8 `file_path` returns `InvalidArgument` (the requested path +/// can't be honoured). Otherwise returns `Success` when the FIRST call +/// installed logging against the requested destination (or was skipped for +/// level `OFF`), or `Internal` (with a stored last-error) when that first +/// install did not fully honour the request — the log file couldn't be +/// opened (logging fell back to stderr) or a global subscriber was already +/// installed (no kernel subscriber installed). Because init is +/// once-per-process, the Success/Internal result reflects the **first** +/// call's outcome, NOT a later call's `level`/`file_path` (which have no +/// effect). A caller that can't see stderr can use `Internal` to surface +/// the degradation. /// /// # Safety /// `level` / `file_path`, if non-null, must be NUL-terminated C strings. @@ -346,16 +350,24 @@ pub unsafe extern "C" fn kernel_init_logging( file_path: *const c_char, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); - // Best-effort on the args: a non-UTF-8 arg is treated as absent rather - // than an error, matching the layer's own tolerance. + // `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(); - let file = optional_str(file_path, "log file path").ok().flatten(); + // `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, + Err(e) => return crate::c_abi::error::store_and_code(e), + }; if crate::logging::init_logging(&crate::logging::LogConfig { level, file }) { KernelStatusCode::Success } else { crate::c_abi::error::store_and_code(Error::new( crate::kernel_error::ErrorCode::Internal, - "kernel_init_logging: failed to install the logging subscriber (log file could not be opened)", + "kernel_init_logging: logging was not fully initialized as requested (the log file \ + could not be opened, or a global subscriber was already installed); kernel logs may \ + go to stderr or not flow", )) } } diff --git a/src/logging.rs b/src/logging.rs index 9f0e0bcd..24fd61e8 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -76,15 +76,19 @@ pub(crate) struct LogConfig { /// Initialize the tracing subscriber. /// /// Uses `OnceLock` to ensure this runs at most once per process — the -/// first call configures logging and subsequent calls are no-ops that -/// return the first call's outcome. +/// **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 +/// arguments). /// -/// Returns `true` if the subscriber was installed (or intentionally -/// skipped because the level is `OFF`), `false` if it could not be -/// installed — currently only when the requested log file fails to open. -/// Callers that cannot see stderr (GUI / BI hosts) can use the `false` -/// return to surface the failure their own way instead of assuming logs -/// are flowing. +/// 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. pub(crate) fn init_logging(config: &LogConfig) -> bool { *LOGGING_INITIALIZED.get_or_init(|| { // Check if the configured level is "OFF" — skip initialization @@ -124,7 +128,11 @@ pub(crate) fn init_logging(config: &LogConfig) -> bool { }); let file_requested_ok = config.file.is_none() || file.is_some(); - if let Some(file) = file { + // `try_init` returns Err if a global subscriber was already + // installed by another component — in which case NO kernel + // subscriber is installed and logs won't flow, so that must fold + // into the outcome (not be swallowed with `.ok()`). + let installed = if let Some(file) = file { tracing_subscriber::registry() .with(filter) .with( @@ -135,7 +143,7 @@ pub(crate) fn init_logging(config: &LogConfig) -> bool { .with_timer(SystemTime), ) .try_init() - .ok(); + .is_ok() } else { tracing_subscriber::registry() .with(filter) @@ -146,9 +154,11 @@ pub(crate) fn init_logging(config: &LogConfig) -> bool { .with_timer(SystemTime), ) .try_init() - .ok(); - } - file_requested_ok + .is_ok() + }; + // Success only if the subscriber installed AND the requested file + // (if any) was honoured. + installed && file_requested_ok }) } @@ -191,21 +201,27 @@ mod tests { let _filter = EnvFilter::new(directive); } - /// `init_logging` returns a bool signal and is idempotent in its - /// return value. (The subscriber is process-global, so we assert the - /// contract via the return rather than installing/observing output, - /// which would be order-dependent across the shared test binary.) + /// `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_returns_signal_and_is_idempotent() { - // stderr config always succeeds; a second call returns the same - // (first-call-wins) outcome. + fn init_logging_return_is_idempotent() { let cfg = LogConfig { level: Some("warn".to_string()), file: None, }; let first = init_logging(&cfg); - let second = init_logging(&cfg); - assert!(first, "stderr logging should install successfully"); + // 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"); } } diff --git a/src/session.rs b/src/session.rs index dc40bfb2..09e49cd0 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1009,3 +1009,58 @@ mod retry_config_tests { assert_eq!(hcc.read_timeout, Duration::from_millis(4500)); } } + +#[cfg(test)] +mod is_open_tests { + use super::*; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + /// `Session::is_open` reports true for a freshly-opened session and + /// false once its server-side delete has been initiated. This is the + /// only place the false path is reachable — over the C ABI + /// `kernel_session_close` frees the handle in the same call, so the C + /// wrapper can't observe it; `is_open`/`initiate_delete` are + /// `pub(crate)`, so this must live in-crate. Guards against an + /// inverted / hardcoded-true regression (hosts back + /// `SQL_ATTR_CONNECTION_DEAD` on this). + #[tokio::test] + async fn is_open_flips_true_to_false_on_delete() { + 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-is-open","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-is-open")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + 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(), + }) + .open() + .await + .expect("session must open"); + + assert!( + session.is_open(), + "a freshly-opened session must report open" + ); + session.initiate_delete(); + assert!( + !session.is_open(), + "after initiate_delete the session must report not-open" + ); + } +} diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 5a895fb9..b96dfdef 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -199,8 +199,11 @@ static void test_init_logging(void) { CHECK(rc == KernelStatusCode_Success, "init_logging twice is safe"); } -/* is_open null-guards its args. (The true→false behavior is covered by a - * Rust unit test that can build and close a Session without a network.) */ +/* is_open null-guards its args. (The true→false behavior is covered by the + * in-crate Rust test + * `session::is_open_tests::is_open_flips_true_to_false_on_delete`, which can + * reach the pub(crate) Session::is_open / initiate_delete the C ABI can't + * observe after close.) */ static void test_is_open_null_guards(void) { bool open = true; KernelStatusCode rc = kernel_session_is_open(NULL, &open); diff --git a/tests/v0_c_abi_session_close_wiremock.rs b/tests/v0_c_abi_session_close_wiremock.rs index f78332b6..a06ab437 100644 --- a/tests/v0_c_abi_session_close_wiremock.rs +++ b/tests/v0_c_abi_session_close_wiremock.rs @@ -93,8 +93,8 @@ fn session_close_initiates_delete_with_statement_still_open() { // A freshly-opened session reports open (guards against an inverted // or hardcoded-false is_open). The false case can't be probed over // the C ABI — kernel_session_close frees the handle in the same - // call — so it's covered by the crate-internal Session::is_open - // path instead. + // call — so it's covered by the crate-internal + // `session::is_open_tests::is_open_flips_true_to_false_on_delete`. let mut is_open = false; assert_eq!( kernel_session_is_open(session, &mut is_open),