Skip to content
Merged
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
15 changes: 15 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions napi/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Statement, AsyncStatement>`
(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

Expand Down
135 changes: 82 additions & 53 deletions napi/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String>` whose iteration order is
Expand Down Expand Up @@ -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<i64>,
/// 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<u32>,
/// 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
Expand Down Expand Up @@ -194,18 +178,13 @@ 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,
sql: String,
statement_conf: Option<HashMap<String, String>>,
query_tags: Option<HashMap<String, Option<String>>>,
row_limit: Option<i64>,
query_timeout_secs: Option<u32>,
positional_params: Vec<TypedValue>,
named_params: Vec<(String, TypedValue)>,
) -> napi::Result<databricks_sql_kernel::Statement> {
Expand All @@ -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()
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -353,7 +328,6 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
query_timeout_secs,
positional_params,
named_params,
)?
Expand All @@ -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<ExecuteOptions>,
) -> napi::Result<napi::Either<Statement, AsyncStatement>> {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MODERATE CONFIDENCE — 2 reviewers]

The kernel models the union correctly (DirectStatement::{Completed, Running}, exhaustively matchable). Both bindings throw the tag away: this napi method returns Either<Statement, AsyncStatement> (opaque #[napi] classes with no discriminant — TS cannot narrow the union), and pyo3 returns untyped Bound<PyAny>. The only discrimination mechanism is probing for awaitResult/await_result.

Verified sound today (those methods exist only on the async arm), but soundness rests on an unenforced invariant: the day someone adds an awaitResult-named method (or shim) to Statement, every consumer silently misroutes — and since the Running arm lacks fetchNextBatch, mis-discrimination yields a runtime TypeError, not a typed error. The consumer (databricks-sql-nodejs#426) already needs an as unknown as double-cast to defeat the type checker, which corroborates the gap.

Suggestion: add an explicit kind/boolean discriminant per arm so TS can narrow and Python can branch safely; at minimum document the feature-detect as a load-bearing contract and add a kernel test asserting Statement never gains an awaitResult/await_result member.

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*.
Expand All @@ -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]
Expand All @@ -397,11 +438,8 @@ impl Connection {
mut options: Option<ExecuteOptions>,
) -> napi::Result<crate::cancellable::CancellableExecution> {
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())
Expand Down Expand Up @@ -433,7 +471,6 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
query_timeout_secs,
positional_params,
named_params,
)?
Expand All @@ -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,
Expand All @@ -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()
Expand Down Expand Up @@ -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,
)?
Expand Down
9 changes: 4 additions & 5 deletions napi/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<String>> {
let inner = Arc::clone(&self.inner);
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,
};
Loading
Loading