From f257c1e86b309aff6d9b1818e44fe1fa0622cc8a Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Fri, 5 Jun 2026 19:33:15 +0000 Subject: [PATCH 1/8] =?UTF-8?q?feat(statement):=20add=20directResults=20ex?= =?UTF-8?q?ecute=20(execute=5Fdirect)=20=E2=80=94=20Thrift/JDBC=20model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Statement::execute_direct()` runs ExecuteStatement with a bounded server-side inline wait (omits `wait_timeout` so the server applies its ~10s default AND auto-closes on success) and returns WITHOUT the internal poll loop: - `DirectStatement::Completed(ExecutedStatement)` when the statement finished within the inline wait — result stream materialised inline, no extra GetStatementResult round-trip (identical to `execute()`'s fast path); - `DirectStatement::Running(ExecutedAsyncStatement)` when it did not — a poll/cancel handle (identical to `submit()`'s return) the caller drives. This is the directResults shape that Thrift / JDBC / Python `use_sea` use: fast queries come back terminal+inline, slow ones come back as a running handle. It gives consumers three properties the plain blocking `execute()` can't all have at once: - fire-and-forget DDL/DML commits (the server runs it inline during the POST, so a CREATE/INSERT with no fetch still lands); - `close()` is a clean release on a server-owned statement — no client-side drive-to-terminal ("close-drives"); - a long query stays cancellable via the running handle's statement id, which the POST response publishes (no mid-execute observer race). Additive: `execute()` and `submit()` are unchanged, so existing consumers are untouched. New transport method `execute_statement_direct` (call_execute_api + conditional reader, no `wait_for_completion`); `DirectOutcome` transport enum; `DirectStatement` re-exported from the crate root. Exposed on both bindings: napi `Connection.executeStatementDirect` (Either) and pyo3 `Statement.execute_direct` (ExecutedStatement | ExecutedAsyncStatement). Tests: cargo +stable fmt --all --check, cargo clippy --all-targets -D warnings clean; cargo test --lib 620 passed. Validated e2e via the Node and Python bindings against a live warehouse (CREATE commits, mid-run cancel, no close-drive, error-at-execute). Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 64 ++++++++++++++++ pyo3/src/statement.rs | 34 ++++++++- src/client/mod.rs | 2 +- src/client/sea.rs | 68 ++++++++++++++++- src/client/transport.rs | 32 ++++++++ src/lib.rs | 2 +- src/reader/cloudfetch/link_fetcher.rs | 8 ++ src/reader/mod.rs | 8 ++ src/statement/mod.rs | 2 +- src/statement/mutable.rs | 105 ++++++++++++++++++++++++++ 10 files changed, 318 insertions(+), 7 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index d9d17287..f5e7333b 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -370,6 +370,70 @@ impl Connection { .await } + /// directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + /// with a bounded server-side inline wait (`wait_timeout=10s`, + /// `on_wait_timeout=CONTINUE`) and returns WITHOUT polling past it: + /// + /// - a **`Statement`** (left arm) when the query finished within the inline + /// wait — terminal, result ready inline, `close()` is a clean release; + /// - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel + /// handle the caller drives (`status()` / `awaitResult()` / `cancel()`). + /// + /// JS distinguishes the arms by feature-detecting `awaitResult` (present + /// only on `AsyncStatement`). This is the path that gives mid-run cancel for + /// long queries WITHOUT the eager-handle / close-drives workaround: the + /// returned handle always corresponds to a server-owned statement. + #[napi] + pub async fn execute_statement_direct( + &self, + sql: String, + mut options: Option, + ) -> napi::Result> { + let inner = Arc::clone(&self.inner); + let row_limit = options.as_ref().and_then(|o| o.row_limit); + let query_timeout_secs = options.as_ref().and_then(|o| o.query_timeout_secs); + let positional_params = options + .as_mut() + .and_then(|o| o.positional_params.take()) + .map(decode_positional_params) + .transpose()? + .unwrap_or_default(); + let named_params = options + .as_mut() + .and_then(|o| o.named_params.take()) + .map(decode_named_params) + .transpose()? + .unwrap_or_default(); + let statement_conf = options.as_mut().and_then(|o| o.statement_conf.take()); + let query_tags = options.as_mut().and_then(|o| o.query_tags.take()); + guarded(async move { + let mut stmt = { + let guard = inner.lock().await; + let session = guard.as_ref().ok_or_else(connection_closed_err)?; + build_statement( + session, + sql, + statement_conf, + query_tags, + row_limit, + query_timeout_secs, + positional_params, + named_params, + )? + }; + + match stmt.execute_direct().await.map_err(napi_err_from_kernel)? { + databricks_sql_kernel::DirectStatement::Completed(executed) => { + Ok(napi::Either::A(Statement::from_executed(stmt, executed))) + } + databricks_sql_kernel::DirectStatement::Running(executed_async) => Ok( + napi::Either::B(AsyncStatement::from_executed_async(stmt, executed_async)), + ), + } + }) + .await + } + /// Execute a SQL statement on the blocking (sync) path, but return a /// `CancellableExecution` handle so a concurrent JS task can cancel /// the query *while it is still running server-side*. diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 40a2b24c..7f174a68 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -26,8 +26,8 @@ use crate::params::parse_typed_value; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{ - Error as KError, ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, - Statement as KStatement, StatementCanceller as KStatementCanceller, + DirectStatement as KDirectStatement, Error as KError, ExecutedStatement as KExecutedStatement, + ExecutedStatementHandle, Statement as KStatement, StatementCanceller as KStatementCanceller, }; use pyo3::prelude::*; use std::collections::HashMap; @@ -241,6 +241,36 @@ impl Statement { Ok(ExecutedAsyncStatement::new(exec, runtime)) } + /// directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + /// with a bounded server-side inline wait (omits `wait_timeout` so the + /// server applies its ~10s default AND auto-closes on success) and returns + /// WITHOUT polling past it: + /// - an **`ExecutedStatement`** when the query finished within the inline + /// wait (terminal, result ready inline) — identical to `execute()`; + /// - an **`ExecutedAsyncStatement`** when it did not — a poll/cancel + /// handle (identical to `submit()`). + /// + /// Python distinguishes the arms by feature-detecting `await_result` + /// (present only on `ExecutedAsyncStatement`). Like `execute()`, the + /// blocking inline wait is `KeyboardInterrupt`-interruptible. + fn execute_direct<'py>(&mut self, py: Python<'py>) -> PyResult> { + let inner = alive_mut!(self, "Statement"); + let runtime = inner.runtime.clone(); + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Statement.execute_direct: directResults execute (GIL released, interruptible)" + ); + let outcome = run_kernel_interruptible!(py, &runtime, inner.stmt.execute_direct())?; + match outcome { + KDirectStatement::Completed(exec) => { + Ok(Bound::new(py, ExecutedStatement::new(exec, runtime))?.into_any()) + } + KDirectStatement::Running(exec) => { + Ok(Bound::new(py, ExecutedAsyncStatement::new(exec, runtime))?.into_any()) + } + } + } + /// Explicit close — cancels and closes any executed handle this /// `Statement` is still tracking, then drops the lifecycle /// owner. diff --git a/src/client/mod.rs b/src/client/mod.rs index f49bdd4e..74c85085 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -45,6 +45,6 @@ pub use retry::{ // Crate-internal surface — `Transport` trait + its value types. pub(crate) use sea::SeaRestTransport; pub(crate) use transport::{ - ChunkLinkFetchResult, ExecuteResponse, ExecuteResult, ExecuteResultData, + ChunkLinkFetchResult, DirectOutcome, ExecuteResponse, ExecuteResult, ExecuteResultData, InlineChunkFetchResult, SessionInfo, Transport, TransportConfig, }; diff --git a/src/client/sea.rs b/src/client/sea.rs index 4e82af78..ad0337e6 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -19,8 +19,8 @@ use crate::client::retry::RequestType; use crate::client::{ - ChunkLinkFetchResult, DatabricksHttpClient, ExecuteResponse, ExecuteResult, ExecuteResultData, - InlineChunkFetchResult, SessionInfo, Transport, TransportConfig, + ChunkLinkFetchResult, DatabricksHttpClient, DirectOutcome, ExecuteResponse, ExecuteResult, + ExecuteResultData, InlineChunkFetchResult, SessionInfo, Transport, TransportConfig, }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -787,6 +787,70 @@ impl Transport for SeaRestTransport { .await } + async fn execute_statement_direct( + &self, + session_id: &str, + sql: &str, + params: &ExecuteParams, + ) -> Result { + // directResults model: OMIT `wait_timeout` (exactly like the sync + // `execute` path) so the server applies its default ~10s inline wait + // AND auto-closes on success (returns `state=CLOSED`). This is the fast + // path: a quick query / fire-and-forget DDL comes back terminal AND + // already server-closed, so the handle's `close()` is a true no-op (no + // cancel+close round-trip that would otherwise discard an unfetched + // result). Setting `wait_timeout=10s` explicitly instead yields + // `SUCCEEDED` (statement still alive → needs an explicit cancel+close), + // which is both slower and breaks fire-and-forget. We just DON'T run the + // `wait_for_completion` poll loop: a query that outlasts the inline wait + // comes back `Running` for the caller to poll/cancel. + let response = self + .call_execute_api(session_id, sql, params, RequestType::ExecuteStatement) + .await?; + let statement_id = response.statement_id.clone(); + + // Publish the server statement id to the caller's canceller slot now — + // a concurrent `StatementCanceller::cancel()` (the Running arm) can + // target the still-running query immediately, no mid-execute observer + // race (the id is known from this POST response). + if let Some(observer) = params.inflight_id_observer.as_ref() { + if let Ok(mut slot) = observer.lock() { + *slot = Some(statement_id.clone()); + } + } + + match Self::terminal_outcome(response) { + // Terminal + succeeded within the inline wait → materialise the + // reader from the inline result (no extra GetStatementResult). + StatementOutcome::Done(r) => { + let reader_factory = self.reader_factory()?; + let reader = match reader_factory.create_reader(&r.statement_id, &r).await { + Ok(reader) => reader, + Err(e) => { + self.close_orphaned_statement(&statement_id, "create_reader (direct)") + .await; + return Err(e); + } + }; + Ok(DirectOutcome::Completed(ExecuteResult { + statement_id: r.statement_id, + reader, + manifest: r.manifest, + status: r.status, + })) + } + // Still running after the inline wait → hand back a running handle; + // the caller polls (and may cancel) via the statement id. + StatementOutcome::NotReady(r) => Ok(DirectOutcome::Running(r)), + // Inline terminal failure/cancel → surface it (close the orphan). + StatementOutcome::Err(e) => { + self.close_orphaned_statement(&statement_id, "execute_statement_direct") + .await; + Err(e) + } + } + } + async fn fetch_completed_result(&self, statement_id: &str) -> Result> { let response = self.get_statement_status(statement_id).await?; match Self::terminal_outcome(response) { diff --git a/src/client/transport.rs b/src/client/transport.rs index 237150e9..301e46e8 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -105,6 +105,23 @@ impl std::fmt::Debug for ExecuteResult { } } +/// Outcome of a directResults-style execute (`Transport::execute_statement_direct`): +/// the server is given a bounded inline wait (`wait_timeout` + `on_wait_timeout=CONTINUE`) +/// and we return WITHOUT the internal poll loop. +/// +/// - `Completed` — the statement reached a terminal-and-succeeded state within +/// the inline wait; the reader is materialised from the inline result (no +/// extra `GetStatementResult` round-trip), exactly like `execute_statement`. +/// - `Running` — the statement is still `Pending`/`Running`; the caller gets the +/// `statement_id` + status and drives polling itself (and can cancel by id). +/// +/// Mirrors the Thrift/JDBC directResults shape: fast queries come back inline, +/// slow ones come back as a running handle. +pub(crate) enum DirectOutcome { + Completed(ExecuteResult), + Running(ExecuteResponse), +} + /// Unified response from statement execution (internal to client implementations). #[derive(Debug, Clone)] pub(crate) struct ExecuteResponse { @@ -244,6 +261,21 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { params: &ExecuteParams, ) -> Result; + /// Execute a SQL statement with a bounded server-side inline wait + /// (`wait_timeout` + `on_wait_timeout=CONTINUE`), returning WITHOUT the + /// internal poll loop — the Thrift/JDBC directResults model. + /// + /// Returns [`DirectOutcome::Completed`] (terminal + reader materialised + /// inline) for queries that finish within the wait, or + /// [`DirectOutcome::Running`] (statement id + status, no reader) for ones + /// that don't. The caller drives any further polling and owns cancellation. + async fn execute_statement_direct( + &self, + session_id: &str, + sql: &str, + params: &ExecuteParams, + ) -> Result; + /// Submit a SQL statement without polling for completion. /// /// Returns whatever the server replied with on the initial diff --git a/src/lib.rs b/src/lib.rs index 10cb7b73..eaacf7d7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -136,7 +136,7 @@ pub use statement::executed_async::{ AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus, }; pub use statement::handle::ExecutedStatementHandle; -pub use statement::mutable::{Statement, StatementCanceller}; +pub use statement::mutable::{DirectStatement, Statement, StatementCanceller}; pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 85e0bbf4..edf9ec94 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1160,6 +1160,14 @@ mod tests { ) -> Result { unimplemented!("submit_statement not used by the link-fetcher mock") } + async fn execute_statement_direct( + &self, + _session_id: &str, + _sql: &str, + _params: &ExecuteParams, + ) -> Result { + unimplemented!("execute_statement_direct not used by the link-fetcher mock") + } async fn fetch_completed_result( &self, diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 8fb3f628..21dc2911 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1431,6 +1431,14 @@ mod tests { ) -> Result { unreachable!() } + async fn execute_statement_direct( + &self, + _: &str, + _: &str, + _: &ExecuteParams, + ) -> Result { + unreachable!() + } async fn fetch_completed_result(&self, _: &str) -> Result> { unreachable!() } diff --git a/src/statement/mod.rs b/src/statement/mod.rs index 13a461cb..bad2077b 100644 --- a/src/statement/mod.rs +++ b/src/statement/mod.rs @@ -40,5 +40,5 @@ pub(crate) mod validity; pub use executed::ExecutedStatement; pub use executed_async::{AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus}; pub use handle::ExecutedStatementHandle; -pub use mutable::{Statement, StatementCanceller}; +pub use mutable::{DirectStatement, Statement, StatementCanceller}; pub use spec::{ResultFormat, StatementSpec, TypedValue}; diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 7133af43..46fdfd6a 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -54,6 +54,7 @@ //! stale handle short-circuits locally — no network round-trip. See //! `crate::statement::validity` for the flag implementation. +use crate::client::DirectOutcome; use crate::kernel_error::{Error, Result}; use crate::klog::warn; use crate::result_stream::ResultStream; @@ -68,6 +69,25 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use tracing::Instrument; +/// Outcome of [`Statement::execute_direct`] — the Thrift/JDBC directResults +/// model. A fast query comes back [`DirectStatement::Completed`] (terminal, +/// result stream ready inline); a slow one comes back +/// [`DirectStatement::Running`] (a poll/cancel handle), letting the caller stay +/// cancellable and keep `close()` a clean release. +#[allow( + clippy::large_enum_variant, + reason = "ephemeral return value of execute_direct, matched and unwrapped \ + immediately by the caller — never stored in a collection, so the \ + inter-variant size gap costs nothing and boxing would only add an \ + allocation on the hot result path" +)] +pub enum DirectStatement { + /// Finished within the server inline wait — result ready, no further poll. + Completed(ExecutedStatement), + /// Still running after the inline wait — poll / cancel via this handle. + Running(ExecutedAsyncStatement), +} + /// Shared slot holding the server statement id of the statement /// currently in flight on a [`Statement`] (or its most recent /// execution). Written by `execute()` / `submit()` as soon as the @@ -380,6 +400,91 @@ impl Statement { .await } + /// directResults execute — the Thrift/JDBC model. + /// + /// Sends ExecuteStatement with a bounded server-side inline wait + /// (`wait_timeout=10s`, `on_wait_timeout=CONTINUE`) and returns WITHOUT + /// polling past it: + /// - [`DirectStatement::Completed`] when the query reached a terminal, + /// succeeded state within the inline wait — the result stream is ready + /// inline (no extra `GetStatementResult` round-trip), identical to + /// [`Statement::execute`]'s fast path; + /// - [`DirectStatement::Running`] when it did not — a poll/cancel handle + /// (identical to [`Statement::submit`]'s return) the caller drives. + /// + /// Unlike [`Statement::execute`], this never blocks past the inline wait and + /// never swallows a still-running handle: a long query stays cancellable via + /// the `Running` handle, and `close()` on either arm is a clean release (the + /// statement is server-owned, so there is no client-side drive-to-terminal). + /// + /// The server statement id is published to the shared in-flight slot from + /// the POST response (not mid-execute), so a `StatementCanceller` / + /// `AsyncStatementCanceller` targets it without an observer race. + pub async fn execute_direct(&mut self) -> Result { + let span = self.session.log_span().clone(); + async { + self.invalidate_prior().await; + // `prepare_for_dispatch(None)` here; `execute_statement_direct` + // forces `wait_timeout=10s` + `on_wait_timeout=CONTINUE` itself. + let (sql, mut exec_params) = self.prepare_for_dispatch(None)?; + + let cancel_state = MidExecuteCancelState::new( + Arc::clone(&self.session), + Arc::clone(&self.inflight_id), + ); + let guard = cancel_state.guard(); + exec_params.inflight_id_observer = Some(Arc::clone(&self.inflight_id)); + + let outcome = self + .session + .transport() + .execute_statement_direct(self.session.session_id(), &sql, &exec_params) + .await?; + + let valid = ValidityFlag::new(); + match outcome { + DirectOutcome::Completed(result) => { + cancel_state.observe(&result.statement_id); + guard.defuse(); + let already_closed = result.status.state == StatementState::Closed; + let closed = Arc::new(AtomicBool::new(already_closed)); + self.last_statement_id = Some(result.statement_id.clone()); + self.last_valid = Some(valid.clone()); + self.last_closed = Some(Arc::clone(&closed)); + let result_stream = ResultStream::from_reader(result.reader).await?; + Ok(DirectStatement::Completed(ExecutedStatement::new( + Arc::clone(&self.session), + result.statement_id, + valid, + result_stream, + closed, + result.status, + ))) + } + DirectOutcome::Running(resp) => { + cancel_state.observe(&resp.statement_id); + guard.defuse(); + // Still running — start the closed flag false (the server + // can't have auto-closed a non-terminal statement); later + // close()/await drives it. + let closed = Arc::new(AtomicBool::new(false)); + self.last_statement_id = Some(resp.statement_id.clone()); + self.last_valid = Some(valid.clone()); + self.last_closed = Some(Arc::clone(&closed)); + Ok(DirectStatement::Running(ExecutedAsyncStatement::new( + Arc::clone(&self.session), + resp.statement_id, + valid, + closed, + resp.status, + ))) + } + } + } + .instrument(span) + .await + } + /// Explicit close. Cancels and closes any executed handle this /// `Statement` is still tracking, then drops the lifecycle /// owner. Mirrors what users of JDBC `Statement.close()` / From f9a7225b8ca83c4e75ba974da6b3587149664614 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sat, 6 Jun 2026 15:44:47 +0000 Subject: [PATCH 2/8] fix(client): treat CLOSED as terminal success (JDBC parity), not an error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `terminal_outcome` rejected a `CLOSED` response with no result payload as `invalid_state("Statement was closed")` — stricter than JDBC and inconsistent with this crate's own `create_reader` (which already builds an `EmptyReader` for an empty `CLOSED`). JDBC's `DatabricksSdkClient` treats `SUCCEEDED` and `CLOSED` identically as success (only other states hit `handleFailedExecution`); an empty `CLOSED` yields an empty result set, not an error. Make `CLOSED -> Done` unconditional. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- src/client/sea.rs | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index ad0337e6..4381fe2a 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -42,10 +42,11 @@ use tokio::runtime::Handle as RuntimeHandle; /// Used by the shared decoder [`SeaRestTransport::terminal_outcome`] /// so the sync polling loop and the async one-shot /// [`Transport::fetch_completed_result`] path produce identical -/// outcomes (and identical errors) for `FAILED` / `CANCELLED` / -/// `CLOSED-no-data` responses. +/// outcomes (and identical errors) for `FAILED` / `CANCELLED` responses. enum StatementOutcome { - /// `Succeeded` (or `Closed` with inline data). + /// Terminal success — `Succeeded` OR `Closed` (with or without inline + /// data; an empty `Closed` is a valid empty result set, materialised + /// downstream by `create_reader`'s `EmptyReader`). Done(ExecuteResponse), /// `Pending` / `Running` — caller polls again. NotReady(ExecuteResponse), @@ -329,21 +330,17 @@ impl SeaRestTransport { )) } StatementState::Closed => { - // Closed with result data is valid for inline results - // — the server delivers the data and immediately - // closes the statement since no further fetching is - // needed. - if response.result.is_some() { - StatementOutcome::Done(response) - } else { - let error = Error::invalid_state() - .message("Statement was closed") - .with_query_id(&response.statement_id); - StatementOutcome::Err(crate::kernel_error::carry_extended_status( - error, - &response.status, - )) - } + // CLOSED is a terminal SUCCESS state — parity with JDBC's + // `DatabricksSdkClient`, which treats SUCCEEDED and CLOSED + // identically as success (anything else → handleFailedExecution). + // It's the server's auto-close-on-completion signal. A CLOSED + // response with NO result payload is a valid EMPTY result set + // (common for DDL/DML and no-row queries that auto-close), NOT + // an error: `create_reader` builds an `EmptyReader` from the + // manifest schema for exactly this case (see its own CLOSED arm + // in reader/mod.rs). Gating on `result.is_some()` here was both + // stricter than JDBC and internally inconsistent with that. + StatementOutcome::Done(response) } StatementState::Pending | StatementState::Running => { StatementOutcome::NotReady(response) From 5dcfa2118904e2de7bbeea7215f590eb4c2ab524 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 7 Jun 2026 20:15:33 +0000 Subject: [PATCH 3/8] =?UTF-8?q?fix(statement):=20address=20review=20?= =?UTF-8?q?=E2=80=94=20defuse=20cancel=20guard=20on=20inline=20error;=20co?= =?UTF-8?q?rrect=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Behavioral fix (verified via debug-log trace against a live warehouse): - `execute_direct`: on an inline terminal failure, the transport already closes the orphaned statement, but the `?` propagated the error WITHOUT defusing the `MidExecuteCancelGuard`, so its `Drop` fired a SECOND, redundant `CancelStatement` against the just-closed statement. Now defuse on the error path. Validated: inline error previously logged Closing/Closed + Canceling/ Canceled (2 RPCs); now logs only Closing/Closed (1 RPC). Doc corrections (no behavior change): - The direct path sends NO `wait_timeout` field (server default ~10s + auto-close on success); the docs claiming `wait_timeout=10s, on_wait_timeout=CONTINUE` were wrong. Fixed in `mutable.rs` (doc + inline), `napi/connection.rs`, `transport.rs`. The OMIT (vs explicit 10s) is what makes the Completed arm's `close()` a no-op. - Documented the `query_timeout_secs` interaction: it sends `wait_timeout={N}s` + CANCEL, so a timeout shorter than the query yields an eager Cancelled error, NOT a `Running` handle (and <5s is rejected by the SEA wire as HTTP 400). Verified live: `queryTimeout=5` cancels at ~5.3s. - CLOSED-as-terminal-success reaches ALL `terminal_outcome` callers (sync `execute()` + `fetch_completed_result`), not just the direct path. Corrected the stale "Closed-no-data returns Err" contracts in `executed.rs`, `napi/statement.rs`, and the `terminal_outcome` method doc. - Documented the load-bearing `awaitResult` feature-detect contract on `executeStatementDirect` (`Statement` must never gain an `awaitResult` member). Tests: clippy clean (lib+napi+pyo3); cargo test --lib 620; v0_execute_wiremock 17. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 11 +++++++-- napi/src/statement.rs | 9 ++++---- src/client/sea.rs | 5 +++-- src/client/transport.rs | 7 +++--- src/statement/executed.rs | 19 ++++++++-------- src/statement/mutable.rs | 47 +++++++++++++++++++++++++++++++++------ 6 files changed, 69 insertions(+), 29 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index f5e7333b..a10dde4a 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -371,8 +371,8 @@ impl Connection { } /// directResults execute — the Thrift/JDBC model. Sends ExecuteStatement - /// with a bounded server-side inline wait (`wait_timeout=10s`, - /// `on_wait_timeout=CONTINUE`) and returns WITHOUT polling past it: + /// with no `wait_timeout` field (server applies its ~10s default inline wait + /// and auto-closes on success) and returns WITHOUT polling past it: /// /// - a **`Statement`** (left arm) when the query finished within the inline /// wait — terminal, result ready inline, `close()` is a clean release; @@ -383,6 +383,13 @@ impl Connection { /// only on `AsyncStatement`). This is the path that gives mid-run cancel for /// long queries WITHOUT the eager-handle / close-drives workaround: the /// returned handle always corresponds to a server-owned statement. + /// + /// **Load-bearing contract:** the kernel's `DirectStatement::{Completed, + /// Running}` discriminant cannot ride on these opaque `#[napi]` classes, so + /// consumers MUST feature-detect via `awaitResult` (the only member unique to + /// `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an + /// `awaitResult` member, or every consumer silently misroutes. The pyo3 + /// binding makes the same `await_result`-probe assumption. #[napi] pub async fn execute_statement_direct( &self, diff --git a/napi/src/statement.rs b/napi/src/statement.rs index f215c228..ce81814d 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -247,11 +247,10 @@ impl Statement { /// data note:** may contain SQL fragments or parameter values — /// redact before centralised logging. /// - /// Populated on `Succeeded` / `Closed-with-inline-data` paths. - /// On terminal-error states (`Failed` / `Cancelled` / - /// `Closed-no-data`) the kernel returns an Error instead of a - /// `Statement`, and the same field rides on the JS Error envelope - /// under the same `displayMessage` key. + /// Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). + /// On terminal-error states (`Failed` / `Cancelled`) the kernel returns + /// an Error instead of a `Statement`, and the same field rides on the JS + /// Error envelope under the same `displayMessage` key. #[napi] pub async fn display_message(&self) -> napi::Result> { let inner = Arc::clone(&self.inner); diff --git a/src/client/sea.rs b/src/client/sea.rs index 4381fe2a..27637b2b 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -261,8 +261,9 @@ impl SeaRestTransport { /// /// Shared by `wait_for_completion` (sync poll loop) and /// [`Transport::fetch_completed_result`] (async one-shot fetch) - /// so both paths produce identical errors for `FAILED` / - /// `CANCELLED` / `CLOSED-no-data`. + /// so both paths produce identical errors for `FAILED` / `CANCELLED`. + /// `CLOSED` (with or without result data) is a terminal success — JDBC + /// parity; an empty `CLOSED` materialises an empty result downstream. fn terminal_outcome(response: ExecuteResponse) -> StatementOutcome { match response.status.state { StatementState::Succeeded => StatementOutcome::Done(response), diff --git a/src/client/transport.rs b/src/client/transport.rs index 301e46e8..a1f7afdf 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -261,9 +261,10 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { params: &ExecuteParams, ) -> Result; - /// Execute a SQL statement with a bounded server-side inline wait - /// (`wait_timeout` + `on_wait_timeout=CONTINUE`), returning WITHOUT the - /// internal poll loop — the Thrift/JDBC directResults model. + /// Execute a SQL statement relying on the server's default inline wait + /// (the caller's `ExecuteParams` omit `wait_timeout`/`on_wait_timeout` unless + /// a `query_timeout_secs` was set), returning WITHOUT the internal poll loop + /// — the Thrift/JDBC directResults model. /// /// Returns [`DirectOutcome::Completed`] (terminal + reader materialised /// inline) for queries that finish within the wait, or diff --git a/src/statement/executed.rs b/src/statement/executed.rs index e2481f03..f8abb28d 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -178,9 +178,9 @@ impl ExecutedStatement { /// MERGE). Absent for SELECT and on warehouses that don't surface /// the counter. /// - /// Reachable only on the `Succeeded` / `Closed-with-inline-data` - /// paths — the kernel returns `Err` (no `ExecutedStatement`) on - /// `Failed` / `Cancelled` / `Closed-no-data`. + /// Reachable on the `Succeeded` / `Closed` paths — the kernel returns + /// `Err` (no `ExecutedStatement`) on `Failed` / `Cancelled`. (A `Closed` + /// response with no result data is a valid empty result, not an error.) pub fn num_modified_rows(&self) -> Option { self.status.num_modified_rows } @@ -202,11 +202,10 @@ impl ExecutedStatement { /// `error.message` that the kernel folds into `Error::sql_error()` /// on the `Failed` path. /// - /// **Reachability:** populated on `Succeeded` / `Closed-with-inline-data` - /// only. Failed / Cancelled / Closed-no-data return `Err` before - /// the `ExecutedStatement` is constructed, so cancellation-reason - /// messages from those paths are NOT reachable here — they flow - /// through the `Error` instead. + /// **Reachability:** populated on `Succeeded` / `Closed` (incl. an empty + /// `Closed`). Failed / Cancelled return `Err` before the `ExecutedStatement` + /// is constructed, so cancellation-reason messages from those paths are NOT + /// reachable here — they flow through the `Error` instead. /// /// **PII / sensitive-data note:** server-supplied free-form text /// may include SQL fragments or parameter values. Redact before @@ -219,7 +218,7 @@ impl ExecutedStatement { /// frames or operator context. Intended for log / support /// surfaces; not user-facing. /// - /// **Reachability:** populated on `Succeeded` / `Closed-with-inline-data` + /// **Reachability:** populated on `Succeeded` / `Closed` /// only — same caveat as [`Self::display_message`]. /// /// **PII / sensitive-data note:** like `display_message`, this is @@ -233,7 +232,7 @@ impl ExecutedStatement { /// Pass-through string — wrappers parse if they need structured /// access. /// - /// **Reachability:** populated on `Succeeded` / `Closed-with-inline-data` + /// **Reachability:** populated on `Succeeded` / `Closed` /// only. The corresponding details for Failed statements flow /// through the returned `Error`, not this accessor. /// diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 46fdfd6a..54795791 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -402,9 +402,9 @@ impl Statement { /// directResults execute — the Thrift/JDBC model. /// - /// Sends ExecuteStatement with a bounded server-side inline wait - /// (`wait_timeout=10s`, `on_wait_timeout=CONTINUE`) and returns WITHOUT - /// polling past it: + /// Sends ExecuteStatement with **no `wait_timeout` field** (the server then + /// applies its ~10s default inline wait AND auto-closes on success, + /// `state=CLOSED`) and returns WITHOUT polling past it: /// - [`DirectStatement::Completed`] when the query reached a terminal, /// succeeded state within the inline wait — the result stream is ready /// inline (no extra `GetStatementResult` round-trip), identical to @@ -412,6 +412,21 @@ impl Statement { /// - [`DirectStatement::Running`] when it did not — a poll/cancel handle /// (identical to [`Statement::submit`]'s return) the caller drives. /// + /// Omitting `wait_timeout` (rather than sending an explicit `wait_timeout=10s`, + /// which returns `SUCCEEDED` and leaves the statement alive needing a separate + /// `CloseStatement`) is what makes the `Completed` arm's `close()` a no-op and + /// lets fire-and-forget DDL commit. + /// + /// **`query_timeout_secs` caveat.** If the spec sets `query_timeout_secs = N`, + /// `prepare_for_dispatch` sends `wait_timeout="{N}s"` + `on_wait_timeout=CANCEL` + /// instead of omitting it. The server then holds for `N`s and **CANCELs** the + /// statement on expiry — surfacing as an eager `Cancelled` error from this call, + /// NOT a `DirectStatement::Running` handle. So a `query_timeout_secs` shorter + /// than the query's runtime makes the `Running` arm unreachable (the statement + /// is cancelled rather than handed back). (The SEA wire also rejects + /// `wait_timeout` below 5s with HTTP 400, so `query_timeout_secs` in 1..=4 errors + /// at the server rather than cancelling.) + /// /// Unlike [`Statement::execute`], this never blocks past the inline wait and /// never swallows a still-running handle: a long query stays cancellable via /// the `Running` handle, and `close()` on either arm is a clean release (the @@ -424,8 +439,14 @@ impl Statement { let span = self.session.log_span().clone(); async { self.invalidate_prior().await; - // `prepare_for_dispatch(None)` here; `execute_statement_direct` - // forces `wait_timeout=10s` + `on_wait_timeout=CONTINUE` itself. + // `prepare_for_dispatch(None)` leaves `wait_timeout` / `on_wait_timeout` + // UNSET, so `execute_statement_direct` sends ExecuteStatement with no + // `wait_timeout` field — the server applies its ~10s default AND + // auto-closes on success (`state=CLOSED`). Omitting (vs an explicit + // `wait_timeout=10s`, which returns `SUCCEEDED` and leaves the statement + // alive) is what makes the Completed arm's `close()` a no-op and lets + // fire-and-forget DDL commit. (`query_timeout_secs`, if set on the spec, + // is the exception — see the method doc: it sends `{secs}s` + CANCEL.) let (sql, mut exec_params) = self.prepare_for_dispatch(None)?; let cancel_state = MidExecuteCancelState::new( @@ -435,11 +456,23 @@ impl Statement { let guard = cancel_state.guard(); exec_params.inflight_id_observer = Some(Arc::clone(&self.inflight_id)); - let outcome = self + let outcome = match self .session .transport() .execute_statement_direct(self.session.session_id(), &sql, &exec_params) - .await?; + .await + { + Ok(outcome) => outcome, + Err(e) => { + // Inline terminal failure/cancel. The transport already published + // the statement id to the shared slot and closed the orphaned + // statement (`execute_statement_direct`'s `Err` arm). Defuse the + // cancel guard so its `Drop` does NOT fire a second, redundant + // `CancelStatement` against that now-closed statement. + guard.defuse(); + return Err(e); + } + }; let valid = ValidityFlag::new(); match outcome { From 5f6b9669a08123d7a1b177776e42f62ed95b7534 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 7 Jun 2026 21:15:46 +0000 Subject: [PATCH 4/8] =?UTF-8?q?refactor:=20remove=20query=5Ftimeout=5Fsecs?= =?UTF-8?q?=20=E2=80=94=20it=20abused=20wait=5Ftimeout,=20not=20a=20real?= =?UTF-8?q?=20timeout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `query_timeout_secs` mapped the JDBC-style `setQueryTimeout` onto the SEA `wait_timeout` field via `resolve_wait_timeout` (`{N}s` + on_wait_timeout=CANCEL). That is incorrect: `wait_timeout` is the server's inline-HOLD window (how long the ExecuteStatement POST blocks for results, capped 5–50s), NOT a statement-execution timeout. Mapping there silently caps the timeout at 50s, rejects <5s with HTTP 400, and conflates the inline wait with execution. A real per-statement timeout is the `STATEMENT_TIMEOUT` SQL conf, not this field. It was reachable only through the napi `ExecuteOptions.query_timeout_secs` (pyo3 never exposed it; Python `use_kernel` has no query-timeout wiring at all), and the Node driver now treats `queryTimeout` as a no-op — so the field had no correct consumer. Remove it end to end: - `StatementSpec`: drop the `query_timeout_secs` field + setter + tests. - `resolve_wait_timeout`: drop the `spec_query_timeout_secs` param and the CANCEL branch; the sync path now always omits `wait_timeout` (server default + auto-close). - napi `ExecuteOptions`: drop the `query_timeout_secs` field; `build_statement` loses the param; all three call sites stop decoding/threading it. - Doc cleanups across `mutable.rs` / `connection.rs` / `spec.rs`. Tests: clippy clean (lib+napi+pyo3); cargo test --lib 619; v0_execute_wiremock 17. e2e: `queryTimeout` is now ignored (a 5s timeout on a ~34s query no longer cancels). Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 70 ++++++++-------------------------------- src/statement/mutable.rs | 66 +++++++++++++------------------------ src/statement/spec.rs | 33 +++---------------- 3 files changed, 40 insertions(+), 129 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index a10dde4a..d0c24f06 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -53,10 +53,11 @@ use crate::util::guarded; /// produces (`lib/utils/queryTags.ts`). Backslashes in keys are /// doubled; backslash/colon/comma in values are backslash-escaped. /// -/// `rowLimit` (SEA `row_limit`) and `queryTimeoutSecs` (the per-statement -/// server wait timeout) are exposed here and threaded onto the kernel +/// `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel /// `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) /// carry bound query parameters, decoded via `params::parse_typed_value`. +/// (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold +/// window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) /// /// **Tag-order caveat (M4 parity note).** The napi `queryTags` field /// is a Rust `HashMap` whose iteration order is @@ -100,23 +101,6 @@ pub struct ExecuteOptions { /// (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to /// `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. pub row_limit: Option, - /// Per-statement server wait timeout in whole seconds. Bounds how - /// long the server waits before cancelling the statement - /// (`on_wait_timeout = CANCEL`), surfacing as a timeout — the - /// server statement timeout (JDBC `setQueryTimeout`). Maps to - /// `StatementSpec.query_timeout_secs`. Distinct from the - /// connection-level transport timeout. The SEA wire caps it at 50s. - /// - /// **Applies to `executeStatement` only.** The async `submitStatement` - /// path always sends `wait_timeout=0s` (so the server returns a - /// `statement_id` immediately and never blocks), which means this - /// field is *not* consulted on the submit path — the caller drives - /// completion via `AsyncStatement.status()` / `awaitResult()` and is - /// responsible for its own timeout (e.g. `Promise.race`). Passing - /// `queryTimeoutSecs` to `submitStatement` is silently ignored. This - /// matches the Python `use_sea` async-submit contract, where the - /// wait-timeout and any statement timeout are orthogonal. - pub query_timeout_secs: Option, /// Positional parameters, in 1-based wire order. Index `i` in this /// Vec corresponds to the `i+1`-th `?` placeholder in the SQL. /// Each entry is a `{ sqlType, value }` pair — `value` is the @@ -194,10 +178,6 @@ pub(crate) fn connection_closed_err() -> napi::Error { /// edited once). `Session::statement()` clones the session's internal `Arc`, /// so the returned `Statement` is independent of the borrow and the caller can /// release the lock before `execute()` / `submit()`. -/// -/// `query_timeout_secs` is honoured on the sync `execute` path; the submit path -/// passes `None` because submit pins `wait_timeout=0s` and `resolve_wait_timeout` -/// never consults the spec timeout there (see `statement/mutable.rs`). #[allow(clippy::too_many_arguments)] fn build_statement( session: &Session, @@ -205,7 +185,6 @@ fn build_statement( statement_conf: Option>, query_tags: Option>>, row_limit: Option, - query_timeout_secs: Option, positional_params: Vec, named_params: Vec<(String, TypedValue)>, ) -> napi::Result { @@ -229,9 +208,7 @@ fn build_statement( stmt.spec().query_tags(tags).map_err(napi_err_from_kernel)?; } // `None` leaves the kernel's omit-the-field default in place. - stmt.spec() - .row_limit(row_limit) - .query_timeout_secs(query_timeout_secs); + stmt.spec().row_limit(row_limit); // Bind positional params 1-based on the wire. for (i, value) in positional_params.into_iter().enumerate() { stmt.spec() @@ -308,9 +285,7 @@ impl Connection { let inner = Arc::clone(&self.inner); // Pull the scalar knobs out (both `i64`/`u32` are `Copy`) before // the `.take()`s below consume the map fields out of `options`. - let row_limit = options.as_ref().and_then(|o| o.row_limit); - let query_timeout_secs = options.as_ref().and_then(|o| o.query_timeout_secs); - // Decode positional params before `options` is consumed below; a + let row_limit = options.as_ref().and_then(|o| o.row_limit); // Decode positional params before `options` is consumed below; a // malformed entry surfaces as InvalidArgument here, before any wire // round-trip. let positional_params = options @@ -353,7 +328,6 @@ impl Connection { statement_conf, query_tags, row_limit, - query_timeout_secs, positional_params, named_params, )? @@ -397,9 +371,7 @@ impl Connection { mut options: Option, ) -> napi::Result> { let inner = Arc::clone(&self.inner); - let row_limit = options.as_ref().and_then(|o| o.row_limit); - let query_timeout_secs = options.as_ref().and_then(|o| o.query_timeout_secs); - let positional_params = options + let row_limit = options.as_ref().and_then(|o| o.row_limit); let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) .map(decode_positional_params) @@ -423,7 +395,6 @@ impl Connection { statement_conf, query_tags, row_limit, - query_timeout_secs, positional_params, named_params, )? @@ -456,9 +427,7 @@ impl Connection { /// `Statement` `executeStatement` returns) and can fire `cancel()` /// concurrently to interrupt a still-running query mid-COMPUTE. /// - /// Option semantics are identical to `executeStatement` — including - /// `queryTimeoutSecs`, which IS honoured here (this is the sync - /// `execute` path; only the async `submitStatement` ignores it). + /// Option semantics are identical to `executeStatement`. /// Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` /// split (PR #121): obtain the canceller before the blocking drive. #[napi] @@ -468,12 +437,8 @@ impl Connection { mut options: Option, ) -> napi::Result { let inner = Arc::clone(&self.inner); - // Same option decoding as `execute_statement` — `queryTimeoutSecs` - // IS honoured here (sync execute path), so it is read and threaded - // through `build_statement` like the rest of the knobs. - let row_limit = options.as_ref().and_then(|o| o.row_limit); - let query_timeout_secs = options.as_ref().and_then(|o| o.query_timeout_secs); - let positional_params = options + // Same option decoding as `execute_statement`. + let row_limit = options.as_ref().and_then(|o| o.row_limit); let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) .map(decode_positional_params) @@ -504,7 +469,6 @@ impl Connection { statement_conf, query_tags, row_limit, - query_timeout_secs, positional_params, named_params, )? @@ -527,14 +491,11 @@ impl Connection { /// uses (`runAsync: true`): the SEA backend submits, returns a /// pending operation handle, and polls to terminal during /// fetch. Option semantics (statementConf / queryTags / - /// rowLimit / positional + named params) match `executeStatement`, - /// with one carve-out: `queryTimeoutSecs` is **ignored** here. + /// rowLimit / positional + named params) match `executeStatement`. /// Submit always sends `wait_timeout=0s` so the call returns - /// immediately, leaving no server wait to bound; the caller drives - /// completion and its own timeout via `status()` / `awaitResult()` - /// (e.g. `Promise.race`). Only the blocking-vs-pending return - /// contract — and that timeout carve-out — differ from - /// `executeStatement`. + /// immediately; the caller drives completion via `status()` / + /// `awaitResult()`. Only the blocking-vs-pending return contract + /// differs from `executeStatement`. #[napi] pub async fn submit_statement( &self, @@ -544,9 +505,6 @@ impl Connection { let inner = Arc::clone(&self.inner); // Same option decoding as `execute_statement` — malformed // params surface as InvalidArgument before any wire round-trip. - // `queryTimeoutSecs` is intentionally NOT read here: submit pins - // `wait_timeout=0s`, so `resolve_wait_timeout` never consults the - // spec timeout on this path (see statement/mutable.rs). let row_limit = options.as_ref().and_then(|o| o.row_limit); let positional_params = options .as_mut() @@ -578,14 +536,12 @@ impl Connection { let mut stmt = { let guard = inner.lock().await; let session = guard.as_ref().ok_or_else(connection_closed_err)?; - // `None` for query_timeout_secs — ignored on the submit path. build_statement( session, sql, statement_conf, query_tags, row_limit, - None, positional_params, named_params, )? diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 54795791..aea2c76f 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -104,21 +104,18 @@ type InflightId = Arc>>; /// - `caller_wait_secs = Some(s)` — the caller pinned the wait shape /// (e.g. `submit` passes `"0s"` for async). Respected verbatim with /// `CONTINUE`; overriding it would make async submit block. -/// - `caller_wait_secs = None` — the sync `execute` path. A per-statement -/// `spec_query_timeout_secs` then bounds the server wait and `CANCEL`s -/// the statement on elapse (JDBC `setQueryTimeout` / Python `use_sea`'s -/// `wait_timeout` semantics). With no spec timeout, both are omitted so -/// the server applies its default (~10s wait + auto-close on success). -fn resolve_wait_timeout( - caller_wait_secs: Option<&str>, - spec_query_timeout_secs: Option, -) -> (Option, Option) { +/// - `caller_wait_secs = None` — the sync `execute` path. Both fields are +/// omitted so the server applies its default (~10s wait + auto-close on +/// success). +/// +/// Note: there is intentionally NO statement-execution-timeout knob here. +/// `wait_timeout` is the server's inline-HOLD window (capped 5–50s), not an +/// execution deadline; a real per-statement timeout is the `STATEMENT_TIMEOUT` +/// SQL conf, not this field. See the removal of `query_timeout_secs`. +fn resolve_wait_timeout(caller_wait_secs: Option<&str>) -> (Option, Option) { match caller_wait_secs { Some(s) => (Some(s.to_string()), Some("CONTINUE".to_string())), - None => match spec_query_timeout_secs { - Some(secs) => (Some(format!("{secs}s")), Some("CANCEL".to_string())), - None => (None, None), - }, + None => (None, None), } } @@ -153,8 +150,7 @@ fn build_execute_params( return Err(Error::invalid_argument() .message("positional and named parameters are mutually exclusive; pass only one")); } - let (wait_timeout, on_wait_timeout) = - resolve_wait_timeout(wait_timeout_secs, spec.query_timeout_secs); + let (wait_timeout, on_wait_timeout) = resolve_wait_timeout(wait_timeout_secs); let mut exec_params = ExecuteParams { wait_timeout, on_wait_timeout, @@ -415,17 +411,9 @@ impl Statement { /// Omitting `wait_timeout` (rather than sending an explicit `wait_timeout=10s`, /// which returns `SUCCEEDED` and leaves the statement alive needing a separate /// `CloseStatement`) is what makes the `Completed` arm's `close()` a no-op and - /// lets fire-and-forget DDL commit. - /// - /// **`query_timeout_secs` caveat.** If the spec sets `query_timeout_secs = N`, - /// `prepare_for_dispatch` sends `wait_timeout="{N}s"` + `on_wait_timeout=CANCEL` - /// instead of omitting it. The server then holds for `N`s and **CANCELs** the - /// statement on expiry — surfacing as an eager `Cancelled` error from this call, - /// NOT a `DirectStatement::Running` handle. So a `query_timeout_secs` shorter - /// than the query's runtime makes the `Running` arm unreachable (the statement - /// is cancelled rather than handed back). (The SEA wire also rejects - /// `wait_timeout` below 5s with HTTP 400, so `query_timeout_secs` in 1..=4 errors - /// at the server rather than cancelling.) + /// lets fire-and-forget DDL commit. There is no statement-execution-timeout + /// knob on this path — `wait_timeout` is the inline-hold window, not an + /// execution deadline. /// /// Unlike [`Statement::execute`], this never blocks past the inline wait and /// never swallows a still-running handle: a long query stays cancellable via @@ -445,8 +433,7 @@ impl Statement { // auto-closes on success (`state=CLOSED`). Omitting (vs an explicit // `wait_timeout=10s`, which returns `SUCCEEDED` and leaves the statement // alive) is what makes the Completed arm's `close()` a no-op and lets - // fire-and-forget DDL commit. (`query_timeout_secs`, if set on the spec, - // is the exception — see the method doc: it sends `{secs}s` + CANCEL.) + // fire-and-forget DDL commit. let (sql, mut exec_params) = self.prepare_for_dispatch(None)?; let cancel_state = MidExecuteCancelState::new( @@ -791,27 +778,18 @@ mod tests { #[test] fn async_submit_caller_value_is_respected_verbatim() { - // submit() pins "0s" for async; never overridden, even if a spec - // query_timeout is set (overriding would make submit block). - let (wait, on_wait) = resolve_wait_timeout(Some("0s"), Some(30)); + // submit() pins "0s" for async; respected verbatim with CONTINUE. + let (wait, on_wait) = resolve_wait_timeout(Some("0s")); assert_eq!(wait.as_deref(), Some("0s")); assert_eq!(on_wait.as_deref(), Some("CONTINUE")); } #[test] - fn sync_with_query_timeout_cancels_on_elapse() { - // execute() passes None; a spec query_timeout bounds the wait and - // CANCELs the statement on elapse (server statement-timeout). - let (wait, on_wait) = resolve_wait_timeout(None, Some(30)); - assert_eq!(wait.as_deref(), Some("30s")); - assert_eq!(on_wait.as_deref(), Some("CANCEL")); - } - - #[test] - fn sync_without_query_timeout_omits_field() { - // No caller pin and no spec timeout: omit both so the server uses - // its default (~10s wait + auto-close on success). - let (wait, on_wait) = resolve_wait_timeout(None, None); + fn sync_omits_wait_timeout_field() { + // execute() passes None: omit both so the server uses its default + // (~10s wait + auto-close on success). There is no statement-timeout + // knob — `query_timeout_secs` was removed (it abused `wait_timeout`). + let (wait, on_wait) = resolve_wait_timeout(None); assert_eq!(wait, None); assert_eq!(on_wait, None); } diff --git a/src/statement/spec.rs b/src/statement/spec.rs index e13f55b1..ff4ef809 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -203,18 +203,6 @@ pub struct StatementSpec { /// omits the field, so the server applies no driver-imposed cap. pub row_limit: Option, - /// Server-side statement wait timeout, in whole seconds. Bounds how - /// long the server waits for the statement to reach a terminal state - /// before the wait elapses; on elapse the statement is cancelled - /// (`on_wait_timeout = CANCEL`), surfacing as a timeout to the caller. - /// This is the per-statement server timeout (JDBC `setQueryTimeout` / - /// Python `use_sea`'s `wait_timeout=`), distinct from the transport - /// `overall_timeout`. `None` lets the kernel pick its sync/async - /// default (see `Statement::execute` / `submit`). The SEA wire caps - /// the value at 50s; the kernel forwards the requested value verbatim - /// and lets the server clamp. - pub query_timeout_secs: Option, - /// Result wire format. pub result_format: ResultFormat, } @@ -329,14 +317,6 @@ impl StatementSpec { self } - /// Set the per-statement server wait timeout in whole seconds. `None` - /// clears it (kernel default applies). See the field docs for the - /// `CANCEL`-on-elapse semantics and the 50s server cap. - pub fn query_timeout_secs(&mut self, secs: Option) -> &mut Self { - self.query_timeout_secs = secs; - self - } - /// Set the result wire format. pub fn result_format(&mut self, fmt: ResultFormat) -> &mut Self { self.result_format = fmt; @@ -391,23 +371,20 @@ mod tests { assert!(s.positional_params.is_empty()); assert!(s.named_params.is_empty()); assert!(s.statement_conf.is_empty()); - // row_limit / query_timeout default to "omit the field" so the - // server applies no driver-imposed cap and its own wait default. + // row_limit defaults to "omit the field" so the server applies no + // driver-imposed cap. assert!(s.row_limit.is_none()); - assert!(s.query_timeout_secs.is_none()); assert_eq!(s.result_format, ResultFormat::Arrow); } #[test] - fn row_limit_and_query_timeout_setters() { + fn row_limit_setter() { let mut s = StatementSpec::new(); - s.row_limit(Some(100)).query_timeout_secs(Some(30)); + s.row_limit(Some(100)); assert_eq!(s.row_limit, Some(100)); - assert_eq!(s.query_timeout_secs, Some(30)); // `None` clears back to the omit-the-field default. - s.row_limit(None).query_timeout_secs(None); + s.row_limit(None); assert!(s.row_limit.is_none()); - assert!(s.query_timeout_secs.is_none()); } #[test] From 8b194fb1c99a674fe657d86e04a4350c8f2694e9 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 8 Jun 2026 09:21:05 +0000 Subject: [PATCH 5/8] style(napi): rustfmt connection.rs (build_statement call-site reflow) The root `cargo fmt --all` does not reach the napi sub-crate; run fmt there so the call sites left after dropping the query_timeout_secs arg are formatted. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/connection.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index d0c24f06..cd9d2d7f 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -285,9 +285,9 @@ impl Connection { let inner = Arc::clone(&self.inner); // Pull the scalar knobs out (both `i64`/`u32` are `Copy`) before // the `.take()`s below consume the map fields out of `options`. - let row_limit = options.as_ref().and_then(|o| o.row_limit); // Decode positional params before `options` is consumed below; a - // malformed entry surfaces as InvalidArgument here, before any wire - // round-trip. + let row_limit = options.as_ref().and_then(|o| o.row_limit); // Decode positional params before `options` is consumed below; a + // malformed entry surfaces as InvalidArgument here, before any wire + // round-trip. let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) @@ -371,7 +371,8 @@ impl Connection { mut options: Option, ) -> napi::Result> { let inner = Arc::clone(&self.inner); - let row_limit = options.as_ref().and_then(|o| o.row_limit); let positional_params = options + let row_limit = options.as_ref().and_then(|o| o.row_limit); + let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) .map(decode_positional_params) @@ -438,7 +439,8 @@ impl Connection { ) -> napi::Result { let inner = Arc::clone(&self.inner); // Same option decoding as `execute_statement`. - let row_limit = options.as_ref().and_then(|o| o.row_limit); let positional_params = options + let row_limit = options.as_ref().and_then(|o| o.row_limit); + let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) .map(decode_positional_params) From a6a0b41b87a914cb5fb021f10e66b508b330a6ff Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 8 Jun 2026 10:03:56 +0000 Subject: [PATCH 6/8] refactor(pyo3): drop unused execute_direct binding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The directResults primitive was mirrored onto pyo3 for binding parity, but no consumer uses it: Python `use_kernel` runs the blocking `execute()` (the additive design means Python needs no change), and there is no pyo3 test for it. Only Node consumes directResults (via the napi `executeStatementDirect`), so the pyo3 surface is dead. Remove `Statement.execute_direct` and the now-unused `DirectStatement as KDirectStatement` import. Clean removal — pyo3 `ExecutedStatement` is still constructed by the unchanged blocking `execute()` and `ExecutedAsyncStatement` by `submit()`, so nothing is orphaned. pyo3 clippy clean; Python use_kernel e2e (CREATE / cheap-close / mid-run cancel) unaffected. The kernel `Statement::execute_direct` and napi `executeStatementDirect` are untouched. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- pyo3/src/statement.rs | 34 ++-------------------------------- 1 file changed, 2 insertions(+), 32 deletions(-) diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 7f174a68..40a2b24c 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -26,8 +26,8 @@ use crate::params::parse_typed_value; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{ - DirectStatement as KDirectStatement, Error as KError, ExecutedStatement as KExecutedStatement, - ExecutedStatementHandle, Statement as KStatement, StatementCanceller as KStatementCanceller, + Error as KError, ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, + Statement as KStatement, StatementCanceller as KStatementCanceller, }; use pyo3::prelude::*; use std::collections::HashMap; @@ -241,36 +241,6 @@ impl Statement { Ok(ExecutedAsyncStatement::new(exec, runtime)) } - /// directResults execute — the Thrift/JDBC model. Sends ExecuteStatement - /// with a bounded server-side inline wait (omits `wait_timeout` so the - /// server applies its ~10s default AND auto-closes on success) and returns - /// WITHOUT polling past it: - /// - an **`ExecutedStatement`** when the query finished within the inline - /// wait (terminal, result ready inline) — identical to `execute()`; - /// - an **`ExecutedAsyncStatement`** when it did not — a poll/cancel - /// handle (identical to `submit()`). - /// - /// Python distinguishes the arms by feature-detecting `await_result` - /// (present only on `ExecutedAsyncStatement`). Like `execute()`, the - /// blocking inline wait is `KeyboardInterrupt`-interruptible. - fn execute_direct<'py>(&mut self, py: Python<'py>) -> PyResult> { - let inner = alive_mut!(self, "Statement"); - let runtime = inner.runtime.clone(); - tracing::debug!( - target: crate::logging::PYO3_LOG_TARGET, - "Statement.execute_direct: directResults execute (GIL released, interruptible)" - ); - let outcome = run_kernel_interruptible!(py, &runtime, inner.stmt.execute_direct())?; - match outcome { - KDirectStatement::Completed(exec) => { - Ok(Bound::new(py, ExecutedStatement::new(exec, runtime))?.into_any()) - } - KDirectStatement::Running(exec) => { - Ok(Bound::new(py, ExecutedAsyncStatement::new(exec, runtime))?.into_any()) - } - } - } - /// Explicit close — cancels and closes any executed handle this /// `Statement` is still tracking, then drops the lifecycle /// owner. From 1afcbd5095965a5e8b3de89f429dde58ca9893e3 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 8 Jun 2026 10:45:24 +0000 Subject: [PATCH 7/8] docs(changelog): stage directResults + CLOSED-parity + query_timeout removal Add NEXT_CHANGELOG entries (Rust crate + napi binding) for this PR, per the changelog system merged from main (#138). pyo3 has no entry (untouched). Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- NEXT_CHANGELOG.md | 15 +++++++++++++++ napi/NEXT_CHANGELOG.md | 7 +++++++ 2 files changed, 22 insertions(+) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 28a2d4ab..f82eaacb 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -10,10 +10,25 @@ changes go in their respective binding's NEXT_CHANGELOG. ## [Unreleased] ### Added +- `Statement::execute_direct()` — directResults execution (the Thrift/JDBC model): + one `ExecuteStatement` POST with the server inline wait, returning + `DirectStatement::Completed` (terminal, result materialised inline) or + `DirectStatement::Running` (a poll/cancel handle) **without** an internal poll + loop. Added **alongside** an unchanged blocking `execute()`. ### Updated +- Removed `StatementSpec::query_timeout_secs` and the `resolve_wait_timeout` + `CANCEL` branch: it mapped a per-statement timeout onto the SEA `wait_timeout` + field, which is the server's inline-hold window (capped 5–50s), not a + statement-execution timeout (use the `STATEMENT_TIMEOUT` SQL conf for that). + The sync path now always omits `wait_timeout`. ### Fixed +- `terminal_outcome`: `CLOSED` is now an unconditional terminal **success** + (parity with JDBC's `DatabricksSdkClient`); an empty `CLOSED` materialises an + empty result set instead of erroring with `invalid_state("Statement was + closed")`. Reaches all callers (`execute()`, `fetch_completed_result`, + `execute_direct`). --- *Note: When making changes, please add your change under the appropriate diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 762d3e8d..f8fc2ece 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -13,8 +13,15 @@ layout, or npm publishing. Pure-kernel changes go in the root ## [Unreleased] ### Added +- `Connection.executeStatementDirect(sql, options?)` — exposes the kernel's + directResults `execute_direct`, returning `Either` + (terminal `Statement` for a fast query, or an `AsyncStatement` poll/cancel + handle for a slow one). Consumed by the Node.js driver's default sync path. ### Updated +- Removed `ExecuteOptions.queryTimeoutSecs`: it threaded onto the now-removed + kernel `query_timeout_secs`, which abused the SEA `wait_timeout` inline-hold + window rather than being a real statement timeout. ### Fixed From 22fd1ea8e85d47b41294180c07198e0f9c82f692 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Mon, 8 Jun 2026 10:53:03 +0000 Subject: [PATCH 8/8] test(e2e): cover the direct-execute interface usages (PR #140 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per @gopalldb's review request, add live e2e coverage for `execute_direct` to the `#[ignore]` `v0_execute_e2e` suite — one test per distinct usage: - `execute_direct_completed_returns_inline_result` — Completed (fast) arm: result materialised inline, no extra fetch. - `execute_direct_empty_result_is_not_an_error` — empty/CLOSED-no-data → empty result set, not an error (JDBC parity). - `execute_direct_inline_failure_surfaces_eagerly` — analysis error surfaces as `Err(SqlError)` from execute_direct (eager), matching Python use_kernel. - `execute_direct_running_handle_is_cancellable` — Running arm: a 40B-row scan returns a live handle; cancel() → await_result surfaces `Cancelled`. - `execute_direct_running_await_result_completes` — Running arm driven to a successful terminal result via await_result. All 5 pass against a live warehouse (40s; the two Running tests run a 40B scan). clippy --all-targets clean. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- tests/v0_execute_e2e.rs | 139 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 137 insertions(+), 2 deletions(-) diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 5ade4065..d4c1c8ca 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -23,8 +23,8 @@ //! ``` use databricks_sql_kernel::{ - AuthConfig, ErrorCode, ExecutedStatementHandle, ResultBatch, ResultConfig, ResultStream, - Session, TypedValue, + AuthConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, ResultBatch, ResultConfig, + ResultStream, Session, TypedValue, }; use std::env; @@ -100,6 +100,141 @@ async fn select_with_positional_params() { session.close().await.expect("session close"); } +// ------------------------------------------------------------------------- +// directResults (`execute_direct`) — the Thrift/JDBC model. +// +// `execute_direct()` POSTs with the server inline wait and returns WITHOUT an +// internal poll loop: `DirectStatement::Completed` (terminal, result inline) +// for a query that finishes within the wait, or `DirectStatement::Running` +// (a live poll/cancel handle) for one that does not. These exercise each arm +// against a live warehouse (the usage coverage requested on PR #140). +// ------------------------------------------------------------------------- + +/// Completed arm: a fast query finishes within the inline wait and comes back +/// with its result materialised inline (no extra fetch round-trip), just like +/// `execute()`'s fast path. +#[tokio::test] +#[ignore] +async fn execute_direct_completed_returns_inline_result() { + let session = live_session().await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + match stmt + .execute_direct() + .await + .expect("execute_direct SELECT 1") + { + DirectStatement::Completed(mut exec) => { + assert_eq!( + drain_rows(exec.result_stream_mut()).await, + 1, + "one row inline" + ); + exec.close().await.expect("close"); + } + DirectStatement::Running(_) => panic!("a trivial query must return Completed, not Running"), + } + session.close().await.expect("session close"); +} + +/// Empty / CLOSED-no-data: a 0-row query the server auto-closes is a valid +/// EMPTY result set, not an error (JDBC parity — see the `terminal_outcome` +/// CLOSED change). +#[tokio::test] +#[ignore] +async fn execute_direct_empty_result_is_not_an_error() { + let session = live_session().await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n WHERE 1 = 0"); + match stmt.execute_direct().await.expect("execute_direct empty") { + DirectStatement::Completed(mut exec) => { + assert_eq!( + drain_rows(exec.result_stream_mut()).await, + 0, + "empty result, no error" + ); + exec.close().await.expect("close"); + } + DirectStatement::Running(_) => panic!("a trivial query must return Completed"), + } + session.close().await.expect("session close"); +} + +/// Inline failure surfaces EAGERLY as `Err` from `execute_direct` (not deferred +/// to a later fetch), matching Python `use_kernel`. +#[tokio::test] +#[ignore] +async fn execute_direct_inline_failure_surfaces_eagerly() { + let session = live_session().await; + let mut stmt = session.statement(); + stmt.spec() + .sql("SELECT * FROM definitely_no_such_table_xyz123"); + match stmt.execute_direct().await { + Ok(_) => panic!("analysis error must surface eagerly from execute_direct, got Ok"), + Err(err) => assert_eq!(err.code, ErrorCode::SqlError, "{err:?}"), + } + session.close().await.expect("session close"); +} + +/// Running arm + cancel: a query that exceeds the inline wait comes back as a +/// live `Running` handle; cancelling it makes `await_result` surface the +/// cancellation — the mid-run-cancel path directResults exists for. +#[tokio::test] +#[ignore] +async fn execute_direct_running_handle_is_cancellable() { + let session = live_session().await; + let mut stmt = session.statement(); + // A 40B-row scan reliably runs past the ~10s server inline wait. + stmt.spec() + .sql("SELECT count(*) FROM range(40000000000) WHERE id % 7 = 3 AND rand() < 0.9999"); + match stmt + .execute_direct() + .await + .expect("execute_direct slow query") + { + DirectStatement::Running(async_stmt) => { + async_stmt + .cancel() + .await + .expect("cancel the running statement"); + match async_stmt.await_result().await { + Ok(_) => panic!("cancelled statement must not yield a result stream"), + Err(err) => assert_eq!(err.code, ErrorCode::Cancelled, "{err:?}"), + } + } + DirectStatement::Completed(_) => { + panic!("a 40B-row scan must not finish within the inline wait") + } + } + session.close().await.expect("session close"); +} + +/// Running arm driven to a SUCCESSFUL terminal result via `await_result` (no +/// cancel) — proves the slow-query poll-to-terminal path returns rows. +#[tokio::test] +#[ignore] +async fn execute_direct_running_await_result_completes() { + let session = live_session().await; + let mut stmt = session.statement(); + stmt.spec() + .sql("SELECT count(*) AS c FROM range(40000000000) WHERE id % 7 = 3 AND rand() < 0.9999"); + match stmt + .execute_direct() + .await + .expect("execute_direct slow query") + { + DirectStatement::Running(async_stmt) => { + let mut stream = async_stmt + .await_result() + .await + .expect("await_result to terminal"); + assert_eq!(drain_rows(&mut stream).await, 1, "count(*) returns one row"); + } + DirectStatement::Completed(_) => panic!("a 40B-row scan must be Running"), + } + session.close().await.expect("session close"); +} + #[tokio::test] #[ignore] async fn select_with_named_params() {