Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion napi/src/cancellable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
59 changes: 18 additions & 41 deletions napi/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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<ExecuteOptions>,
) -> napi::Result<Statement> {
) -> napi::Result<AsyncStatement> {
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())
Expand All @@ -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)?;
Expand All @@ -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
}
Expand Down
61 changes: 42 additions & 19 deletions pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ExecutedStatement> {
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
Expand All @@ -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<ExecutedAsyncStatement> {
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<ExecutedStatement> {
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.
Expand Down
2 changes: 1 addition & 1 deletion src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
105 changes: 85 additions & 20 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -787,6 +788,70 @@ impl Transport for SeaRestTransport {
.await
}

async fn execute_statement_direct(
&self,
session_id: &str,
sql: &str,
params: &ExecuteParams,
) -> Result<DirectOutcome> {
// 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<Option<ExecuteResult>> {
let response = self.get_statement_status(statement_id).await?;
match Self::terminal_outcome(response) {
Expand Down
32 changes: 32 additions & 0 deletions src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -244,6 +261,21 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {
params: &ExecuteParams,
) -> Result<ExecuteResult>;

/// 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<DirectOutcome>;

/// Submit a SQL statement without polling for completion.
///
/// Returns whatever the server replied with on the initial
Expand Down
8 changes: 8 additions & 0 deletions src/reader/cloudfetch/link_fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,14 @@ mod tests {
) -> Result<crate::client::ExecuteResponse> {
unimplemented!("submit_statement not used by the link-fetcher mock")
}
async fn execute_statement_direct(
&self,
_session_id: &str,
_sql: &str,
_params: &ExecuteParams,
) -> Result<crate::client::DirectOutcome> {
unimplemented!("execute_statement_direct not used by the link-fetcher mock")
}

async fn fetch_completed_result(
&self,
Expand Down
Loading
Loading