From 639e19ef97decc1c5aa2365c0b3a229c1ccd5b58 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Thu, 4 Jun 2026 11:15:38 +0000 Subject: [PATCH 1/5] feat(napi): expose sync StatementCanceller via executeStatementCancellable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The blocking `Connection.executeStatement` builds a kernel `Statement`, awaits `execute()` (which polls to terminal), and only then hands JS a `Statement` wrapper — so a query running for several seconds server-side is uncancellable from JS on that path (no handle until the blocking call resolves). Add `Connection.executeStatementCancellable(sql, opts)` returning a `CancellableExecution` handle that captures a detached `StatementCanceller` BEFORE dispatching `execute()`, then exposes: - `result()` — drives the blocking execute, resolves to a `Statement` identical to what `executeStatement` returns; - `cancel()` — fires the detached canceller lock-free, interrupting a still-running `result()` mid-COMPUTE; - `statementId` getter for log correlation while in flight. Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` split (PR #121) and the napi `AsyncStatement` detached-canceller pattern. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/cancellable.rs | 158 ++++++++++++++++++++++++++++++++++++++++ napi/src/connection.rs | 74 +++++++++++++++++++ napi/src/lib.rs | 1 + napi/src/statement.rs | 2 +- 4 files changed, 234 insertions(+), 1 deletion(-) create mode 100644 napi/src/cancellable.rs diff --git a/napi/src/cancellable.rs b/napi/src/cancellable.rs new file mode 100644 index 00000000..f5c7241a --- /dev/null +++ b/napi/src/cancellable.rs @@ -0,0 +1,158 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Cancellable sync-execute handle. +//! +//! The blocking `Connection.executeStatement` builds a kernel +//! `Statement`, awaits `execute()` (which polls to a terminal state), +//! and only then hands JS a `Statement` wrapper. A query that runs for +//! several seconds server-side is therefore *uncancellable* from JS on +//! that path — there is no handle to call `cancel()` on until the +//! blocking call has already resolved. +//! +//! `Connection.executeStatementCancellable` closes that gap. It builds +//! the kernel `Statement`, captures a detached +//! [`StatementCanceller`](databricks_sql_kernel::StatementCanceller) +//! **before** dispatching `execute()`, and returns a +//! `CancellableExecution` handle that exposes: +//! +//! - `cancel()` — fires the detached canceller (session + the shared +//! in-flight-id slot). Lock-free: it does not contend with the +//! in-flight `result()`. Once the transport publishes the server +//! statement id mid-execute, the cancel reaches a still-running query; +//! if fired before the id is observed it is a no-op (the kernel's +//! per-execute drop guard still covers the future-dropped case). +//! - `result()` — drives the blocking `execute()` and resolves to a +//! `Statement` (the same wrapper `executeStatement` returns), ready to +//! stream batches. +//! +//! This mirrors `AsyncStatement` on the submit path (which captures an +//! `AsyncStatementCanceller` at construction so `cancel()` interrupts an +//! in-flight `awaitResult()`), and the pyo3 `Statement.canceller()` / +//! `Statement.execute()` split from PR #121 — the canceller is obtained +//! before the blocking drive so a concurrent task can cancel a running +//! query. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use tokio::sync::Mutex; + +use databricks_sql_kernel::{Statement as KernelStatement, StatementCanceller}; + +use crate::error::napi_err_from_kernel; +use crate::statement::{statement_closed_err, Statement}; +use crate::util::guarded; + +/// Handle returned by `Connection.executeStatementCancellable`. Owns the +/// built-but-not-yet-executed kernel `Statement` plus a detached +/// [`StatementCanceller`] captured before dispatch, so JS can fire a +/// server-side cancel while the blocking `result()` is in flight. +/// +/// `pending` is `Arc>>` so `result()` can +/// `.take()` the statement (the kernel `execute()` borrows it `&mut`, +/// then it moves into the produced `Statement` wrapper to keep its +/// `ValidityFlag` set — see `statement.rs`). A second `result()` call +/// after the first resolved surfaces `InvalidStatementHandle`. +#[napi] +pub struct CancellableExecution { + /// The built kernel `Statement`, awaiting its blocking `execute()`. + /// Taken by the first `result()` call. + pending: Arc>>, + /// Detached canceller (session + shared in-flight-id slot), captured + /// before `execute()` dispatches. Held **outside** `pending` so + /// `cancel()` never contends for the mutex `result()` holds across + /// the blocking drive. Cheap to clone (two `Arc` bumps). + canceller: StatementCanceller, + /// Lock-free guard against a `result()` after the statement was + /// taken. Set by `result()` before it takes `pending`; read by a + /// second `result()` so the double-drive surfaces + /// `InvalidStatementHandle` without taking the mutex. + consumed: Arc, +} + +impl CancellableExecution { + /// Crate-internal constructor — called from + /// `Connection::execute_statement_cancellable` once the kernel + /// `Statement` is built (SQL + params + conf set) but **before** + /// `execute()` is dispatched. Captures the canceller off the + /// statement here so it targets the execution `result()` will drive. + pub(crate) fn new(stmt: KernelStatement) -> Self { + let canceller = stmt.canceller(); + Self { + pending: Arc::new(Mutex::new(Some(stmt))), + canceller, + consumed: Arc::new(AtomicBool::new(false)), + } + } +} + +#[napi] +impl CancellableExecution { + /// The server-issued statement id this execution targets, if the + /// server has issued one yet (`null` before the initial submit + /// round-trip publishes it mid-`result()`). Useful for log + /// correlation while the blocking drive is in flight. + #[napi(getter)] + pub fn statement_id(&self) -> Option { + self.canceller.statement_id() + } + + /// Drive the blocking `execute()` and resolve to a `Statement` + /// (identical to what `executeStatement` returns) once the kernel + /// reaches a terminal state and the result stream is ready. + /// + /// Consumes the pending statement: a second `result()` call returns + /// `KernelError(InvalidStatementHandle)`. The future is + /// drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` + /// guard fires a fire-and-forget `cancel_statement` if this future is + /// dropped mid-flight (`Promise.race` / timeout loser), independently + /// of an explicit `cancel()`. + #[napi] + pub async fn result(&self) -> napi::Result { + // Mark consumed before taking, so a racing second `result()` + // short-circuits to the closed error rather than awaiting a + // taken-out statement. + if self.consumed.swap(true, Ordering::AcqRel) { + return Err(statement_closed_err()); + } + let pending = Arc::clone(&self.pending); + guarded(async move { + let mut stmt = { + let mut guard = pending.lock().await; + guard.take().ok_or_else(statement_closed_err)? + }; + let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; + // Pass the parent kernel `Statement` into the JS wrapper so + // its `Drop` doesn't invalidate the executed handle via the + // shared `ValidityFlag` — same rationale as + // `Connection::execute_statement`. + Ok(Statement::from_executed(stmt, executed)) + }) + .await + } + + /// Server-side cancel of the in-flight statement. + /// + /// Lock-free: fires the detached `StatementCanceller` captured at + /// construction rather than taking the mutex `result()` holds, so it + /// interrupts a still-running blocking `result()` instead of queueing + /// behind it. No-op (returns `Ok`) if no statement id has been + /// observed yet (query still in its initial submit round-trip), and + /// idempotent against a server already in a terminal state. + #[napi] + pub async fn cancel(&self) -> napi::Result<()> { + let canceller = self.canceller.clone(); + guarded(async move { canceller.cancel().await.map_err(napi_err_from_kernel) }).await + } +} diff --git a/napi/src/connection.rs b/napi/src/connection.rs index f1c89219..d9d17287 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -370,6 +370,80 @@ impl Connection { .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*. + /// + /// `executeStatement` builds the kernel `Statement`, awaits the + /// blocking `execute()`, and only then hands JS a `Statement` — so a + /// query that runs for several seconds is uncancellable from JS on + /// that path (there is no handle until the blocking call resolves). + /// This method instead builds the statement, captures a detached + /// `StatementCanceller` **before** dispatching `execute()`, and hands + /// JS a `CancellableExecution` immediately. The caller drives the + /// blocking execution via `result()` (resolves to the same + /// `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). + /// Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` + /// split (PR #121): obtain the canceller before the blocking drive. + #[napi] + pub async fn execute_statement_cancellable( + &self, + sql: String, + mut options: Option, + ) -> napi::Result { + let inner = Arc::clone(&self.inner); + // Same option decoding as `execute_statement` — `queryTimeoutSecs` + // IS honoured here (sync execute path), so it is read and threaded + // through `build_statement` like the rest of the knobs. + let row_limit = options.as_ref().and_then(|o| o.row_limit); + let query_timeout_secs = options.as_ref().and_then(|o| o.query_timeout_secs); + let positional_params = options + .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 { + // Build the kernel `Statement` under the session lock, release + // the lock, then hand the built statement to the + // `CancellableExecution` WITHOUT dispatching `execute()` here — + // the blocking drive runs in `CancellableExecution::result()`, + // after JS has the cancellable handle in hand. The canceller is + // captured inside `CancellableExecution::new` off the built + // statement before any execute dispatch. + let stmt = { + let guard = inner.lock().await; + let session = guard.as_ref().ok_or_else(connection_closed_err)?; + build_statement( + session, + sql, + statement_conf, + query_tags, + row_limit, + query_timeout_secs, + positional_params, + named_params, + )? + // session lock released here + }; + Ok(crate::cancellable::CancellableExecution::new(stmt)) + }) + .await + } + /// Submit a SQL statement and return immediately with an /// `AsyncStatement` handle, without blocking until the query /// finishes. The kernel's `Statement::submit()` sends diff --git a/napi/src/lib.rs b/napi/src/lib.rs index 810c4889..ee134cfa 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -40,6 +40,7 @@ extern crate napi_derive; pub(crate) mod async_statement; +pub(crate) mod cancellable; pub(crate) mod connection; pub(crate) mod database; pub(crate) mod error; diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 13118901..9df01251 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -537,7 +537,7 @@ impl Drop for Statement { /// (fetch_next_batch / cancel and their Connection-side cousin) — /// keeps the wire-message shape stable for the TS reviver's contract /// test. -fn statement_closed_err() -> napi::Error { +pub(crate) fn statement_closed_err() -> napi::Error { napi_err_from_kernel( KernelError::invalid_statement_handle().message("statement already closed"), ) From 0fa1958761479dab962f5eb0475d27514c4179c6 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Thu, 4 Jun 2026 14:24:09 +0000 Subject: [PATCH 2/5] test(e2e): sync StatementCanceller cancels a running execute mid-compute Adds the missing live e2e coverage for the sync-cancel surface (the `StatementCanceller` from #121 that #122 exposes over napi): obtain a detached canceller before execute(), drive a ~1e12-row cross join, cancel 13s in (past the ~10s wait-timeout window so the statement_id is published), and assert the blocking execute() rejects instead of running to completion. Finding documented in the test: the sync execute() path currently surfaces a server-side cancel as `InvalidArgument` (the async path returns `Cancelled`); the napi/pyo3 wrappers normalise it to a cancelled status client-side. The assertion accepts both so it stays green before and after that is normalised. Verified live (13.6s; statement cancelled server-side). Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- tests/v0_execute_e2e.rs | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index c1201aec..b8ddbad0 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -923,3 +923,56 @@ async fn live_failed_statement_error_envelope_carries_extended_fields() { session.close().await.expect("session close"); } + +// Sync-cancel surface (#121 core + #122 napi): a detached `StatementCanceller` +// obtained BEFORE `execute()` cancels a still-running blocking execute. Past the +// server's ~10s wait-timeout window the statement_id is published into the +// shared inflight slot, so `cancel()` reaches the running query (before that +// window it is a tolerant no-op — a documented kernel-core property). +#[tokio::test] +#[ignore] +async fn sync_canceller_cancels_a_running_execute_mid_compute() { + let session = live_session().await; + let mut stmt = session.statement(); + // ~1e12-row cross join: runs for minutes, so it cannot complete before the + // cancel — the assertion below proves the cancel actually took effect. + stmt.spec() + .sql("SELECT count(*) FROM range(0,1000000) a CROSS JOIN range(0,1000000) b WHERE (a.id*b.id)%7=3"); + + // Detached canceller captured before dispatch — the whole point of the API. + let canceller = stmt.canceller(); + let cancel_task = tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(13)).await; + let id_present = canceller.statement_id().is_some(); + let cancelled = canceller.cancel().await; + (id_present, cancelled) + }); + + // Drive the blocking execute; it must reject (Cancelled), not run to term. + let result = stmt.execute().await; + let (id_present, cancelled) = cancel_task.await.expect("cancel task join"); + + assert!( + id_present, + "statement_id must be published before cancel (past the wait-timeout window)" + ); + cancelled.expect("cancel() should succeed"); + let err = result + .err() + .expect("execute() must reject after a server-side cancel, not run to completion"); + // The invariant that matters: the cancel interrupted the running execute + // (it errored ~13s in, not after running the 1e12-row cross join to term). + // KERNEL QUIRK (follow-up): the sync execute() path currently surfaces a + // server-side cancel as `InvalidArgument`, whereas the async path returns + // `Cancelled`. The napi/pyo3 wrappers map it to a cancelled status via their + // client-side cancel flag, so callers still observe "cancelled". Accept both + // so this test stays green today and after the code is normalised to + // `Cancelled`. + assert!( + matches!(err.code, ErrorCode::Cancelled | ErrorCode::InvalidArgument), + "cancelled execute should error (Cancelled, or today's InvalidArgument), got {:?}", + err.code + ); + + session.close().await.expect("session close"); +} From 9a509048d53629f863b6ebd540e3e09556d45a11 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Thu, 4 Jun 2026 16:39:51 +0000 Subject: [PATCH 3/5] feat(napi): normalise sync-cancel to Cancelled + gate redundant cancel RPC MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the #122 review (gopalldb): - P1.2: `CancellableExecution::result()` now normalises the kernel's sync-cancel quirk — `execute()` surfaces a server-side cancel as `InvalidArgument` (the async path returns `Cancelled`) — into `Cancelled` when this handle's `cancel()` fired (tracked via a `cancel_fired` AtomicBool). So every napi consumer sees a single cancelled-status code regardless of execution path, rather than relying on each wrapper's own client-side mapping. Verified end-to-end against a live warehouse: a mid-compute `cancel()` makes `result()` reject with `{"code":"Cancelled"}` (was `InvalidArgument`). - P2.3: `cancel()` skips the server-side cancel RPC once `result()` has finished successfully (a `finished` AtomicBool), matching the post-completion gating on `AsyncStatement`/`Statement` — no redundant no-op-at-server call / confusing log line. - P2.4: documented the API-shape asymmetry vs pyo3 (napi exposes a single `Connection.executeStatementCancellable -> CancellableExecution`; pyo3 splits it across `Statement.canceller()` / `Statement.execute()`). - P1.2 doc: corrected the e2e test comment — the core `Statement::execute()` still returns `InvalidArgument`; the napi layer is what normalises to `Cancelled` (this PR). pyo3 does not yet. cargo fmt / clippy -D warnings / `cargo test --lib` (620) green; core e2e sync-cancel green. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/cancellable.rs | 79 +++++++++++++++++++++++++++++++++++------ tests/v0_execute_e2e.rs | 12 +++---- 2 files changed, 75 insertions(+), 16 deletions(-) diff --git a/napi/src/cancellable.rs b/napi/src/cancellable.rs index f5c7241a..2faacc1e 100644 --- a/napi/src/cancellable.rs +++ b/napi/src/cancellable.rs @@ -43,12 +43,23 @@ //! `Statement.execute()` split from PR #121 — the canceller is obtained //! before the blocking drive so a concurrent task can cancel a running //! query. +//! +//! **API-shape note (vs pyo3):** the two bindings expose the same capability +//! with different shapes. pyo3 splits it across the statement builder — +//! `stmt.canceller()` returns a detached canceller and `stmt.execute()` drives +//! the blocking call separately. napi instead returns a single combined +//! `CancellableExecution` from `Connection.executeStatementCancellable(...)` +//! that owns both halves (`cancel()` + `result()`), because the napi surface +//! has no exposed builder-shape `Statement` to hang a `canceller()` off. Same +//! semantics, fewer moving parts for the JS caller. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::{Statement as KernelStatement, StatementCanceller}; +use databricks_sql_kernel::{ + Error as KernelError, ErrorCode, Statement as KernelStatement, StatementCanceller, +}; use crate::error::napi_err_from_kernel; use crate::statement::{statement_closed_err, Statement}; @@ -79,6 +90,15 @@ pub struct CancellableExecution { /// second `result()` so the double-drive surfaces /// `InvalidStatementHandle` without taking the mutex. consumed: Arc, + /// Set by `cancel()`. Read in `result()`'s error arm to normalise the + /// kernel's sync-cancel quirk (`execute()` surfaces a server-side cancel + /// as `InvalidArgument`, not `Cancelled`) into `Cancelled`, so every napi + /// consumer sees a consistent cancelled status — matching the async path. + cancel_fired: Arc, + /// Set by `result()` once it resolves successfully. Read by `cancel()` to + /// skip a redundant server-side cancel RPC on an already-finished + /// statement (parity with `AsyncStatement`/`Statement` cancel gating). + finished: Arc, } impl CancellableExecution { @@ -93,6 +113,8 @@ impl CancellableExecution { pending: Arc::new(Mutex::new(Some(stmt))), canceller, consumed: Arc::new(AtomicBool::new(false)), + cancel_fired: Arc::new(AtomicBool::new(false)), + finished: Arc::new(AtomicBool::new(false)), } } } @@ -118,6 +140,12 @@ impl CancellableExecution { /// guard fires a fire-and-forget `cancel_statement` if this future is /// dropped mid-flight (`Promise.race` / timeout loser), independently /// of an explicit `cancel()`. + /// + /// On a server-side cancel the kernel's blocking `execute()` currently + /// surfaces `InvalidArgument` (a known kernel quirk — the async path + /// returns `Cancelled`). When this handle's `cancel()` fired, we normalise + /// that into `Cancelled` here so JS callers can rely on a single + /// cancelled-status code regardless of execution path. #[napi] pub async fn result(&self) -> napi::Result { // Mark consumed before taking, so a racing second `result()` @@ -127,17 +155,39 @@ impl CancellableExecution { return Err(statement_closed_err()); } let pending = Arc::clone(&self.pending); + let cancel_fired = Arc::clone(&self.cancel_fired); + let finished = Arc::clone(&self.finished); guarded(async move { let mut stmt = { let mut guard = pending.lock().await; guard.take().ok_or_else(statement_closed_err)? }; - let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; - // Pass the parent kernel `Statement` into the JS wrapper so - // its `Drop` doesn't invalidate the executed handle via the - // shared `ValidityFlag` — same rationale as - // `Connection::execute_statement`. - Ok(Statement::from_executed(stmt, executed)) + match stmt.execute().await { + Ok(executed) => { + // Mark finished so a later `cancel()` skips a redundant RPC. + finished.store(true, Ordering::Release); + // Pass the parent kernel `Statement` into the JS wrapper so + // its `Drop` doesn't invalidate the executed handle via the + // shared `ValidityFlag` — same rationale as + // `Connection::execute_statement`. + Ok(Statement::from_executed(stmt, executed)) + } + Err(kernel_err) => { + // Normalise the sync-cancel `InvalidArgument` quirk into + // `Cancelled` when the caller fired `cancel()`. Any other + // failure (or a non-cancel `InvalidArgument`) passes through + // verbatim. + if cancel_fired.load(Ordering::Acquire) + && kernel_err.code == ErrorCode::InvalidArgument + { + Err(napi_err_from_kernel( + KernelError::cancelled().message("statement cancelled by client"), + )) + } else { + Err(napi_err_from_kernel(kernel_err)) + } + } + } }) .await } @@ -147,11 +197,20 @@ impl CancellableExecution { /// Lock-free: fires the detached `StatementCanceller` captured at /// construction rather than taking the mutex `result()` holds, so it /// interrupts a still-running blocking `result()` instead of queueing - /// behind it. No-op (returns `Ok`) if no statement id has been - /// observed yet (query still in its initial submit round-trip), and - /// idempotent against a server already in a terminal state. + /// behind it. No-op (returns `Ok`) if `result()` already finished + /// successfully, or if no statement id has been observed yet (query still + /// in its initial submit round-trip), and idempotent against a server + /// already in a terminal state. #[napi] pub async fn cancel(&self) -> napi::Result<()> { + // Skip the server-side cancel RPC if the statement already finished — + // it would be a redundant no-op-at-server call and a confusing log line. + if self.finished.load(Ordering::Acquire) { + return Ok(()); + } + // Record intent so `result()` can normalise the kernel's sync-cancel + // `InvalidArgument` into `Cancelled`. + self.cancel_fired.store(true, Ordering::Release); let canceller = self.canceller.clone(); guarded(async move { canceller.cancel().await.map_err(napi_err_from_kernel) }).await } diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index b8ddbad0..5ade4065 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -962,12 +962,12 @@ async fn sync_canceller_cancels_a_running_execute_mid_compute() { .expect("execute() must reject after a server-side cancel, not run to completion"); // The invariant that matters: the cancel interrupted the running execute // (it errored ~13s in, not after running the 1e12-row cross join to term). - // KERNEL QUIRK (follow-up): the sync execute() path currently surfaces a - // server-side cancel as `InvalidArgument`, whereas the async path returns - // `Cancelled`. The napi/pyo3 wrappers map it to a cancelled status via their - // client-side cancel flag, so callers still observe "cancelled". Accept both - // so this test stays green today and after the code is normalised to - // `Cancelled`. + // KERNEL QUIRK: this CORE `Statement::execute()` path surfaces a server-side + // cancel as `InvalidArgument`, whereas the async path returns `Cancelled`. + // The napi `CancellableExecution` normalises it to `Cancelled` at the + // binding layer (see napi/src/cancellable.rs — done in this PR); pyo3 does + // not yet. This core test asserts the raw kernel behaviour, so it accepts + // both — and stays green if/when the core itself is normalised to `Cancelled`. assert!( matches!(err.code, ErrorCode::Cancelled | ErrorCode::InvalidArgument), "cancelled execute should error (Cancelled, or today's InvalidArgument), got {:?}", From dcbbf5746e3f21655934188886b5af6c1104f230 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Thu, 4 Jun 2026 18:01:02 +0000 Subject: [PATCH 4/5] fix(napi): gate cancel-normalisation on real dispatch + make it unit-testable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the #122 round-2 review (gopalldb): - P1.1 (correctness bug): a first-window `cancel()` (before the statement_id is published) dispatches no RPC, yet it was still setting `cancel_fired` — so a later GENUINE `InvalidArgument` (a real SQL/parse/type error) got mislabelled `Cancelled` and its diagnostic discarded. `cancel()` now sets `cancel_fired` only when a server-side cancel actually dispatched (statement_id observed), so the normalisation keys on "we issued a cancel", not "JS called cancel()". - P1.2 (testability): factored the error-normalisation into a pure `normalize_execute_err(err, cancel_fired) -> KernelError` and added offline unit tests — (InvalidArgument, dispatched)→Cancelled, (InvalidArgument, not-dispatched)→InvalidArgument (diagnostic preserved), (NetworkError, dispatched)→NetworkError. (napi crate: 44 tests.) - P2.3: `terminal` flag (renamed from `finished`) is now set in BOTH arms of `result()` (success and error), so a defensive `cancel()` after any terminal state skips the redundant RPC — not just after success. - P2.4: the flag-ordering race is resolved as a side effect of P1.1 (the flag is only set after dispatch). - P2.5: documented the three racing outcomes (natural completion / dispatched cancel / dropped-future drop-guard) and which one yields a Cancelled code. fmt / clippy -D warnings / napi `cargo test` (44) green; happy-path mid-compute cancel re-verified live → `result()` rejects with `{"code":"Cancelled"}`. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/cancellable.rs | 152 ++++++++++++++++++++++++++++------------ 1 file changed, 107 insertions(+), 45 deletions(-) diff --git a/napi/src/cancellable.rs b/napi/src/cancellable.rs index 2faacc1e..52af999f 100644 --- a/napi/src/cancellable.rs +++ b/napi/src/cancellable.rs @@ -90,15 +90,20 @@ pub struct CancellableExecution { /// second `result()` so the double-drive surfaces /// `InvalidStatementHandle` without taking the mutex. consumed: Arc, - /// Set by `cancel()`. Read in `result()`'s error arm to normalise the - /// kernel's sync-cancel quirk (`execute()` surfaces a server-side cancel - /// as `InvalidArgument`, not `Cancelled`) into `Cancelled`, so every napi - /// consumer sees a consistent cancelled status — matching the async path. + /// Set by `cancel()` **only when it actually dispatched a server-side + /// cancel** (a statement id was already observed). Read in `result()`'s + /// error arm to normalise the kernel's sync-cancel quirk (`execute()` + /// surfaces a server-side cancel as `InvalidArgument`, not `Cancelled`) + /// into `Cancelled`. Gating on real dispatch — rather than merely "JS + /// called `cancel()`" — is what keeps a first-window no-op `cancel()` from + /// mis-attributing an unrelated `InvalidArgument` (a genuine SQL/parse + /// error) as cancelled and discarding its diagnostic. cancel_fired: Arc, - /// Set by `result()` once it resolves successfully. Read by `cancel()` to - /// skip a redundant server-side cancel RPC on an already-finished - /// statement (parity with `AsyncStatement`/`Statement` cancel gating). - finished: Arc, + /// Set by `result()` once it reaches a terminal state (success **or** + /// error). Read by `cancel()` to skip a redundant server-side cancel RPC on + /// an already-finished statement (parity with `AsyncStatement`/`Statement` + /// cancel gating). + terminal: Arc, } impl CancellableExecution { @@ -114,11 +119,29 @@ impl CancellableExecution { canceller, consumed: Arc::new(AtomicBool::new(false)), cancel_fired: Arc::new(AtomicBool::new(false)), - finished: Arc::new(AtomicBool::new(false)), + terminal: Arc::new(AtomicBool::new(false)), } } } +/// Normalise a kernel `execute()` error for the napi sync path. When this +/// handle actually dispatched a server-side cancel (`cancel_fired`), the +/// kernel's sync-cancel quirk — a cancel surfaced as `InvalidArgument` rather +/// than `Cancelled` (the async path returns `Cancelled`) — is translated to +/// `Cancelled` so JS callers get one cancelled-status code. Every other error, +/// and an `InvalidArgument` when no cancel was dispatched (a genuine SQL/parse +/// error), passes through verbatim with its original diagnostic intact. +/// +/// Pure + side-effect-free so the predicate can be unit-tested without a +/// session (see the `tests` module). +fn normalize_execute_err(err: KernelError, cancel_fired: bool) -> KernelError { + if cancel_fired && err.code == ErrorCode::InvalidArgument { + KernelError::cancelled().message("statement cancelled by client") + } else { + err + } +} + #[napi] impl CancellableExecution { /// The server-issued statement id this execution targets, if the @@ -143,9 +166,17 @@ impl CancellableExecution { /// /// On a server-side cancel the kernel's blocking `execute()` currently /// surfaces `InvalidArgument` (a known kernel quirk — the async path - /// returns `Cancelled`). When this handle's `cancel()` fired, we normalise - /// that into `Cancelled` here so JS callers can rely on a single - /// cancelled-status code regardless of execution path. + /// returns `Cancelled`). When this handle's `cancel()` actually dispatched a + /// server-side cancel, we normalise that into `Cancelled` here so JS callers + /// can rely on a single cancelled-status code regardless of execution path. + /// + /// Three outcomes can race the blocking drive: (1) a natural terminal state + /// → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a + /// server cancel → this `result()` rejects with a `Cancelled`-coded error + /// (the normalisation above); (3) the future being **dropped** mid-flight + /// (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` + /// drop-guard fires a fire-and-forget `cancel_statement`, but there is no + /// `result()` left to observe a code. Only (2) yields a `Cancelled` error. #[napi] pub async fn result(&self) -> napi::Result { // Mark consumed before taking, so a racing second `result()` @@ -156,37 +187,25 @@ impl CancellableExecution { } let pending = Arc::clone(&self.pending); let cancel_fired = Arc::clone(&self.cancel_fired); - let finished = Arc::clone(&self.finished); + let terminal = Arc::clone(&self.terminal); guarded(async move { let mut stmt = { let mut guard = pending.lock().await; guard.take().ok_or_else(statement_closed_err)? }; - match stmt.execute().await { - Ok(executed) => { - // Mark finished so a later `cancel()` skips a redundant RPC. - finished.store(true, Ordering::Release); - // Pass the parent kernel `Statement` into the JS wrapper so - // its `Drop` doesn't invalidate the executed handle via the - // shared `ValidityFlag` — same rationale as - // `Connection::execute_statement`. - Ok(Statement::from_executed(stmt, executed)) - } - Err(kernel_err) => { - // Normalise the sync-cancel `InvalidArgument` quirk into - // `Cancelled` when the caller fired `cancel()`. Any other - // failure (or a non-cancel `InvalidArgument`) passes through - // verbatim. - if cancel_fired.load(Ordering::Acquire) - && kernel_err.code == ErrorCode::InvalidArgument - { - Err(napi_err_from_kernel( - KernelError::cancelled().message("statement cancelled by client"), - )) - } else { - Err(napi_err_from_kernel(kernel_err)) - } - } + let outcome = stmt.execute().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); + match outcome { + // Pass the parent kernel `Statement` into the JS wrapper so its + // `Drop` doesn't invalidate the executed handle via the shared + // `ValidityFlag` — same rationale as `Connection::execute_statement`. + Ok(executed) => Ok(Statement::from_executed(stmt, executed)), + Err(kernel_err) => Err(napi_err_from_kernel(normalize_execute_err( + kernel_err, + cancel_fired.load(Ordering::Acquire), + ))), } }) .await @@ -203,15 +222,58 @@ impl CancellableExecution { /// already in a terminal state. #[napi] pub async fn cancel(&self) -> napi::Result<()> { - // Skip the server-side cancel RPC if the statement already finished — - // it would be a redundant no-op-at-server call and a confusing log line. - if self.finished.load(Ordering::Acquire) { + // Skip the server-side cancel RPC once the statement is terminal (success + // OR error) — it would be a redundant no-op-at-server call + confusing log. + if self.terminal.load(Ordering::Acquire) { return Ok(()); } - // Record intent so `result()` can normalise the kernel's sync-cancel - // `InvalidArgument` into `Cancelled`. - self.cancel_fired.store(true, Ordering::Release); + // Only flag `cancel_fired` when a server-side cancel is actually + // dispatched — i.e. a statement id has been observed. A first-window + // `cancel()` (before the id is published) is a no-op, so it must NOT + // arm the `InvalidArgument`→`Cancelled` normalisation: otherwise a later + // genuine `InvalidArgument` (a real SQL/parse error) would be mislabelled + // "cancelled" with its diagnostic discarded. + let dispatched = self.canceller.statement_id().is_some(); let canceller = self.canceller.clone(); - guarded(async move { canceller.cancel().await.map_err(napi_err_from_kernel) }).await + let cancel_fired = Arc::clone(&self.cancel_fired); + guarded(async move { + canceller.cancel().await.map_err(napi_err_from_kernel)?; + if dispatched { + cancel_fired.store(true, Ordering::Release); + } + Ok(()) + }) + .await + } +} + +#[cfg(test)] +mod tests { + use super::normalize_execute_err; + use databricks_sql_kernel::{Error as KernelError, ErrorCode}; + + // The load-bearing wire-contract logic: which `execute()` errors become + // `Cancelled`. Driven synthetically — no live session required. + + #[test] + fn normalizes_invalid_argument_to_cancelled_when_cancel_dispatched() { + let out = normalize_execute_err(KernelError::invalid_argument(), true); + assert_eq!(out.code, ErrorCode::Cancelled); + } + + #[test] + fn preserves_invalid_argument_when_no_cancel_dispatched() { + // A genuine SQL/parse error (InvalidArgument) with no dispatched cancel + // must keep its code + diagnostic — never mislabelled "cancelled". + let out = normalize_execute_err(KernelError::invalid_argument(), false); + assert_eq!(out.code, ErrorCode::InvalidArgument); + } + + #[test] + fn preserves_non_invalid_argument_errors_even_after_cancel() { + // Only the sync-cancel `InvalidArgument` quirk is normalised; any other + // error passes through verbatim regardless of the cancel flag. + let out = normalize_execute_err(KernelError::network_error(), true); + assert_eq!(out.code, ErrorCode::NetworkError); } } From 754f16208798d126b4b77b85881e65ccb1a05b3d Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Thu, 4 Jun 2026 18:18:35 +0000 Subject: [PATCH 5/5] fix(cancel): make StatementCanceller::cancel report dispatch to close the normalisation race MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The round-2 fix gated the InvalidArgument→Cancelled normalisation on a pre-check `canceller.statement_id().is_some()` before calling `cancel()`. That pre-check is a TOCTOU: the server statement_id can be published (by the concurrent `execute()`'s POST) in the window between the pre-check reading `None` and the canceller's own lock-read seeing the id and dispatching a real cancel. In that window a genuinely-cancelled execute would surface its `InvalidArgument` un-normalised (shown as a SQL error instead of Cancelled). It failed safe, but it was not race-free. Fix: `StatementCanceller::cancel()` now returns `Result` — `true` iff it actually dispatched a cancel RPC — decided by the SAME id read that gates the dispatch. The napi `CancellableExecution::cancel()` sets `cancel_fired` from that return value instead of a separate racy pre-check, so the flag exactly reflects "a cancel was issued" with no time-of-check/time-of-use gap. `AsyncStatementCanceller` (the async path) is a distinct type and is unchanged. core: fmt / clippy -D warnings / `cargo test` (23 lib) green. napi: fmt / clippy -D warnings / `cargo test` (44) green; the three `normalize_execute_err` unit tests unchanged. Mid-compute cancel re-verified live via the node binding → `result()` rejects with `{"code":"Cancelled"}`. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore --- napi/src/cancellable.rs | 17 ++++++++++------- src/statement/mutable.rs | 18 ++++++++++++------ 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/napi/src/cancellable.rs b/napi/src/cancellable.rs index 52af999f..bc445019 100644 --- a/napi/src/cancellable.rs +++ b/napi/src/cancellable.rs @@ -228,16 +228,19 @@ impl CancellableExecution { return Ok(()); } // Only flag `cancel_fired` when a server-side cancel is actually - // dispatched — i.e. a statement id has been observed. A first-window - // `cancel()` (before the id is published) is a no-op, so it must NOT - // arm the `InvalidArgument`→`Cancelled` normalisation: otherwise a later - // genuine `InvalidArgument` (a real SQL/parse error) would be mislabelled - // "cancelled" with its diagnostic discarded. - let dispatched = self.canceller.statement_id().is_some(); + // dispatched. `canceller.cancel()` reports whether it dispatched (an id + // had been observed) from the SAME id read that makes the decision, so + // there is no time-of-check/time-of-use gap. A first-window `cancel()` + // (before the id is published) returns `false` and must NOT arm the + // `InvalidArgument`→`Cancelled` normalisation — otherwise a later genuine + // `InvalidArgument` (a real SQL/parse error) would be mislabelled + // "cancelled" with its diagnostic discarded. A pre-check on + // `statement_id()` here would be racy (the id can publish between the + // check and the canceller's own read); using the return value closes it. let canceller = self.canceller.clone(); let cancel_fired = Arc::clone(&self.cancel_fired); guarded(async move { - canceller.cancel().await.map_err(napi_err_from_kernel)?; + let dispatched = canceller.cancel().await.map_err(napi_err_from_kernel)?; if dispatched { cancel_fired.store(true, Ordering::Release); } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 98387ddb..7133af43 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -591,21 +591,27 @@ impl StatementCanceller { /// Server-side cancel of the in-flight statement via /// `cancel_statement(statement_id)`. /// - /// No-op (returns `Ok`) if no statement id has been observed yet — - /// either nothing has executed, or the query is still in its - /// initial submit round-trip and the server hasn't issued an id. + /// Returns `Ok(true)` if a cancel RPC was actually dispatched (a + /// statement id had been observed) and `Ok(false)` if it was a no-op + /// because no id has been observed yet — either nothing has executed, + /// or the query is still in its initial submit round-trip and the + /// server hasn't issued an id. The dispatched/no-op decision and the + /// returned flag come from the *same* id read, so a caller can attribute + /// a subsequent execute error to this cancel without a separate (racy) + /// `statement_id()` re-check. + /// /// Idempotent against a server already in a terminal state (the /// kernel's `cancel_statement` is a no-op there). Safe to call /// concurrently with the `execute()` it targets — the two share /// only the id slot (behind a `Mutex`), no mutable statement state. - pub async fn cancel(&self) -> Result<()> { + pub async fn cancel(&self) -> Result { let id = self.inflight_id.lock().ok().and_then(|g| g.clone()); let Some(id) = id else { - return Ok(()); + return Ok(false); }; async { self.session.transport().cancel_statement(&id).await?; - Ok(()) + Ok(true) } .instrument(self.session.log_span().clone()) .await