Skip to content

[PECOBLR-2096] Implement the v0 Kernel C ABI (PR 6) - #158

Merged
vikrantpuppala merged 7 commits into
mainfrom
pecoblr-2096-kernel-c-abi
Jul 3, 2026
Merged

vikrantpuppala merged 7 commits into
mainfrom
pecoblr-2096-kernel-c-abi

Conversation

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

What

Implements the kernel's custom C ABI under src/ffi/ — the migration plan's "PR 6", which was deferred until an ODBC / Go consumer needed it. The Databricks OSS ODBC driver is now that consumer: it is migrating off its ADBC Rust backend onto this kernel, and links the C ABI declared in the new include/databricks_kernel.h.

The async kernel core (auth, SEA transport, CloudFetch/inline readers, metadata) is unchanged — this PR is purely the C edge: process-wide runtime, config/handle marshalling, and Arrow C Data Interface result export.

What's included

  • Runtime + errors (src/ffi/mod.rs, src/ffi/error.rs): process-wide OnceLock<tokio::runtime::Runtime>; block_on_ffi with a panic-catch at the FFI edge (no unwinding across extern "C"); thread-local last-error buffer + kernel_get_last_error.
  • Session (src/ffi/session.rs): KernelSessionConfig builder + setters (set_warehouse / set_http_path / set_auth_pat / set_auth_m2m / set_session_conf), kernel_session_open / close / new_statement. Auth over the C ABI is PAT + OAuth M2M only (U2M stays Rust-crate-only, per migration-plan §6).
  • Statement (src/ffi/statement.rs): set_sql, positional bind_* (null/int64/double/bool/string), synchronous execute. The async submit path remains deferred (returns InvalidArgument) until a consumer needs caller-driven polling over the C ABI.
  • Result stream (src/ffi/result.rs): schema + per-batch export via the Arrow C Data Interface (arrow-array's ffi feature). The executed-statement stream borrows its executed handle so the drain-driven auto-close and lazy CloudFetch link fetches keep working.
  • Metadata (src/ffi/metadata.rs): list_catalogs / _schemas / _tables / _columns / primary_keys / foreign_keys as thin shims over Session::metadata(), returning server-shaped streams.
  • Header + tests (include/databricks_kernel.h, tests/c/session_smoke.c, make c-abi-test, pr-checks.yml job): hand-written C header (cbindgen is a v0.1 concern), and a hermetic C smoke test that links the cdylib and exercises config lifecycle, null guards, and the full async open→error path.

Scope notes / deferrals

  • Async submit path, functions / procedures / type_info / table_types metadata, and additional bind_* types (decimal/date/timestamp/binary) are left as follow-ups — wired when an ODBC / Go consumer needs them.
  • arrow-array gains the ffi feature (used only by the result export).

Testing

  • cargo build / cargo clippy --all-targets -- -D warnings / cargo fmt --check — clean.
  • cargo test — 668 tests pass (5 new ffi::error unit tests).
  • make c-abi-test — 20 C smoke checks pass (links the real cdylib end-to-end).

This pull request and its description were written by Isaac.

@vikrantpuppala
vikrantpuppala requested a review from a team as a code owner June 30, 2026 10:42
Comment thread src/c_abi/statement.rs Resolved
Comment thread src/c_abi/result.rs Resolved
Comment thread src/c_abi/result.rs Resolved
Comment thread src/c_abi/mod.rs Resolved
Comment thread src/c_abi/statement.rs Resolved
Comment thread include/databricks_kernel.h Resolved
Comment thread include/databricks_kernel.h Resolved
Comment thread src/c_abi/statement.rs Resolved
Comment thread src/c_abi/result.rs Resolved
Comment thread src/c_abi/session.rs Resolved
The ODBC driver's proxy / TLS / self-signed connection properties are
supported features with E2E coverage (the old ADBC backend honoured
them), but the v0 C ABI had no way to pass them through — so the ODBC
side had to reject them, breaking the proxy/tls E2E tests. The kernel's
SessionConfig already carries ProxyConfig / TlsConfig; this wires them to
the C ABI.

Add to src/c_abi/session.rs (and databricks_kernel.h):
- kernel_session_config_set_proxy(url, username, password, bypass_hosts)
  → SessionConfig.proxy (ProxyConfig). url required; rest optional.
- kernel_session_config_set_tls_trusted_certs(pem, len)
  → TlsConfig.custom_ca_cert (PEM bundle bytes).
- kernel_session_config_set_tls_allow_self_signed(bool)
  → TlsConfig.accept_self_signed.
- kernel_session_config_set_tls_skip_hostname_verification(bool)
  → TlsConfig.skip_hostname_verification.

build_session only constructs a Proxy/Tls config when a knob was set, so
the strict-TLS / env-var-proxy defaults are preserved otherwise. C smoke
test extended to cover the new setters.

cargo clippy --all-targets -D warnings / fmt clean; 670 lib tests + C
smoke checks pass.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@gopalldb

gopalldb commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

⚠️ [MAJOR] · bug · src/c_abi/statement.rs:335

kernel_statement_close invalidates still-held executed handles, contradicting the C ABI independence contract

Statement close silently invalidates executed handles the header says survive it. kernel_statement_close (statement.rs:335) drops the Statement, whose Drop calls self.last_valid.take().invalidate() (mutable.rs:780). That ValidityFlag is the same handle cloned into the ExecutedStatement at execute time (mutable.rs:324-335) and read by ExecutedStatement::is_valid() (executed.rs:195). After the statement is closed, exec.is_valid() returns false, so kernel_executed_statement_get_result_stream (statement.rs:379), kernel_executed_statement_num_modified_rows (statement.rs:427), and result-stream next_batch (result.rs:131) all return InvalidStatementHandle. The C ABI header for kernel_statement_close (databricks_kernel.h:298-301) states it "Does NOT free executed-handle boxes; close each of those separately," presenting executed handles as independently-owned and usable after statement close. An ODBC/Go consumer following the natural teardown order execute → statement_close → drain result therefore finds result consumption broken.


💡 [MINOR] · bug · src/c_abi/mod.rs:126

block_on_ffi panics (→ silent Internal) if an FFI call is reentered on the C-ABI runtime's own worker

Reentrant block_on on the process-wide runtime panics and silently degrades to Internal. block_on_ffi calls rt.block_on(fut_builder()) (mod.rs:126) on the shared multi-thread runtime. tokio::runtime::Runtime::block_on panics with "Cannot start a runtime from within a runtime" when called from a thread that is already a worker of a tokio runtime. If any C-ABI entry point is transitively invoked from within a task running on this same runtime (e.g. a consumer that drives the kernel from a callback executing on a runtime worker), the panic is caught by the surrounding catch_unwind and mapped to KernelStatusCode::Internal — the operation fails with a generic, misleading status instead of completing or reporting a clear reentrancy error.


💡 [MINOR] · bug · src/c_abi/metadata.rs:284

primary_keys NULL catalog/schema contradicts header's "NULL means unfiltered" contract

Documented C-ABI contract mismatch on kernel_metadata_primary_keys. The header states NULL string args mean "unfiltered" for all metadata calls (databricks_kernel.h:335), and kernel_metadata_primary_keys reads catalog/schema via opt_ident (metadata.rs:282-283), which maps NULL to None. But Metadata::primary_keys requires both to be Some: it returns InvalidArgument ("primary_keys requires a catalog/schema identifier") when either is None (metadata_v0.rs:511-516), because Databricks SHOW KEYS needs a fully-qualified IN CATALOG / IN SCHEMA / IN TABLE. A C consumer that follows the documented contract and passes NULL catalog or schema therefore gets a runtime InvalidArgument rather than the promised unfiltered result.

…uard reentrancy

Addresses gopalldb's review on #158.

[MAJOR] kernel_statement_close vs. executed-handle independence
The header implied executed handles are usable after kernel_statement_close
("close each of those separately"), but a Statement shares a ValidityFlag
with the executed handles it produces and Statement::Drop invalidates it —
by design, so ExecutedStatement::cancel short-circuits cheaply on a zombie
handle (pinned by kernel_invariant_parent_drop_invalidates_executed_cancel,
relied on by the napi binding). Rather than weaken that tested invariant,
correct the contract: databricks_kernel.h + the Rust docs now state the
statement must be closed LAST — drain/close result streams, then executed
handles, then the statement — and the InvalidStatementHandle messages on
get_result_stream / num_modified_rows / result-stream next_batch now name
"re-execute or close" and point at the ordering. (The ODBC driver already
tears down in this order.)

[MINOR] primary_keys / foreign_keys NULL contract
The metadata header said "NULL string args mean unfiltered" blanket, but
primary_keys requires catalog+schema+table and foreign_keys requires the
full foreign_* triple (Databricks SHOW KEYS needs a qualified target) —
NULL yields InvalidArgument. Scoped the "unfiltered" wording to the list_*
calls and documented the required identifiers per-function.

[MINOR] block_on_ffi reentrancy
Called from a thread already inside a Tokio runtime, Runtime::block_on
panics ("runtime within a runtime") and the catch_unwind arm degraded it to
a generic Internal. Detect Handle::try_current() up front and return a typed
Internal with an actionable message documenting the native-thread contract.
Added a unit test.

cargo fmt / clippy --all-targets clean; 671 lib tests + C smoke pass.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Thanks @gopalldb — all three addressed in bd17c8b:

[MAJOR] kernel_statement_close invalidates still-held executed handles. You're right that the header over-promised. The parent-drop invalidation is deliberate, though: a Statement shares its ValidityFlag with the executed handles it produces so that ExecutedStatement::cancel short-circuits cheaply on a zombie handle — pinned by kernel_invariant_parent_drop_invalidates_executed_cancel and depended on by the napi binding. Rather than weaken that tested invariant, I corrected the contract to match the real (intended) semantics: the header + Rust docs now state the statement must be closed last (drain/close result streams → executed handles → statement), and the InvalidStatementHandle messages on get_result_stream / num_modified_rows / result-stream next_batch now say "re-execute or close" and point at the ordering. The ODBC consumer already tears down in exactly this order, so no consumer breakage. If you feel executed handles should be truly independent of the parent (a bigger change touching the cancel invariant + napi), happy to discuss as a follow-up — but the doc fix makes the shipped behavior correct and self-consistent.

[MINOR] primary_keys NULL contract. Fixed the header: the blanket "NULL = unfiltered" now applies only to the list_* calls; primary_keys (catalog+schema+table) and foreign_keys (full foreign_* triple) are documented as requiring those identifiers, matching the InvalidArgument the kernel returns.

[MINOR] block_on_ffi reentrancy → silent Internal. Now detects Handle::try_current() up front and returns a typed Internal with an actionable message ("called from within a Tokio runtime thread; entry points must be invoked from a native thread") instead of relying on the caught-panic path. Documented the native-thread contract on block_on_ffi and added a unit test.

cargo fmt / clippy --all-targets clean; 671 lib tests + C smoke pass. (The dependent ODBC PR #101 will re-pin its KERNEL_REPO_TAG to the merge commit once this lands.)

@gopalldb

gopalldb commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

Check if we can address these in separate PR:

⚠️ [MAJOR] · bug · src/c_abi/metadata.rs:99

drain_metadata buffers entire result set; ALL-CATALOGS column listing breaks the "bounded" assumption

Unbounded in-memory buffering of a metadata result set. drain_metadata (metadata.rs:87-107) drains the whole ResultStream into a Vec (cloning each batch at metadata.rs:99) before returning, and the module comment justifies this by asserting metadata results are "bounded — a handful of batches at most". That assumption does not hold for kernel_metadata_list_columns with a NULL catalog: list_columns(catalog=None) emits SHOW COLUMNS IN ALL CATALOGS (metadata_v0.rs:423-429), returning a row per column of every table in every catalog visible to the session. In a large workspace an ODBC getColumns(null, …) therefore materialises the entire cross-catalog column inventory at once, spiking memory for the life of the returned stream handle.


⚠️ [MAJOR] · bug · src/c_abi/metadata.rs:176

Empty-string catalog arg errors instead of meaning "unfiltered" in list_schemas/tables/columns

Empty (non-NULL) identifier arg rejected instead of treated as unfiltered. opt_ident (metadata.rs:65) distinguishes only a NULL pointer (→ None, "unfiltered"); a non-null empty C string "" becomes Some("") and is passed to Identifier::new(""), which returns InvalidArgument (metadata_v0.rs:150-152, "identifier must not be empty"). The header contract only states that NULL means "unfiltered" (databricks_kernel.h:359) and says nothing about empty strings. ODBC/JDBC drivers commonly pass an empty string rather than NULL to mean "match all catalogs"; such a call to kernel_metadata_list_schemas / _list_tables / _list_columns fails with InvalidArgument instead of returning the unfiltered listing the consumer intends.


⚠️ [MAJOR] · bug · src/c_abi/session.rs:547

Header "close initiates delete" contract is false when statement handles outlive the session

kernel_session_close does not initiate server-side delete when a statement/executed handle is still live. The header (databricks_kernel.h:59-63) states close "returns once the server-side delete is initiated". But kernel_session_close drops only one Arc (session.rs:547), and DeleteSession is spawned solely from SessionInner::Drop (session.rs:155), which runs only when the last Arc drops. Session::statement()/metadata() each clone the Arc (session.rs:337,342), and ExecutedStatement retains one, so any live statement/executed handle keeps the strong count above one. In that case closing the session defers DeleteSession until those handles are also released, contradicting the documented close-initiation contract and potentially leaving the server session to expire on its idle timeout.

@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Thanks @gopalldb — since this PR is already merged, Ill address these three in a separate follow-up PR on main (as you suggested):

  1. [MAJOR] drain_metadata unbounded buffering — list_columns(catalog=NULL) = SHOW COLUMNS IN ALL CATALOGS can materialize the whole cross-catalog inventory. Will make the metadata result stream lazy/pull-based instead of draining into a Vec<RecordBatch> up front.
  2. [MAJOR] empty-string identifier rejected — opt_ident maps only NULL → None; "" becomes Some("") → InvalidArgument. ODBC/JDBC commonly pass "" for "match all", so Ill treat empty (or whitespace-only) as unfiltered (None) in the list_* paths.
  3. [MAJOR] kernel_session_close delete-initiation contract — DeleteSession only fires when the last Arc<SessionInner> drops, so a live statement/executed handle defers it, contradicting the header. Will reconcile behavior vs. contract (either force-initiate on close, or correct the header to state delete is initiated once the last handle is released).

Will link the follow-up PR here once its up.

@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Follow-up PR with all three fixes is up: #160 (lazy metadata streaming, empty-filter → unfiltered, session-close delete initiation).

This branch was previously deployed

1 inactive deployment
azure-prod — bd17c8b8 Deployed Jul 2, 2026 by vikrantpuppala via PyO3 build + test (Python 3.13) #144
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants