From f28692609ed226f3be286dac6d04d5c5f3002ca5 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Tue, 30 Jun 2026 10:39:01 +0000 Subject: [PATCH 1/7] [PECOBLR-2096] Implement the v0 Kernel C ABI (deferred PR 6) Fill in the C ABI bodies under src/ffi/ so ODBC / Go consumers can link the kernel without going through ADBC. This unblocks the ODBC driver's migration off the ADBC Rust backend onto the kernel. - Process-wide tokio runtime + thread-local last-error buffer (block_on_ffi, kernel_get_last_error), with panic-catch at the FFI edge. - Session: KernelSessionConfig builder + setters (warehouse / http_path, PAT + OAuth M2M), kernel_session_open / close / new_statement. - Statement: set_sql, positional bind_* setters, synchronous execute. Async submit stays deferred (returns InvalidArgument) until a consumer needs caller-driven polling over the C ABI. - Result stream: schema + per-batch export via the Arrow C Data Interface (arrow-array `ffi` feature). The executed-statement stream borrows its executed handle so drain-driven auto-close and lazy CloudFetch link fetches keep working. - Metadata: list_catalogs / _schemas / _tables / _columns / primary_keys / foreign_keys as thin shims over Session::metadata(), server-shaped. - Hand-written include/databricks_kernel.h, a hermetic C smoke test (tests/c/session_smoke.c, 20 checks), a `make c-abi-test` target, and a pr-checks.yml CI job. cargo build / clippy --all-targets -D warnings / fmt --check clean; 668 Rust tests + 20 C smoke checks pass. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- .github/workflows/pr-checks.yml | 23 ++ Cargo.lock | 3 + Cargo.toml | 6 +- Makefile | 17 +- include/databricks_kernel.h | 300 ++++++++++++++++++++++ src/ffi/error.rs | 216 ++++++++++++++-- src/ffi/metadata.rs | 275 ++++++++++++++++++-- src/ffi/mod.rs | 111 +++++++- src/ffi/result.rs | 222 +++++++++++++--- src/ffi/session.rs | 398 ++++++++++++++++++++++++++--- src/ffi/statement.rs | 438 +++++++++++++++++++------------- tests/c/session_smoke.c | 140 ++++++++++ 12 files changed, 1872 insertions(+), 277 deletions(-) create mode 100644 include/databricks_kernel.h create mode 100644 tests/c/session_smoke.c diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index e7a96734..874c9a95 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -118,6 +118,29 @@ jobs: # a live workspace; `rust-e2e.yml` runs them separately. run: cargo test --workspace + c-abi: + name: C ABI smoke test + runs-on: + group: databricks-protected-runner-group + labels: linux-ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - uses: ./.github/actions/setup-jfrog + with: + cargo: "true" + + - uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1.16.1 + with: + toolchain: stable + + - name: make c-abi-test + # Builds the cdylib and compiles + runs the hand-written C smoke + # tests in tests/c/ against the C ABI exported from src/ffi/. + # Hermetic (no live warehouse) — proves ODBC / Go consumers can + # link and call the kernel. `cc` is preinstalled on the runner. + run: make c-abi-test + check-tls-rustls: name: Build (tls-rustls feature) runs-on: diff --git a/Cargo.lock b/Cargo.lock index 1c7ac8ee..2c59f7e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,6 +142,9 @@ name = "arrow-schema" version = "57.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4cf0d4a6609679e03002167a61074a21d7b1ad9ea65e462b2c0a97f8a3b2bc6" +dependencies = [ + "bitflags", +] [[package]] name = "arrow-select" diff --git a/Cargo.toml b/Cargo.toml index 60836ebd..03954470 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,11 @@ categories = ["database"] tracing = { version = "0.1", features = ["log"] } tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } -arrow-array = "57" +# `ffi` enables the Arrow C Data Interface (`FFI_ArrowArray` / +# `FFI_ArrowSchema`, `to_ffi`) used by the C ABI's result-stream export +# (`src/ffi/result.rs`) so ODBC / Go consumers can pull result batches +# across the boundary without re-encoding. +arrow-array = { version = "57", features = ["ffi"] } arrow-buffer = "57" arrow-cast = "57" arrow-ord = "57" diff --git a/Makefile b/Makefile index 30c016fd..f102d484 100644 --- a/Makefile +++ b/Makefile @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -.PHONY: all build test fmt lint clean check coverage coverage-check +.PHONY: all build test fmt lint clean check coverage coverage-check c-abi-test all: build @@ -31,7 +31,20 @@ fmt-check: lint: cargo clippy -- -D warnings -check: fmt-check lint test +# Compile the hand-written C smoke tests against the cdylib and run them. +# Proves the C ABI in `src/ffi/` links and behaves from a real C consumer +# (the ODBC / Go path). Hermetic — no live warehouse needed. +c-abi-test: + cargo build --lib + @mkdir -p target/c-abi + @for src in tests/c/*.c; do \ + name=$$(basename $$src .c); \ + echo "cc $$src"; \ + cc -I include $$src -L target/debug -ldatabricks_sql_kernel -o target/c-abi/$$name || exit 1; \ + LD_LIBRARY_PATH=target/debug DYLD_LIBRARY_PATH=target/debug ./target/c-abi/$$name || exit 1; \ + done + +check: fmt-check lint test c-abi-test clean: cargo clean diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h new file mode 100644 index 00000000..d5d7b356 --- /dev/null +++ b/include/databricks_kernel.h @@ -0,0 +1,300 @@ +/* + * 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. + */ + +/* + * Databricks SQL Kernel — C ABI (v0). + * + * Hand-written header for the kernel's custom C ABI (cbindgen + * integration is a v0.1 concern). The bodies live in `src/ffi/` in the + * `databricks-sql-kernel` crate, compiled as a `cdylib` / `staticlib`. + * + * This is the surface ODBC / Go consumers link against. It is NOT ADBC: + * the kernel exposes a Databricks-native session / statement / result / + * metadata model. Result data crosses the boundary via the Arrow C Data + * Interface (`FFI_ArrowArray` / `FFI_ArrowSchema`), one array per + * `kernel_result_stream_next_batch` call (a pull model). + * + * ## Error reporting + * + * Every fallible entry point returns a `KernelStatusCode`. On any + * non-`Success` return, call `kernel_get_last_error` to fetch the typed + * detail for the current thread. The thread-local error buffer is reset + * at the start of every kernel call, and the `char*` fields it hands + * back are valid only until the next kernel call on the same thread — + * copy them out before calling again. + * + * ## ABI versioning + * + * Every public struct carries a leading `uint32_t version`. Struct + * layout may change freely through v0.x (no ABI promise); ABI stability + * is committed at v1.0. + */ + +#ifndef DATABRICKS_KERNEL_H +#define DATABRICKS_KERNEL_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* ─── Arrow C Data Interface ────────────────────────────────────────── + * + * Mirrors the canonical `ArrowArray` / `ArrowSchema` from the Arrow C + * Data Interface (https://arrow.apache.org/docs/format/CDataInterface.html). + * The kernel populates these via the `arrow-array` crate's `ffi` module. + * If the consuming project already declares these (e.g. via Arrow's + * `abi.h`), define `DATABRICKS_KERNEL_NO_ARROW_CDATA` before including + * this header to suppress the duplicate definitions. + */ +#ifndef DATABRICKS_KERNEL_NO_ARROW_CDATA + +struct ArrowSchema { + const char* format; + const char* name; + const char* metadata; + int64_t flags; + int64_t n_children; + struct ArrowSchema** children; + struct ArrowSchema* dictionary; + void (*release)(struct ArrowSchema*); + void* private_data; +}; + +struct ArrowArray { + int64_t length; + int64_t null_count; + int64_t offset; + int64_t n_buffers; + int64_t n_children; + const void** buffers; + struct ArrowArray** children; + struct ArrowArray* dictionary; + void (*release)(struct ArrowArray*); + void* private_data; +}; + +#endif /* DATABRICKS_KERNEL_NO_ARROW_CDATA */ + +/* ─── Status + error ────────────────────────────────────────────────── + * + * Discriminants match `crate::ffi::KernelStatusCode`. Keep this enum in + * lockstep with that Rust enum (the Rust side enforces a 1:1 mapping + * against `ErrorCode` with an exhaustive match). + */ +typedef enum KernelStatusCode { + KernelStatusCode_Success = 0, + KernelStatusCode_InvalidArgument = 1, + KernelStatusCode_Unauthenticated = 2, + KernelStatusCode_PermissionDenied = 3, + KernelStatusCode_NotFound = 4, + KernelStatusCode_ResourceExhausted = 5, + KernelStatusCode_Unavailable = 6, + KernelStatusCode_Timeout = 7, + KernelStatusCode_Cancelled = 8, + KernelStatusCode_DataLoss = 9, + KernelStatusCode_Internal = 10, + KernelStatusCode_InvalidStatementHandle = 11, + KernelStatusCode_NetworkError = 12, + KernelStatusCode_SqlError = 13, +} KernelStatusCode; + +/* Server-side async execution status (mirror of + * `KernelStatementStatusKind`). Reserved for the async submit path, + * which is not exposed over the v0 C ABI. */ +typedef enum KernelStatementStatusKind { + KernelStatementStatusKind_Pending = 0, + KernelStatementStatusKind_Running = 1, + KernelStatementStatusKind_Succeeded = 2, + KernelStatementStatusKind_Failed = 3, + KernelStatementStatusKind_Cancelled = 4, + KernelStatementStatusKind_Closed = 5, +} KernelStatementStatusKind; + +/* + * Typed last-error detail. Populated by `kernel_get_last_error`. The + * `char*` fields point into the calling thread's last-error buffer and + * are valid only until the next kernel call on that thread; a NULL + * pointer means the field was absent. `vendor_code` / `http_status` are + * `0` when absent. + */ +typedef struct KernelError { + /* Discriminant value of `KernelStatusCode`. */ + int32_t code; + const char* message; + /* 5 ASCII chars + NUL, or NULL if absent. */ + const char* sql_state; + int32_t vendor_code; + uint16_t http_status; + bool retryable; + const char* query_id; +} KernelError; + +/* + * Fetch the last error recorded on the calling thread. Returns `false` + * (leaving `*out` untouched) if no error has been recorded since the + * last kernel call cleared the buffer. + */ +bool kernel_get_last_error(KernelError* out); + +/* ─── Opaque handles ────────────────────────────────────────────────── + * + * All handles are owned heap allocations on the Rust side; the C side + * holds them by pointer and releases each via its matching `*_close` / + * `*_free`. + */ +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; +typedef struct kernel_result_stream_t kernel_result_stream_t; + +/* ─── Session config ────────────────────────────────────────────────── + * + * 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. + */ +KernelStatusCode kernel_session_config_new(KernelSessionConfig** out); +void kernel_session_config_free(KernelSessionConfig* config); + +/* Connection identity — call exactly one; the last one wins. */ +KernelStatusCode kernel_session_config_set_warehouse(KernelSessionConfig* config, + const char* host, + const char* warehouse_id); +KernelStatusCode kernel_session_config_set_http_path(KernelSessionConfig* config, + const char* host, + const char* http_path); + +/* Authentication — call exactly one; the last one wins. */ +KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, + const char* token); +KernelStatusCode kernel_session_config_set_auth_m2m(KernelSessionConfig* config, + const char* client_id, + const char* client_secret); + +/* Add (or overwrite) one server-bound session-conf entry. */ +KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* config, + const char* key, + const char* value); + +/* ─── Session lifecycle ───────────────────────────────────────────────*/ + +/* + * Open a session. CONSUMES `config` on both success and failure — do not + * use or free `config` afterwards. On success, `*out` holds a session + * handle released with `kernel_session_close`. + */ +KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session_t** out); +KernelStatusCode kernel_session_close(kernel_session_t* session); + +/* Construct a new mutable statement bound to this session. */ +KernelStatusCode kernel_session_new_statement(kernel_session_t* session, + kernel_statement_t** out); + +/* ─── Statement ───────────────────────────────────────────────────────*/ + +KernelStatusCode kernel_statement_set_sql(kernel_statement_t* stmt, const char* sql); + +/* Positional parameter binding (1-based ordinal). */ +KernelStatusCode kernel_statement_bind_null(kernel_statement_t* stmt, size_t ordinal); +KernelStatusCode kernel_statement_bind_int64(kernel_statement_t* stmt, size_t ordinal, + int64_t value); +KernelStatusCode kernel_statement_bind_double(kernel_statement_t* stmt, size_t ordinal, + double value); +KernelStatusCode kernel_statement_bind_bool(kernel_statement_t* stmt, size_t ordinal, bool value); +KernelStatusCode kernel_statement_bind_string(kernel_statement_t* stmt, size_t ordinal, + const char* value); + +/* + * Wait-for-result execution. On success, `*out` holds an executed handle + * released with `kernel_executed_statement_close`. + */ +KernelStatusCode kernel_statement_execute(kernel_statement_t* stmt, + kernel_executed_statement_t** out); + +/* + * Free the statement lifecycle owner. Does NOT free executed-handle + * boxes; close each of those separately. + */ +KernelStatusCode kernel_statement_close(kernel_statement_t* stmt); + +/* ─── Executed statement (sync) ───────────────────────────────────────*/ + +/* + * Obtain a result-stream handle that BORROWS `exec`. The stream is valid + * only as long as `exec` is: close the stream + * (`kernel_result_stream_close`) before closing `exec`. + */ +KernelStatusCode kernel_executed_statement_get_result_stream(kernel_executed_statement_t* exec, + kernel_result_stream_t** out); + +/* Rows modified by a DML statement, or -1 if not applicable / unknown. */ +int64_t kernel_executed_statement_num_modified_rows(const kernel_executed_statement_t* exec); + +KernelStatusCode kernel_executed_statement_close(kernel_executed_statement_t* exec); + +/* ─── Result stream ─────────────────────────────────────────────────── + * + * The schema is exported once; each `next_batch` call exports one Arrow + * array. End-of-stream is signalled by a RELEASED array (its `release` + * callback is NULL) returned with `KernelStatusCode_Success`. + */ +KernelStatusCode kernel_result_stream_get_schema(kernel_result_stream_t* stream, + struct ArrowSchema* out); +KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, + struct ArrowArray* out_array, + struct ArrowSchema* out_schema); +KernelStatusCode kernel_result_stream_close(kernel_result_stream_t* stream); + +/* ─── Metadata ──────────────────────────────────────────────────────── + * + * Each returns a self-contained result stream (released via + * `kernel_result_stream_close`) carrying the server-shaped + * (JDBC-canonical) columns. NULL string args mean "unfiltered". Pattern + * args accept SQL LIKE wildcards; identifier args are exact. + */ +KernelStatusCode kernel_metadata_list_catalogs(kernel_session_t* session, + kernel_result_stream_t** out); +KernelStatusCode kernel_metadata_list_schemas(kernel_session_t* session, const char* catalog, + const char* schema_pattern, + kernel_result_stream_t** out); +KernelStatusCode kernel_metadata_list_tables(kernel_session_t* session, const char* catalog, + const char* schema_pattern, const char* table_pattern, + const char* table_types_csv, + kernel_result_stream_t** out); +KernelStatusCode kernel_metadata_list_columns(kernel_session_t* session, const char* catalog, + const char* schema_pattern, const char* table_pattern, + const char* column_pattern, + kernel_result_stream_t** out); +KernelStatusCode kernel_metadata_primary_keys(kernel_session_t* session, const char* catalog, + const char* schema, const char* table, + kernel_result_stream_t** out); +KernelStatusCode kernel_metadata_foreign_keys(kernel_session_t* session, const char* parent_catalog, + const char* parent_schema, const char* parent_table, + const char* foreign_catalog, + const char* foreign_schema, const char* foreign_table, + kernel_result_stream_t** out); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* DATABRICKS_KERNEL_H */ diff --git a/src/ffi/error.rs b/src/ffi/error.rs index 196b5583..6ba73fd3 100644 --- a/src/ffi/error.rs +++ b/src/ffi/error.rs @@ -19,10 +19,10 @@ //! function clears the buffer at entry and writes to it on error; //! callers fetch detail with `kernel_get_last_error`. -#![allow(dead_code, unused_variables)] - +use super::KernelStatusCode; use crate::kernel_error::Error; -use std::ffi::c_char; +use std::cell::RefCell; +use std::ffi::{c_char, CString}; /// Mirror of `crate::kernel_error::Error` in `repr(C)` form. /// @@ -47,10 +47,52 @@ pub struct KernelError { pub query_id: *const c_char, } +/// Owned backing store for the thread-local last error. +/// +/// Holds the `CString`s alive so the `*const c_char` pointers handed +/// back through [`KernelError`] stay valid until the next FFI call on +/// this thread clears or overwrites the buffer. `code == None` means +/// "no error recorded since the last clear". +#[derive(Default)] +struct LastError { + code: Option, + message: Option, + sql_state: Option, + vendor_code: i32, + http_status: u16, + retryable: bool, + query_id: Option, +} + +thread_local! { + /// Per-thread last-error slot. The C ABI is call-response on a + /// single thread: a function clears this on entry, populates it on + /// failure, and the caller reads it via `kernel_get_last_error` + /// before making the next FFI call on the same thread. + static LAST_ERROR: RefCell = RefCell::new(LastError::default()); +} + +/// Turn a Rust `String` into a `CString`, replacing any interior NUL +/// bytes with `?` so a message that happens to contain `\0` can't make +/// `CString::new` fail (which would lose the error detail entirely). +fn to_cstring_lossy(s: &str) -> CString { + // Fast path: no interior NUL. + match CString::new(s) { + Ok(c) => c, + Err(_) => { + let sanitised: String = s.chars().map(|c| if c == '\0' { '?' } else { c }).collect(); + CString::new(sanitised).unwrap_or_else(|_| CString::new("").expect("empty CString")) + } + } +} + /// Fetch the last error set on this thread. /// /// Returns `false` if no error has been recorded since the last -/// `clear_last_error()` (or thread-start). +/// [`clear_error`] (or thread start), leaving `*out` untouched. On +/// `true`, `*out` is fully populated; its `*const c_char` fields point +/// into this thread's last-error buffer and are valid until the next +/// `kernel_*` call on this thread. /// /// # Safety /// `out` must be a valid, writable pointer to a `KernelError`. The @@ -58,23 +100,165 @@ pub struct KernelError { /// this thread. #[no_mangle] pub unsafe extern "C" fn kernel_get_last_error(out: *mut KernelError) -> bool { - unimplemented!("PR 7a: thread-local last-error pattern") + if out.is_null() { + return false; + } + LAST_ERROR.with(|cell| { + let last = cell.borrow(); + let Some(code) = last.code else { + return false; + }; + let as_ptr = |c: &Option| c.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()); + // SAFETY: `out` is non-null and writable per the contract. + std::ptr::write( + out, + KernelError { + code: KernelStatusCode::from(code) as i32, + message: as_ptr(&last.message), + sql_state: as_ptr(&last.sql_state), + vendor_code: last.vendor_code, + http_status: last.http_status, + retryable: last.retryable, + query_id: as_ptr(&last.query_id), + }, + ); + true + }) } -/// Crate-internal: write a typed kernel `Error` into the thread-local +/// Crate-internal: write a typed kernel [`Error`] into the thread-local /// last-error buffer. Every FFI function that returns a non-`Success` -/// status code calls this with the underlying `Error` first; the -/// consumer then retrieves it via `kernel_get_last_error`. -/// -/// PR 7a fills the body. The signature is captured here so PR 7a's -/// implementation is a body-only change with no public-API surface. +/// status code calls this (via [`crate::ffi::block_on_ffi`] or directly) +/// so the consumer can retrieve the structured detail with +/// [`kernel_get_last_error`]. pub(crate) fn store_error(err: Error) { - unimplemented!("PR 7a: serialize Error into the thread-local KernelError buffer") + LAST_ERROR.with(|cell| { + let mut last = cell.borrow_mut(); + // Prefer the structured `vendor_code`; the SEA wire ships a + // string `error_code` slug, which we surface in the message + // rather than the numeric slot (the C struct has no string + // error-code field in v0). + let mut message = err.message.clone(); + if let Some(ec) = err.error_code.as_deref() { + if !message.is_empty() { + message.push_str("; "); + } + message.push_str("error_code="); + message.push_str(ec); + } + *last = LastError { + code: Some(err.code), + message: Some(to_cstring_lossy(&message)), + sql_state: err.sql_state.as_deref().map(to_cstring_lossy), + vendor_code: err.vendor_code.unwrap_or(0), + http_status: err.http_status.unwrap_or(0), + retryable: err.retryable, + query_id: err.query_id.as_deref().map(to_cstring_lossy), + }; + }); } -/// Crate-internal: clear the thread-local last-error buffer. Called -/// at the entry of every FFI function so a previous thread's stale -/// error doesn't leak into a subsequent call. +/// Crate-internal: clear the thread-local last-error buffer. Called at +/// the entry of every FFI function (via [`crate::ffi::block_on_ffi`] or +/// directly) so a previous call's stale error can't leak into a +/// subsequent one that succeeds. pub(crate) fn clear_error() { - unimplemented!("PR 7a: zero out the thread-local") + LAST_ERROR.with(|cell| *cell.borrow_mut() = LastError::default()); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Helper: read the thread-local error into a `KernelError` and run + /// `f` with the borrowed C strings still alive. + fn with_last_error(f: impl FnOnce(Option) -> R) -> R { + let mut out = std::mem::MaybeUninit::::uninit(); + // SAFETY: out is a valid writable pointer. + let present = unsafe { kernel_get_last_error(out.as_mut_ptr()) }; + if present { + // SAFETY: kernel_get_last_error returned true so out is init. + f(Some(unsafe { out.assume_init() })) + } else { + f(None) + } + } + + #[test] + fn no_error_after_clear() { + clear_error(); + with_last_error(|e| assert!(e.is_none())); + } + + #[test] + fn store_then_fetch_roundtrips_core_fields() { + store_error( + Error::sql_error() + .message("boom") + .with_sql_state("42601") + .with_http_status(400) + .with_query_id("q-123"), + ); + with_last_error(|e| { + let e = e.expect("error present"); + assert_eq!(e.code, KernelStatusCode::SqlError as i32); + assert_eq!(e.http_status, 400); + // SAFETY: message is non-null after a store. + let msg = unsafe { std::ffi::CStr::from_ptr(e.message) } + .to_str() + .unwrap(); + assert!(msg.contains("boom")); + let ss = unsafe { std::ffi::CStr::from_ptr(e.sql_state) } + .to_str() + .unwrap(); + assert_eq!(ss, "42601"); + let qid = unsafe { std::ffi::CStr::from_ptr(e.query_id) } + .to_str() + .unwrap(); + assert_eq!(qid, "q-123"); + }); + clear_error(); + } + + #[test] + fn store_error_folds_error_code_slug_into_message() { + store_error( + Error::sql_error() + .message("statement gone") + .with_error_code("STATEMENT_NOT_FOUND"), + ); + with_last_error(|e| { + let e = e.expect("error present"); + let msg = unsafe { std::ffi::CStr::from_ptr(e.message) } + .to_str() + .unwrap(); + assert!(msg.contains("statement gone")); + assert!(msg.contains("STATEMENT_NOT_FOUND")); + }); + clear_error(); + } + + #[test] + fn retryable_flag_carries_through() { + store_error(Error::unavailable().message("cold start")); + with_last_error(|e| { + let e = e.expect("error present"); + assert_eq!(e.code, KernelStatusCode::Unavailable as i32); + assert!(e.retryable); + }); + clear_error(); + } + + #[test] + fn message_with_interior_nul_is_sanitised() { + store_error(Error::internal().message("a\0b")); + with_last_error(|e| { + let e = e.expect("error present"); + let msg = unsafe { std::ffi::CStr::from_ptr(e.message) } + .to_str() + .unwrap(); + assert_eq!(msg, "a?b"); + }); + clear_error(); + } } diff --git a/src/ffi/metadata.rs b/src/ffi/metadata.rs index 0ffb476b..e63c24b9 100644 --- a/src/ffi/metadata.rs +++ b/src/ffi/metadata.rs @@ -12,67 +12,300 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Metadata FFI — one C entry point per `Metadata` method. Each -//! returns a `kernel_result_stream_t` the caller drives via -//! `kernel_result_stream_*`. (`Metadata` is `'static`; addendum A1.) - -#![allow(dead_code, unused_variables)] +//! Metadata FFI — one C entry point per `Metadata` method. Each returns +//! 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. +//! +//! Results carry the **server-shaped** (JDBC-canonical) columns the +//! kernel's `Metadata` produces; ODBC / JDBC drivers keep their own +//! rename / reshape layer on top. +use super::result::{into_raw_result_stream, kernel_result_stream_t}; use super::session::kernel_session_t; -use super::KernelStatusCode; -use std::ffi::c_char; +use super::{block_on_ffi, KernelStatusCode}; +use crate::kernel_error::{Error, Result}; +use crate::metadata_v0::{Identifier, LikePattern}; +use crate::result_stream::{OwnedBatchIter, ResultStream, SchemaRef}; +use crate::session::Session; +use std::ffi::{c_char, CStr}; + +/// Read an optional C string: null → `None`, else borrowed `&str` +/// (errors on non-UTF-8). +/// +/// # Safety +/// `ptr`, if non-null, must point to a NUL-terminated C string. +unsafe fn opt_str<'a>(ptr: *const c_char, what: &str) -> Result> { + if ptr.is_null() { + return Ok(None); + } + CStr::from_ptr(ptr) + .to_str() + .map(Some) + .map_err(|_| Error::invalid_argument().message(format!("{what} is not valid UTF-8"))) +} + +/// Read a required C string as a borrowed `&str`. +/// +/// # Safety +/// As [`opt_str`]. +unsafe fn req_str<'a>(ptr: *const c_char, what: &str) -> Result<&'a str> { + opt_str(ptr, what)? + .ok_or_else(|| Error::invalid_argument().message(format!("{what} must not be null"))) +} + +/// Optional [`Identifier`] from a C string (null → `None`). +unsafe fn opt_ident<'a>(ptr: *const c_char, what: &str) -> Result>> { + match opt_str(ptr, what)? { + Some(s) => Ok(Some(Identifier::new(s)?)), + None => Ok(None), + } +} + +/// Optional [`LikePattern`] from a C string (null → `None`). +unsafe fn opt_pattern<'a>(ptr: *const c_char, what: &str) -> Result>> { + match opt_str(ptr, what)? { + Some(s) => Ok(Some(LikePattern::new(s)?)), + None => Ok(None), + } +} + +/// Capture a `ResultStream`'s schema and consume it into an owned batch +/// iterator, ready to wrap in a `kernel_result_stream_t`. +fn into_parts(stream: ResultStream) -> (SchemaRef, OwnedBatchIter) { + let schema = stream.schema(); + (schema, stream.into_owned_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. +/// +/// # Safety +/// `session` must be a live session handle; `out` must be writable. +unsafe fn run_metadata( + session: *mut kernel_session_t, + out: *mut *mut kernel_result_stream_t, + build: F, +) -> KernelStatusCode +where + F: FnOnce( + &Session, + ) + -> std::pin::Pin> + '_>>, +{ + crate::ffi::error::clear_error(); + let Some(session) = (session as *const Session).as_ref() else { + return store_null("metadata: session must not be null"); + }; + if out.is_null() { + return store_null("metadata: out must not be null"); + } + let result = block_on_ffi(move || async move { + let stream = build(session).await?; + Ok(into_parts(stream)) + }); + match result { + Ok((schema, iter)) => { + std::ptr::write(out, into_raw_result_stream(schema, iter)); + KernelStatusCode::Success + } + Err(code) => code, + } +} +/// List the catalogs visible to the session. +/// +/// # Safety +/// `session` must be a live handle from `kernel_session_open`; `out` +/// must be a valid, writable pointer. #[no_mangle] pub unsafe extern "C" fn kernel_metadata_list_catalogs( session: *mut kernel_session_t, - out: *mut *mut super::result::kernel_result_stream_t, + out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { - unimplemented!("PR 7d") + run_metadata(session, out, |session| { + Box::pin(async move { session.metadata().list_catalogs().await }) + }) } +/// List schemas filtered by catalog (exact) and schema-name pattern. +/// +/// # Safety +/// `session` must be a live session handle; the string args, if +/// non-null, must be NUL-terminated C strings; `out` must be writable. #[no_mangle] pub unsafe extern "C" fn kernel_metadata_list_schemas( session: *mut kernel_session_t, catalog: *const c_char, schema_pattern: *const c_char, - out: *mut *mut super::result::kernel_result_stream_t, + out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { - unimplemented!("PR 7d") + run_metadata(session, out, |session| { + Box::pin(async move { + let catalog = opt_ident(catalog, "catalog")?; + let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; + session + .metadata() + .list_schemas(catalog, schema_pattern) + .await + }) + }) } +/// List tables filtered by catalog (exact), schema / table patterns, +/// and an optional comma-separated `table_types` filter. +/// +/// # Safety +/// `session` must be a live session handle; the string args, if +/// non-null, must be NUL-terminated C strings; `out` must be writable. #[no_mangle] pub unsafe extern "C" fn kernel_metadata_list_tables( session: *mut kernel_session_t, catalog: *const c_char, - schema: *const c_char, + schema_pattern: *const c_char, table_pattern: *const c_char, table_types_csv: *const c_char, - out: *mut *mut super::result::kernel_result_stream_t, + out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { - unimplemented!("PR 7d") + run_metadata(session, out, |session| { + Box::pin(async move { + let catalog = opt_ident(catalog, "catalog")?; + let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; + let table_pattern = opt_pattern(table_pattern, "table_pattern")?; + // Split the comma-separated table types into a borrowed slice. + let types_csv = opt_str(table_types_csv, "table_types")?; + let types_owned: Option> = types_csv.map(|csv| { + csv.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect() + }); + session + .metadata() + .list_tables( + catalog, + schema_pattern, + table_pattern, + types_owned.as_deref(), + ) + .await + }) + }) } +/// List columns filtered by catalog (exact) and schema / table / column +/// patterns. +/// +/// # Safety +/// `session` must be a live session handle; the string args, if +/// non-null, must be NUL-terminated C strings; `out` must be writable. #[no_mangle] pub unsafe extern "C" fn kernel_metadata_list_columns( session: *mut kernel_session_t, catalog: *const c_char, - schema: *const c_char, - table: *const c_char, + schema_pattern: *const c_char, + table_pattern: *const c_char, column_pattern: *const c_char, - out: *mut *mut super::result::kernel_result_stream_t, + out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { - unimplemented!("PR 7d") + run_metadata(session, out, |session| { + Box::pin(async move { + let catalog = opt_ident(catalog, "catalog")?; + let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; + let table_pattern = opt_pattern(table_pattern, "table_pattern")?; + let column_pattern = opt_pattern(column_pattern, "column_pattern")?; + session + .metadata() + .list_columns(catalog, schema_pattern, table_pattern, column_pattern) + .await + }) + }) } +/// Primary keys for an exactly-named table. +/// +/// # Safety +/// `session` must be a live session handle; `table` must be a +/// NUL-terminated C string; `catalog` / `schema`, if non-null, must be +/// NUL-terminated C strings; `out` must be writable. #[no_mangle] pub unsafe extern "C" fn kernel_metadata_primary_keys( session: *mut kernel_session_t, catalog: *const c_char, schema: *const c_char, table: *const c_char, - out: *mut *mut super::result::kernel_result_stream_t, + out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { - unimplemented!("PR 7d") + run_metadata(session, out, |session| { + Box::pin(async move { + let catalog = opt_ident(catalog, "catalog")?; + let schema = opt_ident(schema, "schema")?; + let table = Identifier::new(req_str(table, "table")?)?; + session + .metadata() + .primary_keys(catalog, schema, table) + .await + }) + }) +} + +/// Foreign keys. Mirrors ODBC `SQLForeignKeys`: the `parent_*` triple is +/// the referenced (primary-key) table, the `foreign_*` triple the +/// referencing table. The kernel requires the `foreign_*` triple (the +/// referencing table) to be fully specified; the `parent_*` triple is +/// optional and filters the referenced side. +/// +/// # Safety +/// `session` must be a live session handle; the identifier args, if +/// non-null, must be NUL-terminated C strings; `out` must be writable. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn kernel_metadata_foreign_keys( + session: *mut kernel_session_t, + parent_catalog: *const c_char, + parent_schema: *const c_char, + parent_table: *const c_char, + foreign_catalog: *const c_char, + foreign_schema: *const c_char, + foreign_table: *const c_char, + out: *mut *mut kernel_result_stream_t, +) -> KernelStatusCode { + run_metadata(session, out, |session| { + Box::pin(async move { + let parent_catalog = opt_ident(parent_catalog, "parent_catalog")?; + let parent_schema = opt_ident(parent_schema, "parent_schema")?; + let parent_table = opt_ident(parent_table, "parent_table")?; + let foreign_catalog = opt_ident(foreign_catalog, "foreign_catalog")?; + let foreign_schema = opt_ident(foreign_schema, "foreign_schema")?; + let foreign_table = opt_ident(foreign_table, "foreign_table")?; + session + .metadata() + .foreign_keys( + parent_catalog, + parent_schema, + parent_table, + foreign_catalog, + foreign_schema, + foreign_table, + ) + .await + }) + }) +} + +/// Store an `InvalidArgument` for a null pointer and return its code. +fn store_null(msg: &str) -> KernelStatusCode { + crate::ffi::error::store_error(Error::invalid_argument().message(msg)); + KernelStatusCode::InvalidArgument } -// PR 7d: foreign_keys, functions, procedures, type_info, table_types +// PR 7d follow-ups: functions, procedures, type_info, table_types — the +// kernel `Metadata` exposes these (some synthesised in-memory). Wire them +// over the C ABI when an ODBC / Go consumer needs SQLGetTypeInfo / +// SQLProcedures. diff --git a/src/ffi/mod.rs b/src/ffi/mod.rs index 5d0bb7c0..95f2be71 100644 --- a/src/ffi/mod.rs +++ b/src/ffi/mod.rs @@ -21,11 +21,9 @@ //! for `Session`, `Statement`, `ExecutedStatement`, //! `ExecutedAsyncStatement`, and `ResultStream`. -#![allow(dead_code, unused_variables)] -// Skeleton: each function will get its `# Safety` doc when its body -// lands in PRs 7a–7d. Suppress the lint at the module root for now so -// reviewers can read the signatures without 31 lint markers. -#![allow(clippy::missing_safety_doc)] +// Each `extern "C"` function carries its own `# Safety` section; the +// module-wide allow that masked them in the skeleton phase is gone now +// that bodies have landed. pub mod error; pub mod metadata; @@ -33,6 +31,109 @@ pub mod result; pub mod session; pub mod statement; +use std::sync::OnceLock; + +/// Process-wide tokio runtime owned by the C ABI. +/// +/// Rust-crate consumers (PyO3 / napi-rs) own their own runtime and call +/// the async surface directly; the C ABI has no caller-owned runtime to +/// borrow, so it owns one here and `block_on`s every entry point through +/// it. Initialised lazily on the first `kernel_session_open` and shared +/// by every session for the life of the process (matches the +/// migration-plan §5.2 contract). +static RUNTIME: OnceLock = OnceLock::new(); + +/// Fetch (initialising on first use) the process-wide C-ABI runtime. +/// +/// A multi-thread runtime so concurrent FFI calls from different host +/// threads (e.g. an ODBC app issuing queries on several connections) +/// don't serialise behind a single worker. Returns an [`Error`] tagged +/// `Internal` if the runtime fails to build — the only failure mode is +/// the OS refusing to spawn worker threads, which is fatal and not +/// retryable. +/// +/// [`Error`]: crate::kernel_error::Error +pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime::Runtime> { + // `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. + if let Some(rt) = RUNTIME.get() { + return Ok(rt); + } + let built = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_name("kernel-c-abi") + .build() + .map_err(|e| { + crate::kernel_error::Error::internal() + .message(format!("failed to build the C-ABI tokio runtime: {e}")) + .location(concat!(file!(), ":", line!())) + })?; + // If another thread installed one between our `get` and here, keep + // theirs and drop ours. + let _ = RUNTIME.set(built); + Ok(RUNTIME.get().expect("runtime just set")) +} + +/// Run a fallible async block to completion on the process-wide runtime, +/// translating the outcome into a [`KernelStatusCode`] and storing the +/// typed [`Error`] in the thread-local last-error buffer on failure. +/// +/// Every `extern "C"` entry point that drives async work funnels through +/// here so the runtime-fetch, `block_on`, error-store, and status-map +/// steps stay in exactly one place. A panic inside the future is caught +/// at the `block_on` edge and surfaced as `Internal` rather than +/// unwinding across the FFI boundary (which is UB). +/// +/// [`KernelStatusCode`]: crate::ffi::KernelStatusCode +/// [`Error`]: crate::kernel_error::Error +pub(crate) fn block_on_ffi(fut_builder: F) -> Result +where + F: FnOnce() -> Fut, + Fut: std::future::Future>, +{ + error::clear_error(); + let rt = match runtime() { + Ok(rt) => rt, + Err(e) => { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + return Err(code); + } + }; + // Catch panics so a kernel bug can't unwind across `extern "C"`. + let result = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rt.block_on(fut_builder()))); + match result { + Ok(Ok(value)) => Ok(value), + Ok(Err(e)) => { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + Err(code) + } + Err(panic) => { + let detail = panic_message(&panic); + let e = crate::kernel_error::Error::internal() + .message(format!("panic in kernel C ABI: {detail}")) + .location(concat!(file!(), ":", line!())); + error::store_error(e); + Err(KernelStatusCode::Internal) + } + } +} + +/// Best-effort extraction of a human-readable message from a caught +/// panic payload. +fn panic_message(panic: &Box) -> String { + if let Some(s) = panic.downcast_ref::<&str>() { + (*s).to_string() + } else if let Some(s) = panic.downcast_ref::() { + s.clone() + } else { + "".to_string() + } +} + /// Status enum returned by every C entry point. /// /// Variants parallel [`crate::kernel_error::ErrorCode`] one-to-one. The diff --git a/src/ffi/result.rs b/src/ffi/result.rs index ade2b877..8adb9b9d 100644 --- a/src/ffi/result.rs +++ b/src/ffi/result.rs @@ -12,62 +12,226 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Result FFI — exports `ResultStream` via the Arrow C Data Interface. +//! Result FFI — exports a result stream via the Arrow C Data Interface. //! //! `kernel_result_stream_get_schema` / `kernel_result_stream_next_batch` -//! return `FFI_ArrowSchema` / `FFI_ArrowArray` so any C consumer with an -//! Arrow C Data Interface implementation can iterate. PR 7c implements -//! the actual export plumbing using the `arrow` crate's `ffi` feature. +//! hand back `FFI_ArrowSchema` / `FFI_ArrowArray` (the Arrow C Data +//! Interface) so any C consumer with an Arrow C Data Interface +//! implementation can iterate. The kernel yields **one array per +//! `next_batch` call** (a pull model); consumers that want a +//! self-contained `ArrowArrayStream` wrap this surface on their side. +//! +//! 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. +//! - **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 +//! keep working; the caller must keep the executed handle alive until +//! the stream is closed. -#![allow(dead_code, unused_variables, non_camel_case_types)] +#![allow(non_camel_case_types)] use super::KernelStatusCode; +use crate::kernel_error::Error; +use crate::result_stream::{OwnedBatchIter, ResultBatch, SchemaRef}; +use crate::statement::executed::ExecutedStatement; +use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; +use arrow_array::Array; +/// Opaque result-stream handle. Boxed [`ResultStreamInner`]. #[repr(C)] pub struct kernel_result_stream_t { _private: [u8; 0], } -/// Export the schema as an `FFI_ArrowSchema`. The caller releases via -/// the schema's release callback. +/// Backing state for a result-stream handle. +enum ResultStreamInner { + /// Self-contained owned stream (metadata path). + Owned { + schema: SchemaRef, + iter: OwnedBatchIter, + }, + /// Borrow of the executed statement that produced this stream + /// (sync execute path). The pointer is valid as long as the + /// executed handle is — the C consumer must not close the executed + /// handle before closing this stream. + Executed { exec: *mut ExecutedStatement }, +} + +/// Crate-internal: build an owned result-stream handle from a schema and +/// an owned batch iterator (used by the metadata FFI). +pub(crate) fn into_raw_result_stream( + schema: SchemaRef, + iter: OwnedBatchIter, +) -> *mut kernel_result_stream_t { + Box::into_raw(Box::new(ResultStreamInner::Owned { schema, iter })) + as *mut kernel_result_stream_t +} + +/// Crate-internal: build a result-stream handle that borrows from an +/// executed statement (used by the sync execute path). +/// +/// # Safety +/// `exec` must remain valid for the lifetime of the returned stream +/// handle. +pub(crate) unsafe fn into_raw_executed_stream( + exec: *mut ExecutedStatement, +) -> *mut kernel_result_stream_t { + Box::into_raw(Box::new(ResultStreamInner::Executed { exec })) as *mut kernel_result_stream_t +} + +/// Export the schema as an `FFI_ArrowSchema`. +/// +/// On success, `*out` holds an `FFI_ArrowSchema` the caller releases via +/// the schema's own release callback (per the Arrow C Data Interface +/// contract). Safe to call before or between `next_batch` calls. +/// +/// # Safety +/// `stream` must be a live result-stream handle; `out` must be a valid, +/// writable pointer to an `FFI_ArrowSchema`. #[no_mangle] pub unsafe extern "C" fn kernel_result_stream_get_schema( stream: *mut kernel_result_stream_t, - // out: *mut FFI_ArrowSchema, + out: *mut FFI_ArrowSchema, ) -> KernelStatusCode { - unimplemented!("PR 7c: arrow::ffi schema export") + crate::ffi::error::clear_error(); + let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { + return store_null("kernel_result_stream_get_schema: stream must not be null"); + }; + if out.is_null() { + return store_null("kernel_result_stream_get_schema: out must not be null"); + } + let schema = match inner { + ResultStreamInner::Owned { schema, .. } => schema.clone(), + ResultStreamInner::Executed { exec } => { + let Some(exec) = exec.as_ref() else { + return store_null( + "kernel_result_stream_get_schema: backing executed handle is null", + ); + }; + exec.schema() + } + }; + match FFI_ArrowSchema::try_from(schema.as_ref()) { + Ok(ffi_schema) => { + std::ptr::write(out, ffi_schema); + KernelStatusCode::Success + } + Err(e) => store_error(Error::from(e)), + } } -/// Export the next batch as an `FFI_ArrowArray`. Returns -/// `KernelStatusCode::Success` with a released-state array when the stream -/// is exhausted. +/// Export the next batch as an `FFI_ArrowArray` (+ its `FFI_ArrowSchema`). +/// +/// When the stream is exhausted, returns `KernelStatusCode::Success` and +/// writes a **released-state** (empty) array to `*out_array` — the +/// consumer detects end-of-stream by checking `out_array->release == +/// NULL` (the Arrow C Data Interface convention for a released array). +/// +/// # Safety +/// `stream` must be a live result-stream handle; `out_array` and +/// `out_schema` must be valid, writable pointers. #[no_mangle] pub unsafe extern "C" fn kernel_result_stream_next_batch( stream: *mut kernel_result_stream_t, - // out: *mut FFI_ArrowArray, + out_array: *mut FFI_ArrowArray, + out_schema: *mut FFI_ArrowSchema, ) -> KernelStatusCode { - unimplemented!("PR 7c: arrow::ffi array export, drives next_batch()") + crate::ffi::error::clear_error(); + let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { + return store_null("kernel_result_stream_next_batch: stream must not be null"); + }; + if out_array.is_null() || out_schema.is_null() { + return store_null("kernel_result_stream_next_batch: out pointers must not be null"); + } + + // Pull the next owned batch from whichever backing shape this is. + let next = match inner { + ResultStreamInner::Owned { iter, .. } => iter.next(), + ResultStreamInner::Executed { exec } => { + let Some(exec) = exec.as_mut() else { + return store_null( + "kernel_result_stream_next_batch: backing executed handle is null", + ); + }; + // Drive the executed handle's own next_batch so the + // drain-driven auto-close and lazy CloudFetch link fetches + // keep working. Convert the borrowed batch into an owned + // RecordBatch for FFI export. + match super::block_on_ffi(move || { + let exec: &mut ExecutedStatement = exec; + Box::pin(async move { + Ok(exec + .next_batch() + .await? + .map(|ResultBatch::Arrow(rb)| rb.clone())) + }) + }) { + Ok(Some(rb)) => Some(Ok(rb)), + Ok(None) => None, + Err(code) => return code, // error already stored + } + } + }; + + match next { + None => { + // End-of-stream: hand back a released (empty) array. A + // default `FFI_ArrowArray` has a null release callback, + // which the Arrow C Data Interface treats as "released". + std::ptr::write(out_array, FFI_ArrowArray::empty()); + std::ptr::write(out_schema, FFI_ArrowSchema::empty()); + KernelStatusCode::Success + } + Some(Ok(batch)) => { + // A RecordBatch maps to a StructArray for the C Data + // Interface export (the Arrow-canonical batch-as-array form). + let struct_array: arrow_array::StructArray = batch.into(); + match arrow_array::ffi::to_ffi(&struct_array.into_data()) { + Ok((ffi_array, ffi_schema)) => { + std::ptr::write(out_array, ffi_array); + std::ptr::write(out_schema, ffi_schema); + KernelStatusCode::Success + } + Err(e) => store_error(Error::from(e)), + } + } + Some(Err(e)) => store_error(e), + } } -/// Free client-side resources held by the stream — buffered chunks, -/// the link prefetcher, in-flight downloaders. Local-only; does not -/// issue any server-side RPC. To cancel the underlying statement, -/// call `kernel_executed_statement_cancel` / -/// `kernel_executed_async_statement_cancel` on the executed handle -/// that produced the stream. +/// Free client-side resources held by the stream. Local-only; issues no +/// server RPC. For the **executed** shape this frees only the borrow +/// wrapper, not the executed handle itself (close that separately via +/// `kernel_executed_statement_close`). /// /// # Safety -/// -/// `stream` must have been returned by -/// `kernel_executed_async_statement_await_result` / -/// `kernel_executed_async_statement_fetch_result` and not previously -/// closed (or borrowed via `kernel_executed_statement_get_result_stream`, -/// in which case the executed handle owns the stream and frees it on -/// its own `_close`). After this call, `stream` is invalid; passing -/// it to any other `kernel_*` function is UB. +/// `stream` must have been returned by a `kernel_*` call that produces a +/// result stream and not previously closed. #[no_mangle] pub unsafe extern "C" fn kernel_result_stream_close( stream: *mut kernel_result_stream_t, ) -> KernelStatusCode { - unimplemented!("PR 7c") + crate::ffi::error::clear_error(); + if stream.is_null() { + return store_null("kernel_result_stream_close: stream must not be null"); + } + drop(Box::from_raw(stream as *mut ResultStreamInner)); + KernelStatusCode::Success +} + +/// Store an `InvalidArgument` for a null pointer and return its code. +fn store_null(msg: &str) -> KernelStatusCode { + crate::ffi::error::store_error(Error::invalid_argument().message(msg)); + KernelStatusCode::InvalidArgument +} + +/// Store a typed error and return its mapped status code. +fn store_error(e: Error) -> KernelStatusCode { + let code = KernelStatusCode::from(e.code); + crate::ffi::error::store_error(e); + code } diff --git a/src/ffi/session.rs b/src/ffi/session.rs index 63a0388e..78d00aff 100644 --- a/src/ffi/session.rs +++ b/src/ffi/session.rs @@ -12,72 +12,410 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Session FFI — open / close / new_statement. +//! 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). //! //! Transaction methods (autocommit / commit / rollback) are deferred to //! v0.1 per `docs/spec-v0.md` addendum A5. -#![allow(dead_code, unused_variables)] - -use super::KernelStatusCode; +use super::{block_on_ffi, KernelStatusCode}; +use crate::config::{AuthConfig, ConnectionConfig}; +use crate::kernel_error::Error; +use crate::session::Session; +use std::collections::HashMap; +use std::ffi::{c_char, CStr}; -/// Opaque session handle. Boxed `Session` on the Rust side. +/// Opaque session handle. Boxed [`Session`] on the Rust side. #[repr(C)] pub struct kernel_session_t { _private: [u8; 0], } -/// C-side session config. Opaque `#[non_exhaustive]` so the layout is -/// stable for forward declarations even though PR 7a populates the -/// fields. Same skeleton property as `kernel_session_t`: C consumers -/// can declare a `KernelSessionConfig*` against this header today; -/// constructors / setters land in PR 7a (`kernel_session_config_new`, -/// `kernel_session_config_set_host`, etc.). +/// How the caller chose to identify the warehouse. +enum ConnectionSpec { + /// `host` + bare `warehouse_id`. + HostWarehouse { host: String, warehouse_id: String }, + /// `host` + JDBC-style `http_path` (parsed for warehouse + org id). + HttpPath { host: String, http_path: String }, +} + +/// Auth choice captured from the C-side setters. v0 C ABI wires PAT and +/// OAuth M2M; other [`AuthConfig`] variants stay Rust-crate-only. +enum AuthSpec { + Pat { + token: String, + }, + OAuthM2M { + client_id: String, + client_secret: String, + }, +} + +/// C-side session config builder state. +/// +/// Constructed by [`kernel_session_config_new`], populated by the +/// `kernel_session_config_set_*` setters, and consumed by +/// [`kernel_session_open`]. Heap-boxed; the C side holds a +/// `*mut KernelSessionConfig` and never sees the field layout — the +/// struct stays effectively opaque to C even though it carries real +/// fields on the Rust side. +/// +/// The `version` field leads the struct per the C-ABI versioning +/// convention (every public struct carries a `uint32_t version` so a +/// future reader can detect older callers); it is set by +/// `kernel_session_config_new` and not exposed to setters. #[repr(C)] -#[non_exhaustive] pub struct KernelSessionConfig { - _private: [u8; 0], + /// ABI version tag. `1` for v0. + version: u32, + connection: Option, + auth: Option, + session_conf: HashMap, } -/// Open a session from a `repr(C)` config struct. +const KERNEL_SESSION_CONFIG_VERSION: u32 = 1; + +/// Read a required C string argument into an owned `String`, mapping a +/// null or non-UTF-8 pointer to a typed `InvalidArgument` error. /// -/// PR 7a finalizes the config struct fields and the -/// `kernel_session_config_*` constructor surface. On success, `*out` -/// holds an owned handle the caller releases with `kernel_session_close`. +/// # Safety +/// `ptr`, if non-null, must point to a NUL-terminated C string valid +/// for the duration of the call. +unsafe fn required_str(ptr: *const c_char, what: &str) -> Result { + if ptr.is_null() { + return Err(Error::invalid_argument().message(format!("{what} must not be null"))); + } + CStr::from_ptr(ptr) + .to_str() + .map(|s| s.to_owned()) + .map_err(|_| Error::invalid_argument().message(format!("{what} is not valid UTF-8"))) +} + +/// Allocate a fresh, empty session config. Returns +/// `KernelStatusCode::Success` and writes an owned `*mut +/// KernelSessionConfig` to `*out` that the caller frees via +/// [`kernel_session_config_free`] (or hands to [`kernel_session_open`], +/// which consumes and frees it). /// /// # Safety -/// `config` must point to a valid `KernelSessionConfig` produced by -/// `kernel_session_config_new`; `out` must be writable. +/// `out` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_new( + out: *mut *mut KernelSessionConfig, +) -> KernelStatusCode { + crate::ffi::error::clear_error(); + if out.is_null() { + crate::ffi::error::store_error( + Error::invalid_argument().message("kernel_session_config_new: out must not be null"), + ); + return KernelStatusCode::InvalidArgument; + } + let config = Box::new(KernelSessionConfig { + version: KERNEL_SESSION_CONFIG_VERSION, + connection: None, + auth: None, + session_conf: HashMap::new(), + }); + std::ptr::write(out, Box::into_raw(config)); + KernelStatusCode::Success +} + +/// Free a session config without opening a session. Only needed if the +/// caller allocated a config but never passed it to +/// [`kernel_session_open`] (which consumes the config). +/// +/// # Safety +/// `config` must have been returned by [`kernel_session_config_new`] and +/// not previously freed or consumed by [`kernel_session_open`]. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_free(config: *mut KernelSessionConfig) { + if !config.is_null() { + drop(Box::from_raw(config)); + } +} + +/// Set the workspace host and bare warehouse id. Mutually exclusive with +/// [`kernel_session_config_set_http_path`] — the last one called wins. +/// +/// # Safety +/// `config` must be a live config handle; `host` / `warehouse_id` must +/// be NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_warehouse( + config: *mut KernelSessionConfig, + host: *const c_char, + warehouse_id: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.connection = Some(ConnectionSpec::HostWarehouse { + host: required_str(host, "host")?, + warehouse_id: required_str(warehouse_id, "warehouse_id")?, + }); + Ok(()) + }) +} + +/// Set the workspace host and a JDBC-style HTTP path +/// (`/sql/1.0/warehouses/{id}` with an optional `?o={org_id}`). +/// Mutually exclusive with [`kernel_session_config_set_warehouse`] — the +/// last one called wins. The path is parsed at [`kernel_session_open`] +/// so a malformed path surfaces there as `InvalidArgument`. +/// +/// # Safety +/// `config` must be a live config handle; `host` / `http_path` must be +/// NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_http_path( + config: *mut KernelSessionConfig, + host: *const c_char, + http_path: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.connection = Some(ConnectionSpec::HttpPath { + host: required_str(host, "host")?, + http_path: required_str(http_path, "http_path")?, + }); + Ok(()) + }) +} + +/// Set PAT (personal access token) authentication. Mutually exclusive +/// with [`kernel_session_config_set_auth_m2m`] — the last one called +/// wins. +/// +/// # Safety +/// `config` must be a live config handle; `token` must be a +/// NUL-terminated C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_auth_pat( + config: *mut KernelSessionConfig, + token: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.auth = Some(AuthSpec::Pat { + token: required_str(token, "token")?, + }); + Ok(()) + }) +} + +/// Set OAuth M2M (client-credentials / service-principal) +/// authentication. Mutually exclusive with +/// [`kernel_session_config_set_auth_pat`] — the last one called wins. +/// +/// # Safety +/// `config` must be a live config handle; `client_id` / `client_secret` +/// must be NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_auth_m2m( + config: *mut KernelSessionConfig, + client_id: *const c_char, + client_secret: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.auth = Some(AuthSpec::OAuthM2M { + client_id: required_str(client_id, "client_id")?, + client_secret: required_str(client_secret, "client_secret")?, + }); + Ok(()) + }) +} + +/// 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. +/// +/// # Safety +/// `config` must be a live config handle; `key` / `value` must be +/// NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_session_conf( + config: *mut KernelSessionConfig, + key: *const c_char, + value: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + let key = required_str(key, "session_conf key")?; + let value = required_str(value, "session_conf value")?; + c.session_conf.insert(key, value); + Ok(()) + }) +} + +/// Shared body for the config setters: null-check the handle, clear the +/// thread-local error, run `f` against the borrowed config, and store +/// any error. +/// +/// # Safety +/// `config` must be a live `*mut KernelSessionConfig`. +unsafe fn set_on_config( + config: *mut KernelSessionConfig, + f: impl FnOnce(&mut KernelSessionConfig) -> Result<(), Error>, +) -> KernelStatusCode { + crate::ffi::error::clear_error(); + let Some(config) = config.as_mut() else { + crate::ffi::error::store_error( + Error::invalid_argument().message("config handle must not be null"), + ); + return KernelStatusCode::InvalidArgument; + }; + match f(config) { + Ok(()) => KernelStatusCode::Success, + Err(e) => { + let code = KernelStatusCode::from(e.code); + crate::ffi::error::store_error(e); + code + } + } +} + +/// Open a session from a config produced by the +/// `kernel_session_config_*` surface. +/// +/// **Consumes `config`**: on both success and failure the config box is +/// freed before returning, so the caller must not use or free `config` +/// afterwards. On success, `*out` holds an owned session handle the +/// caller releases with [`kernel_session_close`]. +/// +/// # Safety +/// `config` must have been returned by [`kernel_session_config_new`] and +/// not previously freed or consumed. `out` must be a valid, writable +/// pointer. #[no_mangle] pub unsafe extern "C" fn kernel_session_open( - config: *const KernelSessionConfig, + config: *mut KernelSessionConfig, out: *mut *mut kernel_session_t, ) -> KernelStatusCode { - unimplemented!("PR 7a: marshal config, block_on Session::open") + crate::ffi::error::clear_error(); + if config.is_null() || out.is_null() { + crate::ffi::error::store_error( + Error::invalid_argument() + .message("kernel_session_open: config and out must be non-null"), + ); + return KernelStatusCode::InvalidArgument; + } + // Take ownership of the config box; it is dropped at end of scope on + // every path, so the caller never frees it. + let config = Box::from_raw(config); + + let session = match build_session(*config) { + Ok(s) => s, + Err(code) => return code, // error already stored by build_session + }; + + std::ptr::write( + out, + Box::into_raw(Box::new(session)) as *mut kernel_session_t, + ); + KernelStatusCode::Success +} + +/// 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 +/// code. +fn build_session(config: KernelSessionConfig) -> Result { + let KernelSessionConfig { + version: _, + connection, + auth, + session_conf, + } = config; + + block_on_ffi(move || { + Box::pin(async move { + let connection = connection.ok_or_else(|| { + Error::invalid_argument().message( + "session config requires a connection \ + (set_warehouse or set_http_path)", + ) + })?; + let auth = auth.ok_or_else(|| { + Error::invalid_argument() + .message("session config requires auth (set_auth_pat or set_auth_m2m)") + })?; + + let connection = match connection { + ConnectionSpec::HostWarehouse { host, warehouse_id } => { + ConnectionConfig::new(host, warehouse_id) + } + ConnectionSpec::HttpPath { host, http_path } => { + ConnectionConfig::from_http_path(host, &http_path)? + } + }; + + let auth = match auth { + AuthSpec::Pat { token } => AuthConfig::pat(Some(token))?, + AuthSpec::OAuthM2M { + client_id, + client_secret, + } => AuthConfig::oauth_m2m(Some(client_id), Some(client_secret), None, None)?, + }; + + Session::builder() + .connection(connection) + .auth(auth) + .session_conf(session_conf) + .open() + .await + }) + }) } -/// Close a session. Releases the underlying Rust `Session`. +/// Close a session. Releases the underlying Rust [`Session`] (which +/// fires `DeleteSession` server-side on drop / explicit close). /// /// # Safety /// -/// `session` must have been returned by `kernel_session_open` and not -/// previously closed. After this call, `session` is invalid; passing -/// it to any other `kernel_*` function is UB. +/// `session` must have been returned by [`kernel_session_open`] and not +/// previously closed. After this call, `session` is invalid; passing it +/// to any other `kernel_*` function is UB. #[no_mangle] pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> KernelStatusCode { - unimplemented!("PR 7a: drop the boxed Session") + crate::ffi::error::clear_error(); + if session.is_null() { + crate::ffi::error::store_error( + Error::invalid_argument().message("kernel_session_close: session must not be null"), + ); + 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)); + KernelStatusCode::Success } -/// Construct a new mutable statement bound to this session. Returns a -/// borrowed pointer; the statement's lifetime is bound to the session. +/// 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`. /// -/// Caller releases with `kernel_statement_close`. +/// # Safety +/// `session` must be a live session handle; `out` must be writable. #[no_mangle] pub unsafe extern "C" fn kernel_session_new_statement( session: *mut kernel_session_t, out: *mut *mut super::statement::kernel_statement_t, ) -> KernelStatusCode { - unimplemented!("PR 7b") + crate::ffi::error::clear_error(); + if session.is_null() || out.is_null() { + crate::ffi::error::store_error( + Error::invalid_argument() + .message("kernel_session_new_statement: session and out must be non-null"), + ); + return KernelStatusCode::InvalidArgument; + } + let session = &*(session as *const Session); + let statement = session.statement(); + std::ptr::write(out, super::statement::into_raw_statement(statement)); + KernelStatusCode::Success } // Deferred to v0.1 (see addendum A5): diff --git a/src/ffi/statement.rs b/src/ffi/statement.rs index 88ef9468..6be0d965 100644 --- a/src/ffi/statement.rs +++ b/src/ffi/statement.rs @@ -12,48 +12,55 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Statement FFI — four opaque handle types per `docs/spec-v0.md` -//! addendum A1. +//! Statement FFI — set sql, bind params, execute, and fetch results. +//! +//! ## Scope in v0 +//! +//! The C ABI wires the **synchronous** execute path +//! (`kernel_statement_execute` → `kernel_executed_statement_t` → +//! `kernel_result_stream_t`), which is what the ODBC consumer needs. The +//! **async** submit path (`kernel_statement_submit` + +//! `kernel_executed_async_statement_*`) keeps its skeleton declarations +//! and `unimplemented!()` bodies until a consumer needs caller-driven +//! polling over the C ABI; Rust-crate consumers use `Statement::submit` +//! directly. //! //! ## Error reporting convention //! //! Every function returns [`KernelStatusCode`]. On any non-`Success` //! return, the consumer calls [`crate::ffi::error::kernel_get_last_error`] //! to populate a [`crate::ffi::error::KernelError`] with the typed -//! detail (sql_state, vendor_code, retryable, query_id, …). The -//! thread-local error buffer is reset at the start of every FFI -//! function. +//! detail. The thread-local error buffer is reset at the start of every +//! FFI function. -#![allow(dead_code, unused_variables, non_camel_case_types)] +#![allow(non_camel_case_types)] -use super::KernelStatusCode; -use std::ffi::c_char; +use super::result::{into_raw_executed_stream, kernel_result_stream_t}; +use super::{block_on_ffi, KernelStatusCode}; +use crate::kernel_error::Error; +use crate::statement::executed::ExecutedStatement; +use crate::statement::mutable::Statement; +use crate::statement::spec::TypedValue; +use std::ffi::{c_char, CStr}; // ─── Opaque handles ────────────────────────────────────────────────────────── -/// Plain-data spec (sql, params, conf, result format). Constructible -/// without a session; useful for caller-side spec building. -#[repr(C)] -pub struct kernel_statement_spec_t { - _private: [u8; 0], -} - -/// Lifecycle owner. Returned by `kernel_session_new_statement`. Owns -/// one `kernel_statement_spec_t` and at most one live executed handle. +/// Lifecycle owner. Returned by `kernel_session_new_statement`. Boxed +/// [`Statement`] on the Rust side. #[repr(C)] pub struct kernel_statement_t { _private: [u8; 0], } /// Sync-consumption executed handle. Returned by -/// `kernel_statement_execute`. +/// [`kernel_statement_execute`]. Boxed [`ExecutedStatement`]. #[repr(C)] pub struct kernel_executed_statement_t { _private: [u8; 0], } /// Async-consumption executed handle. Returned by -/// `kernel_statement_submit`. +/// `kernel_statement_submit` (deferred in v0 — see module docs). #[repr(C)] pub struct kernel_executed_async_statement_t { _private: [u8; 0], @@ -62,14 +69,8 @@ pub struct kernel_executed_async_statement_t { /// Server-side execution status — C-side mirror of /// [`crate::statement::executed_async::StatementStatus`]. /// -/// The Rust-side `StatementStatus::Failed(Error)` carries an `Error` -/// payload that cannot be encoded as a scalar enum. The C ABI -/// flattens to the kind tag here; on `Failed`, the consumer calls -/// [`crate::ffi::error::kernel_get_last_error`] to retrieve the -/// detail. -/// -/// `#[repr(C)]` with explicit discriminants so wrappers can declare -/// the enum verbatim in their generated bindings. +/// `#[repr(C)]` with explicit discriminants so wrappers can declare the +/// enum verbatim in their generated bindings. #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum KernelStatementStatusKind { @@ -77,226 +78,317 @@ pub enum KernelStatementStatusKind { Running = 1, Succeeded = 2, /// Server-side execution failed. Call `kernel_get_last_error` for - /// the underlying `KernelError` (sql_state, vendor_code, …). + /// the underlying `KernelError`. Failed = 3, Cancelled = 4, Closed = 5, } -// ─── Spec setters ──────────────────────────────────────────────────────────── +// ─── Crate-internal raw-handle helpers ─────────────────────────────────────── -#[no_mangle] -pub unsafe extern "C" fn kernel_statement_spec_new( - out: *mut *mut kernel_statement_spec_t, -) -> KernelStatusCode { - unimplemented!("PR 7b: alloc StatementSpec, return owned ptr") +/// Box a [`Statement`] and erase it to the opaque C handle type. +pub(crate) fn into_raw_statement(stmt: Statement) -> *mut kernel_statement_t { + Box::into_raw(Box::new(stmt)) as *mut kernel_statement_t } -/// Free a `kernel_statement_spec_t`. +/// Borrow the boxed [`Statement`] behind a handle, mutably. /// /// # Safety +/// `stmt` must be a live handle from `kernel_session_new_statement`. +unsafe fn statement_mut<'a>(stmt: *mut kernel_statement_t) -> Option<&'a mut Statement> { + (stmt as *mut Statement).as_mut() +} + +// ─── SQL + parameter binding ───────────────────────────────────────────────── + +/// Set the statement's SQL text, replacing any previously set SQL. /// -/// `spec` must have been returned by `kernel_statement_spec_new` and -/// not previously freed. After this call, `spec` is invalid; passing -/// it to any other `kernel_*` function is UB. +/// # Safety +/// `stmt` must be a live statement handle; `sql` must be a +/// NUL-terminated C string. #[no_mangle] -pub unsafe extern "C" fn kernel_statement_spec_free( - spec: *mut kernel_statement_spec_t, +pub unsafe extern "C" fn kernel_statement_set_sql( + stmt: *mut kernel_statement_t, + sql: *const c_char, ) -> KernelStatusCode { - unimplemented!("PR 7b") + with_statement(stmt, |stmt| { + if sql.is_null() { + return Err(Error::invalid_argument().message("sql must not be null")); + } + let sql = CStr::from_ptr(sql) + .to_str() + .map_err(|_| Error::invalid_argument().message("sql is not valid UTF-8"))?; + stmt.spec().sql(sql); + Ok(()) + }) } +/// Bind a 1-based positional parameter to a NULL value. +/// +/// # Safety +/// `stmt` must be a live statement handle. #[no_mangle] -pub unsafe extern "C" fn kernel_statement_spec_set_sql( - spec: *mut kernel_statement_spec_t, - sql: *const c_char, +pub unsafe extern "C" fn kernel_statement_bind_null( + stmt: *mut kernel_statement_t, + ordinal: usize, ) -> KernelStatusCode { - unimplemented!("PR 7b") + bind_positional(stmt, ordinal, TypedValue::Null) } -// PR 7b: bind_param, bind_param_named, set_statement_conf, set_result_format - -// ─── Statement (lifecycle owner) ───────────────────────────────────────────── - -/// Borrow the statement's spec. Mutating the returned spec mutates -/// the statement's spec in place. +/// Bind a 1-based positional `BIGINT` parameter. /// -/// **Lifetime:** the returned pointer is valid as long as `stmt` is. -/// Do not pass it to `kernel_statement_spec_free` — it is borrowed, -/// not owned. +/// # Safety +/// `stmt` must be a live statement handle. #[no_mangle] -pub unsafe extern "C" fn kernel_statement_get_spec( +pub unsafe extern "C" fn kernel_statement_bind_int64( stmt: *mut kernel_statement_t, - out: *mut *mut kernel_statement_spec_t, + ordinal: usize, + value: i64, ) -> KernelStatusCode { - unimplemented!("PR 7b: return &mut self.spec via raw ptr") + bind_positional(stmt, ordinal, TypedValue::Int64(value)) } -/// Wait-for-result execution. Auto-cancels + closes any prior -/// executed handle from this statement. On success, `*out` holds an -/// owned `kernel_executed_statement_t` the caller releases with -/// `kernel_executed_statement_close`. +/// Bind a 1-based positional `DOUBLE` parameter. +/// +/// # Safety +/// `stmt` must be a live statement handle. #[no_mangle] -pub unsafe extern "C" fn kernel_statement_execute( +pub unsafe extern "C" fn kernel_statement_bind_double( stmt: *mut kernel_statement_t, - out: *mut *mut kernel_executed_statement_t, + ordinal: usize, + value: f64, ) -> KernelStatusCode { - unimplemented!("PR 7b: block_on Statement::execute") + bind_positional(stmt, ordinal, TypedValue::Float64(value)) } -/// Submit-and-return. Same auto-cancel-and-close semantics. On -/// success, `*out` holds an owned -/// `kernel_executed_async_statement_t` the caller releases with -/// `kernel_executed_async_statement_close`. +/// Bind a 1-based positional `BOOLEAN` parameter. +/// +/// # Safety +/// `stmt` must be a live statement handle. #[no_mangle] -pub unsafe extern "C" fn kernel_statement_submit( +pub unsafe extern "C" fn kernel_statement_bind_bool( stmt: *mut kernel_statement_t, - out: *mut *mut kernel_executed_async_statement_t, + ordinal: usize, + value: bool, ) -> KernelStatusCode { - unimplemented!("PR 7b: block_on Statement::submit") + bind_positional(stmt, ordinal, TypedValue::Bool(value)) } -/// Free the lifecycle owner. +/// Bind a 1-based positional `STRING` parameter. /// -/// **Non-destructive for executed-handle pointers.** If a previously -/// returned `kernel_executed_statement_t` or -/// `kernel_executed_async_statement_t` from this statement is still -/// held by the caller, that pointer **remains safe to call** after -/// this function returns: subsequent calls dispatch through the -/// shared validity flag and return `KernelStatusCode::InvalidStatementHandle` -/// (no network round-trip). The caller is still responsible for -/// freeing each executed-handle pointer via the corresponding -/// `kernel_executed_*_close` function. +/// # Safety +/// `stmt` must be a live statement handle; `value` must be a +/// NUL-terminated C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_bind_string( + stmt: *mut kernel_statement_t, + ordinal: usize, + value: *const c_char, +) -> KernelStatusCode { + with_statement(stmt, |stmt| { + if value.is_null() { + return Err( + Error::invalid_argument().message("string parameter value must not be null") + ); + } + let value = CStr::from_ptr(value).to_str().map_err(|_| { + Error::invalid_argument().message("string parameter is not valid UTF-8") + })?; + stmt.spec() + .param(ordinal, TypedValue::String(value.to_owned()))?; + Ok(()) + }) +} + +/// Shared body for the scalar `bind_*` setters. /// -/// Net effect: this function frees only the statement-lifecycle box -/// and flips the validity flag. It does *not* free executed-handle -/// boxes — those live independently with their own refcounts. +/// # Safety +/// `stmt` must be a live statement handle. +unsafe fn bind_positional( + stmt: *mut kernel_statement_t, + ordinal: usize, + value: TypedValue, +) -> KernelStatusCode { + with_statement(stmt, |stmt| { + stmt.spec().param(ordinal, value)?; + Ok(()) + }) +} + +// ─── Execute (sync) ────────────────────────────────────────────────────────── + +/// Wait-for-result execution. Auto-cancels + closes any prior executed +/// handle from this statement. On success, `*out` holds an owned +/// `kernel_executed_statement_t` the caller releases with +/// [`kernel_executed_statement_close`]. /// /// # Safety +/// `stmt` must be a live statement handle; `out` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_execute( + stmt: *mut kernel_statement_t, + out: *mut *mut kernel_executed_statement_t, +) -> KernelStatusCode { + crate::ffi::error::clear_error(); + let Some(stmt) = statement_mut(stmt) else { + return store_null_handle("kernel_statement_execute: stmt must not be null"); + }; + if out.is_null() { + return store_null_handle("kernel_statement_execute: out must not be null"); + } + + // `Statement::execute` borrows `&mut self`; we need that borrow to + // live across the `block_on`. Raw-pointer the statement so the + // closure can re-borrow it inside the runtime without entangling + // lifetimes with `block_on_ffi`'s `'static` future bound. + let stmt_ptr: *mut Statement = stmt; + let executed = block_on_ffi(move || { + let stmt: &mut Statement = unsafe { &mut *stmt_ptr }; + Box::pin(async move { stmt.execute().await }) + }); + match executed { + Ok(executed) => { + std::ptr::write( + out, + Box::into_raw(Box::new(executed)) as *mut kernel_executed_statement_t, + ); + KernelStatusCode::Success + } + Err(code) => code, + } +} + +/// Free the statement-lifecycle owner. Does not free executed-handle +/// boxes (those are owned independently); see the spec contract. /// -/// `stmt` must have been returned by `kernel_session_new_statement` -/// and not previously closed. After this call, `stmt` is invalid; -/// passing it to any other `kernel_*` function is UB. +/// # Safety +/// `stmt` must have been returned by `kernel_session_new_statement` and +/// not previously closed. #[no_mangle] pub unsafe extern "C" fn kernel_statement_close(stmt: *mut kernel_statement_t) -> KernelStatusCode { - unimplemented!("PR 7b: flip validity flag, drop the lifecycle owner box") + crate::ffi::error::clear_error(); + if stmt.is_null() { + return store_null_handle("kernel_statement_close: stmt must not be null"); + } + drop(Box::from_raw(stmt as *mut Statement)); + KernelStatusCode::Success } // ─── ExecutedStatement (sync) ──────────────────────────────────────────────── -/// Server-issued statement id, NUL-terminated. +/// Obtain a result-stream handle that **borrows** the sync executed +/// handle. The returned `kernel_result_stream_t` drives the executed +/// handle's own stream, so the executed handle's drain-driven +/// auto-close and lazy CloudFetch link fetches keep working. /// -/// **Lifetime:** the returned pointer is valid as long as `exec` is. -/// Do not free it; do not retain past -/// `kernel_executed_statement_close`. +/// **Lifetime:** the returned stream is valid only as long as `exec` is. +/// The caller must close the stream (`kernel_result_stream_close`) +/// before closing the executed handle (`kernel_executed_statement_close`). /// -/// **On stale handle:** returns `null` if `exec` has been invalidated -/// by a re-execute on the parent statement. Callers should null-check -/// before dereferencing. -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_statement_id( - exec: *const kernel_executed_statement_t, -) -> *const c_char { - unimplemented!("PR 7b") -} - -/// Borrow the result stream. Pointer is valid as long as `exec` is. +/// On success `*out` holds the stream handle. +/// +/// # Safety +/// `exec` must be a live executed handle; `out` must be writable. #[no_mangle] pub unsafe extern "C" fn kernel_executed_statement_get_result_stream( exec: *mut kernel_executed_statement_t, - out: *mut *mut super::result::kernel_result_stream_t, + out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { - unimplemented!("PR 7b") + crate::ffi::error::clear_error(); + if exec.is_null() { + return store_null_handle("get_result_stream: exec must not be null"); + } + if out.is_null() { + return store_null_handle("get_result_stream: out must not be null"); + } + let exec_ptr = exec as *mut ExecutedStatement; + std::ptr::write(out, into_raw_executed_stream(exec_ptr)); + KernelStatusCode::Success } +/// Number of rows modified by a DML statement, or `-1` if not +/// applicable / unknown. +/// +/// # Safety +/// `exec` must be a live executed handle. #[no_mangle] -pub unsafe extern "C" fn kernel_executed_statement_cancel( - exec: *mut kernel_executed_statement_t, -) -> KernelStatusCode { - unimplemented!("PR 7b") +pub unsafe extern "C" fn kernel_executed_statement_num_modified_rows( + exec: *const kernel_executed_statement_t, +) -> i64 { + let Some(exec) = (exec as *const ExecutedStatement).as_ref() else { + return -1; + }; + exec.num_modified_rows().unwrap_or(-1) } /// Free a sync executed handle. /// /// # Safety -/// -/// `exec` must have been returned by `kernel_statement_execute` and -/// not previously closed. After this call, `exec` is invalid; -/// passing it to any other `kernel_*` function is UB. +/// `exec` must have been returned by [`kernel_statement_execute`] and +/// not previously closed. #[no_mangle] pub unsafe extern "C" fn kernel_executed_statement_close( exec: *mut kernel_executed_statement_t, ) -> KernelStatusCode { - unimplemented!("PR 7b") + crate::ffi::error::clear_error(); + if exec.is_null() { + return store_null_handle("kernel_executed_statement_close: exec must not be null"); + } + drop(Box::from_raw(exec as *mut ExecutedStatement)); + KernelStatusCode::Success } -// ─── ExecutedAsyncStatement (async) ────────────────────────────────────────── +// ─── ExecutedAsyncStatement (async) — deferred in v0 ───────────────────────── +// +// The async submit path keeps its skeleton until a consumer needs +// caller-driven polling over the C ABI. Rust-crate consumers use +// `Statement::submit` + `ExecutedAsyncStatement` directly. -/// Server-issued statement id, NUL-terminated. +/// Submit-and-return. **Deferred in v0** — see module docs. /// -/// **Lifetime:** the returned pointer is valid as long as `exec` is. -/// Do not free it; do not retain past -/// `kernel_executed_async_statement_close`. -/// -/// **On stale handle:** returns `null` if `exec` has been invalidated -/// by a re-execute on the parent statement. -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_async_statement_id( - exec: *const kernel_executed_async_statement_t, -) -> *const c_char { - unimplemented!("PR 7b") -} - -/// One-shot status check. Writes a [`KernelStatementStatusKind`] kind -/// tag to `out_status`. On `Failed`, the caller invokes -/// `kernel_get_last_error` to retrieve the underlying error detail. -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_async_statement_status( - exec: *mut kernel_executed_async_statement_t, - out_status: *mut KernelStatementStatusKind, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -/// Block until the server reaches a terminal state, then return the -/// result stream. On success, `*out` holds an owned -/// `kernel_result_stream_t` the caller releases with -/// `kernel_result_stream_close`. -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_async_statement_await_result( - exec: *mut kernel_executed_async_statement_t, - out: *mut *mut super::result::kernel_result_stream_t, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -/// Fetch the result without polling. Same ownership rules as -/// `kernel_executed_async_statement_await_result`. +/// # Safety +/// `stmt` / `out` must be valid pointers. #[no_mangle] -pub unsafe extern "C" fn kernel_executed_async_statement_fetch_result( - exec: *mut kernel_executed_async_statement_t, - out: *mut *mut super::result::kernel_result_stream_t, +pub unsafe extern "C" fn kernel_statement_submit( + stmt: *mut kernel_statement_t, + out: *mut *mut kernel_executed_async_statement_t, ) -> KernelStatusCode { - unimplemented!("PR 7b") + let _ = (stmt, out); + crate::ffi::error::clear_error(); + crate::ffi::error::store_error(Error::invalid_argument().message( + "async submit is not exposed over the v0 C ABI; use the synchronous execute path", + )); + KernelStatusCode::InvalidArgument } -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_async_statement_cancel( - exec: *mut kernel_executed_async_statement_t, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} +// ─── Shared helpers ────────────────────────────────────────────────────────── -/// Free an async executed handle. +/// Clear the thread-local error, null-check the statement handle, run +/// `f` against the borrowed statement, and store/translate any error. /// /// # Safety -/// -/// `exec` must have been returned by `kernel_statement_submit` and -/// not previously closed. After this call, `exec` is invalid; -/// passing it to any other `kernel_*` function is UB. -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_async_statement_close( - exec: *mut kernel_executed_async_statement_t, +/// `stmt` must be a live `*mut kernel_statement_t`. +unsafe fn with_statement( + stmt: *mut kernel_statement_t, + f: impl FnOnce(&mut Statement) -> Result<(), Error>, ) -> KernelStatusCode { - unimplemented!("PR 7b") + crate::ffi::error::clear_error(); + let Some(stmt) = statement_mut(stmt) else { + return store_null_handle("statement handle must not be null"); + }; + match f(stmt) { + Ok(()) => KernelStatusCode::Success, + Err(e) => { + let code = KernelStatusCode::from(e.code); + crate::ffi::error::store_error(e); + code + } + } +} + +/// Store an `InvalidArgument` for a null handle and return the matching +/// status code. +fn store_null_handle(msg: &str) -> KernelStatusCode { + crate::ffi::error::store_error(Error::invalid_argument().message(msg)); + KernelStatusCode::InvalidArgument } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c new file mode 100644 index 00000000..dc89f9b3 --- /dev/null +++ b/tests/c/session_smoke.c @@ -0,0 +1,140 @@ +/* + * 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. + */ + +/* + * C ABI smoke test — links the kernel cdylib and exercises the parts of + * the surface that need no live warehouse: config lifecycle, null-handle + * guards, and the error-reporting path. A connection error against an + * unreachable host proves the open path marshals config, drives the + * runtime, and routes a typed error back through `kernel_get_last_error`. + * + * Build / run (see the CMake/CI wiring in A6): + * cc -I include tests/c/session_smoke.c -L target/debug \ + * -ldatabricks_sql_kernel -o session_smoke && ./session_smoke + */ + +#include +#include +#include + +#include "databricks_kernel.h" + +static int failures = 0; + +#define CHECK(cond, msg) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL: %s (%s:%d)\n", msg, __FILE__, __LINE__); \ + failures++; \ + } else { \ + fprintf(stderr, "ok: %s\n", msg); \ + } \ + } while (0) + +/* Config new → set warehouse + PAT → free, with no open. */ +static void test_config_lifecycle(void) { + KernelSessionConfig* config = NULL; + KernelStatusCode rc = kernel_session_config_new(&config); + CHECK(rc == KernelStatusCode_Success, "config_new succeeds"); + CHECK(config != NULL, "config_new writes a non-null handle"); + + rc = kernel_session_config_set_warehouse(config, "https://example.databricks.com", "wh123"); + CHECK(rc == KernelStatusCode_Success, "set_warehouse succeeds"); + + rc = kernel_session_config_set_auth_pat(config, "dapi-not-a-real-token"); + CHECK(rc == KernelStatusCode_Success, "set_auth_pat succeeds"); + + rc = kernel_session_config_set_session_conf(config, "ANSI_MODE", "true"); + CHECK(rc == KernelStatusCode_Success, "set_session_conf succeeds"); + + kernel_session_config_free(config); + CHECK(1, "config_free does not crash"); +} + +/* Null handles must return InvalidArgument, not crash. */ +static void test_null_guards(void) { + KernelStatusCode rc = kernel_session_config_new(NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "config_new(NULL) → InvalidArgument"); + + rc = kernel_session_close(NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "session_close(NULL) → InvalidArgument"); + + rc = kernel_statement_close(NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "statement_close(NULL) → InvalidArgument"); + + rc = kernel_result_stream_close(NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "result_stream_close(NULL) → InvalidArgument"); + + KernelError err; + memset(&err, 0, sizeof(err)); + bool present = kernel_get_last_error(&err); + CHECK(present, "last error is populated after a null-guard failure"); + CHECK(err.code == KernelStatusCode_InvalidArgument, "last error code is InvalidArgument"); + CHECK(err.message != NULL && strlen(err.message) > 0, "last error carries a message"); +} + +/* Missing connection / auth → the open path reports InvalidArgument. */ +static void test_open_requires_connection_and_auth(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + /* No connection, no auth set. */ + kernel_session_t* session = NULL; + KernelStatusCode rc = kernel_session_open(config, &session); + CHECK(rc == KernelStatusCode_InvalidArgument, "open without connection → InvalidArgument"); + CHECK(session == NULL, "session stays null on failed open"); + + KernelError err; + memset(&err, 0, sizeof(err)); + bool present = kernel_get_last_error(&err); + CHECK(present, "open failure populates last error"); +} + +/* Open against an unreachable host → a transport/connection error code + * (NOT Success), with the error surfaced via kernel_get_last_error. The + * exact code depends on DNS/connect behaviour; we assert only that it + * failed and produced a populated error, so the test stays hermetic. */ +static void test_open_unreachable_host_errors(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + /* RFC 5737 TEST-NET-1: guaranteed non-routable. */ + (void)kernel_session_config_set_warehouse(config, "https://192.0.2.1", "wh123"); + (void)kernel_session_config_set_auth_pat(config, "dapi-not-a-real-token"); + + kernel_session_t* session = NULL; + KernelStatusCode rc = kernel_session_open(config, &session); + CHECK(rc != KernelStatusCode_Success, "open against unreachable host fails"); + CHECK(session == NULL, "session stays null on failed open"); + + KernelError err; + memset(&err, 0, sizeof(err)); + bool present = kernel_get_last_error(&err); + CHECK(present, "unreachable-host open populates last error"); + CHECK(err.message != NULL, "error has a message"); +} + +int main(void) { + test_config_lifecycle(); + test_null_guards(); + test_open_requires_connection_and_auth(); + test_open_unreachable_host_errors(); + + if (failures == 0) { + fprintf(stderr, "\nAll C ABI smoke checks passed.\n"); + return 0; + } + fprintf(stderr, "\n%d C ABI smoke check(s) FAILED.\n", failures); + return 1; +} From eb39debfce0efdbba2dc6a1dcd9ae2d2688c0a61 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Tue, 30 Jun 2026 10:53:36 +0000 Subject: [PATCH 2/7] [PECOBLR-2096] Rename C ABI module src/ffi -> src/c_abi Distinguish the C ABI from the PyO3 / napi FFI bindings, which are also "FFI" in the broad sense. Document in the module + lib.rs docs why the C ABI lives in the core crate (shares the kernel's tls-native backend) while the bindings are separate workspaces (they carry tls-rustls, which must not unify into the kernel build). Mechanical: src/ffi -> src/c_abi, `crate::ffi` -> `crate::c_abi`, `pub mod ffi` -> `pub mod c_abi`. No behavior change; the exported C symbols and include/databricks_kernel.h are unaffected. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- src/{ffi => c_abi}/error.rs | 4 ++-- src/{ffi => c_abi}/metadata.rs | 4 ++-- src/{ffi => c_abi}/mod.rs | 22 +++++++++++++++++++++- src/{ffi => c_abi}/result.rs | 10 +++++----- src/{ffi => c_abi}/session.rs | 22 +++++++++++----------- src/{ffi => c_abi}/statement.rs | 22 +++++++++++----------- src/lib.rs | 13 +++++++++---- 7 files changed, 61 insertions(+), 36 deletions(-) rename src/{ffi => c_abi}/error.rs (98%) rename src/{ffi => c_abi}/metadata.rs (98%) rename src/{ffi => c_abi}/mod.rs (86%) rename src/{ffi => c_abi}/result.rs (97%) rename src/{ffi => c_abi}/session.rs (96%) rename src/{ffi => c_abi}/statement.rs (95%) diff --git a/src/ffi/error.rs b/src/c_abi/error.rs similarity index 98% rename from src/ffi/error.rs rename to src/c_abi/error.rs index 6ba73fd3..63235941 100644 --- a/src/ffi/error.rs +++ b/src/c_abi/error.rs @@ -128,7 +128,7 @@ pub unsafe extern "C" fn kernel_get_last_error(out: *mut KernelError) -> bool { /// Crate-internal: write a typed kernel [`Error`] into the thread-local /// last-error buffer. Every FFI function that returns a non-`Success` -/// status code calls this (via [`crate::ffi::block_on_ffi`] or directly) +/// status code calls this (via [`crate::c_abi::block_on_ffi`] or directly) /// so the consumer can retrieve the structured detail with /// [`kernel_get_last_error`]. pub(crate) fn store_error(err: Error) { @@ -159,7 +159,7 @@ pub(crate) fn store_error(err: Error) { } /// Crate-internal: clear the thread-local last-error buffer. Called at -/// the entry of every FFI function (via [`crate::ffi::block_on_ffi`] or +/// the entry of every FFI function (via [`crate::c_abi::block_on_ffi`] or /// directly) so a previous call's stale error can't leak into a /// subsequent one that succeeds. pub(crate) fn clear_error() { diff --git a/src/ffi/metadata.rs b/src/c_abi/metadata.rs similarity index 98% rename from src/ffi/metadata.rs rename to src/c_abi/metadata.rs index e63c24b9..c110fbab 100644 --- a/src/ffi/metadata.rs +++ b/src/c_abi/metadata.rs @@ -99,7 +99,7 @@ where ) -> std::pin::Pin> + '_>>, { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); let Some(session) = (session as *const Session).as_ref() else { return store_null("metadata: session must not be null"); }; @@ -301,7 +301,7 @@ pub unsafe extern "C" fn kernel_metadata_foreign_keys( /// Store an `InvalidArgument` for a null pointer and return its code. fn store_null(msg: &str) -> KernelStatusCode { - crate::ffi::error::store_error(Error::invalid_argument().message(msg)); + crate::c_abi::error::store_error(Error::invalid_argument().message(msg)); KernelStatusCode::InvalidArgument } diff --git a/src/ffi/mod.rs b/src/c_abi/mod.rs similarity index 86% rename from src/ffi/mod.rs rename to src/c_abi/mod.rs index 95f2be71..549550e1 100644 --- a/src/ffi/mod.rs +++ b/src/c_abi/mod.rs @@ -20,6 +20,26 @@ //! C strings / structs into `SessionConfig`, and exposes opaque handles //! for `Session`, `Statement`, `ExecutedStatement`, //! `ExecutedAsyncStatement`, and `ResultStream`. +//! +//! ## Why this lives in the core crate (and the bindings don't) +//! +//! The PyO3 (`pyo3/`) and napi (`napi/`) bindings are *separate Cargo +//! workspaces* that depend on the kernel via `path = ".."`. They are +//! split out for one reason: they build the kernel with `tls-rustls`, +//! while the kernel core builds with the default `tls-native`. Living in +//! one workspace would unify those features (`tls-native ∪ tls-rustls`), +//! trip the mutual-exclusion `compile_error!` in `lib.rs`, and otherwise +//! link two TLS stacks into one artifact. +//! +//! The C ABI has no such conflict — it uses the same `tls-native` backend +//! as the core. Keeping it here means it compiles straight into +//! `libdatabricks_sql_kernel.{a,so}`, which is exactly what a C / C++ +//! consumer wants to link: one static library, no satellite crate. The +//! module is named `c_abi` (not `ffi`) to distinguish it from the +//! PyO3 / napi FFI bindings, which are also "FFI" in the broad sense. +//! +//! A `cbindgen`-generated header is a v0.1 follow-up; today the header at +//! `include/databricks_kernel.h` is hand-maintained alongside this module. // Each `extern "C"` function carries its own `# Safety` section; the // module-wide allow that masked them in the skeleton phase is gone now @@ -85,7 +105,7 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime:: /// at the `block_on` edge and surfaced as `Internal` rather than /// unwinding across the FFI boundary (which is UB). /// -/// [`KernelStatusCode`]: crate::ffi::KernelStatusCode +/// [`KernelStatusCode`]: crate::c_abi::KernelStatusCode /// [`Error`]: crate::kernel_error::Error pub(crate) fn block_on_ffi(fut_builder: F) -> Result where diff --git a/src/ffi/result.rs b/src/c_abi/result.rs similarity index 97% rename from src/ffi/result.rs rename to src/c_abi/result.rs index 8adb9b9d..d0455136 100644 --- a/src/ffi/result.rs +++ b/src/c_abi/result.rs @@ -97,7 +97,7 @@ pub unsafe extern "C" fn kernel_result_stream_get_schema( stream: *mut kernel_result_stream_t, out: *mut FFI_ArrowSchema, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { return store_null("kernel_result_stream_get_schema: stream must not be null"); }; @@ -140,7 +140,7 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( out_array: *mut FFI_ArrowArray, out_schema: *mut FFI_ArrowSchema, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { return store_null("kernel_result_stream_next_batch: stream must not be null"); }; @@ -215,7 +215,7 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( pub unsafe extern "C" fn kernel_result_stream_close( stream: *mut kernel_result_stream_t, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); if stream.is_null() { return store_null("kernel_result_stream_close: stream must not be null"); } @@ -225,13 +225,13 @@ pub unsafe extern "C" fn kernel_result_stream_close( /// Store an `InvalidArgument` for a null pointer and return its code. fn store_null(msg: &str) -> KernelStatusCode { - crate::ffi::error::store_error(Error::invalid_argument().message(msg)); + crate::c_abi::error::store_error(Error::invalid_argument().message(msg)); KernelStatusCode::InvalidArgument } /// Store a typed error and return its mapped status code. fn store_error(e: Error) -> KernelStatusCode { let code = KernelStatusCode::from(e.code); - crate::ffi::error::store_error(e); + crate::c_abi::error::store_error(e); code } diff --git a/src/ffi/session.rs b/src/c_abi/session.rs similarity index 96% rename from src/ffi/session.rs rename to src/c_abi/session.rs index 78d00aff..db018f79 100644 --- a/src/ffi/session.rs +++ b/src/c_abi/session.rs @@ -108,9 +108,9 @@ unsafe fn required_str(ptr: *const c_char, what: &str) -> Result pub unsafe extern "C" fn kernel_session_config_new( out: *mut *mut KernelSessionConfig, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); if out.is_null() { - crate::ffi::error::store_error( + crate::c_abi::error::store_error( Error::invalid_argument().message("kernel_session_config_new: out must not be null"), ); return KernelStatusCode::InvalidArgument; @@ -257,9 +257,9 @@ unsafe fn set_on_config( config: *mut KernelSessionConfig, f: impl FnOnce(&mut KernelSessionConfig) -> Result<(), Error>, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); let Some(config) = config.as_mut() else { - crate::ffi::error::store_error( + crate::c_abi::error::store_error( Error::invalid_argument().message("config handle must not be null"), ); return KernelStatusCode::InvalidArgument; @@ -268,7 +268,7 @@ unsafe fn set_on_config( Ok(()) => KernelStatusCode::Success, Err(e) => { let code = KernelStatusCode::from(e.code); - crate::ffi::error::store_error(e); + crate::c_abi::error::store_error(e); code } } @@ -291,9 +291,9 @@ pub unsafe extern "C" fn kernel_session_open( config: *mut KernelSessionConfig, out: *mut *mut kernel_session_t, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); if config.is_null() || out.is_null() { - crate::ffi::error::store_error( + crate::c_abi::error::store_error( Error::invalid_argument() .message("kernel_session_open: config and out must be non-null"), ); @@ -377,9 +377,9 @@ fn build_session(config: KernelSessionConfig) -> Result KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); if session.is_null() { - crate::ffi::error::store_error( + crate::c_abi::error::store_error( Error::invalid_argument().message("kernel_session_close: session must not be null"), ); return KernelStatusCode::InvalidArgument; @@ -404,9 +404,9 @@ pub unsafe extern "C" fn kernel_session_new_statement( session: *mut kernel_session_t, out: *mut *mut super::statement::kernel_statement_t, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); if session.is_null() || out.is_null() { - crate::ffi::error::store_error( + crate::c_abi::error::store_error( Error::invalid_argument() .message("kernel_session_new_statement: session and out must be non-null"), ); diff --git a/src/ffi/statement.rs b/src/c_abi/statement.rs similarity index 95% rename from src/ffi/statement.rs rename to src/c_abi/statement.rs index 6be0d965..73d97795 100644 --- a/src/ffi/statement.rs +++ b/src/c_abi/statement.rs @@ -28,8 +28,8 @@ //! ## Error reporting convention //! //! Every function returns [`KernelStatusCode`]. On any non-`Success` -//! return, the consumer calls [`crate::ffi::error::kernel_get_last_error`] -//! to populate a [`crate::ffi::error::KernelError`] with the typed +//! return, the consumer calls [`crate::c_abi::error::kernel_get_last_error`] +//! to populate a [`crate::c_abi::error::KernelError`] with the typed //! detail. The thread-local error buffer is reset at the start of every //! FFI function. @@ -229,7 +229,7 @@ pub unsafe extern "C" fn kernel_statement_execute( stmt: *mut kernel_statement_t, out: *mut *mut kernel_executed_statement_t, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); let Some(stmt) = statement_mut(stmt) else { return store_null_handle("kernel_statement_execute: stmt must not be null"); }; @@ -266,7 +266,7 @@ pub unsafe extern "C" fn kernel_statement_execute( /// not previously closed. #[no_mangle] pub unsafe extern "C" fn kernel_statement_close(stmt: *mut kernel_statement_t) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); if stmt.is_null() { return store_null_handle("kernel_statement_close: stmt must not be null"); } @@ -294,7 +294,7 @@ pub unsafe extern "C" fn kernel_executed_statement_get_result_stream( exec: *mut kernel_executed_statement_t, out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); if exec.is_null() { return store_null_handle("get_result_stream: exec must not be null"); } @@ -330,7 +330,7 @@ pub unsafe extern "C" fn kernel_executed_statement_num_modified_rows( pub unsafe extern "C" fn kernel_executed_statement_close( exec: *mut kernel_executed_statement_t, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); if exec.is_null() { return store_null_handle("kernel_executed_statement_close: exec must not be null"); } @@ -354,8 +354,8 @@ pub unsafe extern "C" fn kernel_statement_submit( out: *mut *mut kernel_executed_async_statement_t, ) -> KernelStatusCode { let _ = (stmt, out); - crate::ffi::error::clear_error(); - crate::ffi::error::store_error(Error::invalid_argument().message( + crate::c_abi::error::clear_error(); + crate::c_abi::error::store_error(Error::invalid_argument().message( "async submit is not exposed over the v0 C ABI; use the synchronous execute path", )); KernelStatusCode::InvalidArgument @@ -372,7 +372,7 @@ unsafe fn with_statement( stmt: *mut kernel_statement_t, f: impl FnOnce(&mut Statement) -> Result<(), Error>, ) -> KernelStatusCode { - crate::ffi::error::clear_error(); + crate::c_abi::error::clear_error(); let Some(stmt) = statement_mut(stmt) else { return store_null_handle("statement handle must not be null"); }; @@ -380,7 +380,7 @@ unsafe fn with_statement( Ok(()) => KernelStatusCode::Success, Err(e) => { let code = KernelStatusCode::from(e.code); - crate::ffi::error::store_error(e); + crate::c_abi::error::store_error(e); code } } @@ -389,6 +389,6 @@ unsafe fn with_statement( /// Store an `InvalidArgument` for a null handle and return the matching /// status code. fn store_null_handle(msg: &str) -> KernelStatusCode { - crate::ffi::error::store_error(Error::invalid_argument().message(msg)); + crate::c_abi::error::store_error(Error::invalid_argument().message(msg)); KernelStatusCode::InvalidArgument } diff --git a/src/lib.rs b/src/lib.rs index eaacf7d7..48a3942f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -37,8 +37,12 @@ //! //! - **Direct Rust crate** for PyO3 / napi-rs wrappers (Python and //! Node.js). -//! - **Custom C ABI** under `crate::ffi` (skeleton today; bodies land -//! when an ODBC / Go consumer needs them). +//! - **Custom C ABI** under [`crate::c_abi`] for ODBC / Go consumers +//! that cannot link the Rust crate directly. It lives *in* the core +//! crate (not a separate crate like the PyO3 / napi bindings) because +//! it shares the kernel's default `tls-native` backend — the bindings +//! are split out only to carry `tls-rustls` without unifying it into +//! the kernel build. See the `c_abi` module docs. //! //! ## Example //! @@ -114,8 +118,9 @@ pub mod result_stream; pub mod session; pub(crate) mod util; -// Custom C ABI for ODBC / Go consumers (skeleton). -pub mod ffi; +// Custom C ABI for ODBC / Go consumers (lives in the core crate; see +// `c_abi` module docs for why it is not a separate crate like pyo3 / napi). +pub mod c_abi; // === Public re-exports === pub use config::{ From bb8c603b0500ff2d90d45f3259569cad9572d926 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 1 Jul 2026 12:10:24 +0000 Subject: [PATCH 3/7] [PECOBLR-2096] Address code-review findings on the C ABI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes from the automated review of the C ABI. Safety (High): - catch_ffi(): route every synchronous entry point (bind_*, set_sql, config setters, result get_schema/next_batch/close, metadata) through a catch_unwind guard so a panic can't unwind across `extern "C"` (UB). Previously only block_on_ffi's async body was guarded. - Metadata Owned stream: drain the (bounded) metadata ResultStream fully on the runtime inside block_on_ffi, then serve batches in-memory — instead of driving a possibly-CloudFetch-backed reader off the tokio reactor from a plain C thread (hang/panic). - Bound the positional bind ordinal (<= 65536) before StatementSpec::param so a caller-controlled ordinal can't trigger an unbounded Vec::resize (OOM / capacity-overflow panic). Correctness (Medium): - Result stream shares a ValidityFlag with its executed handle; closing the executed handle first now yields InvalidStatementHandle instead of a use-after-free on the raw pointer. - Panic logging: tracing::error! in the shared panic handler so a caught panic is observable, not silently folded into Internal. - num_modified_rows clears the error buffer on entry and stores InvalidArgument on a null handle (no stale last-error); documents that -1 with no stored error means "not applicable". - kernel_statement_execute documents the re-execute invalidation + the half-mutated-handle-on-panic contract. Docs / cleanup (Medium/Low): - Header + CI: src/ffi -> src/c_abi; crate::ffi -> crate::c_abi; scope the ABI-version note to reality (handles are opaque; only KernelError is readable); document async-close best-effort semantics; declare the deferred kernel_statement_submit + async handle type. - Hoist store_and_code / store_invalid_arg into c_abi::error (dedup across modules); drop the misleading #[repr(C)] + dead version field on the private KernelSessionConfig builder box; explicit #[non_exhaustive] ResultBatch match with a NotImplemented fallback; note secret zeroize as future work. - Tests: Rust unit tests for the Owned exhaustion sentinel (released array + Success) and result-stream null guards; expand the C smoke test with http_path/M2M setters, null-arg rejection, the submit stub, and bind null-handle guards. cargo clippy --all-targets -D warnings / fmt clean; 670 lib tests + 28 C smoke checks pass. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- .github/workflows/pr-checks.yml | 2 +- include/databricks_kernel.h | 44 ++++- src/c_abi/error.rs | 18 ++ src/c_abi/metadata.rs | 51 ++++-- src/c_abi/mod.rs | 58 +++++- src/c_abi/result.rs | 315 +++++++++++++++++++++----------- src/c_abi/session.rs | 29 ++- src/c_abi/statement.rs | 158 +++++++++++----- tests/c/session_smoke.c | 44 +++++ 9 files changed, 519 insertions(+), 200 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 874c9a95..76be5308 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -136,7 +136,7 @@ jobs: - name: make c-abi-test # Builds the cdylib and compiles + runs the hand-written C smoke - # tests in tests/c/ against the C ABI exported from src/ffi/. + # tests in tests/c/ against the C ABI exported from src/c_abi/. # Hermetic (no live warehouse) — proves ODBC / Go consumers can # link and call the kernel. `cc` is preinstalled on the runner. run: make c-abi-test diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index d5d7b356..5b189bc2 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -18,7 +18,7 @@ * Databricks SQL Kernel — C ABI (v0). * * Hand-written header for the kernel's custom C ABI (cbindgen - * integration is a v0.1 concern). The bodies live in `src/ffi/` in the + * integration is a v0.1 concern). The bodies live in `src/c_abi/` in the * `databricks-sql-kernel` crate, compiled as a `cdylib` / `staticlib`. * * This is the surface ODBC / Go consumers link against. It is NOT ADBC: @@ -38,9 +38,29 @@ * * ## ABI versioning * - * Every public struct carries a leading `uint32_t version`. Struct - * layout may change freely through v0.x (no ABI promise); ABI stability - * is committed at v1.0. + * There is no ABI promise through v0.x: struct layouts and the function + * set may change freely; ABI stability is committed at v1.0. All handle + * types below are *opaque* (incomplete) to C — you only ever hold + * pointers to them, never read their fields — so their Rust-side layout + * is irrelevant. The one caller-*readable* struct, `KernelError`, is laid + * out exactly as declared here; copy its fields out before the next + * `kernel_*` call on the thread. + * + * ## Lifecycle & threading notes + * + * - **Re-execution invalidates prior handles.** `kernel_statement_execute` + * auto-cancels and closes any `kernel_executed_statement_t` previously + * returned by the same statement; calls on the stale handle then return + * `KernelStatusCode_InvalidStatementHandle`. Don't hold two live + * executed handles from one statement. + * - **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. */ #ifndef DATABRICKS_KERNEL_H @@ -94,7 +114,7 @@ struct ArrowArray { /* ─── Status + error ────────────────────────────────────────────────── * - * Discriminants match `crate::ffi::KernelStatusCode`. Keep this enum in + * Discriminants match `crate::c_abi::KernelStatusCode`. Keep this enum in * lockstep with that Rust enum (the Rust side enforces a 1:1 mapping * against `ErrorCode` with an exhaustive match). */ @@ -163,6 +183,10 @@ 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. */ +typedef struct kernel_executed_async_statement_t kernel_executed_async_statement_t; typedef struct kernel_result_stream_t kernel_result_stream_t; /* ─── Session config ────────────────────────────────────────────────── @@ -230,6 +254,16 @@ KernelStatusCode kernel_statement_bind_string(kernel_statement_t* stmt, size_t o 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. + */ +KernelStatusCode kernel_statement_submit(kernel_statement_t* stmt, + kernel_executed_async_statement_t** out); + /* * Free the statement lifecycle owner. Does NOT free executed-handle * boxes; close each of those separately. diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index 63235941..28503f4b 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -166,6 +166,24 @@ pub(crate) fn clear_error() { LAST_ERROR.with(|cell| *cell.borrow_mut() = LastError::default()); } +/// Store a typed [`Error`] and return its mapped [`KernelStatusCode`]. +/// +/// The single "map code + store + return code" helper shared by every +/// C entry point that surfaces a typed error (previously reimplemented +/// per module). +pub(crate) fn store_and_code(err: Error) -> KernelStatusCode { + let code = KernelStatusCode::from(err.code); + store_error(err); + code +} + +/// Store an `InvalidArgument` with `msg` and return +/// [`KernelStatusCode::InvalidArgument`]. Used for the null-pointer / +/// bad-argument guards at the top of every entry point. +pub(crate) fn store_invalid_arg(msg: &str) -> KernelStatusCode { + store_and_code(Error::invalid_argument().message(msg)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/c_abi/metadata.rs b/src/c_abi/metadata.rs index c110fbab..1c2cba0e 100644 --- a/src/c_abi/metadata.rs +++ b/src/c_abi/metadata.rs @@ -26,13 +26,15 @@ //! kernel's `Metadata` produces; ODBC / JDBC drivers keep their own //! rename / reshape layer on top. +use super::error::store_invalid_arg; use super::result::{into_raw_result_stream, kernel_result_stream_t}; 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::{OwnedBatchIter, ResultStream, SchemaRef}; +use crate::result_stream::{ResultBatch, ResultStream, SchemaRef}; use crate::session::Session; +use arrow_array::RecordBatch; use std::ffi::{c_char, CStr}; /// Read an optional C string: null → `None`, else borrowed `&str` @@ -75,11 +77,34 @@ unsafe fn opt_pattern<'a>(ptr: *const c_char, what: &str) -> Result (SchemaRef, OwnedBatchIter) { +/// 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(); - (schema, stream.into_owned_batches()) + 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 @@ -101,18 +126,18 @@ where { crate::c_abi::error::clear_error(); let Some(session) = (session as *const Session).as_ref() else { - return store_null("metadata: session must not be null"); + return store_invalid_arg("metadata: session must not be null"); }; if out.is_null() { - return store_null("metadata: out must not be null"); + return store_invalid_arg("metadata: out must not be null"); } let result = block_on_ffi(move || async move { let stream = build(session).await?; - Ok(into_parts(stream)) + drain_metadata(stream).await }); match result { - Ok((schema, iter)) => { - std::ptr::write(out, into_raw_result_stream(schema, iter)); + Ok((schema, batches)) => { + std::ptr::write(out, into_raw_result_stream(schema, batches)); KernelStatusCode::Success } Err(code) => code, @@ -299,12 +324,6 @@ pub unsafe extern "C" fn kernel_metadata_foreign_keys( }) } -/// Store an `InvalidArgument` for a null pointer and return its code. -fn store_null(msg: &str) -> KernelStatusCode { - crate::c_abi::error::store_error(Error::invalid_argument().message(msg)); - KernelStatusCode::InvalidArgument -} - // PR 7d follow-ups: functions, procedures, type_info, table_types — the // kernel `Metadata` exposes these (some synthesised in-memory). Wire them // over the C ABI when an ODBC / Go consumer needs SQLGetTypeInfo / diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 549550e1..49e1e1ff 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -131,17 +131,59 @@ where error::store_error(e); Err(code) } - Err(panic) => { - let detail = panic_message(&panic); - let e = crate::kernel_error::Error::internal() - .message(format!("panic in kernel C ABI: {detail}")) - .location(concat!(file!(), ":", line!())); - error::store_error(e); - Err(KernelStatusCode::Internal) - } + Err(panic) => Err(handle_panic(panic)), + } +} + +/// Run a **synchronous** fallible closure at an `extern "C"` boundary, +/// catching any panic so it can't unwind across the FFI frame (UB) and +/// mapping it to [`KernelStatusCode::Internal`]. +/// +/// Sibling of [`block_on_ffi`] for entry points that do no async work +/// (parameter binding, config setters, the Arrow C Data Interface +/// export, handle teardown). The closure returns a `KernelStatusCode` +/// directly — it is expected to have already stored any typed error via +/// [`error::store_error`] on its own failure paths; this wrapper only +/// adds the panic guard (and clears the thread-local error on entry, so +/// a caller reading `kernel_get_last_error` after a `Success` never sees +/// a stale error). +/// +/// # Safety note +/// The closure runs under `AssertUnwindSafe`; callers that hold a `&mut` +/// to a handle across this boundary must treat the handle as potentially +/// half-mutated on an `Internal` return (see `kernel_statement_execute`). +pub(crate) fn catch_ffi(f: F) -> KernelStatusCode +where + F: FnOnce() -> KernelStatusCode, +{ + error::clear_error(); + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) { + Ok(code) => code, + Err(panic) => handle_panic(panic), } } +/// Shared panic handler for both FFI wrappers: log it (so a recurring +/// panic bug is visible to on-call rather than silently folded into +/// `Internal`), store a typed `Internal` error in the thread-local +/// buffer, and return the `Internal` status code. +fn handle_panic(panic: Box) -> KernelStatusCode { + let detail = panic_message(&panic); + // Log at ERROR so a recurring panic (bad CloudFetch batch, reader + // unwrap) is observable in aggregate — a caught panic across the C + // ABI is always a kernel bug, never a routine query failure. + tracing::error!( + target: crate::klog::KERNEL_LOG_TARGET, + detail = %detail, + "panic caught at the kernel C ABI boundary" + ); + let e = crate::kernel_error::Error::internal() + .message(format!("panic in kernel C ABI: {detail}")) + .location(concat!(file!(), ":", line!())); + error::store_error(e); + KernelStatusCode::Internal +} + /// Best-effort extraction of a human-readable message from a caught /// panic payload. fn panic_message(panic: &Box) -> String { diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index d0455136..8afc873c 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -34,12 +34,14 @@ #![allow(non_camel_case_types)] -use super::KernelStatusCode; -use crate::kernel_error::Error; -use crate::result_stream::{OwnedBatchIter, ResultBatch, SchemaRef}; +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::statement::executed::ExecutedStatement; +use crate::statement::validity::ValidityFlag; use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; -use arrow_array::Array; +use arrow_array::{Array, RecordBatch}; /// Opaque result-stream handle. Boxed [`ResultStreamInner`]. #[repr(C)] @@ -49,38 +51,75 @@ pub struct kernel_result_stream_t { /// Backing state for a result-stream handle. enum ResultStreamInner { - /// Self-contained owned stream (metadata path). + /// 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. Owned { schema: SchemaRef, - iter: OwnedBatchIter, + batches: std::vec::IntoIter, }, /// Borrow of the executed statement that produced this stream - /// (sync execute path). The pointer is valid as long as the - /// executed handle is — the C consumer must not close the executed - /// handle before closing this stream. - Executed { exec: *mut ExecutedStatement }, + /// (sync execute path). The raw pointer is only dereferenced after + /// `valid.check()` passes; closing the executed handle invalidates + /// `valid`, so an out-of-order close is a defined + /// `InvalidStatementHandle` error, not a use-after-free. + Executed { + exec: *mut ExecutedStatement, + valid: ValidityFlag, + }, } /// Crate-internal: build an owned result-stream handle from a schema and -/// an owned batch iterator (used by the metadata FFI). +/// a fully-materialised batch list (used by the metadata FFI, which +/// drains its bounded result on the runtime before calling this). pub(crate) fn into_raw_result_stream( schema: SchemaRef, - iter: OwnedBatchIter, + batches: Vec, ) -> *mut kernel_result_stream_t { - Box::into_raw(Box::new(ResultStreamInner::Owned { schema, iter })) - as *mut kernel_result_stream_t + Box::into_raw(Box::new(ResultStreamInner::Owned { + schema, + batches: batches.into_iter(), + })) as *mut kernel_result_stream_t } /// Crate-internal: build a result-stream handle that borrows from an -/// executed statement (used by the sync execute path). +/// executed statement (used by the sync execute path). `valid` is shared +/// with the executed handle and invalidated when it is closed. /// /// # Safety -/// `exec` must remain valid for the lifetime of the returned stream -/// handle. +/// `exec` must point at the executed handle's `ExecutedStatement` and +/// remain valid as long as `valid.check()` passes. pub(crate) unsafe fn into_raw_executed_stream( exec: *mut ExecutedStatement, + valid: ValidityFlag, ) -> *mut kernel_result_stream_t { - Box::into_raw(Box::new(ResultStreamInner::Executed { exec })) as *mut kernel_result_stream_t + Box::into_raw(Box::new(ResultStreamInner::Executed { exec, valid })) + as *mut kernel_result_stream_t +} + +/// Resolve the backing `ExecutedStatement` for the `Executed` shape, +/// checking the shared validity flag first so a closed executed handle +/// yields `InvalidStatementHandle` rather than a dangling deref. +/// +/// # Safety +/// Caller must hold `&mut ResultStreamInner`. +unsafe fn executed_ref<'a>( + exec: *mut ExecutedStatement, + valid: &ValidityFlag, +) -> Result<&'a mut ExecutedStatement, KernelStatusCode> { + if valid.check().is_err() { + return Err(store_and_code(Error::new( + ErrorCode::InvalidStatementHandle, + "result stream used after its executed statement was closed", + ))); + } + match exec.as_mut() { + Some(e) => Ok(e), + None => Err(store_invalid_arg( + "result stream: backing executed handle is null", + )), + } } /// Export the schema as an `FFI_ArrowSchema`. @@ -97,31 +136,28 @@ pub unsafe extern "C" fn kernel_result_stream_get_schema( stream: *mut kernel_result_stream_t, out: *mut FFI_ArrowSchema, ) -> KernelStatusCode { - crate::c_abi::error::clear_error(); - let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { - return store_null("kernel_result_stream_get_schema: stream must not be null"); - }; - if out.is_null() { - return store_null("kernel_result_stream_get_schema: out must not be null"); - } - let schema = match inner { - ResultStreamInner::Owned { schema, .. } => schema.clone(), - ResultStreamInner::Executed { exec } => { - let Some(exec) = exec.as_ref() else { - return store_null( - "kernel_result_stream_get_schema: backing executed handle is null", - ); - }; - exec.schema() + catch_ffi(|| { + let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { + return store_invalid_arg("kernel_result_stream_get_schema: stream must not be null"); + }; + if out.is_null() { + return store_invalid_arg("kernel_result_stream_get_schema: out must not be null"); } - }; - match FFI_ArrowSchema::try_from(schema.as_ref()) { - Ok(ffi_schema) => { - std::ptr::write(out, ffi_schema); - KernelStatusCode::Success + let schema = match inner { + ResultStreamInner::Owned { schema, .. } => schema.clone(), + ResultStreamInner::Executed { exec, valid } => match executed_ref(*exec, valid) { + Ok(e) => e.schema(), + Err(code) => return code, + }, + }; + match FFI_ArrowSchema::try_from(schema.as_ref()) { + Ok(ffi_schema) => { + std::ptr::write(out, ffi_schema); + KernelStatusCode::Success + } + Err(e) => store_and_code(Error::from(e)), } - Err(e) => store_error(Error::from(e)), - } + }) } /// Export the next batch as an `FFI_ArrowArray` (+ its `FFI_ArrowSchema`). @@ -140,67 +176,83 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( out_array: *mut FFI_ArrowArray, out_schema: *mut FFI_ArrowSchema, ) -> KernelStatusCode { - crate::c_abi::error::clear_error(); - let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { - return store_null("kernel_result_stream_next_batch: stream must not be null"); - }; - if out_array.is_null() || out_schema.is_null() { - return store_null("kernel_result_stream_next_batch: out pointers must not be null"); - } + catch_ffi(|| { + let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { + return store_invalid_arg("kernel_result_stream_next_batch: stream must not be null"); + }; + if out_array.is_null() || out_schema.is_null() { + return store_invalid_arg( + "kernel_result_stream_next_batch: out pointers must not be null", + ); + } - // Pull the next owned batch from whichever backing shape this is. - let next = match inner { - ResultStreamInner::Owned { iter, .. } => iter.next(), - ResultStreamInner::Executed { exec } => { - let Some(exec) = exec.as_mut() else { - return store_null( - "kernel_result_stream_next_batch: backing executed handle is null", - ); - }; - // Drive the executed handle's own next_batch so the - // drain-driven auto-close and lazy CloudFetch link fetches - // keep working. Convert the borrowed batch into an owned - // RecordBatch for FFI export. - match super::block_on_ffi(move || { - let exec: &mut ExecutedStatement = exec; - Box::pin(async move { - Ok(exec - .next_batch() - .await? - .map(|ResultBatch::Arrow(rb)| rb.clone())) - }) - }) { - Ok(Some(rb)) => Some(Ok(rb)), - Ok(None) => None, - Err(code) => return code, // error already stored + // 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), + ResultStreamInner::Executed { exec, valid } => { + let exec = match executed_ref(*exec, valid) { + Ok(e) => e, + Err(code) => return code, + }; + // Drive the executed handle's own next_batch so the + // drain-driven auto-close and lazy CloudFetch link fetches + // keep working. Convert the borrowed batch into an owned + // RecordBatch for FFI export. Explicit match on the + // #[non_exhaustive] ResultBatch so a future non-Arrow + // variant surfaces as a defined error, not a compile break + // with no fallback. + match super::block_on_ffi(move || { + let exec: &mut ExecutedStatement = exec; + Box::pin(async move { + #[allow( + unreachable_patterns, + reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" + )] + match exec.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 { - None => { - // End-of-stream: hand back a released (empty) array. A - // default `FFI_ArrowArray` has a null release callback, - // which the Arrow C Data Interface treats as "released". - std::ptr::write(out_array, FFI_ArrowArray::empty()); - std::ptr::write(out_schema, FFI_ArrowSchema::empty()); - KernelStatusCode::Success - } - Some(Ok(batch)) => { - // A RecordBatch maps to a StructArray for the C Data - // Interface export (the Arrow-canonical batch-as-array form). - let struct_array: arrow_array::StructArray = batch.into(); - match arrow_array::ffi::to_ffi(&struct_array.into_data()) { - Ok((ffi_array, ffi_schema)) => { - std::ptr::write(out_array, ffi_array); - std::ptr::write(out_schema, ffi_schema); - KernelStatusCode::Success + }; + + match next { + None => { + // End-of-stream: hand back a released (empty) array. A + // default `FFI_ArrowArray` has a null release callback, + // which the Arrow C Data Interface treats as "released". + std::ptr::write(out_array, FFI_ArrowArray::empty()); + std::ptr::write(out_schema, FFI_ArrowSchema::empty()); + KernelStatusCode::Success + } + Some(Ok(batch)) => { + // A RecordBatch maps to a StructArray for the C Data + // Interface export (the Arrow-canonical batch-as-array form). + let struct_array: arrow_array::StructArray = batch.into(); + match arrow_array::ffi::to_ffi(&struct_array.into_data()) { + Ok((ffi_array, ffi_schema)) => { + std::ptr::write(out_array, ffi_array); + std::ptr::write(out_schema, ffi_schema); + KernelStatusCode::Success + } + Err(e) => store_and_code(Error::from(e)), } - Err(e) => store_error(Error::from(e)), } + Some(Err(e)) => store_and_code(e), } - Some(Err(e)) => store_error(e), - } + }) } /// Free client-side resources held by the stream. Local-only; issues no @@ -217,21 +269,68 @@ pub unsafe extern "C" fn kernel_result_stream_close( ) -> KernelStatusCode { crate::c_abi::error::clear_error(); if stream.is_null() { - return store_null("kernel_result_stream_close: stream must not be null"); + return store_invalid_arg("kernel_result_stream_close: stream must not be null"); } drop(Box::from_raw(stream as *mut ResultStreamInner)); KernelStatusCode::Success } -/// Store an `InvalidArgument` for a null pointer and return its code. -fn store_null(msg: &str) -> KernelStatusCode { - crate::c_abi::error::store_error(Error::invalid_argument().message(msg)); - KernelStatusCode::InvalidArgument -} +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{Int32Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + fn one_row_batch() -> (SchemaRef, RecordBatch) { + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![7]))]) + .unwrap(); + (schema, batch) + } -/// Store a typed error and return its mapped status code. -fn store_error(e: Error) -> KernelStatusCode { - let code = KernelStatusCode::from(e.code); - crate::c_abi::error::store_error(e); - code + /// 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]); + + // First call: a real batch (release non-null). + let mut arr = FFI_ArrowArray::empty(); + let mut sch = FFI_ArrowSchema::empty(); + let rc = unsafe { kernel_result_stream_next_batch(stream, &mut arr, &mut sch) }; + assert_eq!(rc, KernelStatusCode::Success); + assert!(!arr.is_released(), "first batch should be a live array"); + + // Second call: exhausted → Success + released array. + let mut arr2 = FFI_ArrowArray::empty(); + let mut sch2 = FFI_ArrowSchema::empty(); + let rc2 = unsafe { kernel_result_stream_next_batch(stream, &mut arr2, &mut sch2) }; + assert_eq!(rc2, KernelStatusCode::Success); + assert!( + arr2.is_released(), + "exhausted stream must yield a released array" + ); + + unsafe { kernel_result_stream_close(stream) }; + } + + /// Null-pointer guards return `InvalidArgument`, never crash. + #[test] + fn null_guards_return_invalid_argument() { + let mut arr = FFI_ArrowArray::empty(); + let mut sch = FFI_ArrowSchema::empty(); + let rc = + unsafe { kernel_result_stream_next_batch(std::ptr::null_mut(), &mut arr, &mut sch) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + + let rc = unsafe { kernel_result_stream_get_schema(std::ptr::null_mut(), &mut sch) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + + let rc = unsafe { kernel_result_stream_close(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + } } diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index db018f79..3be65997 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -46,6 +46,12 @@ enum ConnectionSpec { /// Auth choice captured from the C-side setters. v0 C ABI wires PAT and /// OAuth M2M; other [`AuthConfig`] variants stay Rust-crate-only. +/// +/// NOTE (secret handling): `token` / `client_secret` are copied out of +/// the C string into owned `String`s and are not zeroized on drop, so +/// plaintext lingers in freed heap. This matches the rest of the crate +/// (no `zeroize`/`secrecy` anywhere); when the crate adopts a +/// zeroize-on-drop policy, these copies must be included. enum AuthSpec { Pat { token: String, @@ -60,26 +66,19 @@ enum AuthSpec { /// /// Constructed by [`kernel_session_config_new`], populated by the /// `kernel_session_config_set_*` setters, and consumed by -/// [`kernel_session_open`]. Heap-boxed; the C side holds a -/// `*mut KernelSessionConfig` and never sees the field layout — the -/// struct stays effectively opaque to C even though it carries real -/// fields on the Rust side. -/// -/// The `version` field leads the struct per the C-ABI versioning -/// convention (every public struct carries a `uint32_t version` so a -/// future reader can detect older callers); it is set by -/// `kernel_session_config_new` and not exposed to setters. -#[repr(C)] +/// [`kernel_session_open`]. Heap-boxed; C only ever holds a +/// `*mut KernelSessionConfig` to an incomplete type and never reads the +/// fields — so this is a private Rust-side builder box (like the boxed +/// `Session` / `Statement` handles) and is intentionally **not** +/// `#[repr(C)]`: it holds non-FFI-safe fields (`Option`, `HashMap`) and +/// a `#[repr(C)]` annotation would imply a stable C layout that neither +/// exists nor is needed. pub struct KernelSessionConfig { - /// ABI version tag. `1` for v0. - version: u32, connection: Option, auth: Option, session_conf: HashMap, } -const KERNEL_SESSION_CONFIG_VERSION: u32 = 1; - /// Read a required C string argument into an owned `String`, mapping a /// null or non-UTF-8 pointer to a typed `InvalidArgument` error. /// @@ -116,7 +115,6 @@ pub unsafe extern "C" fn kernel_session_config_new( return KernelStatusCode::InvalidArgument; } let config = Box::new(KernelSessionConfig { - version: KERNEL_SESSION_CONFIG_VERSION, connection: None, auth: None, session_conf: HashMap::new(), @@ -321,7 +319,6 @@ pub unsafe extern "C" fn kernel_session_open( /// code. fn build_session(config: KernelSessionConfig) -> Result { let KernelSessionConfig { - version: _, connection, auth, session_conf, diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 73d97795..36ae94e4 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -35,14 +35,39 @@ #![allow(non_camel_case_types)] +use super::error::{store_and_code, store_invalid_arg}; use super::result::{into_raw_executed_stream, kernel_result_stream_t}; -use super::{block_on_ffi, KernelStatusCode}; +use super::{block_on_ffi, catch_ffi, KernelStatusCode}; use crate::kernel_error::Error; use crate::statement::executed::ExecutedStatement; use crate::statement::mutable::Statement; use crate::statement::spec::TypedValue; +use crate::statement::validity::ValidityFlag; use std::ffi::{c_char, CStr}; +/// Upper bound on a positional parameter ordinal accepted over the C ABI. +/// +/// `StatementSpec::param` grows `positional_params` with +/// `Vec::resize(ordinal, Null)`, so an unbounded caller-supplied ordinal +/// (e.g. `usize::MAX`) would trigger a multi-GB allocation / capacity +/// overflow before execution. SEA itself caps parameter markers far +/// below this; 64Ki is comfortably above any real statement and cheap to +/// reject past. +const MAX_PARAM_ORDINAL: usize = 65_536; + +/// Owned box behind a `kernel_executed_statement_t`. +/// +/// Wraps the [`ExecutedStatement`] together with a [`ValidityFlag`] +/// shared with any result stream borrowed from it +/// (`kernel_executed_statement_get_result_stream`). Closing the executed +/// handle invalidates the flag *before* dropping the box, so a stream +/// used after its executed handle is closed short-circuits to +/// `InvalidStatementHandle` instead of dereferencing freed memory. +pub(crate) struct ExecutedHandle { + pub(crate) exec: ExecutedStatement, + pub(crate) stream_valid: ValidityFlag, +} + // ─── Opaque handles ────────────────────────────────────────────────────────── /// Lifecycle owner. Returned by `kernel_session_new_statement`. Boxed @@ -191,6 +216,7 @@ pub unsafe extern "C" fn kernel_statement_bind_string( Error::invalid_argument().message("string parameter value must not be null") ); } + check_ordinal(ordinal)?; let value = CStr::from_ptr(value).to_str().map_err(|_| { Error::invalid_argument().message("string parameter is not valid UTF-8") })?; @@ -210,11 +236,24 @@ unsafe fn bind_positional( value: TypedValue, ) -> KernelStatusCode { with_statement(stmt, |stmt| { + check_ordinal(ordinal)?; stmt.spec().param(ordinal, value)?; Ok(()) }) } +/// Reject an out-of-range positional ordinal before it reaches +/// `StatementSpec::param` (whose `Vec::resize(ordinal, …)` would +/// otherwise allocate unboundedly / overflow). +fn check_ordinal(ordinal: usize) -> Result<(), Error> { + if ordinal > MAX_PARAM_ORDINAL { + return Err(Error::invalid_argument().message(format!( + "positional parameter ordinal {ordinal} exceeds the maximum of {MAX_PARAM_ORDINAL}" + ))); + } + Ok(()) +} + // ─── Execute (sync) ────────────────────────────────────────────────────────── /// Wait-for-result execution. Auto-cancels + closes any prior executed @@ -222,6 +261,17 @@ unsafe fn bind_positional( /// `kernel_executed_statement_t` the caller releases with /// [`kernel_executed_statement_close`]. /// +/// **Re-execution invalidates prior handles.** Calling this again on the +/// same statement auto-cancels and closes any `kernel_executed_statement_t` +/// previously returned by it; the stale handle's calls then return +/// `KernelStatusCode::InvalidStatementHandle`. Don't retain two live +/// executed handles from one statement. +/// +/// **Panic contract.** On a `KernelStatusCode::Internal` return caused by +/// a caught panic mid-`execute`, the statement handle may be +/// half-mutated; the caller must treat it as invalid and only +/// `kernel_statement_close` it (do not re-`execute`). +/// /// # Safety /// `stmt` must be a live statement handle; `out` must be writable. #[no_mangle] @@ -231,26 +281,31 @@ pub unsafe extern "C" fn kernel_statement_execute( ) -> KernelStatusCode { crate::c_abi::error::clear_error(); let Some(stmt) = statement_mut(stmt) else { - return store_null_handle("kernel_statement_execute: stmt must not be null"); + return store_invalid_arg("kernel_statement_execute: stmt must not be null"); }; if out.is_null() { - return store_null_handle("kernel_statement_execute: out must not be null"); + return store_invalid_arg("kernel_statement_execute: out must not be null"); } // `Statement::execute` borrows `&mut self`; we need that borrow to // live across the `block_on`. Raw-pointer the statement so the // closure can re-borrow it inside the runtime without entangling - // lifetimes with `block_on_ffi`'s `'static` future bound. + // lifetimes with `block_on_ffi`'s future bound. `block_on_ffi` + // catches any panic (see the panic contract above). let stmt_ptr: *mut Statement = stmt; let executed = block_on_ffi(move || { let stmt: &mut Statement = unsafe { &mut *stmt_ptr }; Box::pin(async move { stmt.execute().await }) }); match executed { - Ok(executed) => { + Ok(exec) => { + let handle = ExecutedHandle { + exec, + stream_valid: ValidityFlag::new(), + }; std::ptr::write( out, - Box::into_raw(Box::new(executed)) as *mut kernel_executed_statement_t, + Box::into_raw(Box::new(handle)) as *mut kernel_executed_statement_t, ); KernelStatusCode::Success } @@ -268,7 +323,7 @@ pub unsafe extern "C" fn kernel_statement_execute( pub unsafe extern "C" fn kernel_statement_close(stmt: *mut kernel_statement_t) -> KernelStatusCode { crate::c_abi::error::clear_error(); if stmt.is_null() { - return store_null_handle("kernel_statement_close: stmt must not be null"); + return store_invalid_arg("kernel_statement_close: stmt must not be null"); } drop(Box::from_raw(stmt as *mut Statement)); KernelStatusCode::Success @@ -281,9 +336,11 @@ pub unsafe extern "C" fn kernel_statement_close(stmt: *mut kernel_statement_t) - /// handle's own stream, so the executed handle's drain-driven /// auto-close and lazy CloudFetch link fetches keep working. /// -/// **Lifetime:** the returned stream is valid only as long as `exec` is. -/// The caller must close the stream (`kernel_result_stream_close`) -/// before closing the executed handle (`kernel_executed_statement_close`). +/// **Lifetime:** the returned stream borrows the executed handle. Closing +/// the executed handle (`kernel_executed_statement_close`) invalidates the +/// stream: subsequent stream calls return +/// `KernelStatusCode::InvalidStatementHandle` (a defined error, not +/// undefined behaviour). Close the stream first for orderly teardown. /// /// On success `*out` holds the stream handle. /// @@ -295,19 +352,26 @@ pub unsafe extern "C" fn kernel_executed_statement_get_result_stream( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); - if exec.is_null() { - return store_null_handle("get_result_stream: exec must not be null"); - } + let Some(handle) = (exec as *mut ExecutedHandle).as_mut() else { + return store_invalid_arg("get_result_stream: exec must not be null"); + }; if out.is_null() { - return store_null_handle("get_result_stream: out must not be null"); + return store_invalid_arg("get_result_stream: out must not be null"); } - let exec_ptr = exec as *mut ExecutedStatement; - std::ptr::write(out, into_raw_executed_stream(exec_ptr)); + // Share the validity flag with the stream so an out-of-order close of + // the executed handle turns stream use into a defined error rather + // than a use-after-free. + let exec_ptr: *mut ExecutedStatement = &mut handle.exec; + std::ptr::write( + out, + into_raw_executed_stream(exec_ptr, handle.stream_valid.clone()), + ); KernelStatusCode::Success } -/// Number of rows modified by a DML statement, or `-1` if not -/// applicable / unknown. +/// Number of rows modified by a DML statement, or `-1` if not applicable +/// / unknown. `-1` with **no** stored last error means "not applicable"; +/// `-1` after a stored `InvalidArgument` means the handle was null. /// /// # Safety /// `exec` must be a live executed handle. @@ -315,13 +379,19 @@ pub unsafe extern "C" fn kernel_executed_statement_get_result_stream( pub unsafe extern "C" fn kernel_executed_statement_num_modified_rows( exec: *const kernel_executed_statement_t, ) -> i64 { - let Some(exec) = (exec as *const ExecutedStatement).as_ref() else { + crate::c_abi::error::clear_error(); + let Some(handle) = (exec as *const ExecutedHandle).as_ref() else { + crate::c_abi::error::store_invalid_arg( + "kernel_executed_statement_num_modified_rows: exec must not be null", + ); return -1; }; - exec.num_modified_rows().unwrap_or(-1) + handle.exec.num_modified_rows().unwrap_or(-1) } -/// Free a sync executed handle. +/// Free a sync executed handle. Invalidates any result stream borrowed +/// from it before dropping (so a stream outliving its handle fails +/// cleanly rather than dereferencing freed memory). /// /// # Safety /// `exec` must have been returned by [`kernel_statement_execute`] and @@ -332,9 +402,13 @@ pub unsafe extern "C" fn kernel_executed_statement_close( ) -> KernelStatusCode { crate::c_abi::error::clear_error(); if exec.is_null() { - return store_null_handle("kernel_executed_statement_close: exec must not be null"); + return store_invalid_arg("kernel_executed_statement_close: exec must not be null"); } - drop(Box::from_raw(exec as *mut ExecutedStatement)); + let handle = Box::from_raw(exec as *mut ExecutedHandle); + // Invalidate before drop so a still-open borrowed stream sees the + // handle as gone and returns InvalidStatementHandle. + handle.stream_valid.invalidate(); + drop(handle); KernelStatusCode::Success } @@ -355,16 +429,16 @@ pub unsafe extern "C" fn kernel_statement_submit( ) -> KernelStatusCode { let _ = (stmt, out); crate::c_abi::error::clear_error(); - crate::c_abi::error::store_error(Error::invalid_argument().message( + store_invalid_arg( "async submit is not exposed over the v0 C ABI; use the synchronous execute path", - )); - KernelStatusCode::InvalidArgument + ) } // ─── Shared helpers ────────────────────────────────────────────────────────── -/// Clear the thread-local error, null-check the statement handle, run -/// `f` against the borrowed statement, and store/translate any error. +/// Null-check the statement handle and run the fallible closure `f` +/// against the borrowed statement, catching panics at the FFI boundary +/// (via [`catch_ffi`]) and storing/translating any typed error. /// /// # Safety /// `stmt` must be a live `*mut kernel_statement_t`. @@ -372,23 +446,15 @@ unsafe fn with_statement( stmt: *mut kernel_statement_t, f: impl FnOnce(&mut Statement) -> Result<(), Error>, ) -> KernelStatusCode { - crate::c_abi::error::clear_error(); - let Some(stmt) = statement_mut(stmt) else { - return store_null_handle("statement handle must not be null"); - }; - match f(stmt) { - Ok(()) => KernelStatusCode::Success, - Err(e) => { - let code = KernelStatusCode::from(e.code); - crate::c_abi::error::store_error(e); - code + // `catch_ffi` clears the thread-local error and guards against a + // panic unwinding across `extern "C"` (e.g. from spec mutation). + catch_ffi(|| { + let Some(stmt) = statement_mut(stmt) else { + return store_invalid_arg("statement handle must not be null"); + }; + match f(stmt) { + Ok(()) => KernelStatusCode::Success, + Err(e) => store_and_code(e), } - } -} - -/// Store an `InvalidArgument` for a null handle and return the matching -/// status code. -fn store_null_handle(msg: &str) -> KernelStatusCode { - crate::c_abi::error::store_error(Error::invalid_argument().message(msg)); - KernelStatusCode::InvalidArgument + }) } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index dc89f9b3..3d662e2b 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -125,11 +125,55 @@ static void test_open_unreachable_host_errors(void) { CHECK(err.message != NULL, "error has a message"); } +/* http_path + M2M setters accept valid input. */ +static void test_http_path_and_m2m_setters(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + KernelStatusCode rc = + kernel_session_config_set_http_path(config, "https://example.databricks.com", + "/sql/1.0/warehouses/abc123"); + CHECK(rc == KernelStatusCode_Success, "set_http_path succeeds"); + rc = kernel_session_config_set_auth_m2m(config, "client-id", "client-secret"); + CHECK(rc == KernelStatusCode_Success, "set_auth_m2m succeeds"); + kernel_session_config_free(config); +} + +/* A null required string argument to a setter → InvalidArgument. */ +static void test_setter_null_arg_rejected(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + KernelStatusCode rc = kernel_session_config_set_auth_pat(config, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_auth_pat(NULL token) → InvalidArgument"); + kernel_session_config_free(config); +} + +/* 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; + /* A null statement is fine here — the stub rejects before touching it. */ + KernelStatusCode rc = kernel_statement_submit(NULL, &out); + CHECK(rc == KernelStatusCode_InvalidArgument, "submit stub → InvalidArgument"); +} + +/* bind_* on a null statement handle → InvalidArgument, no crash. */ +static void test_bind_null_handle_rejected(void) { + KernelStatusCode rc = kernel_statement_bind_int64(NULL, 1, 42); + CHECK(rc == KernelStatusCode_InvalidArgument, "bind_int64(NULL stmt) → InvalidArgument"); + rc = kernel_statement_bind_null(NULL, 1); + CHECK(rc == KernelStatusCode_InvalidArgument, "bind_null(NULL stmt) → InvalidArgument"); + rc = kernel_statement_set_sql(NULL, "SELECT 1"); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_sql(NULL stmt) → InvalidArgument"); +} + int main(void) { test_config_lifecycle(); test_null_guards(); test_open_requires_connection_and_auth(); test_open_unreachable_host_errors(); + test_http_path_and_m2m_setters(); + test_setter_null_arg_rejected(); + test_submit_stub_rejects(); + test_bind_null_handle_rejected(); if (failures == 0) { fprintf(stderr, "\nAll C ABI smoke checks passed.\n"); From 1d8ce890195d84a7243e35f4199162e2ca93c219 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 1 Jul 2026 16:16:47 +0000 Subject: [PATCH 4/7] [PECOBLR-2096] Refresh lockfiles: arrow-array ffi feature + quinn-proto security bump MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two lockfile updates across the root + satellite (napi, pyo3) workspaces: 1. Adding the `ffi` feature to `arrow-array` in the kernel Cargo.toml changed the resolved dependency graph, leaving `napi/Cargo.lock` and `pyo3/Cargo.lock` stale — the `napi fmt + clippy + test` job builds with `--locked` and failed. Regenerate both (also picks up the kernel's own 0.1.2 -> 0.2.0 version that had drifted in pyo3). 2. Bump quinn-proto 0.11.14 -> 0.11.15 in all three lockfiles to clear RUSTSEC-2026-0185 (remote memory exhaustion via unbounded out-of-order stream reassembly; a transitive dep, patch-level bump, no API change). NOTE: the Security Scan also flags pyo3 0.26 (RUSTSEC-2026-0176/0177, fixed in 0.29). These are pre-existing on main and cannot be cleared here without upgrading the whole arrow stack: `arrow-pyarrow v57` pins `pyo3 =0.26.0`, so pyo3 can't move to 0.29 until arrow-pyarrow does. Tracked for a dedicated dependency-upgrade PR. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- Cargo.lock | 4 ++-- napi/Cargo.lock | 7 +++++-- pyo3/Cargo.lock | 8 ++++---- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2c59f7e0..9ecafd3c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1514,9 +1514,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.14" +version = "0.11.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e" dependencies = [ "bytes", "getrandom 0.3.4", diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 8ce37f53..f0bdc956 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -136,6 +136,9 @@ name = "arrow-schema" version = "57.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4cf0d4a6609679e03002167a61074a21d7b1ad9ea65e462b2c0a97f8a3b2bc6" +dependencies = [ + "bitflags", +] [[package]] name = "arrow-select" @@ -1333,9 +1336,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.14" +version = "0.11.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e" dependencies = [ "bytes", "getrandom 0.3.4", diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index ac9d847a..e0dbb0b3 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -380,7 +380,7 @@ dependencies = [ [[package]] name = "databricks-sql-kernel" -version = "0.1.2" +version = "0.2.0" dependencies = [ "arrow-array", "arrow-buffer", @@ -412,7 +412,7 @@ dependencies = [ [[package]] name = "databricks-sql-kernel-pyo3" -version = "0.1.2" +version = "0.2.0" dependencies = [ "arrow-array", "arrow-pyarrow", @@ -1368,9 +1368,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.14" +version = "0.11.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e" dependencies = [ "bytes", "getrandom 0.3.4", From 7102034dd69e3877731ea779994dcfad205c4c92 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 2 Jul 2026 07:25:24 +0000 Subject: [PATCH 5/7] [PECOBLR-2096] Address gopalldb review: FFI stale-handle + leak + filter fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five findings from @gopalldb's review of the C ABI: 1. [MINOR] kernel_session_open leaked the config box on the null-`out` error path (early-return ran before Box::from_raw). Reclaim the box up front so it drops on every guard path, honouring the "config consumed on all paths" contract. 2/4. [MAJOR] A stale executed handle (and any result stream borrowed from it) kept working after the parent statement was re-executed, instead of returning InvalidStatementHandle — the FFI's own `stream_valid` flag was disconnected from the ExecutedStatement's re-execute invalidation. Add a crate-internal ExecutedStatement::is_valid() and check it in kernel_executed_statement_{num_modified_rows,get_result_stream} and in the Executed result-stream path (executed_ref, before each deref). 3. [MAJOR] get_result_stream could be called repeatedly, handing out multiple streams that alias &mut ExecutedStatement (UB). Add a stream_taken AtomicBool to ExecutedHandle; a second call returns InvalidArgument. (Renamed the close-guard flag stream_valid -> alive to distinguish it from the re-execute validity.) 5. [MAJOR] An empty / whitespace-only / comma-only table_types_csv collapsed to Some(vec![]) — a match-nothing filter yielding zero tables — instead of "all types". Map an empty result back to None so it matches the NULL-means-unfiltered contract. cargo clippy --all-targets -D warnings / fmt clean; 670 lib tests + C smoke checks pass. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- src/c_abi/metadata.rs | 16 ++++++-- src/c_abi/result.rs | 33 +++++++++++----- src/c_abi/session.rs | 16 ++++++-- src/c_abi/statement.rs | 81 ++++++++++++++++++++++++++++++--------- src/statement/executed.rs | 11 ++++++ 5 files changed, 123 insertions(+), 34 deletions(-) diff --git a/src/c_abi/metadata.rs b/src/c_abi/metadata.rs index 1c2cba0e..1bd0e338 100644 --- a/src/c_abi/metadata.rs +++ b/src/c_abi/metadata.rs @@ -204,12 +204,22 @@ pub unsafe extern "C" fn kernel_metadata_list_tables( let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; let table_pattern = opt_pattern(table_pattern, "table_pattern")?; // Split the comma-separated table types into a borrowed slice. + // An empty / whitespace-only / comma-only CSV must mean + // "all types" (like a NULL arg), NOT "match nothing": the + // kernel treats Some(&[]) as a filter that rejects every row, + // so collapse an empty result back to None. let types_csv = opt_str(table_types_csv, "table_types")?; - let types_owned: Option> = types_csv.map(|csv| { - csv.split(',') + let types_owned: Option> = types_csv.and_then(|csv| { + let v: Vec<&str> = csv + .split(',') .map(str::trim) .filter(|s| !s.is_empty()) - .collect() + .collect(); + if v.is_empty() { + None + } else { + Some(v) + } }); session .metadata() diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 8afc873c..fce7abb2 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -98,28 +98,43 @@ pub(crate) unsafe fn into_raw_executed_stream( as *mut kernel_result_stream_t } -/// Resolve the backing `ExecutedStatement` for the `Executed` shape, -/// checking the shared validity flag first so a closed executed handle -/// yields `InvalidStatementHandle` rather than a dangling deref. +/// Resolve the backing `ExecutedStatement` for the `Executed` shape. +/// +/// Two independent stale-handle guards, checked in this order so the +/// pointer is only dereferenced once it is known to be live (either +/// failing yields `InvalidStatementHandle` rather than UB): +/// +/// 1. `alive` (shared with the executed handle, invalidated on its +/// `close`) — checked BEFORE the deref, because a closed handle has +/// been freed and the pointer would dangle. +/// 2. `ExecutedStatement::is_valid()` (the handle's own flag, flipped +/// when the parent statement is re-executed) — checked AFTER the +/// deref, since it lives on the (now known-live) object. /// /// # Safety /// Caller must hold `&mut ResultStreamInner`. unsafe fn executed_ref<'a>( exec: *mut ExecutedStatement, - valid: &ValidityFlag, + alive: &ValidityFlag, ) -> Result<&'a mut ExecutedStatement, KernelStatusCode> { - if valid.check().is_err() { + if alive.check().is_err() { return Err(store_and_code(Error::new( ErrorCode::InvalidStatementHandle, "result stream used after its executed statement was closed", ))); } - match exec.as_mut() { - Some(e) => Ok(e), - None => Err(store_invalid_arg( + let Some(e) = exec.as_mut() else { + return Err(store_invalid_arg( "result stream: backing executed handle is null", - )), + )); + }; + if !e.is_valid() { + return Err(store_and_code(Error::new( + ErrorCode::InvalidStatementHandle, + "result stream's executed statement was invalidated by a re-execute", + ))); } + Ok(e) } /// Export the schema as an `FFI_ArrowSchema`. diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 3be65997..5497ee7f 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -290,16 +290,24 @@ pub unsafe extern "C" fn kernel_session_open( out: *mut *mut kernel_session_t, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); - if config.is_null() || out.is_null() { + // The contract is "config is consumed on every path". Reclaim the box + // up front (when non-null) so it is dropped even on the argument-guard + // error paths below — otherwise a valid config + null out would leak + // the box and its owned Strings (including any auth secret). + let config = if config.is_null() { + None + } else { + Some(Box::from_raw(config)) + }; + if config.is_none() || out.is_null() { + // `config` (if Some) drops here, honouring the consume contract. crate::c_abi::error::store_error( Error::invalid_argument() .message("kernel_session_open: config and out must be non-null"), ); return KernelStatusCode::InvalidArgument; } - // Take ownership of the config box; it is dropped at end of scope on - // every path, so the caller never frees it. - let config = Box::from_raw(config); + let config = config.expect("config is Some (checked above)"); let session = match build_session(*config) { Ok(s) => s, diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 36ae94e4..9d13af2d 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -57,15 +57,26 @@ const MAX_PARAM_ORDINAL: usize = 65_536; /// Owned box behind a `kernel_executed_statement_t`. /// -/// Wraps the [`ExecutedStatement`] together with a [`ValidityFlag`] -/// shared with any result stream borrowed from it -/// (`kernel_executed_statement_get_result_stream`). Closing the executed -/// handle invalidates the flag *before* dropping the box, so a stream -/// used after its executed handle is closed short-circuits to -/// `InvalidStatementHandle` instead of dereferencing freed memory. +/// Wraps the [`ExecutedStatement`] with the state the C ABI needs to keep +/// stale-handle access defined rather than UB: +/// +/// - `alive`: a [`ValidityFlag`] shared with any borrowed result stream. +/// `kernel_executed_statement_close` invalidates it *before* dropping +/// the box, so a stream used after its executed handle is closed +/// short-circuits to `InvalidStatementHandle` instead of dereferencing +/// freed memory (out-of-order **close** guard). +/// - `stream_taken`: enforces **at most one** live result stream per +/// executed handle. Two streams would each reborrow `&mut exec` into a +/// raw pointer and alias `&mut ExecutedStatement` — UB. A second +/// `get_result_stream` returns `InvalidArgument`. +/// +/// Note the re-execute guard is separate: a result stream also checks +/// `exec.is_valid()` (the `ExecutedStatement`'s own flag, flipped when the +/// parent `Statement` is re-executed) — see `result.rs`. pub(crate) struct ExecutedHandle { pub(crate) exec: ExecutedStatement, - pub(crate) stream_valid: ValidityFlag, + pub(crate) alive: ValidityFlag, + pub(crate) stream_taken: std::sync::atomic::AtomicBool, } // ─── Opaque handles ────────────────────────────────────────────────────────── @@ -301,7 +312,8 @@ pub unsafe extern "C" fn kernel_statement_execute( Ok(exec) => { let handle = ExecutedHandle { exec, - stream_valid: ValidityFlag::new(), + alive: ValidityFlag::new(), + stream_taken: std::sync::atomic::AtomicBool::new(false), }; std::ptr::write( out, @@ -336,11 +348,16 @@ pub unsafe extern "C" fn kernel_statement_close(stmt: *mut kernel_statement_t) - /// handle's own stream, so the executed handle's drain-driven /// auto-close and lazy CloudFetch link fetches keep working. /// -/// **Lifetime:** the returned stream borrows the executed handle. Closing -/// the executed handle (`kernel_executed_statement_close`) invalidates the -/// stream: subsequent stream calls return -/// `KernelStatusCode::InvalidStatementHandle` (a defined error, not -/// undefined behaviour). Close the stream first for orderly teardown. +/// **At most one stream per handle.** A second call returns +/// `InvalidArgument` — handing out two streams would alias `&mut +/// ExecutedStatement` (UB) and corrupt the shared drain state. +/// +/// **Lifetime / validity:** the returned stream borrows the executed +/// handle. It short-circuits to `InvalidStatementHandle` (a defined +/// error, never UB) if either (a) the executed handle is closed first +/// (`kernel_executed_statement_close`), or (b) the parent statement is +/// re-executed (which invalidates this handle). Close the stream first +/// for orderly teardown. /// /// On success `*out` holds the stream handle. /// @@ -358,13 +375,31 @@ pub unsafe extern "C" fn kernel_executed_statement_get_result_stream( if out.is_null() { return store_invalid_arg("get_result_stream: out must not be null"); } - // Share the validity flag with the stream so an out-of-order close of - // the executed handle turns stream use into a defined error rather - // than a use-after-free. + // Reject if the parent statement was re-executed (this handle is stale). + if !handle.exec.is_valid() { + return store_and_code(Error::new( + crate::kernel_error::ErrorCode::InvalidStatementHandle, + "executed statement was invalidated by a re-execute on its statement", + )); + } + // At most one live stream per handle: a second reborrow of `&mut exec` + // into a raw pointer would alias `&mut ExecutedStatement` (UB). + if handle + .stream_taken + .swap(true, std::sync::atomic::Ordering::AcqRel) + { + return store_invalid_arg( + "a result stream has already been taken from this executed statement; \ + only one is allowed", + ); + } + // The stream shares `alive` (invalidated on close) for the + // out-of-order-close UAF guard; it separately calls `exec.is_valid()` + // through the pointer on each use to honour re-execute invalidation. let exec_ptr: *mut ExecutedStatement = &mut handle.exec; std::ptr::write( out, - into_raw_executed_stream(exec_ptr, handle.stream_valid.clone()), + into_raw_executed_stream(exec_ptr, handle.alive.clone()), ); KernelStatusCode::Success } @@ -386,6 +421,16 @@ pub unsafe extern "C" fn kernel_executed_statement_num_modified_rows( ); return -1; }; + // Stale after a re-execute on the parent statement → -1 with a stored + // InvalidStatementHandle (distinct from the not-applicable -1, which + // stores no error). + if !handle.exec.is_valid() { + crate::c_abi::error::store_and_code(Error::new( + crate::kernel_error::ErrorCode::InvalidStatementHandle, + "executed statement was invalidated by a re-execute on its statement", + )); + return -1; + } handle.exec.num_modified_rows().unwrap_or(-1) } @@ -407,7 +452,7 @@ pub unsafe extern "C" fn kernel_executed_statement_close( let handle = Box::from_raw(exec as *mut ExecutedHandle); // Invalidate before drop so a still-open borrowed stream sees the // handle as gone and returns InvalidStatementHandle. - handle.stream_valid.invalidate(); + handle.alive.invalidate(); drop(handle); KernelStatusCode::Success } diff --git a/src/statement/executed.rs b/src/statement/executed.rs index f8abb28d..ab496894 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -185,6 +185,17 @@ impl ExecutedStatement { self.status.num_modified_rows } + /// Whether this executed handle is still valid, i.e. the parent + /// `Statement` has not been re-executed (which flips the shared + /// `ValidityFlag` and closes this statement server-side). The C ABI + /// checks this so a stale handle — or a result stream borrowed from + /// it — returns `InvalidStatementHandle` rather than driving a + /// superseded server statement. Crate-internal; Rust-crate consumers + /// hold the handle by value and can't observe a re-execute. + pub(crate) fn is_valid(&self) -> bool { + self.valid.check().is_ok() + } + // TODO(pr23-followup): add `progress()` once the SEA server emits // a progress field. Verified empirically on 2026-05-27 that a 37s // TPC-H query against a SQL warehouse returns no From b774afae71aae670b84c1919246e0b9c747a1259 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 2 Jul 2026 08:39:18 +0000 Subject: [PATCH 6/7] [PECOBLR-2096] C ABI: add proxy + TLS session-config setters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ODBC driver's proxy / TLS / self-signed connection properties are supported features with E2E coverage (the old ADBC backend honoured them), but the v0 C ABI had no way to pass them through — so the ODBC side had to reject them, breaking the proxy/tls E2E tests. The kernel's SessionConfig already carries ProxyConfig / TlsConfig; this wires them to the C ABI. Add to src/c_abi/session.rs (and databricks_kernel.h): - kernel_session_config_set_proxy(url, username, password, bypass_hosts) → SessionConfig.proxy (ProxyConfig). url required; rest optional. - kernel_session_config_set_tls_trusted_certs(pem, len) → TlsConfig.custom_ca_cert (PEM bundle bytes). - kernel_session_config_set_tls_allow_self_signed(bool) → TlsConfig.accept_self_signed. - kernel_session_config_set_tls_skip_hostname_verification(bool) → TlsConfig.skip_hostname_verification. build_session only constructs a Proxy/Tls config when a knob was set, so the strict-TLS / env-var-proxy defaults are preserved otherwise. C smoke test extended to cover the new setters. cargo clippy --all-targets -D warnings / fmt clean; 670 lib tests + C smoke checks pass. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 30 +++++++ src/c_abi/session.rs | 160 ++++++++++++++++++++++++++++++++++-- tests/c/session_smoke.c | 21 +++++ 3 files changed, 206 insertions(+), 5 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 5b189bc2..18b33b3d 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -219,6 +219,36 @@ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* con const char* key, const char* value); +/* ─── Proxy / TLS (optional) ────────────────────────────────────────── + * + * All optional; defaults are: no explicit proxy (reqwest honours + * HTTP(S)_PROXY / NO_PROXY env vars) and strict TLS (system trust store, + * valid chain, hostname verified). Any setter below is a relaxation or + * override. + */ + +/* Route traffic through an HTTP/HTTPS proxy. `url` is required (e.g. + * "http://proxy.corp:8080"); `username` / `password` / `bypass_hosts` + * (comma-separated) are optional — pass NULL to omit. */ +KernelStatusCode kernel_session_config_set_proxy(KernelSessionConfig* config, const char* url, + const char* username, const char* password, + const char* bypass_hosts); + +/* Add a PEM-encoded CA-certificate bundle (`pem`/`len` bytes) to the TLS + * trust store on top of the system roots (corporate re-signing proxy / + * on-prem CA). */ +KernelStatusCode kernel_session_config_set_tls_trusted_certs(KernelSessionConfig* config, + const uint8_t* pem, size_t len); + +/* Accept self-signed / invalid server certs (disables chain validation). + * Development / on-prem only. */ +KernelStatusCode kernel_session_config_set_tls_allow_self_signed(KernelSessionConfig* config, + bool allow); + +/* Skip the certificate hostname-vs-SNI check. Development / lab only. */ +KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(KernelSessionConfig* config, + bool skip); + /* ─── Session lifecycle ───────────────────────────────────────────────*/ /* diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 5497ee7f..fe5e96fd 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}; +use crate::config::{AuthConfig, ConnectionConfig, ProxyConfig, TlsConfig}; use crate::kernel_error::Error; use crate::session::Session; use std::collections::HashMap; @@ -77,6 +77,29 @@ pub struct KernelSessionConfig { connection: Option, auth: Option, session_conf: HashMap, + /// Programmatic HTTP proxy (populated by `..._set_proxy`). `None` ⇒ + /// reqwest's env-var proxy behaviour. + proxy: Option, + /// TLS relaxations / custom trust (populated by the `..._set_tls_*` + /// setters). Defaults to the kernel's strict validation. + tls: TlsSpec, +} + +/// C-side proxy config captured from `kernel_session_config_set_proxy`. +struct ProxySpec { + url: String, + username: Option, + password: Option, + bypass_hosts: Option, +} + +/// C-side TLS config captured from the `..._set_tls_*` setters. +#[derive(Default)] +struct TlsSpec { + /// PEM-encoded CA bundle bytes (from a file the ODBC layer read). + custom_ca_cert: Option>, + accept_self_signed: bool, + skip_hostname_verification: bool, } /// Read a required C string argument into an owned `String`, mapping a @@ -118,6 +141,8 @@ pub unsafe extern "C" fn kernel_session_config_new( connection: None, auth: None, session_conf: HashMap::new(), + proxy: None, + tls: TlsSpec::default(), }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -245,6 +270,103 @@ pub unsafe extern "C" fn kernel_session_config_set_session_conf( }) } +/// Read an optional C string: null → `None`, else an owned `String` +/// (errors on non-UTF-8). +/// +/// # Safety +/// `ptr`, if non-null, must be a NUL-terminated C string. +unsafe fn optional_str(ptr: *const c_char, what: &str) -> Result, Error> { + if ptr.is_null() { + return Ok(None); + } + CStr::from_ptr(ptr) + .to_str() + .map(|s| Some(s.to_owned())) + .map_err(|_| Error::invalid_argument().message(format!("{what} is not valid UTF-8"))) +} + +/// Configure an HTTP/HTTPS proxy. `url` is required (e.g. +/// `http://proxy:8080`); `username` / `password` / `bypass_hosts` are +/// optional (pass NULL to omit). Maps to the kernel's `ProxyConfig`. +/// +/// # Safety +/// `config` must be a live config handle; `url` must be a NUL-terminated +/// C string; the optional args, if non-null, must be NUL-terminated C +/// strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_proxy( + config: *mut KernelSessionConfig, + url: *const c_char, + username: *const c_char, + password: *const c_char, + bypass_hosts: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.proxy = Some(ProxySpec { + url: required_str(url, "proxy url")?, + username: optional_str(username, "proxy username")?, + password: optional_str(password, "proxy password")?, + bypass_hosts: optional_str(bypass_hosts, "proxy bypass_hosts")?, + }); + Ok(()) + }) +} + +/// Add a PEM-encoded CA-certificate bundle (bytes) to the TLS trust store +/// on top of the system roots — for a corporate re-signing proxy or an +/// on-prem CA. Maps to `TlsConfig::custom_ca_cert`. +/// +/// # Safety +/// `config` must be a live config handle; `pem` must point to `len` +/// readable bytes. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_tls_trusted_certs( + config: *mut KernelSessionConfig, + pem: *const u8, + len: usize, +) -> KernelStatusCode { + set_on_config(config, |c| { + if pem.is_null() { + return Err(Error::invalid_argument().message("trusted certs pem must not be null")); + } + c.tls.custom_ca_cert = Some(std::slice::from_raw_parts(pem, len).to_vec()); + Ok(()) + }) +} + +/// Accept self-signed / otherwise-invalid server certificates (disables +/// chain validation). Dev/on-prem only. Maps to +/// `TlsConfig::accept_self_signed`. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_tls_allow_self_signed( + config: *mut KernelSessionConfig, + allow: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.tls.accept_self_signed = allow; + Ok(()) + }) +} + +/// Skip the certificate hostname-vs-SNI check. Dev/lab only. Maps to +/// `TlsConfig::skip_hostname_verification`. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_tls_skip_hostname_verification( + config: *mut KernelSessionConfig, + skip: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.tls.skip_hostname_verification = skip; + Ok(()) + }) +} + /// Shared body for the config setters: null-check the handle, clear the /// thread-local error, run `f` against the borrowed config, and store /// any error. @@ -330,6 +452,8 @@ fn build_session(config: KernelSessionConfig) -> Result Result AuthConfig::oauth_m2m(Some(client_id), Some(client_secret), None, None)?, }; - Session::builder() + let mut builder = Session::builder() .connection(connection) .auth(auth) - .session_conf(session_conf) - .open() - .await + .session_conf(session_conf); + + // Programmatic proxy (env-var behaviour preserved when unset). + if let Some(p) = proxy { + builder = builder.proxy(ProxyConfig { + url: Some(p.url), + username: p.username, + password: p.password, + bypass_hosts: p.bypass_hosts, + ..ProxyConfig::default() + }); + } + + // TLS relaxations / custom trust. Only build a TlsConfig when a + // non-default knob was set, so the strict default is preserved + // otherwise. + if tls.custom_ca_cert.is_some() + || tls.accept_self_signed + || tls.skip_hostname_verification + { + builder = builder.tls(TlsConfig { + custom_ca_cert: tls.custom_ca_cert, + accept_self_signed: tls.accept_self_signed, + skip_hostname_verification: tls.skip_hostname_verification, + ..TlsConfig::default() + }); + } + + builder.open().await }) }) } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 3d662e2b..e1f0b588 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -147,6 +147,26 @@ static void test_setter_null_arg_rejected(void) { kernel_session_config_free(config); } +/* Proxy + TLS setters accept valid input. */ +static void test_proxy_and_tls_setters(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + KernelStatusCode rc = + kernel_session_config_set_proxy(config, "http://localhost:3128", "u", "p", "localhost"); + CHECK(rc == KernelStatusCode_Success, "set_proxy succeeds"); + rc = kernel_session_config_set_proxy(config, NULL, NULL, NULL, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_proxy(NULL url) → InvalidArgument"); + + const unsigned char pem[] = "-----BEGIN CERTIFICATE-----\n"; + rc = kernel_session_config_set_tls_trusted_certs(config, pem, sizeof(pem) - 1); + CHECK(rc == KernelStatusCode_Success, "set_tls_trusted_certs succeeds"); + rc = kernel_session_config_set_tls_allow_self_signed(config, true); + CHECK(rc == KernelStatusCode_Success, "set_tls_allow_self_signed succeeds"); + rc = kernel_session_config_set_tls_skip_hostname_verification(config, true); + CHECK(rc == KernelStatusCode_Success, "set_tls_skip_hostname_verification succeeds"); + kernel_session_config_free(config); +} + /* 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; @@ -172,6 +192,7 @@ int main(void) { test_open_unreachable_host_errors(); test_http_path_and_m2m_setters(); test_setter_null_arg_rejected(); + test_proxy_and_tls_setters(); test_submit_stub_rejects(); test_bind_null_handle_rejected(); From bd17c8b8a6cb3cf4c1b0a56d82ea77800c7040d5 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 2 Jul 2026 10:07:29 +0000 Subject: [PATCH 7/7] [PECOBLR-2096] C ABI: correct handle-teardown + metadata contracts, guard reentrancy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses gopalldb's review on #158. [MAJOR] kernel_statement_close vs. executed-handle independence The header implied executed handles are usable after kernel_statement_close ("close each of those separately"), but a Statement shares a ValidityFlag with the executed handles it produces and Statement::Drop invalidates it — by design, so ExecutedStatement::cancel short-circuits cheaply on a zombie handle (pinned by kernel_invariant_parent_drop_invalidates_executed_cancel, relied on by the napi binding). Rather than weaken that tested invariant, correct the contract: databricks_kernel.h + the Rust docs now state the statement must be closed LAST — drain/close result streams, then executed handles, then the statement — and the InvalidStatementHandle messages on get_result_stream / num_modified_rows / result-stream next_batch now name "re-execute or close" and point at the ordering. (The ODBC driver already tears down in this order.) [MINOR] primary_keys / foreign_keys NULL contract The metadata header said "NULL string args mean unfiltered" blanket, but primary_keys requires catalog+schema+table and foreign_keys requires the full foreign_* triple (Databricks SHOW KEYS needs a qualified target) — NULL yields InvalidArgument. Scoped the "unfiltered" wording to the list_* calls and documented the required identifiers per-function. [MINOR] block_on_ffi reentrancy Called from a thread already inside a Tokio runtime, Runtime::block_on panics ("runtime within a runtime") and the catch_unwind arm degraded it to a generic Internal. Detect Handle::try_current() up front and return a typed Internal with an actionable message documenting the native-thread contract. Added a unit test. cargo fmt / clippy --all-targets clean; 671 lib tests + C smoke pass. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 47 ++++++++++++++++++++++++++---- src/c_abi/mod.rs | 58 +++++++++++++++++++++++++++++++++++++ src/c_abi/result.rs | 10 ++++--- src/c_abi/statement.rs | 24 ++++++++++----- 4 files changed, 123 insertions(+), 16 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 18b33b3d..4d2fdcf5 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -296,7 +296,18 @@ KernelStatusCode kernel_statement_submit(kernel_statement_t* stmt, /* * Free the statement lifecycle owner. Does NOT free executed-handle - * boxes; close each of those separately. + * boxes — each executed handle is a separate allocation that you must + * release with `kernel_executed_statement_close`. + * + * ORDERING: close the statement LAST. Executed handles produced by this + * statement (and any result stream borrowed from them) share a validity + * flag with the statement; closing the statement invalidates them, after + * which `kernel_executed_statement_get_result_stream`, + * `kernel_executed_statement_num_modified_rows`, and + * `kernel_result_stream_next_batch` on those handles return + * `KernelStatusCode_InvalidStatementHandle` (a defined error, never UB). + * Drain / close the result stream, then the executed handle(s), then the + * statement. The statement must outlive every handle it produced. */ KernelStatusCode kernel_statement_close(kernel_statement_t* stmt); @@ -305,12 +316,22 @@ KernelStatusCode kernel_statement_close(kernel_statement_t* stmt); /* * Obtain a result-stream handle that BORROWS `exec`. The stream is valid * only as long as `exec` is: close the stream - * (`kernel_result_stream_close`) before closing `exec`. + * (`kernel_result_stream_close`) before closing `exec`, and keep the + * parent statement open until the stream is drained/closed (see + * `kernel_statement_close`). At most one stream per executed handle; a + * second call returns `KernelStatusCode_InvalidArgument`. Returns + * `KernelStatusCode_InvalidStatementHandle` if the parent statement was + * re-executed or closed. */ KernelStatusCode kernel_executed_statement_get_result_stream(kernel_executed_statement_t* exec, kernel_result_stream_t** out); -/* Rows modified by a DML statement, or -1 if not applicable / unknown. */ +/* + * Rows modified by a DML statement, or -1 if not applicable / unknown. + * A -1 with NO stored last error means "not applicable"; a -1 after a + * stored `InvalidStatementHandle` means the parent statement was + * re-executed or closed (call `kernel_get_last_error` to distinguish). + */ int64_t kernel_executed_statement_num_modified_rows(const kernel_executed_statement_t* exec); KernelStatusCode kernel_executed_statement_close(kernel_executed_statement_t* exec); @@ -332,8 +353,17 @@ KernelStatusCode kernel_result_stream_close(kernel_result_stream_t* stream); * * Each returns a self-contained result stream (released via * `kernel_result_stream_close`) carrying the server-shaped - * (JDBC-canonical) columns. NULL string args mean "unfiltered". Pattern - * args accept SQL LIKE wildcards; identifier args are exact. + * (JDBC-canonical) columns. Pattern args accept SQL LIKE wildcards; + * identifier args are exact. + * + * NULL string args mean "unfiltered" for the list_* calls (catalogs / + * schemas / tables / columns). The key/constraint calls are stricter: + * `kernel_metadata_primary_keys` requires a non-NULL catalog, schema, AND + * table (Databricks SHOW KEYS must target a fully-qualified table), and + * `kernel_metadata_foreign_keys` requires the full foreign_* (referencing) + * triple while the parent_* (referenced) triple is optional. Passing NULL + * for a required identifier returns `KernelStatusCode_InvalidArgument` + * with an explanatory last error (see each function's comment). */ KernelStatusCode kernel_metadata_list_catalogs(kernel_session_t* session, kernel_result_stream_t** out); @@ -348,9 +378,16 @@ KernelStatusCode kernel_metadata_list_columns(kernel_session_t* session, const c const char* schema_pattern, const char* table_pattern, const char* column_pattern, kernel_result_stream_t** out); +/* `catalog`, `schema`, and `table` are all REQUIRED (non-NULL): the + * underlying SHOW KEYS targets a fully-qualified table. NULL for any of + * them returns `KernelStatusCode_InvalidArgument`. */ KernelStatusCode kernel_metadata_primary_keys(kernel_session_t* session, const char* catalog, const char* schema, const char* table, kernel_result_stream_t** out); +/* The foreign_* (referencing) triple is REQUIRED (all non-NULL); the + * parent_* (referenced) triple is optional and filters the referenced + * side. NULL for any foreign_* arg returns + * `KernelStatusCode_InvalidArgument`. */ KernelStatusCode kernel_metadata_foreign_keys(kernel_session_t* session, const char* parent_catalog, const char* parent_schema, const char* parent_table, const char* foreign_catalog, diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index 49e1e1ff..bdb54a4c 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -105,6 +105,16 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime:: /// at the `block_on` edge and surfaced as `Internal` rather than /// unwinding across the FFI boundary (which is UB). /// +/// **Threading contract:** the C ABI must be driven from threads that are +/// NOT already running inside a Tokio runtime. `Runtime::block_on` panics +/// ("Cannot start a runtime from within a runtime") if called from a +/// worker of any runtime — including this one — so a reentrant C-ABI call +/// (e.g. a consumer that invokes a `kernel_*` entry point from a callback +/// executing on a runtime worker) is rejected up front with a clear +/// `Internal` error instead of the opaque caught-panic path. Native +/// (non-runtime) caller threads — the intended ODBC / Go usage — are +/// unaffected. +/// /// [`KernelStatusCode`]: crate::c_abi::KernelStatusCode /// [`Error`]: crate::kernel_error::Error pub(crate) fn block_on_ffi(fut_builder: F) -> Result @@ -113,6 +123,19 @@ where Fut: std::future::Future>, { error::clear_error(); + // Reject reentrancy explicitly: calling `block_on` from within any + // Tokio runtime would panic. Surface a typed, actionable error rather + // than a caught panic mapped to a generic `Internal`. + if tokio::runtime::Handle::try_current().is_ok() { + let e = crate::kernel_error::Error::new( + crate::kernel_error::ErrorCode::Internal, + "kernel C ABI called from within a Tokio runtime thread; entry points must be \ + invoked from a native (non-async-runtime) thread", + ); + let code = KernelStatusCode::from(e.code); + error::store_error(e); + return Err(code); + } let rt = match runtime() { Ok(rt) => rt, Err(e) => { @@ -245,3 +268,38 @@ impl From for KernelStatusCode { } } } + +#[cfg(test)] +mod tests { + use super::*; + + /// `block_on_ffi` must reject a reentrant call (one made from a thread + /// already inside a Tokio runtime) with a typed `Internal` error and a + /// populated last-error, rather than letting `Runtime::block_on` panic + /// into the caught-panic path (which also maps to `Internal` but loses + /// the actionable message). Guards the threading contract documented on + /// `block_on_ffi`. + #[test] + fn block_on_ffi_rejects_reentrancy_from_runtime_thread() { + let rt = tokio::runtime::Runtime::new().expect("runtime"); + rt.block_on(async { + let result: Result<(), KernelStatusCode> = block_on_ffi(|| async { Ok(()) }); + assert_eq!(result, Err(KernelStatusCode::Internal)); + + let mut out = std::mem::MaybeUninit::::uninit(); + // SAFETY: out is a valid writable pointer. + let present = unsafe { crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr()) }; + assert!(present, "reentrancy must populate the last-error buffer"); + // SAFETY: present is true, so out is initialised. + let err = unsafe { out.assume_init() }; + // SAFETY: message is non-null after a store. + let msg = unsafe { std::ffi::CStr::from_ptr(err.message) } + .to_str() + .unwrap(); + assert!( + msg.contains("within a Tokio runtime"), + "reentrancy error should explain the threading contract, got: {msg}", + ); + }); + } +} diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index fce7abb2..5682d9aa 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -107,9 +107,10 @@ pub(crate) unsafe fn into_raw_executed_stream( /// 1. `alive` (shared with the executed handle, invalidated on its /// `close`) — checked BEFORE the deref, because a closed handle has /// been freed and the pointer would dangle. -/// 2. `ExecutedStatement::is_valid()` (the handle's own flag, flipped -/// when the parent statement is re-executed) — checked AFTER the -/// deref, since it lives on the (now known-live) object. +/// 2. `ExecutedStatement::is_valid()` (the flag shared with the parent +/// statement, flipped when that statement is re-executed OR closed) — +/// checked AFTER the deref, since it lives on the (now known-live) +/// object. This is why the parent statement must outlive the stream. /// /// # Safety /// Caller must hold `&mut ResultStreamInner`. @@ -131,7 +132,8 @@ unsafe fn executed_ref<'a>( if !e.is_valid() { return Err(store_and_code(Error::new( ErrorCode::InvalidStatementHandle, - "result stream's executed statement was invalidated by a re-execute", + "result stream's executed statement was invalidated by a re-execute or close on its \ + parent statement; drain/close the stream before closing the statement", ))); } Ok(e) diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 9d13af2d..0ee34b94 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -326,7 +326,14 @@ pub unsafe extern "C" fn kernel_statement_execute( } /// Free the statement-lifecycle owner. Does not free executed-handle -/// boxes (those are owned independently); see the spec contract. +/// boxes (those are separate allocations, closed via +/// `kernel_executed_statement_close`). +/// +/// Close the statement LAST: it shares a validity flag with the executed +/// handles it produced, so closing it invalidates any still-live executed +/// handle (and its borrowed result stream), which then return +/// `InvalidStatementHandle` on further use. Drain/close streams and +/// executed handles first. See the `databricks_kernel.h` contract. /// /// # Safety /// `stmt` must have been returned by `kernel_session_new_statement` and @@ -375,11 +382,13 @@ pub unsafe extern "C" fn kernel_executed_statement_get_result_stream( if out.is_null() { return store_invalid_arg("get_result_stream: out must not be null"); } - // Reject if the parent statement was re-executed (this handle is stale). + // Reject if the parent statement was re-executed or closed (this + // handle shares the statement's validity flag; both flip it). if !handle.exec.is_valid() { return store_and_code(Error::new( crate::kernel_error::ErrorCode::InvalidStatementHandle, - "executed statement was invalidated by a re-execute on its statement", + "executed statement was invalidated by a re-execute or close on its parent statement; \ + drain/close result streams and executed handles before closing the statement", )); } // At most one live stream per handle: a second reborrow of `&mut exec` @@ -421,13 +430,14 @@ pub unsafe extern "C" fn kernel_executed_statement_num_modified_rows( ); return -1; }; - // Stale after a re-execute on the parent statement → -1 with a stored - // InvalidStatementHandle (distinct from the not-applicable -1, which - // stores no error). + // Stale after a re-execute or close on the parent statement → -1 with + // a stored InvalidStatementHandle (distinct from the not-applicable + // -1, which stores no error). if !handle.exec.is_valid() { crate::c_abi::error::store_and_code(Error::new( crate::kernel_error::ErrorCode::InvalidStatementHandle, - "executed statement was invalidated by a re-execute on its statement", + "executed statement was invalidated by a re-execute or close on its parent statement; \ + query num_modified_rows before closing the statement", )); return -1; }