From 1ca7c68d2e4aa9d9af8a2f4d0fc92e9d1d15ea2c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 20:46:26 +0000 Subject: [PATCH 1/9] fix(napi): release the session when an AsyncStatement closes AsyncStatement.close() left its detached canceller in place and never released the result streams of the AsyncResultHandles it returned. Both hold the kernel session, so the host's shared telemetry client stayed alive until JS garbage collection. A later session on the same host then reused it and ignored its own batch size and flush interval. close() now drops the canceller and empties every result slot it handed out, even if the close RPC fails. Fetching from an AsyncResultHandle after its statement is closed returns InvalidStatementHandle. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- napi/NEXT_CHANGELOG.md | 2 + napi/src/async_statement.rs | 234 ++++++++++++++++++++++++++++++++++-- 2 files changed, 224 insertions(+), 12 deletions(-) diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 8597f31e..a394f802 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -20,6 +20,8 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Fixed +- `AsyncStatement.close()` now releases its canceller and the result streams of its `AsyncResultHandle`s. These held the session until JS garbage collection, so a host's shared telemetry client, and its settings, outlived every closed session and were reused by the next one. Fetching from an `AsyncResultHandle` after its statement is closed now returns `InvalidStatementHandle`. + --- *Note: When making changes, please add your change under the appropriate section with a brief description. At release time, move the entries here diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index f62d49c4..280fb0c3 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -52,9 +52,14 @@ //! rather than queue behind it. The `Arc>>` shape is //! otherwise the same as `Connection`/`Statement` so Drop's //! fire-and-forget cleanup behaves consistently. +//! +//! `close()` also releases the canceller and the result streams of the +//! `AsyncResultHandle`s it produced. Both hold the kernel session, and with +//! it the host's shared telemetry client, so leaving them to JS GC kept that +//! client (and its configuration) alive after every session had closed. use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, PoisonError, Weak}; use tokio::sync::Mutex; use arrow_schema::SchemaRef; @@ -88,6 +93,10 @@ fn closed_err(what: &str) -> napi::Error { // ───────────────────────── AsyncStatement ───────────────────────── +/// An `AsyncResultHandle`'s stream, shared with its parent `AsyncStatement` +/// so the parent's `close()` can release it. +type ResultSlot = Mutex>; + /// Inner state for the JS-visible `AsyncStatement` wrapper. Same /// shape rationale as `StatementInner` in `statement.rs`: we hold /// the parent kernel `Statement` alive so its `Drop` (which @@ -130,8 +139,13 @@ pub struct AsyncStatement { /// construction and held **outside** `inner` so `cancel()` can fire /// a server-side cancel without contending for the mutex an /// in-flight `awaitResult()` holds. See the struct-level - /// concurrency note. - canceller: AsyncStatementCanceller, + /// concurrency note. A std mutex (never held across an `.await`) so + /// `close()` can drop it; `None` once closed. + canceller: Arc>>, + /// Result slots of the `AsyncResultHandle`s returned by + /// `awaitResult()`, emptied by `close()`. Weak so a handle JS has + /// already dropped is not kept alive here. + results: Arc>>>, /// Lock-free mirror of "has `close()` taken `inner`". Set by /// `close()`; read by the lock-free `cancel()` so a cancel after an /// explicit close still surfaces `InvalidStatementHandle` without @@ -164,7 +178,8 @@ impl AsyncStatement { _parent: parent, executed_async, }))), - canceller, + canceller: Arc::new(std::sync::Mutex::new(Some(canceller))), + results: Arc::new(std::sync::Mutex::new(Vec::new())), closed: Arc::new(AtomicBool::new(false)), statement_id, } @@ -294,6 +309,7 @@ impl AsyncStatement { #[napi] pub async fn await_result(&self) -> napi::Result { let inner = Arc::clone(&self.inner); + let results = Arc::clone(&self.results); guarded(async move { // Acquire and HOLD the lock across the kernel await: // dropping the guard while the long-running @@ -312,8 +328,15 @@ impl AsyncStatement { .map_err(napi_err_from_kernel)?; let statement_id = inner_state.executed_async.statement_id().to_owned(); let schema = stream.schema(); + let slot = Arc::new(Mutex::new(Some(stream))); + // Registered while `inner` is still held, so a `close()` queued + // behind this call always sees the slot. + results + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(Arc::downgrade(&slot)); Ok(AsyncResultHandle { - inner: Arc::new(Mutex::new(Some(stream))), + inner: slot, schema, statement_id, }) @@ -342,7 +365,14 @@ impl AsyncStatement { if self.closed.load(Ordering::Acquire) { return Err(closed_err("AsyncStatement")); } - let canceller = self.canceller.clone(); + let canceller = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone(); + let Some(canceller) = canceller else { + return Err(closed_err("AsyncStatement")); + }; guarded(async move { canceller.cancel().await.map_err(napi_err_from_kernel) }).await } @@ -356,6 +386,8 @@ impl AsyncStatement { pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); let closed = Arc::clone(&self.closed); + let canceller = Arc::clone(&self.canceller); + let results = Arc::clone(&self.results); guarded(async move { let taken = { let mut guard = inner.lock().await; @@ -368,9 +400,23 @@ impl AsyncStatement { // lock-free `cancel()` short-circuits to InvalidStatementHandle // rather than firing a wire cancel on a closing statement. closed.store(true, Ordering::Release); - ExecutedAsyncStatement::close(&mut inner_state.executed_async) + let outcome = ExecutedAsyncStatement::close(&mut inner_state.executed_async) .await - .map_err(napi_err_from_kernel) + .map_err(napi_err_from_kernel); + // Release everything that holds the session, even if the + // close RPC failed: JS may keep this object (and its result + // handles) reachable long after close. + drop(inner_state); + canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + let slots = + std::mem::take(&mut *results.lock().unwrap_or_else(PoisonError::into_inner)); + for slot in slots.iter().filter_map(Weak::upgrade) { + slot.lock().await.take(); + } + outcome }) .await } @@ -413,10 +459,9 @@ impl Drop for AsyncStatement { /// post-close contract. #[napi] pub struct AsyncResultHandle { - /// `Option` only so a future explicit-close path - /// can `.take()` consistently. Today the slot is filled at - /// construction and never emptied until Drop. - inner: Arc>>, + /// Emptied when the parent `AsyncStatement` closes; fetching after + /// that returns `InvalidStatementHandle`. + inner: Arc, schema: SchemaRef, statement_id: String, } @@ -493,6 +538,12 @@ impl AsyncResultHandle { #[cfg(test)] mod tests { use super::*; + use crate::connection::Connection; + use databricks_sql_kernel::{AuthConfig, ConnectionConfig, Session, TelemetryConfig}; + use serde_json::json; + use std::time::Duration; + use wiremock::matchers::{method, path, path_regex}; + use wiremock::{Mock, MockServer, ResponseTemplate}; #[test] fn closed_err_carries_invalid_statement_handle_envelope() { @@ -519,4 +570,163 @@ mod tests { let err = closed_err("AsyncResultHandle"); assert_eq!(err.status, napi::Status::InvalidArg); } + + const FIRST_SESSION: &str = "sess-napi-lease-first"; + const SECOND_SESSION: &str = "sess-napi-lease-second"; + const STATEMENT: &str = "stmt-napi-lease"; + + async fn lease_server() -> MockServer { + let server = MockServer::start().await; + for session_id in [FIRST_SESSION, SECOND_SESSION] { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({ "session_id": session_id })), + ) + .up_to_n_times(1) + .mount(&server) + .await; + } + Mock::given(method("DELETE")) + .and(path_regex(r"^/api/2\.0/sql/sessions/.+")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": STATEMENT, + "status": { "state": "PENDING" }, + }))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("/api/2.0/sql/statements/{STATEMENT}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": STATEMENT, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 1, + "columns": [{ + "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0, + }], + }, + "total_chunk_count": 0, + "total_row_count": 0, + "truncated": false, + }, + }))) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path_regex(r"^/api/2\.0/sql/statements/.+")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/telemetry-ext")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + server + } + + async fn telemetry_connection( + server: &MockServer, + batch_size: usize, + flush_interval: Duration, + ) -> Connection { + let mut telemetry = TelemetryConfig::default(); + telemetry.set_enabled(true); + telemetry.batch_size = batch_size; + telemetry.flush_interval = flush_interval; + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid HTTP path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .telemetry(telemetry) + .open() + .await + .expect("session opens against mock server"); + let session_id = session.session_id().to_owned(); + Connection { + inner: Arc::new(Mutex::new(Some(session))), + session_id, + } + } + + async fn exports_for(server: &MockServer, session_id: &str) -> usize { + server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|request| { + request.url.path() == "/telemetry-ext" + && String::from_utf8_lossy(&request.body).contains(session_id) + }) + .count() + } + + /// The host's telemetry client must be released once its sessions and + /// their statements are closed, even while JS still references the closed + /// handles. Otherwise the next session on the host reuses it and ignores + /// its own telemetry settings. + async fn next_session_gets_its_own_telemetry_client(fetch_result: bool) { + let server = lease_server().await; + // Batch size 1: this client exports every event at once. + let first = telemetry_connection(&server, 1, Duration::from_millis(100)).await; + let statement = first + .submit_statement("SELECT 1 AS n".into(), None) + .await + .expect("submit"); + let result = if fetch_result { + Some(statement.await_result().await.expect("await result")) + } else { + None + }; + statement.close().await.expect("close statement"); + first.close().await.expect("close first session"); + + let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + // Inheriting the first client would export CREATE_SESSION right away. + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!( + exports_for(&server, SECOND_SESSION).await, + 0, + "second session reused the first session's telemetry client" + ); + second.close().await.expect("close second session"); + assert!( + exports_for(&server, SECOND_SESSION).await > 0, + "closing the last session must flush its events" + ); + if let Some(result) = &result { + let err = result + .fetch_next_batch() + .await + .err() + .expect("fetching after the parent closed must fail"); + assert!(err.reason.contains("AsyncResultHandle already closed")); + } + // Dropped only now, as JS GC would. + drop((statement, result)); + } + + #[tokio::test] + async fn close_releases_session_held_by_canceller() { + next_session_gets_its_own_telemetry_client(false).await; + } + + #[tokio::test] + async fn close_releases_session_held_by_result_handles() { + next_session_gets_its_own_telemetry_client(true).await; + } } From 8fc05d33c0524690ae348b77aff0565644a93e31 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 21:14:17 +0000 Subject: [PATCH 2/9] fix(napi): don't make AsyncStatement.close() wait for an in-flight fetch fetchNextBatch() holds the result slot's mutex for the whole batch fetch, so awaiting that mutex in close() held the close promise until the fetch finished. close() now marks each slot closed and takes the stream only if the slot is free. A fetch that holds the slot drops the stream when it returns. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- napi/src/async_statement.rs | 117 ++++++++++++++++++++++++++++-------- 1 file changed, 91 insertions(+), 26 deletions(-) diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 280fb0c3..c3230fff 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -95,7 +95,28 @@ fn closed_err(what: &str) -> napi::Error { /// An `AsyncResultHandle`'s stream, shared with its parent `AsyncStatement` /// so the parent's `close()` can release it. -type ResultSlot = Mutex>; +struct ResultSlot { + stream: Mutex>, + /// Set by the parent's `close()`. A fetch holding `stream` at that moment + /// drops it on return, so `close()` never waits for a fetch. + closed: AtomicBool, +} + +impl ResultSlot { + fn new(stream: ResultStream) -> Self { + Self { + stream: Mutex::new(Some(stream)), + closed: AtomicBool::new(false), + } + } + + fn release(&self) { + self.closed.store(true, Ordering::Release); + if let Ok(mut stream) = self.stream.try_lock() { + stream.take(); + } + } +} /// Inner state for the JS-visible `AsyncStatement` wrapper. Same /// shape rationale as `StatementInner` in `statement.rs`: we hold @@ -328,7 +349,7 @@ impl AsyncStatement { .map_err(napi_err_from_kernel)?; let statement_id = inner_state.executed_async.statement_id().to_owned(); let schema = stream.schema(); - let slot = Arc::new(Mutex::new(Some(stream))); + let slot = Arc::new(ResultSlot::new(stream)); // Registered while `inner` is still held, so a `close()` queued // behind this call always sees the slot. results @@ -414,7 +435,7 @@ impl AsyncStatement { let slots = std::mem::take(&mut *results.lock().unwrap_or_else(PoisonError::into_inner)); for slot in slots.iter().filter_map(Weak::upgrade) { - slot.lock().await.take(); + slot.release(); } outcome }) @@ -466,6 +487,34 @@ pub struct AsyncResultHandle { statement_id: String, } +/// Pull one batch from `stream` and encode it as an Arrow IPC payload. +async fn next_ipc_batch( + stream: &mut ResultStream, + schema: &SchemaRef, +) -> napi::Result> { + let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; + let Some(batch) = maybe_batch else { + return Ok(None); + }; + let record_batch = match batch { + ResultBatch::Arrow(rb) => rb, + _ => { + 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(), + })) +} + #[napi] impl AsyncResultHandle { /// Server-issued statement id. Cached at construction; readable @@ -487,31 +536,21 @@ impl AsyncResultHandle { let inner = Arc::clone(&self.inner); let schema = self.schema.clone(); guarded(async move { - let mut guard = inner.lock().await; - let stream = guard - .as_mut() - .ok_or_else(|| closed_err("AsyncResultHandle"))?; - let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; - let Some(batch) = maybe_batch else { - return Ok(None); - }; - let record_batch = match batch { - ResultBatch::Arrow(rb) => rb, - _ => { - 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 outcome = { + let mut guard = inner.stream.lock().await; + if inner.closed.load(Ordering::Acquire) { + guard.take(); + } + match guard.as_mut() { + Some(stream) => next_ipc_batch(stream, &schema).await, + None => Err(closed_err("AsyncResultHandle")), } }; - let bytes = encode_ipc_stream(&schema, Some(record_batch))?; - Ok(Some(ArrowBatch { - ipc_bytes: bytes.into(), - })) + // The parent may have closed while this fetch held the stream. + if inner.closed.load(Ordering::Acquire) { + inner.release(); + } + outcome }) .await } @@ -729,4 +768,30 @@ mod tests { async fn close_releases_session_held_by_result_handles() { next_session_gets_its_own_telemetry_client(true).await; } + + #[tokio::test] + async fn close_does_not_wait_for_an_in_flight_fetch() { + let server = lease_server().await; + let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let statement = connection + .submit_statement("SELECT 1 AS n".into(), None) + .await + .expect("submit"); + let result = statement.await_result().await.expect("await result"); + // Hold the stream the way an in-flight `fetchNextBatch()` does. + let in_flight = result.inner.stream.lock().await; + tokio::time::timeout(Duration::from_secs(5), statement.close()) + .await + .expect("close must not wait for an in-flight fetch") + .expect("close statement"); + drop(in_flight); + let err = result + .fetch_next_batch() + .await + .err() + .expect("fetching after the parent closed must fail"); + assert!(err.reason.contains("AsyncResultHandle already closed")); + assert!(result.inner.stream.lock().await.is_none()); + connection.close().await.expect("close session"); + } } From ae433ec1ca5aa34d819a4b3239e73d85b4cab6e6 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 07:11:43 +0000 Subject: [PATCH 3/9] fix(napi): release a result stream held by an in-flight fetch on close close() set the slot's closed flag and then tried the lock, while a finishing fetch released the lock and then read the flag. With Release/Acquire ordering both sides can miss each other, so neither drops the stream and the session stays alive until JS GC. A same-primitive litmus run hit this 181 times in 3M iterations. When the slot is busy, close() now spawns a task that waits for the lock and drops the stream, so the release no longer depends on the fetch noticing. Also prune dead result slots when registering a new one, and test that a failed close RPC still releases the canceller and stream. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/src/async_statement.rs | 81 ++++++++++++++++++++++++++----------- 1 file changed, 58 insertions(+), 23 deletions(-) diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index c3230fff..f517d22c 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -97,8 +97,8 @@ fn closed_err(what: &str) -> napi::Error { /// so the parent's `close()` can release it. struct ResultSlot { stream: Mutex>, - /// Set by the parent's `close()`. A fetch holding `stream` at that moment - /// drops it on return, so `close()` never waits for a fetch. + /// Set by the parent's `close()`; a fetch that locks `stream` afterwards + /// drops it and returns `InvalidStatementHandle`. closed: AtomicBool, } @@ -110,11 +110,17 @@ impl ResultSlot { } } - fn release(&self) { + /// Drops the stream without waiting for an in-flight fetch: if one holds + /// it, a task drops it as soon as that fetch returns. + fn release(self: Arc) { self.closed.store(true, Ordering::Release); if let Ok(mut stream) = self.stream.try_lock() { stream.take(); + return; } + tokio::spawn(async move { + self.stream.lock().await.take(); + }); } } @@ -352,10 +358,11 @@ impl AsyncStatement { let slot = Arc::new(ResultSlot::new(stream)); // Registered while `inner` is still held, so a `close()` queued // behind this call always sees the slot. - results - .lock() - .unwrap_or_else(PoisonError::into_inner) - .push(Arc::downgrade(&slot)); + { + let mut results = results.lock().unwrap_or_else(PoisonError::into_inner); + results.retain(|slot| slot.strong_count() > 0); + results.push(Arc::downgrade(&slot)); + } Ok(AsyncResultHandle { inner: slot, schema, @@ -434,9 +441,10 @@ impl AsyncStatement { .take(); let slots = std::mem::take(&mut *results.lock().unwrap_or_else(PoisonError::into_inner)); - for slot in slots.iter().filter_map(Weak::upgrade) { - slot.release(); - } + slots + .iter() + .filter_map(Weak::upgrade) + .for_each(ResultSlot::release); outcome }) .await @@ -536,21 +544,14 @@ impl AsyncResultHandle { let inner = Arc::clone(&self.inner); let schema = self.schema.clone(); guarded(async move { - let outcome = { - let mut guard = inner.stream.lock().await; - if inner.closed.load(Ordering::Acquire) { - guard.take(); - } - match guard.as_mut() { - Some(stream) => next_ipc_batch(stream, &schema).await, - None => Err(closed_err("AsyncResultHandle")), - } - }; - // The parent may have closed while this fetch held the stream. + let mut guard = inner.stream.lock().await; if inner.closed.load(Ordering::Acquire) { - inner.release(); + guard.take(); } - outcome + let stream = guard + .as_mut() + .ok_or_else(|| closed_err("AsyncResultHandle"))?; + next_ipc_batch(stream, &schema).await }) .await } @@ -785,12 +786,46 @@ mod tests { .expect("close must not wait for an in-flight fetch") .expect("close statement"); drop(in_flight); + // Released once the fetch returns, without relying on another fetch. + tokio::time::timeout(Duration::from_secs(5), async { + while result.inner.stream.lock().await.is_some() { + tokio::task::yield_now().await; + } + }) + .await + .expect("the stream must be dropped once the in-flight fetch returns"); let err = result .fetch_next_batch() .await .err() .expect("fetching after the parent closed must fail"); assert!(err.reason.contains("AsyncResultHandle already closed")); + connection.close().await.expect("close session"); + } + + #[tokio::test] + async fn close_releases_session_when_the_close_rpc_fails() { + let server = lease_server().await; + Mock::given(method("DELETE")) + .and(path_regex(r"^/api/2\.0/sql/statements/.+")) + .respond_with(ResponseTemplate::new(400).set_body_json(json!({ + "error_code": "INVALID_PARAMETER_VALUE", + "message": "close failed", + }))) + .with_priority(1) + .mount(&server) + .await; + let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let statement = connection + .submit_statement("SELECT 1 AS n".into(), None) + .await + .expect("submit"); + let result = statement.await_result().await.expect("await result"); + statement + .close() + .await + .expect_err("the close RPC must fail"); + assert!(statement.canceller.lock().unwrap().is_none()); assert!(result.inner.stream.lock().await.is_none()); connection.close().await.expect("close session"); } From 06e40488c21f65707ebced046d749012c8dd3f19 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 07:20:42 +0000 Subject: [PATCH 4/9] fix(napi): release on a panicking close and document handle invalidation A panic in the close RPC skipped the release of the canceller and result streams, and a retried close() returns early, so the session leaked again. The release now lives in a drop guard created before the RPC, so it runs on return and on unwind. Document on AsyncStatement.close() and AsyncResultHandle.fetchNextBatch() that closing the statement invalidates the handles awaitResult() returned, and mirror it in index.d.ts. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/index.d.ts | 6 +++ napi/src/async_statement.rs | 86 +++++++++++++++++++++++++++++++------ 2 files changed, 79 insertions(+), 13 deletions(-) diff --git a/napi/index.d.ts b/napi/index.d.ts index bcb54502..d90c4ce1 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -853,6 +853,10 @@ export declare class AsyncStatement { * closed-handle short-circuit and returns `Ok(())` without * re-attempting the wire call. The kernel's own `Drop` * fire-and-forget retry runs once in the background. + * + * Closing also invalidates the `AsyncResultHandle`s returned by + * `awaitResult()`: their `fetchNextBatch()` then rejects with + * `InvalidStatementHandle`, so finish fetching first. */ close(): Promise } @@ -887,6 +891,8 @@ export declare class AsyncResultHandle { * message), suitable for handing to `apache-arrow`'s * `RecordBatchReader`. Byte-identical to the sync * `Statement.fetchNextBatch()` payload for the same query. + * Rejects with `KernelError(InvalidStatementHandle)` once the + * parent `AsyncStatement` has been closed. */ fetchNextBatch(): Promise /** diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index f517d22c..c33d6548 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -124,6 +124,30 @@ impl ResultSlot { } } +/// Drops `AsyncStatement::close()`'s canceller and result streams on scope +/// exit, including unwind. +struct CloseRelease { + canceller: Arc>>, + results: Arc>>>, +} + +impl Drop for CloseRelease { + fn drop(&mut self) { + let canceller = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + drop(canceller); + let slots = + std::mem::take(&mut *self.results.lock().unwrap_or_else(PoisonError::into_inner)); + slots + .iter() + .filter_map(Weak::upgrade) + .for_each(ResultSlot::release); + } +} + /// Inner state for the JS-visible `AsyncStatement` wrapper. Same /// shape rationale as `StatementInner` in `statement.rs`: we hold /// the parent kernel `Statement` alive so its `Drop` (which @@ -410,6 +434,10 @@ impl AsyncStatement { /// closed-handle short-circuit and returns `Ok(())` without /// re-attempting the wire call. The kernel's own `Drop` /// fire-and-forget retry runs once in the background. + /// + /// Closing also invalidates the `AsyncResultHandle`s returned by + /// `awaitResult()`: their `fetchNextBatch()` then rejects with + /// `InvalidStatementHandle`, so finish fetching first. #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); @@ -428,23 +456,14 @@ impl AsyncStatement { // lock-free `cancel()` short-circuits to InvalidStatementHandle // rather than firing a wire cancel on a closing statement. closed.store(true, Ordering::Release); + // Release everything that holds the session when this scope + // ends, even if the close RPC fails or panics: JS may keep this + // object (and its result handles) reachable long after close. + let _release = CloseRelease { canceller, results }; let outcome = ExecutedAsyncStatement::close(&mut inner_state.executed_async) .await .map_err(napi_err_from_kernel); - // Release everything that holds the session, even if the - // close RPC failed: JS may keep this object (and its result - // handles) reachable long after close. drop(inner_state); - canceller - .lock() - .unwrap_or_else(PoisonError::into_inner) - .take(); - let slots = - std::mem::take(&mut *results.lock().unwrap_or_else(PoisonError::into_inner)); - slots - .iter() - .filter_map(Weak::upgrade) - .for_each(ResultSlot::release); outcome }) .await @@ -539,6 +558,8 @@ impl AsyncResultHandle { /// message), suitable for handing to `apache-arrow`'s /// `RecordBatchReader`. Byte-identical to the sync /// `Statement.fetchNextBatch()` payload for the same query. + /// Rejects with `KernelError(InvalidStatementHandle)` once the + /// parent `AsyncStatement` has been closed. #[napi] pub async fn fetch_next_batch(&self) -> napi::Result> { let inner = Arc::clone(&self.inner); @@ -829,4 +850,43 @@ mod tests { assert!(result.inner.stream.lock().await.is_none()); connection.close().await.expect("close session"); } + + fn panicking_close_rpc() -> napi::Result<()> { + panic!("close RPC panicked") + } + + #[tokio::test] + async fn close_release_runs_when_the_close_rpc_panics() { + let server = lease_server().await; + let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let statement = connection + .submit_statement("SELECT 1 AS n".into(), None) + .await + .expect("submit"); + let result = statement.await_result().await.expect("await result"); + // A busy slot makes the release spawn its task during the unwind. + let in_flight = result.inner.stream.lock().await; + let release = CloseRelease { + canceller: Arc::clone(&statement.canceller), + results: Arc::clone(&statement.results), + }; + let err = guarded(async move { + let _release = release; + panicking_close_rpc() + }) + .await + .expect_err("the panic must surface as an error"); + assert!(err.reason.contains("close RPC panicked")); + assert!(statement.canceller.lock().unwrap().is_none()); + drop(in_flight); + tokio::time::timeout(Duration::from_secs(5), async { + while result.inner.stream.lock().await.is_some() { + tokio::task::yield_now().await; + } + }) + .await + .expect("the stream must be dropped after a panicking close"); + statement.close().await.expect("close statement"); + connection.close().await.expect("close session"); + } } From 869c9808f862a546008d16ba844deb710dd81ae5 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 07:37:47 +0000 Subject: [PATCH 5/9] test(napi): name the unwind test for what it covers The test drops a hand-built CloseRelease during a panic, so it covers the guard's unwind behaviour, not close() itself. Rename it and say so. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/src/async_statement.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index c33d6548..4fac1224 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -855,8 +855,10 @@ mod tests { panic!("close RPC panicked") } + /// Covers `CloseRelease` on unwind only; a panic can't be injected into + /// the kernel close RPC, so `close()`'s use of the guard isn't driven here. #[tokio::test] - async fn close_release_runs_when_the_close_rpc_panics() { + async fn close_release_guard_releases_on_unwind() { let server = lease_server().await; let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; let statement = connection From 18021a2a6c2a83140f5fb4c37054665f7c8e35a0 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 07:54:58 +0000 Subject: [PATCH 6/9] fix(napi): don't panic releasing a busy result slot outside a runtime ResultSlot::release() runs from CloseRelease's drop, which can happen when the close() future is dropped off a runtime worker. The ambient tokio::spawn panics there, and a panic in a drop during unwind aborts the process. Spawn on the current runtime, or the captured napi runtime, and otherwise leave the stream for the next fetch or the handle's drop. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/src/async_statement.rs | 38 ++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 4fac1224..09234ef5 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -60,6 +60,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, PoisonError, Weak}; +use tokio::runtime::Handle; use tokio::sync::Mutex; use arrow_schema::SchemaRef; @@ -118,7 +119,16 @@ impl ResultSlot { stream.take(); return; } - tokio::spawn(async move { + // May run from a drop outside any runtime (e.g. teardown), where + // `tokio::spawn` would panic. With no runtime at all, the next fetch + // or the handle's drop frees the stream instead. + let Some(handle) = Handle::try_current() + .ok() + .or_else(|| runtime::try_get_handle().cloned()) + else { + return; + }; + handle.spawn(async move { self.stream.lock().await.take(); }); } @@ -851,6 +861,32 @@ mod tests { connection.close().await.expect("close session"); } + #[tokio::test] + async fn release_outside_a_runtime_does_not_panic() { + let server = lease_server().await; + let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let statement = connection + .submit_statement("SELECT 1 AS n".into(), None) + .await + .expect("submit"); + let result = statement.await_result().await.expect("await result"); + let in_flight = result.inner.stream.lock().await; + let slot = Arc::clone(&result.inner); + std::thread::spawn(move || slot.release()) + .join() + .expect("releasing a busy slot outside a runtime must not panic"); + drop(in_flight); + let err = result + .fetch_next_batch() + .await + .err() + .expect("fetching after release must fail"); + assert!(err.reason.contains("AsyncResultHandle already closed")); + assert!(result.inner.stream.lock().await.is_none()); + statement.close().await.expect("close statement"); + connection.close().await.expect("close session"); + } + fn panicking_close_rpc() -> napi::Result<()> { panic!("close RPC panicked") } From a283fcbf1dfcd19bb343bfec67c1416c47e08bec Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 08:20:23 +0000 Subject: [PATCH 7/9] test(napi): cover the closed-flag check in fetchNextBatch When close() finds the slot busy, the closed flag is what makes a fetch issued after close() reject before the spawned release takes the lock. No test failed with the check removed. The new test fetches right after close(), before the current-thread runtime polls the release task. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/src/async_statement.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 09234ef5..588a3fef 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -834,6 +834,30 @@ mod tests { connection.close().await.expect("close session"); } + #[tokio::test] + async fn fetch_after_close_fails_before_the_release_task_runs() { + let server = lease_server().await; + let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let statement = connection + .submit_statement("SELECT 1 AS n".into(), None) + .await + .expect("submit"); + let result = statement.await_result().await.expect("await result"); + let in_flight = result.inner.stream.lock().await; + statement.close().await.expect("close statement"); + drop(in_flight); + // The current-thread runtime hasn't polled the spawned release yet, + // so only the closed flag makes this fetch fail. + let err = result + .fetch_next_batch() + .await + .err() + .expect("fetching after the parent closed must fail"); + assert!(err.reason.contains("AsyncResultHandle already closed")); + assert!(result.inner.stream.lock().await.is_none()); + connection.close().await.expect("close session"); + } + #[tokio::test] async fn close_releases_session_when_the_close_rpc_fails() { let server = lease_server().await; From 4c4d4de1557439deb26599de80a96a6ca33036ef Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 16 Nov 2026 01:57:06 +0000 Subject: [PATCH 8/9] refactor(napi): trim the AsyncStatement.close() release to the minimal fix Keep only what TELEMETRY-015 needs and what avoids a regression: close() drops the canceller and empties every idle result slot, and skips a slot an in-flight fetch holds, so close never waits for a fetch. Drop the hardening that came after: the closed flag, the spawned release of a busy slot and its runtime-handle fallback, the drop guard for a panicking close RPC, dead-Weak pruning, and the doc and index.d.ts additions, along with the tests that only covered them. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/NEXT_CHANGELOG.md | 2 +- napi/index.d.ts | 6 - napi/src/async_statement.rs | 289 +++++++----------------------------- 3 files changed, 53 insertions(+), 244 deletions(-) diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index a394f802..d5ca462e 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -20,7 +20,7 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Fixed -- `AsyncStatement.close()` now releases its canceller and the result streams of its `AsyncResultHandle`s. These held the session until JS garbage collection, so a host's shared telemetry client, and its settings, outlived every closed session and were reused by the next one. Fetching from an `AsyncResultHandle` after its statement is closed now returns `InvalidStatementHandle`. +- `AsyncStatement.close()` now releases its canceller and the result streams of its `AsyncResultHandle`s. These held the session until JS garbage collection, so a host's shared telemetry client, and its settings, outlived every closed session and were reused by the next one. Fetching from an `AsyncResultHandle` after its statement is closed now returns `InvalidStatementHandle`, unless a fetch was using the stream when `close()` ran. --- *Note: When making changes, please add your change under the appropriate diff --git a/napi/index.d.ts b/napi/index.d.ts index d90c4ce1..bcb54502 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -853,10 +853,6 @@ export declare class AsyncStatement { * closed-handle short-circuit and returns `Ok(())` without * re-attempting the wire call. The kernel's own `Drop` * fire-and-forget retry runs once in the background. - * - * Closing also invalidates the `AsyncResultHandle`s returned by - * `awaitResult()`: their `fetchNextBatch()` then rejects with - * `InvalidStatementHandle`, so finish fetching first. */ close(): Promise } @@ -891,8 +887,6 @@ export declare class AsyncResultHandle { * message), suitable for handing to `apache-arrow`'s * `RecordBatchReader`. Byte-identical to the sync * `Statement.fetchNextBatch()` payload for the same query. - * Rejects with `KernelError(InvalidStatementHandle)` once the - * parent `AsyncStatement` has been closed. */ fetchNextBatch(): Promise /** diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 588a3fef..4cf05f58 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -52,15 +52,9 @@ //! rather than queue behind it. The `Arc>>` shape is //! otherwise the same as `Connection`/`Statement` so Drop's //! fire-and-forget cleanup behaves consistently. -//! -//! `close()` also releases the canceller and the result streams of the -//! `AsyncResultHandle`s it produced. Both hold the kernel session, and with -//! it the host's shared telemetry client, so leaving them to JS GC kept that -//! client (and its configuration) alive after every session had closed. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, PoisonError, Weak}; -use tokio::runtime::Handle; use tokio::sync::Mutex; use arrow_schema::SchemaRef; @@ -94,69 +88,8 @@ fn closed_err(what: &str) -> napi::Error { // ───────────────────────── AsyncStatement ───────────────────────── -/// An `AsyncResultHandle`'s stream, shared with its parent `AsyncStatement` -/// so the parent's `close()` can release it. -struct ResultSlot { - stream: Mutex>, - /// Set by the parent's `close()`; a fetch that locks `stream` afterwards - /// drops it and returns `InvalidStatementHandle`. - closed: AtomicBool, -} - -impl ResultSlot { - fn new(stream: ResultStream) -> Self { - Self { - stream: Mutex::new(Some(stream)), - closed: AtomicBool::new(false), - } - } - - /// Drops the stream without waiting for an in-flight fetch: if one holds - /// it, a task drops it as soon as that fetch returns. - fn release(self: Arc) { - self.closed.store(true, Ordering::Release); - if let Ok(mut stream) = self.stream.try_lock() { - stream.take(); - return; - } - // May run from a drop outside any runtime (e.g. teardown), where - // `tokio::spawn` would panic. With no runtime at all, the next fetch - // or the handle's drop frees the stream instead. - let Some(handle) = Handle::try_current() - .ok() - .or_else(|| runtime::try_get_handle().cloned()) - else { - return; - }; - handle.spawn(async move { - self.stream.lock().await.take(); - }); - } -} - -/// Drops `AsyncStatement::close()`'s canceller and result streams on scope -/// exit, including unwind. -struct CloseRelease { - canceller: Arc>>, - results: Arc>>>, -} - -impl Drop for CloseRelease { - fn drop(&mut self) { - let canceller = self - .canceller - .lock() - .unwrap_or_else(PoisonError::into_inner) - .take(); - drop(canceller); - let slots = - std::mem::take(&mut *self.results.lock().unwrap_or_else(PoisonError::into_inner)); - slots - .iter() - .filter_map(Weak::upgrade) - .for_each(ResultSlot::release); - } -} +/// An `AsyncResultHandle`'s stream, shared with its parent `AsyncStatement`. +type ResultSlot = Mutex>; /// Inner state for the JS-visible `AsyncStatement` wrapper. Same /// shape rationale as `StatementInner` in `statement.rs`: we hold @@ -200,12 +133,10 @@ pub struct AsyncStatement { /// construction and held **outside** `inner` so `cancel()` can fire /// a server-side cancel without contending for the mutex an /// in-flight `awaitResult()` holds. See the struct-level - /// concurrency note. A std mutex (never held across an `.await`) so - /// `close()` can drop it; `None` once closed. + /// concurrency note. Taken by `close()`: it holds the session. canceller: Arc>>, - /// Result slots of the `AsyncResultHandle`s returned by - /// `awaitResult()`, emptied by `close()`. Weak so a handle JS has - /// already dropped is not kept alive here. + /// Streams of the `AsyncResultHandle`s from `awaitResult()`, emptied + /// by `close()` because they also hold the session. results: Arc>>>, /// Lock-free mirror of "has `close()` taken `inner`". Set by /// `close()`; read by the lock-free `cancel()` so a cancel after an @@ -240,7 +171,7 @@ impl AsyncStatement { executed_async, }))), canceller: Arc::new(std::sync::Mutex::new(Some(canceller))), - results: Arc::new(std::sync::Mutex::new(Vec::new())), + results: Arc::default(), closed: Arc::new(AtomicBool::new(false)), statement_id, } @@ -389,16 +320,14 @@ impl AsyncStatement { .map_err(napi_err_from_kernel)?; let statement_id = inner_state.executed_async.statement_id().to_owned(); let schema = stream.schema(); - let slot = Arc::new(ResultSlot::new(stream)); - // Registered while `inner` is still held, so a `close()` queued - // behind this call always sees the slot. - { - let mut results = results.lock().unwrap_or_else(PoisonError::into_inner); - results.retain(|slot| slot.strong_count() > 0); - results.push(Arc::downgrade(&slot)); - } + let stream = Arc::new(Mutex::new(Some(stream))); + // Registered while `inner` is held, so a queued `close()` sees it. + results + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(Arc::downgrade(&stream)); Ok(AsyncResultHandle { - inner: slot, + inner: stream, schema, statement_id, }) @@ -444,10 +373,6 @@ impl AsyncStatement { /// closed-handle short-circuit and returns `Ok(())` without /// re-attempting the wire call. The kernel's own `Drop` /// fire-and-forget retry runs once in the background. - /// - /// Closing also invalidates the `AsyncResultHandle`s returned by - /// `awaitResult()`: their `fetchNextBatch()` then rejects with - /// `InvalidStatementHandle`, so finish fetching first. #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); @@ -466,14 +391,23 @@ impl AsyncStatement { // lock-free `cancel()` short-circuits to InvalidStatementHandle // rather than firing a wire cancel on a closing statement. closed.store(true, Ordering::Release); - // Release everything that holds the session when this scope - // ends, even if the close RPC fails or panics: JS may keep this - // object (and its result handles) reachable long after close. - let _release = CloseRelease { canceller, results }; let outcome = ExecutedAsyncStatement::close(&mut inner_state.executed_async) .await .map_err(napi_err_from_kernel); - drop(inner_state); + // Release what holds the session, so JS references to closed + // handles don't keep it (and the host's telemetry client) alive. + // A stream held by an in-flight fetch is left; close doesn't wait. + canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + let slots = + std::mem::take(&mut *results.lock().unwrap_or_else(PoisonError::into_inner)); + for slot in slots.iter().filter_map(Weak::upgrade) { + if let Ok(mut stream) = slot.try_lock() { + stream.take(); + } + } outcome }) .await @@ -517,41 +451,12 @@ impl Drop for AsyncStatement { /// post-close contract. #[napi] pub struct AsyncResultHandle { - /// Emptied when the parent `AsyncStatement` closes; fetching after - /// that returns `InvalidStatementHandle`. + /// Emptied by the parent's `close()`, unless a fetch holds it then. inner: Arc, schema: SchemaRef, statement_id: String, } -/// Pull one batch from `stream` and encode it as an Arrow IPC payload. -async fn next_ipc_batch( - stream: &mut ResultStream, - schema: &SchemaRef, -) -> napi::Result> { - let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; - let Some(batch) = maybe_batch else { - return Ok(None); - }; - let record_batch = match batch { - ResultBatch::Arrow(rb) => rb, - _ => { - 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(), - })) -} - #[napi] impl AsyncResultHandle { /// Server-issued statement id. Cached at construction; readable @@ -568,21 +473,36 @@ impl AsyncResultHandle { /// message), suitable for handing to `apache-arrow`'s /// `RecordBatchReader`. Byte-identical to the sync /// `Statement.fetchNextBatch()` payload for the same query. - /// Rejects with `KernelError(InvalidStatementHandle)` once the - /// parent `AsyncStatement` has been closed. #[napi] pub async fn fetch_next_batch(&self) -> napi::Result> { let inner = Arc::clone(&self.inner); let schema = self.schema.clone(); guarded(async move { - let mut guard = inner.stream.lock().await; - if inner.closed.load(Ordering::Acquire) { - guard.take(); - } + let mut guard = inner.lock().await; let stream = guard .as_mut() .ok_or_else(|| closed_err("AsyncResultHandle"))?; - next_ipc_batch(stream, &schema).await + let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; + let Some(batch) = maybe_batch else { + return Ok(None); + }; + let record_batch = match batch { + ResultBatch::Arrow(rb) => rb, + _ => { + 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 } @@ -811,50 +731,12 @@ mod tests { .expect("submit"); let result = statement.await_result().await.expect("await result"); // Hold the stream the way an in-flight `fetchNextBatch()` does. - let in_flight = result.inner.stream.lock().await; + let in_flight = result.inner.lock().await; tokio::time::timeout(Duration::from_secs(5), statement.close()) .await .expect("close must not wait for an in-flight fetch") .expect("close statement"); drop(in_flight); - // Released once the fetch returns, without relying on another fetch. - tokio::time::timeout(Duration::from_secs(5), async { - while result.inner.stream.lock().await.is_some() { - tokio::task::yield_now().await; - } - }) - .await - .expect("the stream must be dropped once the in-flight fetch returns"); - let err = result - .fetch_next_batch() - .await - .err() - .expect("fetching after the parent closed must fail"); - assert!(err.reason.contains("AsyncResultHandle already closed")); - connection.close().await.expect("close session"); - } - - #[tokio::test] - async fn fetch_after_close_fails_before_the_release_task_runs() { - let server = lease_server().await; - let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; - let statement = connection - .submit_statement("SELECT 1 AS n".into(), None) - .await - .expect("submit"); - let result = statement.await_result().await.expect("await result"); - let in_flight = result.inner.stream.lock().await; - statement.close().await.expect("close statement"); - drop(in_flight); - // The current-thread runtime hasn't polled the spawned release yet, - // so only the closed flag makes this fetch fail. - let err = result - .fetch_next_batch() - .await - .err() - .expect("fetching after the parent closed must fail"); - assert!(err.reason.contains("AsyncResultHandle already closed")); - assert!(result.inner.stream.lock().await.is_none()); connection.close().await.expect("close session"); } @@ -881,74 +763,7 @@ mod tests { .await .expect_err("the close RPC must fail"); assert!(statement.canceller.lock().unwrap().is_none()); - assert!(result.inner.stream.lock().await.is_none()); - connection.close().await.expect("close session"); - } - - #[tokio::test] - async fn release_outside_a_runtime_does_not_panic() { - let server = lease_server().await; - let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; - let statement = connection - .submit_statement("SELECT 1 AS n".into(), None) - .await - .expect("submit"); - let result = statement.await_result().await.expect("await result"); - let in_flight = result.inner.stream.lock().await; - let slot = Arc::clone(&result.inner); - std::thread::spawn(move || slot.release()) - .join() - .expect("releasing a busy slot outside a runtime must not panic"); - drop(in_flight); - let err = result - .fetch_next_batch() - .await - .err() - .expect("fetching after release must fail"); - assert!(err.reason.contains("AsyncResultHandle already closed")); - assert!(result.inner.stream.lock().await.is_none()); - statement.close().await.expect("close statement"); - connection.close().await.expect("close session"); - } - - fn panicking_close_rpc() -> napi::Result<()> { - panic!("close RPC panicked") - } - - /// Covers `CloseRelease` on unwind only; a panic can't be injected into - /// the kernel close RPC, so `close()`'s use of the guard isn't driven here. - #[tokio::test] - async fn close_release_guard_releases_on_unwind() { - let server = lease_server().await; - let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; - let statement = connection - .submit_statement("SELECT 1 AS n".into(), None) - .await - .expect("submit"); - let result = statement.await_result().await.expect("await result"); - // A busy slot makes the release spawn its task during the unwind. - let in_flight = result.inner.stream.lock().await; - let release = CloseRelease { - canceller: Arc::clone(&statement.canceller), - results: Arc::clone(&statement.results), - }; - let err = guarded(async move { - let _release = release; - panicking_close_rpc() - }) - .await - .expect_err("the panic must surface as an error"); - assert!(err.reason.contains("close RPC panicked")); - assert!(statement.canceller.lock().unwrap().is_none()); - drop(in_flight); - tokio::time::timeout(Duration::from_secs(5), async { - while result.inner.stream.lock().await.is_some() { - tokio::task::yield_now().await; - } - }) - .await - .expect("the stream must be dropped after a panicking close"); - statement.close().await.expect("close statement"); + assert!(result.inner.lock().await.is_none()); connection.close().await.expect("close session"); } } From 24032253370a21f959e36e493e22abb50030b969 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 16 Nov 2026 02:03:06 +0000 Subject: [PATCH 9/9] docs(napi): note that AsyncStatement.close() invalidates result handles State the user-facing change on close() and fetchNextBatch(), and mirror it in index.d.ts. A handle that was mid-fetch at close is left as before. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/index.d.ts | 6 ++++++ napi/src/async_statement.rs | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/napi/index.d.ts b/napi/index.d.ts index bcb54502..064f856d 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -853,6 +853,10 @@ export declare class AsyncStatement { * closed-handle short-circuit and returns `Ok(())` without * re-attempting the wire call. The kernel's own `Drop` * fire-and-forget retry runs once in the background. + * + * Also invalidates the handles `awaitResult()` returned: their + * `fetchNextBatch()` then rejects with `InvalidStatementHandle`, + * unless a fetch was in progress when `close()` ran. */ close(): Promise } @@ -887,6 +891,8 @@ export declare class AsyncResultHandle { * message), suitable for handing to `apache-arrow`'s * `RecordBatchReader`. Byte-identical to the sync * `Statement.fetchNextBatch()` payload for the same query. + * Rejects with `KernelError(InvalidStatementHandle)` after the + * parent `AsyncStatement` is closed (see `AsyncStatement.close()`). */ fetchNextBatch(): Promise /** diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 4cf05f58..df416254 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -373,6 +373,10 @@ impl AsyncStatement { /// closed-handle short-circuit and returns `Ok(())` without /// re-attempting the wire call. The kernel's own `Drop` /// fire-and-forget retry runs once in the background. + /// + /// Also invalidates the handles `awaitResult()` returned: their + /// `fetchNextBatch()` then rejects with `InvalidStatementHandle`, + /// unless a fetch was in progress when `close()` ran. #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); @@ -473,6 +477,8 @@ impl AsyncResultHandle { /// message), suitable for handing to `apache-arrow`'s /// `RecordBatchReader`. Byte-identical to the sync /// `Statement.fetchNextBatch()` payload for the same query. + /// Rejects with `KernelError(InvalidStatementHandle)` after the + /// parent `AsyncStatement` is closed (see `AsyncStatement.close()`). #[napi] pub async fn fetch_next_batch(&self) -> napi::Result> { let inner = Arc::clone(&self.inner);