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 diff --git a/napi/src/connection.rs b/napi/src/connection.rs index d9d17287..cd9d2d7f 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,11 +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); - 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 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()) @@ -353,7 +328,6 @@ impl Connection { statement_conf, query_tags, row_limit, - query_timeout_secs, positional_params, named_params, )? @@ -370,6 +344,75 @@ impl Connection { .await } + /// directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + /// 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; + /// - 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. + /// + /// **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, + 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 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, + 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*. @@ -385,9 +428,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] @@ -397,11 +438,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. + // Same option decoding as `execute_statement`. 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()) @@ -433,7 +471,6 @@ impl Connection { statement_conf, query_tags, row_limit, - query_timeout_secs, positional_params, named_params, )? @@ -456,14 +493,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, @@ -473,9 +507,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() @@ -507,14 +538,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/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/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..27637b2b 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,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), @@ -260,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), @@ -329,21 +331,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) @@ -787,6 +785,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..a1f7afdf 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,22 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { params: &ExecuteParams, ) -> Result; + /// 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 + /// [`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/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/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..aea2c76f 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 @@ -84,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), } } @@ -133,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, @@ -380,6 +396,115 @@ impl Statement { .await } + /// directResults execute — the Thrift/JDBC model. + /// + /// 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 + /// [`Statement::execute`]'s fast path; + /// - [`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. 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 + /// 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)` 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. + 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 = match self + .session + .transport() + .execute_statement_direct(self.session.session_id(), &sql, &exec_params) + .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 { + 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()` / @@ -653,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] 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() {