Skip to content

Commit b307fb4

Browse files
[PECOBLR-2096] C ABI follow-up: lazy metadata streaming, empty-filter semantics, session-close delete initiation (#160)
Follow-up to #158 (merged), addressing @gopalldb's three post-merge review findings on the v0 C ABI. ## [MAJOR] Unbounded metadata buffering → lazy streaming `drain_metadata` materialized the whole metadata result into a `Vec<RecordBatch>` at construction, justified as "bounded — a handful of batches". That's false for `kernel_metadata_list_columns` with a NULL catalog, which becomes `SHOW COLUMNS IN ALL CATALOGS` — a row per column of every table in every visible catalog. In a large workspace an ODBC `getColumns(null, …)` would materialize the entire cross-catalog column inventory at once. The owned result-stream handle now **holds the `ResultStream` and drives `next_batch` lazily on the runtime** (one batch per `kernel_result_stream_next_batch`, via `block_on_ffi` — the same on-runtime discipline the executed path already uses to avoid driving a CloudFetch reader off a plain C thread). `run_metadata` now captures just the schema up front and hands the stream to the handle. Bounded memory, no behavior change for consumers. ## [MAJOR] Empty-string identifier rejected instead of "unfiltered" `opt_ident` mapped only a NULL pointer to `None`; a non-null empty string became `Some("")` → `Identifier::new("")` → `InvalidArgument`. ODBC/JDBC drivers commonly pass `""` (not NULL) to mean "match all", so `list_schemas` / `list_tables` / `list_columns` rejected a legitimate call. New `opt_filter_str` treats NULL and empty/whitespace-only alike as `None`; `opt_ident` / `opt_pattern` route through it. Required identifiers (PK/FK table) still correctly reject empty. ## [MAJOR] `kernel_session_close` didn't initiate DeleteSession when handles outlive the session Close dropped one `Arc<SessionInner>`; `DeleteSession` only fires from `SessionInner::Drop` (last-Arc-drop). A live statement/executed handle holds its own clone, so the delete was deferred until those were released too — contradicting the header's "close initiates the delete" contract and risking the server session lingering to idle-timeout. Added `SessionInner::initiate_delete` (idempotent via a compare-and-swap on `closed`; `Drop` now delegates to it), exposed `Session::initiate_delete`, and call it from `kernel_session_close` so the delete is initiated immediately regardless of outstanding handles. ## Docs + tests - `databricks_kernel.h` and the Rust docs updated to match (metadata NULL/empty semantics; close-initiation contract). - Metadata empty→unfiltered unit tests (`opt_filter_str`, `opt_ident`). - New C-ABI wiremock test asserting close initiates `DELETE` with a statement handle still open. - The existing owned-stream exhaustion test now builds a lazy `ResultStream` via `MockReader`. `cargo fmt` / `clippy --all-targets` clean; **673 lib tests + all integration suites + C smoke** pass. The dependent ODBC PR databricks/databricks-odbc#101 will re-pin `KERNEL_REPO_TAG` to this PR's merge commit once it lands. This pull request and its description were written by Isaac. --------- Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
1 parent 285a8eb commit b307fb4

6 files changed

Lines changed: 357 additions & 88 deletions

File tree

‎include/databricks_kernel.h‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,20 @@
5656
* - **A result stream borrows its executed handle.** Closing the executed
5757
* handle invalidates any stream obtained from it: subsequent stream
5858
* calls return `InvalidStatementHandle` (a defined error, not UB).
59-
* - **Close is best-effort async.** `kernel_session_close` returns once
60-
* the server-side delete is *initiated*, not completed — a detached task
61-
* runs it on the kernel's process-wide runtime. A process that exits
62-
* immediately after `kernel_session_close` may drop that task before it
63-
* runs, leaving the server session to expire on its own idle timeout.
59+
* - **Close is best-effort async.** `kernel_session_close` initiates the
60+
* server-side delete before returning — a detached task runs it on the
61+
* kernel's process-wide runtime — but does not wait for completion. A
62+
* process that exits immediately after `kernel_session_close` may drop
63+
* the detached task before it runs, leaving the server session to expire
64+
* on its own idle timeout.
65+
* - **Close the session LAST.** Because close initiates the server-side
66+
* delete, any handle still open against that session — a statement /
67+
* executed handle, or a metadata result stream (which holds its own
68+
* session reference and remains drivable) — must be drained and closed
69+
* BEFORE `kernel_session_close`. Driving such a handle afterwards issues
70+
* RPCs against a session whose delete has already been initiated and
71+
* will surface server errors. Order teardown: result streams → executed
72+
* handles → statements → session.
6473
*/
6574

6675
#ifndef DATABRICKS_KERNEL_H

‎src/c_abi/metadata.rs‎

Lines changed: 81 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,12 @@
1616
//! a `kernel_result_stream_t` the caller drives via
1717
//! `kernel_result_stream_*`.
1818
//!
19-
//! Each call captures the result schema and consumes the stream into an
20-
//! owned batch iterator (metadata results are bounded — a handful of
21-
//! batches at most), so the returned handle is self-contained and does
22-
//! not borrow the session. The session must still outlive the call
23-
//! itself.
19+
//! Each call captures the result schema up front and hands the owned
20+
//! `ResultStream` to a self-contained handle that drives it lazily (one
21+
//! batch per `kernel_result_stream_next_batch`), so the handle does not
22+
//! borrow the session and a large result (e.g. a cross-catalog column
23+
//! listing) streams with bounded memory. The session must still outlive
24+
//! the call itself.
2425
//!
2526
//! Results carry the **server-shaped** (JDBC-canonical) columns the
2627
//! kernel's `Metadata` produces; ODBC / JDBC drivers keep their own
@@ -32,9 +33,8 @@ use super::session::kernel_session_t;
3233
use super::{block_on_ffi, KernelStatusCode};
3334
use crate::kernel_error::{Error, Result};
3435
use crate::metadata_v0::{Identifier, LikePattern};
35-
use crate::result_stream::{ResultBatch, ResultStream, SchemaRef};
36+
use crate::result_stream::ResultStream;
3637
use crate::session::Session;
37-
use arrow_array::RecordBatch;
3838
use std::ffi::{c_char, CStr};
3939

4040
/// 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> {
6161
.ok_or_else(|| Error::invalid_argument().message(format!("{what} must not be null")))
6262
}
6363

