diff --git a/napi/src/connection.rs b/napi/src/connection.rs new file mode 100644 index 00000000..58be04ca --- /dev/null +++ b/napi/src/connection.rs @@ -0,0 +1,217 @@ +// 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. +//! +//! - `Connection.executeStatement(sql)` — builds a kernel `Statement`, +//! sets the SQL, awaits `execute()`, and wraps the result in a +//! JS-visible `Statement` opaque handle. Catalog / schema / +//! 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. + +use std::sync::Arc; +use tokio::sync::Mutex; + +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`), +/// - `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()`. + /// + /// No per-statement options: catalog / schema / sessionConf are + /// session-level (`openSession`). + #[napi] + pub async fn execute_statement(&self, sql: String) -> napi::Result { + let inner = Arc::clone(&self.inner); + 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); + + let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; + Ok(Statement::from_executed(executed)) + }) + .await + } + + /// 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`. + /// + /// **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); + guarded(async move { + let session = { + let mut guard = inner.lock().await; + guard.take() + }; + let Some(session) = session else { + return Ok(()); + }; + session.close().await.map_err(napi_err_from_kernel) + }) + .await + } +} + +impl Drop for Connection { + fn drop(&mut self) { + // 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; + }; + let inner = Arc::clone(&self.inner); + handle.spawn(async move { + // Drop the session value on the runtime. The kernel's + // `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() + }; + }); + } +} + +#[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 new file mode 100644 index 00000000..b94cafcc --- /dev/null +++ b/napi/src/database.rs @@ -0,0 +1,126 @@ +// 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. +//! +//! 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; +use tokio::sync::Mutex; + +use databricks_sql_kernel::{AuthConfig, DefaultOpts, 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. +/// `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 on this binding. +#[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 + /// 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, + /// 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 +/// `Connection` wrapping the kernel `Session`. +/// +/// 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 { + // 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 mut builder = Session::builder() + .http_path(options.host_name, options.http_path) + .auth(AuthConfig::Pat { + token: options.token, + }); + // Only wire `DefaultOpts` when at least one of catalog / schema + // was provided; otherwise leave the config's `defaults` field + // `None` so the kernel can distinguish "no defaults" from + // "empty defaults" if that distinction ever becomes meaningful. + // `DefaultOpts` is `#[non_exhaustive]` — must construct via + // `default()` and mutate fields. + if options.catalog.is_some() || options.schema.is_some() { + let mut defaults = DefaultOpts::default(); + defaults.catalog = options.catalog; + defaults.schema = options.schema; + builder = builder.defaults(defaults); + } + if let Some(conf) = options.session_conf { + builder = builder.session_conf(conf); + } + let session = builder.open().await.map_err(napi_err_from_kernel)?; + let session_id = session.session_id().to_owned(); + Ok(Connection { + inner: Arc::new(Mutex::new(Some(session))), + session_id, + }) + }) + .await +} diff --git a/napi/src/lib.rs b/napi/src/lib.rs index b418e743..455bfc91 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -15,11 +15,12 @@ //! `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. +//! Surface: `openSession()` (free function) → `Connection` (opaque +//! class with `executeStatement` / `close` / `sessionId`) → +//! `Statement` (opaque class with `fetchNextBatch` / `schema` / +//! `cancel` / `close` / `statementId`). Results cross the FFI as +//! Arrow IPC bytes (`ArrowBatch` / `ArrowSchema` POJOs in +//! `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 +39,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..f0515e23 --- /dev/null +++ b/napi/src/result.rs @@ -0,0 +1,41 @@ +// 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 { + /// Arrow IPC stream payload (schema header + 1 record-batch + /// message). Decode with `apache-arrow`'s `RecordBatchReader`. + 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 { + /// 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 new file mode 100644 index 00000000..4fcab4b0 --- /dev/null +++ b/napi/src/statement.rs @@ -0,0 +1,469 @@ +// 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`. +//! +//! - `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 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 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}; +use crate::runtime; +use crate::util::guarded; + +/// Opaque executed-statement handle. +/// +/// **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`. 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 { + /// 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 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(statement_closed_err)?; + + let stream = executed.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 + // natural completion can short-circuit to Ok(()). + finished.store(true, Ordering::Release); + 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, + _ => { + // `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", + env!("CARGO_PKG_VERSION"), + )), + )); + } + }; + 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, 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 fn schema(&self) -> napi::Result { + let bytes = encode_ipc_stream(&self.schema, None)?; + Ok(ArrowSchema { + ipc_bytes: bytes.into(), + }) + } + + /// 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(statement_closed_err)?; + executed.cancel().await.map_err(napi_err_from_kernel) + }) + .await + } + + /// 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`. + /// + /// **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); + 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) { + // 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; + }; + 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() + }; + }); + } +} + +/// 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 +/// 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> { + fn arrow_err(e: impl std::fmt::Display) -> napi::Error { + napi::Error::new(napi::Status::GenericFailure, e.to_string()) + } + // 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 { + writer.write(rb).map_err(arrow_err)?; + } + 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()); + } + + // ─── 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 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); +}