From 68b5bf7b81c532b0a4548291a137b487f7595614 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sat, 16 May 2026 14:38:27 +0000 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] =?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 6/7] 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 7/7] =?UTF-8?q?fix(napi,kernel):=20address=20PR=20#25=20re?= =?UTF-8?q?view=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); +}