diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 4d2fdcf5..8e9cc8d3 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -56,11 +56,20 @@ * - **A result stream borrows its executed handle.** Closing the executed * handle invalidates any stream obtained from it: subsequent stream * calls return `InvalidStatementHandle` (a defined error, not UB). - * - **Close is best-effort async.** `kernel_session_close` returns once - * the server-side delete is *initiated*, not completed — a detached task - * runs it on the kernel's process-wide runtime. A process that exits - * immediately after `kernel_session_close` may drop that task before it - * runs, leaving the server session to expire on its own idle timeout. + * - **Close is best-effort async.** `kernel_session_close` initiates the + * server-side delete before returning — a detached task runs it on the + * kernel's process-wide runtime — but does not wait for completion. A + * process that exits immediately after `kernel_session_close` may drop + * the detached task before it runs, leaving the server session to expire + * on its own idle timeout. + * - **Close the session LAST.** Because close initiates the server-side + * delete, any handle still open against that session — a statement / + * executed handle, or a metadata result stream (which holds its own + * session reference and remains drivable) — must be drained and closed + * BEFORE `kernel_session_close`. Driving such a handle afterwards issues + * RPCs against a session whose delete has already been initiated and + * will surface server errors. Order teardown: result streams → executed + * handles → statements → session. */ #ifndef DATABRICKS_KERNEL_H diff --git a/src/c_abi/metadata.rs b/src/c_abi/metadata.rs index 1bd0e338..d024d8c1 100644 --- a/src/c_abi/metadata.rs +++ b/src/c_abi/metadata.rs @@ -16,11 +16,12 @@ //! a `kernel_result_stream_t` the caller drives via //! `kernel_result_stream_*`. //! -//! Each call captures the result schema and consumes the stream into an -//! owned batch iterator (metadata results are bounded — a handful of -//! batches at most), so the returned handle is self-contained and does -//! not borrow the session. The session must still outlive the call -//! itself. +//! Each call captures the result schema up front and hands the owned +//! `ResultStream` to a self-contained handle that drives it lazily (one +//! batch per `kernel_result_stream_next_batch`), so the handle does not +//! borrow the session and a large result (e.g. a cross-catalog column +//! listing) streams with bounded memory. The session must still outlive +//! the call itself. //! //! Results carry the **server-shaped** (JDBC-canonical) columns the //! kernel's `Metadata` produces; ODBC / JDBC drivers keep their own @@ -32,9 +33,8 @@ use super::session::kernel_session_t; use super::{block_on_ffi, KernelStatusCode}; use crate::kernel_error::{Error, Result}; use crate::metadata_v0::{Identifier, LikePattern}; -use crate::result_stream::{ResultBatch, ResultStream, SchemaRef}; +use crate::result_stream::ResultStream; use crate::session::Session; -use arrow_array::RecordBatch; use std::ffi::{c_char, CStr}; /// Read an optional C string: null → `None`, else borrowed `&str` @@ -61,52 +61,37 @@ unsafe fn req_str<'a>(ptr: *const c_char, what: &str) -> Result<&'a str> { .ok_or_else(|| Error::invalid_argument().message(format!("{what} must not be null"))) } -/// Optional [`Identifier`] from a C string (null → `None`). +/// Read an optional C string, treating both a null pointer AND an empty / +/// whitespace-only string as "unfiltered" (`None`). +/// +/// ODBC/JDBC drivers routinely pass an empty string rather than NULL to +/// mean "match all catalogs/schemas/tables"; the header only documents +/// NULL, but rejecting `""` with `InvalidArgument` (as `Identifier::new` +/// would) breaks those callers. Normalising empty → `None` here makes the +/// two spellings equivalent for every filter arg. +/// +/// # Safety +/// As [`opt_str`]. +unsafe fn opt_filter_str<'a>(ptr: *const c_char, what: &str) -> Result> { + Ok(opt_str(ptr, what)?.filter(|s| !s.trim().is_empty())) +} + +/// Optional [`Identifier`] from a C string (null or empty → `None`). unsafe fn opt_ident<'a>(ptr: *const c_char, what: &str) -> Result>> { - match opt_str(ptr, what)? { + match opt_filter_str(ptr, what)? { Some(s) => Ok(Some(Identifier::new(s)?)), None => Ok(None), } } -/// Optional [`LikePattern`] from a C string (null → `None`). +/// Optional [`LikePattern`] from a C string (null or empty → `None`). unsafe fn opt_pattern<'a>(ptr: *const c_char, what: &str) -> Result>> { - match opt_str(ptr, what)? { + match opt_filter_str(ptr, what)? { Some(s) => Ok(Some(LikePattern::new(s)?)), None => Ok(None), } } -/// Drain a metadata `ResultStream` fully into owned batches **on the -/// runtime** (this runs inside `block_on_ffi`), capturing the schema. -/// -/// Metadata results are bounded (a handful of batches at most), so full -/// materialisation here is cheap and lets the C-side `next_batch` be a -/// pure in-memory pop — avoiding driving a possibly-CloudFetch-backed -/// reader off the tokio reactor from a plain C thread. -async fn drain_metadata(mut stream: ResultStream) -> Result<(SchemaRef, Vec)> { - let schema = stream.schema(); - let mut batches = Vec::new(); - while let Some(batch) = stream.next_batch().await? { - // `ResultBatch` is `#[non_exhaustive]`; the wildcard is unreachable - // today (Arrow is the only variant) but is the defined fallback - // for a future non-Arrow variant at this Arrow-only boundary. - #[allow( - unreachable_patterns, - reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" - )] - match batch { - ResultBatch::Arrow(rb) => batches.push(rb.clone()), - _ => { - return Err(Error::not_implemented().message( - "metadata stream yielded a non-Arrow batch; C ABI exports Arrow only", - )) - } - } - } - Ok((schema, batches)) -} - /// Shared body for the metadata entry points: clear the error, null-check /// `session` / `out`, run the async builder on the runtime, and write the /// resulting owned stream handle. @@ -131,13 +116,18 @@ where if out.is_null() { return store_invalid_arg("metadata: out must not be null"); } + // Build the stream on the runtime and capture its schema; the stream + // itself is handed to the owned handle and driven lazily (one batch + // per `kernel_result_stream_next_batch`), so a large metadata result + // (e.g. cross-catalog column listing) is not buffered up front. let result = block_on_ffi(move || async move { let stream = build(session).await?; - drain_metadata(stream).await + let schema = stream.schema(); + Ok((schema, stream)) }); match result { - Ok((schema, batches)) => { - std::ptr::write(out, into_raw_result_stream(schema, batches)); + Ok((schema, stream)) => { + std::ptr::write(out, into_raw_result_stream(schema, stream)); KernelStatusCode::Success } Err(code) => code, @@ -338,3 +328,50 @@ pub unsafe extern "C" fn kernel_metadata_foreign_keys( // kernel `Metadata` exposes these (some synthesised in-memory). Wire them // over the C ABI when an ODBC / Go consumer needs SQLGetTypeInfo / // SQLProcedures. + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::CString; + + /// A null pointer, an empty string, and a whitespace-only string all + /// mean "unfiltered" (`None`); a real value is borrowed through. This + /// lets ODBC/JDBC callers pass "" (their common "match all" spelling) + /// instead of NULL without hitting `Identifier`'s empty-string reject. + #[test] + fn opt_filter_str_treats_null_and_blank_as_unfiltered() { + unsafe { + assert_eq!(opt_filter_str(std::ptr::null(), "catalog").unwrap(), None); + + let empty = CString::new("").unwrap(); + assert_eq!(opt_filter_str(empty.as_ptr(), "catalog").unwrap(), None); + + let blank = CString::new(" ").unwrap(); + assert_eq!(opt_filter_str(blank.as_ptr(), "catalog").unwrap(), None); + + let real = CString::new("main").unwrap(); + assert_eq!( + opt_filter_str(real.as_ptr(), "catalog").unwrap(), + Some("main") + ); + } + } + + /// `opt_ident` inherits the same normalisation: null / empty / blank → + /// `None` (no `InvalidArgument`), a real value → `Some(ident)`. + #[test] + fn opt_ident_maps_empty_to_none_not_error() { + unsafe { + assert!(opt_ident(std::ptr::null(), "catalog").unwrap().is_none()); + + let empty = CString::new("").unwrap(); + assert!( + opt_ident(empty.as_ptr(), "catalog").unwrap().is_none(), + "empty identifier must be treated as unfiltered, not rejected" + ); + + let real = CString::new("main").unwrap(); + assert!(opt_ident(real.as_ptr(), "catalog").unwrap().is_some()); + } + } +} diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 5682d9aa..eec29de0 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -23,9 +23,13 @@ //! //! Two stream shapes back the same opaque handle: //! -//! - **Owned** — a `ResultStream` consumed into an `OwnedBatchIter` plus -//! its schema. Produced by the metadata calls (`kernel_metadata_*`), -//! which return a standalone stream not tied to an executed handle. +//! - **Owned** — a standalone `ResultStream` the handle owns outright. +//! Produced by the metadata calls (`kernel_metadata_*`), which return a +//! stream not tied to an executed handle. `next_batch` drives it lazily +//! on the runtime (via `block_on_ffi`), one batch at a time, so a large +//! result (e.g. `list_columns` with no catalog filter → SHOW COLUMNS IN +//! ALL CATALOGS) streams with bounded memory instead of being buffered +//! up front. //! - **Executed** — a borrow of the `ExecutedStatement` that produced //! it. `next_batch` drives the executed handle's own stream so the //! handle's drain-driven auto-close and lazy CloudFetch link fetches @@ -51,13 +55,14 @@ pub struct kernel_result_stream_t { /// Backing state for a result-stream handle. enum ResultStreamInner { - /// Self-contained owned stream (metadata path). The batches are - /// **fully drained on the runtime at construction** (metadata results - /// are bounded), so iterating here is pure in-memory — no tokio - /// reactor needed, sidestepping the off-runtime CloudFetch hang. + /// Self-contained owned stream (metadata path). The handle owns the + /// `ResultStream` and drives `next_batch` lazily on the runtime (via + /// `block_on_ffi`) — one batch per C call — so an unbounded metadata + /// result (e.g. cross-catalog column listing) streams with bounded + /// memory rather than being drained into a `Vec` at construction. Owned { schema: SchemaRef, - batches: std::vec::IntoIter, + stream: crate::result_stream::ResultStream, }, /// Borrow of the executed statement that produced this stream /// (sync execute path). The raw pointer is only dereferenced after @@ -70,17 +75,16 @@ enum ResultStreamInner { }, } -/// Crate-internal: build an owned result-stream handle from a schema and -/// a fully-materialised batch list (used by the metadata FFI, which -/// drains its bounded result on the runtime before calling this). +/// Crate-internal: build an owned result-stream handle that lazily drives +/// the given `ResultStream` (used by the metadata FFI). `schema` is +/// captured up front so `get_schema` needs no runtime; each `next_batch` +/// pulls one batch on the runtime. pub(crate) fn into_raw_result_stream( schema: SchemaRef, - batches: Vec, + stream: crate::result_stream::ResultStream, ) -> *mut kernel_result_stream_t { - Box::into_raw(Box::new(ResultStreamInner::Owned { - schema, - batches: batches.into_iter(), - })) as *mut kernel_result_stream_t + Box::into_raw(Box::new(ResultStreamInner::Owned { schema, stream })) + as *mut kernel_result_stream_t } /// Crate-internal: build a result-stream handle that borrows from an @@ -205,10 +209,34 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( // Pull the next owned batch from whichever backing shape this is. let next: Option> = match inner { - // Owned (metadata): batches were fully drained on the runtime - // at construction, so this is a pure in-memory pop — no tokio - // reactor needed (avoids the off-runtime CloudFetch hang). - ResultStreamInner::Owned { batches, .. } => batches.next().map(Ok), + // Owned (metadata): drive the owned ResultStream lazily on the + // runtime, one batch at a time, so an unbounded result streams + // with bounded memory. Running through block_on_ffi keeps the + // (possibly CloudFetch-backed) reader on the tokio reactor + // rather than off a plain C thread. + ResultStreamInner::Owned { stream, .. } => { + match super::block_on_ffi(move || { + let stream: &mut crate::result_stream::ResultStream = stream; + Box::pin(async move { + #[allow( + unreachable_patterns, + reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" + )] + match stream.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), + Some(_) => Err(Error::not_implemented().message( + "metadata stream yielded a non-Arrow batch; the C ABI exports \ + Arrow only", + )), + None => Ok(None), + } + }) + }) { + Ok(Some(rb)) => Some(Ok(rb)), + Ok(None) => None, + Err(code) => return code, // error already stored + } + } ResultStreamInner::Executed { exec, valid } => { let exec = match executed_ref(*exec, valid) { Ok(e) => e, @@ -306,6 +334,24 @@ mod tests { (schema, batch) } + /// Build an Owned result-stream handle over the given in-memory + /// batches (mirrors the metadata FFI's lazy `ResultStream`-backed + /// handle) using a throwaway runtime for the async `from_reader`. + fn owned_stream_over( + schema: SchemaRef, + batches: Vec, + ) -> *mut kernel_result_stream_t { + use crate::reader::test_utils::MockReader; + use crate::result_stream::ResultStream; + let rt = tokio::runtime::Runtime::new().unwrap(); + let stream = rt.block_on(async { + ResultStream::from_reader(Box::new(MockReader::new(batches))) + .await + .unwrap() + }); + into_raw_result_stream(schema, stream) + } + /// End-of-stream on an Owned stream returns `Success` with a /// **released** array (`release == null`) — the sentinel ODBC / Go /// consumers loop on. A regression that returned a non-released empty @@ -313,7 +359,7 @@ mod tests { #[test] fn owned_stream_exhaustion_yields_released_array() { let (schema, batch) = one_row_batch(); - let stream = into_raw_result_stream(schema, vec![batch]); + let stream = owned_stream_over(schema, vec![batch]); // First call: a real batch (release non-null). let mut arr = FFI_ArrowArray::empty(); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index fe5e96fd..005261d5 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -522,8 +522,17 @@ fn build_session(config: KernelSessionConfig) -> Result` and stays drivable) — must be drained and closed +/// before this call. Driving such a handle afterwards issues RPCs against +/// an already-deleting session and surfaces server errors. See the +/// `databricks_kernel.h` teardown-ordering contract. /// /// # Safety /// @@ -539,12 +548,19 @@ pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> ); return KernelStatusCode::InvalidArgument; } - // Reclaim the box; its `Drop` fires the fire-and-forget - // `DeleteSession`. We deliberately don't `block_on` an explicit - // `Session::close()` here — `Drop` already handles server cleanup, - // and a synchronous close would make `kernel_session_close` block on - // the network for no caller benefit. - drop(Box::from_raw(session as *mut Session)); + // Reclaim the box and initiate the fire-and-forget `DeleteSession` + // right now. We call `initiate_delete()` explicitly rather than + // relying on `Drop`: a still-live statement / executed handle holds + // its own `Arc` clone, so `SessionInner::Drop` (which + // only fires when the *last* Arc drops) would otherwise defer the + // server-side delete until those handles are released — contradicting + // the header's "close initiates the delete" contract. `initiate_delete` + // is idempotent, so the eventual `Drop` becomes a no-op. We still don't + // `block_on` an awaited close — that would make close block on the + // network for no caller benefit. + let session = Box::from_raw(session as *mut Session); + session.initiate_delete(); + drop(session); KernelStatusCode::Success } diff --git a/src/session.rs b/src/session.rs index 93641528..ce6ac4e0 100644 --- a/src/session.rs +++ b/src/session.rs @@ -138,18 +138,28 @@ impl SessionInner { pub(crate) fn runtime_handle(&self) -> &tokio::runtime::Handle { &self.runtime_handle } -} -impl Drop for SessionInner { - fn drop(&mut self) { - // If `Session::close()` already ran the delete, skip. - if self.closed.load(std::sync::atomic::Ordering::Acquire) { - return; + /// Initiate the fire-and-forget server-side `DeleteSession` now, + /// idempotently. Flips `closed` first (via a compare-and-swap) so at + /// most one delete is ever spawned — a later `Drop` (or a second + /// call) becomes a no-op. Unlike waiting for the last `Arc` to drop, + /// this fires immediately even while child handles (statements / + /// executed handles) still hold `Arc` clones, so an + /// explicit close genuinely *initiates* the delete rather than + /// deferring it to an idle-timeout. + pub(crate) fn initiate_delete(&self) { + if self + .closed + .compare_exchange( + false, + true, + std::sync::atomic::Ordering::AcqRel, + std::sync::atomic::Ordering::Acquire, + ) + .is_err() + { + return; // already closed / closing } - // Fire-and-forget DeleteSession when the last `Arc` reference - // goes away. Swallows errors — Drop must not panic, and we - // can't surface a failure here. The runtime keeps the - // background task alive until completion. let transport = Arc::clone(&self.transport); let session_id = self.session_id.clone(); self.runtime_handle.spawn(async move { @@ -158,6 +168,18 @@ impl Drop for SessionInner { } } +impl Drop for SessionInner { + fn drop(&mut self) { + // Fire-and-forget DeleteSession when the last `Arc` reference + // goes away, unless an explicit close / a prior initiation + // already fired it. `initiate_delete` is idempotent (flips + // `closed` via compare-and-swap) and swallows errors — Drop must + // not panic. The runtime keeps the background task alive until + // completion. + self.initiate_delete(); + } +} + /// Stateful authenticated session against a Databricks workspace. /// /// `'static` (no lifetime parameter) so wrappers can hold it inside @@ -342,6 +364,16 @@ impl Session { Metadata::new(Arc::clone(&self.inner)) } + /// Initiate the fire-and-forget server-side `DeleteSession` now, + /// without awaiting it or consuming `self`. Idempotent. Used by the C + /// ABI's `kernel_session_close` so the delete is initiated on close + /// even when child handles still hold `Arc` clones + /// (otherwise it would be deferred until the last handle drops). For + /// an awaitable close that surfaces failure, use [`Session::close`]. + pub(crate) fn initiate_delete(&self) { + self.inner.initiate_delete(); + } + /// 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/v0_c_abi_session_close_wiremock.rs b/tests/v0_c_abi_session_close_wiremock.rs new file mode 100644 index 00000000..8559d8cf --- /dev/null +++ b/tests/v0_c_abi_session_close_wiremock.rs @@ -0,0 +1,129 @@ +// 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. + +//! Wiremock test for the C ABI's `kernel_session_close` delete-initiation +//! contract: closing a session must initiate the server-side +//! `DeleteSession` **even while a statement handle from that session is +//! still open**. The statement handle holds its own `Arc` +//! clone, so if close relied on the last-`Arc`-drop path (`SessionInner:: +//! Drop`) the delete would be deferred until the statement is also closed +//! — the bug this pins. `kernel_session_close` instead calls +//! `initiate_delete` eagerly. +//! +//! The C ABI drives its own process-wide tokio runtime inside +//! `block_on_ffi`, so the entry points must be called from a plain +//! (non-async) thread — hence `#[test]`, not `#[tokio::test]`, with a +//! dedicated runtime only to host the wiremock server. + +use std::ffi::CString; +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, +}; +use databricks_sql_kernel::c_abi::statement::{kernel_statement_close, kernel_statement_t}; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +#[test] +fn session_close_initiates_delete_with_statement_still_open() { + // A dedicated runtime just to run the async wiremock setup / polling; + // the C ABI calls themselves run on the kernel's own runtime. + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = + rt.block_on(async { + 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-c-abi-close","warehouse_id":"test_wh"}"#, + )) + .mount(&server) + .await; + // The DELETE we expect close to initiate. + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-c-abi-close")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + // Build config → open session. + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let host = CString::new(uri.as_str()).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + let token = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + + // 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(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + assert!(!stmt.is_null()); + + // Close the session while the statement is STILL open. The fix + // must initiate DeleteSession now rather than deferring it. + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + + // Close the statement afterwards (orderly teardown of the leftover + // handle). This must not double-fire the delete. + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + } + + // The DELETE is a detached fire-and-forget task; poll the mock's + // received requests until it lands (or time out). + let saw_delete = rt.block_on(async { + for _ in 0..50 { + let requests = server.received_requests().await.unwrap_or_default(); + if requests.iter().any(|r| { + r.method.as_str() == "DELETE" && r.url.path().ends_with("sess-c-abi-close") + }) { + return true; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + false + }); + assert!( + saw_delete, + "kernel_session_close must initiate DeleteSession even with a statement handle still open" + ); +}