From 68b5bf7b81c532b0a4548291a137b487f7595614 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sat, 16 May 2026 14:38:27 +0000 Subject: [PATCH 01/28] feat(napi): add Database / Connection / Statement / ResultStream napi classes Lands the four #[napi] classes that expose the kernel's v0 surface: - Database.open() returns a Database handle (Session) - Connection.execute_statement() returns a Statement handle - Statement.fetch_next_batch() / .schema() / .cancel() / .close() - ResultStream (used internally; not directly exposed) Results cross the FFI as Arrow IPC bytes (see result.rs); the TS adapter decodes them via apache-arrow. Builds on the skeleton commit; cargo check is clean. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 166 ++++++++++++++++++++++++++++++++ napi/src/database.rs | 90 +++++++++++++++++ napi/src/lib.rs | 13 ++- napi/src/result.rs | 36 +++++++ napi/src/statement.rs | 212 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 512 insertions(+), 5 deletions(-) create mode 100644 napi/src/connection.rs create mode 100644 napi/src/database.rs create mode 100644 napi/src/result.rs create mode 100644 napi/src/statement.rs diff --git a/napi/src/connection.rs b/napi/src/connection.rs new file mode 100644 index 00000000..4afbd724 --- /dev/null +++ b/napi/src/connection.rs @@ -0,0 +1,166 @@ +// 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. + +//! Opaque `Connection` wrapper around the kernel's `Session`. +//! +//! The kernel collapses ADBC's `Database` + `Connection` into a single +//! `Session`. We keep the wrapper name `Connection` on the JS side because +//! that matches the existing Node driver's mental model. +//! +//! M0 surface (Round 2): +//! - `Connection.executeStatement(sql, options)` — builds a kernel +//! `Statement`, sets the spec, awaits `execute()`, wraps the result +//! in a JS-visible `Statement` opaque handle. +//! - `Connection.close()` — explicit async close. Drop schedules a +//! fire-and-forget close on the captured runtime handle if explicit +//! close was never called. + +use std::collections::HashMap; +use std::sync::Arc; +use tokio::sync::Mutex; + +use databricks_sql_kernel::Session; + +use crate::error::napi_err_from_kernel; +use crate::runtime; +use crate::statement::Statement; +use crate::util::guarded; + +/// JS-visible per-execute options. M0 only carries +/// initialCatalog / initialSchema / sessionConfig — parameters and +/// per-statement overrides land in M1. +#[napi(object)] +pub struct ExecuteOptions { + /// Default catalog applied to this statement via session conf. + pub initial_catalog: Option, + /// Default schema applied to this statement via session conf. + pub initial_schema: Option, + /// Per-statement session conf overrides (forwarded to SEA + /// `parameters` / Thrift `confOverlay`). + pub session_config: Option>, +} + +/// Opaque connection handle wrapping a kernel `Session`. +/// +/// `inner` is `Arc>>` so: +/// - the Drop impl can clone the `Arc` and `.take()` the session on a +/// background tokio task without holding `&mut self` (which Drop is +/// forbidden from doing across an `await`), +/// - `executeStatement` can share immutable access to the session via +/// the `Arc` clones the kernel makes internally +/// (`Session::statement()` only needs `&self`). +#[napi] +pub struct Connection { + pub(crate) inner: Arc>>, +} + +#[napi] +impl Connection { + /// Execute a SQL statement and return a Statement handle that + /// streams batches via `fetchNextBatch()`. + #[napi] + pub async fn execute_statement( + &self, + sql: String, + options: ExecuteOptions, + ) -> napi::Result { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let session = guard.as_ref().ok_or_else(|| { + napi::Error::new(napi::Status::InvalidArg, "connection already closed") + })?; + + // Build a per-statement spec on the kernel's mutable + // Statement. Session conf overrides surface through the + // statement_conf overlay; M0 has no parameter binding. + let mut stmt = session.statement(); + stmt.spec().sql(sql); + + let mut overlay: HashMap = + options.session_config.unwrap_or_default(); + if let Some(catalog) = options.initial_catalog { + overlay.insert("default_catalog".to_string(), catalog); + } + if let Some(schema) = options.initial_schema { + overlay.insert("default_schema".to_string(), schema); + } + if !overlay.is_empty() { + stmt.spec().statement_conf(overlay); + } + + let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; + Ok(Statement::from_executed(executed)) + }) + .await + } + + /// Explicit close. Marks the connection wrapper as closed so + /// subsequent calls on this `Connection` return `InvalidArg`, then + /// schedules a fire-and-forget server-side close on the runtime. + /// + /// **Why fire-and-forget and not `Session::close().await`:** the + /// kernel's `Session::close(self).await` body holds a + /// `tracing::EnteredSpan` (a `!Send` type) across an `.await`, so + /// the future is not `Send`. napi-rs's `execute_tokio_future` glue + /// rejects non-`Send` futures, and `Handle::spawn` does too. The + /// kernel's `SessionInner::Drop` already spawns the + /// `delete_session` RPC on the same runtime handle the napi + /// binding captured, so dropping the value is functionally + /// equivalent — the difference is that JS callers can't observe a + /// `delete_session` failure from `close()`. Tracked as a kernel- + /// side follow-up (clone the span rather than entering it) in + /// Round 3 findings. + #[napi] + pub async fn close(&self) -> napi::Result<()> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let _taken = { + let mut guard = inner.lock().await; + guard.take() + }; + // `_taken` drops here. Kernel's `SessionInner::Drop` + // spawns `delete_session` on its captured handle. + Ok(()) + }) + .await + } +} + +impl Drop for Connection { + fn drop(&mut self) { + // Fire-and-forget close on the captured runtime. If `close()` + // was already called, `inner` holds `None` and the spawned + // task is a trivial no-op. + let Some(handle) = runtime::try_get_handle() else { + // No async entry point ever ran — there's nothing to close. + return; + }; + let inner = Arc::clone(&self.inner); + handle.spawn(async move { + // Drop the session value on the runtime. The kernel's + // `SessionInner::Drop` already spawns a fire-and-forget + // `delete_session` against its own captured handle. We do + // NOT call `Session::close().await` here because that + // method holds a `tracing::EnteredSpan` (`!Send`) across + // its body, which would conflict with `Handle::spawn`'s + // `Send` bound on the future. + let _taken = { + let mut guard = inner.lock().await; + guard.take() + }; + // `_taken` drops here; kernel's SessionInner::Drop fires. + }); + } +} diff --git a/napi/src/database.rs b/napi/src/database.rs new file mode 100644 index 00000000..7f86760e --- /dev/null +++ b/napi/src/database.rs @@ -0,0 +1,90 @@ +// 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. + +//! `openSession()` — the binding's session-construction entry point. +//! +//! The kernel collapses ADBC's `Database` + `Connection` into a single +//! `Session`. The TS adapter layer reconstructs a `DBSQLClient` / +//! `Database` wrapper on top of this binding, so the napi surface itself +//! stays flat: one free function, one opaque `Connection` class. +//! +//! Rationale for a free function over a static class method: +//! - napi-rs v2's static-method codegen for async functions returning a +//! `#[napi]` struct is fragile — the runtime registration sometimes +//! omits the method from the class object. Free `#[napi]` functions +//! go through a different, more stable codegen path. +//! - There is no kernel-side `Database` state to wrap; everything +//! meaningful lives on `Session`. A wrapper class with no fields adds +//! a JS object allocation per session for no benefit. + +use std::sync::Arc; +use tokio::sync::Mutex; + +use databricks_sql_kernel::{AuthConfig, Session}; + +use crate::connection::Connection; +use crate::error::napi_err_from_kernel; +use crate::runtime; +use crate::util::guarded; + +/// JS-visible options for opening a Databricks SQL session over PAT. +/// +/// M0 supports PAT only — `token` is required. OAuth M2M / U2M variants +/// land in M1 along with a discriminated-union shape on the JS side. +#[napi(object)] +pub struct ConnectionOptions { + /// Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel + /// normalises this — bare hostnames get `https://` prepended. + pub host_name: String, + /// JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The + /// kernel parses out the warehouse id. + pub http_path: String, + /// Personal access token. Must be non-empty (the kernel rejects + /// empty PATs at session construction). + pub token: String, +} + +/// Open a Databricks SQL session over PAT auth and return an opaque +/// `Connection` wrapping the kernel `Session`. +/// +/// The JS-visible name is `openSession` (napi-rs converts snake_case +/// to camelCase for free functions). +#[napi] +pub async fn open_session(options: ConnectionOptions) -> napi::Result { + guarded(async move { + // Cache the napi-rs tokio Handle on the very first async call + // so Drop impls (which run on the V8 GC thread, outside any + // tokio context) can still `spawn` cleanup tasks onto the + // runtime that's driving this future. + let _ = runtime::get_handle(); + + // SessionConfig is `#[non_exhaustive]` — go through the + // builder, which is the only public path that constructs it. + // `http_path()` is the convenience setter that maps a bare + // hostname + `/sql/1.0/warehouses/{id}` path into the kernel's + // `ConnectionConfig`. + let session = Session::builder() + .http_path(options.host_name, options.http_path) + .auth(AuthConfig::Pat { + token: options.token, + }) + .open() + .await + .map_err(napi_err_from_kernel)?; + Ok(Connection { + inner: Arc::new(Mutex::new(Some(session))), + }) + }) + .await +} diff --git a/napi/src/lib.rs b/napi/src/lib.rs index b418e743..d3213e21 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -15,11 +15,10 @@ //! `databricks-sea-native` — napi-rs binding crate for the Databricks //! SQL Node.js driver's SEA (Statement Execution API) path. //! -//! **Skeleton commit.** This commit lands the crate's infrastructure: -//! Cargo manifest, build script, error envelope formatter, tokio -//! runtime helper, `tracing` logger bridge, and shared utilities. -//! The actual `#[napi]` classes (`Database`, `Connection`, `Statement`, -//! `ResultStream`) are added in the follow-up commit. +//! Round 2 surface: `Database.open` → `Connection.execute_statement` +//! → `Statement.fetch_next_batch` / `schema` / `cancel` / `close`. +//! Results cross the FFI as Arrow IPC bytes (see `result.rs`); the +//! TS adapter decodes them via `apache-arrow`. #![deny(unsafe_op_in_unsafe_fn)] // Skeleton-PR state: every `pub(crate)` item in this crate (error @@ -38,9 +37,13 @@ #[macro_use] extern crate napi_derive; +pub(crate) mod connection; +pub(crate) mod database; pub(crate) mod error; pub(crate) mod logger; +pub(crate) mod result; pub(crate) mod runtime; +pub(crate) mod statement; pub(crate) mod util; /// Returns the native binding's crate version (`CARGO_PKG_VERSION`). diff --git a/napi/src/result.rs b/napi/src/result.rs new file mode 100644 index 00000000..488c0851 --- /dev/null +++ b/napi/src/result.rs @@ -0,0 +1,36 @@ +// 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. + +//! Arrow IPC payload types crossed across the napi boundary. +//! +//! Per sea-design.md Layer 2: "The binding ships the batch across the +//! FFI as Arrow IPC bytes. The adapter converts those bytes into +//! JavaScript rows…" — so the napi boundary is intentionally narrow: +//! one envelope per batch, one envelope per schema. + +use napi::bindgen_prelude::Buffer; + +/// A single Arrow IPC stream payload encoding one record batch (plus +/// the schema header so the JS-side reader is stateless). +#[napi(object)] +pub struct ArrowBatch { + pub ipc_bytes: Buffer, +} + +/// An Arrow IPC stream payload encoding just the result schema (no +/// record-batch messages). Returned by `Statement.schema()`. +#[napi(object)] +pub struct ArrowSchema { + pub ipc_bytes: Buffer, +} diff --git a/napi/src/statement.rs b/napi/src/statement.rs new file mode 100644 index 00000000..6d7b8761 --- /dev/null +++ b/napi/src/statement.rs @@ -0,0 +1,212 @@ +// 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. + +//! Opaque `Statement` wrapper around the kernel's `ExecutedStatement`. +//! +//! M0 surface (Round 2): +//! - `Statement.fetchNextBatch() -> Option` — drives +//! `ResultStream::next_batch().await`, serialises the borrowed +//! `RecordBatch` to Arrow IPC bytes, returns them to JS. +//! - `Statement.schema() -> ArrowSchema` — returns the cached schema +//! from the kernel side, serialised as a schema-only IPC payload. +//! - `Statement.cancel()` / `Statement.close()` — forwards to +//! `ExecutedStatement::cancel/close` via the +//! `ExecutedStatementHandle` trait. Drop fires-and-forgets close +//! if not already explicitly closed. + +use std::sync::Arc; +use tokio::sync::Mutex; + +use arrow_ipc::writer::StreamWriter; +use databricks_sql_kernel::{ExecutedStatement, ExecutedStatementHandle, ResultBatch}; + +use crate::error::napi_err_from_kernel; +use crate::result::{ArrowBatch, ArrowSchema}; +use crate::runtime; +use crate::util::guarded; + +/// Opaque executed-statement handle. +/// +/// `inner` is wrapped in `Arc>>` so: +/// - `fetch_next_batch` can `await` `ResultStream::next_batch` which +/// requires `&mut ExecutedStatement` (via `result_stream_mut`), +/// - `cancel` / `close` (which take `&self` on the kernel side via the +/// `ExecutedStatementHandle` trait) can run concurrently with each +/// other from a JS perspective without panicking, +/// - `Drop` can hand the inner handle off to a tokio task without +/// touching `&mut self` across an `await`. +#[napi] +pub struct Statement { + inner: Arc>>, +} + +impl Statement { + /// Crate-internal constructor — called from + /// `Connection::execute_statement` once the kernel hands back the + /// `ExecutedStatement`. + pub(crate) fn from_executed(executed: ExecutedStatement) -> Self { + Self { + inner: Arc::new(Mutex::new(Some(executed))), + } + } +} + +#[napi] +impl Statement { + /// Pull the next batch of results. Returns `None` when the stream + /// is exhausted. The returned `ArrowBatch.ipcBytes` is a complete + /// Arrow IPC stream (schema header + 1 record-batch message) + /// suitable for handing to `apache-arrow`'s `RecordBatchReader`. + #[napi] + pub async fn fetch_next_batch(&self) -> napi::Result> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let mut guard = inner.lock().await; + let executed = guard.as_mut().ok_or_else(|| { + napi::Error::new(napi::Status::InvalidArg, "statement already closed") + })?; + + let stream = executed.result_stream_mut(); + // Capture the schema before borrowing the next batch — we + // include the schema header in every IPC payload so the + // JS-side consumer can decode each batch independently + // without carrying state across calls. + let schema = stream.schema(); + let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; + let Some(batch) = maybe_batch else { + return Ok(None); + }; + // `ResultBatch` is `#[non_exhaustive]`; v0 only ever + // yields `Arrow`. The error arm exists for forward + // compat — v1+ may add ColumnarThrift / JsonRows / etc., + // and we want the binding to surface that as a typed + // error rather than silently misbehaving. + let record_batch = match batch { + ResultBatch::Arrow(rb) => rb, + _ => { + return Err(napi::Error::new( + napi::Status::GenericFailure, + "non-Arrow ResultBatch variant — binding needs upgrade", + )); + } + }; + let bytes = encode_ipc_stream(&schema, Some(record_batch))?; + Ok(Some(ArrowBatch { + ipc_bytes: bytes.into(), + })) + }) + .await + } + + /// Result schema as an Arrow IPC payload (schema header only, no + /// record-batch message). Available before any batches have been + /// fetched. + #[napi] + pub async fn schema(&self) -> napi::Result { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let executed = guard.as_ref().ok_or_else(|| { + napi::Error::new(napi::Status::InvalidArg, "statement already closed") + })?; + let schema = executed.schema(); + let bytes = encode_ipc_stream(&schema, None)?; + Ok(ArrowSchema { + ipc_bytes: bytes.into(), + }) + }) + .await + } + + /// Server-side cancel. No-op if already finished. + #[napi] + pub async fn cancel(&self) -> napi::Result<()> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let executed = guard.as_ref().ok_or_else(|| { + napi::Error::new(napi::Status::InvalidArg, "statement already closed") + })?; + executed.cancel().await.map_err(napi_err_from_kernel) + }) + .await + } + + /// Explicit close. Awaits the server-side close so the JS caller + /// can observe failures. + #[napi] + pub async fn close(&self) -> napi::Result<()> { + let inner = Arc::clone(&self.inner); + guarded(async move { + // Take the handle out so `Drop` knows there's nothing left + // to clean up. + let executed = { + let mut guard = inner.lock().await; + guard.take() + }; + if let Some(executed) = executed { + executed.close().await.map_err(napi_err_from_kernel)?; + } + Ok(()) + }) + .await + } +} + +impl Drop for Statement { + fn drop(&mut self) { + let Some(handle) = runtime::try_get_handle() else { + return; + }; + let inner = Arc::clone(&self.inner); + handle.spawn(async move { + // Drop the executed statement on the runtime. The kernel's + // `ExecutedStatement::Drop` already spawns a fire-and-forget + // `close_statement` against its own captured handle, so we + // just need to ensure the value is dropped inside a tokio + // context (the kernel's Drop reads `runtime_handle.clone()` + // and spawns; that handle is the same one we captured here). + let _taken = { + let mut guard = inner.lock().await; + guard.take() + }; + }); + } +} + +/// Encode an Arrow schema (and optional one record batch) as an IPC +/// stream payload. Used for both `schema()` (schema only) and +/// `fetchNextBatch()` (schema + one batch). Returning a self-contained +/// IPC stream per call is wasteful header-wise but lets the JS adapter +/// stay stateless — it decodes each `ipcBytes` independently via the +/// same `apache-arrow` `RecordBatchReader` path. +fn encode_ipc_stream( + schema: &arrow_schema::SchemaRef, + batch: Option<&arrow_array::RecordBatch>, +) -> napi::Result> { + let mut buf: Vec = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut buf, schema) + .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?; + if let Some(rb) = batch { + writer + .write(rb) + .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?; + } + writer + .finish() + .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?; + } + Ok(buf) +} From 5b8a591c9accabed67f57465071dd6a792493472 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 24 May 2026 13:26:28 +0000 Subject: [PATCH 02/28] feat(napi)!: move catalog/schema/sessionConf to session-level, drop ExecuteOptions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JS callers passing initialCatalog/initialSchema/sessionConfig on executeStatement were silently no-op'd: the kernel does not read StatementSpec::statement_conf (zero readers across src/), and the SEA wire ExecuteStatementRequest has no per-statement catalog/schema/conf fields. They were stuffed into a dead HashMap and the statement ran against whatever the session was opened with. Mirror pyo3's design: expose catalog/schema/sessionConf on ConnectionOptions (openSession), routed through Session::builder().defaults(DefaultOpts) and .session_conf(HashMap) — the kernel APIs that actually populate SEA CreateSession.catalog / .schema / .session_confs. Drop ExecuteOptions entirely; executeStatement takes only the SQL. Cross-checked: JDBC SEA carries catalog/schema only on CreateSession, not ExecuteStatement (databricks-jdbc/.../sqlexec/CreateSessionRequest .java vs ExecuteStatementRequest.java). pyo3 exposes them only on Session.__new__ (pyo3/src/session.rs:73-141) and explicitly defers statement_conf to "later phases" (pyo3/src/statement.rs:39-40). BREAKING: napi executeStatement signature changes from (sql, options) -> (sql). NodeJS driver consumers must move initialCatalog/initialSchema/sessionConfig from per-statement forwarding to per-session openSession() options. Tracked downstream. Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 49 +++++++++----------------------------- napi/src/database.rs | 53 +++++++++++++++++++++++++++++++++++++----- 2 files changed, 58 insertions(+), 44 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 4afbd724..1d9db8be 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -19,14 +19,16 @@ //! that matches the existing Node driver's mental model. //! //! M0 surface (Round 2): -//! - `Connection.executeStatement(sql, options)` — builds a kernel -//! `Statement`, sets the spec, awaits `execute()`, wraps the result -//! in a JS-visible `Statement` opaque handle. +//! - `Connection.executeStatement(sql)` — builds a kernel `Statement`, +//! sets the SQL, awaits `execute()`, wraps the result in a +//! JS-visible `Statement` opaque handle. Catalog / schema / +//! sessionConf are session-level (`openSession` options), matching +//! pyo3 — the SEA wire protocol carries them on `CreateSession`, +//! not per-statement. Positional / named parameters land in M1. //! - `Connection.close()` — explicit async close. Drop schedules a //! fire-and-forget close on the captured runtime handle if explicit //! close was never called. -use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; @@ -37,20 +39,6 @@ use crate::runtime; use crate::statement::Statement; use crate::util::guarded; -/// JS-visible per-execute options. M0 only carries -/// initialCatalog / initialSchema / sessionConfig — parameters and -/// per-statement overrides land in M1. -#[napi(object)] -pub struct ExecuteOptions { - /// Default catalog applied to this statement via session conf. - pub initial_catalog: Option, - /// Default schema applied to this statement via session conf. - pub initial_schema: Option, - /// Per-statement session conf overrides (forwarded to SEA - /// `parameters` / Thrift `confOverlay`). - pub session_config: Option>, -} - /// Opaque connection handle wrapping a kernel `Session`. /// /// `inner` is `Arc>>` so: @@ -69,12 +57,12 @@ pub struct Connection { impl Connection { /// Execute a SQL statement and return a Statement handle that /// streams batches via `fetchNextBatch()`. + /// + /// No per-statement options: catalog / schema / sessionConf are + /// session-level (`openSession`). Positional / named parameters + /// land in M1 via `Statement::spec().param(…)` on the kernel. #[napi] - pub async fn execute_statement( - &self, - sql: String, - options: ExecuteOptions, - ) -> napi::Result { + pub async fn execute_statement(&self, sql: String) -> napi::Result { let inner = Arc::clone(&self.inner); guarded(async move { let guard = inner.lock().await; @@ -82,24 +70,9 @@ impl Connection { napi::Error::new(napi::Status::InvalidArg, "connection already closed") })?; - // Build a per-statement spec on the kernel's mutable - // Statement. Session conf overrides surface through the - // statement_conf overlay; M0 has no parameter binding. let mut stmt = session.statement(); stmt.spec().sql(sql); - let mut overlay: HashMap = - options.session_config.unwrap_or_default(); - if let Some(catalog) = options.initial_catalog { - overlay.insert("default_catalog".to_string(), catalog); - } - if let Some(schema) = options.initial_schema { - overlay.insert("default_schema".to_string(), schema); - } - if !overlay.is_empty() { - stmt.spec().statement_conf(overlay); - } - let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; Ok(Statement::from_executed(executed)) }) diff --git a/napi/src/database.rs b/napi/src/database.rs index 7f86760e..ec36a08d 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -28,10 +28,11 @@ //! meaningful lives on `Session`. A wrapper class with no fields adds //! a JS object allocation per session for no benefit. +use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::{AuthConfig, Session}; +use databricks_sql_kernel::{AuthConfig, DefaultOpts, Session}; use crate::connection::Connection; use crate::error::napi_err_from_kernel; @@ -42,6 +43,16 @@ use crate::util::guarded; /// /// M0 supports PAT only — `token` is required. OAuth M2M / U2M variants /// land in M1 along with a discriminated-union shape on the JS side. +/// +/// Catalog / schema / sessionConf are applied once at session creation +/// and remain in effect for every statement run on the resulting +/// `Connection`. The SEA wire protocol carries them on +/// `CreateSession`, not on `ExecuteStatement` — so there is no +/// per-statement override path in either this binding or pyo3. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] #[napi(object)] pub struct ConnectionOptions { /// Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel @@ -53,6 +64,18 @@ pub struct ConnectionOptions { /// Personal access token. Must be non-empty (the kernel rejects /// empty PATs at session construction). pub token: String, + /// Default catalog for statements executed on this session. + /// Routed through the kernel's `DefaultOpts` and onto the SEA + /// `CreateSession.catalog` wire field. + pub catalog: Option, + /// Default schema for statements executed on this session. + /// Routed through the kernel's `DefaultOpts` and onto the SEA + /// `CreateSession.schema` wire field. + pub schema: Option, + /// Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, + /// query-tag presets, …). Forwarded verbatim to SEA + /// `session_confs`. Unknown keys are rejected server-side. + pub session_conf: Option>, } /// Open a Databricks SQL session over PAT auth and return an opaque @@ -60,6 +83,10 @@ pub struct ConnectionOptions { /// /// The JS-visible name is `openSession` (napi-rs converts snake_case /// to camelCase for free functions). +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] #[napi] pub async fn open_session(options: ConnectionOptions) -> napi::Result { guarded(async move { @@ -74,14 +101,28 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result Date: Sun, 24 May 2026 15:17:35 +0000 Subject: [PATCH 03/28] fix(napi): await Session::close so JS callers observe DeleteSession failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Connection::close was fire-and-forget on the premise that the kernel's Session::close().await holds a !Send EnteredSpan across an .await. Reading the kernel: Session::close uses .instrument(span).await, which keeps the future Send. The kernel also has a compile-time assert_send(&session.close()) test that fails the build if anyone flips that pattern. Fix: await session.close() and map errors. The kernel docstring on Session::close says it exists specifically so callers can observe a DeleteSession failure — restore that contract. On Err, the kernel leaves its closed flag false so Drop's fire-and-forget cleanup retries as a fallback; the caller still gets the error to surface. Drop stays fire-and-forget — Drop can't .await, period — but the stale !Send rationale comment is removed. Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 47 +++++++++++++++++------------------------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 1d9db8be..a30cfb62 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -79,33 +79,26 @@ impl Connection { .await } - /// Explicit close. Marks the connection wrapper as closed so - /// subsequent calls on this `Connection` return `InvalidArg`, then - /// schedules a fire-and-forget server-side close on the runtime. + /// Explicit close. Awaits the server-side `DeleteSession` so the + /// JS caller can observe failures (auth revoked mid-session, + /// warehouse stopped, network error). Idempotent — a second call + /// on an already-closed connection returns `Ok`. /// - /// **Why fire-and-forget and not `Session::close().await`:** the - /// kernel's `Session::close(self).await` body holds a - /// `tracing::EnteredSpan` (a `!Send` type) across an `.await`, so - /// the future is not `Send`. napi-rs's `execute_tokio_future` glue - /// rejects non-`Send` futures, and `Handle::spawn` does too. The - /// kernel's `SessionInner::Drop` already spawns the - /// `delete_session` RPC on the same runtime handle the napi - /// binding captured, so dropping the value is functionally - /// equivalent — the difference is that JS callers can't observe a - /// `delete_session` failure from `close()`. Tracked as a kernel- - /// side follow-up (clone the span rather than entering it) in - /// Round 3 findings. + /// On `Err`, the kernel leaves its internal `closed` flag false + /// so `Drop`'s fire-and-forget cleanup retries; the caller still + /// sees the error and can surface it to logs / telemetry. #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); guarded(async move { - let _taken = { + let session = { let mut guard = inner.lock().await; guard.take() }; - // `_taken` drops here. Kernel's `SessionInner::Drop` - // spawns `delete_session` on its captured handle. - Ok(()) + let Some(session) = session else { + return Ok(()); + }; + session.close().await.map_err(napi_err_from_kernel) }) .await } @@ -114,8 +107,10 @@ impl Connection { impl Drop for Connection { fn drop(&mut self) { // Fire-and-forget close on the captured runtime. If `close()` - // was already called, `inner` holds `None` and the spawned - // task is a trivial no-op. + // was already called explicitly, `inner` holds `None` and the + // spawned task is a trivial no-op. `Drop` itself cannot + // `.await`, so callers who care about observing + // `DeleteSession` failures must call `close()` explicitly. let Some(handle) = runtime::try_get_handle() else { // No async entry point ever ran — there's nothing to close. return; @@ -123,17 +118,13 @@ impl Drop for Connection { let inner = Arc::clone(&self.inner); handle.spawn(async move { // Drop the session value on the runtime. The kernel's - // `SessionInner::Drop` already spawns a fire-and-forget - // `delete_session` against its own captured handle. We do - // NOT call `Session::close().await` here because that - // method holds a `tracing::EnteredSpan` (`!Send`) across - // its body, which would conflict with `Handle::spawn`'s - // `Send` bound on the future. + // `SessionInner::Drop` spawns a fire-and-forget + // `delete_session` against its own captured handle, so + // dropping inside a tokio context is sufficient cleanup. let _taken = { let mut guard = inner.lock().await; guard.take() }; - // `_taken` drops here; kernel's SessionInner::Drop fires. }); } } From acdb6c7cc4fec9830a44e8ceca619006b898c825 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 24 May 2026 15:21:57 +0000 Subject: [PATCH 04/28] test(napi): add encode_ipc_stream tests + tighten docstrings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - statement.rs: two round-trip tests pinning the Arrow IPC wire-format contract between the binding and the JS-side `apache-arrow` adapter. Schema-only payload yields 0 batches; schema+batch yields 1 batch with input rows preserved. Collapse 3 identical error-wrap lambdas into a local `arrow_err` helper. - statement.rs: docstring contracts — `fetchNextBatch` post-error recovery (close and discard); `cancel` is non-idempotent against natural completion (kernel hits the wire every time). - connection.rs / statement.rs: `Drop` impls memorialize the napi-rs-runtime-alive invariant so any future process-exit reorder surfaces the assumption rather than silently leaking handles. - Prune milestone roadmap markers from module-level docs; keep the technical WHY comments (Arc/Mutex rationale, #[non_exhaustive] arms, Send-safety). Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 23 +++++++----- napi/src/database.rs | 15 ++++---- napi/src/statement.rs | 79 ++++++++++++++++++++++++++++++++++++------ 3 files changed, 89 insertions(+), 28 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index a30cfb62..aa802619 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -15,16 +15,14 @@ //! Opaque `Connection` wrapper around the kernel's `Session`. //! //! The kernel collapses ADBC's `Database` + `Connection` into a single -//! `Session`. We keep the wrapper name `Connection` on the JS side because -//! that matches the existing Node driver's mental model. +//! `Session`. We keep the wrapper name `Connection` on the JS side +//! because that matches the existing Node driver's mental model. //! -//! M0 surface (Round 2): //! - `Connection.executeStatement(sql)` — builds a kernel `Statement`, -//! sets the SQL, awaits `execute()`, wraps the result in a +//! sets the SQL, awaits `execute()`, and wraps the result in a //! JS-visible `Statement` opaque handle. Catalog / schema / -//! sessionConf are session-level (`openSession` options), matching -//! pyo3 — the SEA wire protocol carries them on `CreateSession`, -//! not per-statement. Positional / named parameters land in M1. +//! sessionConf are session-level (`openSession` options) — the SEA +//! wire protocol carries them on `CreateSession`, not per-statement. //! - `Connection.close()` — explicit async close. Drop schedules a //! fire-and-forget close on the captured runtime handle if explicit //! close was never called. @@ -59,8 +57,7 @@ impl Connection { /// streams batches via `fetchNextBatch()`. /// /// No per-statement options: catalog / schema / sessionConf are - /// session-level (`openSession`). Positional / named parameters - /// land in M1 via `Statement::spec().param(…)` on the kernel. + /// session-level (`openSession`). #[napi] pub async fn execute_statement(&self, sql: String) -> napi::Result { let inner = Arc::clone(&self.inner); @@ -111,6 +108,14 @@ impl Drop for Connection { // spawned task is a trivial no-op. `Drop` itself cannot // `.await`, so callers who care about observing // `DeleteSession` failures must call `close()` explicitly. + // + // Invariant: `handle.spawn` only completes its body while the + // tokio runtime captured at first-call time is alive. If this + // `Drop` ever runs after napi-rs has torn down its runtime, + // the spawned task is cancelled before `take()` runs and the + // kernel handle leaks (no `delete_session` is issued). This + // is unreachable under napi-rs's current process-exit + // ordering; revisit if that ordering ever changes. let Some(handle) = runtime::try_get_handle() else { // No async entry point ever ran — there's nothing to close. return; diff --git a/napi/src/database.rs b/napi/src/database.rs index ec36a08d..76223aaa 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -40,15 +40,13 @@ use crate::runtime; use crate::util::guarded; /// JS-visible options for opening a Databricks SQL session over PAT. -/// -/// M0 supports PAT only — `token` is required. OAuth M2M / U2M variants -/// land in M1 along with a discriminated-union shape on the JS side. +/// `token` is required. /// /// Catalog / schema / sessionConf are applied once at session creation /// and remain in effect for every statement run on the resulting /// `Connection`. The SEA wire protocol carries them on /// `CreateSession`, not on `ExecuteStatement` — so there is no -/// per-statement override path in either this binding or pyo3. +/// per-statement override path on this binding. #[allow( dead_code, reason = "exported via napi macro codegen; not called from Rust" @@ -106,11 +104,10 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result Option` — drives //! `ResultStream::next_batch().await`, serialises the borrowed //! `RecordBatch` to Arrow IPC bytes, returns them to JS. @@ -68,6 +67,11 @@ impl Statement { /// is exhausted. The returned `ArrowBatch.ipcBytes` is a complete /// Arrow IPC stream (schema header + 1 record-batch message) /// suitable for handing to `apache-arrow`'s `RecordBatchReader`. + /// + /// On `Err`, the stream is left in an unspecified state — the + /// recommended recovery is to call `close()` and discard the + /// `Statement`. Subsequent `fetchNextBatch()` calls after an error + /// are not guaranteed to succeed or fail consistently. #[napi] pub async fn fetch_next_batch(&self) -> napi::Result> { let inner = Arc::clone(&self.inner); @@ -129,7 +133,13 @@ impl Statement { .await } - /// Server-side cancel. No-op if already finished. + /// Server-side cancel. Hits the wire on every call — the kernel + /// does not short-circuit cancel against an already-finished or + /// already-closed statement, so a cancel that races with natural + /// completion can surface a server-side error indicating the + /// statement is no longer in a cancellable state. Callers that + /// fire cancel defensively after `fetchNextBatch` returned `None` + /// should treat that error as benign. #[napi] pub async fn cancel(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); @@ -166,6 +176,14 @@ impl Statement { impl Drop for Statement { fn drop(&mut self) { + // Invariant: `handle.spawn` only completes its body while the + // tokio runtime captured at first-call time is alive. If this + // `Drop` ever runs after napi-rs has torn down its runtime, + // the spawned task is cancelled before `take()` runs and the + // kernel handle leaks (no `close_statement` is issued). This + // is unreachable under napi-rs's current process-exit + // ordering; revisit (e.g. switch to a blocking close path) if + // that ordering ever changes. let Some(handle) = runtime::try_get_handle() else { return; }; @@ -195,18 +213,59 @@ fn encode_ipc_stream( schema: &arrow_schema::SchemaRef, batch: Option<&arrow_array::RecordBatch>, ) -> napi::Result> { + fn arrow_err(e: impl std::fmt::Display) -> napi::Error { + napi::Error::new(napi::Status::GenericFailure, e.to_string()) + } let mut buf: Vec = Vec::new(); { - let mut writer = StreamWriter::try_new(&mut buf, schema) - .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?; + let mut writer = StreamWriter::try_new(&mut buf, schema).map_err(arrow_err)?; if let Some(rb) = batch { - writer - .write(rb) - .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?; + writer.write(rb).map_err(arrow_err)?; } - writer - .finish() - .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?; + writer.finish().map_err(arrow_err)?; } Ok(buf) } + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{Int32Array, RecordBatch}; + use arrow_ipc::reader::StreamReader; + use arrow_schema::{DataType, Field, Schema}; + + fn make_schema() -> Arc { + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])) + } + + #[test] + fn encode_ipc_stream_schema_only_yields_zero_batches() { + let schema = make_schema(); + let bytes = encode_ipc_stream(&schema, None).expect("encode succeeds"); + let reader = StreamReader::try_new(bytes.as_slice(), None).expect("reader opens"); + let decoded_schema = reader.schema(); + let batches: Vec<_> = reader + .collect::, _>>() + .expect("decode succeeds"); + assert_eq!(decoded_schema.fields(), schema.fields()); + assert_eq!(batches.len(), 0, "schema-only payload yields 0 batches"); + } + + #[test] + fn encode_ipc_stream_schema_plus_batch_round_trips() { + let schema = make_schema(); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .expect("batch builds"); + let bytes = encode_ipc_stream(&schema, Some(&batch)).expect("encode succeeds"); + let reader = StreamReader::try_new(bytes.as_slice(), None).expect("reader opens"); + let decoded: Vec<_> = reader + .collect::, _>>() + .expect("decode succeeds"); + assert_eq!(decoded.len(), 1, "exactly one batch decoded"); + assert_eq!(decoded[0].num_rows(), 3); + assert_eq!(decoded[0].schema().fields(), schema.fields()); + } +} From d4286715b77931bd1fa1e521dd72e8f208bf1319 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 24 May 2026 17:14:47 +0000 Subject: [PATCH 05/28] =?UTF-8?q?fix(napi):=20address=20PR=20#25=20round-2?= =?UTF-8?q?=20review=20=E2=80=94=20typed=20closed-state=20errors,=20cached?= =?UTF-8?q?=20fields,=20idempotent=20cancel,=20kernel=20close=20retry=20co?= =?UTF-8?q?ntract?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary of changes across kernel + binding: - Kernel src/statement/executed.rs: reorder ExecutedStatement::close to set `closed=true` only after a successful wire call, mirroring Session::close. On wire failure the flag stays false so Drop's fire-and-forget retry runs as a fallback — without this a transient close failure silently leaks the server-side statement until session expiry. Allows two callers racing through `&self` to both hit the wire (server-side close is idempotent), trading one redundant RPC for the retry contract. - napi/src/statement.rs: * Cache `schema: Arc` and `statement_id: String` on the wrapper at construction so they survive close() — JS callers can still build error reports against a disposed Statement. * Add `statementId` getter via #[napi(getter)]. * Idempotent cancel via `finished: AtomicBool` — set when fetch_next_batch observes the natural end of stream, short-circuits cancel() to Ok(()) so a defensive cancel after natural completion no longer surfaces an opaque server-side error. * Route closed-state errors through napi_err_from_kernel( KernelError::invalid_statement_handle()) via a single statement_closed_err() helper — TS adapter reviver gets typed KernelError(code='InvalidStatementHandle') instead of raw Status::InvalidArg with substring-only discrimination. * Route the non-Arrow ResultBatch fallback through the envelope too, include CARGO_PKG_VERSION so JS-side error reports pin which binding version was in use. * 6 new #[cfg(test)] unit tests pinning closed-state error envelope shape, cached-field survival, Arc cheapness, and finished-flag toggle. - napi/src/connection.rs: * Add `session_id: String` cached on the wrapper, exposed as #[napi(getter)] — survives close() for log correlation. * Same envelope-routed closed-state error via connection_closed_err() helper. * 3 new #[cfg(test)] unit tests for the closed-state envelope shape and session_id survival. - Both wrappers: soften Drop comments to "best-effort cleanup; we do not guarantee delete_session / close_statement on process exit" rather than asserting the uncited "unreachable under napi-rs's current process-exit ordering." - Both wrappers: rewrite the `inner` field doc-comments to honestly describe the current single-mutex serialisation behaviour and link the follow-up JIRA candidate that tracks the lock-shape split. - napi/src/database.rs: rationale for free-fn-over-static-method rewritten as the positive choice (no Database state to wrap) instead of an uncited claim about napi-rs codegen fragility. - napi/src/lib.rs: module-level surface description updated to match the actual exports (openSession free fn + Connection + Statement + ArrowBatch/ArrowSchema POJOs — no Database class, no ResultStream class). Test suite: 24/24 pass (was 16/16). All gates clean: cargo fmt --check, cargo clippy --all-targets -- -D warnings, cargo test --lib. The single-mutex concurrency limitation (cancel queues behind fetchNextBatch; concurrent executeStatement calls serialise) is documented but unfixed — the proper fix needs a kernel-side accessor to expose ExecutedStatement as a shared Arc plus a separate ResultStream slot. Tracked at sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md. Also-deferred: typed error refactor (LOW; existing JIRA candidate 2026-05-23-napi-typed-error-refactor.md), submit/async-consumption path (LOW; M1 scope), parameter binding (LOW; M1 scope), fetchAll convenience (LOW; JS-side SeaResultsProvider already wraps the streaming primitive). Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 116 ++++++++++++--- napi/src/database.rs | 14 +- napi/src/lib.rs | 10 +- napi/src/statement.rs | 287 ++++++++++++++++++++++++++++++-------- src/statement/executed.rs | 25 +++- 5 files changed, 351 insertions(+), 101 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index aa802619..8f584f0c 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -30,29 +30,61 @@ use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::Session; +use databricks_sql_kernel::{Error as KernelError, Session}; use crate::error::napi_err_from_kernel; use crate::runtime; use crate::statement::Statement; use crate::util::guarded; +/// Closed-state error builder. Mirrors `statement::statement_closed_err` +/// — route through the kernel envelope so the TS reviver mints a typed +/// `KernelError(code='InvalidStatementHandle')`. Single source of truth +/// for `executeStatement` on a closed Connection. +fn connection_closed_err() -> napi::Error { + napi_err_from_kernel( + KernelError::invalid_statement_handle().message("connection already closed"), + ) +} + /// Opaque connection handle wrapping a kernel `Session`. /// /// `inner` is `Arc>>` so: /// - the Drop impl can clone the `Arc` and `.take()` the session on a /// background tokio task without holding `&mut self` (which Drop is /// forbidden from doing across an `await`), -/// - `executeStatement` can share immutable access to the session via -/// the `Arc` clones the kernel makes internally -/// (`Session::statement()` only needs `&self`). +/// - `close()` can `.take()` the session to consume it for the kernel's +/// move-by-value `Session::close(self)` signature. +/// +/// **Current concurrency shape** — `executeStatement` holds +/// `inner.lock()` across `stmt.execute().await`, so two concurrent +/// `Promise.all([executeStatement(q1), executeStatement(q2)])` calls +/// on the same Connection serialise even though the kernel transport +/// supports concurrent statements per session, and `close()` blocks +/// behind any in-flight execute. The kernel's `Session::statement()` +/// is `&self`-callable, so the right shape is `Arc` with +/// concurrent execute paths; that lands in the follow-up lock-shape +/// refactor — see +/// `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. #[napi] pub struct Connection { pub(crate) inner: Arc>>, + /// Server-issued session id. Cached at construction; readable + /// even after `close()` so JS-side log lines can correlate + /// against kernel / server logs which key on the same id. + pub(crate) session_id: String, } #[napi] impl Connection { + /// Server-issued session id. Cached at construction; readable + /// even after `close()` so JS-side log lines can correlate + /// against kernel / server logs which key on the same id. + #[napi(getter)] + pub fn session_id(&self) -> &str { + &self.session_id + } + /// Execute a SQL statement and return a Statement handle that /// streams batches via `fetchNextBatch()`. /// @@ -63,9 +95,7 @@ impl Connection { let inner = Arc::clone(&self.inner); guarded(async move { let guard = inner.lock().await; - let session = guard.as_ref().ok_or_else(|| { - napi::Error::new(napi::Status::InvalidArg, "connection already closed") - })?; + let session = guard.as_ref().ok_or_else(connection_closed_err)?; let mut stmt = session.statement(); stmt.spec().sql(sql); @@ -103,19 +133,14 @@ impl Connection { impl Drop for Connection { fn drop(&mut self) { - // Fire-and-forget close on the captured runtime. If `close()` - // was already called explicitly, `inner` holds `None` and the - // spawned task is a trivial no-op. `Drop` itself cannot - // `.await`, so callers who care about observing - // `DeleteSession` failures must call `close()` explicitly. - // - // Invariant: `handle.spawn` only completes its body while the - // tokio runtime captured at first-call time is alive. If this - // `Drop` ever runs after napi-rs has torn down its runtime, - // the spawned task is cancelled before `take()` runs and the - // kernel handle leaks (no `delete_session` is issued). This - // is unreachable under napi-rs's current process-exit - // ordering; revisit if that ordering ever changes. + // Best-effort cleanup: schedule a drop of the kernel handle on + // the captured tokio runtime. JS callers who need a + // guaranteed `DeleteSession` round-trip must call `close()` + // explicitly — `Drop` cannot `.await` and cannot surface + // failures, and the spawned task is subject to the runtime's + // lifetime. If process exit tears down the runtime before the + // task runs, the handle is dropped without a wire close; the + // server reclaims the session on its idle-timeout schedule. let Some(handle) = runtime::try_get_handle() else { // No async entry point ever ran — there's nothing to close. return; @@ -133,3 +158,54 @@ impl Drop for Connection { }); } } + +#[cfg(test)] +mod tests { + use super::*; + + // The closed-state error shape pins the TS adapter's reviver + // contract — a future maintainer who switches back to raw + // `napi::Error::new(Status::InvalidArg, "...")` will break this + // test instead of silently breaking the adapter. + + fn assert_invalid_statement_handle_envelope(err: &napi::Error) { + let msg = err.reason.as_str(); + assert!( + msg.starts_with(crate::error::ERROR_SENTINEL), + "expected envelope-sentinel-prefixed error, got: {msg}", + ); + assert!( + msg.contains(r#""code":"InvalidStatementHandle""#), + "envelope payload missing InvalidStatementHandle code: {msg}", + ); + } + + #[test] + fn connection_closed_err_carries_invalid_statement_handle_envelope() { + let err = connection_closed_err(); + assert_invalid_statement_handle_envelope(&err); + assert!( + err.reason.contains("connection already closed"), + "closed-state error must carry the human message: {}", + err.reason, + ); + } + + #[test] + fn connection_closed_err_status_collapses_to_invalid_arg() { + let err = connection_closed_err(); + assert_eq!(err.status, napi::Status::InvalidArg); + } + + #[test] + fn session_id_is_cached_and_survives_close() { + // The cached id is stored on the wrapper, not on the kernel + // Session — so even after close() takes the session out of + // `inner`, the getter still returns the original id. + let conn = Connection { + inner: Arc::new(Mutex::new(None)), // "already closed" + session_id: "session-survives-close".to_owned(), + }; + assert_eq!(conn.session_id(), "session-survives-close"); + } +} diff --git a/napi/src/database.rs b/napi/src/database.rs index 76223aaa..b94cafcc 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -19,14 +19,10 @@ //! `Database` wrapper on top of this binding, so the napi surface itself //! stays flat: one free function, one opaque `Connection` class. //! -//! Rationale for a free function over a static class method: -//! - napi-rs v2's static-method codegen for async functions returning a -//! `#[napi]` struct is fragile — the runtime registration sometimes -//! omits the method from the class object. Free `#[napi]` functions -//! go through a different, more stable codegen path. -//! - There is no kernel-side `Database` state to wrap; everything -//! meaningful lives on `Session`. A wrapper class with no fields adds -//! a JS object allocation per session for no benefit. +//! A free function (not a static method on a wrapper class) because +//! there is no kernel-side `Database` state to hold — everything +//! meaningful lives on `Session`. A `Database` wrapper class with no +//! fields would add a JS object allocation per session for no benefit. use std::collections::HashMap; use std::sync::Arc; @@ -120,8 +116,10 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result Option` — drives //! `ResultStream::next_batch().await`, serialises the borrowed //! `RecordBatch` to Arrow IPC bytes, returns them to JS. -//! - `Statement.schema() -> ArrowSchema` — returns the cached schema -//! from the kernel side, serialised as a schema-only IPC payload. +//! - `Statement.schema() -> ArrowSchema` — returns the schema cached +//! at construction time, serialised as a schema-only IPC payload. +//! Available even after `close()` so JS callers can build error +//! reports against a disposed statement. //! - `Statement.cancel()` / `Statement.close()` — forwards to //! `ExecutedStatement::cancel/close` via the //! `ExecutedStatementHandle` trait. Drop fires-and-forgets close //! if not already explicitly closed. +//! - `Statement.statementId` — server-issued statement id, cached at +//! construction and exposed for log correlation against kernel / +//! server logs which key on the same id. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tokio::sync::Mutex; use arrow_ipc::writer::StreamWriter; -use databricks_sql_kernel::{ExecutedStatement, ExecutedStatementHandle, ResultBatch}; +use arrow_schema::SchemaRef; +use databricks_sql_kernel::{ + Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, +}; use crate::error::napi_err_from_kernel; use crate::result::{ArrowBatch, ArrowSchema}; @@ -37,58 +46,87 @@ use crate::util::guarded; /// Opaque executed-statement handle. /// -/// `inner` is wrapped in `Arc>>` so: -/// - `fetch_next_batch` can `await` `ResultStream::next_batch` which -/// requires `&mut ExecutedStatement` (via `result_stream_mut`), -/// - `cancel` / `close` (which take `&self` on the kernel side via the -/// `ExecutedStatementHandle` trait) can run concurrently with each -/// other from a JS perspective without panicking, -/// - `Drop` can hand the inner handle off to a tokio task without -/// touching `&mut self` across an `await`. +/// **Current concurrency shape** — every method takes `inner.lock()` +/// and holds the guard across the kernel `.await`. tokio `Mutex` is +/// FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` +/// until it returns naturally. This is a known limitation that exists +/// because the napi shape has not yet been split into an +/// `Arc` (for cancel/close, which the +/// kernel exposes as `&self`-callable) plus a `Mutex>` only +/// for the borrowed-mut fetch path. The lock-shape refactor needs a +/// small kernel-side accessor and lands in a follow-up PR — see +/// `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. +/// +/// `schema` and `statement_id` are cached at construction so they +/// survive `close()` — JS callers building error reports against a +/// disposed statement can still read them. #[napi] pub struct Statement { inner: Arc>>, + /// Schema captured at construction. Available even after `close()`. + schema: SchemaRef, + /// Server-issued id. Available even after `close()` for log + /// correlation. + statement_id: String, + /// Set to `true` when `fetchNextBatch` observes the natural end of + /// the stream (`None`). `cancel()` short-circuits to `Ok(())` when + /// this is set, matching the JDBC `Statement.cancel()` no-op-after- + /// completion contract — without it, a defensive cancel after the + /// stream is drained surfaces an opaque server-side error. + finished: Arc, } impl Statement { /// Crate-internal constructor — called from /// `Connection::execute_statement` once the kernel hands back the - /// `ExecutedStatement`. + /// `ExecutedStatement`. Caches `schema` and `statement_id` so + /// they're readable after `close()`. pub(crate) fn from_executed(executed: ExecutedStatement) -> Self { + let schema = executed.schema(); + let statement_id = executed.statement_id().to_owned(); Self { inner: Arc::new(Mutex::new(Some(executed))), + schema, + statement_id, + finished: Arc::new(AtomicBool::new(false)), } } } #[napi] impl Statement { - /// Pull the next batch of results. Returns `None` when the stream + /// Server-issued statement id. Cached at construction; readable + /// even after `close()` so JS-side log lines can correlate against + /// kernel / server logs which key on the same id. + #[napi(getter)] + pub fn statement_id(&self) -> &str { + &self.statement_id + } + + /// Pull the next batch of results. Returns `null` when the stream /// is exhausted. The returned `ArrowBatch.ipcBytes` is a complete /// Arrow IPC stream (schema header + 1 record-batch message) /// suitable for handing to `apache-arrow`'s `RecordBatchReader`. /// - /// On `Err`, the stream is left in an unspecified state — the - /// recommended recovery is to call `close()` and discard the - /// `Statement`. Subsequent `fetchNextBatch()` calls after an error - /// are not guaranteed to succeed or fail consistently. + /// On `Err`, the stream is in an unspecified state — call + /// `close()` and discard the `Statement`. Subsequent + /// `fetchNextBatch()` calls after an error are not guaranteed to + /// succeed or fail consistently. #[napi] pub async fn fetch_next_batch(&self) -> napi::Result> { let inner = Arc::clone(&self.inner); + let schema = self.schema.clone(); + let finished = Arc::clone(&self.finished); guarded(async move { let mut guard = inner.lock().await; - let executed = guard.as_mut().ok_or_else(|| { - napi::Error::new(napi::Status::InvalidArg, "statement already closed") - })?; + let executed = guard.as_mut().ok_or_else(statement_closed_err)?; let stream = executed.result_stream_mut(); - // Capture the schema before borrowing the next batch — we - // include the schema header in every IPC payload so the - // JS-side consumer can decode each batch independently - // without carrying state across calls. - let schema = stream.schema(); let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; let Some(batch) = maybe_batch else { + // End of stream — record so a defensive cancel after + // natural completion can short-circuit to Ok(()). + finished.store(true, Ordering::Release); return Ok(None); }; // `ResultBatch` is `#[non_exhaustive]`; v0 only ever @@ -99,10 +137,14 @@ impl Statement { let record_batch = match batch { ResultBatch::Arrow(rb) => rb, _ => { - return Err(napi::Error::new( - napi::Status::GenericFailure, - "non-Arrow ResultBatch variant — binding needs upgrade", - )); + return Err(napi_err_from_kernel(KernelError::internal().message( + format!( + "non-Arrow ResultBatch variant from kernel — \ + databricks-sea-native v{} cannot decode this batch \ + shape, upgrade the binding", + env!("CARGO_PKG_VERSION"), + ), + ))); } }; let bytes = encode_ipc_stream(&schema, Some(record_batch))?; @@ -115,46 +157,50 @@ impl Statement { /// Result schema as an Arrow IPC payload (schema header only, no /// record-batch message). Available before any batches have been - /// fetched. + /// fetched, and remains available after `close()` — the kernel + /// materialises the schema eagerly so JS callers can build error + /// reports against a disposed statement. #[napi] pub async fn schema(&self) -> napi::Result { - let inner = Arc::clone(&self.inner); - guarded(async move { - let guard = inner.lock().await; - let executed = guard.as_ref().ok_or_else(|| { - napi::Error::new(napi::Status::InvalidArg, "statement already closed") - })?; - let schema = executed.schema(); - let bytes = encode_ipc_stream(&schema, None)?; - Ok(ArrowSchema { - ipc_bytes: bytes.into(), - }) + let bytes = encode_ipc_stream(&self.schema, None)?; + Ok(ArrowSchema { + ipc_bytes: bytes.into(), }) - .await } - /// Server-side cancel. Hits the wire on every call — the kernel - /// does not short-circuit cancel against an already-finished or - /// already-closed statement, so a cancel that races with natural - /// completion can surface a server-side error indicating the - /// statement is no longer in a cancellable state. Callers that - /// fire cancel defensively after `fetchNextBatch` returned `None` - /// should treat that error as benign. + /// Server-side cancel. + /// + /// Short-circuits to `Ok(())` if `fetchNextBatch` has already + /// returned `null` (stream naturally exhausted) — matches the + /// JDBC `Statement.cancel()` no-op-after-completion contract, so + /// JS callers can fire cancel defensively without distinguishing + /// "real cancel" from "raced with natural completion." + /// + /// Returns `KernelError(InvalidStatementHandle)` if the statement + /// has been explicitly `close()`d. #[napi] pub async fn cancel(&self) -> napi::Result<()> { + // Idempotent against natural completion. + if self.finished.load(Ordering::Acquire) { + return Ok(()); + } let inner = Arc::clone(&self.inner); guarded(async move { let guard = inner.lock().await; - let executed = guard.as_ref().ok_or_else(|| { - napi::Error::new(napi::Status::InvalidArg, "statement already closed") - })?; + let executed = guard.as_ref().ok_or_else(statement_closed_err)?; executed.cancel().await.map_err(napi_err_from_kernel) }) .await } - /// Explicit close. Awaits the server-side close so the JS caller - /// can observe failures. + /// Explicit close. Awaits the server-side `CloseStatement` so the + /// JS caller can observe failures (auth revoked mid-session, + /// network error, server-side error). Idempotent — a second call + /// on an already-closed statement returns `Ok`. + /// + /// On `Err`, the kernel leaves its internal `closed` flag false + /// so `Drop`'s fire-and-forget cleanup retries; the caller still + /// sees the error and can surface it to logs / telemetry. #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); @@ -176,14 +222,14 @@ impl Statement { impl Drop for Statement { fn drop(&mut self) { - // Invariant: `handle.spawn` only completes its body while the - // tokio runtime captured at first-call time is alive. If this - // `Drop` ever runs after napi-rs has torn down its runtime, - // the spawned task is cancelled before `take()` runs and the - // kernel handle leaks (no `close_statement` is issued). This - // is unreachable under napi-rs's current process-exit - // ordering; revisit (e.g. switch to a blocking close path) if - // that ordering ever changes. + // Best-effort cleanup: schedule a drop of the kernel handle on + // the captured tokio runtime. JS callers who need a + // guaranteed `close_statement` round-trip must call `close()` + // explicitly — `Drop` cannot `.await` and cannot surface + // failures, and the spawned task is subject to the runtime's + // lifetime. If process exit tears down the runtime before the + // task runs, the handle is dropped without a wire close; the + // server reclaims the statement when the session expires. let Some(handle) = runtime::try_get_handle() else { return; }; @@ -203,6 +249,20 @@ impl Drop for Statement { } } +/// Closed-state error builder. Routes through the kernel error +/// envelope so the TS-side reviver mints a typed +/// `KernelError(code='InvalidStatementHandle')` rather than a raw +/// `Status::InvalidArg` string the adapter can only match by +/// substring. Single source of truth for all four call sites +/// (fetch_next_batch / cancel and their Connection-side cousin) — +/// keeps the wire-message shape stable for the TS reviver's contract +/// test. +fn statement_closed_err() -> napi::Error { + napi_err_from_kernel( + KernelError::invalid_statement_handle().message("statement already closed"), + ) +} + /// Encode an Arrow schema (and optional one record batch) as an IPC /// stream payload. Used for both `schema()` (schema only) and /// `fetchNextBatch()` (schema + one batch). Returning a self-contained @@ -268,4 +328,107 @@ mod tests { assert_eq!(decoded[0].num_rows(), 3); assert_eq!(decoded[0].schema().fields(), schema.fields()); } + + // ─── Closed-state behaviour ───────────────────────────────────── + // + // These tests pin the contract that the closed-state error + // shape is the kernel envelope (sentinel + `code` field), not a + // raw `Status::InvalidArg` string the TS reviver can only match + // by substring. We call the `statement_closed_err` helper + // directly rather than awaiting `#[napi]` methods: the napi-rs + // attribute macro injects code paths that link against the + // native napi runtime (`napi_get_reference_value` etc.) which + // aren't available in `cargo test`. Testing the helper is the + // load-bearing assertion — the methods all funnel through it. + + fn assert_invalid_statement_handle_envelope(err: &napi::Error) { + let msg = err.reason.as_str(); + assert!( + msg.starts_with(crate::error::ERROR_SENTINEL), + "expected envelope-sentinel-prefixed error, got: {msg}", + ); + assert!( + msg.contains(r#""code":"InvalidStatementHandle""#), + "envelope payload missing InvalidStatementHandle code: {msg}", + ); + } + + #[test] + fn statement_closed_err_carries_invalid_statement_handle_envelope() { + // Single source of truth for all four call sites that surface + // closed-state errors. Pinning the wire shape here means a + // future maintainer who changes the error builder will break + // this test instead of silently breaking the TS adapter's + // reviver. + let err = statement_closed_err(); + assert_invalid_statement_handle_envelope(&err); + // The human-readable message survives — TS-side error + // .stack frames stay informative. + assert!( + err.reason.contains("statement already closed"), + "closed-state error must carry the human message: {}", + err.reason, + ); + } + + #[test] + fn statement_closed_err_status_collapses_to_invalid_arg() { + // The napi `Status` field collapses to `InvalidArg` because + // it's an enum with no `InvalidStatementHandle` variant. The + // TS adapter discriminates on the envelope `code` field, not + // on this status. Pin it so a future kernel-side ErrorCode + // -> Status mapping change is loud. + let err = statement_closed_err(); + assert_eq!(err.status, napi::Status::InvalidArg); + } + + #[test] + fn statement_id_is_cached_and_survives_close() { + // `statement_id` is stored on the wrapper, not delegated to + // the kernel handle. Once cached, `close()` (which sets + // `inner = None`) cannot null it out. + let stmt = Statement { + inner: Arc::new(Mutex::new(None)), // "already closed" + schema: make_schema(), + statement_id: "stmt-survives-close".to_owned(), + finished: Arc::new(AtomicBool::new(false)), + }; + assert_eq!(stmt.statement_id(), "stmt-survives-close"); + } + + #[test] + fn schema_field_is_cached_arc() { + // Schema is held as a cheap Arc, not a fresh clone — so the + // getter is O(1) even on a closed statement. Verify by + // confirming Arc::strong_count rises when we clone. + let schema = make_schema(); + let stmt = Statement { + inner: Arc::new(Mutex::new(None)), + schema: schema.clone(), + statement_id: "x".to_owned(), + finished: Arc::new(AtomicBool::new(false)), + }; + // Two refs alive: the local + the stmt field. + assert!(Arc::strong_count(&stmt.schema) >= 2); + drop(stmt); + // After dropping the stmt only the local remains. + assert_eq!(Arc::strong_count(&schema), 1); + } + + #[test] + fn finished_flag_starts_false_and_can_be_toggled() { + // Pin the cancel-after-completion contract at field level: + // `cancel()` reads `finished` and short-circuits to Ok(()) + // when set, matching the JDBC no-op-after-completion + // semantics. fetch_next_batch sets it when it returns None. + let stmt = Statement { + inner: Arc::new(Mutex::new(None)), + schema: make_schema(), + statement_id: "x".to_owned(), + finished: Arc::new(AtomicBool::new(false)), + }; + assert!(!stmt.finished.load(Ordering::Acquire)); + stmt.finished.store(true, Ordering::Release); + assert!(stmt.finished.load(Ordering::Acquire)); + } } diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 710029e9..0213dacd 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -126,19 +126,30 @@ impl ExecutedStatementHandle for ExecutedStatement { } async fn close(&self) -> Result<()> { - // Idempotent: the first call flips the flag; subsequent - // calls return Ok(()) without hitting the wire. The - // server-side close is idempotent too, but skipping the - // round-trip is cheaper and avoids ambiguous "double-close" - // log noise. + // Idempotent on success: a prior successful close sets + // `closed=true` and subsequent calls short-circuit. + // + // On wire failure we deliberately keep `closed=false` so that + // `Drop`'s fire-and-forget retry path runs as a fallback — + // otherwise a transient close failure would silently leak the + // server-side statement until session expiry. Mirrors + // `Session::close`. + // + // The `&self` signature allows two callers to race and both + // hit the wire. The server-side close is idempotent (it + // returns the same Ok for duplicate close_statement calls), + // so the only cost of the race is one redundant RPC — far + // better than dropping the retry contract. async { - if self.closed.swap(true, Ordering::AcqRel) { + if self.closed.load(Ordering::Acquire) { return Ok(()); } self.session .transport() .close_statement(&self.statement_id) - .await + .await?; + self.closed.store(true, Ordering::Release); + Ok(()) } .instrument(self.session.log_span().clone()) .await From 142e43cd97d26f76342a4d04266b337d71150e69 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 24 May 2026 18:42:09 +0000 Subject: [PATCH 06/28] fix(napi): map non-Arrow ResultBatch fallback to InvalidArgument MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Was: KernelError::internal() — pages oncall on telemetry false-positives because Internal-category errors are interpreted as kernel bugs. Now: KernelError::invalid_argument() — this isn't a kernel bug, it's "binding too old for the kernel it's linked against" (the kernel rolled a new ResultBatch variant that this binding's decode path doesn't know how to handle). Matches the sibling-binding convention at pyo3/src/fetch.rs:43,58. The error message retains env!("CARGO_PKG_VERSION") so the JS-side adapter surfaces actionable version-skew context to the user. Signed-off-by: Madhavendra Rathore --- napi/src/statement.rs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 9899796b..eb57b440 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -137,14 +137,23 @@ impl Statement { let record_batch = match batch { ResultBatch::Arrow(rb) => rb, _ => { - return Err(napi_err_from_kernel(KernelError::internal().message( - format!( + // `InvalidArgument`, not `Internal`: this isn't a + // kernel bug (which would page oncall via the + // Internal-category dashboards) — it's "binding + // too old for the kernel it's linked against." + // The kernel has rolled a new ResultBatch variant + // that this binding's decode path doesn't know + // how to handle, and the JS-side adapter should + // surface this as a version-skew error to the + // user. Matches the sibling-binding convention. + return Err(napi_err_from_kernel( + KernelError::invalid_argument().message(format!( "non-Arrow ResultBatch variant from kernel — \ - databricks-sea-native v{} cannot decode this batch \ - shape, upgrade the binding", + databricks-sea-native v{} cannot decode this batch \ + shape, upgrade the binding", env!("CARGO_PKG_VERSION"), - ), - ))); + )), + )); } }; let bytes = encode_ipc_stream(&schema, Some(record_batch))?; From 9c56fbedcd268e8cb46a1430cbdc70e7260bf39b Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 25 May 2026 19:09:45 +0000 Subject: [PATCH 07/28] =?UTF-8?q?fix(napi,kernel):=20address=20PR=20#25=20?= =?UTF-8?q?review=20=E2=80=94=20sync=20schema(),=20close=20JSDoc=20honesty?= =?UTF-8?q?,=20IPC=20capacity,=20field=20docs,=20executed=5Fasync=20close?= =?UTF-8?q?=20parity,=20cancel-after-parent-drop=20regression=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses 7 of the 20 review findings on PR #25 directly. Remaining findings are tracked as JIRA candidates in the NodeJS workflow repo under sea-workflow/jira-candidates/. - F1+F2 (napi/src/statement.rs): drop async from Statement::schema(). The body is pure CPU work over a cached Arc and matches pyo3/src/statement.rs::arrow_schema (sync). napi-rs handles panic conversion for sync #[napi] entry points, so the util::guarded wrapper used by the remaining async methods is not required here. - F7/I4 (napi/src/{connection,statement}.rs): rewrite the close() JSDoc to honestly state that errors are terminal from the JS side. The kernel handle is .take()-ed before the wire call (because both Session::close and ExecutedStatement::close consume the handle by value or via the close-flag pattern), so a JS-side retry sees an already-closed wrapper and returns Ok(()). Only the kernel-level Drop fires a single fire-and-forget retry. The old JSDoc claim that callers could observe and retry close failures was misleading. - F14 (napi/src/statement.rs::encode_ipc_stream): pre-size the IPC buffer with Vec::with_capacity( batch.map(get_array_memory_size).unwrap_or(0) + 4096) instead of Vec::new(). Removes ~17 reallocations on a typical 500 KB batch; 4 KiB slack covers schema header + IPC framing overhead. - F18 (napi/src/result.rs): add /// field-level docs on ArrowBatch.ipc_bytes and ArrowSchema.ipc_bytes so the generated .d.ts carries the "Decode with apache-arrow's RecordBatchReader" hint. - F3+F10 (src/statement/executed_async.rs): mirror the new load -> wire -> store-on-success close pattern from ExecutedStatement::close into ExecutedAsyncStatement::close. Restores symmetric retry-on-failure contract across both executed handles. The retry branch is currently dead code because the SEA transport (src/client/sea.rs::close_statement) swallows errors; tracked as a follow-up kernel PR in the JIRA candidate file. Until the transport surfaces errors, the new pattern is forward-prep with identical observable behavior to the previous swap pattern. - F9 (tests/v0_execute_wiremock.rs): add kernel_invariant_parent_drop_invalidates_executed_cancel. Pins the kernel-level invariant that PR #29's binding-side fix is designed around: dropping the parent Statement invalidates any outstanding ExecutedStatement's validity flag, so a subsequent cancel() short-circuits locally with InvalidStatementHandle. PR #29's StatementInner { _parent, executed } shape keeps the parent alive to avoid hitting this short-circuit. This test fails loudly if the kernel ever weakens the parent-drop semantic. Refs: vikrantpuppala PR #25 review at 2026-05-25T15:40-15:44Z (F1/F2/F3/F7/F9/F10/F14/F18). Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 12 ++++-- napi/src/result.rs | 5 +++ napi/src/statement.rs | 36 +++++++++++++++--- src/statement/executed_async.rs | 31 +++++++++++++--- tests/v0_execute_wiremock.rs | 66 +++++++++++++++++++++++++++++++++ 5 files changed, 137 insertions(+), 13 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 8f584f0c..58be04ca 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -111,9 +111,15 @@ impl Connection { /// warehouse stopped, network error). Idempotent — a second call /// on an already-closed connection returns `Ok`. /// - /// On `Err`, the kernel leaves its internal `closed` flag false - /// so `Drop`'s fire-and-forget cleanup retries; the caller still - /// sees the error and can surface it to logs / telemetry. + /// **Errors are terminal from the JS side.** The kernel session + /// handle is consumed (`take()`) BEFORE the wire `DeleteSession` + /// runs, because `Session::close` takes `self` by value. On `Err`, + /// the napi `inner` is already `None`, so a JS-side retry sees a + /// closed connection and returns `Ok(())` without re-attempting + /// the wire call. The kernel's own `Drop` fire-and-forget retry + /// runs once in the background — the JS caller can log the error + /// but cannot drive a retry. If you need retry-on-failure + /// semantics for `DeleteSession`, layer them above this method. #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); diff --git a/napi/src/result.rs b/napi/src/result.rs index 488c0851..f0515e23 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -25,6 +25,8 @@ use napi::bindgen_prelude::Buffer; /// the schema header so the JS-side reader is stateless). #[napi(object)] pub struct ArrowBatch { + /// Arrow IPC stream payload (schema header + 1 record-batch + /// message). Decode with `apache-arrow`'s `RecordBatchReader`. pub ipc_bytes: Buffer, } @@ -32,5 +34,8 @@ pub struct ArrowBatch { /// record-batch messages). Returned by `Statement.schema()`. #[napi(object)] pub struct ArrowSchema { + /// Arrow IPC stream payload (schema header only, no record-batch + /// messages). Decode with `apache-arrow`'s `RecordBatchReader` — + /// the reader will expose the schema and immediately end. pub ipc_bytes: Buffer, } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index eb57b440..4fcab4b0 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -169,8 +169,16 @@ impl Statement { /// fetched, and remains available after `close()` — the kernel /// materialises the schema eagerly so JS callers can build error /// reports against a disposed statement. + /// + /// Sync because the body has no `.await` — `encode_ipc_stream` is + /// pure CPU work over an `Arc` already cached on the + /// wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). + /// napi-rs converts a panic in a sync `#[napi]` entry point into a + /// thrown JS error via its own macro-expanded boundary, so the + /// `util::guarded` `catch_unwind` wrapper that the `async fn` + /// entry points use is not required for this method. #[napi] - pub async fn schema(&self) -> napi::Result { + pub fn schema(&self) -> napi::Result { let bytes = encode_ipc_stream(&self.schema, None)?; Ok(ArrowSchema { ipc_bytes: bytes.into(), @@ -207,9 +215,18 @@ impl Statement { /// network error, server-side error). Idempotent — a second call /// on an already-closed statement returns `Ok`. /// - /// On `Err`, the kernel leaves its internal `closed` flag false - /// so `Drop`'s fire-and-forget cleanup retries; the caller still - /// sees the error and can surface it to logs / telemetry. + /// **Errors are terminal from the JS side.** The kernel executed + /// handle is taken out of `inner` BEFORE the wire `CloseStatement` + /// runs (so `Drop` knows there's nothing left to clean up). On + /// `Err`, the napi `inner` is already `None`, so a JS-side retry + /// sees a closed statement and returns `Ok(())` without re- + /// attempting the wire call. The kernel-level `ExecutedStatement` + /// has been consumed at that point and the value is dropped on + /// the way out of the closure — the kernel's `ExecutedStatement:: + /// Drop` then fires-and-forgets a single retry on the captured + /// runtime. The JS caller can log the error but cannot drive a + /// further retry. If you need retry-on-failure semantics for + /// `CloseStatement`, layer them above this method. #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); @@ -285,7 +302,16 @@ fn encode_ipc_stream( fn arrow_err(e: impl std::fmt::Display) -> napi::Error { napi::Error::new(napi::Status::GenericFailure, e.to_string()) } - let mut buf: Vec = Vec::new(); + // Pre-size the buffer so a typical 500KB batch doesn't reallocate + // ~17 times growing from `Vec::new()`'s default capacity of 0. + // `get_array_memory_size` is the kernel-side memory footprint (close + // enough to the IPC-encoded size for capacity-hint purposes — IPC + // adds ~hundreds of bytes of framing per batch, not orders of + // magnitude). 4 KiB slack covers the schema-header on the + // schema-only path (`batch = None`) and the framing overhead on + // the schema+batch path. + let estimated = batch.map(|rb| rb.get_array_memory_size()).unwrap_or(0) + 4096; + let mut buf: Vec = Vec::with_capacity(estimated); { let mut writer = StreamWriter::try_new(&mut buf, schema).map_err(arrow_err)?; if let Some(rb) = batch { diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 019335f7..91aad839 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -374,17 +374,38 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { } async fn close(&self) -> Result<()> { - // Idempotent — the first call flips the flag; subsequent - // calls return Ok(()) without hitting the wire. Matches - // ExecutedStatement::close's contract. + // Idempotent on success: a prior successful close sets + // `closed=true` and subsequent calls short-circuit. + // + // On wire failure we deliberately keep `closed=false` so that + // `Drop`'s fire-and-forget retry path runs as a fallback — + // otherwise a transient close failure would silently leak the + // server-side statement until session expiry. Mirrors + // `Session::close` and the sibling `ExecutedStatement::close`. + // + // The `&self` signature allows two callers to race and both + // hit the wire. The server-side close is idempotent (it + // returns the same Ok for duplicate close_statement calls), + // so the only cost of the race is one redundant RPC — far + // better than dropping the retry contract. + // + // Note: today's SEA transport at `src/client/sea.rs:: + // close_statement` swallows wire errors and always returns + // `Ok(())`, so the retry-on-failure branch is reachable only + // once the transport is changed to surface real errors. The + // load-then-store-on-success shape is the forward-prep for + // that change — see the JIRA candidate at + // `sea-workflow/jira-candidates/2026-05-25-kernel-sea-close-statement-surface-errors.md`. async { - if self.closed.swap(true, Ordering::AcqRel) { + if self.closed.load(Ordering::Acquire) { return Ok(()); } self.session .transport() .close_statement(&self.statement_id) - .await + .await?; + self.closed.store(true, Ordering::Release); + Ok(()) } .instrument(self.session.log_span().clone()) .await diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index f7f3aec9..fcab664f 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -527,3 +527,69 @@ async fn row_accessors_walk_succeeded_result() { assert!(stream.next_row_in_batch().is_none()); exec.close().await.expect("close"); } + +// ─── Cancel-after-parent-drop regression guard (PR #25 / #29) ───── +// +// Pins the kernel-level contract that the napi binding (PR #29) must +// counteract. +// +// The kernel `Statement` (mutable) shares a `ValidityFlag` with each +// `ExecutedStatement` / `ExecutedAsyncStatement` it produces. Dropping +// the parent calls `valid.invalidate()` on that shared flag — so any +// subsequent `ExecutedStatement::cancel` short-circuits locally with +// `KernelError(InvalidStatementHandle)` without a wire round-trip. +// +// `close()` is **not** validity-checked: dropping the parent still +// lets the server-side `CloseStatement` round-trip run so the server +// resource is released. The asymmetry is intentional — cancel must +// be cheap on a zombie handle (no wire) while close must always +// reach the server when possible. +// +// The cancel-lifecycle bug surfaced by PR #25 is that the napi +// `Connection::execute_statement` wrapper drops the parent kernel +// `Statement` at end of its closure, leaving the JS-visible +// `Statement` holding only the `ExecutedStatement`. The next +// `Statement.cancel()` from JS hits the short-circuit above and +// returns `InvalidStatementHandle`. +// +// PR #29 fixes the binding by wrapping the inner state in a +// `StatementInner { _parent, executed }` struct that keeps the +// parent alive for the wrapper's lifetime. +// +// This test pins the **kernel invariant** the fix is designed +// around. If the kernel ever weakens the parent-drop semantics +// (e.g. doesn't invalidate on Drop), this test fails loudly and +// the binding's fix can be reviewed for whether it's still needed. +// If the kernel keeps the semantics, the binding-side regression +// guard (added separately once #29 lands) holds the binding to +// account. + +#[tokio::test] +async fn kernel_invariant_parent_drop_invalidates_executed_cancel() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("n", vec![1]); + mount_execute(&server, succeeded_inline_body("stmt-parent-drop", &batch)).await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let exec = stmt.execute().await.expect("execute"); + + // This is the exact shape the napi binding's + // `Connection::execute_statement` produces today (PR #25): the + // kernel `Statement` (`stmt`) is dropped at end of the closure + // while the caller keeps holding the `ExecutedStatement` + // (`exec`). PR #29 fixes the binding by stashing `stmt` alongside + // `exec` so the parent outlives the executed handle. + drop(stmt); + + let err = exec + .cancel() + .await + .expect_err("cancel after parent Statement drop must short-circuit"); + assert_eq!(err.code, ErrorCode::InvalidStatementHandle); +} From 4acde6aba4d023a9c7d2fda2a6da75c7bb7cdfe5 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Fri, 15 May 2026 09:02:54 +0000 Subject: [PATCH 08/28] napi: propagate StatementInner ValidityFlag fix from sea-operation When the binding's Statement wrapper was first written it held only the kernel's ExecutedStatement. The sea-operation feature surfaced a bug: kernel Statement::Drop invalidates its produced ExecutedStatement via a shared ValidityFlag, so the parent kernel Statement constructed in Connection::execute_statement was dropping at the end of that function and rendering every subsequent cancel()/close() on the executed handle a no-op throwing InvalidStatementHandle. Fix: introduce StatementInner { _parent: KernelStatement, executed } in the wrapper so both lifetimes are tied. Statement::from_executed now takes the parent statement alongside the executed handle. Connection::execute_statement passes both in. ValidityFlag stays set for as long as JS holds the wrapper. Originally landed in the nodejs sea-operation worktree (e06a5e8); relocated here as part of the napi-source move into the kernel workspace. The integration branch's version was the authoritative one because it had all downstream feature merges layered in. Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 6 ++- napi/src/statement.rs | 84 ++++++++++++++++++++++++++++++++++-------- 2 files changed, 74 insertions(+), 16 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 58be04ca..20d3d11a 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -101,7 +101,11 @@ impl Connection { stmt.spec().sql(sql); let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; - Ok(Statement::from_executed(executed)) + // Pass the parent kernel `Statement` into the JS wrapper. + // Dropping it here would invalidate the executed handle + // via the shared ValidityFlag — see `StatementInner` docs + // in `statement.rs` for the rationale. + Ok(Statement::from_executed(stmt, executed)) }) .await } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 4fcab4b0..2377addc 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -37,6 +37,7 @@ use arrow_ipc::writer::StreamWriter; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, + Statement as KernelStatement, }; use crate::error::napi_err_from_kernel; @@ -44,6 +45,31 @@ use crate::result::{ArrowBatch, ArrowSchema}; use crate::runtime; use crate::util::guarded; +/// Inner state for the JS-visible `Statement` wrapper. +/// +/// **Why we also hold the parent kernel `Statement`:** the kernel's +/// `Statement::Drop` (`src/statement/mutable.rs:341-361`) invalidates +/// its produced `ExecutedStatement` via the shared `ValidityFlag`. If +/// the binding wrapper held only the `ExecutedStatement`, the parent +/// kernel `Statement` constructed in `Connection::execute_statement` +/// would drop at the end of that function, flipping the validity flag +/// and rendering every subsequent `cancel()` / `close()` call against +/// the executed handle a no-op that throws +/// `InvalidStatementHandle("executed-statement handle has been +/// invalidated by a re-execute on its parent Statement")`. +/// +/// Keeping the kernel `Statement` alive in the same `Arc>` +/// as the `ExecutedStatement` ties their lifetimes together — the +/// validity flag stays set for as long as JS holds the wrapper. +struct StatementInner { + /// The kernel's `Statement` (mutable). Kept alive solely to + /// prevent its `Drop` from invalidating `executed`. + _parent: KernelStatement, + /// The executed handle — drives `fetchNextBatch` / `cancel` / + /// `close`. + executed: ExecutedStatement, +} + /// Opaque executed-statement handle. /// /// **Current concurrency shape** — every method takes `inner.lock()` @@ -62,7 +88,11 @@ use crate::util::guarded; /// disposed statement can still read them. #[napi] pub struct Statement { - inner: Arc>>, + /// Wraps the kernel `Statement` + `ExecutedStatement` pair so the + /// parent's `Drop` doesn't fire (and invalidate the executed + /// handle via the shared `ValidityFlag`) while JS still holds + /// this wrapper. See `StatementInner` docs above. + inner: Arc>>, /// Schema captured at construction. Available even after `close()`. schema: SchemaRef, /// Server-issued id. Available even after `close()` for log @@ -79,13 +109,20 @@ pub struct Statement { impl Statement { /// Crate-internal constructor — called from /// `Connection::execute_statement` once the kernel hands back the - /// `ExecutedStatement`. Caches `schema` and `statement_id` so - /// they're readable after `close()`. - pub(crate) fn from_executed(executed: ExecutedStatement) -> Self { + /// `ExecutedStatement`. The parent kernel `Statement` is passed + /// in alongside so its `Drop` doesn't fire while the JS side + /// still holds the executed handle (see `StatementInner` docs + /// above). `schema` and `statement_id` are read off the executed + /// handle here and cached on the wrapper so they remain readable + /// after `close()` for log correlation / error reporting. + pub(crate) fn from_executed(parent: KernelStatement, executed: ExecutedStatement) -> Self { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); Self { - inner: Arc::new(Mutex::new(Some(executed))), + inner: Arc::new(Mutex::new(Some(StatementInner { + _parent: parent, + executed, + }))), schema, statement_id, finished: Arc::new(AtomicBool::new(false)), @@ -119,7 +156,8 @@ impl Statement { let finished = Arc::clone(&self.finished); guarded(async move { let mut guard = inner.lock().await; - let executed = guard.as_mut().ok_or_else(statement_closed_err)?; + let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?; + let executed = &mut inner_state.executed; let stream = executed.result_stream_mut(); let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; @@ -204,8 +242,12 @@ impl Statement { let inner = Arc::clone(&self.inner); guarded(async move { let guard = inner.lock().await; - let executed = guard.as_ref().ok_or_else(statement_closed_err)?; - executed.cancel().await.map_err(napi_err_from_kernel) + let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; + inner_state + .executed + .cancel() + .await + .map_err(napi_err_from_kernel) }) .await } @@ -231,14 +273,22 @@ impl Statement { pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); guarded(async move { - // Take the handle out so `Drop` knows there's nothing left - // to clean up. - let executed = { + // Take the inner state out so `Drop` knows there's nothing + // left to clean up. The parent kernel `Statement`'s Drop + // runs here too — but only AFTER the executed handle's + // close has finished, so we still observe a clean + // server-side close result before the validity flag flips. + let inner_state = { let mut guard = inner.lock().await; guard.take() }; - if let Some(executed) = executed { - executed.close().await.map_err(napi_err_from_kernel)?; + if let Some(inner_state) = inner_state { + inner_state + .executed + .close() + .await + .map_err(napi_err_from_kernel)?; + // _parent drops here, after close has resolved. } Ok(()) }) @@ -261,12 +311,16 @@ impl Drop for Statement { }; let inner = Arc::clone(&self.inner); handle.spawn(async move { - // Drop the executed statement on the runtime. The kernel's + // Drop the inner state on the runtime. The kernel's // `ExecutedStatement::Drop` already spawns a fire-and-forget // `close_statement` against its own captured handle, so we // just need to ensure the value is dropped inside a tokio // context (the kernel's Drop reads `runtime_handle.clone()` - // and spawns; that handle is the same one we captured here). + // and spawns; that handle is the same one we captured + // here). The kernel `Statement` we kept alive in + // `_parent` drops at the same time, but it only owns + // local state (its Drop is non-async — see + // `src/statement/mutable.rs:341-361`). let _taken = { let mut guard = inner.lock().await; guard.take() From 09472d788cc8713ef4c30bb090ffc7a7edd911d2 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Fri, 15 May 2026 15:01:42 +0000 Subject: [PATCH 09/28] krn-napi-binding: reclassify OAuth token-exchange failures as Unauthenticated Per src/kernel_error.rs:74-77 doc-comment, Unauthenticated is the intended ErrorCode for "Server returned HTTP 401 (or OIDC discovery rejected the token request)". M2M and U2M token-exchange paths were using Error::io() (-> Internal), which is reserved for kernel-side I/O / parsing failures. The misclassification caused authentication failures to surface in NodeJS as HiveDriverError instead of AuthenticationError (D-015). Fix: m2m.rs:270 and u2m.rs:433 swap Error::io() -> Error::unauthenticated(). No kernel unit tests assert ErrorCode::Internal on these paths (verified by grep) so no test updates are needed. The U2M test `test_u2m_cache_miss_with_expired_refresh` asserts only `result.is_err()`, which remains true. Deferred (worth a follow-up): distinguish oauth2::RequestTokenError subtypes so 5xx token-endpoint failures get NetworkError while invalid_client / invalid_grant / unauthorized_client stay Unauthenticated. The current change correctly handles the dominant case (bad-credentials -> 400/401 from server) and matches the existing kernel doc-comment intent. Signed-off-by: Madhavendra Rathore --- src/auth/oauth/m2m.rs | 2 +- src/auth/oauth/u2m.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/auth/oauth/m2m.rs b/src/auth/oauth/m2m.rs index 1ba757f5..74e93ec8 100644 --- a/src/auth/oauth/m2m.rs +++ b/src/auth/oauth/m2m.rs @@ -287,7 +287,7 @@ impl AuthProvider for ClientCredentialsProvider { .request_async(http_client.inner()) .await .map_err(|e| { - Error::io() + Error::unauthenticated() .message(format!("M2M token exchange failed: {}", e)) .context("client credentials grant") })?; diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index f1c5d7e0..2d2e8b08 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -447,7 +447,7 @@ impl AuthProvider for AuthorizationCodeProvider { .request_async(http_client.inner()) .await .map_err(|e| { - Error::io() + Error::unauthenticated() .message(format!("U2M authorization code exchange failed: {}", e)) .context("authorization code grant") })?; From c14c1ff6bacf92967db59aaaed173b45cad01d1f Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 17 May 2026 12:37:21 +0000 Subject: [PATCH 10/28] feat(config): bump HttpConfig pool_max_idle_per_host default 10 -> 100 Matches the JDBC driver's `HttpConnectionPoolSize` default (100) and the kernel-internal `HttpClientConfig` default. Closes ~9x of the throughput gap with the NodeJS thrift driver's `maxSockets: Infinity` default for high-concurrency workloads (bursty parallel executeStatement, parallel CloudFetch chunk downloads). reqwest/hyper does not bound this; the prior 10 was a kernel-side conservative choice. Spec: sea-workflow/specs/07-errors-retries/connection-pool-default-mismatch.md Signed-off-by: Madhavendra Rathore --- src/config.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index d5ae76ca..9d6e2b7a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -321,7 +321,13 @@ pub struct HttpConfig { /// Maximum total time across retries for a single logical RPC. pub overall_timeout: Duration, - /// Connection pool size. + /// Connection pool size (max idle warm sockets per remote host). + /// + /// Defaults to `100`, matching the JDBC driver's `HttpConnectionPoolSize` + /// default. Raise this for workloads that burst many concurrent + /// `executeStatement` calls or CloudFetch chunk downloads against a + /// single host; too low a value forces fresh TLS handshakes when the + /// pool fills. pub pool_max_idle_per_host: usize, } @@ -330,7 +336,7 @@ impl Default for HttpConfig { Self { request_timeout: Duration::from_secs(120), overall_timeout: Duration::from_secs(900), - pool_max_idle_per_host: 10, + pool_max_idle_per_host: 100, } } } @@ -640,4 +646,15 @@ mod tests { assert!(s.contains("")); assert!(s.contains("databricks")); } + + // ─── HttpConfig defaults ─────────────────────────────────────── + + #[test] + fn http_config_default_pool_max_idle_per_host_is_100() { + // Matches the JDBC driver's `HttpConnectionPoolSize` default and + // narrows the throughput gap with thrift's `maxSockets: Infinity` + // for high-concurrency workloads. See + // `sea-workflow/specs/07-errors-retries/connection-pool-default-mismatch.md`. + assert_eq!(HttpConfig::default().pool_max_idle_per_host, 100); + } } From 8c0aabc04d07251a10dc0c1cd0d1d6c4e9279405 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sat, 16 May 2026 13:54:26 +0000 Subject: [PATCH 11/28] krn-tls-public-api: expose TlsConfig fields + stop discarding in session.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The kernel has had working reqwest plumbing for custom CA certs, self-signed acceptance, and hostname-verification skip at client/http.rs since the original TLS migration. That implementation has been unreachable from any public wrapper because (a) the public TlsConfig struct in config.rs was empty and (b) session.rs explicitly discarded any caller-supplied TlsConfig and replaced with default. This commit: - Adds custom_ca_cert / accept_self_signed / skip_hostname_verification fields to public TlsConfig - Adds a trusted_certificate_pem field to the internal HttpTlsConfig so the public custom_ca_cert (Vec) can flow through without a tempfile shim — foreign-language wrappers (napi-rs Buffer / pyo3 bytes) get a direct path - Adds HttpTlsConfig::from_public / From<&public::TlsConfig> to project the public surface onto the internal layer - Wires session.rs::build_http_client_config to call HttpTlsConfig::from_public(&config.tls) instead of discarding - Adds a custom Debug impl on the public TlsConfig that summarises the cert bytes ("") instead of dumping the whole PEM into log lines - Adds builder-introspection tests that construct a DatabricksHttpClient via the public -> internal mapping with each flag in turn and verify the reqwest builder succeeds Public TlsConfig defaults remain strict: accept_self_signed=false, skip_hostname_verification=false, custom_ca_cert=None. The default projection produces an internal config with `None` everywhere on the permissive switches so RUST_LOG output stays free of no-op overrides. Unblocks NodeJS-side TLS Buffer->tempfile shim row (kernel now accepts Vec directly; no tempfile needed) and is a prereq for future mTLS work (client_cert / client_key remain unwired — that's a separate follow-up). The pre-existing lib-test failure in client::http::tests:: test_http_client_with_invalid_pem (D-016: reqwest::Certificate:: from_pem accepts garbage strings under the rustls-tls backend) is unrelated to this commit and reproduces on the krn-napi-binding base. Signed-off-by: Madhavendra Rathore --- src/client/http.rs | 133 +++++++++++++++++++++++++++++++++++++++++++++ src/config.rs | 89 ++++++++++++++++++++++++++++-- src/session.rs | 15 +++-- 3 files changed, 224 insertions(+), 13 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 3bc4a8bb..a074dcdb 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -93,6 +93,42 @@ pub struct TlsConfig { pub allow_hostname_mismatch: Option, /// Path to a PEM-encoded CA certificate file to add to the trust store. pub trusted_certificate_path: Option, + /// PEM-encoded CA certificate bytes to add to the trust store. + /// Alternative to `trusted_certificate_path` for callers that + /// have the cert in-memory (e.g. foreign-language wrappers + /// passing `Buffer` / `bytes` without a tempfile shim). When + /// both are set, the path is read first, then the in-memory PEM + /// is added as an additional root. + pub trusted_certificate_pem: Option>, +} + +impl TlsConfig { + /// Project the public [`crate::config::TlsConfig`] onto the internal + /// HTTP-client TLS struct. Public fields land on their internal + /// counterparts; internal-only fields (`enabled`, + /// `trusted_certificate_path`) stay at their defaults. + /// + /// `accept_self_signed` / `skip_hostname_verification` are booleans + /// on the public surface (default: stricter); the internal layer + /// uses `Option` so the existing `None == default` semantics + /// are preserved. We map a `false` to `None` rather than + /// `Some(false)` to keep `Debug` output / RUST_LOG noise free of + /// no-op overrides. + pub fn from_public(cfg: &crate::config::TlsConfig) -> Self { + Self { + enabled: None, + allow_self_signed: cfg.accept_self_signed.then_some(true), + allow_hostname_mismatch: cfg.skip_hostname_verification.then_some(true), + trusted_certificate_path: None, + trusted_certificate_pem: cfg.custom_ca_cert.clone(), + } + } +} + +impl From<&crate::config::TlsConfig> for TlsConfig { + fn from(cfg: &crate::config::TlsConfig) -> Self { + Self::from_public(cfg) + } } /// Configuration for the HTTP client. @@ -213,6 +249,18 @@ impl DatabricksHttpClient { debug!("Added custom CA certificate from: {}", cert_path); } + if let Some(ref pem) = config.tls.trusted_certificate_pem { + let cert = reqwest::Certificate::from_pem(pem).map_err(|e| { + Error::invalid_argument() + .message(format!("Invalid in-memory PEM certificate: {}", e)) + })?; + builder = builder.add_root_certificate(cert); + debug!( + "Added custom CA certificate from in-memory bytes ({} bytes)", + pem.len() + ); + } + // Apply proxy configuration if let Some(ref proxy_url) = config.proxy.url { // Validate proxy URL scheme @@ -811,6 +859,91 @@ lGrv15pBcePj assert!(err_msg.contains("Invalid PEM certificate")); } + #[test] + fn test_http_client_with_in_memory_pem_bytes() { + // Public-API path: PEM bytes pass through the internal + // `trusted_certificate_pem` field directly (no tempfile shim + // required by foreign-language wrappers). + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(TEST_CA_CERT_PEM.as_bytes().to_vec()); + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!(client.is_ok()); + } + + #[test] + fn test_tls_config_from_public_maps_all_fields() { + // accept_self_signed=true maps to Some(true); + // skip_hostname_verification=true maps to Some(true); + // custom_ca_cert maps to trusted_certificate_pem. + let public = crate::config::TlsConfig { + custom_ca_cert: Some(b"pem-bytes".to_vec()), + accept_self_signed: true, + skip_hostname_verification: true, + }; + let internal = TlsConfig::from_public(&public); + assert_eq!(internal.allow_self_signed, Some(true)); + assert_eq!(internal.allow_hostname_mismatch, Some(true)); + assert_eq!( + internal.trusted_certificate_pem, + Some(b"pem-bytes".to_vec()) + ); + // `enabled` and `trusted_certificate_path` stay at internal + // defaults — the public surface doesn't expose them. + assert!(internal.enabled.is_none()); + assert!(internal.trusted_certificate_path.is_none()); + } + + #[test] + fn test_tls_config_from_public_default_is_strict() { + // A default public TlsConfig produces an internal config that + // does NOT relax any default — `None` everywhere on the + // permissive switches so log output stays clean. + let internal = TlsConfig::from_public(&crate::config::TlsConfig::default()); + assert!(internal.allow_self_signed.is_none()); + assert!(internal.allow_hostname_mismatch.is_none()); + assert!(internal.trusted_certificate_pem.is_none()); + assert!(internal.trusted_certificate_path.is_none()); + } + + #[test] + fn test_http_client_via_public_tls_config_with_self_signed_accepts_build() { + // End-to-end builder check: a Session-style construction + // (public TlsConfig -> from_public -> HttpClientConfig -> + // reqwest builder) succeeds when accept_self_signed is set. + let public = crate::config::TlsConfig { + custom_ca_cert: None, + accept_self_signed: true, + skip_hostname_verification: false, + }; + let config = HttpClientConfig { + tls: TlsConfig::from_public(&public), + ..HttpClientConfig::default() + }; + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!( + client.is_ok(), + "reqwest client construction should succeed when accept_self_signed=true is set" + ); + } + + #[test] + fn test_http_client_via_public_tls_config_with_custom_ca_accepts_build() { + let public = crate::config::TlsConfig { + custom_ca_cert: Some(TEST_CA_CERT_PEM.as_bytes().to_vec()), + accept_self_signed: false, + skip_hostname_verification: false, + }; + let config = HttpClientConfig { + tls: TlsConfig::from_public(&public), + ..HttpClientConfig::default() + }; + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!( + client.is_ok(), + "reqwest client construction should succeed when custom_ca_cert is set with a valid PEM" + ); + } + #[test] fn test_proxy_config_debug_redacts_password() { let config = ProxyConfig { diff --git a/src/config.rs b/src/config.rs index 9d6e2b7a..8a791815 100644 --- a/src/config.rs +++ b/src/config.rs @@ -349,13 +349,64 @@ impl Default for HttpConfig { #[derive(Debug, Clone, Default)] pub struct ProxyConfig {} -// ─── TLS (reserved) ───────────────────────────────────────────────────────── +// ─── TLS ──────────────────────────────────────────────────────────────────── -/// Reserved for v0.1. Fields land once the TLS story (custom CA bundles, -/// cert pinning, FIPS mode) is settled. +/// TLS settings for the HTTP client. +/// +/// All defaults match the most secure stance: validate the system trust +/// store, require a valid certificate chain, and verify hostnames. Any +/// non-default field is a *relaxation* — flip these for dev / on-prem +/// boxes with self-signed certs, never against production. +/// +/// The kernel exposes only fields that the internal rustls plumbing +/// already supports — cert pinning and FIPS mode are *not* in scope. #[non_exhaustive] -#[derive(Debug, Clone, Default)] -pub struct TlsConfig {} +#[derive(Clone, Default)] +pub struct TlsConfig { + /// PEM-encoded CA certificate bytes to add to the trust store on + /// top of the system roots. Use this when connecting through a + /// corporate proxy that re-signs TLS or to an on-prem Databricks + /// deployment using an internal CA. + /// + /// Carrying bytes (rather than a path) keeps the surface friendly + /// for foreign-language wrappers — napi-rs / pyo3 callers pass a + /// `Buffer` / `bytes` directly without needing to materialise a + /// tempfile. + pub custom_ca_cert: Option>, + + /// Accept self-signed server certificates. + /// + /// Note: the underlying reqwest backend does not distinguish + /// "self-signed only" from "fully unvalidated" — setting this to + /// `true` disables ALL chain validation (CA trust, expiration, + /// etc.) via `danger_accept_invalid_certs(true)`. Use only in + /// development. + pub accept_self_signed: bool, + + /// Skip the certificate-hostname-vs-SNI match check. Use only + /// when connecting via an IP literal or a hostname the cert + /// wasn't issued for in a development / lab environment. + pub skip_hostname_verification: bool, +} + +impl std::fmt::Debug for TlsConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TlsConfig") + .field( + "custom_ca_cert", + &self + .custom_ca_cert + .as_ref() + .map(|b| format!("<{} bytes>", b.len())), + ) + .field("accept_self_signed", &self.accept_self_signed) + .field( + "skip_hostname_verification", + &self.skip_hostname_verification, + ) + .finish() + } +} // ─── Result management (CloudFetch + future result knobs) ─────────────────── @@ -657,4 +708,32 @@ mod tests { // `sea-workflow/specs/07-errors-retries/connection-pool-default-mismatch.md`. assert_eq!(HttpConfig::default().pool_max_idle_per_host, 100); } + + // ─── TlsConfig ───────────────────────────────────────────────── + + #[test] + fn tls_config_default_is_strict() { + let tls = TlsConfig::default(); + assert!(tls.custom_ca_cert.is_none()); + assert!(!tls.accept_self_signed); + assert!(!tls.skip_hostname_verification); + } + + #[test] + fn tls_config_debug_redacts_ca_cert_bytes() { + // The PEM bytes themselves aren't secret, but a multi-kB blob + // in every log line is unhelpful — Debug should summarise. + let tls = TlsConfig { + custom_ca_cert: Some(b"-----BEGIN CERTIFICATE-----...".to_vec()), + accept_self_signed: false, + skip_hostname_verification: false, + }; + let s = format!("{tls:?}"); + assert!(s.contains("<"), "expected byte-count summary, got: {s}"); + assert!( + s.contains("bytes>"), + "expected byte-count summary, got: {s}" + ); + assert!(!s.contains("BEGIN CERTIFICATE"), "raw bytes leaked: {s}"); + } } diff --git a/src/session.rs b/src/session.rs index f630d06a..fd2be786 100644 --- a/src/session.rs +++ b/src/session.rs @@ -518,11 +518,11 @@ impl SessionBuilder { /// Translate the public [`HttpConfig`] (+ proxy / TLS / org_id) into /// the internal [`HttpClientConfig`] the HTTP client expects. /// -/// v0's [`ProxyConfig`] and [`TlsConfig`] are empty `#[non_exhaustive]` -/// reservation structs — they don't carry fields yet. We pass through -/// the internal [`HttpProxyConfig::default`] / [`HttpTlsConfig::default`] -/// for now; PR follow-ups will wire the real fields when the v0 -/// proxy/TLS shape lands. +/// The public [`ProxyConfig`] is still a reserved `#[non_exhaustive]` +/// struct (no fields wired yet); the public [`TlsConfig`] now carries +/// `custom_ca_cert` / `accept_self_signed` / +/// `skip_hostname_verification` and is projected onto the internal +/// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`]. fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { let mut hcc = HttpClientConfig { connect_timeout: Duration::from_secs(30), @@ -531,15 +531,14 @@ fn build_http_client_config(config: &SessionConfig, org_id: Option) -> H read_timeout: config.http.request_timeout, max_connections_per_host: config.http.pool_max_idle_per_host, proxy: HttpProxyConfig::default(), - tls: HttpTlsConfig::default(), + tls: HttpTlsConfig::from_public(&config.tls), org_id, ..HttpClientConfig::default() }; - // Touch the v0 reserved configs so a future field addition + // Touch the still-reserved proxy config so a future field addition // (without setting it through here) shows up as a compile error // rather than a silently-dropped option. let ProxyConfig { .. } = config.proxy.clone().unwrap_or_default(); - let TlsConfig { .. } = config.tls.clone(); let _ = &mut hcc; hcc } From 5265c75c13870d3ac81d5733051fd18f6d325bbe Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sat, 16 May 2026 13:44:11 +0000 Subject: [PATCH 12/28] krn-status-fields: expose 5 status accessors on ExecutedStatement Adds num_modified_rows(), progress(), display_message(), diagnostic_info(), and error_details_json() getters on ExecutedStatement. Data is parsed from the SEA GET /sql/statements/{id} response in client/sea.rs; this commit only exposes the accessors so the napi binding (and Python pyo3 binding) can surface them. Structural change: the wire-protocol StatementStatus in types/sea.rs was previously decoding only `state` and `error`; the five new fields are added as `Option<...>` behind `#[serde(default)]` so they remain backward- compatible with the absent-field SEA responses today's classic-warehouse fixtures emit. The status struct flows through ExecuteResult (already carrying manifest) into ExecutedStatement, which stores it once at construction and hands out cheap field-level accessors. Unblocks NodeJS Operation.status() field synthesis (feature-tracker line 39 / kernel carry-over row). Tests: - types::sea::tests::test_statement_status_with_extended_fields - types::sea::tests::test_statement_status_extended_fields_absent - tests/v0_execute_wiremock::executed_statement_surfaces_extended_status_fields - tests/v0_execute_wiremock::executed_statement_status_fields_default_to_none Signed-off-by: Madhavendra Rathore --- src/client/sea.rs | 14 +-- src/client/transport.rs | 34 +++--- src/reader/cloudfetch/link_fetcher.rs | 12 ++- src/statement/executed.rs | 44 ++++++++ src/statement/mutable.rs | 3 +- src/types/sea.rs | 74 +++++++++++++ tests/v0_execute_wiremock.rs | 145 ++++++++++++++++++++++++++ 7 files changed, 303 insertions(+), 23 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 0dd732cd..8dd0f015 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -381,15 +381,16 @@ impl SeaRestTransport { .create_reader(&response.statement_id, &response) .await?; - // `server_state` carries the terminal state forward so the - // executed handle can skip a redundant CloseStatement when - // the server already cleaned up (state=Closed). - let server_state = response.status.state; + // The full `status` is carried forward so the executed handle + // can skip a redundant CloseStatement when the server already + // cleaned up (status.state=Closed) AND expose + // num_modified_rows / progress / etc. without a second + // GetStatementStatus round-trip. Ok(ExecuteResult { statement_id: response.statement_id, reader, manifest: response.manifest, - server_state, + status: response.status, }) } } @@ -533,12 +534,11 @@ impl Transport for SeaRestTransport { StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; let reader = reader_factory.create_reader(&r.statement_id, &r).await?; - let server_state = r.status.state; Ok(Some(ExecuteResult { statement_id: r.statement_id, reader, manifest: r.manifest, - server_state, + status: r.status, })) } StatementOutcome::NotReady(_) => Ok(None), diff --git a/src/client/transport.rs b/src/client/transport.rs index 85e1257e..b5837007 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -27,7 +27,7 @@ use crate::kernel_error::Result; use crate::reader::ResultReader; use crate::types::cloudfetch::CloudFetchLink; -use crate::types::sea::{ExecuteParams, ResultManifest, StatementState, StatementStatus}; +use crate::types::sea::{ExecuteParams, ResultManifest, StatementStatus}; use async_trait::async_trait; use std::collections::HashMap; use std::time::Duration; @@ -67,22 +67,30 @@ pub(crate) struct SessionInfo { /// Result from [`Transport::execute_statement`]. Contains the /// statement ID (for cancellation/cleanup), a reader over the result -/// data, and optionally the SEA manifest for metadata propagation. +/// data, optionally the SEA manifest for metadata propagation, and +/// the terminal `StatementStatus` so callers can surface +/// `num_modified_rows` / `progress` / etc. without a second +/// GetStatementStatus round-trip. pub(crate) struct ExecuteResult { pub statement_id: String, pub reader: Box, pub manifest: Option, - /// Terminal state the server reported in its final response. - /// `Closed` means the server has already cleaned up the - /// statement on its end — the kernel must NOT issue a + /// Terminal status the server reported in its final response. + /// + /// `status.state == Closed` means the server has already cleaned + /// up the statement on its end — the kernel must NOT issue a /// separate `CloseStatement` for it (the server returns 404 - /// `STATEMENT_NOT_FOUND` on such redundant closes). This is - /// the common case when the kernel omits `wait_timeout` from - /// the execute request: the server holds the connection for - /// its default wait, returns inline data with `state=CLOSED`, - /// and is done. Setting a concrete `wait_timeout` yields - /// `Succeeded` instead and requires an explicit close. - pub server_state: StatementState, + /// `STATEMENT_NOT_FOUND` on such redundant closes). This is the + /// common case when the kernel omits `wait_timeout` from the + /// execute request: the server holds the connection for its + /// default wait, returns inline data with `state=CLOSED`, and is + /// done. Setting a concrete `wait_timeout` yields `Succeeded` + /// instead and requires an explicit close. + /// + /// The full status is carried (not just the state) so the + /// `ExecutedStatement` can expose `num_modified_rows` / `progress` + /// / etc. without a second GetStatementStatus round-trip. + pub status: StatementStatus, } impl std::fmt::Debug for ExecuteResult { @@ -91,7 +99,7 @@ impl std::fmt::Debug for ExecuteResult { .field("statement_id", &self.statement_id) .field("reader", &"") .field("manifest", &self.manifest) - .field("server_state", &self.server_state) + .field("status", &self.status) .finish() } } diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 8aacaf74..29f7df0f 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -547,7 +547,7 @@ mod tests { use super::*; use crate::client::{ExecuteResult, SessionInfo}; use crate::reader::EmptyReader; - use crate::types::sea::{ExecuteParams, StatementState}; + use crate::types::sea::{ExecuteParams, StatementState, StatementStatus}; use arrow_schema::Schema; use std::collections::HashMap; use std::sync::Arc as StdArc; @@ -591,7 +591,15 @@ mod tests { statement_id: "mock-statement".to_string(), reader: Box::new(EmptyReader::new(StdArc::new(Schema::empty()))), manifest: None, - server_state: StatementState::Succeeded, + status: StatementStatus { + state: StatementState::Succeeded, + error: None, + num_modified_rows: None, + progress: None, + display_message: None, + diagnostic_info: None, + error_details_json: None, + }, }) } diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 0213dacd..087a1a15 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -33,6 +33,7 @@ use crate::result_stream::{ResultStream, SchemaRef}; use crate::session::SessionInner; use crate::statement::handle::ExecutedStatementHandle; use crate::statement::validity::ValidityFlag; +use crate::types::sea::StatementStatus as SeaStatementStatus; use async_trait::async_trait; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -47,6 +48,11 @@ pub struct ExecutedStatement { /// stale calls locally with no network round-trip. valid: ValidityFlag, result_stream: ResultStream, + /// Terminal SEA `StatementStatus` captured at construction. + /// Kept as the wire-shape struct so the accessor methods can + /// hand back individual fields without re-querying the server. + /// Mutated only at construction; no interior mutability. + status: SeaStatementStatus, /// Flips to `true` after the first successful (or the first /// duplicate-call short-circuited) `close()`. Tells `Drop` to /// skip its fire-and-forget cleanup so an explicit close @@ -69,6 +75,7 @@ impl ExecutedStatement { valid: ValidityFlag, result_stream: ResultStream, closed: Arc, + status: SeaStatementStatus, ) -> Self { Self { session, @@ -76,6 +83,7 @@ impl ExecutedStatement { valid, result_stream, closed, + status, } } @@ -101,6 +109,42 @@ impl ExecutedStatement { pub fn result_stream_mut(&mut self) -> &mut ResultStream { &mut self.result_stream } + + /// Rows modified by the statement (UPDATE / INSERT / DELETE / + /// MERGE). Absent for SELECT and on warehouses that don't surface + /// the counter. + pub fn num_modified_rows(&self) -> Option { + self.status.num_modified_rows + } + + /// Fractional completion in `[0.0, 1.0]`. Populated on analytics + /// warehouses; absent elsewhere. On a terminal `ExecutedStatement` + /// this is typically `Some(1.0)` when populated at all. + pub fn progress(&self) -> Option { + self.status.progress + } + + /// Server-supplied user-facing message. Distinct from the + /// `error.message` carried inside `Failed` — populated on + /// non-error states too (e.g. cancellation reasons, progress + /// hints). + pub fn display_message(&self) -> Option<&str> { + self.status.display_message.as_deref() + } + + /// Server-supplied diagnostic detail — multi-line text with + /// stack frames or operator context. Intended for log / support + /// surfaces; not user-facing. + pub fn diagnostic_info(&self) -> Option<&str> { + self.status.diagnostic_info.as_deref() + } + + /// Server-supplied JSON blob with extended error details. + /// Pass-through string — wrappers parse if they need structured + /// access. + pub fn error_details_json(&self) -> Option<&str> { + self.status.error_details_json.as_deref() + } } #[async_trait] diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index cb48b5c6..7f43c106 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -170,7 +170,7 @@ impl Statement { // path. See `prepare_for_dispatch` for why omitting // `wait_timeout` typically yields `Closed` on the inline-result // fast path. - let already_closed = result.server_state == StatementState::Closed; + let already_closed = result.status.state == StatementState::Closed; let closed = Arc::new(AtomicBool::new(already_closed)); self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); @@ -183,6 +183,7 @@ impl Statement { valid, result_stream, closed, + result.status, )) } .instrument(span) diff --git a/src/types/sea.rs b/src/types/sea.rs index 294113e9..fc79392a 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -38,6 +38,30 @@ pub struct StatementStatus { pub state: StatementState, #[serde(default)] pub error: Option, + /// Number of rows modified by the statement (UPDATE / INSERT / + /// DELETE / MERGE). Absent on SELECT and on warehouses that don't + /// surface the counter. + #[serde(default)] + pub num_modified_rows: Option, + /// Fractional completion in `[0.0, 1.0]`. Populated on analytics + /// warehouses; absent (or always 1.0 on terminal) elsewhere. + #[serde(default)] + pub progress: Option, + /// Server-supplied user-facing message (e.g. "Statement was + /// canceled by the user" or progress hints). Distinct from + /// `error.message`; populated on non-error states too. + #[serde(default)] + pub display_message: Option, + /// Server-supplied diagnostic detail — multi-line text with + /// stack frames or operator context. Intended for log / support + /// surfaces, not user-facing strings. + #[serde(default)] + pub diagnostic_info: Option, + /// Server-supplied JSON blob with extended error details. + /// Pass-through string — wrappers parse if they need structured + /// access. + #[serde(default)] + pub error_details_json: Option, } /// Possible states of a statement during execution. @@ -503,6 +527,56 @@ mod tests { assert_eq!(manifest.total_row_count, Some(0)); } + #[test] + fn test_statement_status_with_extended_fields() { + // SEA response with all five extended status fields populated. + let json = r#"{ + "statement_id": "stmt-extended", + "status": { + "state": "SUCCEEDED", + "num_modified_rows": 42, + "progress": 0.875, + "display_message": "Statement completed", + "diagnostic_info": "operator=Scan; rows=42", + "error_details_json": "{\"trace\":\"...\"}" + } + }"#; + + let response: StatementExecutionResponse = serde_json::from_str(json).unwrap(); + assert_eq!(response.status.state, StatementState::Succeeded); + assert_eq!(response.status.num_modified_rows, Some(42)); + assert_eq!(response.status.progress, Some(0.875)); + assert_eq!( + response.status.display_message, + Some("Statement completed".to_string()) + ); + assert_eq!( + response.status.diagnostic_info, + Some("operator=Scan; rows=42".to_string()) + ); + assert_eq!( + response.status.error_details_json, + Some(r#"{"trace":"..."}"#.to_string()) + ); + } + + #[test] + fn test_statement_status_extended_fields_absent() { + // Minimal SEA response — extended fields are optional and + // default to None when the server omits them. + let json = r#"{ + "statement_id": "stmt-min", + "status": { "state": "SUCCEEDED" } + }"#; + + let response: StatementExecutionResponse = serde_json::from_str(json).unwrap(); + assert_eq!(response.status.num_modified_rows, None); + assert_eq!(response.status.progress, None); + assert_eq!(response.status.display_message, None); + assert_eq!(response.status.diagnostic_info, None); + assert_eq!(response.status.error_details_json, None); + } + #[test] fn test_column_info_with_interval_type() { let json = r#"{ diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index fcab664f..5d7eb8c1 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -593,3 +593,148 @@ async fn kernel_invariant_parent_drop_invalidates_executed_cancel() { .expect_err("cancel after parent Statement drop must short-circuit"); assert_eq!(err.code, ErrorCode::InvalidStatementHandle); } + +// ─── ExecutedStatement extended status accessors (PR #23) ───────── + +/// Build a SEA `SUCCEEDED` body with the 5 extended status fields +/// populated. Mirrors `succeeded_inline_body` but injects status +/// fields the kernel surfaces via `ExecutedStatement::*` getters. +#[allow(clippy::too_many_arguments)] +fn succeeded_inline_body_with_status( + statement_id: &str, + batch: &RecordBatch, + num_modified_rows: Option, + progress: Option, + display_message: Option<&str>, + diagnostic_info: Option<&str>, + error_details_json: Option<&str>, +) -> String { + let ipc = arrow_ipc_bytes(batch); + let attachment = STANDARD.encode(&ipc); + let columns: Vec<_> = batch + .schema() + .fields() + .iter() + .enumerate() + .map(|(i, f)| { + json!({ + "name": f.name(), + "type_name": match f.data_type() { + DataType::Int64 => "BIGINT", + DataType::Utf8 => "STRING", + _ => "STRING", + }, + "type_text": match f.data_type() { + DataType::Int64 => "BIGINT", + DataType::Utf8 => "STRING", + _ => "STRING", + }, + "position": i as i32, + }) + }) + .collect(); + + let mut status = json!({ "state": "SUCCEEDED" }); + let status_obj = status.as_object_mut().unwrap(); + if let Some(n) = num_modified_rows { + status_obj.insert("num_modified_rows".to_string(), json!(n)); + } + if let Some(p) = progress { + status_obj.insert("progress".to_string(), json!(p)); + } + if let Some(m) = display_message { + status_obj.insert("display_message".to_string(), json!(m)); + } + if let Some(d) = diagnostic_info { + status_obj.insert("diagnostic_info".to_string(), json!(d)); + } + if let Some(e) = error_details_json { + status_obj.insert("error_details_json".to_string(), json!(e)); + } + + json!({ + "statement_id": statement_id, + "status": status, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": batch.num_columns() as i32, + "columns": columns, + }, + "total_chunk_count": 1, + "total_row_count": batch.num_rows() as i64, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows() as i64, + "byte_count": ipc.len() as i64, + "attachment": attachment, + }, + }) + .to_string() +} + +#[tokio::test] +async fn executed_statement_surfaces_extended_status_fields() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("n", vec![1]); + mount_execute( + &server, + succeeded_inline_body_with_status( + "stmt-status", + &batch, + Some(7), + Some(1.0), + Some("All good"), + Some("operator=Scan"), + Some(r#"{"k":"v"}"#), + ), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("UPDATE t SET x = 1"); + let exec = stmt.execute().await.expect("execute"); + + assert_eq!(exec.num_modified_rows(), Some(7)); + assert_eq!(exec.progress(), Some(1.0)); + assert_eq!(exec.display_message(), Some("All good")); + assert_eq!(exec.diagnostic_info(), Some("operator=Scan")); + assert_eq!(exec.error_details_json(), Some(r#"{"k":"v"}"#)); + + exec.close().await.expect("close"); +} + +#[tokio::test] +async fn executed_statement_status_fields_default_to_none() { + // When the server omits the extended fields (the common case for + // SELECT on classic warehouses), all five accessors return None. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("n", vec![1]); + mount_execute(&server, succeeded_inline_body("stmt-empty-status", &batch)).await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let exec = stmt.execute().await.expect("execute"); + + assert_eq!(exec.num_modified_rows(), None); + assert_eq!(exec.progress(), None); + assert_eq!(exec.display_message(), None); + assert_eq!(exec.diagnostic_info(), None); + assert_eq!(exec.error_details_json(), None); + + exec.close().await.expect("close"); +} From c36e2862956e47371bbad3de691bc196264ece7a Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 20 May 2026 22:36:44 +0000 Subject: [PATCH 13/28] feat(napi): expose 10 metadata methods on Connection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Statement::from_result_stream (internal constructor wrapping a bare ResultStream) and a new napi/src/metadata.rs that wires all 10 kernel Metadata methods onto the JS Connection class: listCatalogs, listSchemas, listTables, listColumns, listFunctions, listProcedures, listTableTypes, listTypeInfo, getPrimaryKeys, getCrossReference Each returns the same Statement type as executeStatement so the JS SeaOperationBackend wraps them uniformly. Cancel on metadata-derived Statements is a no-op (no server-side cancellation surface today). The kernel Metadata methods hold a tracing::EnteredSpan (!Send) across their await points. The fix: acquire the session lock, clone the Send Metadata handle, drop the lock, then run the !Send future inside tokio::task::spawn_blocking via Handle::block_on — a standard pattern for escaping the Send bound without LocalSet. Also fixes: - pre-existing unused StatementState import in src/client/transport.rs - pre-existing dead_code lint on open_session + ConnectionOptions in napi/src/database.rs (exported via napi macro codegen, not called from Rust directly) - AnyInner::Executed variant boxed to satisfy large_enum_variant lint Signed-off-by: Madhavendra Rathore --- napi/src/lib.rs | 1 + napi/src/metadata.rs | 326 ++++++++++++++++++++++++++++++++++++++++++ napi/src/statement.rs | 144 ++++++++++++++----- 3 files changed, 433 insertions(+), 38 deletions(-) create mode 100644 napi/src/metadata.rs diff --git a/napi/src/lib.rs b/napi/src/lib.rs index 455bfc91..fe4b2201 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -43,6 +43,7 @@ pub(crate) mod connection; pub(crate) mod database; pub(crate) mod error; pub(crate) mod logger; +pub(crate) mod metadata; pub(crate) mod result; pub(crate) mod runtime; pub(crate) mod statement; diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs new file mode 100644 index 00000000..4623251f --- /dev/null +++ b/napi/src/metadata.rs @@ -0,0 +1,326 @@ +// 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 methods on `Connection` — napi-rs layer over the kernel's +//! flat `Metadata` API. +//! +//! Each method mirrors a `databricks_sql_kernel::Metadata` method +//! one-to-one and returns the same `Statement` type that +//! `executeStatement` returns, so the JS side can wrap any result in +//! `SeaOperationBackend` uniformly. The `Statement` is constructed via +//! `Statement::from_result_stream` — no parent kernel `Statement` is +//! involved (metadata calls don't use the mutable `Statement` path). +//! +//! Parameter mapping from JS strings to kernel newtypes follows the +//! pyo3 binding pattern: `Option` → `Option>` +//! or `Option>`, with runtime validation left to the +//! kernel. Rejected inputs surface as `InvalidArgument` via the +//! standard kernel-error envelope. +//! +//! ## `!Send` future workaround +//! +//! The kernel's `Metadata` methods hold a `tracing::EnteredSpan` +//! (`!Send`) across their internal `.await` points, making each +//! method's future `!Send`. napi-rs requires the top-level async fn +//! future to be `Send`. The fix: acquire the lock, clone a `Metadata` +//! handle (`Send + Sync` — wraps `Arc`), release the +//! lock, and then run the `!Send` kernel future inside +//! `tokio::task::spawn_blocking` via `Handle::block_on`. A blocking +//! thread is outside the tokio executor's scheduler, so `block_on` is +//! safe there and the `!Send` constraint does not propagate to the +//! enclosing `Send` async fn. +//! +//! ## Cancel on metadata `Statement`s +//! +//! Cancel is a no-op for metadata streams: the kernel has no +//! in-flight cancellation surface for metadata calls today. This is +//! documented on `Statement::cancel` and tracked as a kernel follow-up +//! for v1. + +use std::sync::Arc; + +use databricks_sql_kernel::{Identifier, LikePattern, Metadata, Result as KResult, ResultStream}; +use tokio::runtime::Handle; + +use crate::connection::Connection; +use crate::error::napi_err_from_kernel; +use crate::runtime::get_handle; +use crate::statement::Statement; +use crate::util::guarded; + +// ─── Conversion helpers ───────────────────────────────────────────────────── + +fn opt_identifier(s: &Option) -> KResult>> { + s.as_deref().map(Identifier::new).transpose() +} + +fn opt_pattern(s: &Option) -> KResult>> { + s.as_deref().map(LikePattern::new).transpose() +} + +/// Run a `!Send` async kernel metadata operation on a blocking thread. +/// +/// `Metadata` itself is `Send + 'static` (wraps `Arc`). +/// The *futures* its methods return are `!Send` because they hold a +/// `tracing::EnteredSpan` across internal await points. Running them +/// inside `spawn_blocking` moves execution to a thread-pool thread +/// where `Handle::block_on` is safe and the `!Send` constraint doesn't +/// infect the enclosing napi async fn. +async fn run_on_blocking(f: F) -> napi::Result +where + F: FnOnce(Handle) -> Fut + Send + 'static, + Fut: std::future::Future>, +{ + // Capture the handle before entering spawn_blocking; get_handle() + // must be called from inside an async context (it snapshots + // Handle::current() on first call). + let handle = get_handle().clone(); + let stream = tokio::task::spawn_blocking(move || handle.block_on(f(handle.clone()))) + .await + .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))? + .map_err(napi_err_from_kernel)?; + Ok(stream) +} + +/// Acquire the lock, return a `Metadata` handle, and release the lock. +async fn take_metadata( + inner: &Arc>>, +) -> napi::Result { + let guard = inner.lock().await; + let session = guard + .as_ref() + .ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, "connection already closed"))?; + Ok(session.metadata()) +} + +// ─── Metadata impls on Connection ─────────────────────────────────────────── + +#[napi] +impl Connection { + /// All catalogs visible to the session. + /// + /// JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + #[napi] + pub async fn list_catalogs(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = + run_on_blocking(move |_h| async move { meta.list_catalogs().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Schemas filtered by catalog (exact) and schema name pattern. + /// + /// JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + #[napi] + pub async fn list_schemas( + &self, + catalog: Option, + schema_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let pat = opt_pattern(&schema_pattern)?; + meta.list_schemas(cat, pat).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Tables filtered by catalog (exact), schema (pattern), table (pattern). + /// + /// JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + /// filters rows by `TABLE_TYPE` kernel-side. + #[napi] + pub async fn list_tables( + &self, + catalog: Option, + schema_pattern: Option, + table_pattern: Option, + table_types: Option>, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let types_owned: Option> = table_types + .as_ref() + .map(|v| v.iter().map(String::as_str).collect()); + let types_slice: Option<&[&str]> = types_owned.as_deref(); + meta.list_tables(cat, sch, tbl, types_slice).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Columns of tables matching the filter. + /// + /// JDBC `getColumns` shape: 23 columns. + #[napi] + pub async fn list_columns( + &self, + catalog: Option, + schema_pattern: Option, + table_pattern: Option, + column_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let col = opt_pattern(&column_pattern)?; + meta.list_columns(cat, sch, tbl, col).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Functions visible to the session. `catalog` is exact; + /// `schemaPattern` and `functionPattern` are SQL LIKE. + #[napi] + pub async fn list_functions( + &self, + catalog: Option, + schema_pattern: Option, + function_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&function_pattern)?; + meta.functions(cat, sch, nam).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Procedures visible to the session. `catalog` is exact; + /// `schemaPattern` and `procedurePattern` are SQL LIKE. + #[napi] + pub async fn list_procedures( + &self, + catalog: Option, + schema_pattern: Option, + procedure_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&procedure_pattern)?; + meta.procedures(cat, sch, nam).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + /// No wire call — static in-memory result. + #[napi] + pub async fn list_table_types(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { meta.table_types().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// SQL data types supported by the workspace. + /// No wire call — static in-memory result. + #[napi] + pub async fn list_type_info(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { meta.type_info().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Primary keys for the given table. All three identifiers are + /// exact — ODBC `SQLPrimaryKeys` does not support patterns. + #[napi] + pub async fn get_primary_keys( + &self, + catalog: String, + schema: String, + table: String, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let cat = Some(Identifier::new(&catalog)?); + let sch = Some(Identifier::new(&schema)?); + let tbl = Identifier::new(&table)?; + meta.primary_keys(cat, sch, tbl).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Foreign-key relationships. The foreign side must be fully + /// specified (catalog + schema + table); the parent side is + /// optional. All identifiers are exact — no LIKE patterns. + #[napi] + #[allow(clippy::too_many_arguments)] + pub async fn get_cross_reference( + &self, + parent_catalog: Option, + parent_schema: Option, + parent_table: Option, + foreign_catalog: String, + foreign_schema: String, + foreign_table: String, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move |_h| async move { + let pc = opt_identifier(&parent_catalog)?; + let ps = opt_identifier(&parent_schema)?; + let pt = opt_identifier(&parent_table)?; + let fc = Some(Identifier::new(&foreign_catalog)?); + let fs = Some(Identifier::new(&foreign_schema)?); + let ft = Some(Identifier::new(&foreign_table)?); + meta.foreign_keys(pc, ps, pt, fc, fs, ft).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } +} diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 2377addc..38c614d7 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -36,7 +36,7 @@ use tokio::sync::Mutex; use arrow_ipc::writer::StreamWriter; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ - Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, + Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, ResultStream, Statement as KernelStatement, }; @@ -70,6 +70,30 @@ struct StatementInner { executed: ExecutedStatement, } +/// Discriminated inner state for `Statement`. +enum AnyInner { + /// Produced by `Connection::execute_statement`. Boxed to keep the + /// enum size close to the `Metadata` variant (StatementInner is + /// large; ResultStream is much smaller). + Executed(Box), + /// Produced by metadata methods — wraps a bare `ResultStream`. + Metadata(ResultStream), +} + +impl AnyInner { + /// Borrow the underlying result stream regardless of variant. The + /// executed-statement variant delegates to its + /// `ExecutedStatement::result_stream_mut`; the metadata variant + /// returns the bare `ResultStream` directly. Used by + /// `fetch_next_batch` to share one streaming path across both. + fn result_stream_mut(&mut self) -> &mut ResultStream { + match self { + AnyInner::Executed(s) => s.executed.result_stream_mut(), + AnyInner::Metadata(rs) => rs, + } + } +} + /// Opaque executed-statement handle. /// /// **Current concurrency shape** — every method takes `inner.lock()` @@ -88,21 +112,31 @@ struct StatementInner { /// disposed statement can still read them. #[napi] pub struct Statement { - /// Wraps the kernel `Statement` + `ExecutedStatement` pair so the - /// parent's `Drop` doesn't fire (and invalidate the executed - /// handle via the shared `ValidityFlag`) while JS still holds - /// this wrapper. See `StatementInner` docs above. - inner: Arc>>, + /// Discriminated inner state: the `Executed` variant wraps the + /// kernel `Statement` + `ExecutedStatement` pair (the parent kept + /// alive to prevent its `Drop` from invalidating the executed + /// handle via the shared `ValidityFlag`); the `Metadata` variant + /// wraps a bare `ResultStream` produced by `Metadata::list_*` / + /// `primary_keys` / `foreign_keys` / `type_info` / `table_types`. + inner: Arc>>, /// Schema captured at construction. Available even after `close()`. + /// For the `Executed` variant this is the executed handle's + /// schema; for the `Metadata` variant it's the result-stream's + /// schema. Either way, cached so JS callers can build error + /// reports against a disposed statement. schema: SchemaRef, - /// Server-issued id. Available even after `close()` for log - /// correlation. + /// Server-issued statement id. Populated for the `Executed` + /// variant; empty string for the `Metadata` variant (the kernel + /// does not emit a statement id for SHOW/information_schema + /// queries driven through `Metadata`). statement_id: String, /// Set to `true` when `fetchNextBatch` observes the natural end of /// the stream (`None`). `cancel()` short-circuits to `Ok(())` when /// this is set, matching the JDBC `Statement.cancel()` no-op-after- /// completion contract — without it, a defensive cancel after the /// stream is drained surfaces an opaque server-side error. + /// (Irrelevant for the `Metadata` variant where cancel is already + /// a no-op kernel-side; harmless to carry the field regardless.) finished: Arc, } @@ -119,15 +153,37 @@ impl Statement { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); Self { - inner: Arc::new(Mutex::new(Some(StatementInner { - _parent: parent, - executed, - }))), + inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( + StatementInner { + _parent: parent, + executed, + }, + ))))), schema, statement_id, finished: Arc::new(AtomicBool::new(false)), } } + + /// Crate-internal constructor for metadata calls. Wraps a bare + /// `ResultStream` returned by `Metadata::list_*` / `primary_keys` / + /// `foreign_keys` / `type_info` / `table_types`. Cancel is a no-op + /// for metadata streams (the kernel has no in-flight cancellation + /// surface for them); close just drops the stream. + /// + /// `schema` is captured from the stream so the `schema()` getter + /// works after close. `statement_id` is empty (kernel does not + /// emit one for metadata queries). `finished` defaults false and + /// is unread on this path (cancel is already a no-op). + pub(crate) fn from_result_stream(stream: ResultStream) -> Self { + let schema = stream.schema(); + Self { + inner: Arc::new(Mutex::new(Some(AnyInner::Metadata(stream)))), + schema, + statement_id: String::new(), + finished: Arc::new(AtomicBool::new(false)), + } + } } #[napi] @@ -157,9 +213,14 @@ impl Statement { guarded(async move { let mut guard = inner.lock().await; let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?; - let executed = &mut inner_state.executed; - - let stream = executed.result_stream_mut(); + // `result_stream_mut` returns `&mut ResultStream` for both + // variants — the executed-path borrows from its + // `ExecutedStatement`, the metadata-path borrows from its + // bare `ResultStream`. The IPC schema header serialised + // into every batch payload comes from the cached + // `self.schema` captured outside the lock (see method + // start), so no need to re-fetch from the stream. + let stream = inner_state.result_stream_mut(); let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; let Some(batch) = maybe_batch else { // End of stream — record so a defensive cancel after @@ -225,11 +286,15 @@ impl Statement { /// Server-side cancel. /// - /// Short-circuits to `Ok(())` if `fetchNextBatch` has already - /// returned `null` (stream naturally exhausted) — matches the - /// JDBC `Statement.cancel()` no-op-after-completion contract, so - /// JS callers can fire cancel defensively without distinguishing - /// "real cancel" from "raced with natural completion." + /// For executed statements: short-circuits to `Ok(())` if + /// `fetchNextBatch` has already returned `null` (stream + /// naturally exhausted) — matches the JDBC `Statement.cancel()` + /// no-op-after-completion contract, so JS callers can fire cancel + /// defensively without distinguishing "real cancel" from "raced + /// with natural completion." + /// + /// For metadata streams: no-op (the kernel has no in-flight + /// cancellation surface for metadata calls today). /// /// Returns `KernelError(InvalidStatementHandle)` if the statement /// has been explicitly `close()`d. @@ -243,17 +308,19 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - inner_state - .executed - .cancel() - .await - .map_err(napi_err_from_kernel) + match inner_state { + AnyInner::Executed(s) => s.executed.cancel().await.map_err(napi_err_from_kernel), + // Metadata streams have no server-side cancel handle. + AnyInner::Metadata(_) => Ok(()), + } }) .await } - /// Explicit close. Awaits the server-side `CloseStatement` so the - /// JS caller can observe failures (auth revoked mid-session, + /// Explicit close. + /// + /// For executed statements: awaits the server-side `CloseStatement` + /// so the JS caller can observe failures (auth revoked mid-session, /// network error, server-side error). Idempotent — a second call /// on an already-closed statement returns `Ok`. /// @@ -269,26 +336,27 @@ impl Statement { /// runtime. The JS caller can log the error but cannot drive a /// further retry. If you need retry-on-failure semantics for /// `CloseStatement`, layer them above this method. + /// + /// For metadata streams: drops the stream (no server round-trip + /// needed — metadata results have no in-flight server-side + /// resource to release). #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); guarded(async move { // Take the inner state out so `Drop` knows there's nothing - // left to clean up. The parent kernel `Statement`'s Drop - // runs here too — but only AFTER the executed handle's - // close has finished, so we still observe a clean - // server-side close result before the validity flag flips. + // left to clean up. let inner_state = { let mut guard = inner.lock().await; guard.take() }; - if let Some(inner_state) = inner_state { - inner_state - .executed - .close() - .await - .map_err(napi_err_from_kernel)?; - // _parent drops here, after close has resolved. + match inner_state { + Some(AnyInner::Executed(s)) => { + s.executed.close().await.map_err(napi_err_from_kernel)?; + // _parent drops here, after close has resolved. + } + // Metadata stream: just drop it. + Some(AnyInner::Metadata(_)) | None => {} } Ok(()) }) From d10e271d9287c96e050fce9cc25c75f392e11485 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 20 May 2026 23:10:23 +0000 Subject: [PATCH 14/28] fix(napi/metadata): remove footgun Handle param + reject whitespace-only identifiers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit H1: `run_on_blocking`'s closure type was `FnOnce(Handle) -> Fut`, giving callers access to the runtime handle inside a `spawn_blocking` thread. Any future caller using that handle to call `block_on_in_runtime` would trigger `block_in_place` inside a blocking thread — the PECOBLR-2917 abort vector. Drop the parameter; callers that needed it for `Handle::block_on` already have a captured `handle`. All 10 call sites updated from `move |_h|` to `move ||`. H2: `Identifier::new` and `LikePattern::new` accepted whitespace-only strings (e.g., `" "`) that would produce meaningless or empty tokens at the SQL layer. Add `s.trim().is_empty()` guard after the `s.is_empty()` check in both. Two unit tests added covering space, tab, newline, and mixed whitespace inputs. Signed-off-by: Madhavendra Rathore --- napi/src/metadata.rs | 24 ++++++++++++------------ src/metadata_v0.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index 4623251f..e8e4212a 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -79,14 +79,14 @@ fn opt_pattern(s: &Option) -> KResult>> { /// infect the enclosing napi async fn. async fn run_on_blocking(f: F) -> napi::Result where - F: FnOnce(Handle) -> Fut + Send + 'static, + F: FnOnce() -> Fut + Send + 'static, Fut: std::future::Future>, { // Capture the handle before entering spawn_blocking; get_handle() // must be called from inside an async context (it snapshots // Handle::current() on first call). let handle = get_handle().clone(); - let stream = tokio::task::spawn_blocking(move || handle.block_on(f(handle.clone()))) + let stream = tokio::task::spawn_blocking(move || handle.block_on(f())) .await .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))? .map_err(napi_err_from_kernel)?; @@ -116,7 +116,7 @@ impl Connection { let meta = take_metadata(&self.inner).await?; guarded(async move { let stream = - run_on_blocking(move |_h| async move { meta.list_catalogs().await }).await?; + run_on_blocking(move || async move { meta.list_catalogs().await }).await?; Ok(Statement::from_result_stream(stream)) }) .await @@ -133,7 +133,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let pat = opt_pattern(&schema_pattern)?; meta.list_schemas(cat, pat).await @@ -158,7 +158,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let sch = opt_pattern(&schema_pattern)?; let tbl = opt_pattern(&table_pattern)?; @@ -187,7 +187,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let sch = opt_pattern(&schema_pattern)?; let tbl = opt_pattern(&table_pattern)?; @@ -211,7 +211,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let sch = opt_pattern(&schema_pattern)?; let nam = opt_pattern(&function_pattern)?; @@ -234,7 +234,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = opt_identifier(&catalog)?; let sch = opt_pattern(&schema_pattern)?; let nam = opt_pattern(&procedure_pattern)?; @@ -252,7 +252,7 @@ impl Connection { pub async fn list_table_types(&self) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { meta.table_types().await }).await?; + let stream = run_on_blocking(move || async move { meta.table_types().await }).await?; Ok(Statement::from_result_stream(stream)) }) .await @@ -264,7 +264,7 @@ impl Connection { pub async fn list_type_info(&self) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { meta.type_info().await }).await?; + let stream = run_on_blocking(move || async move { meta.type_info().await }).await?; Ok(Statement::from_result_stream(stream)) }) .await @@ -281,7 +281,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let cat = Some(Identifier::new(&catalog)?); let sch = Some(Identifier::new(&schema)?); let tbl = Identifier::new(&table)?; @@ -309,7 +309,7 @@ impl Connection { ) -> napi::Result { let meta = take_metadata(&self.inner).await?; guarded(async move { - let stream = run_on_blocking(move |_h| async move { + let stream = run_on_blocking(move || async move { let pc = opt_identifier(&parent_catalog)?; let ps = opt_identifier(&parent_schema)?; let pt = opt_identifier(&parent_table)?; diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index cca8ea02..76b5a455 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -148,6 +148,9 @@ impl<'a> Identifier<'a> { if s.is_empty() { return Err(Error::invalid_argument().message("identifier must not be empty")); } + if s.trim().is_empty() { + return Err(Error::invalid_argument().message("identifier must not be all whitespace")); + } if s.len() > MAX_IDENTIFIER_BYTES { return Err(Error::invalid_argument().message(format!( "identifier exceeds {MAX_IDENTIFIER_BYTES}-byte limit ({} bytes)", @@ -206,6 +209,10 @@ impl<'a> LikePattern<'a> { return Err(Error::invalid_argument() .message("LIKE pattern must not be empty (pass None for \"match all\")")); } + if s.trim().is_empty() { + return Err(Error::invalid_argument() + .message("LIKE pattern must not be all whitespace (pass None for \"match all\")")); + } if s.len() > MAX_LIKE_PATTERN_BYTES { return Err(Error::invalid_argument().message(format!( "LIKE pattern exceeds {MAX_LIKE_PATTERN_BYTES}-byte limit ({} bytes)", @@ -669,4 +676,30 @@ mod tests { let err = LikePattern::new(&s).expect_err("oversize pattern rejected"); assert_eq!(err.code, ErrorCode::InvalidArgument); } + + #[test] + fn identifier_rejects_whitespace_only() { + for s in &[" ", "\t", "\n", " \t "] { + let err = Identifier::new(s).expect_err("whitespace-only identifier rejected"); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!( + err.message.contains("whitespace"), + "expected 'whitespace' in: {}", + err.message + ); + } + } + + #[test] + fn like_pattern_rejects_whitespace_only() { + for s in &[" ", "\t", "\n", " \t "] { + let err = LikePattern::new(s).expect_err("whitespace-only pattern rejected"); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!( + err.message.contains("whitespace"), + "expected 'whitespace' in: {}", + err.message + ); + } + } } From 70938ce6666c2785a03805996973852127c5eb8c Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 20 May 2026 23:13:56 +0000 Subject: [PATCH 15/28] docs(napi): document tableTypes advisory-filter behavior in list_tables Databricks SHOW TABLES does not accept a table-type filter server-side; the kernel applies it client-side after the result returns. Mirror the language already present in src/metadata_v0.rs:310-313 so napi callers are not misled into expecting server-side enforcement. Signed-off-by: Madhavendra Rathore --- napi/src/metadata.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index e8e4212a..b5caf147 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -148,6 +148,11 @@ impl Connection { /// /// JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, /// filters rows by `TABLE_TYPE` kernel-side. + /// + /// `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + /// NOT honour the table-type filter server-side; the kernel applies + /// it client-side after the result returns. Callers expecting + /// server-side rejection of off-type tables should not rely on this. #[napi] pub async fn list_tables( &self, From 804668ca8c875546df3e21b39c8eeed322de1893 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 20 May 2026 23:44:17 +0000 Subject: [PATCH 16/28] docs(kernel): list whitespace rejection in Identifier and LikePattern docblocks The whitespace-only check was added in code but the /// Rejects: bullet list in each constructor docblock didn't mention it. Add a bullet to both Identifier::new and LikePattern::new explaining the rejection and the reason (blank token / use None for "match all"). Signed-off-by: Madhavendra Rathore --- src/metadata_v0.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index 76b5a455..c15f0b6e 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -134,6 +134,8 @@ impl<'a> Identifier<'a> { /// Rejects: /// - Empty string — meaningless as an identifier; almost always a /// bug at the wrapper layer. + /// - Strings consisting only of whitespace — would backtick-escape + /// to a blank token and produce a server-side parse error. /// - Embedded NUL bytes (`\0`) — would terminate the string at the /// first FFI / C ABI boundary and silently truncate the /// identifier in transit. @@ -197,6 +199,8 @@ impl<'a> LikePattern<'a> { /// /// Rejects: /// - Empty string — callers should pass `None` for "match all". + /// - Strings consisting only of whitespace — callers should pass + /// `None` for "match all". /// - Embedded NUL bytes — same FFI-truncation hazard as /// [`Identifier::new`]. /// - Strings exceeding 255 bytes. From 6cda5ecca8cc500742bb4d72fcb7cbd859fddaa8 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Thu, 21 May 2026 00:03:31 +0000 Subject: [PATCH 17/28] fix(napi): drop now-unused tokio::runtime::Handle import in metadata.rs Leftover from the H1 fixup that removed the `Handle` parameter from `run_on_blocking`'s signature. With no callers of `Handle` as a type remaining in metadata.rs, the import is dead and trips `cargo clippy --all-targets -- -D warnings`. Doc-comment references to `Handle::block_on` and `Handle::current()` remain (they describe behavior, not Rust paths). Signed-off-by: Madhavendra Rathore --- napi/src/metadata.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index b5caf147..05fa3077 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -51,7 +51,6 @@ use std::sync::Arc; use databricks_sql_kernel::{Identifier, LikePattern, Metadata, Result as KResult, ResultStream}; -use tokio::runtime::Handle; use crate::connection::Connection; use crate::error::napi_err_from_kernel; From 66d47c87059fa93756512bfffe7198a5d6b3fcef Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 25 May 2026 21:52:35 +0000 Subject: [PATCH 18/28] =?UTF-8?q?feat(napi):=20accept=20ExecuteOptions=20o?= =?UTF-8?q?n=20executeStatement=20=E2=80=94=20statementConf=20+=20queryTag?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Surfaces two of the kernel `StatementSpec` knobs through napi so JS callers can pass per-statement Spark conf and query tags: - `statementConf: Record` — per-statement conf overlay; merged on top of the session-level `sessionConf` at execute time. The kernel's `StatementSpec::statement_conf()` setter accepts this verbatim and forwards to SEA `parameters` / Thrift `confOverlay`. - `queryTags: Record` — convenience wrapper that JSON-encodes the tag map into the `query_tags` conf overlay key, matching NodeJS Thrift's `serializeQueryTags` shape (`{"k":"v","k2":"v2"}`). Passing both `queryTags` and an explicit `statementConf["query_tags"]` raises `InvalidArgument` to surface the ambiguity to the caller. Deferred (require kernel-side `StatementSpec` extensions or napi TypedValue mapping — separate PRs): - Positional / named parameters (TypedValue mapping) - Row limit, wait timeout (need `StatementSpec.row_limit` / `wait_timeout` fields — currently only on internal `ExecuteParams`) - Async execute (kernel has `submit()`; needs new napi wrapper class) The new `ExecuteOptions` napi-object is `Option<…>` so existing callers (`executeStatement(sql)`) keep working — napi-rs emits `options?: ExecuteOptions | undefined | null` on the JS-side d.ts. Empty maps (`{statementConf: {}}`) are treated the same as omission so the wire shape stays stable for the common case. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 244 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 241 insertions(+), 3 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 20d3d11a..ebf49ac0 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -27,6 +27,7 @@ //! fire-and-forget close on the captured runtime handle if explicit //! close was never called. +use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; @@ -37,6 +38,40 @@ use crate::runtime; use crate::statement::Statement; use crate::util::guarded; +/// Per-statement options for `Connection.executeStatement`. +/// +/// Mirrors the kernel `StatementSpec` knobs that are safe to thread +/// through napi without a kernel-side change. Today this covers: +/// - `statementConf` — per-statement Spark conf overlay +/// (`StatementSpec.statement_conf` → SEA `parameters` / +/// Thrift `confOverlay`) +/// - `queryTags` — convenience wrapper over `statementConf` with +/// key `query_tags`; serialised to JSON before being placed in the +/// conf overlay. Mirrors NodeJS Thrift's `serializeQueryTags` +/// convention (`lib/DBSQLSession.ts::serializeQueryTags`). +/// +/// Positional parameters, named parameters, row limit, and wait +/// timeout are deferred: they require either a non-trivial JS↔napi +/// `TypedValue` mapping (params) or a kernel-side `StatementSpec` +/// extension (`row_limit`/`wait_timeout`). Both land in follow-on PRs. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct ExecuteOptions { + /// Per-statement Spark conf overlay. Merged on top of the + /// session-level `sessionConf` at execute time; this map wins + /// on key collisions. Unknown keys are rejected by the server. + pub statement_conf: Option>, + /// Query tags as key→value pairs. JSON-encoded into the + /// `query_tags` conf overlay key, matching NodeJS Thrift's + /// `serializeQueryTags` shape. Passing both `queryTags` and a + /// `query_tags` key in `statementConf` raises `InvalidArgument` + /// — the explicit field wins to avoid silent overwrite. + pub query_tags: Option>, +} + /// Closed-state error builder. Mirrors `statement::statement_closed_err` /// — route through the kernel envelope so the TS reviver mints a typed /// `KernelError(code='InvalidStatementHandle')`. Single source of truth @@ -47,6 +82,73 @@ fn connection_closed_err() -> napi::Error { ) } +/// Merge `statement_conf` and `query_tags` from JS-supplied +/// `ExecuteOptions` into the single `HashMap` the +/// kernel's `StatementSpec::statement_conf` accepts. +/// +/// Returns `Ok(None)` when no per-statement conf is set (caller skips +/// the `.statement_conf(...)` builder call so the kernel sees the +/// session-level conf untouched). Returns `Ok(Some(conf))` when at +/// least one knob was set. Returns `Err(InvalidArgument)` when both +/// `queryTags` and `statementConf["query_tags"]` are present — the +/// caller's intent is ambiguous. +fn build_merged_statement_conf( + options: Option, +) -> napi::Result>> { + let Some(options) = options else { + return Ok(None); + }; + + let mut conf = options.statement_conf.unwrap_or_default(); + if let Some(tags) = options.query_tags { + if !tags.is_empty() && conf.contains_key("query_tags") { + return Err(napi_err_from_kernel( + KernelError::invalid_argument().message( + "ExecuteOptions: cannot supply both `queryTags` and \ + `statementConf[\"query_tags\"]` — pick one", + ), + )); + } + if !tags.is_empty() { + conf.insert("query_tags".to_string(), serialize_query_tags(&tags)); + } + } + + if conf.is_empty() { + Ok(None) + } else { + Ok(Some(conf)) + } +} + +/// Serialise a tag map to the same wire shape NodeJS Thrift's +/// `serializeQueryTags` produces: comma-separated `key:value` pairs. +/// Backslashes in keys are doubled; backslash, colon, and comma in +/// values are backslash-escaped. Null/empty values would produce a +/// bare key with no colon — but the napi `HashMap` +/// shape can't carry nulls today, so every tag here is `key:value`. +/// +/// Match the Thrift wire shape exactly: the SEA server merges +/// `confOverlay.query_tags` the same way regardless of which backend +/// produced it, and JS callers porting from Thrift expect identical +/// behaviour. +fn serialize_query_tags(tags: &HashMap) -> String { + tags.iter() + .map(|(k, v)| { + let esc_key = k.replace('\\', "\\\\"); + let esc_val = v + .chars() + .flat_map(|c| match c { + '\\' | ':' | ',' => vec!['\\', c], + other => vec![other], + }) + .collect::(); + format!("{esc_key}:{esc_val}") + }) + .collect::>() + .join(",") +} + /// Opaque connection handle wrapping a kernel `Session`. /// /// `inner` is `Arc>>` so: @@ -88,17 +190,36 @@ impl Connection { /// Execute a SQL statement and return a Statement handle that /// streams batches via `fetchNextBatch()`. /// - /// No per-statement options: catalog / schema / sessionConf are - /// session-level (`openSession`). + /// Catalog / schema / sessionConf are session-level + /// (`openSession`). Per-statement options on `ExecuteOptions`: + /// - `statementConf` — per-statement Spark conf overlay + /// - `queryTags` — JSON-encoded into `statement_conf["query_tags"]` + /// matching NodeJS Thrift's `serializeQueryTags` shape + /// + /// `options` is omitted/`None` for the no-options path; passing + /// `{ statementConf: {} }` (an empty map) is treated the same as + /// omission to keep the wire shape stable for the common case. #[napi] - pub async fn execute_statement(&self, sql: String) -> napi::Result { + pub async fn execute_statement( + &self, + sql: String, + options: Option, + ) -> napi::Result { let inner = Arc::clone(&self.inner); + // Merge `query_tags` into `statement_conf` at the napi boundary + // so the kernel sees a single conf map. JSON-encode the tag + // map to match the wire shape NodeJS Thrift produces in + // `serializeQueryTags` (`{"key":"value", ...}`). + let merged_conf = build_merged_statement_conf(options)?; guarded(async move { let guard = inner.lock().await; let session = guard.as_ref().ok_or_else(connection_closed_err)?; let mut stmt = session.statement(); stmt.spec().sql(sql); + if let Some(conf) = merged_conf { + stmt.spec().statement_conf(conf); + } let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. @@ -218,4 +339,121 @@ mod tests { }; assert_eq!(conn.session_id(), "session-survives-close"); } + + // ─── ExecuteOptions / build_merged_statement_conf ─────────────────── + + #[test] + fn merged_conf_none_when_options_is_none() { + let result = build_merged_statement_conf(None).unwrap(); + assert!(result.is_none(), "no options → no statement_conf"); + } + + #[test] + fn merged_conf_none_when_both_maps_empty() { + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(HashMap::new()), + query_tags: Some(HashMap::new()), + })) + .unwrap(); + assert!(result.is_none(), "empty maps → no statement_conf"); + } + + #[test] + fn merged_conf_passes_through_statement_conf() { + let mut conf = HashMap::new(); + conf.insert("ANSI_MODE".to_string(), "true".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: None, + })) + .unwrap() + .unwrap(); + assert_eq!(result.get("ANSI_MODE").map(String::as_str), Some("true")); + } + + #[test] + fn merged_conf_query_tags_serialised_into_query_tags_key() { + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + })) + .unwrap() + .unwrap(); + // Single-tag case is deterministic regardless of HashMap order. + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("team:platform"), + ); + } + + #[test] + fn merged_conf_query_tags_escape_special_chars_in_values() { + let mut tags = HashMap::new(); + tags.insert("k".to_string(), "v:1,v\\2".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + })) + .unwrap() + .unwrap(); + let encoded = result.get("query_tags").unwrap(); + // `:` → `\:`, `,` → `\,`, `\` → `\\`. Order in the input is + // `v:1,v\2` so the encoded form is `v\:1\,v\\2`. + assert_eq!(encoded, "k:v\\:1\\,v\\\\2"); + } + + #[test] + fn merged_conf_query_tags_escape_backslash_in_keys() { + let mut tags = HashMap::new(); + tags.insert("k\\1".to_string(), "v".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + })) + .unwrap() + .unwrap(); + assert_eq!(result.get("query_tags").map(String::as_str), Some("k\\\\1:v")); + } + + #[test] + fn merged_conf_rejects_dual_query_tags_definition() { + let mut conf = HashMap::new(); + conf.insert("query_tags".to_string(), "explicit:value".to_string()); + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + let err = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: Some(tags), + })) + .err() + .expect("must reject when both are set"); + assert!( + err.reason.contains("cannot supply both"), + "error must explain the conflict: {}", + err.reason, + ); + } + + #[test] + fn merged_conf_empty_query_tags_does_not_collide_with_existing_key() { + // An empty `queryTags: {}` map should be ignored, so the + // caller can still pass an explicit + // `statementConf["query_tags"]` alongside `queryTags: {}` + // without tripping the ambiguity guard. Convention: empty + // input maps mean "not supplied". + let mut conf = HashMap::new(); + conf.insert("query_tags".to_string(), "explicit:value".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: Some(HashMap::new()), + })) + .unwrap() + .unwrap(); + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("explicit:value"), + ); + } } From a50b50c21bc3a882b03e809675794c681189d6e1 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 25 May 2026 22:20:42 +0000 Subject: [PATCH 19/28] =?UTF-8?q?fix(napi):=20F3=20fixup=20=E2=80=94=20cli?= =?UTF-8?q?ppy=20err=5Fexpect=20+=20rustfmt=20on=20connection.rs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DA round 1 findings on F3: H1 (clippy `err_expect`): the `merged_conf_rejects_dual_query_tags_definition` test used `.err().expect(...)` which clippy 1.95+ flags. Switch to `.expect_err(...)` per the suggested help text. Behaviour unchanged; this was a stylistic clippy lint, not a logic defect. H2 (rustfmt): the `merged_conf_query_tags_escape_backslash_in_keys` test expressed a long `assert_eq!` on one line that exceeded rustfmt's max width. Break across three lines per the cargo fmt diff. Behaviour unchanged. Why I missed these initially: my prior gate verification ran inside a different worktree on the same branch (the F3b worktree, which had an in-progress amend), so my local `cargo clippy` + `cargo fmt --check` both reported green there. The origin branch (this PR's HEAD `79bba34`) didn't carry that amend. Lesson: never trust gate verification across worktrees without confirming the working tree matches the pushed SHA. Verified post-fix: - `cargo clippy --all-targets -- -D warnings` ✓ - `cargo +stable fmt --check` ✓ - `cargo test --lib` ✓ (32/32, same as before the fix) Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index ebf49ac0..dff0f473 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -414,7 +414,10 @@ mod tests { })) .unwrap() .unwrap(); - assert_eq!(result.get("query_tags").map(String::as_str), Some("k\\\\1:v")); + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("k\\\\1:v") + ); } #[test] @@ -427,8 +430,7 @@ mod tests { statement_conf: Some(conf), query_tags: Some(tags), })) - .err() - .expect("must reject when both are set"); + .expect_err("must reject when both are set"); assert!( err.reason.contains("cannot supply both"), "error must explain the conflict: {}", From be45ab2d8cf7a08718974e00baceb79f3f7d3794 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 25 May 2026 22:47:05 +0000 Subject: [PATCH 20/28] =?UTF-8?q?fix(napi):=20F3=20round-2=20=E2=80=94=20d?= =?UTF-8?q?ocstring=20+=20parity=20test=20fixups=20(DA=20M1/M4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DA round 2 findings on F3 (statement options + query tags): M1 docs: prior docstring claimed `queryTags` is "JSON-encoded into the conf overlay" — wrong. The actual implementation serialises to comma-separated `key:value` matching NodeJS Thrift's `serializeQueryTags` wire shape (`lib/utils/queryTags.ts`). Updated three sites that carried the stale "JSON" reference: - `ExecuteOptions` struct doc - `query_tags` field doc - `Connection::execute_statement` method doc + inline comment M2 dead code: the napi `queryTags` field is intentionally exported even though the JS adapter today pre-serialises via the Thrift helper and writes into `statementConf["query_tags"]` directly. The field stays as an alternate API surface for non- NodeJS consumers (future pyo3 reuse, direct napi consumers); the NodeJS adapter path is documented as the byte-identical-Thrift- parity route. Updated the struct doc to spell out the dual paths and their parity contracts. M4 parity: added a struct-level "Tag-order caveat" doc block that documents the HashMap-iteration-order vs `Object.keys`- insertion-order divergence between the napi `queryTags` path and Thrift's `serializeQueryTags`. The SEA server is order- insensitive on conf values so the two are functionally equivalent; callers needing byte-identical Thrift parity use the JS adapter path. Added 5 new Rust unit tests pinning the per-tag byte shape against the Thrift algorithm: - single-tag deterministic case - value-side escape ordering (`\` `:` `,`) - key-side backslash-only escape (NOT colons/commas — Thrift asymmetry pinned so a future "uniformity" refactor fails the test) - empty-map edge case - multi-tag order-insensitive set equality M3 lint: already clean — `cargo clippy --all-targets -- -D warnings` passes locally on this branch's tip. Test count: 32 → 37 (5 new). All passing. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 124 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 111 insertions(+), 13 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index dff0f473..4a20f490 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -46,14 +46,28 @@ use crate::util::guarded; /// (`StatementSpec.statement_conf` → SEA `parameters` / /// Thrift `confOverlay`) /// - `queryTags` — convenience wrapper over `statementConf` with -/// key `query_tags`; serialised to JSON before being placed in the -/// conf overlay. Mirrors NodeJS Thrift's `serializeQueryTags` -/// convention (`lib/DBSQLSession.ts::serializeQueryTags`). +/// key `query_tags`; serialised to the same comma-separated +/// `key:value` wire shape NodeJS Thrift's `serializeQueryTags` +/// produces (`lib/utils/queryTags.ts`). Backslashes in keys are +/// doubled; backslash/colon/comma in values are backslash-escaped. /// /// Positional parameters, named parameters, row limit, and wait /// timeout are deferred: they require either a non-trivial JS↔napi /// `TypedValue` mapping (params) or a kernel-side `StatementSpec` /// extension (`row_limit`/`wait_timeout`). Both land in follow-on PRs. +/// +/// **Tag-order caveat (M4 parity note).** The napi `queryTags` field +/// is a Rust `HashMap` whose iteration order is +/// non-deterministic, so the serialised `query_tags` value may have +/// a different key order than Thrift's `serializeQueryTags` (which +/// iterates `Object.keys(...)` in insertion order) for the same +/// input. The SEA server is order-insensitive on conf values, so +/// the two are functionally equivalent. If a caller needs +/// byte-identical Thrift parity, the JS adapter pre-serialises via +/// `serializeQueryTags` and writes the result into +/// `statementConf["query_tags"]` directly — see +/// `SeaSessionBackend.executeStatement` in the NodeJS driver. This +/// path is the one the production code uses. #[allow( dead_code, reason = "exported via napi macro codegen; not called from Rust" @@ -64,11 +78,17 @@ pub struct ExecuteOptions { /// session-level `sessionConf` at execute time; this map wins /// on key collisions. Unknown keys are rejected by the server. pub statement_conf: Option>, - /// Query tags as key→value pairs. JSON-encoded into the - /// `query_tags` conf overlay key, matching NodeJS Thrift's - /// `serializeQueryTags` shape. Passing both `queryTags` and a - /// `query_tags` key in `statementConf` raises `InvalidArgument` - /// — the explicit field wins to avoid silent overwrite. + /// Query tags as key→value pairs. Serialised to a comma- + /// separated `key:value` string (backslash-escaping `\`, `:`, + /// `,`) and placed into `statementConf["query_tags"]`, matching + /// NodeJS Thrift's `serializeQueryTags` wire shape. Passing + /// both `queryTags` AND a `query_tags` key in `statementConf` + /// raises `InvalidArgument` — the caller's intent is ambiguous + /// so we refuse to silently pick one over the other. + /// + /// See the struct-level "Tag-order caveat" for the + /// HashMap-iteration-order vs `Object.keys`-iteration-order + /// divergence and the byte-identical-Thrift-parity workaround. pub query_tags: Option>, } @@ -193,8 +213,9 @@ impl Connection { /// Catalog / schema / sessionConf are session-level /// (`openSession`). Per-statement options on `ExecuteOptions`: /// - `statementConf` — per-statement Spark conf overlay - /// - `queryTags` — JSON-encoded into `statement_conf["query_tags"]` - /// matching NodeJS Thrift's `serializeQueryTags` shape + /// - `queryTags` — serialised to a comma-separated `key:value` + /// string and placed in `statement_conf["query_tags"]`, + /// matching NodeJS Thrift's `serializeQueryTags` wire shape /// /// `options` is omitted/`None` for the no-options path; passing /// `{ statementConf: {} }` (an empty map) is treated the same as @@ -207,9 +228,10 @@ impl Connection { ) -> napi::Result { let inner = Arc::clone(&self.inner); // Merge `query_tags` into `statement_conf` at the napi boundary - // so the kernel sees a single conf map. JSON-encode the tag - // map to match the wire shape NodeJS Thrift produces in - // `serializeQueryTags` (`{"key":"value", ...}`). + // so the kernel sees a single conf map. Serialise the tag + // map to the comma-separated `key:value` wire shape NodeJS + // Thrift produces in `serializeQueryTags` + // (`lib/utils/queryTags.ts`). let merged_conf = build_merged_statement_conf(options)?; guarded(async move { let guard = inner.lock().await; @@ -458,4 +480,80 @@ mod tests { Some("explicit:value"), ); } + + // ─── DA round-2 M4 parity — byte-shape vs Thrift's serializeQueryTags ─ + + /// `serializeQueryTags` (NodeJS Thrift, `lib/utils/queryTags.ts`) + /// is the canonical wire shape for `query_tags`. Pin the + /// per-tag byte shape produced by the kernel-side serializer + /// against the algorithm Thrift uses, so a regression on either + /// side fails this test. + /// + /// Algorithm (per Thrift): + /// - Keys: backslash doubled (`\` → `\\`); no other escaping + /// - Values: backslash, colon, and comma each backslash-escaped + /// - Tags: joined with `,` + /// - Single-tag case is order-deterministic; multi-tag case + /// asserts each pair appears regardless of HashMap iteration + /// order (the documented order caveat). + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_single_tag() { + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + assert_eq!(serialize_query_tags(&tags), "team:platform"); + } + + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_escapes() { + // Per Thrift's `escapedValue.replace(/[\\:,]/g, c => '\\' + c)`: + // input `v:1,v\2` + // output `v\:1\,v\\2` + let mut tags = HashMap::new(); + tags.insert("k".to_string(), "v:1,v\\2".to_string()); + assert_eq!(serialize_query_tags(&tags), "k:v\\:1\\,v\\\\2"); + } + + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_key_backslash_only() { + // Per Thrift's `escapedKey = key.replace(/\\/g, '\\\\')`: + // input `k\1` + // output `k\\1` + // Colons/commas in keys are NOT escaped on Thrift's path — + // they're only escaped in values. Test pins this asymmetry + // so a future "uniformity" refactor that escapes them in + // keys too gets caught. + let mut tags = HashMap::new(); + tags.insert("k\\1".to_string(), "v".to_string()); + assert_eq!(serialize_query_tags(&tags), "k\\\\1:v"); + } + + #[test] + fn serialize_query_tags_empty_map_yields_empty_string() { + // Thrift returns `undefined` for empty input, but Thrift's + // caller only invokes the serializer when input is non-empty + // (see `lib/DBSQLSession.ts:231` `if (serializedQueryTags + // !== undefined)`). Our serializer is called only by + // `build_merged_statement_conf` which already filters empty + // input out, so this test pins the never-called case for + // defense. + assert_eq!(serialize_query_tags(&HashMap::new()), ""); + } + + #[test] + fn serialize_query_tags_multi_tag_contains_each_pair_regardless_of_order() { + // Multi-tag case: HashMap iteration is non-deterministic, so + // we can't assert a single byte string. Assert each pair is + // present and the join uses `,`. SEA server treats conf + // values as order-insensitive, so this is functionally + // equivalent to the Thrift output regardless of order. + let mut tags = HashMap::new(); + tags.insert("a".to_string(), "1".to_string()); + tags.insert("b".to_string(), "2".to_string()); + let s = serialize_query_tags(&tags); + let pairs: std::collections::HashSet<&str> = s.split(',').collect(); + assert!( + pairs == ["a:1", "b:2"].iter().copied().collect(), + "got: {s}", + ); + } } From 16b1becd6e294ff00ba44920b6a6ee51d2824775 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Fri, 29 May 2026 06:25:40 +0000 Subject: [PATCH 21/28] feat(napi): TypedValue codec for positional params MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mirror pyo3/src/params.rs in the napi binding so the JS side can bind positional parameters via Connection.executeStatement(sql, { positional_params }). Each parameter is a { sql_type, value } pair — value is the string-encoded literal or null for SQL NULL. The decoder parses through the same validation surface pyo3 uses (DECIMAL precision/scale, non-finite FLOAT/DOUBLE rejection, compound/BINARY rejection), so the two language bindings stay aligned on what the kernel sees on the wire. ExecuteOptions is exposed as a JS-visible object so future statement-level knobs (named params, conf overlay, result format) can land non-breakingly. Tests cover the 10-type C5 matrix (INT, BIGINT, FLOAT, DOUBLE, STRING, BOOLEAN, DATE, TIMESTAMP, DECIMAL, BINARY-rejected) plus the eager-failure + null-value contracts at the helper level. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/Cargo.lock | 1 + napi/Cargo.toml | 7 + napi/src/connection.rs | 208 +++++++++++- napi/src/lib.rs | 1 + napi/src/params.rs | 743 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 956 insertions(+), 4 deletions(-) create mode 100644 napi/src/params.rs diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 4732b960..68485eeb 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -380,6 +380,7 @@ dependencies = [ "arrow-array", "arrow-ipc", "arrow-schema", + "chrono", "databricks-sql-kernel", "futures", "napi", diff --git a/napi/Cargo.toml b/napi/Cargo.toml index 5949b986..306f4d1c 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -97,6 +97,13 @@ arrow-ipc = "57" # `src/error.rs` without bouncing through a hand-rolled escaper. serde_json = "1" +# Date/time parsing for the params codec. Already a kernel transitive +# dep (the kernel's `TypedValue::Date`/`Timestamp{,Ntz,Ltz}` variants +# wrap `chrono` types directly); declared here so `params.rs` can name +# `NaiveDate` / `NaiveDateTime` / `DateTime` for literal parsing. +# Version kept in lock-step with the kernel's `chrono` dep. +chrono = { version = "0.4", default-features = false, features = ["clock"] } + [build-dependencies] napi-build = "2" diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 20d3d11a..6220e6cc 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -30,13 +30,63 @@ use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::{Error as KernelError, Session}; +use databricks_sql_kernel::{Error as KernelError, Session, TypedValue}; use crate::error::napi_err_from_kernel; +use crate::params::{parse_typed_value, TypedValueInput}; use crate::runtime; use crate::statement::Statement; use crate::util::guarded; +/// JS-visible options bag for `Connection.executeStatement`. +/// +/// All fields are optional. The default-everything shape (no options +/// argument on the JS side, or `{}`) is equivalent to the parameterless +/// `executeStatement(sql)` form preserved from the napi-skeleton PR. +/// +/// Today the only field is `positional_params`. Keeping the surface as +/// a struct — rather than overloading per-call — lets future +/// statement-level knobs (named params, conf overlay, result format) +/// land non-breakingly. Mirrors `StatementSpec`'s plain-data shape +/// kernel-side. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct ExecuteOptions { + /// Positional parameters, in 1-based wire order. Index `i` in this + /// Vec corresponds to the `i+1`-th `?` placeholder in the SQL. + /// Each entry is a `{ sqlType, value }` pair — `value` is the + /// string-encoded literal or `null` for SQL NULL. + /// + /// Mirrors `StatementSpec::positional_params` (kernel-side) and + /// `pyo3::Statement::bind_param` (pyo3-side). The JS adapter is + /// expected to stringify values before crossing the FFI — see + /// `DBSQLParameter.toSparkParameter()` on the Node-driver side for + /// the canonical stringification rules. + pub positional_params: Option>, +} + +/// Translate the JS-side `ExecuteOptions.positional_params` into the +/// kernel's `Vec`. Each entry is parsed through +/// [`parse_typed_value`] so the validation surface (bad literal, bad +/// DECIMAL precision, unsupported type) is the same as the pyo3 +/// binding's. +/// +/// Returns `Err` on the FIRST malformed entry — the JS caller sees the +/// first failure's structured envelope, and the kernel never receives +/// a partially-bound spec. Matches how pyo3 surfaces bind failures +/// (eager, per-call). +fn decode_positional_params(inputs: Vec) -> Result, napi::Error> { + inputs + .into_iter() + .map(|tv| { + parse_typed_value(&tv.sql_type, tv.value.as_deref()).map_err(napi_err_from_kernel) + }) + .collect() +} + /// Closed-state error builder. Mirrors `statement::statement_closed_err` /// — route through the kernel envelope so the TS reviver mints a typed /// `KernelError(code='InvalidStatementHandle')`. Single source of truth @@ -88,10 +138,33 @@ impl Connection { /// Execute a SQL statement and return a Statement handle that /// streams batches via `fetchNextBatch()`. /// - /// No per-statement options: catalog / schema / sessionConf are - /// session-level (`openSession`). + /// `options` is optional. The `positional_params` field, when + /// present, is the typed-value codec input the kernel binds against + /// the `?` placeholders in `sql`. Catalog / schema / sessionConf + /// remain session-level (`openSession`) — the SEA wire protocol + /// carries them on `CreateSession`, not per-statement. + /// + /// Bind-time errors (bad DECIMAL precision, unsupported SQL type, + /// non-finite FLOAT/DOUBLE) surface as `KernelError(code= + /// 'InvalidArgument')` BEFORE the wire `ExecuteStatement` call — + /// matches the pyo3 binding's eager-bind contract and the JDBC / + /// ODBC drivers' "fail at setParameter" expectation. #[napi] - pub async fn execute_statement(&self, sql: String) -> napi::Result { + pub async fn execute_statement( + &self, + sql: String, + options: Option, + ) -> napi::Result { + // Decode params BEFORE acquiring the session lock — bind-time + // validation failures should not block other concurrent + // executors waiting on the mutex. The kernel `StatementSpec` + // is plain data and accepts a pre-built `Vec` via + // the `positional_params` field, so we can do this work on the + // caller's tokio task. + let positional = match options.and_then(|o| o.positional_params) { + Some(inputs) => decode_positional_params(inputs)?, + None => Vec::new(), + }; let inner = Arc::clone(&self.inner); guarded(async move { let guard = inner.lock().await; @@ -99,6 +172,13 @@ impl Connection { let mut stmt = session.statement(); stmt.spec().sql(sql); + if !positional.is_empty() { + // Set the whole vec at once — `StatementSpec::positional_params` + // is a public field, so direct assignment is the + // intended kernel surface. Avoids the per-call `param(i, + // v)` resize loop that's there for sparse-bind cases. + stmt.spec().positional_params = positional; + } let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. @@ -218,4 +298,124 @@ mod tests { }; assert_eq!(conn.session_id(), "session-survives-close"); } + + // ─── decode_positional_params ────────────────────────────────── + // + // The decode happens BEFORE the session lock — these tests pin + // that contract at the helper level. End-to-end behavior is + // covered by the params.rs codec tests; here we focus on the + // happy-path Vec composition and the error-envelope shape. + + #[test] + fn decode_positional_params_empty_vec_round_trips() { + let got = decode_positional_params(Vec::new()).expect("empty decode succeeds"); + assert!(got.is_empty()); + } + + #[test] + fn decode_positional_params_10_type_matrix() { + // The C5 cluster's headline 10-type matrix, end-to-end through + // the decode helper rather than through `parse_typed_value` + // directly. Confirms the `TypedValueInput` → `TypedValue` + // mapping survives the Vec round trip. + let inputs = vec![ + TypedValueInput { + sql_type: "INT".into(), + value: Some("42".into()), + }, + TypedValueInput { + sql_type: "BIGINT".into(), + value: Some("9999999999".into()), + }, + TypedValueInput { + sql_type: "FLOAT".into(), + value: Some("3.14".into()), + }, + TypedValueInput { + sql_type: "DOUBLE".into(), + value: Some("2.718281828459045".into()), + }, + TypedValueInput { + sql_type: "STRING".into(), + value: Some("hello world".into()), + }, + TypedValueInput { + sql_type: "BOOLEAN".into(), + value: Some("true".into()), + }, + TypedValueInput { + sql_type: "DATE".into(), + value: Some("2026-05-15".into()), + }, + TypedValueInput { + sql_type: "TIMESTAMP".into(), + value: Some("2026-05-15 12:30:45".into()), + }, + TypedValueInput { + sql_type: "DECIMAL(10,2)".into(), + value: Some("-123.45".into()), + }, + ]; + let decoded = decode_positional_params(inputs).expect("10-type decode succeeds"); + assert_eq!(decoded.len(), 9); + // BINARY — pin the bind-time-rejection contract through the + // helper. The 10th type in the matrix produces an + // InvalidArgument envelope rather than aborting the whole vec + // silently. + let err = decode_positional_params(vec![TypedValueInput { + sql_type: "BINARY".into(), + value: Some("cafe".into()), + }]) + .unwrap_err(); + let reason = err.reason.as_str(); + assert!( + reason.starts_with(crate::error::ERROR_SENTINEL), + "BINARY rejection must be enveloped, got: {reason}" + ); + assert!( + reason.contains(r#""code":"InvalidArgument""#), + "BINARY rejection must carry InvalidArgument, got: {reason}" + ); + } + + #[test] + fn decode_positional_params_short_circuits_on_first_bad_entry() { + // First bad entry stops decoding — the JS caller sees one + // structured envelope rather than a multi-error report. The + // good entry that follows must not contribute to the result. + let inputs = vec![ + TypedValueInput { + sql_type: "INT".into(), + value: Some("42".into()), + }, + TypedValueInput { + sql_type: "DECIMAL(10,2)".into(), + value: Some("not-a-number".into()), + }, + TypedValueInput { + sql_type: "STRING".into(), + value: Some("should-not-decode".into()), + }, + ]; + let err = decode_positional_params(inputs).unwrap_err(); + let reason = err.reason.as_str(); + assert!(reason.starts_with(crate::error::ERROR_SENTINEL)); + assert!( + reason.contains("DECIMAL"), + "first failure should be the DECIMAL one, got: {reason}" + ); + } + + #[test] + fn decode_positional_params_null_value_becomes_kernel_null() { + // `value: None` ⇒ `TypedValue::Null` regardless of `sql_type` — + // matches the connector's VoidParameter shape and pyo3. + let inputs = vec![TypedValueInput { + sql_type: "INT".into(), + value: None, + }]; + let decoded = decode_positional_params(inputs).expect("null decode succeeds"); + assert_eq!(decoded.len(), 1); + assert!(matches!(decoded[0], TypedValue::Null)); + } } diff --git a/napi/src/lib.rs b/napi/src/lib.rs index 455bfc91..efe1f772 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -43,6 +43,7 @@ pub(crate) mod connection; pub(crate) mod database; pub(crate) mod error; pub(crate) mod logger; +pub(crate) mod params; pub(crate) mod result; pub(crate) mod runtime; pub(crate) mod statement; diff --git a/napi/src/params.rs b/napi/src/params.rs new file mode 100644 index 00000000..9afa4c5b --- /dev/null +++ b/napi/src/params.rs @@ -0,0 +1,743 @@ +// 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. + +//! JS↔napi parameter codec — parses a connector-style +//! `{ type, value }` pair into a kernel `TypedValue`. +//! +//! Mirrors `pyo3/src/params.rs` line-for-line so the two bindings share +//! a single contract for what the kernel sees on the wire. The JS-side +//! `DBSQLParameter` already stringifies values before crossing the FFI +//! (see `lib/DBSQLParameter.ts::toSparkParameter` in the Node driver): +//! the napi binding takes the `(sql_type, value_str)` form directly to +//! avoid a per-call JS-value → Rust-value reflection trip. +//! +//! Compound types (`ARRAY` / `MAP` / `STRUCT`) and BINARY are +//! explicitly rejected — the SEA wire does not accept either as a bound +//! parameter today, and we surface that as an `InvalidArgument` error +//! at bind time so the failure mode matches pyo3's `NotSupportedError` +//! shape rather than an opaque server-side execute error. + +use chrono::{NaiveDate, NaiveDateTime}; +use databricks_sql_kernel::{Error, Result, TypedValue}; + +/// JS-visible binding for a single positional parameter. +/// +/// Shape mirrors the `TSparkParameter` wire object the Thrift backend +/// already emits via `DBSQLParameter.toSparkParameter()` — `type` is the +/// canonical Databricks SQL type name (`"INT"`, `"STRING"`, +/// `"DECIMAL(10,2)"`, ...), `value` is the string-encoded literal or +/// `None` for SQL NULL. +/// +/// Why a string for `value` instead of a tagged JS union: round-tripping +/// arbitrary JS values across the FFI requires either (a) a custom +/// napi `FromNapiValue` per arm, or (b) a `serde_json::Value`-style +/// dynamic dispatch on the Rust side. The Node-driver adapter already +/// stringifies before calling the binding (see `DBSQLParameter` and the +/// existing pyo3 wrapper), so the string-in / string-parsed contract +/// adds no JS-side complexity and keeps the kernel-side validation in +/// one place. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct TypedValueInput { + /// Canonical Databricks SQL type name. Case-insensitive for the + /// simple variants; for DECIMAL the parenthesised form + /// (`"DECIMAL(10,2)"`) is required so the kernel can extract + /// precision/scale. + pub sql_type: String, + /// String-encoded value. `None` always produces `TypedValue::Null` + /// regardless of `sql_type` — matches the connector's + /// `VoidParameter` shape and the pyo3 binding's contract. + pub value: Option, +} + +/// Parse a single `TypedValueInput` into a kernel `TypedValue`. +/// +/// Public for cross-module use within the crate (the future +/// `Connection::execute_statement` overload will call this for each +/// entry in `ExecuteOptions.positional_params`). +pub(crate) fn parse_typed_value(sql_type: &str, value_str: Option<&str>) -> Result { + let s = match value_str { + None => return Ok(TypedValue::Null), + Some(s) => s, + }; + + let upper = sql_type.to_ascii_uppercase(); + match upper.as_str() { + "VOID" => Ok(TypedValue::Null), + "BOOLEAN" | "BOOL" => parse_bool(s), + "TINYINT" => parse_i8(s), + "SMALLINT" => parse_i16(s), + "INT" | "INTEGER" => parse_i32(s), + "BIGINT" | "LONG" => parse_i64(s), + "FLOAT" => parse_f32(s), + "DOUBLE" => parse_f64(s), + "STRING" | "VARCHAR" | "CHAR" => Ok(TypedValue::String(s.to_owned())), + "BINARY" => Err(invalid( + "BINARY parameters are not supported by the SEA wire today", + )), + "DATE" => parse_date(s), + // TIMESTAMP / TIMESTAMP_NTZ share `parse_timestamp` for naive + // parsing; the NTZ arm re-wraps so the SEA wire payload emits + // the explicit type-name. TIMESTAMP_LTZ has its own parser since + // it carries a timezone offset. + "TIMESTAMP" => parse_timestamp(s), + "TIMESTAMP_NTZ" => parse_timestamp(s).map(|v| match v { + TypedValue::Timestamp(ts) => TypedValue::TimestampNtz(ts), + other => other, + }), + "TIMESTAMP_LTZ" => parse_timestamp_ltz(s), + "INTERVAL" => Ok(TypedValue::Interval(s.to_owned())), + // VARIANT — JSON text passes through verbatim. Same JSON-null + // vs SQL-NULL distinction as the pyo3 codec: `value=None` + // short-circuits to TypedValue::Null at the top of this + // function; `value=Some("null")` lands here as + // TypedValue::Variant("null") which is a JSON-null VARIANT + // value, not SQL NULL. + "VARIANT" => Ok(TypedValue::Variant(s.to_owned())), + _ if upper.starts_with("DECIMAL(") => parse_decimal(sql_type, s), + _ if is_compound_type_name(&upper) => Err(invalid( + "compound parameter types (ARRAY/MAP/STRUCT) are not yet supported", + )), + _ => Err(invalid_msg(format!( + "unsupported parameter SQL type: {sql_type:?}" + ))), + } +} + +/// True iff `upper` is one of ARRAY/MAP/STRUCT exactly, or one of +/// those followed by `<` (generic) or `(` (function-style). Tighter +/// than a `starts_with("ARRAY")` test, which would also match unrelated +/// names like `ARRAYBUFFER` or `STRUCTURE`. +fn is_compound_type_name(upper: &str) -> bool { + for prefix in ["ARRAY", "MAP", "STRUCT"] { + if upper == prefix { + return true; + } + if let Some(rest) = upper.strip_prefix(prefix) { + if rest.starts_with('<') || rest.starts_with('(') { + return true; + } + } + } + false +} + +fn invalid(msg: &'static str) -> Error { + Error::invalid_argument().message(msg) +} + +fn invalid_msg(msg: String) -> Error { + Error::invalid_argument().message(msg) +} + +fn parse_bool(s: &str) -> Result { + match s.to_ascii_lowercase().as_str() { + "true" | "1" => Ok(TypedValue::Bool(true)), + "false" | "0" => Ok(TypedValue::Bool(false)), + _ => Err(invalid_msg(format!("invalid BOOLEAN literal: {s:?}"))), + } +} + +fn parse_i8(s: &str) -> Result { + s.parse::() + .map(TypedValue::Int8) + .map_err(|e| invalid_msg(format!("invalid TINYINT literal {s:?}: {e}"))) +} + +fn parse_i16(s: &str) -> Result { + s.parse::() + .map(TypedValue::Int16) + .map_err(|e| invalid_msg(format!("invalid SMALLINT literal {s:?}: {e}"))) +} + +fn parse_i32(s: &str) -> Result { + s.parse::() + .map(TypedValue::Int32) + .map_err(|e| invalid_msg(format!("invalid INT literal {s:?}: {e}"))) +} + +fn parse_i64(s: &str) -> Result { + s.parse::() + .map(TypedValue::Int64) + .map_err(|e| invalid_msg(format!("invalid BIGINT literal {s:?}: {e}"))) +} + +fn parse_f32(s: &str) -> Result { + let v = s + .parse::() + .map_err(|e| invalid_msg(format!("invalid FLOAT literal {s:?}: {e}")))?; + if !v.is_finite() { + return Err(invalid_msg(format!("non-finite FLOAT literal {s:?}"))); + } + Ok(TypedValue::Float32(v)) +} + +fn parse_f64(s: &str) -> Result { + let v = s + .parse::() + .map_err(|e| invalid_msg(format!("invalid DOUBLE literal {s:?}: {e}")))?; + if !v.is_finite() { + return Err(invalid_msg(format!("non-finite DOUBLE literal {s:?}"))); + } + Ok(TypedValue::Float64(v)) +} + +fn parse_date(s: &str) -> Result { + NaiveDate::parse_from_str(s, "%Y-%m-%d") + .map(TypedValue::Date) + .map_err(|e| invalid_msg(format!("invalid DATE literal {s:?}: {e}"))) +} + +fn parse_timestamp(s: &str) -> Result { + // JS's `Date.prototype.toISOString()` always emits a trailing `Z`; + // strip it before parsing since `TypedValue::Timestamp` is a naive + // `NaiveDateTime` (the SEA wire encodes timestamps in UTC). + let body = s.strip_suffix('Z').unwrap_or(s); + let formats = [ + "%Y-%m-%d %H:%M:%S%.f", + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%dT%H:%M:%S%.f", + "%Y-%m-%dT%H:%M:%S", + ]; + for fmt in formats { + if let Ok(ts) = NaiveDateTime::parse_from_str(body, fmt) { + return Ok(TypedValue::Timestamp(ts)); + } + } + Err(invalid_msg(format!("invalid TIMESTAMP literal {s:?}"))) +} + +fn parse_timestamp_ltz(s: &str) -> Result { + use chrono::{DateTime, FixedOffset, Utc}; + + if let Ok(dt) = DateTime::::parse_from_rfc3339(s) { + return Ok(TypedValue::TimestampLtz(dt.with_timezone(&Utc))); + } + if let Ok(dt) = DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f%:z") { + return Ok(TypedValue::TimestampLtz(dt.with_timezone(&Utc))); + } + let body = s.strip_suffix('Z').unwrap_or(s); + let formats = [ + "%Y-%m-%d %H:%M:%S%.f", + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%dT%H:%M:%S%.f", + "%Y-%m-%dT%H:%M:%S", + ]; + for fmt in formats { + if let Ok(naive) = NaiveDateTime::parse_from_str(body, fmt) { + return Ok(TypedValue::TimestampLtz( + DateTime::::from_naive_utc_and_offset(naive, Utc), + )); + } + } + Err(invalid_msg(format!("invalid TIMESTAMP_LTZ literal {s:?}"))) +} + +fn parse_decimal(sql_type: &str, value: &str) -> Result { + let (precision, scale) = extract_decimal_precision_scale(sql_type)?; + validate_decimal_literal(value)?; + Ok(TypedValue::Decimal { + value: value.to_owned(), + precision, + scale, + }) +} + +/// Reject DECIMAL value strings that don't represent a finite number. +/// Accepts an optional sign followed by an integer part (digits) and, +/// optionally, a dot and a fractional part — but requires at least one +/// digit on each side of the dot when a dot is present. Forms like +/// `42.`, `.5` and the bare sign `-` are rejected to match Databricks' +/// DECIMAL literal parser. Scientific notation (`1e5`) is disallowed +/// because it changes the implicit precision/scale and the connector +/// never emits it. +fn validate_decimal_literal(value: &str) -> Result<()> { + let bytes = value.as_bytes(); + if bytes.is_empty() { + return Err(invalid_msg(format!("invalid DECIMAL literal {value:?}"))); + } + let mut i = 0; + if matches!(bytes[i], b'+' | b'-') { + i += 1; + } + let int_start = i; + while i < bytes.len() && bytes[i].is_ascii_digit() { + i += 1; + } + let int_digits = i - int_start; + let mut has_dot = false; + let mut frac_digits = 0; + if i < bytes.len() && bytes[i] == b'.' { + has_dot = true; + i += 1; + let frac_start = i; + while i < bytes.len() && bytes[i].is_ascii_digit() { + i += 1; + } + frac_digits = i - frac_start; + } + let well_formed = i == bytes.len() && int_digits >= 1 && (!has_dot || frac_digits >= 1); + if !well_formed { + return Err(invalid_msg(format!("invalid DECIMAL literal {value:?}"))); + } + Ok(()) +} + +fn extract_decimal_precision_scale(sql_type: &str) -> Result<(u8, i8)> { + let lparen = sql_type.find('(').ok_or_else(|| { + invalid_msg(format!( + "DECIMAL type missing precision/scale: {sql_type:?}" + )) + })?; + let rparen = sql_type + .rfind(')') + .ok_or_else(|| invalid_msg(format!("DECIMAL type missing closing paren: {sql_type:?}")))?; + if rparen <= lparen { + return Err(invalid_msg(format!( + "DECIMAL type has malformed parens: {sql_type:?}" + ))); + } + let inner = &sql_type[lparen + 1..rparen]; + let parts: Vec<&str> = inner.split(',').map(|p| p.trim()).collect(); + let (precision_str, scale_str) = match parts.as_slice() { + [p] => (*p, "0"), + [p, s] => (*p, *s), + _ => { + return Err(invalid_msg(format!( + "DECIMAL type must have one or two parameters: {sql_type:?}" + ))); + } + }; + let precision = precision_str + .parse::() + .map_err(|e| invalid_msg(format!("invalid DECIMAL precision {sql_type:?}: {e}")))?; + let scale = scale_str + .parse::() + .map_err(|e| invalid_msg(format!("invalid DECIMAL scale {sql_type:?}: {e}")))?; + // Kernel-side bind constraint, intentionally tighter than the + // Databricks server spec. Mirrors pyo3 — see `pyo3/src/params.rs` + // for the rationale. + if !(1..=38).contains(&precision) { + return Err(invalid_msg(format!( + "DECIMAL precision must be in 1..=38: {sql_type:?}" + ))); + } + if scale < 0 || (scale as i16) > (precision as i16) { + return Err(invalid_msg(format!( + "DECIMAL scale must be in 0..=precision: {sql_type:?}" + ))); + } + Ok((precision, scale)) +} + +#[cfg(test)] +mod tests { + use super::*; + use databricks_sql_kernel::ErrorCode; + + // ─── Basic-type unit tests ────────────────────────────────────── + // + // These mirror the pyo3 codec's tests so a future maintainer who + // changes one binding's contract sees the other binding's test + // fail. The 10-type matrix corresponds to the C5 cluster — see + // `sea-workflow/decisions/2026-05-28-autonomous-parity-decisions.md` + // row 2.5-2.10 / 3.18-3.22. + + #[test] + fn none_value_is_null() { + assert!(matches!( + parse_typed_value("INT", None).unwrap(), + TypedValue::Null + )); + assert!(matches!( + parse_typed_value("STRING", None).unwrap(), + TypedValue::Null + )); + // Even a bad SQL type is fine when value is None — VOID-style. + assert!(matches!( + parse_typed_value("NOPE", None).unwrap(), + TypedValue::Null + )); + } + + #[test] + fn void_type_is_null() { + assert!(matches!( + parse_typed_value("VOID", Some("anything")).unwrap(), + TypedValue::Null + )); + } + + #[test] + fn boolean_parses_truthy_falsey() { + assert!(matches!( + parse_typed_value("BOOLEAN", Some("true")).unwrap(), + TypedValue::Bool(true) + )); + assert!(matches!( + parse_typed_value("BOOLEAN", Some("False")).unwrap(), + TypedValue::Bool(false) + )); + assert!(matches!( + parse_typed_value("BOOL", Some("1")).unwrap(), + TypedValue::Bool(true) + )); + let e = parse_typed_value("BOOLEAN", Some("yes")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn integer_types_parse() { + assert!(matches!( + parse_typed_value("TINYINT", Some("127")).unwrap(), + TypedValue::Int8(127) + )); + assert!(matches!( + parse_typed_value("SMALLINT", Some("-100")).unwrap(), + TypedValue::Int16(-100) + )); + assert!(matches!( + parse_typed_value("INT", Some("42")).unwrap(), + TypedValue::Int32(42) + )); + assert!(matches!( + parse_typed_value("INTEGER", Some("-42")).unwrap(), + TypedValue::Int32(-42) + )); + assert!(matches!( + parse_typed_value("BIGINT", Some("9999999999")).unwrap(), + TypedValue::Int64(9999999999) + )); + assert!(matches!( + parse_typed_value("LONG", Some("9999999999")).unwrap(), + TypedValue::Int64(9999999999) + )); + } + + #[test] + fn out_of_range_int_errors() { + let e = parse_typed_value("TINYINT", Some("300")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + let e = parse_typed_value("INT", Some("9999999999")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn floats_parse() { + assert!(matches!( + parse_typed_value("FLOAT", Some("3.14")).unwrap(), + TypedValue::Float32(_) + )); + assert!(matches!( + parse_typed_value("DOUBLE", Some("2.718281828459045")).unwrap(), + TypedValue::Float64(_) + )); + } + + #[test] + fn float_overflow_and_nan_rejected() { + for s in ["1e500", "-1e500", "nan", "NaN", "inf", "-Infinity"] { + let e = parse_typed_value("FLOAT", Some(s)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "FLOAT {s:?}"); + let e = parse_typed_value("DOUBLE", Some(s)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "DOUBLE {s:?}"); + } + } + + #[test] + fn string_passes_through() { + match parse_typed_value("STRING", Some("hello world")).unwrap() { + TypedValue::String(s) => assert_eq!(s, "hello world"), + other => panic!("expected String, got {other:?}"), + } + assert!(matches!( + parse_typed_value("VARCHAR", Some("x")).unwrap(), + TypedValue::String(_) + )); + assert!(matches!( + parse_typed_value("CHAR", Some("y")).unwrap(), + TypedValue::String(_) + )); + } + + #[test] + fn string_preserves_embedded_quotes() { + // SEA wire-level escaping is the server's job; the codec must + // not transform a string with an embedded single quote. + match parse_typed_value("STRING", Some("test'quote")).unwrap() { + TypedValue::String(s) => assert_eq!(s, "test'quote"), + other => panic!("expected String, got {other:?}"), + } + } + + #[test] + fn date_parses_iso() { + let v = parse_typed_value("DATE", Some("2026-05-15")).unwrap(); + match v { + TypedValue::Date(d) => { + assert_eq!(d, NaiveDate::from_ymd_opt(2026, 5, 15).unwrap()) + } + other => panic!("expected Date, got {other:?}"), + } + let e = parse_typed_value("DATE", Some("not-a-date")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn timestamp_parses_naive_and_iso() { + let a = parse_typed_value("TIMESTAMP", Some("2026-05-15 12:30:45")).unwrap(); + assert!(matches!(a, TypedValue::Timestamp(_))); + let b = parse_typed_value("TIMESTAMP", Some("2026-05-15 12:30:45.123456")).unwrap(); + assert!(matches!(b, TypedValue::Timestamp(_))); + let c = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45")).unwrap(); + assert!(matches!(c, TypedValue::Timestamp(_))); + } + + #[test] + fn timestamp_accepts_trailing_z() { + // JS's `Date.prototype.toISOString()` always emits the trailing + // `Z`. Confirms the strip is in place. + let v = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45.123Z")).unwrap(); + assert!(matches!(v, TypedValue::Timestamp(_))); + let v = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45Z")).unwrap(); + assert!(matches!(v, TypedValue::Timestamp(_))); + } + + #[test] + fn decimal_extracts_precision_and_scale() { + let v = parse_typed_value("DECIMAL(10,2)", Some("-123.45")).unwrap(); + match v { + TypedValue::Decimal { + value, + precision, + scale, + } => { + assert_eq!(value, "-123.45"); + assert_eq!(precision, 10); + assert_eq!(scale, 2); + } + other => panic!("expected Decimal, got {other:?}"), + } + // Spaces between p and s. + let v = parse_typed_value("DECIMAL(8, 4)", Some("0.0001")).unwrap(); + match v { + TypedValue::Decimal { + precision, scale, .. + } => { + assert_eq!((precision, scale), (8, 4)); + } + other => panic!("expected Decimal, got {other:?}"), + } + } + + #[test] + fn decimal_without_precision_errors() { + let e = parse_typed_value("DECIMAL", Some("1.0")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn decimal_single_arg_defaults_scale_to_zero() { + match parse_typed_value("DECIMAL(38)", Some("123456789")).unwrap() { + TypedValue::Decimal { + precision, scale, .. + } => assert_eq!((precision, scale), (38, 0)), + other => panic!("expected Decimal, got {other:?}"), + } + } + + #[test] + fn decimal_rejects_bad_value_literal() { + let e = parse_typed_value("DECIMAL(10,2)", Some("not-a-number")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + assert!(e.message.contains("DECIMAL"), "{}", e.message); + } + + #[test] + fn decimal_rejects_partial_dot_forms() { + for v in ["42.", ".5", "-.5", "+.", "-", "+", "."] { + let e = parse_typed_value("DECIMAL(10,4)", Some(v)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{v:?}"); + } + } + + #[test] + fn decimal_rejects_out_of_bound_precision_and_scale() { + for ty in [ + "DECIMAL(0,0)", + "DECIMAL(39,0)", + "DECIMAL(10,11)", + "DECIMAL(10,-1)", + ] { + let e = parse_typed_value(ty, Some("1.0")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{ty}"); + } + } + + #[test] + fn binary_is_rejected() { + // BINARY is documented kernel-side as unsupported on the SEA + // wire today; the Node-side adapter must use `unhex(?)` as a + // workaround. The error message must contain "BINARY" so the + // adapter's reviver can distinguish this from an arbitrary + // bind failure. + let e = parse_typed_value("BINARY", Some("cafe")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + assert!(e.message.contains("BINARY"), "{}", e.message); + } + + #[test] + fn compound_types_are_rejected() { + for ty in ["ARRAY", "ARRAY", "MAP", "STRUCT"] { + let e = parse_typed_value(ty, Some("x")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{ty}"); + assert!(e.message.contains("compound"), "{ty}: {}", e.message); + } + } + + #[test] + fn compound_match_does_not_overreach() { + // ARRAYBUFFER / MAPLE / STRUCTURE fall through to the generic + // "unsupported parameter SQL type" message — they're not + // compound types and not real Databricks types. + for ty in ["ARRAYBUFFER", "MAPLE", "STRUCTURE"] { + let e = parse_typed_value(ty, Some("x")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{ty}"); + assert!( + e.message.contains("unsupported"), + "{ty} should fall through, got {}", + e.message + ); + } + } + + #[test] + fn lowercase_sql_type_works() { + // DBSQLParameterType.* enum uppercases, but accept lowercase + // for robustness against direct napi callers. + assert!(matches!( + parse_typed_value("int", Some("1")).unwrap(), + TypedValue::Int32(1) + )); + assert!(matches!( + parse_typed_value("decimal(5,2)", Some("1.23")).unwrap(), + TypedValue::Decimal { .. } + )); + } + + #[test] + fn unknown_type_errors() { + let e = parse_typed_value("MAGIC", Some("x")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn timestamp_ntz_maps_to_distinct_variant() { + let v = parse_typed_value("TIMESTAMP_NTZ", Some("2026-05-15 12:30:45")).unwrap(); + assert!(matches!(v, TypedValue::TimestampNtz(_))); + } + + #[test] + fn timestamp_ltz_parses_naive_offset_and_z_forms() { + let v = parse_typed_value("TIMESTAMP_LTZ", Some("2026-05-15 12:30:45")).unwrap(); + let TypedValue::TimestampLtz(dt) = v else { + panic!("expected TimestampLtz"); + }; + assert_eq!( + dt.format("%Y-%m-%dT%H:%M:%SZ").to_string(), + "2026-05-15T12:30:45Z" + ); + let v = parse_typed_value("TIMESTAMP_LTZ", Some("2026-05-15T18:00:00+05:30")).unwrap(); + let TypedValue::TimestampLtz(dt) = v else { + panic!("expected TimestampLtz"); + }; + assert_eq!(dt.format("%H:%M").to_string(), "12:30"); + } + + #[test] + fn variant_passes_json_text_through() { + let json = r#"{"k":1,"nested":{"a":[true,null]}}"#; + match parse_typed_value("VARIANT", Some(json)).unwrap() { + TypedValue::Variant(s) => assert_eq!(s, json), + other => panic!("expected Variant, got {other:?}"), + } + } + + #[test] + fn interval_passes_through() { + match parse_typed_value("INTERVAL", Some("INTERVAL '1' DAY")).unwrap() { + TypedValue::Interval(s) => assert_eq!(s, "INTERVAL '1' DAY"), + other => panic!("expected Interval, got {other:?}"), + } + } + + // ─── 10-type matrix coverage check ────────────────────────────── + // + // The C5 cluster's headline contract is that all 10 basic types + // surface via this codec. This test exercises each one with a + // representative value that mirrors what the Node adapter will + // send today. + + #[test] + fn c5_ten_type_matrix_round_trips() { + // (sql_type, value_str, predicate-on-the-decoded-TypedValue) + // BINARY is intentionally NOT in the round-trip list — see + // binary_is_rejected above for the documented contract. + type MatrixCase = (&'static str, &'static str, fn(&TypedValue) -> bool); + let cases: &[MatrixCase] = &[ + ("INT", "42", |v| matches!(v, TypedValue::Int32(42))), + ("BIGINT", "9999999999", |v| { + matches!(v, TypedValue::Int64(9999999999)) + }), + ("FLOAT", "3.14", |v| matches!(v, TypedValue::Float32(_))), + ("DOUBLE", "2.718281828459045", |v| { + matches!(v, TypedValue::Float64(_)) + }), + ( + "STRING", + "hello world", + |v| matches!(v, TypedValue::String(s) if s == "hello world"), + ), + ("BOOLEAN", "true", |v| matches!(v, TypedValue::Bool(true))), + ("DATE", "2026-05-15", |v| matches!(v, TypedValue::Date(_))), + ("TIMESTAMP", "2026-05-15 12:30:45", |v| { + matches!(v, TypedValue::Timestamp(_)) + }), + ("DECIMAL(10,2)", "-123.45", |v| { + matches!( + v, + TypedValue::Decimal { + precision: 10, + scale: 2, + .. + } + ) + }), + ]; + for (sql_type, value, pred) in cases { + let got = parse_typed_value(sql_type, Some(value)) + .unwrap_or_else(|e| panic!("{sql_type} {value:?} should parse: {e:?}")); + assert!( + pred(&got), + "{sql_type} {value:?} decoded to unexpected variant: {got:?}" + ); + } + // BINARY — pin the contract: bind-time InvalidArgument. + let e = parse_typed_value("BINARY", Some("cafe")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } +} From 092ba92a89ac206c9f0f5d07d6557858a7f7ff2b Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 31 May 2026 00:55:51 +0000 Subject: [PATCH 22/28] feat(statement,napi): surface row_limit + per-statement query timeout on StatementSpec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the SEA↔Thrift parity rows 2.15 (row_limit) and 2.17 (server statement timeout) from the cross-driver feature matrix. Both are exercised by Python `use_sea` (row_limit=, wait_timeout=) but were not reachable through the kernel's public StatementSpec, so NodeJS SEA and Python use_kernel could not offer them. - StatementSpec gains `row_limit: Option` and `query_timeout_secs: Option` with fluent setters. The SEA wire request already carried `row_limit` / `wait_timeout` / `on_wait_timeout` (types::sea::ExecuteParams); this only surfaces them on the public spec and threads them through `prepare_for_dispatch` — no new wire surface. - Server statement timeout maps to SEA `wait_timeout` with `on_wait_timeout = CANCEL` so the statement is cancelled on elapse (JDBC setQueryTimeout / Python use_sea wait_timeout semantics), distinct from the connection-level transport `overall_timeout`. The wait-timeout precedence (async-submit "0s" respected verbatim vs sync-execute honoring the spec timeout vs server default) is extracted into the pure `resolve_wait_timeout` helper and unit-tested. - napi `ExecuteOptions` exposes `rowLimit` + `queryTimeoutSecs`, threaded onto the spec; the scalars are read before `options` is consumed by the query-tags merge. Validation: cargo fmt + clippy clean; new unit tests cover the spec setters, the wait-timeout precedence (3 cases), and the unchanged query-tags merge. The SEA server clamps wait_timeout at 50s; the kernel forwards the requested value verbatim. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 44 +++++++++++++++++++++++--- src/statement/mutable.rs | 68 ++++++++++++++++++++++++++++++++++++---- src/statement/spec.rs | 49 +++++++++++++++++++++++++++++ 3 files changed, 151 insertions(+), 10 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 4a20f490..c5c9de52 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -51,10 +51,11 @@ use crate::util::guarded; /// produces (`lib/utils/queryTags.ts`). Backslashes in keys are /// doubled; backslash/colon/comma in values are backslash-escaped. /// -/// Positional parameters, named parameters, row limit, and wait -/// timeout are deferred: they require either a non-trivial JS↔napi -/// `TypedValue` mapping (params) or a kernel-side `StatementSpec` -/// extension (`row_limit`/`wait_timeout`). Both land in follow-on PRs. +/// `rowLimit` (SEA `row_limit`) and `queryTimeoutSecs` (the per-statement +/// server wait timeout) are exposed here and threaded onto the kernel +/// `StatementSpec`. Positional and named parameters remain deferred: they +/// require a non-trivial JS↔napi `TypedValue` mapping and land in a +/// follow-on PR. /// /// **Tag-order caveat (M4 parity note).** The napi `queryTags` field /// is a Rust `HashMap` whose iteration order is @@ -90,6 +91,17 @@ pub struct ExecuteOptions { /// HashMap-iteration-order vs `Object.keys`-iteration-order /// divergence and the byte-identical-Thrift-parity workaround. pub query_tags: Option>, + /// Server-side cap on the number of rows this statement returns + /// (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + /// `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + pub row_limit: Option, + /// Per-statement server wait timeout in whole seconds. Bounds how + /// long the server waits before cancelling the statement + /// (`on_wait_timeout = CANCEL`), surfacing as a timeout — the + /// server statement timeout (JDBC `setQueryTimeout`). Maps to + /// `StatementSpec.query_timeout_secs`. Distinct from the + /// connection-level transport timeout. The SEA wire caps it at 50s. + pub query_timeout_secs: Option, } /// Closed-state error builder. Mirrors `statement::statement_closed_err` @@ -227,6 +239,10 @@ impl Connection { options: Option, ) -> napi::Result { let inner = Arc::clone(&self.inner); + // Pull the scalar knobs out before `build_merged_statement_conf` + // consumes `options` (both `i64`/`u32` are `Copy`). + let row_limit = options.as_ref().and_then(|o| o.row_limit); + let query_timeout_secs = options.as_ref().and_then(|o| o.query_timeout_secs); // Merge `query_tags` into `statement_conf` at the napi boundary // so the kernel sees a single conf map. Serialise the tag // map to the comma-separated `key:value` wire shape NodeJS @@ -242,6 +258,12 @@ impl Connection { if let Some(conf) = merged_conf { stmt.spec().statement_conf(conf); } + // `None` leaves the kernel's omit-the-field default in place, + // so threading unconditionally is safe and keeps the spec the + // single source of truth. + stmt.spec() + .row_limit(row_limit) + .query_timeout_secs(query_timeout_secs); let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. @@ -375,6 +397,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: Some(HashMap::new()), query_tags: Some(HashMap::new()), + row_limit: None, + query_timeout_secs: None, })) .unwrap(); assert!(result.is_none(), "empty maps → no statement_conf"); @@ -387,6 +411,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: Some(conf), query_tags: None, + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); @@ -400,6 +426,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: None, query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); @@ -417,6 +445,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: None, query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); @@ -433,6 +463,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: None, query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); @@ -451,6 +483,8 @@ mod tests { let err = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: Some(conf), query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, })) .expect_err("must reject when both are set"); assert!( @@ -472,6 +506,8 @@ mod tests { let result = build_merged_statement_conf(Some(ExecuteOptions { statement_conf: Some(conf), query_tags: Some(HashMap::new()), + row_limit: None, + query_timeout_secs: None, })) .unwrap() .unwrap(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index cb48b5c6..a6fe47f6 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -66,6 +66,31 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tracing::{warn, Instrument}; +/// Resolve the SEA `(wait_timeout, on_wait_timeout)` pair for an execute / +/// submit dispatch. Pure so the precedence rules are unit-testable without +/// a live `Session`. +/// +/// - `caller_wait_secs = Some(s)` — the caller pinned the wait shape +/// (e.g. `submit` passes `"0s"` for async). Respected verbatim with +/// `CONTINUE`; overriding it would make async submit block. +/// - `caller_wait_secs = None` — the sync `execute` path. A per-statement +/// `spec_query_timeout_secs` then bounds the server wait and `CANCEL`s +/// the statement on elapse (JDBC `setQueryTimeout` / Python `use_sea`'s +/// `wait_timeout` semantics). With no spec timeout, both are omitted so +/// the server applies its default (~10s wait + auto-close on success). +fn resolve_wait_timeout( + caller_wait_secs: Option<&str>, + spec_query_timeout_secs: Option, +) -> (Option, Option) { + match caller_wait_secs { + Some(s) => (Some(s.to_string()), Some("CONTINUE".to_string())), + None => match spec_query_timeout_secs { + Some(secs) => (Some(format!("{secs}s")), Some("CANCEL".to_string())), + None => (None, None), + }, + } +} + /// Lifecycle owner for a single statement spec. /// /// Mutable, reusable. Mutate the spec in place via [`Statement::spec`], @@ -300,13 +325,12 @@ impl Statement { if self.spec.result_format != ResultFormat::Arrow { return Err(Error::invalid_argument().message("v0 supports ResultFormat::Arrow only")); } - // `wait_timeout = None` means "omit the field"; the server - // applies its default (~10s wait + auto-close on success). - // `on_wait_timeout` only matters when wait_timeout is set, - // so mirror the presence. + let (wait_timeout, on_wait_timeout) = + resolve_wait_timeout(wait_timeout_secs, self.spec.query_timeout_secs); let mut exec_params = ExecuteParams { - wait_timeout: wait_timeout_secs.map(|s| s.to_string()), - on_wait_timeout: wait_timeout_secs.map(|_| "CONTINUE".to_string()), + wait_timeout, + on_wait_timeout, + row_limit: self.spec.row_limit, ..ExecuteParams::default() }; for (i, value) in self.spec.positional_params.iter().enumerate() { @@ -456,3 +480,35 @@ impl Drop for Statement { // remaining cleanup obligation here. } } + +#[cfg(test)] +mod tests { + use super::resolve_wait_timeout; + + #[test] + fn async_submit_caller_value_is_respected_verbatim() { + // submit() pins "0s" for async; never overridden, even if a spec + // query_timeout is set (overriding would make submit block). + let (wait, on_wait) = resolve_wait_timeout(Some("0s"), Some(30)); + assert_eq!(wait.as_deref(), Some("0s")); + assert_eq!(on_wait.as_deref(), Some("CONTINUE")); + } + + #[test] + fn sync_with_query_timeout_cancels_on_elapse() { + // execute() passes None; a spec query_timeout bounds the wait and + // CANCELs the statement on elapse (server statement-timeout). + let (wait, on_wait) = resolve_wait_timeout(None, Some(30)); + assert_eq!(wait.as_deref(), Some("30s")); + assert_eq!(on_wait.as_deref(), Some("CANCEL")); + } + + #[test] + fn sync_without_query_timeout_omits_field() { + // No caller pin and no spec timeout: omit both so the server uses + // its default (~10s wait + auto-close on success). + let (wait, on_wait) = resolve_wait_timeout(None, None); + assert_eq!(wait, None); + assert_eq!(on_wait, None); + } +} diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 656467d3..e4d708a4 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -139,6 +139,25 @@ pub struct StatementSpec { /// `session_conf` at execute time; this map wins on key collisions. pub statement_conf: HashMap, + /// Server-side cap on the number of rows returned by this statement, + /// independent of SQL `LIMIT`. Maps directly to the SEA + /// `ExecuteStatement.row_limit` wire field (Python `use_sea`'s + /// `row_limit=` kwarg is the canonical cross-driver surface). `None` + /// omits the field, so the server applies no driver-imposed cap. + pub row_limit: Option, + + /// Server-side statement wait timeout, in whole seconds. Bounds how + /// long the server waits for the statement to reach a terminal state + /// before the wait elapses; on elapse the statement is cancelled + /// (`on_wait_timeout = CANCEL`), surfacing as a timeout to the caller. + /// This is the per-statement server timeout (JDBC `setQueryTimeout` / + /// Python `use_sea`'s `wait_timeout=`), distinct from the transport + /// `overall_timeout`. `None` lets the kernel pick its sync/async + /// default (see `Statement::execute` / `submit`). The SEA wire caps + /// the value at 50s; the kernel forwards the requested value verbatim + /// and lets the server clamp. + pub query_timeout_secs: Option, + /// Result wire format. pub result_format: ResultFormat, } @@ -206,6 +225,20 @@ impl StatementSpec { self } + /// Set the server-side row cap (SEA `row_limit`). `None` clears it. + pub fn row_limit(&mut self, row_limit: Option) -> &mut Self { + self.row_limit = row_limit; + self + } + + /// Set the per-statement server wait timeout in whole seconds. `None` + /// clears it (kernel default applies). See the field docs for the + /// `CANCEL`-on-elapse semantics and the 50s server cap. + pub fn query_timeout_secs(&mut self, secs: Option) -> &mut Self { + self.query_timeout_secs = secs; + self + } + /// Set the result wire format. pub fn result_format(&mut self, fmt: ResultFormat) -> &mut Self { self.result_format = fmt; @@ -224,9 +257,25 @@ mod tests { assert!(s.positional_params.is_empty()); assert!(s.named_params.is_empty()); assert!(s.statement_conf.is_empty()); + // row_limit / query_timeout default to "omit the field" so the + // server applies no driver-imposed cap and its own wait default. + assert!(s.row_limit.is_none()); + assert!(s.query_timeout_secs.is_none()); assert_eq!(s.result_format, ResultFormat::Arrow); } + #[test] + fn row_limit_and_query_timeout_setters() { + let mut s = StatementSpec::new(); + s.row_limit(Some(100)).query_timeout_secs(Some(30)); + assert_eq!(s.row_limit, Some(100)); + assert_eq!(s.query_timeout_secs, Some(30)); + // `None` clears back to the omit-the-field default. + s.row_limit(None).query_timeout_secs(None); + assert!(s.row_limit.is_none()); + assert!(s.query_timeout_secs.is_none()); + } + #[test] fn fluent_setters_compose() -> Result<()> { let mut s = StatementSpec::new(); From c65966b978637b922f967ea19cf765d9caa1ff00 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 31 May 2026 10:45:02 +0000 Subject: [PATCH 23/28] fix(reader): clamp inline result to manifest.total_row_count MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With a row_limit applied, the SEA server returns one extra look-ahead Arrow row beyond the logical result size and marks the manifest `truncated = true` with `total_row_count = N` (the requested limit). The inline reader decoded the raw Arrow stream verbatim, so `row_limit = N` surfaced N+1 rows — verified live (limit 10 → 11 rows, ids 0..10; limit 5 → 6) and against the SEA response manifest, which reports `total_row_count = 10, truncated = true` for a limit of 10. The manifest count — not the raw Arrow row count — is the authoritative result size. `InlineArrowProvider::new` now takes the manifest's `total_row_count` and clamps the decoded batches to it (slicing the batch that crosses the boundary), mirroring the Python SEA connector, which bounds its `ArrowQueue` by `total_row_count`. This makes `row_limit` return exactly N rows — parity with Python use_sea and Thrift. `None` (count absent) leaves batches unclamped; an above-actual count is a no-op. The clamp arithmetic is a pure, unit-tested helper. Verified live: row_limit 10 → 10 rows, 5 → 5 rows; non-limited queries unchanged. New unit tests cover None-passthrough, cross-batch slicing, above-actual no-op, and the N+1 look-ahead clamp. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- src/reader/inline/provider.rs | 107 +++++++++++++++++++++++++++++++--- src/reader/mod.rs | 16 +++-- 2 files changed, 112 insertions(+), 11 deletions(-) diff --git a/src/reader/inline/provider.rs b/src/reader/inline/provider.rs index 5a135dcf..4449a290 100644 --- a/src/reader/inline/provider.rs +++ b/src/reader/inline/provider.rs @@ -38,6 +38,37 @@ pub struct InlineArrowProvider { schema: Option, } +/// Clamp a sequence of record batches to an authoritative logical row +/// count (`manifest.total_row_count`), slicing the batch that crosses the +/// boundary and dropping any rows past it. `None` (or a negative count) +/// leaves the batches untouched. Pure so the boundary arithmetic is +/// unit-testable. See [`InlineArrowProvider::new`] for why the manifest +/// count, not the raw Arrow row count, is authoritative. +fn clamp_to_total_rows( + batches: Vec, + total_row_count: Option, +) -> Vec { + let Some(limit) = total_row_count.filter(|n| *n >= 0).map(|n| n as usize) else { + return batches; + }; + let mut out = Vec::with_capacity(batches.len()); + let mut remaining = limit; + for batch in batches { + if remaining == 0 { + break; + } + if batch.num_rows() <= remaining { + remaining -= batch.num_rows(); + out.push(batch); + } else { + // This batch crosses the boundary — keep only `remaining` rows. + out.push(batch.slice(0, remaining)); + remaining = 0; + } + } + out +} + impl InlineArrowProvider { /// Create a new provider from raw Arrow IPC bytes. /// @@ -46,6 +77,14 @@ impl InlineArrowProvider { /// # Arguments /// * `attachment` - Raw Arrow IPC bytes (decoded from base64) /// * `compression` - Compression codec used (from manifest.result_compression) + /// * `total_row_count` - Authoritative logical row count from + /// `manifest.total_row_count`. When `Some`, the decoded batches are + /// clamped to this count: with a `row_limit` applied the SEA server + /// returns one extra look-ahead Arrow row beyond the logical count + /// (`manifest.truncated = true`), and the manifest count — not the + /// raw Arrow row count — is the result size. Mirrors the Python SEA + /// connector, which bounds its `ArrowQueue` by `total_row_count`. + /// `None` leaves the batches unclamped. /// /// # Returns /// A new provider with parsed batches ready for iteration @@ -53,7 +92,11 @@ impl InlineArrowProvider { /// # Errors /// - If decompression fails /// - If Arrow IPC parsing fails - pub fn new(attachment: Vec, compression: CompressionCodec) -> Result { + pub fn new( + attachment: Vec, + compression: CompressionCodec, + total_row_count: Option, + ) -> Result { if attachment.is_empty() { tracing::debug!("Empty attachment, creating empty provider"); return Ok(Self { @@ -69,10 +112,12 @@ impl InlineArrowProvider { ); // Reuse the shared Arrow IPC parser (same format as CloudFetch) - let batches = parse_arrow_ipc(&attachment, compression).map_err(|e| { + let parsed = parse_arrow_ipc(&attachment, compression).map_err(|e| { Error::io().message(format!("Failed to parse inline Arrow data: {}", e)) })?; + let batches = clamp_to_total_rows(parsed, total_row_count); + let schema = batches.first().map(|b| b.schema()); tracing::debug!( @@ -156,7 +201,8 @@ mod tests { let batch = create_test_batch(100); let ipc_data = create_test_arrow_ipc(&[batch]); - let mut provider = InlineArrowProvider::new(ipc_data, CompressionCodec::None).unwrap(); + let mut provider = + InlineArrowProvider::new(ipc_data, CompressionCodec::None, None).unwrap(); // Check schema assert!(provider.schema().is_some()); @@ -189,7 +235,7 @@ mod tests { } let mut provider = - InlineArrowProvider::new(compressed, CompressionCodec::Lz4Frame).unwrap(); + InlineArrowProvider::new(compressed, CompressionCodec::Lz4Frame, None).unwrap(); let batch = provider.next_batch().unwrap().unwrap(); assert_eq!(batch.num_rows(), 100); @@ -201,7 +247,8 @@ mod tests { let batch2 = create_test_batch(30); let ipc_data = create_test_arrow_ipc(&[batch1, batch2]); - let mut provider = InlineArrowProvider::new(ipc_data, CompressionCodec::None).unwrap(); + let mut provider = + InlineArrowProvider::new(ipc_data, CompressionCodec::None, None).unwrap(); // First batch let batch = provider.next_batch().unwrap().unwrap(); @@ -217,7 +264,7 @@ mod tests { #[test] fn test_inline_provider_with_empty_data() { - let provider = InlineArrowProvider::new(vec![], CompressionCodec::None).unwrap(); + let provider = InlineArrowProvider::new(vec![], CompressionCodec::None, None).unwrap(); assert!(provider.schema().is_none()); assert!(!provider.has_more()); @@ -227,7 +274,53 @@ mod tests { fn test_inline_provider_with_invalid_data() { let invalid_data = b"this is not valid arrow ipc data".to_vec(); - let result = InlineArrowProvider::new(invalid_data, CompressionCodec::None); + let result = InlineArrowProvider::new(invalid_data, CompressionCodec::None, None); assert!(result.is_err()); } + + #[test] + fn clamp_none_is_passthrough() { + let batches = vec![create_test_batch(10)]; + let out = clamp_to_total_rows(batches, None); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 10); + } + + #[test] + fn clamp_slices_across_batches() { + // 4 + 4 + 4 = 12 rows; clamp to 10 -> 4 + 4 + 2. + let batches = vec![ + create_test_batch(4), + create_test_batch(4), + create_test_batch(4), + ]; + let out = clamp_to_total_rows(batches, Some(10)); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 10); + assert_eq!(out.len(), 3); + assert_eq!(out[2].num_rows(), 2); + } + + #[test] + fn clamp_above_actual_is_noop() { + let batches = vec![create_test_batch(5)]; + let out = clamp_to_total_rows(batches, Some(1000)); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 5); + } + + #[test] + fn inline_provider_clamps_look_ahead_row_to_manifest_count() { + // Reproduces the row_limit=N -> N+1 server look-ahead: an 11-row + // Arrow attachment with manifest.total_row_count = 10 must surface + // exactly 10 rows (parity with Python use_sea and Thrift). + let batch = create_test_batch(11); + let ipc = create_test_arrow_ipc(&[batch]); + let mut provider = InlineArrowProvider::new(ipc, CompressionCodec::None, Some(10)).unwrap(); + let mut total = 0; + while let Some(b) = provider.next_batch().unwrap() { + total += b.num_rows(); + } + assert_eq!( + total, 10, + "must clamp the +1 look-ahead row to the manifest count" + ); + } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 607cefd6..7fd4dc64 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -177,7 +177,12 @@ impl ResultReaderFactory { inline_data.len() ); - return self.create_inline_reader(inline_data, compression); + // Pass the manifest's authoritative row count so the + // inline provider clamps off any look-ahead row the SEA + // server appends when a row_limit truncates the result. + let total_row_count = + response.manifest.as_ref().and_then(|m| m.total_row_count); + return self.create_inline_reader(inline_data, compression, total_row_count); } } @@ -304,14 +309,17 @@ impl ResultReaderFactory { &self, inline_data: &[u8], compression: CompressionCodec, + total_row_count: Option, ) -> Result> { tracing::debug!( - "Creating inline Arrow reader: {} bytes, compression={:?}", + "Creating inline Arrow reader: {} bytes, compression={:?}, total_row_count={:?}", inline_data.len(), - compression + compression, + total_row_count ); - let provider = InlineArrowProvider::new(inline_data.to_vec(), compression)?; + let provider = + InlineArrowProvider::new(inline_data.to_vec(), compression, total_row_count)?; Ok(Box::new(InlineArrowReader::new(provider))) } From f34cc9d649b565218848d3f221f3c49ee773133d Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 31 May 2026 06:54:54 +0000 Subject: [PATCH 24/28] feat(napi): expose kernel OAuth (M2M + U2M) on openSession ConnectionOptions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The kernel implements OAuth M2M (client-credentials) and U2M (auth-code + PKCE) in `AuthConfig::OAuthM2M` / `OAuthU2M`, but the napi binding only wired `AuthConfig::Pat` — so NodeJS SEA (and pyo3, which has the same gap) could not offer OAuth even though the kernel fully supports it. This surfaces it on the binding. - New `#[napi(string_enum)] AuthMode { Pat, OAuthM2m, OAuthU2m }` whose string values (`'Pat'` / `'OAuthM2m'` / `'OAuthU2m'`) match what the NodeJS SEA adapter (`SeaAuth`) already expects verbatim. - `ConnectionOptions` gains `authMode` (default Pat — back-compat for existing PAT callers that pass only `token`), `oauthClientId`, `oauthClientSecret`, `oauthRedirectPort`, `oauthScopes`. `token` is now optional (required only for Pat). - `build_auth_config` maps the JS options onto the kernel `AuthConfig`, enforcing per-mode required fields at the binding boundary (fail-fast `InvalidArgument` before any network) so the kernel always receives a fully-formed variant. Pure + unit-tested. OAuth `Federation` / `External` are intentionally not exposed (kernel marks federation unimplemented; External is a Rust-trait escape hatch with no JS-callback bridge). Validation: cargo fmt + clippy clean; 4 new unit tests (Pat default + empty-token reject, M2M required-field validation, U2M all-optional with override threading); 41 napi unit tests green. Live: OAuth M2M client-credentials grant against pecotesting authenticated successfully (server then applied warehouse-level authorization); PAT continues to work both with an explicit `authMode: Pat` and with `authMode` omitted. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/database.rs | 210 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 199 insertions(+), 11 deletions(-) diff --git a/napi/src/database.rs b/napi/src/database.rs index d2b8fac4..ede8b051 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -28,7 +28,7 @@ use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::{AuthConfig, DefaultOpts, HttpConfig, Session}; +use databricks_sql_kernel::{AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, Session}; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. /// @@ -49,8 +49,35 @@ use crate::error::napi_err_from_kernel; use crate::runtime; use crate::util::guarded; -/// JS-visible options for opening a Databricks SQL session over PAT. -/// `token` is required. +/// Authentication mode selector crossing the napi boundary. The string +/// literals are what napi-rs emits from this `#[napi(string_enum)]` — the +/// NodeJS SEA adapter (`SeaAuth`) matches them verbatim (`'Pat'`, +/// `'OAuthM2m'`, `'OAuthU2m'`). +/// +/// Mirrors the kernel [`AuthConfig`] variants this binding supports. +/// `OAuthFederation` / `External` are intentionally not exposed yet — the +/// kernel marks federation as not-yet-implemented and `External` is a +/// Rust-trait escape hatch with no JS-callback bridge. +#[napi(string_enum)] +#[derive(Default)] +pub enum AuthMode { + /// Personal access token (`token`). + #[default] + Pat, + /// OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. + OAuthM2m, + /// OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` + /// + `oauthRedirectPort`. + OAuthU2m, +} + +/// JS-visible options for opening a Databricks SQL session. +/// +/// Authentication is selected by `authMode` (default [`AuthMode::Pat`]): +/// - `Pat` — `token` required. +/// - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. +/// - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional (kernel +/// defaults to the `databricks-cli` client on port 8020). /// /// Catalog / schema / sessionConf are applied once at session creation /// and remain in effect for every statement run on the resulting @@ -69,9 +96,23 @@ pub struct ConnectionOptions { /// JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The /// kernel parses out the warehouse id. pub http_path: String, - /// Personal access token. Must be non-empty (the kernel rejects - /// empty PATs at session construction). - pub token: String, + /// Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: + /// existing PAT callers pass only `token`). + pub auth_mode: Option, + /// Personal access token. Required (and non-empty) for + /// [`AuthMode::Pat`]; ignored otherwise. + pub token: Option, + /// OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for + /// [`AuthMode::OAuthU2m`] (kernel defaults to `databricks-cli`). + pub oauth_client_id: Option, + /// OAuth client secret. Required for [`AuthMode::OAuthM2m`]. + pub oauth_client_secret: Option, + /// Localhost callback port for the [`AuthMode::OAuthU2m`] browser + /// flow. Omitted ⇒ kernel default (8020). + pub oauth_redirect_port: Option, + /// OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults + /// (`["all-apis"]` for M2M; `["all-apis", "offline_access"]` for U2M). + pub oauth_scopes: Option>, /// Default catalog for statements executed on this session. /// Routed through the kernel's `DefaultOpts` and onto the SEA /// `CreateSession.catalog` wire field. @@ -107,8 +148,53 @@ pub struct ConnectionOptions { pub max_connections: Option, } -/// Open a Databricks SQL session over PAT auth and return an opaque -/// `Connection` wrapping the kernel `Session`. +/// Require a non-empty `Option` field for a given auth mode, +/// returning a typed `InvalidArgument` naming the JS field otherwise. +fn require_field(value: &Option, js_name: &str, mode: &str) -> napi::Result { + value.clone().filter(|s| !s.is_empty()).ok_or_else(|| { + napi_err_from_kernel( + KernelError::invalid_argument() + .message(format!("authMode {mode} requires a non-empty `{js_name}`")), + ) + }) +} + +/// Map the JS `ConnectionOptions` auth fields onto the kernel +/// [`AuthConfig`]. Per-mode required-field validation lives here at the +/// binding boundary so the kernel always receives a fully-formed variant. +/// Pure (borrows `options`) so it is unit-testable without opening a +/// session. +fn build_auth_config(options: &ConnectionOptions) -> napi::Result { + match options.auth_mode.unwrap_or_default() { + AuthMode::Pat => Ok(AuthConfig::Pat { + token: require_field(&options.token, "token", "Pat")?, + }), + AuthMode::OAuthM2m => Ok(AuthConfig::OAuthM2M { + client_id: require_field(&options.oauth_client_id, "oauthClientId", "OAuthM2m")?, + client_secret: require_field( + &options.oauth_client_secret, + "oauthClientSecret", + "OAuthM2m", + )?, + scopes: options.oauth_scopes.clone(), + token_url_override: None, + }), + AuthMode::OAuthU2m => Ok(AuthConfig::OAuthU2M { + // All U2M fields are optional — the kernel fills `databricks-cli` + // / port 8020 / default scopes when omitted. + client_id: options.oauth_client_id.clone(), + redirect_port: options.oauth_redirect_port, + scopes: options.oauth_scopes.clone(), + token_url_override: None, + callback_timeout: None, + }), + } +} + +/// Open a Databricks SQL session and return an opaque `Connection` +/// wrapping the kernel `Session`. Authentication is selected by +/// `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see +/// [`build_auth_config`]. /// /// The JS-visible name is `openSession` (napi-rs converts snake_case /// to camelCase for free functions). @@ -125,6 +211,10 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result napi::Result napi::Result ConnectionOptions { + ConnectionOptions { + host_name: "adb-1.azuredatabricks.net".to_owned(), + http_path: "/sql/1.0/warehouses/abc".to_owned(), + auth_mode: None, + token: None, + oauth_client_id: None, + oauth_client_secret: None, + oauth_redirect_port: None, + oauth_scopes: None, + catalog: None, + schema: None, + session_conf: None, + max_connections: None, + } + } + + #[test] + fn default_mode_is_pat_and_requires_token() { + let mut o = base(); + // No authMode + no token → fail-fast InvalidArgument. + assert!(build_auth_config(&o).is_err()); + o.token = Some("dapi-xxx".to_owned()); + assert!(matches!( + build_auth_config(&o).unwrap(), + AuthConfig::Pat { .. } + )); + } + + #[test] + fn pat_rejects_empty_token() { + let mut o = base(); + o.auth_mode = Some(AuthMode::Pat); + o.token = Some(String::new()); + assert!(build_auth_config(&o).is_err()); + } + + #[test] + fn m2m_requires_client_id_and_secret() { + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthM2m); + assert!(build_auth_config(&o).is_err(), "missing both"); + o.oauth_client_id = Some("cid".to_owned()); + assert!(build_auth_config(&o).is_err(), "missing secret"); + o.oauth_client_secret = Some("sec".to_owned()); + o.oauth_scopes = Some(vec!["all-apis".to_owned()]); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthM2M { + client_id, + client_secret, + scopes, + .. + } => { + assert_eq!(client_id, "cid"); + assert_eq!(client_secret, "sec"); + assert_eq!(scopes, Some(vec!["all-apis".to_owned()])); + } + other => panic!("expected OAuthM2M, got {other:?}"), + } + } + + #[test] + fn u2m_fields_are_all_optional() { + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthU2m); + // Bare U2M: kernel fills databricks-cli / port 8020 / default scopes. + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { + client_id, + redirect_port, + .. + } => { + assert!(client_id.is_none()); + assert!(redirect_port.is_none()); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + // Explicit overrides thread through. + o.oauth_client_id = Some("custom-cli".to_owned()); + o.oauth_redirect_port = Some(9000); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { + client_id, + redirect_port, + .. + } => { + assert_eq!(client_id.as_deref(), Some("custom-cli")); + assert_eq!(redirect_port, Some(9000)); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } +} From a5dede849d6cc79921fb874cde95145d9f156b7d Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 31 May 2026 11:43:45 +0000 Subject: [PATCH 25/28] =?UTF-8?q?merge:=20combined=20kernel=20(metadata=20?= =?UTF-8?q?+=20OAuth=20+=20row=5Flimit/query=5Ftimeout=20+=20clamp)=20?= =?UTF-8?q?=E2=80=94=20local=20integration=20branch=20for=20the=20node=20S?= =?UTF-8?q?EA=20comparator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- napi/src/statement.rs | 144 +++++++++++++++++++++++++++++++----------- 1 file changed, 106 insertions(+), 38 deletions(-) diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 2377addc..38c614d7 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -36,7 +36,7 @@ use tokio::sync::Mutex; use arrow_ipc::writer::StreamWriter; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ - Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, + Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, ResultStream, Statement as KernelStatement, }; @@ -70,6 +70,30 @@ struct StatementInner { executed: ExecutedStatement, } +/// Discriminated inner state for `Statement`. +enum AnyInner { + /// Produced by `Connection::execute_statement`. Boxed to keep the + /// enum size close to the `Metadata` variant (StatementInner is + /// large; ResultStream is much smaller). + Executed(Box), + /// Produced by metadata methods — wraps a bare `ResultStream`. + Metadata(ResultStream), +} + +impl AnyInner { + /// Borrow the underlying result stream regardless of variant. The + /// executed-statement variant delegates to its + /// `ExecutedStatement::result_stream_mut`; the metadata variant + /// returns the bare `ResultStream` directly. Used by + /// `fetch_next_batch` to share one streaming path across both. + fn result_stream_mut(&mut self) -> &mut ResultStream { + match self { + AnyInner::Executed(s) => s.executed.result_stream_mut(), + AnyInner::Metadata(rs) => rs, + } + } +} + /// Opaque executed-statement handle. /// /// **Current concurrency shape** — every method takes `inner.lock()` @@ -88,21 +112,31 @@ struct StatementInner { /// disposed statement can still read them. #[napi] pub struct Statement { - /// Wraps the kernel `Statement` + `ExecutedStatement` pair so the - /// parent's `Drop` doesn't fire (and invalidate the executed - /// handle via the shared `ValidityFlag`) while JS still holds - /// this wrapper. See `StatementInner` docs above. - inner: Arc>>, + /// Discriminated inner state: the `Executed` variant wraps the + /// kernel `Statement` + `ExecutedStatement` pair (the parent kept + /// alive to prevent its `Drop` from invalidating the executed + /// handle via the shared `ValidityFlag`); the `Metadata` variant + /// wraps a bare `ResultStream` produced by `Metadata::list_*` / + /// `primary_keys` / `foreign_keys` / `type_info` / `table_types`. + inner: Arc>>, /// Schema captured at construction. Available even after `close()`. + /// For the `Executed` variant this is the executed handle's + /// schema; for the `Metadata` variant it's the result-stream's + /// schema. Either way, cached so JS callers can build error + /// reports against a disposed statement. schema: SchemaRef, - /// Server-issued id. Available even after `close()` for log - /// correlation. + /// Server-issued statement id. Populated for the `Executed` + /// variant; empty string for the `Metadata` variant (the kernel + /// does not emit a statement id for SHOW/information_schema + /// queries driven through `Metadata`). statement_id: String, /// Set to `true` when `fetchNextBatch` observes the natural end of /// the stream (`None`). `cancel()` short-circuits to `Ok(())` when /// this is set, matching the JDBC `Statement.cancel()` no-op-after- /// completion contract — without it, a defensive cancel after the /// stream is drained surfaces an opaque server-side error. + /// (Irrelevant for the `Metadata` variant where cancel is already + /// a no-op kernel-side; harmless to carry the field regardless.) finished: Arc, } @@ -119,15 +153,37 @@ impl Statement { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); Self { - inner: Arc::new(Mutex::new(Some(StatementInner { - _parent: parent, - executed, - }))), + inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( + StatementInner { + _parent: parent, + executed, + }, + ))))), schema, statement_id, finished: Arc::new(AtomicBool::new(false)), } } + + /// Crate-internal constructor for metadata calls. Wraps a bare + /// `ResultStream` returned by `Metadata::list_*` / `primary_keys` / + /// `foreign_keys` / `type_info` / `table_types`. Cancel is a no-op + /// for metadata streams (the kernel has no in-flight cancellation + /// surface for them); close just drops the stream. + /// + /// `schema` is captured from the stream so the `schema()` getter + /// works after close. `statement_id` is empty (kernel does not + /// emit one for metadata queries). `finished` defaults false and + /// is unread on this path (cancel is already a no-op). + pub(crate) fn from_result_stream(stream: ResultStream) -> Self { + let schema = stream.schema(); + Self { + inner: Arc::new(Mutex::new(Some(AnyInner::Metadata(stream)))), + schema, + statement_id: String::new(), + finished: Arc::new(AtomicBool::new(false)), + } + } } #[napi] @@ -157,9 +213,14 @@ impl Statement { guarded(async move { let mut guard = inner.lock().await; let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?; - let executed = &mut inner_state.executed; - - let stream = executed.result_stream_mut(); + // `result_stream_mut` returns `&mut ResultStream` for both + // variants — the executed-path borrows from its + // `ExecutedStatement`, the metadata-path borrows from its + // bare `ResultStream`. The IPC schema header serialised + // into every batch payload comes from the cached + // `self.schema` captured outside the lock (see method + // start), so no need to re-fetch from the stream. + let stream = inner_state.result_stream_mut(); let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; let Some(batch) = maybe_batch else { // End of stream — record so a defensive cancel after @@ -225,11 +286,15 @@ impl Statement { /// Server-side cancel. /// - /// Short-circuits to `Ok(())` if `fetchNextBatch` has already - /// returned `null` (stream naturally exhausted) — matches the - /// JDBC `Statement.cancel()` no-op-after-completion contract, so - /// JS callers can fire cancel defensively without distinguishing - /// "real cancel" from "raced with natural completion." + /// For executed statements: short-circuits to `Ok(())` if + /// `fetchNextBatch` has already returned `null` (stream + /// naturally exhausted) — matches the JDBC `Statement.cancel()` + /// no-op-after-completion contract, so JS callers can fire cancel + /// defensively without distinguishing "real cancel" from "raced + /// with natural completion." + /// + /// For metadata streams: no-op (the kernel has no in-flight + /// cancellation surface for metadata calls today). /// /// Returns `KernelError(InvalidStatementHandle)` if the statement /// has been explicitly `close()`d. @@ -243,17 +308,19 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - inner_state - .executed - .cancel() - .await - .map_err(napi_err_from_kernel) + match inner_state { + AnyInner::Executed(s) => s.executed.cancel().await.map_err(napi_err_from_kernel), + // Metadata streams have no server-side cancel handle. + AnyInner::Metadata(_) => Ok(()), + } }) .await } - /// Explicit close. Awaits the server-side `CloseStatement` so the - /// JS caller can observe failures (auth revoked mid-session, + /// Explicit close. + /// + /// For executed statements: awaits the server-side `CloseStatement` + /// so the JS caller can observe failures (auth revoked mid-session, /// network error, server-side error). Idempotent — a second call /// on an already-closed statement returns `Ok`. /// @@ -269,26 +336,27 @@ impl Statement { /// runtime. The JS caller can log the error but cannot drive a /// further retry. If you need retry-on-failure semantics for /// `CloseStatement`, layer them above this method. + /// + /// For metadata streams: drops the stream (no server round-trip + /// needed — metadata results have no in-flight server-side + /// resource to release). #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); guarded(async move { // Take the inner state out so `Drop` knows there's nothing - // left to clean up. The parent kernel `Statement`'s Drop - // runs here too — but only AFTER the executed handle's - // close has finished, so we still observe a clean - // server-side close result before the validity flag flips. + // left to clean up. let inner_state = { let mut guard = inner.lock().await; guard.take() }; - if let Some(inner_state) = inner_state { - inner_state - .executed - .close() - .await - .map_err(napi_err_from_kernel)?; - // _parent drops here, after close has resolved. + match inner_state { + Some(AnyInner::Executed(s)) => { + s.executed.close().await.map_err(napi_err_from_kernel)?; + // _parent drops here, after close has resolved. + } + // Metadata stream: just drop it. + Some(AnyInner::Metadata(_)) | None => {} } Ok(()) }) From 120babfab8d0b57cd2dc48760767740223c64b65 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 31 May 2026 13:38:17 +0000 Subject: [PATCH 26/28] feat(napi): expose intervalsAsString + complexTypesAsJson on openSession MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Surface the kernel's ResultConfig.intervals_as_string and complex_types_as_json knobs on the napi ConnectionOptions, threaded onto the SessionBuilder via `builder.result(ResultConfig)` (mirrors the pyo3 Session.__new__ surface). Omitted ⇒ kernel default (native Arrow month_interval / duration[us] and native nested types). Motivation: the NodeJS Thrift driver surfaces INTERVAL columns as strings, so the SEA driver needs intervals_as_string=true for byte-compatible result parity (verified via the node comparator — interval columns then match Thrift in both type code and value). complex_types_as_json is exposed alongside for completeness; the SEA driver leaves it at the native-Arrow default (which already decodes identically to Thrift). Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/database.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/napi/src/database.rs b/napi/src/database.rs index ede8b051..02135172 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -28,7 +28,9 @@ use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::{AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, Session}; +use databricks_sql_kernel::{ + AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ResultConfig, Session, +}; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. /// @@ -146,6 +148,19 @@ pub struct ConnectionOptions { /// Napi-rs serialises `u32` as JS `number`; values up to /// `2^32 - 1` round-trip safely (any reasonable pool size fits). pub max_connections: Option, + /// Render `INTERVAL` / `DURATION` result columns as strings + /// (`ResultConfig.intervals_as_string`). The kernel default is + /// native Arrow `month_interval` / `duration[us]` types; the NodeJS + /// Thrift driver surfaces intervals as strings, so the SEA driver + /// sets this `true` for byte-compatible parity. Omitted ⇒ kernel + /// default (native Arrow interval types). + pub intervals_as_string: Option, + /// Render complex (`ARRAY` / `MAP` / `STRUCT` / `VARIANT`) result + /// columns as JSON strings (`ResultConfig.complex_types_as_json`) + /// instead of native Arrow nested types. Omitted ⇒ kernel default + /// (native Arrow nested types, which the NodeJS Arrow decoder + /// already renders identically to the Thrift path). + pub complex_types_as_json: Option, } /// Require a non-empty `Option` field for a given auth mode, @@ -238,6 +253,19 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result Date: Sun, 31 May 2026 15:42:50 +0000 Subject: [PATCH 27/28] feat(napi): expose named query parameters (param_named) on ExecuteOptions Adds namedParams (Array<{name, sqlType, value?}>) alongside positionalParams, decoded via the same parse_typed_value codec and bound with StatementSpec::param_named. Named is the SEA-spec-required public param form. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 61 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index f912f10b..676a1d96 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -54,8 +54,8 @@ use crate::util::guarded; /// /// `rowLimit` (SEA `row_limit`) and `queryTimeoutSecs` (the per-statement /// server wait timeout) are exposed here and threaded onto the kernel -/// `StatementSpec`. `positionalParams` carries `?`-placeholder bindings -/// (decoded via `params::parse_typed_value`); named params remain deferred. +/// `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) +/// carry bound query parameters, decoded via `params::parse_typed_value`. /// /// **Tag-order caveat (M4 parity note).** The napi `queryTags` field /// is a Rust `HashMap` whose iteration order is @@ -108,6 +108,28 @@ pub struct ExecuteOptions { /// string-encoded literal or `null` for SQL NULL. Mirrors /// `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. pub positional_params: Option>, + /// Named parameters (`:name` placeholders). Each carries its `name` + /// alongside the `{ sqlType, value? }` pair. Mapped to a kernel + /// `TypedValue` via the same [`parse_typed_value`] codec and bound with + /// `StatementSpec::param_named`. Named is the SEA-spec-required public + /// param form (`StatementParameter.name` is `openapi_required`); + /// positional is the documented-undocumented variant. The two are + /// mutually exclusive at the SQL level (`?` vs `:name`). + pub named_params: Option>, +} + +/// A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a +/// distinct napi object (rather than an optional `name` on `TypedValueInput`) +/// so the positional surface stays a clean ordered list with no name field. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct NamedTypedValueInput { + pub name: String, + pub sql_type: String, + pub value: Option, } /// Translate `ExecuteOptions.positional_params` into the kernel's @@ -124,6 +146,22 @@ fn decode_positional_params(inputs: Vec) -> Result, +) -> Result, napi::Error> { + inputs + .into_iter() + .map(|nv| { + parse_typed_value(&nv.sql_type, nv.value.as_deref()) + .map(|tv| (nv.name, tv)) + .map_err(napi_err_from_kernel) + }) + .collect() +} + /// Closed-state error builder. Mirrors `statement::statement_closed_err` /// — route through the kernel envelope so the TS reviver mints a typed /// `KernelError(code='InvalidStatementHandle')`. Single source of truth @@ -272,6 +310,12 @@ impl Connection { .map(decode_positional_params) .transpose()? .unwrap_or_default(); + let named_params = options + .as_mut() + .and_then(|o| o.named_params.take()) + .map(decode_named_params) + .transpose()? + .unwrap_or_default(); // Merge `query_tags` into `statement_conf` at the napi boundary // so the kernel sees a single conf map. Serialise the tag // map to the comma-separated `key:value` wire shape NodeJS @@ -299,6 +343,12 @@ impl Connection { .param(i + 1, value) .map_err(napi_err_from_kernel)?; } + // Bind named params (`:name`). + for (name, value) in named_params { + stmt.spec() + .param_named(name, value) + .map_err(napi_err_from_kernel)?; + } let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. @@ -435,6 +485,7 @@ mod tests { row_limit: None, query_timeout_secs: None, positional_params: None, + named_params: None, })) .unwrap(); assert!(result.is_none(), "empty maps → no statement_conf"); @@ -450,6 +501,7 @@ mod tests { row_limit: None, query_timeout_secs: None, positional_params: None, + named_params: None, })) .unwrap() .unwrap(); @@ -466,6 +518,7 @@ mod tests { row_limit: None, query_timeout_secs: None, positional_params: None, + named_params: None, })) .unwrap() .unwrap(); @@ -486,6 +539,7 @@ mod tests { row_limit: None, query_timeout_secs: None, positional_params: None, + named_params: None, })) .unwrap() .unwrap(); @@ -505,6 +559,7 @@ mod tests { row_limit: None, query_timeout_secs: None, positional_params: None, + named_params: None, })) .unwrap() .unwrap(); @@ -526,6 +581,7 @@ mod tests { row_limit: None, query_timeout_secs: None, positional_params: None, + named_params: None, })) .expect_err("must reject when both are set"); assert!( @@ -550,6 +606,7 @@ mod tests { row_limit: None, query_timeout_secs: None, positional_params: None, + named_params: None, })) .unwrap() .unwrap(); From fbbd32e11b2304904bef207a5981460046a1c590 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 31 May 2026 16:27:23 +0000 Subject: [PATCH 28/28] fix(kernel,napi): surface close_statement errors + non-blocking concurrent executeStatement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two statement/connection lifecycle robustness fixes from the jira-candidate triage: - kernel `SeaTransport::close_statement` (src/client/sea.rs) now BUBBLES the post-retry wire error instead of `let _ = …` swallowing it. The `ExecutedStatement::close` / `ExecutedAsyncStatement::close` "store-on-success retry" pattern only flips the `closed` flag on success, so the swallow made the failure branch dead code and a failed explicit close looked successful. Both pyo3 and napi inherit the fix; the Drop fire-and-forget fallback close still runs on error. (jira 2026-05-25-kernel-sea-close-statement-surface-errors) - napi `Connection.executeStatement` no longer holds the session mutex across `execute().await`. `Session::statement()` returns an owned kernel `Statement` (it clones the session's internal Arc), so we build the statement under the lock and release it before the wire round-trip. This unblocks concurrent `Promise.all([executeStatement(...)])` (they serialise only for the microsecond statement-build) and stops `close()` from blocking behind an in-flight execute. (jira 2026-05-24-napi-cancel-during-fetch, connection-side) The statement-side half of the lock-shape refactor (cancel-during-fetch — split the kernel ExecutedStatement into a lock-free cancel/close handle + a stream slot) is deferred: it needs a kernel ExecutedStatement restructure and is higher-risk; tracked separately. Build + 69 napi tests + fmt + clippy clean. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 64 +++++++++++++++++++++++++----------------- src/client/sea.rs | 21 ++++++++++++-- 2 files changed, 57 insertions(+), 28 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 676a1d96..a2374aaf 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -323,32 +323,46 @@ impl Connection { // (`lib/utils/queryTags.ts`). let merged_conf = build_merged_statement_conf(options)?; guarded(async move { - let guard = inner.lock().await; - let session = guard.as_ref().ok_or_else(connection_closed_err)?; - - let mut stmt = session.statement(); - stmt.spec().sql(sql); - if let Some(conf) = merged_conf { - stmt.spec().statement_conf(conf); - } - // `None` leaves the kernel's omit-the-field default in place, - // so threading unconditionally is safe and keeps the spec the - // single source of truth. - stmt.spec() - .row_limit(row_limit) - .query_timeout_secs(query_timeout_secs); - // Bind positional params 1-based on the wire. - for (i, value) in positional_params.into_iter().enumerate() { + // Build the kernel `Statement` while holding the session lock, + // then RELEASE the lock before `execute().await`. `Session::statement()` + // returns an owned `Statement` (it clones the session's internal + // `Arc`), so the built statement is independent of the guard — we + // do not need to hold the mutex across the network round-trip. + // This unblocks concurrent `Promise.all([executeStatement(...)])` + // (they serialise only for the microsecond statement-build, not the + // wire call) and stops `close()` from blocking behind an in-flight + // execute. See jira-candidate 2026-05-24-napi-cancel-during-fetch + // (connection-side half). + let mut stmt = { + let guard = inner.lock().await; + let session = guard.as_ref().ok_or_else(connection_closed_err)?; + + let mut stmt = session.statement(); + stmt.spec().sql(sql); + if let Some(conf) = merged_conf { + stmt.spec().statement_conf(conf); + } + // `None` leaves the kernel's omit-the-field default in place, + // so threading unconditionally is safe and keeps the spec the + // single source of truth. stmt.spec() - .param(i + 1, value) - .map_err(napi_err_from_kernel)?; - } - // Bind named params (`:name`). - for (name, value) in named_params { - stmt.spec() - .param_named(name, value) - .map_err(napi_err_from_kernel)?; - } + .row_limit(row_limit) + .query_timeout_secs(query_timeout_secs); + // Bind positional params 1-based on the wire. + for (i, value) in positional_params.into_iter().enumerate() { + stmt.spec() + .param(i + 1, value) + .map_err(napi_err_from_kernel)?; + } + // Bind named params (`:name`). + for (name, value) in named_params { + stmt.spec() + .param_named(name, value) + .map_err(napi_err_from_kernel)?; + } + stmt + // session lock released here + }; let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. diff --git a/src/client/sea.rs b/src/client/sea.rs index b49f97b8..d1f4328b 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -771,11 +771,26 @@ impl Transport for SeaRestTransport { Error::invalid_argument().message(format!("Failed to build request: {e}")) })?; - // Ignore errors on statement close (best effort cleanup) - let _ = self + // Surface the wire error so the caller's retry-on-failure path can + // run — `ExecutedStatement::close` / `ExecutedAsyncStatement::close` + // only flip their `closed` flag on success, so a swallowed error here + // would make their store-on-success semantics dead code (and a failed + // explicit close would look like it succeeded). The HTTP client has + // already applied the SEA retry policy, so callers see only the + // post-retry result; the `Drop` fire-and-forget fallback close still + // runs on the kernel side if the explicit close errored. + if let Err(e) = self .http_client .execute(request, RequestType::CloseStatement) - .await; + .await + { + tracing::warn!( + statement_id = %statement_id, + error = %e, + "close_statement failed after HTTP retries; surfacing to caller (Drop fallback close will run)" + ); + return Err(e); + } debug!("Closed statement: {}", statement_id);