diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index e7a96734..76be5308 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/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 + check-tls-rustls: name: Build (tls-rustls feature) runs-on: diff --git a/Cargo.lock b/Cargo.lock index 1c7ac8ee..9ecafd3c 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" @@ -1511,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/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..4d2fdcf5 --- /dev/null +++ b/include/databricks_kernel.h @@ -0,0 +1,401 @@ +/* + * 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/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: + * 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 + * + * 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 +#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::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). + */ +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; +/* 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 ────────────────────────────────────────────────── + * + * 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); + +/* ─── 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 ───────────────────────────────────────────────*/ + +/* + * 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); + +/* + * 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 — 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); + +/* ─── 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`, 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. + * 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); + +/* ─── 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. 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); +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); +/* `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, + 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/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", diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs new file mode 100644 index 00000000..28503f4b --- /dev/null +++ b/src/c_abi/error.rs @@ -0,0 +1,282 @@ +// 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. + +//! Thread-local last-error storage and the `kernel_get_last_error` C +//! entry point. +//! +//! Pattern borrowed from the legacy `src/adbc/ffi/error.rs`: every C +//! function clears the buffer at entry and writes to it on error; +//! callers fetch detail with `kernel_get_last_error`. + +use super::KernelStatusCode; +use crate::kernel_error::Error; +use std::cell::RefCell; +use std::ffi::{c_char, CString}; + +/// Mirror of `crate::kernel_error::Error` in `repr(C)` form. +/// +/// String fields are owned by the kernel's thread-local buffer; the +/// caller copies them out before the next FFI call on this thread +/// clears the buffer. Pointers are nullable for fields the underlying +/// `Error` left as `None`. +#[repr(C)] +pub struct KernelError { + /// Discriminant matches `KernelStatusCode` (cast-equal). Use + /// `KernelStatusCode::from(error.code)` on the Rust side to + /// convert; the i32 here is the discriminant value of that enum. + pub code: i32, + pub message: *const c_char, + /// 5 ASCII chars + NUL, or null if absent. + pub sql_state: *const c_char, + /// `0` if absent (the underlying `Error::vendor_code` was `None`). + pub vendor_code: i32, + /// `0` if absent. + pub http_status: u16, + pub retryable: bool, + 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_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 +/// pointer fields it returns are valid until the next FFI call on +/// this thread. +#[no_mangle] +pub unsafe extern "C" fn kernel_get_last_error(out: *mut KernelError) -> bool { + 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 +/// last-error buffer. Every FFI function that returns a non-`Success` +/// 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) { + 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 (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() { + 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::*; + + /// 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/c_abi/metadata.rs b/src/c_abi/metadata.rs new file mode 100644 index 00000000..1bd0e338 --- /dev/null +++ b/src/c_abi/metadata.rs @@ -0,0 +1,340 @@ +// 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. + +//! 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::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::{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` +/// (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), + } +} + +/// Drain a metadata `ResultStream` fully into owned batches **on the +/// runtime** (this runs inside `block_on_ffi`), capturing the schema. +/// +/// Metadata results are bounded (a handful of batches at most), so full +/// materialisation here is cheap and lets the C-side `next_batch` be a +/// pure in-memory pop — avoiding driving a possibly-CloudFetch-backed +/// reader off the tokio reactor from a plain C thread. +async fn drain_metadata(mut stream: ResultStream) -> Result<(SchemaRef, Vec)> { + let schema = stream.schema(); + let mut batches = Vec::new(); + while let Some(batch) = stream.next_batch().await? { + // `ResultBatch` is `#[non_exhaustive]`; the wildcard is unreachable + // today (Arrow is the only variant) but is the defined fallback + // for a future non-Arrow variant at this Arrow-only boundary. + #[allow( + unreachable_patterns, + reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" + )] + match batch { + ResultBatch::Arrow(rb) => batches.push(rb.clone()), + _ => { + return Err(Error::not_implemented().message( + "metadata stream yielded a non-Arrow batch; C ABI exports Arrow only", + )) + } + } + } + Ok((schema, batches)) +} + +/// Shared body for the metadata entry points: clear the error, null-check +/// `session` / `out`, run the async builder on the runtime, and write the +/// resulting owned stream handle. +/// +/// # 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::c_abi::error::clear_error(); + let Some(session) = (session as *const Session).as_ref() else { + return store_invalid_arg("metadata: session must not be null"); + }; + if out.is_null() { + return store_invalid_arg("metadata: out must not be null"); + } + let result = block_on_ffi(move || async move { + let stream = build(session).await?; + drain_metadata(stream).await + }); + match result { + Ok((schema, batches)) => { + std::ptr::write(out, into_raw_result_stream(schema, batches)); + 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 kernel_result_stream_t, +) -> KernelStatusCode { + 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 kernel_result_stream_t, +) -> KernelStatusCode { + 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_pattern: *const c_char, + table_pattern: *const c_char, + table_types_csv: *const c_char, + out: *mut *mut kernel_result_stream_t, +) -> KernelStatusCode { + 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. + // 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.and_then(|csv| { + let v: Vec<&str> = csv + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect(); + if v.is_empty() { + None + } else { + Some(v) + } + }); + 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_pattern: *const c_char, + table_pattern: *const c_char, + column_pattern: *const c_char, + out: *mut *mut kernel_result_stream_t, +) -> KernelStatusCode { + 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 kernel_result_stream_t, +) -> KernelStatusCode { + 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 + }) + }) +} + +// 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/c_abi/mod.rs b/src/c_abi/mod.rs new file mode 100644 index 00000000..bdb54a4c --- /dev/null +++ b/src/c_abi/mod.rs @@ -0,0 +1,305 @@ +// 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. + +//! Custom C ABI for the v0 Kernel — for ODBC and Go consumers that +//! cannot link the Rust crate directly. +//! +//! Per `docs/spec-v0.md` "Architecture", this layer is a thin shim over +//! the async kernel core: it owns a process-wide tokio runtime, marshals +//! 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 +// that bodies have landed. + +pub mod error; +pub mod metadata; +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). +/// +/// **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 +where + F: FnOnce() -> Fut, + 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) => { + 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) => 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 { + 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 +/// [`From`] conversion below uses an exhaustive match (no +/// `_ =>` arm) so adding a variant to `ErrorCode` is a compile error +/// here until `KernelStatusCode` grows the matching variant. That +/// catches FFI/Rust drift mechanically. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum KernelStatusCode { + Success = 0, + InvalidArgument = 1, + Unauthenticated = 2, + PermissionDenied = 3, + NotFound = 4, + ResourceExhausted = 5, + Unavailable = 6, + Timeout = 7, + Cancelled = 8, + DataLoss = 9, + Internal = 10, + InvalidStatementHandle = 11, + NetworkError = 12, + SqlError = 13, +} + +impl From for KernelStatusCode { + fn from(code: crate::kernel_error::ErrorCode) -> Self { + use crate::kernel_error::ErrorCode; + // Exhaustive match — no `_ =>` arm. Adding a variant to + // `ErrorCode` is a compile error here, forcing the FFI to + // declare the corresponding `KernelStatusCode` variant. + match code { + ErrorCode::InvalidArgument => Self::InvalidArgument, + ErrorCode::Unauthenticated => Self::Unauthenticated, + ErrorCode::PermissionDenied => Self::PermissionDenied, + ErrorCode::NotFound => Self::NotFound, + ErrorCode::ResourceExhausted => Self::ResourceExhausted, + ErrorCode::Unavailable => Self::Unavailable, + ErrorCode::Timeout => Self::Timeout, + ErrorCode::Cancelled => Self::Cancelled, + ErrorCode::DataLoss => Self::DataLoss, + ErrorCode::Internal => Self::Internal, + ErrorCode::InvalidStatementHandle => Self::InvalidStatementHandle, + ErrorCode::NetworkError => Self::NetworkError, + ErrorCode::SqlError => Self::SqlError, + } + } +} + +#[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 new file mode 100644 index 00000000..5682d9aa --- /dev/null +++ b/src/c_abi/result.rs @@ -0,0 +1,353 @@ +// 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. + +//! Result FFI — exports a result stream via the Arrow C Data Interface. +//! +//! `kernel_result_stream_get_schema` / `kernel_result_stream_next_batch` +//! 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(non_camel_case_types)] + +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, RecordBatch}; + +/// Opaque result-stream handle. Boxed [`ResultStreamInner`]. +#[repr(C)] +pub struct kernel_result_stream_t { + _private: [u8; 0], +} + +/// Backing state for a result-stream handle. +enum ResultStreamInner { + /// Self-contained owned stream (metadata path). The batches are + /// **fully drained on the runtime at construction** (metadata results + /// are bounded), so iterating here is pure in-memory — no tokio + /// reactor needed, sidestepping the off-runtime CloudFetch hang. + Owned { + schema: SchemaRef, + batches: std::vec::IntoIter, + }, + /// Borrow of the executed statement that produced this stream + /// (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 +/// 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, + batches: Vec, +) -> *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). `valid` is shared +/// with the executed handle and invalidated when it is closed. +/// +/// # Safety +/// `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, valid })) + as *mut kernel_result_stream_t +} + +/// Resolve the backing `ExecutedStatement` for the `Executed` shape. +/// +/// Two independent stale-handle guards, checked in this order so the +/// 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 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`. +unsafe fn executed_ref<'a>( + exec: *mut ExecutedStatement, + alive: &ValidityFlag, +) -> Result<&'a mut ExecutedStatement, KernelStatusCode> { + if alive.check().is_err() { + return Err(store_and_code(Error::new( + ErrorCode::InvalidStatementHandle, + "result stream used after its executed statement was closed", + ))); + } + 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 or close on its \ + parent statement; drain/close the stream before closing the statement", + ))); + } + Ok(e) +} + +/// 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, +) -> KernelStatusCode { + 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"); + } + 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)), + } + }) +} + +/// 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_array: *mut FFI_ArrowArray, + out_schema: *mut FFI_ArrowSchema, +) -> KernelStatusCode { + 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: 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 + } + Err(e) => store_and_code(Error::from(e)), + } + } + Some(Err(e)) => store_and_code(e), + } + }) +} + +/// 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 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 { + crate::c_abi::error::clear_error(); + if stream.is_null() { + return store_invalid_arg("kernel_result_stream_close: stream must not be null"); + } + drop(Box::from_raw(stream as *mut ResultStreamInner)); + KernelStatusCode::Success +} + +#[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) + } + + /// 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 new file mode 100644 index 00000000..fe5e96fd --- /dev/null +++ b/src/c_abi/session.rs @@ -0,0 +1,580 @@ +// 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. + +//! 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. + +use super::{block_on_ffi, KernelStatusCode}; +use crate::config::{AuthConfig, ConnectionConfig, ProxyConfig, TlsConfig}; +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. +#[repr(C)] +pub struct kernel_session_t { + _private: [u8; 0], +} + +/// 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. +/// +/// 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, + }, + 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; 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 { + 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 +/// null or non-UTF-8 pointer to a typed `InvalidArgument` error. +/// +/// # 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 +/// `out` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_new( + out: *mut *mut KernelSessionConfig, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + if out.is_null() { + crate::c_abi::error::store_error( + Error::invalid_argument().message("kernel_session_config_new: out must not be null"), + ); + return KernelStatusCode::InvalidArgument; + } + let config = Box::new(KernelSessionConfig { + connection: None, + auth: None, + session_conf: HashMap::new(), + proxy: None, + tls: TlsSpec::default(), + }); + 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(()) + }) +} + +/// 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. +/// +/// # 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::c_abi::error::clear_error(); + let Some(config) = config.as_mut() else { + crate::c_abi::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::c_abi::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: *mut KernelSessionConfig, + out: *mut *mut kernel_session_t, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + // 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; + } + let config = config.expect("config is Some (checked above)"); + + 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 { + connection, + auth, + session_conf, + proxy, + tls, + } = 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)?, + }; + + let mut builder = Session::builder() + .connection(connection) + .auth(auth) + .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 + }) + }) +} + +/// 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. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + if session.is_null() { + crate::c_abi::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. On success, +/// `*out` holds an owned `kernel_statement_t` the 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 { + crate::c_abi::error::clear_error(); + if session.is_null() || out.is_null() { + crate::c_abi::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): +// +// pub unsafe extern "C" fn kernel_session_set_autocommit(...) -> KernelStatusCode; +// pub unsafe extern "C" fn kernel_session_commit(...) -> KernelStatusCode; +// pub unsafe extern "C" fn kernel_session_rollback(...) -> KernelStatusCode; diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs new file mode 100644 index 00000000..0ee34b94 --- /dev/null +++ b/src/c_abi/statement.rs @@ -0,0 +1,515 @@ +// 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. + +//! 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::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. + +#![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, 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`] 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) alive: ValidityFlag, + pub(crate) stream_taken: std::sync::atomic::AtomicBool, +} + +// ─── Opaque handles ────────────────────────────────────────────────────────── + +/// 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`]. Boxed [`ExecutedStatement`]. +#[repr(C)] +pub struct kernel_executed_statement_t { + _private: [u8; 0], +} + +/// Async-consumption executed handle. Returned by +/// `kernel_statement_submit` (deferred in v0 — see module docs). +#[repr(C)] +pub struct kernel_executed_async_statement_t { + _private: [u8; 0], +} + +/// Server-side execution status — C-side mirror of +/// [`crate::statement::executed_async::StatementStatus`]. +/// +/// `#[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 { + Pending = 0, + Running = 1, + Succeeded = 2, + /// Server-side execution failed. Call `kernel_get_last_error` for + /// the underlying `KernelError`. + Failed = 3, + Cancelled = 4, + Closed = 5, +} + +// ─── Crate-internal raw-handle helpers ─────────────────────────────────────── + +/// 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 +} + +/// 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. +/// +/// # 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_set_sql( + stmt: *mut kernel_statement_t, + sql: *const c_char, +) -> KernelStatusCode { + 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_bind_null( + stmt: *mut kernel_statement_t, + ordinal: usize, +) -> KernelStatusCode { + bind_positional(stmt, ordinal, TypedValue::Null) +} + +/// Bind a 1-based positional `BIGINT` parameter. +/// +/// # Safety +/// `stmt` must be a live statement handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_bind_int64( + stmt: *mut kernel_statement_t, + ordinal: usize, + value: i64, +) -> KernelStatusCode { + bind_positional(stmt, ordinal, TypedValue::Int64(value)) +} + +/// Bind a 1-based positional `DOUBLE` parameter. +/// +/// # Safety +/// `stmt` must be a live statement handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_bind_double( + stmt: *mut kernel_statement_t, + ordinal: usize, + value: f64, +) -> KernelStatusCode { + bind_positional(stmt, ordinal, TypedValue::Float64(value)) +} + +/// Bind a 1-based positional `BOOLEAN` parameter. +/// +/// # Safety +/// `stmt` must be a live statement handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_bind_bool( + stmt: *mut kernel_statement_t, + ordinal: usize, + value: bool, +) -> KernelStatusCode { + bind_positional(stmt, ordinal, TypedValue::Bool(value)) +} + +/// Bind a 1-based positional `STRING` parameter. +/// +/// # 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") + ); + } + check_ordinal(ordinal)?; + 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. +/// +/// # 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| { + 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 +/// handle from this statement. On success, `*out` holds an owned +/// `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] +pub unsafe extern "C" fn kernel_statement_execute( + stmt: *mut kernel_statement_t, + out: *mut *mut kernel_executed_statement_t, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(stmt) = statement_mut(stmt) else { + return store_invalid_arg("kernel_statement_execute: stmt must not be null"); + }; + if out.is_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 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(exec) => { + let handle = ExecutedHandle { + exec, + alive: ValidityFlag::new(), + stream_taken: std::sync::atomic::AtomicBool::new(false), + }; + std::ptr::write( + out, + Box::into_raw(Box::new(handle)) as *mut kernel_executed_statement_t, + ); + KernelStatusCode::Success + } + Err(code) => code, + } +} + +/// Free the statement-lifecycle owner. Does not free executed-handle +/// 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 +/// not previously closed. +#[no_mangle] +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_invalid_arg("kernel_statement_close: stmt must not be null"); + } + drop(Box::from_raw(stmt as *mut Statement)); + KernelStatusCode::Success +} + +// ─── ExecutedStatement (sync) ──────────────────────────────────────────────── + +/// 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. +/// +/// **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. +/// +/// # 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 kernel_result_stream_t, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + 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_invalid_arg("get_result_stream: out must not be null"); + } + // 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 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` + // 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.alive.clone()), + ); + KernelStatusCode::Success +} + +/// 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. +#[no_mangle] +pub unsafe extern "C" fn kernel_executed_statement_num_modified_rows( + exec: *const kernel_executed_statement_t, +) -> i64 { + 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; + }; + // 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 or close on its parent statement; \ + query num_modified_rows before closing the statement", + )); + return -1; + } + handle.exec.num_modified_rows().unwrap_or(-1) +} + +/// 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 +/// not previously closed. +#[no_mangle] +pub unsafe extern "C" fn kernel_executed_statement_close( + exec: *mut kernel_executed_statement_t, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + if exec.is_null() { + return store_invalid_arg("kernel_executed_statement_close: exec must not be null"); + } + 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.alive.invalidate(); + drop(handle); + KernelStatusCode::Success +} + +// ─── 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. + +/// Submit-and-return. **Deferred in v0** — see module docs. +/// +/// # Safety +/// `stmt` / `out` must be valid pointers. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_submit( + stmt: *mut kernel_statement_t, + out: *mut *mut kernel_executed_async_statement_t, +) -> KernelStatusCode { + let _ = (stmt, out); + crate::c_abi::error::clear_error(); + store_invalid_arg( + "async submit is not exposed over the v0 C ABI; use the synchronous execute path", + ) +} + +// ─── Shared helpers ────────────────────────────────────────────────────────── + +/// 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`. +unsafe fn with_statement( + stmt: *mut kernel_statement_t, + f: impl FnOnce(&mut Statement) -> Result<(), Error>, +) -> KernelStatusCode { + // `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), + } + }) +} diff --git a/src/ffi/error.rs b/src/ffi/error.rs deleted file mode 100644 index 196b5583..00000000 --- a/src/ffi/error.rs +++ /dev/null @@ -1,80 +0,0 @@ -// 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. - -//! Thread-local last-error storage and the `kernel_get_last_error` C -//! entry point. -//! -//! Pattern borrowed from the legacy `src/adbc/ffi/error.rs`: every C -//! 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 crate::kernel_error::Error; -use std::ffi::c_char; - -/// Mirror of `crate::kernel_error::Error` in `repr(C)` form. -/// -/// String fields are owned by the kernel's thread-local buffer; the -/// caller copies them out before the next FFI call on this thread -/// clears the buffer. Pointers are nullable for fields the underlying -/// `Error` left as `None`. -#[repr(C)] -pub struct KernelError { - /// Discriminant matches `KernelStatusCode` (cast-equal). Use - /// `KernelStatusCode::from(error.code)` on the Rust side to - /// convert; the i32 here is the discriminant value of that enum. - pub code: i32, - pub message: *const c_char, - /// 5 ASCII chars + NUL, or null if absent. - pub sql_state: *const c_char, - /// `0` if absent (the underlying `Error::vendor_code` was `None`). - pub vendor_code: i32, - /// `0` if absent. - pub http_status: u16, - pub retryable: bool, - pub query_id: *const c_char, -} - -/// 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). -/// -/// # Safety -/// `out` must be a valid, writable pointer to a `KernelError`. The -/// pointer fields it returns are valid until the next FFI call on -/// 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") -} - -/// 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. -pub(crate) fn store_error(err: Error) { - unimplemented!("PR 7a: serialize Error into the thread-local KernelError buffer") -} - -/// 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. -pub(crate) fn clear_error() { - unimplemented!("PR 7a: zero out the thread-local") -} diff --git a/src/ffi/metadata.rs b/src/ffi/metadata.rs deleted file mode 100644 index 0ffb476b..00000000 --- a/src/ffi/metadata.rs +++ /dev/null @@ -1,78 +0,0 @@ -// 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. - -//! 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)] - -use super::session::kernel_session_t; -use super::KernelStatusCode; -use std::ffi::c_char; - -#[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, -) -> KernelStatusCode { - unimplemented!("PR 7d") -} - -#[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, -) -> KernelStatusCode { - unimplemented!("PR 7d") -} - -#[no_mangle] -pub unsafe extern "C" fn kernel_metadata_list_tables( - session: *mut kernel_session_t, - catalog: *const c_char, - schema: *const c_char, - table_pattern: *const c_char, - table_types_csv: *const c_char, - out: *mut *mut super::result::kernel_result_stream_t, -) -> KernelStatusCode { - unimplemented!("PR 7d") -} - -#[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, - column_pattern: *const c_char, - out: *mut *mut super::result::kernel_result_stream_t, -) -> KernelStatusCode { - unimplemented!("PR 7d") -} - -#[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, -) -> KernelStatusCode { - unimplemented!("PR 7d") -} - -// PR 7d: foreign_keys, functions, procedures, type_info, table_types diff --git a/src/ffi/mod.rs b/src/ffi/mod.rs deleted file mode 100644 index 5d0bb7c0..00000000 --- a/src/ffi/mod.rs +++ /dev/null @@ -1,84 +0,0 @@ -// 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. - -//! Custom C ABI for the v0 Kernel — for ODBC and Go consumers that -//! cannot link the Rust crate directly. -//! -//! Per `docs/spec-v0.md` "Architecture", this layer is a thin shim over -//! the async kernel core: it owns a process-wide tokio runtime, marshals -//! C strings / structs into `SessionConfig`, and exposes opaque handles -//! 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)] - -pub mod error; -pub mod metadata; -pub mod result; -pub mod session; -pub mod statement; - -/// Status enum returned by every C entry point. -/// -/// Variants parallel [`crate::kernel_error::ErrorCode`] one-to-one. The -/// [`From`] conversion below uses an exhaustive match (no -/// `_ =>` arm) so adding a variant to `ErrorCode` is a compile error -/// here until `KernelStatusCode` grows the matching variant. That -/// catches FFI/Rust drift mechanically. -#[repr(C)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum KernelStatusCode { - Success = 0, - InvalidArgument = 1, - Unauthenticated = 2, - PermissionDenied = 3, - NotFound = 4, - ResourceExhausted = 5, - Unavailable = 6, - Timeout = 7, - Cancelled = 8, - DataLoss = 9, - Internal = 10, - InvalidStatementHandle = 11, - NetworkError = 12, - SqlError = 13, -} - -impl From for KernelStatusCode { - fn from(code: crate::kernel_error::ErrorCode) -> Self { - use crate::kernel_error::ErrorCode; - // Exhaustive match — no `_ =>` arm. Adding a variant to - // `ErrorCode` is a compile error here, forcing the FFI to - // declare the corresponding `KernelStatusCode` variant. - match code { - ErrorCode::InvalidArgument => Self::InvalidArgument, - ErrorCode::Unauthenticated => Self::Unauthenticated, - ErrorCode::PermissionDenied => Self::PermissionDenied, - ErrorCode::NotFound => Self::NotFound, - ErrorCode::ResourceExhausted => Self::ResourceExhausted, - ErrorCode::Unavailable => Self::Unavailable, - ErrorCode::Timeout => Self::Timeout, - ErrorCode::Cancelled => Self::Cancelled, - ErrorCode::DataLoss => Self::DataLoss, - ErrorCode::Internal => Self::Internal, - ErrorCode::InvalidStatementHandle => Self::InvalidStatementHandle, - ErrorCode::NetworkError => Self::NetworkError, - ErrorCode::SqlError => Self::SqlError, - } - } -} diff --git a/src/ffi/result.rs b/src/ffi/result.rs deleted file mode 100644 index ade2b877..00000000 --- a/src/ffi/result.rs +++ /dev/null @@ -1,73 +0,0 @@ -// 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. - -//! Result FFI — exports `ResultStream` 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. - -#![allow(dead_code, unused_variables, non_camel_case_types)] - -use super::KernelStatusCode; - -#[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. -#[no_mangle] -pub unsafe extern "C" fn kernel_result_stream_get_schema( - stream: *mut kernel_result_stream_t, - // out: *mut FFI_ArrowSchema, -) -> KernelStatusCode { - unimplemented!("PR 7c: arrow::ffi schema export") -} - -/// Export the next batch as an `FFI_ArrowArray`. Returns -/// `KernelStatusCode::Success` with a released-state array when the stream -/// is exhausted. -#[no_mangle] -pub unsafe extern "C" fn kernel_result_stream_next_batch( - stream: *mut kernel_result_stream_t, - // out: *mut FFI_ArrowArray, -) -> KernelStatusCode { - unimplemented!("PR 7c: arrow::ffi array export, drives next_batch()") -} - -/// 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. -/// -/// # 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. -#[no_mangle] -pub unsafe extern "C" fn kernel_result_stream_close( - stream: *mut kernel_result_stream_t, -) -> KernelStatusCode { - unimplemented!("PR 7c") -} diff --git a/src/ffi/session.rs b/src/ffi/session.rs deleted file mode 100644 index 63a0388e..00000000 --- a/src/ffi/session.rs +++ /dev/null @@ -1,87 +0,0 @@ -// 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. - -//! Session FFI — open / close / new_statement. -//! -//! 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; - -/// 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.). -#[repr(C)] -#[non_exhaustive] -pub struct KernelSessionConfig { - _private: [u8; 0], -} - -/// Open a session from a `repr(C)` config struct. -/// -/// 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 -/// `config` must point to a valid `KernelSessionConfig` produced by -/// `kernel_session_config_new`; `out` must be writable. -#[no_mangle] -pub unsafe extern "C" fn kernel_session_open( - config: *const KernelSessionConfig, - out: *mut *mut kernel_session_t, -) -> KernelStatusCode { - unimplemented!("PR 7a: marshal config, block_on Session::open") -} - -/// Close a session. Releases the underlying Rust `Session`. -/// -/// # 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. -#[no_mangle] -pub unsafe extern "C" fn kernel_session_close(session: *mut kernel_session_t) -> KernelStatusCode { - unimplemented!("PR 7a: drop the boxed Session") -} - -/// Construct a new mutable statement bound to this session. Returns a -/// borrowed pointer; the statement's lifetime is bound to the session. -/// -/// Caller releases with `kernel_statement_close`. -#[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") -} - -// Deferred to v0.1 (see addendum A5): -// -// pub unsafe extern "C" fn kernel_session_set_autocommit(...) -> KernelStatusCode; -// pub unsafe extern "C" fn kernel_session_commit(...) -> KernelStatusCode; -// pub unsafe extern "C" fn kernel_session_rollback(...) -> KernelStatusCode; diff --git a/src/ffi/statement.rs b/src/ffi/statement.rs deleted file mode 100644 index 88ef9468..00000000 --- a/src/ffi/statement.rs +++ /dev/null @@ -1,302 +0,0 @@ -// 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. - -//! Statement FFI — four opaque handle types per `docs/spec-v0.md` -//! addendum A1. -//! -//! ## 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. - -#![allow(dead_code, unused_variables, non_camel_case_types)] - -use super::KernelStatusCode; -use std::ffi::c_char; - -// ─── 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. -#[repr(C)] -pub struct kernel_statement_t { - _private: [u8; 0], -} - -/// Sync-consumption executed handle. Returned by -/// `kernel_statement_execute`. -#[repr(C)] -pub struct kernel_executed_statement_t { - _private: [u8; 0], -} - -/// Async-consumption executed handle. Returned by -/// `kernel_statement_submit`. -#[repr(C)] -pub struct kernel_executed_async_statement_t { - _private: [u8; 0], -} - -/// 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)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum KernelStatementStatusKind { - Pending = 0, - Running = 1, - Succeeded = 2, - /// Server-side execution failed. Call `kernel_get_last_error` for - /// the underlying `KernelError` (sql_state, vendor_code, …). - Failed = 3, - Cancelled = 4, - Closed = 5, -} - -// ─── Spec setters ──────────────────────────────────────────────────────────── - -#[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") -} - -/// Free a `kernel_statement_spec_t`. -/// -/// # Safety -/// -/// `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. -#[no_mangle] -pub unsafe extern "C" fn kernel_statement_spec_free( - spec: *mut kernel_statement_spec_t, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -#[no_mangle] -pub unsafe extern "C" fn kernel_statement_spec_set_sql( - spec: *mut kernel_statement_spec_t, - sql: *const c_char, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -// 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. -/// -/// **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. -#[no_mangle] -pub unsafe extern "C" fn kernel_statement_get_spec( - stmt: *mut kernel_statement_t, - out: *mut *mut kernel_statement_spec_t, -) -> KernelStatusCode { - unimplemented!("PR 7b: return &mut self.spec via raw ptr") -} - -/// 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`. -#[no_mangle] -pub unsafe extern "C" fn kernel_statement_execute( - stmt: *mut kernel_statement_t, - out: *mut *mut kernel_executed_statement_t, -) -> KernelStatusCode { - unimplemented!("PR 7b: block_on Statement::execute") -} - -/// 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`. -#[no_mangle] -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: block_on Statement::submit") -} - -/// Free the lifecycle owner. -/// -/// **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. -/// -/// 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 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. -#[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") -} - -// ─── ExecutedStatement (sync) ──────────────────────────────────────────────── - -/// Server-issued statement id, NUL-terminated. -/// -/// **Lifetime:** the returned pointer is valid as long as `exec` is. -/// Do not free it; do not retain past -/// `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. -#[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, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_statement_cancel( - exec: *mut kernel_executed_statement_t, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -/// 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. -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_statement_close( - exec: *mut kernel_executed_statement_t, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -// ─── ExecutedAsyncStatement (async) ────────────────────────────────────────── - -/// Server-issued statement id, NUL-terminated. -/// -/// **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`. -#[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, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -#[no_mangle] -pub unsafe extern "C" fn kernel_executed_async_statement_cancel( - exec: *mut kernel_executed_async_statement_t, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} - -/// Free an async executed handle. -/// -/// # 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, -) -> KernelStatusCode { - unimplemented!("PR 7b") -} 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::{ 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 diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c new file mode 100644 index 00000000..e1f0b588 --- /dev/null +++ b/tests/c/session_smoke.c @@ -0,0 +1,205 @@ +/* + * 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"); +} + +/* 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); +} + +/* 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; + /* 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_proxy_and_tls_setters(); + test_submit_stub_rejects(); + test_bind_null_handle_rejected(); + + 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; +}