diff --git a/napi/src/cancellable.rs b/napi/src/cancellable.rs index bc445019..411a2543 100644 --- a/napi/src/cancellable.rs +++ b/napi/src/cancellable.rs @@ -193,7 +193,7 @@ impl CancellableExecution { let mut guard = pending.lock().await; guard.take().ok_or_else(statement_closed_err)? }; - let outcome = stmt.execute().await; + let outcome = stmt.execute_to_completion().await; // The statement is terminal either way now — let a racing/later // `cancel()` short-circuit rather than fire a redundant RPC. terminal.store(true, Ordering::Release); diff --git a/napi/src/connection.rs b/napi/src/connection.rs index d9d17287..57920022 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -37,7 +37,6 @@ use crate::async_statement::AsyncStatement; use crate::error::napi_err_from_kernel; use crate::params::{parse_typed_value, TypedValueInput}; use crate::runtime; -use crate::statement::Statement; use crate::util::guarded; /// Per-statement options for `Connection.executeStatement`. @@ -286,33 +285,32 @@ impl Connection { &self.session_id } - /// Execute a SQL statement and return a Statement handle that - /// streams batches via `fetchNextBatch()`. + /// Execute a SQL statement (directResults — the Thrift / JDBC / Python + /// `use_sea` model) and return a single `AsyncStatement` handle. Sends + /// ExecuteStatement with the server inline wait (`wait_timeout` default ~10s, + /// `on_wait_timeout=CONTINUE`) and returns WITHOUT polling past it. /// - /// Catalog / schema / sessionConf are session-level - /// (`openSession`). Per-statement options on `ExecuteOptions`: - /// - `statementConf` — per-statement Spark conf overlay - /// - `queryTags` — serialised to a comma-separated `key:value` - /// string and placed in `statement_conf["query_tags"]`, - /// matching NodeJS Thrift's `serializeQueryTags` wire shape + /// The handle is uniform regardless of whether the query finished within the + /// inline wait: + /// - **fast query** — the handle is seeded with the inline result, so + /// `awaitResult()` returns it with zero extra round-trips and `status()` + /// reports the terminal state without a poll (the latency fast path; also + /// 404-proof — a terminal handle never polls a released statement); + /// - **slow query** — the handle is a poll/cancel handle the caller drives + /// (`status()` / `awaitResult()` / `cancel()`). /// - /// `options` is omitted/`None` for the no-options path; passing - /// `{ statementConf: {} }` (an empty map) is treated the same as - /// omission to keep the wire shape stable for the common case. + /// 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, and `close()` is a clean release. #[napi] pub async fn execute_statement( &self, sql: String, mut options: Option, - ) -> napi::Result { + ) -> napi::Result { 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 - // malformed entry surfaces as InvalidArgument here, before any wire - // round-trip. let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) @@ -325,25 +323,9 @@ impl Connection { .map(decode_named_params) .transpose()? .unwrap_or_default(); - // Pull the explicit `statement_conf` map and the `query_tags` - // convenience map out of `options`. The kernel `StatementSpec` - // owns the merge + serialisation: set the explicit conf first, - // then fold `query_tags` in via `spec.query_tags(...)`, which - // serialises to the Thrift wire shape and rejects the dual - // `queryTags` + `statementConf["query_tags"]` definition. 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 { - // Build the kernel `Statement` while holding the session lock, - // then RELEASE the lock before `execute().await`. `Session::statement()` - // returns an owned `Statement` (it clones the session's internal - // `Arc`), so the built statement is independent of the guard — we - // do not need to hold the mutex across the network round-trip. - // This unblocks concurrent `Promise.all([executeStatement(...)])` - // (they serialise only for the microsecond statement-build, not the - // wire call) and stops `close()` from blocking behind an in-flight - // execute. See jira-candidate 2026-05-24-napi-cancel-during-fetch - // (connection-side half). let mut stmt = { let guard = inner.lock().await; let session = guard.as_ref().ok_or_else(connection_closed_err)?; @@ -357,15 +339,10 @@ impl Connection { positional_params, named_params, )? - // session lock released here }; - let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; - // Pass the parent kernel `Statement` into the JS wrapper. - // Dropping it here would invalidate the executed handle - // via the shared ValidityFlag — see `StatementInner` docs - // in `statement.rs` for the rationale. - Ok(Statement::from_executed(stmt, executed)) + let executed_async = stmt.execute().await.map_err(napi_err_from_kernel)?; + Ok(AsyncStatement::from_executed_async(stmt, executed_async)) }) .await } diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 40a2b24c..803c1004 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -203,25 +203,6 @@ impl Statement { }) } - /// Wait-for-result execution. Blocks until the kernel finishes - /// polling and returns an `ExecutedStatement` with the result - /// stream ready to drain. - /// - /// The blocking drive is interruptible: a `KeyboardInterrupt` - /// (Ctrl-C) raised while this is running aborts the query — the - /// in-flight future is dropped, firing the kernel's mid-execute - /// cancel guard so the server-side statement is cancelled too. - fn execute(&mut self, py: Python<'_>) -> PyResult { - let inner = alive_mut!(self, "Statement"); - let runtime = inner.runtime.clone(); - tracing::debug!( - target: crate::logging::PYO3_LOG_TARGET, - "Statement.execute: running statement synchronously (GIL released, interruptible)" - ); - let exec = run_kernel_interruptible!(py, &runtime, inner.stmt.execute())?; - Ok(ExecutedStatement::new(exec, runtime)) - } - /// Submit-and-return. Sends `ExecuteStatement` with /// `wait_timeout=0s` so the server returns immediately with a /// `statement_id`; the kernel does not poll. Returns an @@ -241,6 +222,48 @@ impl Statement { Ok(ExecutedAsyncStatement::new(exec, runtime)) } + /// directResults execution — the Thrift / JDBC / Python `use_sea` model, + /// expressed as a single `ExecutedAsyncStatement` handle. Sends + /// ExecuteStatement with the server inline wait (omits `wait_timeout` so the + /// server applies its ~10s default + `on_wait_timeout=CONTINUE`) and returns + /// WITHOUT polling past it. The handle is uniform either way: + /// - a **fast query** comes back seeded with the inline result, so + /// `await_result()` returns it with zero extra round-trips; + /// - a **slow query** comes back as a poll/cancel handle (drive via + /// `await_result()`, same as `submit()`). + /// + /// The inline wait (still-running case) is `KeyboardInterrupt`-interruptible. + /// A genuinely blocking drive-to-terminal lives at `execute_to_completion`. + fn execute(&mut self, py: Python<'_>) -> PyResult { + let inner = alive_mut!(self, "Statement"); + let runtime = inner.runtime.clone(); + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Statement.execute: directResults execute (GIL released, interruptible)" + ); + let exec = run_kernel_interruptible!(py, &runtime, inner.stmt.execute())?; + Ok(ExecutedAsyncStatement::new(exec, runtime)) + } + + /// Blocking drive-to-terminal execution (the JDBC `Statement.execute()` + /// shape). Sends `ExecuteStatement` and polls server-side to a terminal + /// state before returning a fully-materialised `ExecutedStatement` — no + /// caller-driven polling. Unlike [`execute`](Self::execute) (which returns + /// after the inline wait so a long query stays cancellable), this blocks for + /// the full query duration; reach for it only when the caller genuinely + /// wants one synchronous call. The drive is `KeyboardInterrupt`-interruptible + /// (the GIL is released for the duration). + fn execute_to_completion(&mut self, py: Python<'_>) -> PyResult { + let inner = alive_mut!(self, "Statement"); + let runtime = inner.runtime.clone(); + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Statement.execute_to_completion: blocking drive-to-terminal (GIL released, interruptible)" + ); + let exec = run_kernel_interruptible!(py, &runtime, inner.stmt.execute_to_completion())?; + Ok(ExecutedStatement::new(exec, runtime)) + } + /// 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..c10b394b 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}; @@ -42,10 +42,13 @@ 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). Both are JDBC's success states; a `Closed` response with no + /// result payload is a valid empty result set, materialised downstream by + /// `create_reader`'s `EmptyReader`. Done(ExecuteResponse), /// `Pending` / `Running` — caller polls again. NotReady(ExecuteResponse), @@ -329,21 +332,19 @@ 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: the + // statement finished and was reaped server-side, with the result + // delivered inline. 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 reader/mod.rs — its own CLOSED arm). Gating on + // `result.is_some()` here was both stricter than JDBC and + // internally inconsistent with `create_reader`. + StatementOutcome::Done(response) } StatementState::Pending | StatementState::Running => { StatementOutcome::NotReady(response) @@ -787,6 +788,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/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/executed_async.rs b/src/statement/executed_async.rs index 7458388c..7b203573 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -44,7 +44,7 @@ //! class) can route through whichever handle their language idiom //! prefers; field availability is identical. -use crate::client::ExecuteResponse; +use crate::client::{ExecuteResponse, ExecuteResult}; use crate::kernel_error::Error; use crate::kernel_error::Result; use crate::klog::warn; @@ -206,6 +206,25 @@ pub struct ExecutedAsyncStatement { /// don't `.await` and the poll loop releases the lock before /// every network round-trip. latest_status: Arc>, + /// Inline result seeded by [`Statement::execute`]'s fast path — the + /// `ExecuteStatement` POST returned a terminal, succeeded result + /// within the server inline wait, so the reader is already in hand. + /// `Some` only on the `execute()` fast path; always `None` on the + /// `submit()` path (which sends `wait_timeout=0s` and can't be + /// terminal yet). + /// + /// When present, this handle is **fully terminal with the result + /// already materialisable** — `status()` and `await_result()` + /// short-circuit to it with **zero network round-trips**. That is + /// both the latency fast path (the POST already delivered + /// everything; no GetStatementStatus / GetStatementResult) and the + /// reason a fast query is 404-proof: a terminal handle never polls a + /// statement the server may have already auto-released. + /// + /// `await_result()` / `fetch_result()` `take()` it (the reader is + /// consumed once into a `ResultStream`); a second consumption falls + /// through to the normal fetch path. + inline: std::sync::Mutex>, } impl ExecutedAsyncStatement { @@ -230,6 +249,44 @@ impl ExecutedAsyncStatement { valid: ValidityFlag, closed: Arc, initial_status: crate::types::sea::StatementStatus, + ) -> Self { + Self::new_inner(session, statement_id, valid, closed, initial_status, None) + } + + /// Constructor for [`Statement::execute`]'s fast path: the + /// `ExecuteStatement` POST returned a terminal, succeeded result + /// within the server inline wait, so the reader is seeded inline. + /// + /// `initial_status` is the terminal SEA status from that POST + /// (`Succeeded` / `Closed`); `result` carries the inline reader. The + /// resulting handle is fully terminal — `status()` reports the seeded + /// status and `await_result()` materialises the seeded reader, both + /// without any network round-trip (see the `inline` field doc). + pub(crate) fn new_with_inline( + session: Arc, + statement_id: String, + valid: ValidityFlag, + closed: Arc, + initial_status: crate::types::sea::StatementStatus, + result: ExecuteResult, + ) -> Self { + Self::new_inner( + session, + statement_id, + valid, + closed, + initial_status, + Some(result), + ) + } + + fn new_inner( + session: Arc, + statement_id: String, + valid: ValidityFlag, + closed: Arc, + initial_status: crate::types::sea::StatementStatus, + inline: Option, ) -> Self { Self { session, @@ -237,9 +294,17 @@ impl ExecutedAsyncStatement { valid, closed, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + inline: std::sync::Mutex::new(inline), } } + /// True while the seeded inline result is still present (not yet + /// consumed by `await_result` / `fetch_result`). Used to short-circuit + /// `status()` / `await_result()` to a zero-round-trip terminal path. + fn has_inline(&self) -> bool { + self.inline.lock().map(|g| g.is_some()).unwrap_or(false) + } + /// Number of rows modified by the statement (UPDATE / INSERT / /// DELETE / MERGE). Reflects the most recent SEA /// `StatementStatus` this handle has seen (initial submit @@ -329,6 +394,28 @@ impl ExecutedAsyncStatement { let span = self.session.log_span().clone(); async { self.valid.check()?; + // Seeded fast path (`execute()` inline result): the statement + // finished and the result is in hand, so report `Succeeded` + // WITHOUT a GetStatementStatus RPC. This is what makes a fast + // query 404-proof — a terminal handle never polls a statement the + // server may have already released — and removes a round-trip + // from the hot path. + // + // We report `Succeeded` even when the server's inline-wait + // response carried `state=CLOSED`: on warehouses that auto-close + // a statement once it has delivered its result inline, `CLOSED` + // is a *resource* state meaning "succeeded and already released", + // NOT a failure or a client-initiated close. A seeded handle is + // only ever produced for a succeeded terminal outcome (the + // transport surfaces an inline Failed/Canceled as `Err`, never as + // an inline result), and the result is materialisable from the + // seed — so the caller-visible outcome is unambiguously success. + // Collapsing `CLOSED → Succeeded` here keeps directResults parity + // across auto-closing and non-auto-closing warehouses and matches + // the Thrift `FINISHED_STATE` a completed directResults op reports. + if self.has_inline() { + return Ok(StatementStatus::Succeeded); + } let response = self .session .transport() @@ -368,6 +455,15 @@ impl ExecutedAsyncStatement { async { self.valid.check()?; + // Seeded fast path (`execute()` inline result): the result is + // already in hand. Materialise it WITHOUT any poll/fetch + // round-trip (`materialise_result` takes the inline reader). + // Also makes a terminal handle 404-proof — it never + // GetStatementStatus-es a statement the server may have closed. + if self.has_inline() { + return self.materialise_result().await; + } + // Poll cadence + ceiling come from the transport's config — // same source the sync `wait_for_completion` path uses, so // a caller's `SessionBuilder` tuning applies to both modes. @@ -465,6 +561,12 @@ impl ExecutedAsyncStatement { /// status so callers don't have to re-query, and points at the /// actionable follow-up. async fn materialise_result(&self) -> Result { + // Seeded inline result (execute() fast path): consume the reader + // already in hand — no GetStatementResult round-trip. `take()` so a + // second consumption falls through to the normal fetch path below. + if let Some(result) = self.inline.lock().ok().and_then(|mut g| g.take()) { + return ResultStream::from_reader(result.reader).await; + } match self .session .transport() diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 7133af43..44dccda2 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; @@ -258,7 +259,7 @@ impl Statement { /// the prior handle's [`ValidityFlag`] is flipped so subsequent /// calls on it short-circuit to `InvalidStatementHandle` without /// hitting the wire. - pub async fn execute(&mut self) -> Result { + pub async fn execute_to_completion(&mut self) -> Result { // `instrument` (rather than `.entered()`) so the resulting // future stays `Send` — napi-rs's `execute_tokio_future` and // `tokio::spawn` both require `Send`, and `EnteredSpan` is @@ -380,6 +381,97 @@ impl Statement { .await } + /// Execute and return one async-consumption handle — the directResults + /// model (Thrift / JDBC / Python `use_sea`), expressed as a **single** + /// [`ExecutedAsyncStatement`] (no enum, no caller branching). + /// + /// Sends `ExecuteStatement` with the server inline wait (`wait_timeout` + /// omitted ⇒ the server's ~10s default + `on_wait_timeout=CONTINUE`) and + /// returns WITHOUT polling past it. The returned handle is uniform either + /// way: + /// - **fast query** — reached a terminal, succeeded state within the + /// inline wait: the handle is seeded with the inline result + /// ([`ExecutedAsyncStatement::new_with_inline`]), so `await_result()` + /// returns it with **zero** extra round-trips and `status()` reports + /// the terminal state without a poll. This is the latency fast path and + /// is 404-proof (a terminal handle never polls a released statement). + /// - **slow query** — still `Pending`/`Running` after the inline wait: + /// an un-seeded handle the caller polls/cancels via `status()` / + /// `await_result()` / `cancel()`. + /// + /// Why single-threaded callers (napi, the Node driver) need this shape + /// rather than a blocking drive-to-terminal: the handle must come back + /// *before* a long query is terminal so a concurrent `cancel()` can reach + /// it, while a fast query must still commit inline (fire-and-forget DDL/DML) + /// before `close()` can race it. The inline wait threads exactly that + /// needle. A genuinely blocking variant lives at [`execute_to_completion`]. + /// + /// 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(&mut self) -> Result { + let span = self.session.log_span().clone(); + async { + self.invalidate_prior().await; + 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 status = result.status.clone(); + Ok(ExecutedAsyncStatement::new_with_inline( + Arc::clone(&self.session), + result.statement_id.clone(), + valid, + closed, + status, + result, + )) + } + 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(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()` / diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 5ade4065..6a56270d 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -62,7 +62,10 @@ async fn select_one_round_trip() { let session = live_session().await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); - let mut exec = stmt.execute().await.expect("execute SELECT 1"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute SELECT 1"); let stream = exec.result_stream_mut(); stream.next_batch().await.unwrap().unwrap(); @@ -88,7 +91,10 @@ async fn select_with_positional_params() { .unwrap() .param(3, TypedValue::Bool(true)) .unwrap(); - let mut exec = stmt.execute().await.expect("execute with params"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute with params"); let stream = exec.result_stream_mut(); stream.next_batch().await.unwrap().unwrap(); @@ -117,7 +123,10 @@ async fn select_with_named_params() { .unwrap() .param_named("b", TypedValue::Bool(true)) .unwrap(); - let mut exec = stmt.execute().await.expect("execute with named params"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute with named params"); let stream = exec.result_stream_mut(); stream.next_batch().await.unwrap().unwrap(); @@ -148,7 +157,7 @@ async fn mixed_positional_and_named_params_rejected_before_dispatch() { .param_named("n", TypedValue::Int64(99)) .unwrap(); let err = stmt - .execute() + .execute_to_completion() .await .err() .expect("kernel should reject mixed bindings at bind time"); @@ -175,7 +184,7 @@ async fn multi_batch_range_succeeds() { // Large enough to typically span multiple batches via CloudFetch, // but constrained so a tiny warehouse can still complete it. stmt.spec().sql("SELECT * FROM range(100000)"); - let mut exec = stmt.execute().await.expect("execute range"); + let mut exec = stmt.execute_to_completion().await.expect("execute range"); let rows = drain_rows(exec.result_stream_mut()).await; assert_eq!(rows, 100_000, "expected 100k rows from range(100000)"); @@ -190,7 +199,11 @@ async fn select_from_nonexistent_table_returns_sql_error() { let mut stmt = session.statement(); stmt.spec() .sql("SELECT * FROM main.default.__no_such_table_for_v0_e2e"); - let err = stmt.execute().await.err().expect("must fail with SqlError"); + let err = stmt + .execute_to_completion() + .await + .err() + .expect("must fail with SqlError"); assert_eq!(err.code, ErrorCode::SqlError, "{err:?}"); assert!( err.sql_state.is_some(), @@ -205,10 +218,10 @@ async fn re_execute_invalidates_prior_handle() { let session = live_session().await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1"); - let exec_a = stmt.execute().await.expect("execute A"); + let exec_a = stmt.execute_to_completion().await.expect("execute A"); let id_a = exec_a.statement_id().to_owned(); - let exec_b = stmt.execute().await.expect("execute B"); + let exec_b = stmt.execute_to_completion().await.expect("execute B"); assert_ne!(exec_b.statement_id(), id_a, "fresh statement_id expected"); let err = exec_a @@ -255,7 +268,10 @@ async fn select_returns_all_types_correctly() { CAST('2026-05-11 12:34:56' AS TIMESTAMP) AS c_ts, \ CAST(NULL AS INT) AS c_null", ); - let mut exec = stmt.execute().await.expect("execute SELECT all-types"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute SELECT all-types"); let stream = exec.result_stream_mut(); stream.next_batch().await.unwrap().unwrap(); @@ -418,7 +434,10 @@ async fn bind_all_typed_values_round_trip() { .unwrap() .param(12, TypedValue::Null) .unwrap(); - let mut exec = stmt.execute().await.expect("execute bind-all-types"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute bind-all-types"); let stream = exec.result_stream_mut(); stream.next_batch().await.unwrap().unwrap(); @@ -525,7 +544,10 @@ async fn bind_geography_and_geometry_round_trip() { }, ) .unwrap(); - let mut exec = stmt.execute().await.expect("execute geo bind"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute geo bind"); let stream = exec.result_stream_mut(); stream.next_batch().await.unwrap().unwrap(); @@ -572,7 +594,10 @@ async fn binary_sql_literals_and_casts_work() { X'' AS empty_binary, \ CAST('Spark' AS BINARY) AS cast_string", ); - let mut exec = stmt.execute().await.expect("execute binary SQL literals"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute binary SQL literals"); let stream = exec.result_stream_mut(); stream.next_batch().await.unwrap().unwrap(); @@ -612,7 +637,7 @@ async fn bind_binary_typed_value_is_rejected_at_execute_time() { .sql("SELECT ?") .param(1, TypedValue::Binary(vec![0xCA, 0xFE])) .unwrap(); - let err = match stmt.execute().await { + let err = match stmt.execute_to_completion().await { Ok(_) => panic!("Binary must be rejected before wire"), Err(e) => e, }; @@ -657,7 +682,10 @@ async fn cloudfetch_drain_does_not_nest_block_on() { // on the test warehouse. If a future server-side change moves // the inline/external threshold, bump this. stmt.spec().sql("SELECT * FROM range(1000000)"); - let mut exec = stmt.execute().await.expect("execute range(1000000)"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute range(1000000)"); let rows = drain_rows(exec.result_stream_mut()).await; assert_eq!( @@ -687,7 +715,7 @@ async fn cloudfetch_drain_works_on_current_thread_runtime() { let mut stmt = session.statement(); stmt.spec().sql("SELECT * FROM range(1000000)"); let mut exec = stmt - .execute() + .execute_to_completion() .await .expect("execute range(1000000) on current_thread runtime"); @@ -752,7 +780,10 @@ async fn complex_types_as_json_flag_stringifies_complex_columns() { let session = live_session_with_complex_json(false).await; let mut stmt = session.statement(); stmt.spec().sql(sql); - let mut exec = stmt.execute().await.expect("execute (default)"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute (default)"); let stream = exec.result_stream_mut(); let batch = stream.next_batch().await.unwrap().expect("batch (default)"); let ResultBatch::Arrow(batch) = batch else { @@ -790,7 +821,7 @@ async fn complex_types_as_json_flag_stringifies_complex_columns() { let session = live_session_with_complex_json(true).await; let mut stmt = session.statement(); stmt.spec().sql(sql); - let mut exec = stmt.execute().await.expect("execute (json)"); + let mut exec = stmt.execute_to_completion().await.expect("execute (json)"); let stream = exec.result_stream_mut(); let batch = stream.next_batch().await.unwrap().expect("batch (json)"); let ResultBatch::Arrow(batch) = batch else { @@ -863,7 +894,10 @@ async fn live_select_status_accessors_default_to_none() { let session = live_session().await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); - let exec = stmt.execute().await.expect("execute SELECT 1"); + let exec = stmt + .execute_to_completion() + .await + .expect("execute SELECT 1"); // num_modified_rows is None for SELECT. assert_eq!( @@ -901,7 +935,7 @@ async fn live_failed_statement_error_envelope_carries_extended_fields() { // Reference a definitely-nonexistent table to provoke a SqlError. stmt.spec() .sql("SELECT * FROM nonexistent_kernel_pr23_test_table_xyz_123"); - let err = match stmt.execute().await { + let err = match stmt.execute_to_completion().await { Ok(_) => panic!("execute against nonexistent table must fail"), Err(e) => e, }; @@ -949,7 +983,7 @@ async fn sync_canceller_cancels_a_running_execute_mid_compute() { }); // Drive the blocking execute; it must reject (Cancelled), not run to term. - let result = stmt.execute().await; + let result = stmt.execute_to_completion().await; let (id_present, cancelled) = cancel_task.await.expect("cancel task join"); assert!( diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 237f0ece..89afac6b 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -240,7 +240,7 @@ async fn execute_succeeded_inline_returns_one_row() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); - let mut exec = stmt.execute().await.expect("execute"); + let mut exec = stmt.execute_to_completion().await.expect("execute"); let batches = drain(exec.result_stream_mut()).await; assert_eq!(batches.len(), 1); @@ -275,7 +275,7 @@ async fn execute_running_then_succeeded_polls_status() { let mut stmt = session.statement(); stmt.spec().sql("SELECT 42 AS n"); let mut exec = stmt - .execute() + .execute_to_completion() .await .expect("execute should poll to success"); @@ -303,7 +303,7 @@ async fn execute_failed_propagates_sql_state() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELEKT 1"); - let err = match stmt.execute().await { + let err = match stmt.execute_to_completion().await { Ok(_) => panic!("execute should fail on FAILED state"), Err(e) => e, }; @@ -320,7 +320,7 @@ async fn execute_validates_missing_sql() { let session = open_session(&server).await; let mut stmt = session.statement(); - let err = match stmt.execute().await { + let err = match stmt.execute_to_completion().await { Ok(_) => panic!("execute without sql must fail"), Err(e) => e, }; @@ -348,7 +348,10 @@ async fn execute_sends_named_params_in_wire_form() { .sql("SELECT :x") .param_named("x", TypedValue::Int64(1)) .expect("param_named"); - let mut exec = stmt.execute().await.expect("execute with named params"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute with named params"); let batches = drain(exec.result_stream_mut()).await; assert_eq!(batches[0].num_rows(), 1); exec.close().await.expect("close"); @@ -369,7 +372,7 @@ async fn execute_rejects_binary_typed_value_before_wire() { .sql("SELECT ?") .param(1, TypedValue::Binary(vec![0xCA, 0xFE])) .unwrap(); - let err = match stmt.execute().await { + let err = match stmt.execute_to_completion().await { Ok(_) => panic!("Binary must be rejected before any wire call"), Err(e) => e, }; @@ -398,7 +401,10 @@ async fn execute_sends_positional_params_in_wire_form() { .unwrap() .param(2, TypedValue::String("bound".into())) .unwrap(); - let mut exec = stmt.execute().await.expect("execute with params"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute with params"); let batches = drain(exec.result_stream_mut()).await; assert_eq!(batches[0].num_rows(), 1); exec.close().await.expect("close"); @@ -446,11 +452,11 @@ async fn re_execute_invalidates_prior_handle() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1"); - let exec_a = stmt.execute().await.expect("execute A"); + let exec_a = stmt.execute_to_completion().await.expect("execute A"); assert_eq!(exec_a.statement_id(), "stmt-A"); // Re-execute on the same Statement invalidates exec_a. - let _exec_b = stmt.execute().await.expect("execute B"); + let _exec_b = stmt.execute_to_completion().await.expect("execute B"); let err = exec_a .cancel() .await @@ -470,7 +476,7 @@ async fn executed_close_is_idempotent() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1"); - let exec = stmt.execute().await.unwrap(); + let exec = stmt.execute_to_completion().await.unwrap(); exec.close().await.expect("first close"); // Second close short-circuits without hitting the wire. exec.close().await.expect("second close — idempotent"); @@ -499,7 +505,7 @@ async fn statement_close_cancels_and_closes_outstanding_executed_handle() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1"); - let exec = stmt.execute().await.expect("execute"); + let exec = stmt.execute_to_completion().await.expect("execute"); assert_eq!(exec.statement_id(), "stmt-Z"); // Close the parent Statement (not the executed handle). The @@ -538,7 +544,7 @@ async fn row_accessors_walk_succeeded_result() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT id, name FROM t"); - let mut exec = stmt.execute().await.unwrap(); + let mut exec = stmt.execute_to_completion().await.unwrap(); let stream = exec.result_stream_mut(); stream.next_batch().await.unwrap().unwrap(); @@ -604,7 +610,7 @@ async fn kernel_invariant_parent_drop_invalidates_executed_cancel() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); - let exec = stmt.execute().await.expect("execute"); + let exec = stmt.execute_to_completion().await.expect("execute"); // This is the exact shape the napi binding's // `Connection::execute_statement` produces today (PR #25): the @@ -723,7 +729,7 @@ async fn executed_statement_surfaces_extended_status_fields() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("UPDATE t SET x = 1"); - let exec = stmt.execute().await.expect("execute"); + let exec = stmt.execute_to_completion().await.expect("execute"); assert_eq!(exec.num_modified_rows(), Some(7)); assert_eq!(exec.display_message(), Some("All good")); @@ -748,7 +754,7 @@ async fn executed_statement_status_fields_default_to_none() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); - let exec = stmt.execute().await.expect("execute"); + let exec = stmt.execute_to_completion().await.expect("execute"); assert_eq!(exec.num_modified_rows(), None); assert_eq!(exec.display_message(), None); @@ -801,7 +807,7 @@ async fn polling_path_carries_terminal_status_not_initial() { let mut stmt = session.statement(); stmt.spec().sql("UPDATE t SET x = 1"); let exec = stmt - .execute() + .execute_to_completion() .await .expect("execute should poll to terminal SUCCEEDED"); @@ -848,7 +854,7 @@ async fn execute_failed_carries_extended_status_fields_onto_error() { let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT * FROM does_not_exist"); - let err = match stmt.execute().await { + let err = match stmt.execute_to_completion().await { Ok(_) => panic!("execute should fail on FAILED state"), Err(e) => e, }; @@ -975,7 +981,7 @@ async fn execute_cloudfetch_chunk0_failure_closes_statement() { stmt.spec().sql("SELECT id FROM range(2000000)"); let err = stmt - .execute() + .execute_to_completion() .await .err() .expect("execute must fail when chunk-0 returns HTTP 500"); diff --git a/tests/v0_query_tags_headers_e2e.rs b/tests/v0_query_tags_headers_e2e.rs index 5f7242cd..fa4c2489 100644 --- a/tests/v0_query_tags_headers_e2e.rs +++ b/tests/v0_query_tags_headers_e2e.rs @@ -109,7 +109,10 @@ async fn query_tags_round_trip_succeeds() { stmt.spec().sql("SELECT 1 AS n"); stmt.spec().query_tags(tags).expect("query_tags accepted"); - let mut exec = stmt.execute().await.expect("execute with query tags"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute with query tags"); assert_select_one(exec.result_stream_mut()).await; exec.close().await.expect("close"); session.close().await.expect("session close"); @@ -130,7 +133,10 @@ async fn query_tags_with_none_value_succeeds() { .query_tags(tags) .expect("query_tags (with None value) accepted"); - let mut exec = stmt.execute().await.expect("execute with bare-key tag"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute with bare-key tag"); assert_select_one(exec.result_stream_mut()).await; exec.close().await.expect("close"); session.close().await.expect("session close"); @@ -160,7 +166,10 @@ async fn custom_http_headers_round_trip_succeeds() { .await; let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); - let mut exec = stmt.execute().await.expect("execute with custom headers"); + let mut exec = stmt + .execute_to_completion() + .await + .expect("execute with custom headers"); assert_select_one(exec.result_stream_mut()).await; exec.close().await.expect("close"); session.close().await.expect("session close"); @@ -183,7 +192,7 @@ async fn custom_authorization_header_is_dropped_and_real_auth_wins() { let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); let mut exec = stmt - .execute() + .execute_to_completion() .await .expect("execute must succeed — the real PAT wins, the bogus Authorization is dropped"); assert_select_one(exec.result_stream_mut()).await; diff --git a/tests/v0_tls_e2e.rs b/tests/v0_tls_e2e.rs index 1826446c..d2a5d2ac 100644 --- a/tests/v0_tls_e2e.rs +++ b/tests/v0_tls_e2e.rs @@ -131,7 +131,7 @@ async fn assert_select_one(session: &Session) { let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); let mut exec = stmt - .execute() + .execute_to_completion() .await .expect("execute SELECT 1 through proxy"); let stream: &mut ResultStream = exec.result_stream_mut(); @@ -160,7 +160,7 @@ async fn tls_fails_without_config_behind_intercepting_proxy() { // also exercise a query before concluding the connection "worked". let mut stmt = session.statement(); stmt.spec().sql("SELECT 1"); - let exec = stmt.execute().await; + let exec = stmt.execute_to_completion().await; assert!( exec.is_err(), "expected an untrusted-certificate failure behind mitmproxy with default TLS, \