diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 8597f31e..d5ca462e 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`, unless a fetch was using the stream when `close()` ran. + --- *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/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 f62d49c4..df416254 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -54,7 +54,7 @@ //! fire-and-forget cleanup behaves consistently. 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 +88,9 @@ fn closed_err(what: &str) -> napi::Error { // ───────────────────────── AsyncStatement ───────────────────────── +/// 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 /// the parent kernel `Statement` alive so its `Drop` (which @@ -130,8 +133,11 @@ 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. Taken by `close()`: it holds the session. + canceller: Arc>>, + /// 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 /// explicit close still surfaces `InvalidStatementHandle` without @@ -164,7 +170,8 @@ impl AsyncStatement { _parent: parent, executed_async, }))), - canceller, + canceller: Arc::new(std::sync::Mutex::new(Some(canceller))), + results: Arc::default(), closed: Arc::new(AtomicBool::new(false)), statement_id, } @@ -294,6 +301,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 +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 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: Arc::new(Mutex::new(Some(stream))), + inner: stream, schema, statement_id, }) @@ -342,7 +356,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 } @@ -352,10 +373,16 @@ 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); 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 +395,24 @@ 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 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 } @@ -413,10 +455,8 @@ 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 by the parent's `close()`, unless a fetch holds it then. + inner: Arc, schema: SchemaRef, statement_id: String, } @@ -437,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); @@ -493,6 +535,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 +567,209 @@ 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; + } + + #[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.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); + 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.lock().await.is_none()); + connection.close().await.expect("close session"); + } }