64-
/// Optional [`Identifier`] from a C string (null → `None`).
64+
/// Read an optional C string, treating both a null pointer AND an empty /
65+
/// whitespace-only string as "unfiltered" (`None`).
66+
///
67+
/// ODBC/JDBC drivers routinely pass an empty string rather than NULL to
68+
/// mean "match all catalogs/schemas/tables"; the header only documents
69+
/// NULL, but rejecting `""` with `InvalidArgument` (as `Identifier::new`
70+
/// would) breaks those callers. Normalising empty → `None` here makes the
71+
/// two spellings equivalent for every filter arg.
72+
///
73+
/// # Safety
74+
/// As [`opt_str`].
75+
unsafe fn opt_filter_str<'a>(ptr: *const c_char, what: &str) -> Result<Option<&'a str>> {
76+
Ok(opt_str(ptr, what)?.filter(|s| !s.trim().is_empty()))
77+
}
78+
79+
/// Optional [`Identifier`] from a C string (null or empty → `None`).
6580
unsafe fn opt_ident<'a>(ptr: *const c_char, what: &str) -> Result<Option<Identifier<'a>>> {
66-
match opt_str(ptr, what)? {
81+
match opt_filter_str(ptr, what)? {
6782
Some(s) => Ok(Some(Identifier::new(s)?)),
6883
None => Ok(None),
6984
}
7085
}
7186

72-
/// Optional [`LikePattern`] from a C string (null → `None`).
87+
/// Optional [`LikePattern`] from a C string (null or empty → `None`).
7388
unsafe fn opt_pattern<'a>(ptr: *const c_char, what: &str) -> Result<Option<LikePattern<'a>>> {
74-
match opt_str(ptr, what)? {
89+
match opt_filter_str(ptr, what)? {
7590
Some(s) => Ok(Some(LikePattern::new(s)?)),
7691
None => Ok(None),
7792
}
7893
}
7994

80-
/// Drain a metadata `ResultStream` fully into owned batches **on the
81-
/// runtime** (this runs inside `block_on_ffi`), capturing the schema.
82-
///
83-
/// Metadata results are bounded (a handful of batches at most), so full
84-
/// materialisation here is cheap and lets the C-side `next_batch` be a
85-
/// pure in-memory pop — avoiding driving a possibly-CloudFetch-backed
86-
/// reader off the tokio reactor from a plain C thread.
87-
async fn drain_metadata(mut stream: ResultStream) -> Result<(SchemaRef, Vec<RecordBatch>)> {
88-
let schema = stream.schema();
89-
let mut batches = Vec::new();
90-
while let Some(batch) = stream.next_batch().await? {
91-
// `ResultBatch` is `#[non_exhaustive]`; the wildcard is unreachable
92-
// today (Arrow is the only variant) but is the defined fallback
93-
// for a future non-Arrow variant at this Arrow-only boundary.
94-
#[allow(
95-
unreachable_patterns,
96-
reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants"
97-
)]
98-
match batch {
99-
ResultBatch::Arrow(rb) => batches.push(rb.clone()),
100-
_ => {
101-
return Err(Error::not_implemented().message(
102-
"metadata stream yielded a non-Arrow batch; C ABI exports Arrow only",
103-
))
104-
}
105-
}
106-
}
107-
Ok((schema, batches))
108-
}
109-
11095
/// Shared body for the metadata entry points: clear the error, null-check
11196
/// `session` / `out`, run the async builder on the runtime, and write the
11297
/// resulting owned stream handle.
@@ -131,13 +116,18 @@ where
131116
if out.is_null() {
132117
return store_invalid_arg("metadata: out must not be null");
133118
}
119+
// Build the stream on the runtime and capture its schema; the stream
120+
// itself is handed to the owned handle and driven lazily (one batch
121+
// per `kernel_result_stream_next_batch`), so a large metadata result
122+
// (e.g. cross-catalog column listing) is not buffered up front.
134123
let result = block_on_ffi(move || async move {
135124
let stream = build(session).await?;
136-
drain_metadata(stream).await
125+
let schema = stream.schema();
126+
Ok((schema, stream))
137127
});
138128
match result {
139-
Ok((schema, batches)) => {
140-
std::ptr::write(out, into_raw_result_stream(schema, batches));
129+
Ok((schema, stream)) => {
130+
std::ptr::write(out, into_raw_result_stream(schema, stream));
141131
KernelStatusCode::Success
142132
}
143133
Err(code) => code,
@@ -338,3 +328,50 @@ pub unsafe extern "C" fn kernel_metadata_foreign_keys(
338328
// kernel `Metadata` exposes these (some synthesised in-memory). Wire them
339329
// over the C ABI when an ODBC / Go consumer needs SQLGetTypeInfo /
340330
// SQLProcedures.
331+
332+
#[cfg(test)]
333+
mod tests {
334+
use super::*;
335+
use std::ffi::CString;
336+
337+
/// A null pointer, an empty string, and a whitespace-only string all
338+
/// mean "unfiltered" (`None`); a real value is borrowed through. This
339+
/// lets ODBC/JDBC callers pass "" (their common "match all" spelling)
340+
/// instead of NULL without hitting `Identifier`'s empty-string reject.
341+
#[test]
342+
fn opt_filter_str_treats_null_and_blank_as_unfiltered() {
343+
unsafe {
344+
assert_eq!(opt_filter_str(std::ptr::null(), "catalog").unwrap(), None);
345+
346+
let empty = CString::new("").unwrap();
347+
assert_eq!(opt_filter_str(empty.as_ptr(), "catalog").unwrap(), None);
348+
349+
let blank = CString::new(" ").unwrap();
350+
assert_eq!(opt_filter_str(blank.as_ptr(), "catalog").unwrap(), None);
351+
352+
let real = CString::new("main").unwrap();
353+
assert_eq!(
354+
opt_filter_str(real.as_ptr(), "catalog").unwrap(),
355+
Some("main")
356+
);
357+
}
358+
}
359+
360+
/// `opt_ident` inherits the same normalisation: null / empty / blank →
361+
/// `None` (no `InvalidArgument`), a real value → `Some(ident)`.
362+
#[test]
363+
fn opt_ident_maps_empty_to_none_not_error() {
364+
unsafe {
365+
assert!(opt_ident(std::ptr::null(), "catalog").unwrap().is_none());
366+
367+
let empty = CString::new("").unwrap();
368+
assert!(
369+
opt_ident(empty.as_ptr(), "catalog").unwrap().is_none(),
370+
"empty identifier must be treated as unfiltered, not rejected"
371+
);
372+
373+
let real = CString::new("main").unwrap();
374+
assert!(opt_ident(real.as_ptr(), "catalog").unwrap().is_some());
375+
}
376+
}
377+
}

‎src/c_abi/result.rs‎

Lines changed: 67 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,13 @@
2323
//!
2424
//! Two stream shapes back the same opaque handle:
2525
//!
26-
//! - **Owned** — a `ResultStream` consumed into an `OwnedBatchIter` plus
27-
//! its schema. Produced by the metadata calls (`kernel_metadata_*`),
28-
//! which return a standalone stream not tied to an executed handle.
26+
//! - **Owned** — a standalone `ResultStream` the handle owns outright.
27+
//! Produced by the metadata calls (`kernel_metadata_*`), which return a
28+
//! stream not tied to an executed handle. `next_batch` drives it lazily
29+
//! on the runtime (via `block_on_ffi`), one batch at a time, so a large
30+
//! result (e.g. `list_columns` with no catalog filter → SHOW COLUMNS IN
31+
//! ALL CATALOGS) streams with bounded memory instead of being buffered
32+
//! up front.
2933
//! - **Executed** — a borrow of the `ExecutedStatement` that produced
3034
//! it. `next_batch` drives the executed handle's own stream so the
3135
//! handle's drain-driven auto-close and lazy CloudFetch link fetches
@@ -51,13 +55,14 @@ pub struct kernel_result_stream_t {
5155

5256
/// Backing state for a result-stream handle.
5357
enum ResultStreamInner {
54-
/// Self-contained owned stream (metadata path). The batches are
55-
/// **fully drained on the runtime at construction** (metadata results
56-
/// are bounded), so iterating here is pure in-memory — no tokio
57-
/// reactor needed, sidestepping the off-runtime CloudFetch hang.
58+
/// Self-contained owned stream (metadata path). The handle owns the
59+
/// `ResultStream` and drives `next_batch` lazily on the runtime (via
60+
/// `block_on_ffi`) — one batch per C call — so an unbounded metadata
61+
/// result (e.g. cross-catalog column listing) streams with bounded
62+
/// memory rather than being drained into a `Vec` at construction.
5863
Owned {
5964
schema: SchemaRef,
60-
batches: std::vec::IntoIter<RecordBatch>,
65+
stream: crate::result_stream::ResultStream,
6166
},
6267
/// Borrow of the executed statement that produced this stream
6368
/// (sync execute path). The raw pointer is only dereferenced after
@@ -70,17 +75,16 @@ enum ResultStreamInner {
7075
},
7176
}
7277

73-
/// Crate-internal: build an owned result-stream handle from a schema and
74-
/// a fully-materialised batch list (used by the metadata FFI, which
75-
/// drains its bounded result on the runtime before calling this).
78+
/// Crate-internal: build an owned result-stream handle that lazily drives
79+
/// the given `ResultStream` (used by the metadata FFI). `schema` is
80+
/// captured up front so `get_schema` needs no runtime; each `next_batch`
81+
/// pulls one batch on the runtime.
7682
pub(crate) fn into_raw_result_stream(
7783
schema: SchemaRef,
78-
batches: Vec<RecordBatch>,
84+
stream: crate::result_stream::ResultStream,
7985
) -> *mut kernel_result_stream_t {
80-
Box::into_raw(Box::new(ResultStreamInner::Owned {
81-
schema,
82-
batches: batches.into_iter(),
83-
})) as *mut kernel_result_stream_t
86+
Box::into_raw(Box::new(ResultStreamInner::Owned { schema, stream }))
87+
as *mut kernel_result_stream_t
8488
}
8589

8690
/// 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(
205209

206210
// Pull the next owned batch from whichever backing shape this is.
207211
let next: Option<Result<RecordBatch, Error>> = match inner {
208-
// Owned (metadata): batches were fully drained on the runtime
209-
// at construction, so this is a pure in-memory pop — no tokio
210-
// reactor needed (avoids the off-runtime CloudFetch hang).
211-
ResultStreamInner::Owned { batches, .. } => batches.next().map(Ok),
212+
// Owned (metadata): drive the owned ResultStream lazily on the
213+
// runtime, one batch at a time, so an unbounded result streams
214+
// with bounded memory. Running through block_on_ffi keeps the
215+
// (possibly CloudFetch-backed) reader on the tokio reactor
216+
// rather than off a plain C thread.
217+
ResultStreamInner::Owned { stream, .. } => {
218+
match super::block_on_ffi(move || {
219+
let stream: &mut crate::result_stream::ResultStream = stream;
220+
Box::pin(async move {
221+
#[allow(
222+
unreachable_patterns,
223+
reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants"
224+
)]
225+
match stream.next_batch().await? {
226+
Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())),
227+
Some(_) => Err(Error::not_implemented().message(
228+
"metadata stream yielded a non-Arrow batch; the C ABI exports \
229+
Arrow only",
230+
)),
231+
None => Ok(None),
232+
}
233+
})
234+
}) {
235+
Ok(Some(rb)) => Some(Ok(rb)),
236+
Ok(None) => None,
237+
Err(code) => return code, // error already stored
238+
}
239+
}
212240
ResultStreamInner::Executed { exec, valid } => {
213241
let exec = match executed_ref(*exec, valid) {
214242
Ok(e) => e,
@@ -306,14 +334,32 @@ mod tests {
306334
(schema, batch)
307335
}
308336

337+
/// Build an Owned result-stream handle over the given in-memory
338+
/// batches (mirrors the metadata FFI's lazy `ResultStream`-backed
339+
/// handle) using a throwaway runtime for the async `from_reader`.
340+
fn owned_stream_over(
341+
schema: SchemaRef,
342+
batches: Vec<RecordBatch>,
343+
) -> *mut kernel_result_stream_t {
344+
use crate::reader::test_utils::MockReader;
345+
use crate::result_stream::ResultStream;
346+
let rt = tokio::runtime::Runtime::new().unwrap();
347+
let stream = rt.block_on(async {
348+
ResultStream::from_reader(Box::new(MockReader::new(batches)))
349+
.await
350+
.unwrap()
351+
});
352+
into_raw_result_stream(schema, stream)
353+
}
354+
309355
/// End-of-stream on an Owned stream returns `Success` with a
310356
/// **released** array (`release == null`) — the sentinel ODBC / Go
311357
/// consumers loop on. A regression that returned a non-released empty
312358
/// array would loop them forever, so pin it.
313359
#[test]
314360
fn owned_stream_exhaustion_yields_released_array() {
315361
let (schema, batch) = one_row_batch();
316-
let stream = into_raw_result_stream(schema, vec![batch]);
362+
let stream = owned_stream_over(schema, vec![batch]);
317363

318364
// First call: a real batch (release non-null).
319365
let mut arr = FFI_ArrowArray::empty();

‎src/c_abi/session.rs‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -522,8 +522,17 @@ fn build_session(config: KernelSessionConfig) -> Result<Session, KernelStatusCod
522522
})
523523
}
524524

525-
/// Close a session. Releases the underlying Rust [`Session`] (which
526-
/// fires `DeleteSession` server-side on drop / explicit close).
525+
/// Close a session. Initiates the fire-and-forget server-side
526+
/// `DeleteSession` immediately and releases the underlying Rust
527+
/// [`Session`]. Does not block on the delete completing.
528+
///
529+
/// Close the session **last**: because the delete is initiated eagerly,
530+
/// any still-open handle against this session — a statement / executed
531+
/// handle, or a metadata result stream (which holds its own
532+
/// `Arc<SessionInner>` and stays drivable) — must be drained and closed
533+
/// before this call. Driving such a handle afterwards issues RPCs against
534+
/// an already-deleting session and surfaces server errors. See the
535+
/// `databricks_kernel.h` teardown-ordering contract.
527536
///
528537
/// # Safety
529538
///
@@ -539,12 +548,19 @@ pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) ->
539548
);
540549
return KernelStatusCode::InvalidArgument;
541550
}
542-
// Reclaim the box; its `Drop` fires the fire-and-forget
543-
// `DeleteSession`. We deliberately don't `block_on` an explicit
544-
// `Session::close()` here — `Drop` already handles server cleanup,
545-
// and a synchronous close would make `kernel_session_close` block on
546-
// the network for no caller benefit.
547-
drop(Box::from_raw(session as *mut Session));
551+
// Reclaim the box and initiate the fire-and-forget `DeleteSession`
552+
// right now. We call `initiate_delete()` explicitly rather than
553+
// relying on `Drop`: a still-live statement / executed handle holds
554+
// its own `Arc<SessionInner>` clone, so `SessionInner::Drop` (which
555+
// only fires when the *last* Arc drops) would otherwise defer the
556+
// server-side delete until those handles are released — contradicting
557+
// the header's "close initiates the delete" contract. `initiate_delete`
558+
// is idempotent, so the eventual `Drop` becomes a no-op. We still don't
559+
// `block_on` an awaited close — that would make close block on the
560+
// network for no caller benefit.
561+
let session = Box::from_raw(session as *mut Session);
562+
session.initiate_delete();
563+
drop(session);
548564
KernelStatusCode::Success
549565
}
550566

0 commit comments

Comments
 (0)