Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
125 changes: 81 additions & 44 deletions src/c_abi/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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`
Expand All @@ -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<Option<&'a str>> {
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<Option<Identifier<'a>>> {
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<Option<LikePattern<'a>>> {
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<RecordBatch>)> {
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.
Expand All @@ -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,
Expand Down Expand Up @@ -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());
}
}
}
88 changes: 67 additions & 21 deletions src/c_abi/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<RecordBatch>,
stream: crate::result_stream::ResultStream,
},
/// Borrow of the executed statement that produced this stream
/// (sync execute path). The raw pointer is only dereferenced after
Expand All @@ -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<RecordBatch>,
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
Expand Down Expand Up @@ -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<Result<RecordBatch, Error>> = 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,
Expand Down Expand Up @@ -306,14 +334,32 @@ 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<RecordBatch>,
) -> *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
/// array would loop them forever, so pin it.
#[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();
Expand Down
32 changes: 24 additions & 8 deletions src/c_abi/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,8 +522,17 @@ fn build_session(config: KernelSessionConfig) -> Result<Session, KernelStatusCod
})
}

/// Close a session. Releases the underlying Rust [`Session`] (which
/// fires `DeleteSession` server-side on drop / explicit close).
/// Close a session. Initiates the fire-and-forget server-side
/// `DeleteSession` immediately and releases the underlying Rust
/// [`Session`]. Does not block on the delete completing.
///
/// Close the session **last**: because the delete is initiated eagerly,
/// any still-open handle against this session — a statement / executed
/// handle, or a metadata result stream (which holds its own
/// `Arc<SessionInner>` 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
///
Expand All @@ -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<SessionInner>` 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
}

Expand Down
Loading
Loading