Skip to content

feat(napi): expose sync StatementCanceller via executeStatementCancellable - #122

Merged
msrathore-db merged 7 commits into
mainfrom
msrathore/napi-sync-canceller
Jun 4, 2026
Merged

msrathore-db merged 7 commits into
mainfrom
msrathore/napi-sync-canceller

Conversation

@msrathore-db

@msrathore-db msrathore-db commented Jun 4, 2026 •

Copy link
Copy Markdown
Collaborator

What

Expose the sync StatementCanceller over the napi binding (mirroring pyo3's Statement.canceller()), so a multi-second blocking executeStatement is cancellable from JS — the napi hole left by the pyo3 sync-cancel work in #121.

Surface (napi only — zero kernel-core changes)

  • New napi/src/cancellable.rs → CancellableExecution napi class.
  • Connection.executeStatementCancellable(sql, opts) -> CancellableExecution: builds the kernel Statement, captures a detached StatementCanceller before dispatching execute(), then exposes result() (drives the blocking execute → Statement), cancel() (lock-free; interrupts a running result() mid-compute), and statementId (string | null).
  • The cancel mechanism (StatementCanceller, inflight_id, POST /statements/{id}/cancel) is unchanged kernel core from feat(statement): tz-aware/scientific param binds, error context, sync cancel + Ctrl-C #121.

Cancel-status normalisation (review P1.2)

On a server-side cancel the core Statement::execute() surfaces InvalidArgument (a kernel quirk — the async path returns Cancelled). CancellableExecution::result() now normalises that to Cancelled when this handle's cancel() fired, so every napi consumer sees one cancelled-status code regardless of path. Verified end-to-end against a live warehouse driving the raw binding: a mid-compute cancel() makes result() reject with {"code":"Cancelled","message":"statement cancelled by client"} (previously InvalidArgument).

Other review items

  • P2.3: cancel() skips a redundant server-side RPC once result() finished successfully (a finished gate, matching AsyncStatement/Statement).
  • P2.4: documented the API-shape asymmetry vs pyo3 in the module rustdoc.

Tests

  • cargo fmt / clippy -D warnings / cargo test --lib (620) green.
  • Added a live core e2e test (tests/v0_execute_e2e.rs::sync_canceller_cancels_a_running_execute_mid_compute) exercising the StatementCanceller mechanism end-to-end (verified live, 13.6s; statement cancelled server-side).
  • napi-class coverage (review P1.1): the CancellableExecution surface (the string|null getter, double-result() closed-err, cancel-before-id no-op, and the new Cancelled normalisation) is consumed and exercised end-to-end by databricks-sql-nodejs#416 — node unit tests for the cancellable path plus a live mid-compute cancel verified server-side, and the raw-binding Cancelled-normalisation check above. A self-contained kernel-side napi test isn't possible as a pure unit test (the napi modules are pub(crate) and CancellableExecution requires a session); a wiremock-backed napi integration test is a reasonable follow-up. Recommend gating final merge on chore: bump version to 1.3.0 #416's CI.

Remaining kernel-core follow-up (not in this PR)

The sync execute() path returning InvalidArgument rather than Cancelled is a core quirk; this PR papers over it at the napi layer. Normalising it in the core (so pyo3 and direct Rust callers benefit too) is the proper follow-up.

This pull request and its description were written by Isaac.

…lable

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 <madhavendra.rathore@databricks.com>
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 <madhavendra.rathore@databricks.com>
@gopalldb

gopalldb commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator

P1 — Should fix

  1. No JS-side test coverage in this PR — the load-bearing claim is "napi callers can cancel mid-execute", but the only added test (tests/v0_execute_e2e.rs:932-978) exercises the kernel-core
    StatementCanceller via the Rust API, NOT the new CancellableExecution napi class. Downstream consumer is databricks-sql-nodejs#416 — the wire shape (the string | null getter, the closed-err on
    double-result(), the cancel-no-op-before-id behaviour) ships untested-from-JS until that PR lands.
    - Fix: either add a JS contract test here (napi build + node --test), or gate this PR on chore: bump version to 1.3.0 #416's CI and document that in the description. At minimum, add a Rust unit test exercising double-result() and
    pre-execute-cancel() short-circuit paths (both don't require a live session — short-circuit on the atomic / on the None slot respectively).
  2. Misleading comment + behavioral gap: JS callers will see InvalidArgument, not Cancelled (tests/v0_execute_e2e.rs:967-970, napi/src/cancellable.rs:135)
    - The PR description and test comment claim "napi/pyo3 wrappers map it to a cancelled status via their client-side cancel flag". Verified: no such mapping exists in CancellableExecution::result(). The
    kernel InvalidArgument (the sync-cancel kernel finding from PR feat(statement): tz-aware/scientific param binds, error context, sync cancel + Ctrl-C #121 / acknowledged in this PR's "Findings Initial import: Databricks ADBC Rust driver as databricks-sql-kernel #1") flows through napi_err_from_kernel verbatim. JS-side code written if (err.code === 'Cancelled')
    will silently miss cancelled queries.
    - Fix: either (a) implement the client-side flag — add Arc cancel_fired set in cancel(), and translate InvalidArgument → Cancelled in result()'s err arm when set — or (b) correct the test
    comment and PR description to be honest that JS sees InvalidArgument until the kernel-side normalisation lands. Option (a) matches the contract the PR is selling.

P2 — Minor

  1. cancel() after a successful result() fires a redundant server-side cancel RPC (cancellable.rs:153-157) — unlike AsyncStatement::cancel (which checks closed) and Statement::cancel (which checks finished),
    CancellableExecution::cancel has no post-completion gate. Idempotent at the server (cancel-on-terminal is a no-op), but wasteful and produces a counter-intuitive log line. Add an Arc finished set
    in result() after success.
  2. API-shape asymmetry with pyo3 is undocumented. pyo3 exposes Statement.canceller(); napi exposes only Connection.executeStatementCancellable(...) -> CancellableExecution. Defensible (napi doesn't have a
    builder-shape Statement), but callers porting between bindings have to relearn the shape. Add a one-paragraph note in connection.rs rustdoc on execute_statement_cancellable or the binding's README.

…l RPC

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 <madhavendra.rathore@databricks.com>
@msrathore-db

Copy link
Copy Markdown
Collaborator Author

Thanks @gopalldb — addressed in 9a50904 (fmt/clippy/cargo test --lib 620 green; core e2e sync-cancel green):

P1.2 (the important one) — fixed, not just documented. You were right that no mapping existed and InvalidArgument flowed through verbatim. Rather than only correcting the comment, I implemented your option (a): CancellableExecution now carries a cancel_fired flag (set in cancel()), and result()'s error arm normalises InvalidArgument → Cancelled when it's set. So the contract the PR was selling is now real at the napi layer — every consumer sees Cancelled, not just node's driver-level mapping (and pyo3, which doesn't map at all, now gets it for free if it adopts this handle). Verified live driving the raw binding: mid-compute cancel() → result() rejects with {"code":"Cancelled",...}. Corrected the e2e comment too (the core execute() still returns InvalidArgument; the napi layer is what normalises).

P2.3 — cancel() now no-ops once result() finished successfully (a finished gate), matching AsyncStatement/Statement — no redundant server RPC / confusing log line.

P2.4 — added the pyo3 API-shape note to the module rustdoc (napi: one executeStatementCancellable -> CancellableExecution; pyo3: split canceller()/execute()).

P1.1 (test coverage) — option (b) + verification, with a note on why (c) isn't feasible. A pure offline Rust unit test of CancellableExecution isn't possible here: the napi modules are pub(crate) (no external tests/ access) and the handle requires a live/mock session, so the "short-circuit on the atomic / None slot" paths can't be reached without a session. So:

  • The StatementCanceller mechanism has a committed live core e2e test (added here).
  • The CancellableExecution napi class — its string|null getter, double-result() closed-err, cancel-before-id no-op, and the new Cancelled normalisation — is exercised end-to-end by databricks-sql-nodejs#416 (node unit tests + a live server-confirmed mid-compute cancel) and the raw-binding check above. I'd gate final merge on chore: bump version to 1.3.0 #416's CI as you suggested. A wiremock-backed napi integration test is a reasonable follow-up if you'd prefer in-repo coverage — happy to add it.

I also left a note that the core-level InvalidArgument-vs-Cancelled normalisation (so pyo3/direct-Rust callers benefit without the napi shim) is the proper kernel-core follow-up.

This reply was written by Isaac.

@gopalldb

gopalldb commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator

P1 — Should fix

  1. Pre-emptive cancel() mis-attributes unrelated InvalidArgument as Cancelled (napi/src/cancellable.rs:180-185, 211-215)

  2. Sequence that breaks:
    a. JS calls exec.cancel() immediately after executeStatementCancellable(...) — before the kernel publishes a statement_id into inflight_id. canceller.cancel().await no-ops (no RPC dispatched), but
    cancel_fired is set to true at line 213 regardless.
    b. JS calls exec.result(). The server runs the SQL and returns a genuine InvalidParameterValue / parse-error / type-mismatch — kernel surfaces as ErrorCode::InvalidArgument with a real diagnostic.
    c. result()'s err arm sees cancel_fired && code == InvalidArgument → replaces the kernel error with Error::cancelled().message("statement cancelled by client"). The original kernel diagnostic (sql_state,
    error_code, query_id, displayMessage, diagnosticInfo) is discarded.

