Skip to content
Closed
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
47 changes: 39 additions & 8 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,8 @@ typedef struct kernel_session_config_t KernelSessionConfig;
typedef struct kernel_session_t kernel_session_t;
typedef struct kernel_statement_t kernel_statement_t;
typedef struct kernel_executed_statement_t kernel_executed_statement_t;
/* Async-consumption executed handle. Reserved: the async submit path is
* deferred in v0 (see kernel_statement_submit), so no consumer receives a
* live instance yet. */
/* Async-consumption executed handle, returned by kernel_statement_submit
* and polled via kernel_executed_async_statement_status. */
typedef struct kernel_executed_async_statement_t kernel_executed_async_statement_t;
typedef struct kernel_result_stream_t kernel_result_stream_t;

Expand Down Expand Up @@ -285,15 +284,47 @@ KernelStatusCode kernel_statement_execute(kernel_statement_t* stmt,
kernel_executed_statement_t** out);

/*
* Submit-and-return (async). DEFERRED in v0: this always returns
* `KernelStatusCode_InvalidArgument` (with an explanatory last error) and
* writes nothing to `*out`. Use the synchronous `kernel_statement_execute`
* path. Declared so the symbol/contract is visible; wired when an ODBC /
* Go consumer needs caller-driven polling.
* Submit-and-return (async). Submits the statement for asynchronous
* execution and writes an async handle to `*out`; the caller then polls
* `kernel_executed_async_statement_status` (sleeping between polls, so no
* server-side worker thread is held), fetches the result once
* terminal-succeeded, and may cancel a running statement. This is the path
* a host driver uses to honor caller-side cancellation/deadlines. The
* returned handle must be released with `kernel_executed_async_statement_close`.
*/
KernelStatusCode kernel_statement_submit(kernel_statement_t* stmt,
kernel_executed_async_statement_t** out);

/*
* Poll the server-side status of an async statement into `*out_kind`.
* A `Failed` status stores the underlying error (retrievable via
* `kernel_get_last_error`) and writes `KernelStatementStatusKind_Failed`;
* the poll call itself still returns `KernelStatusCode_Success`.
*/
KernelStatusCode kernel_executed_async_statement_status(
kernel_executed_async_statement_t* aexec, KernelStatementStatusKind* out_kind);

/*
* Fetch the result stream once the statement is terminal-succeeded. `*out`
* receives an owned result stream that is driven lazily (CloudFetch chunks
* are fetched on demand, not materialised up front). Release it with
* `kernel_result_stream_close`. Calling this before the statement succeeds
* returns an error.
*/
KernelStatusCode kernel_executed_async_statement_get_result_stream(
kernel_executed_async_statement_t* aexec, kernel_result_stream_t** out);

/* Cancel a running async statement. */
KernelStatusCode kernel_executed_async_statement_cancel(
kernel_executed_async_statement_t* aexec);

/*
* Free an async executed handle. Does NOT touch the parent statement,
* which you release separately with `kernel_statement_close`.
*/
KernelStatusCode kernel_executed_async_statement_close(
kernel_executed_async_statement_t* aexec);

/*
* Free the statement lifecycle owner. Does NOT free executed-handle
* boxes — each executed handle is a separate allocation that you must
Expand Down
6 changes: 6 additions & 0 deletions src/c_abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ static RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
///
/// [`Error`]: crate::kernel_error::Error
pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime::Runtime> {
// Initialise tracing once (idempotent via the logging module's OnceLock) so
// RUST_LOG=databricks_sql_kernel=debug surfaces the kernel's per-request logs
// for a C-ABI consumer (Go/ODBC) that installs no Rust-side subscriber.
// Without this, RUST_LOG is a no-op over the C ABI. Called here because
// runtime() is the funnel every async entry point passes through.
crate::logging::init_logging(&crate::logging::LogConfig::default());
// `OnceLock::get_or_init` can't carry a fallible initialiser, so do
// the build-or-fetch dance by hand: try to fetch, and on a miss
// build once and install. A lost race just drops our spare runtime.
Expand Down
48 changes: 47 additions & 1 deletion src/c_abi/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
use super::error::{store_and_code, store_invalid_arg};
use super::{catch_ffi, KernelStatusCode};
use crate::kernel_error::{Error, ErrorCode};
use crate::result_stream::{ResultBatch, SchemaRef};
use crate::result_stream::{ResultBatch, ResultStream, SchemaRef};
use crate::statement::executed::ExecutedStatement;
use crate::statement::validity::ValidityFlag;
use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema};
Expand Down Expand Up @@ -68,6 +68,14 @@ enum ResultStreamInner {
exec: *mut ExecutedStatement,
valid: ValidityFlag,
},
/// Owns a `ResultStream` and drives it lazily, one batch per
/// `next_batch` call (async execute path, via
/// `kernel_executed_async_statement_get_result_stream`). Unlike
/// `Owned`, batches are NOT pre-drained — a large CloudFetch result
/// streams chunk-by-chunk instead of materialising in memory. Unlike
/// `Executed`, the stream is owned outright (no borrow / validity
/// flag), so it stays valid regardless of the async handle's lifetime.
OwnedLazy { stream: Box<ResultStream> },
}

/// Crate-internal: build an owned result-stream handle from a schema and
Expand Down Expand Up @@ -98,6 +106,16 @@ pub(crate) unsafe fn into_raw_executed_stream(
as *mut kernel_result_stream_t
}

/// Crate-internal: build a result-stream handle that owns a `ResultStream`
/// and drives it lazily (async execute path). The stream is driven one
/// batch per `next_batch` call on the runtime, so CloudFetch chunks are
/// fetched on demand rather than pre-materialised.
pub(crate) fn into_raw_owned_lazy_stream(stream: ResultStream) -> *mut kernel_result_stream_t {
Box::into_raw(Box::new(ResultStreamInner::OwnedLazy {
stream: Box::new(stream),
})) as *mut kernel_result_stream_t
}

/// Resolve the backing `ExecutedStatement` for the `Executed` shape.
///
/// Two independent stale-handle guards, checked in this order so the
Expand Down Expand Up @@ -166,6 +184,7 @@ pub unsafe extern "C" fn kernel_result_stream_get_schema(
Ok(e) => e.schema(),
Err(code) => return code,
},
ResultStreamInner::OwnedLazy { stream } => stream.schema(),
};
match FFI_ArrowSchema::try_from(schema.as_ref()) {
Ok(ffi_schema) => {
Expand Down Expand Up @@ -243,6 +262,33 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch(
Err(code) => return code, // error already stored
}
}
ResultStreamInner::OwnedLazy { stream } => {
// Owned stream: drive its next_batch on the runtime so lazy
// CloudFetch link fetches keep working, cloning the borrowed
// Arrow batch into an owned RecordBatch for FFI export. Same
// #[non_exhaustive] fallback as the Executed arm.
match super::block_on_ffi(move || {
let stream: &mut 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(
"result 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
}
}
};

match next {
Expand Down
Loading
Loading