diff --git a/napi/src/database.rs b/napi/src/database.rs index cfe3cb0f..35ddd1c8 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -34,7 +34,7 @@ use napi::bindgen_prelude::Buffer; type Buffer = Vec; use databricks_sql_kernel::{ - AuthConfig, DefaultOpts, HttpConfig, ResultConfig, Session, TlsConfig, + AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ResultConfig, Session, TlsConfig, }; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. @@ -56,6 +56,27 @@ use crate::error::napi_err_from_kernel; use crate::runtime; use crate::util::guarded; +/// Default U2M OAuth client id for the **Node** binding. +/// +/// Matches the standalone Node driver's +/// `DatabricksOAuthManager.defaultClientId` (`databricks-sql-connector`) +/// rather than the kernel's bare-Rust fallback (`databricks-cli`), for +/// two reasons: +/// +/// 1. **OAuth app identity** — the napi path registers as the same +/// OAuth app the standalone Node driver does, so admin-side consent +/// screens / SSO policies attribute it consistently. +/// 2. **Per-binding cache-key isolation** — the kernel's U2M token +/// cache is keyed on `{host, client_id, scopes}`; a distinct client +/// id keeps the napi cache from colliding with the pyo3 (Python, +/// `databricks-sql-python`) binding's. +/// +/// This does NOT share a token-cache *entry* with databricks-sql-nodejs +/// — the kernel writes to its own `~/.config/databricks-sql-kernel/ +/// oauth/` directory. The alignment is of the OAuth app identity, not +/// the on-disk cache. +const NODE_OAUTH_CLIENT_ID: &str = "databricks-sql-connector"; + /// Authentication mode selector crossing the napi boundary. The string /// literals are what napi-rs emits from this `#[napi(string_enum)]` — the /// NodeJS SEA adapter (`SeaAuth`) matches them verbatim (`'Pat'`, @@ -83,8 +104,8 @@ pub enum AuthMode { /// Authentication is selected by `authMode` (default [`AuthMode::Pat`]): /// - `Pat` — `token` required. /// - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. -/// - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional (kernel -/// defaults to the `databricks-cli` client on port 8020). +/// - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional +/// (defaults to the `databricks-sql-connector` client on port 8020). /// /// Catalog / schema / sessionConf are applied once at session creation /// and remain in effect for every statement run on the resulting @@ -110,7 +131,7 @@ pub struct ConnectionOptions { /// [`AuthMode::Pat`]; ignored otherwise. pub token: Option, /// OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for - /// [`AuthMode::OAuthU2m`] (kernel defaults to `databricks-cli`). + /// [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). pub oauth_client_id: Option, /// OAuth client secret. Required for [`AuthMode::OAuthM2m`]. pub oauth_client_secret: Option, @@ -208,15 +229,39 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { None, ) .map_err(napi_err_from_kernel), - // All U2M fields are optional — the kernel fills `databricks-cli` - // / port 8020 / default scopes when omitted. - AuthMode::OAuthU2m => Ok(AuthConfig::oauth_u2m( - options.oauth_client_id.clone(), - options.oauth_redirect_port, - options.oauth_scopes.clone(), - None, - None, - )), + // All U2M fields are optional. Default the OAuth client_id to + // the Node driver's own registered client + // (`databricks-sql-connector`, matching the standalone + // databricks-sql-nodejs `DatabricksOAuthManager.defaultClientId`) + // rather than the kernel's bare-Rust `databricks-cli` fallback, + // so the napi path presents the same OAuth app identity as the + // standalone Node driver and keeps a cache key distinct from the + // pyo3 (Python) binding. Port 8020 / default scopes are still + // filled by the kernel when omitted. + AuthMode::OAuthU2m => { + // Reject an explicit empty client_id (parity with pyo3): + // an empty string would bypass the default and bind an empty + // OAuth client, surfacing as an opaque server error. Omit + // the field to get the `databricks-sql-connector` default. + if matches!(options.oauth_client_id.as_deref(), Some("")) { + return Err(napi_err_from_kernel( + KernelError::invalid_argument().message( + "oauthClientId must be non-empty when set; omit it to use the \ + default 'databricks-sql-connector'", + ), + )); + } + Ok(AuthConfig::oauth_u2m( + options + .oauth_client_id + .clone() + .or_else(|| Some(NODE_OAUTH_CLIENT_ID.to_owned())), + options.oauth_redirect_port, + options.oauth_scopes.clone(), + None, + None, + )) + } } } @@ -436,14 +481,17 @@ mod tests { fn u2m_fields_are_all_optional() { let mut o = base(); o.auth_mode = Some(AuthMode::OAuthU2m); - // Bare U2M: kernel fills databricks-cli / port 8020 / default scopes. + // Bare U2M: the napi binding defaults client_id to + // `databricks-sql-connector` (matching the standalone Node + // driver), NOT the kernel's bare `databricks-cli`. Port 8020 / + // default scopes are still filled by the kernel. match build_auth_config(&o).unwrap() { AuthConfig::OAuthU2M { client_id, redirect_port, .. } => { - assert!(client_id.is_none()); + assert_eq!(client_id.as_deref(), Some("databricks-sql-connector")); assert!(redirect_port.is_none()); } other => panic!("expected OAuthU2M, got {other:?}"), @@ -464,6 +512,17 @@ mod tests { } } + #[test] + fn u2m_rejects_explicit_empty_client_id() { + // Parity with pyo3: an explicit empty oauthClientId is rejected + // (it would bind an empty client and surface an opaque server + // error), rather than silently falling back to the default. + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthU2m); + o.oauth_client_id = Some(String::new()); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "oauthClientId"); + } + #[test] fn tls_defaults_to_secure() { // No `check_server_certificate` ⇒ secure by default: strict chain + diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 13118901..9c87e887 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -80,15 +80,17 @@ enum AnyInner { } impl AnyInner { - /// Borrow the underlying result stream regardless of variant. The - /// executed-statement variant delegates to its - /// `ExecutedStatement::result_stream_mut`; the metadata variant - /// returns the bare `ResultStream` directly. Used by - /// `fetch_next_batch` to share one streaming path across both. - fn result_stream_mut(&mut self) -> &mut ResultStream { + /// Pull the next batch, variant-aware so the executed path gets the + /// kernel's **auto-close-on-drain** (fire-and-forget CloseStatement + /// once the stream is exhausted, after all lazy CloudFetch link + /// fetches). The metadata variant uses the bare stream's + /// `next_batch` — it carries its own close-on-drop guard + /// (`ResultStream::from_reader_with_close`), so it must NOT route + /// through the executed auto-close. + async fn next_batch(&mut self) -> databricks_sql_kernel::Result> { match self { - AnyInner::Executed(s) => s.executed.result_stream_mut(), - AnyInner::Metadata(rs) => rs, + AnyInner::Executed(s) => s.executed.next_batch().await, + AnyInner::Metadata(rs) => rs.next_batch().await, } } } @@ -328,15 +330,17 @@ impl Statement { guarded(async move { let mut guard = inner.lock().await; let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?; - // `result_stream_mut` returns `&mut ResultStream` for both - // variants — the executed-path borrows from its - // `ExecutedStatement`, the metadata-path borrows from its - // bare `ResultStream`. The IPC schema header serialised - // into every batch payload comes from the cached - // `self.schema` captured outside the lock (see method - // start), so no need to re-fetch from the stream. - let stream = inner_state.result_stream_mut(); - let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; + // The IPC schema header serialised into every batch payload + // comes from the cached `self.schema` captured outside the + // lock (see method start), so no need to re-fetch from the + // stream. + // Variant-aware: the executed path auto-closes the server + // statement on drain; the metadata path uses its own + // close-on-drop guard. (See `AnyInner::next_batch`.) + let maybe_batch = inner_state + .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(()). diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 80258c89..704da752 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -54,6 +54,28 @@ pub(crate) struct OAuthParams { pub callback_timeout_secs: Option, } +/// Default U2M OAuth client id for the **Python** binding. +/// +/// Matches the standalone Thrift connector's `PYSQL_OAUTH_CLIENT_ID` +/// (`databricks-sql-python`) rather than the kernel's bare-Rust +/// fallback (`databricks-cli`). Two reasons: +/// +/// 1. **OAuth app identity** — the `use_kernel=True` path registers as +/// the same OAuth app the standalone Python connector does, so +/// admin-side consent screens / SSO policies attribute it +/// consistently (not as the generic CLI client). +/// 2. **Per-binding cache-key isolation** — the kernel's U2M token +/// cache is keyed on `{host, client_id, scopes}`. Distinct client +/// ids keep the pyo3 (Python) and napi (Node, +/// `databricks-sql-connector`) caches from colliding. +/// +/// Note: this does NOT share a token-cache *entry* with the standalone +/// Thrift connector — the kernel writes to its own +/// `~/.config/databricks-sql-kernel/oauth/` directory, and the Thrift +/// connector caches U2M tokens in-memory only. The alignment is of the +/// OAuth app identity, not the on-disk cache. +const PYSQL_OAUTH_CLIENT_ID: &str = "databricks-sql-python"; + /// Build a kernel `AuthConfig` from the Python kwargs the `Session` /// constructor accepts. /// @@ -117,7 +139,7 @@ fn build_auth_config_inner( if matches!(oauth.client_id.as_deref(), Some("")) { return Err( "auth_type='oauth-u2m' client_id must be non-empty when set; \ - omit it to use the default 'databricks-cli'" + omit it to use the default 'databricks-sql-python'" .to_owned(), ); } @@ -136,7 +158,20 @@ fn build_auth_config_inner( ); } Ok(AuthConfig::OAuthU2M { - client_id: oauth.client_id, + // Default the U2M OAuth client to the Python connector's + // own registered client (`databricks-sql-python`), NOT + // the kernel's bare-Rust fallback (`databricks-cli`). + // This matches the standalone Thrift connector + // (`PYSQL_OAUTH_CLIENT_ID` in databricks-sql-python's + // auth.py) so a user gets the same OAuth app identity — + // and the same SSO token cache entry — whether they use + // the Thrift backend or `use_kernel=True`. It also keeps + // the kernel's per-{host,client_id,scopes} token cache + // distinct from the napi (Node) binding's, which defaults + // to its own client. + client_id: oauth + .client_id + .or_else(|| Some(PYSQL_OAUTH_CLIENT_ID.to_owned())), redirect_port: oauth.redirect_port, scopes: oauth.scopes, token_url_override: oauth.token_url, @@ -250,8 +285,11 @@ mod tests { } #[test] - fn u2m_builds_with_all_defaults_none() { - // U2M takes no mandatory fields; the kernel fills defaults. + fn u2m_defaults_client_id_to_python_connector() { + // U2M takes no mandatory fields. The Python binding defaults the + // OAuth client_id to `databricks-sql-python` (NOT the kernel's + // bare `databricks-cli`) so it matches the standalone Thrift + // connector and the napi binding gets a distinct cache key. let cfg = build_auth_config_inner("oauth-u2m", None, OAuthParams::default()).unwrap(); match cfg { AuthConfig::OAuthU2M { @@ -261,7 +299,7 @@ mod tests { token_url_override, callback_timeout, } => { - assert!(client_id.is_none()); + assert_eq!(client_id.as_deref(), Some("databricks-sql-python")); assert!(redirect_port.is_none()); assert!(scopes.is_none()); assert!(token_url_override.is_none()); @@ -271,6 +309,25 @@ mod tests { } } + #[test] + fn u2m_explicit_client_id_overrides_default() { + let cfg = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + client_id: Some("my-custom-app".to_string()), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthU2M { client_id, .. } => { + assert_eq!(client_id.as_deref(), Some("my-custom-app")); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + #[test] fn u2m_maps_callback_timeout_secs_to_duration() { let cfg = build_auth_config_inner( diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 0ae41fb8..9e7d859c 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -23,7 +23,7 @@ use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; -use databricks_sql_kernel::{Error, Result, ResultBatch, ResultStream}; +use databricks_sql_kernel::{Error, ExecutedStatement, Result, ResultBatch, ResultStream}; use pyo3::prelude::*; use std::sync::Arc; use tokio::runtime::Runtime; @@ -65,6 +65,46 @@ pub(crate) fn drain(runtime: &Runtime, stream: &mut ResultStream) -> Result Result> { + runtime.block_on(async { + match exec.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), + Some(_) => Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")), + None => Ok(None), + } + }) +} + +/// Like [`drain`], but drives the `ExecutedStatement` so auto-close-on- +/// drain fires once the stream is exhausted. Used by +/// `ExecutedStatement.fetch_all_arrow`. +pub(crate) fn drain_exec( + runtime: &Runtime, + exec: &mut ExecutedStatement, +) -> Result> { + runtime.block_on(async { + let mut out = Vec::new(); + loop { + match exec.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), + Some(_) => { + return Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")); + } + None => break, + } + } + Ok(out) + }) +} + /// Wrap a Vec of `RecordBatch` into a `pyarrow.Table`. Centralised /// so both `ExecutedStatement.fetch_all_arrow` and /// `ResultStream.fetch_all_arrow` produce identical Python objects. diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index cb831b2e..40a2b24c 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -324,10 +324,10 @@ impl ExecutedStatement { return Ok(None); } let runtime = inner.runtime.clone(); - let batch = run_sync_kernel!( - py, - fetch::next_batch(&runtime, inner.exec.result_stream_mut()) - )?; + // `next_batch_exec` drives the ExecutedStatement so the kernel's + // auto-close-on-drain fires the server CloseStatement once the + // stream is exhausted (after all lazy CloudFetch link fetches). + let batch = run_sync_kernel!(py, fetch::next_batch_exec(&runtime, &mut inner.exec))?; match batch { Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { @@ -341,7 +341,7 @@ impl ExecutedStatement { fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = alive_mut!(self, "ExecutedStatement"); let runtime = inner.runtime.clone(); - let batches = run_sync_kernel!(py, fetch::drain(&runtime, inner.exec.result_stream_mut()))?; + let batches = run_sync_kernel!(py, fetch::drain_exec(&runtime, &mut inner.exec))?; inner.exhausted = true; fetch::batches_to_pyarrow_table(py, &self.schema, batches) } @@ -351,6 +351,15 @@ impl ExecutedStatement { /// or dropped. fn cancel(&mut self, py: Python<'_>) -> PyResult<()> { let inner = alive_mut!(self, "ExecutedStatement"); + // Short-circuit if the stream was fully drained: the kernel's + // auto-close-on-drain already closed the server statement, so a + // cancel RPC here would hit an already-terminal/closed statement + // (a wasted round-trip, benign error at worst). Matches the + // napi binding's `finished`-flag short-circuit and the JDBC + // cancel-after-completion no-op contract. + if inner.exhausted { + return Ok(()); + } let runtime = inner.runtime.clone(); run_kernel!(py, runtime, inner.exec.cancel())?; Ok(()) diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 963397c3..1ca91105 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -376,11 +376,26 @@ impl AuthProvider for AuthorizationCodeProvider { return Ok(token); } Err(e) => { - crate::klog::warn!( - "Token refresh failed, falling back to browser flow: {}", - e - ); - // Fall through to browser flow + // We HAD a refresh token and it failed + // (expired / revoked / invalid_grant). + // Do NOT fall through to the interactive + // browser flow: in a headless / long-lived + // server context (no browser, no human) + // that would block this query thread for + // the full callback timeout (~120s) and + // then fail opaquely. Fail fast with an + // auth error instead — matching the Thrift + // connector, whose mid-session refresh path + // (oauth.py check_and_refresh_access_token) + // raises and never launches a browser. The + // browser flow remains reachable only for a + // genuine first connect (no cached token), + // below. + crate::klog::warn!("OAuth token refresh failed: {}", e); + return Err(Error::unauthenticated().message(format!( + "OAuth token refresh failed (refresh token expired or \ + revoked); re-authentication required: {e}" + ))); } } } diff --git a/src/client/sea.rs b/src/client/sea.rs index 4e7a0b31..4e82af78 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -313,7 +313,14 @@ impl SeaRestTransport { )) } StatementState::Canceled => { - let error = Error::invalid_state() + // `cancelled()` (ErrorCode::Cancelled), not invalid_state: + // a server-side cancel (admin cancel, warehouse eviction, + // another client's cancel) is an operational/cancelled + // condition, not a caller-argument error. The connector + // maps "Cancelled" -> OperationalError (the DatabaseError + // family Thrift uses), whereas invalid_state collapses to + // InvalidArgument -> ProgrammingError (misleading "bad SQL"). + let error = Error::cancelled() .message("Statement was canceled") .with_query_id(&response.statement_id); StatementOutcome::Err(crate::kernel_error::carry_extended_status( diff --git a/src/lib.rs b/src/lib.rs index fa7db7bb..10cb7b73 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -62,12 +62,18 @@ //! .param(1, TypedValue::Int64(42))?; //! //! let mut exec = stmt.execute().await?; -//! while let Some(_batch) = exec.result_stream_mut().next_batch().await? { -//! while let Some(_row) = exec.result_stream_mut().next_row_in_batch() { -//! // process row -//! } +//! // Drive the result through `exec.next_batch()` (not +//! // `result_stream_mut().next_batch()`): it auto-closes the server +//! // statement when the stream is fully drained, after every lazy +//! // CloudFetch chunk-link fetch — so paginated-link results stay +//! // valid through the last batch. +//! while let Some(_batch) = exec.next_batch().await? { +//! // process the Arrow batch (`ResultBatch::Arrow(rb)`); per-row +//! // access is available via `exec.result_stream_mut() +//! // .next_row_in_batch()` between `next_batch` calls. //! } -//! exec.close().await?; +//! // Optional: `exec.close().await?` closes early if you stop before +//! // the stream is drained; a fully-drained stream auto-closes. //! ``` // === TLS feature wiring guard === diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index b2c6bf98..a4776092 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -285,12 +285,18 @@ impl Metadata { .transport() .list_catalogs(self.session.session_id()) .await?; + let stmt_id = raw.statement_id.clone(); let reshaped = ThriftReshapingReader::new( raw.reader, GET_CATALOGS_SCHEMA.clone(), Box::new(thrift_shape::reshape_catalogs), ); - ResultStream::from_reader(Box::new(reshaped)).await + ResultStream::from_reader_with_close( + Box::new(reshaped), + Arc::clone(&self.session), + stmt_id, + ) + .await } .instrument(span) .await @@ -323,12 +329,18 @@ impl Metadata { Ok(r) => r, Err(e) => return not_found_or(e, GET_SCHEMAS_SCHEMA.clone(), Err).await, }; + let stmt_id = raw.statement_id.clone(); let reshaped = ThriftReshapingReader::new( raw.reader, GET_SCHEMAS_SCHEMA.clone(), Box::new(move |b| thrift_shape::reshape_schemas(b, catalog_str.as_deref())), ); - ResultStream::from_reader(Box::new(reshaped)).await + ResultStream::from_reader_with_close( + Box::new(reshaped), + Arc::clone(&self.session), + stmt_id, + ) + .await } .instrument(span) .await @@ -375,6 +387,7 @@ impl Metadata { Ok(r) => r, Err(e) => return not_found_or(e, GET_TABLES_SCHEMA.clone(), Err).await, }; + let stmt_id = raw.statement_id.clone(); let reshaped = ThriftReshapingReader::new( raw.reader, GET_TABLES_SCHEMA.clone(), @@ -385,7 +398,12 @@ impl Metadata { thrift_shape::reshape_tables(b, catalog_str.as_deref(), types_ref.as_deref()) }), ); - ResultStream::from_reader(Box::new(reshaped)).await + ResultStream::from_reader_with_close( + Box::new(reshaped), + Arc::clone(&self.session), + stmt_id, + ) + .await } .instrument(span) .await @@ -440,12 +458,18 @@ impl Metadata { Ok(r) => r, Err(e) => return not_found_or(e, GET_COLUMNS_SCHEMA.clone(), Err).await, }; + let stmt_id = raw.statement_id.clone(); let reshaped = ThriftReshapingReader::new( raw.reader, GET_COLUMNS_SCHEMA.clone(), Box::new(move |b| thrift_shape::reshape_columns(b, catalog_str.as_deref())), ); - ResultStream::from_reader(Box::new(reshaped)).await + ResultStream::from_reader_with_close( + Box::new(reshaped), + Arc::clone(&self.session), + stmt_id, + ) + .await } .instrument(span) .await @@ -490,7 +514,9 @@ impl Metadata { table.as_str(), ) .await?; - ResultStream::from_reader(raw.reader).await + let stmt_id = raw.statement_id.clone(); + ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id) + .await } .instrument(span) .await @@ -540,7 +566,9 @@ impl Metadata { foreign_table.as_str(), ) .await?; - ResultStream::from_reader(raw.reader).await + let stmt_id = raw.statement_id.clone(); + ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id) + .await } .instrument(span) .await @@ -570,7 +598,9 @@ impl Metadata { name_pattern.as_ref().map(|p| p.as_str()), ) .await?; - ResultStream::from_reader(raw.reader).await + let stmt_id = raw.statement_id.clone(); + ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id) + .await } .instrument(span) .await @@ -599,7 +629,9 @@ impl Metadata { name_pattern.as_ref().map(|p| p.as_str()), ) .await?; - ResultStream::from_reader(raw.reader).await + let stmt_id = raw.statement_id.clone(); + ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id) + .await } .instrument(span) .await diff --git a/src/result_stream.rs b/src/result_stream.rs index 4a870c16..6fdd8501 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -47,6 +47,7 @@ use crate::kernel_error::{Error, Result}; use crate::reader::ResultReader; +use crate::session::SessionInner; use arrow_array::cast::AsArray; use arrow_array::types::{ Date32Type, Date64Type, Decimal128Type, Decimal256Type, DecimalType, Float32Type, Float64Type, @@ -463,6 +464,46 @@ pub struct ResultStream { /// call on readers whose `next_batch` is non-trivial (CloudFetch /// in particular checks state and may take a runtime tick). exhausted: bool, + + /// Optional fire-and-forget `CloseStatement` on Drop. + /// + /// `Some` only for the **metadata** path (`Metadata::list_*`), + /// which produces a bare `ResultStream` with no owning + /// `ExecutedStatement` to reap the server-side statement. Without + /// this, every metadata call leaked a server statement until the + /// session closed. The data path leaves this `None` — there the + /// owning `ExecutedStatement` (or its `Drop`) issues the close, so + /// a second guard here would double-fire. + close_guard: Option, +} + +/// Fire-and-forget `CloseStatement`-on-Drop for a server statement that +/// no other handle owns (the metadata path). Mirrors the +/// `ExecutedStatement` Drop cleanup, scoped to the bare-stream case. +struct StatementCloseGuard { + session: Arc, + statement_id: String, +} + +impl Drop for StatementCloseGuard { + fn drop(&mut self) { + let transport = Arc::clone(self.session.transport()); + let runtime = self.session.runtime_handle().clone(); + let stmt_id = std::mem::take(&mut self.statement_id); + if stmt_id.is_empty() { + return; + } + runtime.spawn(async move { + if let Err(e) = transport.close_statement(&stmt_id).await { + crate::klog::warn!( + "fire-and-forget close_statement for metadata stream {} failed: {} \ + (server reclaims on session close)", + stmt_id, + e + ); + } + }); + } } impl ResultStream { @@ -487,9 +528,37 @@ impl ResultStream { current: None, current_row_idx: 0, exhausted: false, + close_guard: None, }) } + /// Like [`from_reader`](Self::from_reader), but the stream owns a + /// fire-and-forget `CloseStatement` for `statement_id`, fired when + /// the stream is dropped. + /// + /// For the **metadata** path only: `Metadata::list_*` returns a + /// bare `ResultStream` with no owning `ExecutedStatement`, so + /// nothing else reaps the server statement. The data path uses + /// `from_reader` (no guard) because `ExecutedStatement` owns the + /// close there. + pub(crate) async fn from_reader_with_close( + reader: Box, + session: Arc, + statement_id: String, + ) -> Result { + let mut stream = Self::from_reader(reader).await?; + // Skip the guard for an empty id (inline fast-path results the + // server already auto-closed) — nothing to reap, and an empty + // CloseStatement would be a wasted/invalid RPC. + if !statement_id.is_empty() { + stream.close_guard = Some(StatementCloseGuard { + session, + statement_id, + }); + } + Ok(stream) + } + /// Result schema. Available before any batches have been pulled. /// Returns a cheap-clone `Arc` so callers can hold the /// schema independently of the stream (the FFI layer needs this @@ -536,6 +605,18 @@ impl ResultStream { } } + /// The batch most recently buffered by + /// [`next_batch`](Self::next_batch), without advancing the stream + /// or doing any I/O. `None` before the first `next_batch` or after + /// end-of-stream. + /// + /// Used by [`ExecutedStatement::next_batch`](crate::statement::executed::ExecutedStatement::next_batch) + /// to re-borrow the just-fetched batch after a borrow-scoped + /// exhaustion check, so it can fire the auto-close on `None`. + pub fn current(&self) -> Option<&ResultBatch> { + self.current.as_ref() + } + /// Pull the next row from the currently-buffered batch. /// /// **Sync.** Walks within the batch the most recent @@ -567,15 +648,23 @@ impl ResultStream { /// Free client-side resources held by the stream — buffered /// chunks, the link prefetcher, in-flight downloaders. - /// Local-only; does not issue any server-side RPC. To cancel the - /// underlying statement, call `cancel()` on the executed handle. + /// + /// Usually local-only, **except for the metadata path**: a stream + /// built via [`from_reader_with_close`](Self::from_reader_with_close) + /// (`Metadata::list_*`) carries a close-on-drop guard that fires a + /// fire-and-forget `CloseStatement` for its server statement when + /// the stream drops. The data path (`from_reader`) issues no RPC + /// here — the owning `ExecutedStatement` reaps the statement + /// (auto-close-on-drain / its own `Drop`); to cancel a still-running + /// statement, call `cancel()` on the executed handle. /// /// Consuming `self` makes use-after-close a compile error. - /// `Drop` performs the same cleanup if `close` was never called - /// explicitly. + /// `Drop` performs the same cleanup (including the metadata guard's + /// close) if `close` was never called explicitly. pub fn close(self) { - // Drops `self` (and the wrapped reader / current batch). - // Background tasks owned by the reader stop on `Drop`. + // Drops `self` (and the wrapped reader / current batch / any + // metadata close-guard). Background tasks owned by the reader + // stop on `Drop`. } /// Consume the stream and yield **owned** `RecordBatch`es as a diff --git a/src/statement/executed.rs b/src/statement/executed.rs index b33a879c..e2481f03 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -30,7 +30,7 @@ use crate::kernel_error::Result; use crate::klog::warn; -use crate::result_stream::{ResultStream, SchemaRef}; +use crate::result_stream::{ResultBatch, ResultStream, SchemaRef}; use crate::session::SessionInner; use crate::statement::handle::ExecutedStatementHandle; use crate::statement::validity::ValidityFlag; @@ -111,6 +111,69 @@ impl ExecutedStatement { &mut self.result_stream } + /// Pull the next result batch, **auto-closing the server statement + /// when the stream is exhausted**. + /// + /// Identical to `result_stream_mut().next_batch()` except that the + /// first time it observes end-of-stream (`Ok(None)`), it spawns a + /// fire-and-forget `CloseStatement` (guarded by the shared `closed` + /// flag, so `Drop` / explicit `close()` never double-fire). + /// + /// Why this matters: for a large CloudFetch result whose chunk + /// *links* are paginated (`all_fetched=false`), the reader fetches + /// later links lazily via `get_result_chunks` against the live + /// server statement *during consumption*. Closing the statement + /// before the stream is drained (as a premature connector + /// `Statement::close()` did) breaks those lazy fetches. Closing + /// *here*, only once `next_batch` has returned `None`, guarantees + /// every lazy link fetch has already completed — so the close is + /// always safe, and the connector no longer needs to close the + /// statement on the sync path at all. + /// + /// Bindings should call this instead of + /// `result_stream_mut().next_batch()` so the auto-close fires. + pub async fn next_batch(&mut self) -> Result> { + // NLL: when `next_batch` yields `Some`, the returned reference + // keeps `self.result_stream` borrowed, so we return it directly. + // When it yields `None`, that borrow has ended — so we can read + // the other `self` fields to fire the auto-close. We branch on a + // cheap `is_some()` check (not the reference itself) to let the + // borrow end before the `None` arm touches `self`. + if self.result_stream.next_batch().await?.is_some() { + // Re-borrow and return the batch the stream just buffered. + // `current()` returns the same already-fetched batch without + // advancing the stream. + return Ok(self.result_stream.current()); + } + // End-of-stream: every lazy link fetch has completed, so the + // server statement is safe to close. + self.spawn_close_if_open(); + Ok(None) + } + + /// Spawn a fire-and-forget `CloseStatement` unless the statement is + /// already closed (`closed` flag). Shared by [`Self::next_batch`]'s + /// auto-close-on-drain and `Drop`. The `swap` makes whichever fires + /// first win; the other observes `closed=true` and skips. + fn spawn_close_if_open(&self) { + if self.closed.swap(true, Ordering::AcqRel) { + return; + } + let transport = Arc::clone(self.session.transport()); + let runtime = self.session.runtime_handle().clone(); + let stmt_id = self.statement_id.clone(); + runtime.spawn(async move { + if let Err(e) = transport.close_statement(&stmt_id).await { + warn!( + statement_id = %stmt_id, + error = %e, + "fire-and-forget close_statement failed; \ + server-side resource reclaimed when the session closes" + ); + } + }); + } + /// Rows modified by the statement (UPDATE / INSERT / DELETE / /// MERGE). Absent for SELECT and on warehouses that don't surface /// the counter. @@ -246,31 +309,12 @@ impl ExecutedStatementHandle for ExecutedStatement { impl Drop for ExecutedStatement { fn drop(&mut self) { - // `swap` (not `load`) so the shared `closed` flag — held by the - // parent `Statement::last_closed` — reflects that Drop is now - // handling cleanup. Without this, a `drop(executed) → execute() - // again` sequence would have `invalidate_prior` fire a redundant - // `CloseStatement` racing the one we're about to spawn. The - // server is idempotent so it's harmless, but a wasted RPC. - if self.closed.swap(true, Ordering::AcqRel) { - return; - } - // Fire-and-forget CloseStatement. Drop must not panic and - // we can't surface a failure here; the runtime keeps the - // background task alive until completion. Swallows errors - // by design. - let transport = Arc::clone(self.session.transport()); - let runtime = self.session.runtime_handle().clone(); - let stmt_id = self.statement_id.clone(); - runtime.spawn(async move { - if let Err(e) = transport.close_statement(&stmt_id).await { - warn!( - statement_id = %stmt_id, - error = %e, - "fire-and-forget close_statement on Drop failed; \ - server-side resource reclaimed when the session closes" - ); - } - }); + // Backstop for the not-fully-drained case (partial fetch / + // abandoned result / early error): if the stream was drained, + // `next_batch`'s auto-close already fired and flipped `closed`, + // so this is a no-op (the `swap` inside sees `closed=true`). + // Drop must not panic and can't surface failure — fire-and- + // forget; the runtime keeps the task alive until completion. + self.spawn_close_if_open(); } } diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 3b5e2ade..7458388c 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -410,8 +410,11 @@ impl ExecutedAsyncStatement { // the returned Error — mirrors the sync // `terminal_outcome::Canceled` arm so the // Cancelled-state envelope contract is - // identical across kernel handles. - let error = Error::invalid_state() + // identical across kernel handles. `cancelled()` + // (not invalid_state) so the connector maps it to + // OperationalError, not ProgrammingError — see the + // sync arm in client/sea.rs for the rationale. + let error = Error::cancelled() .message(format!("Statement {} was cancelled", self.statement_id)) .with_query_id(&self.statement_id); return Err(crate::kernel_error::carry_extended_status( diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index e94e9463..8ac92ad2 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -362,7 +362,7 @@ async fn await_result_propagates_failed_status() { } #[tokio::test] -async fn await_result_surfaces_cancelled_as_invalid_state() { +async fn await_result_surfaces_cancelled_as_cancelled_code() { let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; @@ -380,10 +380,11 @@ async fn await_result_surfaces_cancelled_as_invalid_state() { Ok(_) => panic!("await_result on CANCELED should error"), Err(e) => e, }; - // `Error::invalid_state()` currently maps to InvalidArgument - // until the ErrorCode taxonomy expansion (spec A8) ships - // `FailedPrecondition` / `InvalidState`. - assert_eq!(err.code, ErrorCode::InvalidArgument); + // A server-side CANCELLED is an operational/cancelled condition, + // not a caller-argument error — `Error::cancelled()` (ErrorCode:: + // Cancelled). The connector maps this to OperationalError, not the + // misleading ProgrammingError that InvalidArgument would yield. + assert_eq!(err.code, ErrorCode::Cancelled); assert!(err.message.contains("cancel"), "{}", err.message); } @@ -963,10 +964,9 @@ async fn async_await_result_cancelled_carries_extended_status_fields_onto_error( Ok(_) => panic!("await_result on CANCELED should error"), Err(e) => e, }; - // Cancelled maps to InvalidArgument per the kernel's invalid-state - // helper today; assert the message + extended fields rather than - // pinning the code (the categorisation may move under ErrorCode - // taxonomy expansion). + // A server-side CANCELLED surfaces as ErrorCode::Cancelled (the + // connector maps it to OperationalError, not ProgrammingError). + assert_eq!(err.code, ErrorCode::Cancelled); assert!( err.message.contains("cancelled"), "message should mention cancellation, got: {}",