JS callers writing if (err.code === 'Cancelled') {...} else { reportSqlError(err) } see "cancelled" for a query that actually failed due to a SQL bug. Observability broken.

Fix: only set cancel_fired = true after the canceller actually dispatched a wire cancel. Gate on canceller.statement_id().is_some() before storing:
let had_id = canceller.statement_id().is_some();
canceller.cancel().await.map_err(napi_err_from_kernel)?;
if had_id {
cancel_fired.store(true, Ordering::Release);
}
This makes the normalisation predicate gate on "we actually issued a server-side cancel" rather than "JS called cancel()".
2. No JS-side / napi-class-level test coverage of the new wire contract (napi/src/cancellable.rs has no #[cfg(test)] mod tests; no JS/TS test files added)
- Round 1 flagged this; round 2 added the load-bearing normalisation + finished-gate logic with zero tests for either.
- The only related test exercises the kernel-core StatementCanceller via Rust API, not CancellableExecution. The three wire-shape promises — cancel() during in-flight → code:"Cancelled", cancel() after
success → no RPC, double result() → InvalidStatementHandle — ship untested at the napi layer.
- Fix: add Rust unit tests in cancellable.rs that don't require a live session. Factor the normalisation match arm into fn normalize_execute_err(err: KernelError, cancel_fired: bool) -> NapiError so tests
can drive (InvalidArgument, true), (InvalidArgument, false), (NetworkError, true) synthetically. Also test default-false initial flag state on CancellableExecution::new(...).

P2 — Minor

  1. cancel() after a non-cancel error still fires a real RPC (cancellable.rs:204-216) — finished is set only in the Ok arm at line 168. If result() returns NetworkError or a real SQL error, finished stays
    false; a defensive cancel() then fires a redundant RPC. Server statement is already terminal so wire-benign (kernel cancel_statement is a no-op on terminal), but it's the same wasted-RPC + log-noise case the
    round-2 commit was designed to eliminate for the success path. Set finished in BOTH arms; rename to terminal for clarity.
  2. Benign race in cancel() flag ordering (cancellable.rs:208-215) — between finished-check and cancel_fired-set, result() could complete. cancel_fired = true ends up set on a completed-success instance, but
    consumed-swap blocks any downstream code path that would observe it. Resolved as a side effect of P1 Initial import: Databricks ADBC Rust driver as databricks-sql-kernel #1's recommended fix (only set after dispatch).
  3. Doc clarification on three concurrent cancel paths (cancellable.rs:138-148) — the rustdoc mentions the drop-cancel guard but doesn't note that drop-cancel, explicit cancel(), and natural completion can
    all race; only the first produces a Cancelled-coded error with the new normalisation.

…testable

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 <madhavendra.rathore@databricks.com>
@msrathore-db

Copy link
Copy Markdown
Collaborator Author

Great catch on P1.1 — that was a real bug I introduced with the normalisation. Fixed in dcbbf57:

  • P1.1 (mis-attribution): cancel() now sets cancel_fired only when it actually dispatched a server-side cancel (a statement_id was already observed) — exactly your had_id gate. So a first-window no-op cancel() no longer arms the normalisation, and a later genuine InvalidArgument (real SQL/parse/type error) passes through with its full diagnostic intact instead of being mislabelled Cancelled.
  • P1.2 (testability): factored the predicate into a pure normalize_execute_err(err, cancel_fired) -> KernelError and added offline unit tests driving it synthetically: (InvalidArgument, dispatched)→Cancelled, (InvalidArgument, not-dispatched)→InvalidArgument, (NetworkError, dispatched)→NetworkError. napi crate is now at 44 tests. (The CancellableExecution::new default-state check needs a session, so it isn't a pure unit test — the wire-shape promises remain covered end-to-end by chore: bump version to 1.3.0 #416 + the raw-binding checks.)
  • P2.3: the terminal flag (renamed finished→terminal) is now set in both arms of result(), so a defensive cancel() after any terminal state (error too, not just success) skips the redundant RPC.
  • P2.4: the flag-ordering race is resolved as a side effect of P1.1 (flag set only after dispatch).
  • P2.5: documented the three racing outcomes (natural completion / dispatched cancel→Cancelled / dropped-future drop-guard) and which yields a Cancelled code.

fmt / clippy -D warnings / napi cargo test (44) green; happy-path mid-compute cancel re-verified live → result() still rejects with {"code":"Cancelled"}. I'll bump the consumer (#416) KERNEL_REV to this commit so it doesn't ship the pre-dcbbf57 mis-attribution behaviour.

This reply was written by Isaac.

… the normalisation race

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<bool>` — `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 <madhavendra.rathore@databricks.com>
@msrathore-db

Copy link
Copy Markdown
Collaborator Author

Following up on my own P1.1 fix — I wasn't satisfied it was fully race-free, and on a second look it wasn't. Pushed 754f162 to close it properly.

The residual race in the had_id pre-check. Gating on canceller.statement_id().is_some() before calling cancel() is a TOCTOU: the server statement_id is published by the concurrent execute()'s POST, and it can land 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 rather than Cancelled). It failed in the safe direction and the window is tiny, but it wasn't actually race-free.

Fix. StatementCanceller::cancel() now returns Result<bool> — true iff it actually dispatched a cancel RPC — and that bool comes from the same inflight_id read that gates the dispatch. The napi layer sets cancel_fired from the return value instead of a separate pre-check, so the flag exactly reflects "a cancel was issued" with zero time-of-check/time-of-use gap. The only remaining ambiguity is inherent to the kernel quirk itself (once a cancel is dispatched, a coincident genuine InvalidArgument is attributed to the cancel) — that can't be resolved at this layer without the core distinguishing cancel-induced from genuine InvalidArgument.

Scope note: this does now touch core (src/statement/mutable.rs), but it's a 2-line signature change + return value; AsyncStatementCanceller is a distinct type and is untouched, and the only other caller (the e2e test) is unaffected.

core: fmt / clippy -D warnings / cargo test (23 lib) green. napi: fmt / clippy -D warnings / cargo test (44) green. Mid-compute cancel re-verified live via the node binding → result() still rejects {"code":"Cancelled"}. Consumer #416 bumped to 754f162.

This reply was written by Isaac.

@msrathore-db

Copy link
Copy Markdown
Collaborator Author

One more verification, since this round touches a core signature (StatementCanceller::cancel() -> Result<()> → Result<bool>) and pyo3 links against it.

pyo3 is unaffected — verified, not assumed. Python's StatementCanceller.cancel() (pyo3/src/statement.rs:410) wraps the call as run_kernel!(py, runtime, self.inner.cancel())?; — the trailing ?; discards the new bool, so it's source-compatible. cd pyo3 && cargo check --lib is green (no errors/warnings). Behaviourally nothing changes: Python's cancel() still returns None and fires the same RPC, and pyo3 does not do the InvalidArgument→Cancelled normalisation at all (it surfaces the raw kernel InvalidArgument on a sync cancel, exactly as before). The new bool is consumed only by the napi CancellableExecution.

Known residual (will file a follow-up). The normalisation keys on a code-level heuristic: the kernel's sync execute() reports a server-side cancel as InvalidArgument (the async path returns Cancelled), so "this handle dispatched a cancel ⇒ treat InvalidArgument as the cancel". That's race-free now, but it can't disambiguate the rare coincidence where a genuine InvalidArgument (bad SQL) lands at the same instant a cancel was dispatched — both arrive as the same code, so the genuine diagnostic gets reported as Cancelled. It only happens when the caller themselves cancelled, so Cancelled is defensible there. The clean fix lives in core (have sync execute() return Cancelled directly, like the async path, and delete the napi heuristic) — I'll open a follow-up issue rather than expand this PR further.

This reply was written by Isaac.

@msrathore-db
msrathore-db added this pull request to the merge queue Jun 4, 2026
Merged via the queue into main with commit 8bedaab Jun 4, 2026
17 checks passed

This branch was previously deployed

1 inactive deployment
azure-prod — 5091cafe Deployed Jun 4, 2026 by msrathore-db via v0 TLS (mitmproxy) #108
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants