Skip to content

feat(napi): openSession / Connection / Statement napi surface (stack 3/8) - #25

Merged
vikrantpuppala merged 8 commits into
mainfrom
msrathore/kernel-napi-classes
May 26, 2026
Merged

vikrantpuppala merged 8 commits into
mainfrom
msrathore/kernel-napi-classes

Conversation

@msrathore-db

@msrathore-db msrathore-db commented May 16, 2026 •

Copy link
Copy Markdown
Collaborator

Stack

Linear stack of 8 PRs on databricks/databricks-sql-kernel landing the SEA-driver kernel-side enablement work. Merge in order from base ↑ to tip. The tip branch (msrathore/krn-status-fields, PR #23) is the single snapshot containing every kernel-side change in flight.

Pos PR Branch Scope
1/8 #26 kernel-async-public-api Remove block_on from ResultStream + Send-safety on Statement + rustls-tls + e2e test ported from #20
2/8 #27 kernel-napi-skeleton napi-rs binding crate skeleton: Cargo manifest + lib + error envelope + util + runtime + logger
3/8 #25 kernel-napi-classes Database / Connection / Statement / ResultStream napi classes
4/8 #29 kernel-napi-statement-validity StatementInner ValidityFlag fix propagated from sea-operation
5/8 #28 kernel-oauth-error-class Reclassify OAuth token-exchange failures as Error::unauthenticated() (2-line fix in auth/oauth/m2m.rs + u2m.rs)
6/8 #30 krn-connection-pool-default-bump Bump HttpConfig.pool_max_idle_per_host default from 10 → 100
7/8 #24 krn-tls-public-api Expose TlsConfig fields (custom_ca_cert + accept_self_signed + skip_hostname_verification) + stop discarding in session.rs
8/8 #23 krn-status-fields ← TIP Expose 5 status accessors on ExecutedStatement (num_modified_rows / progress / display_message / diagnostic_info / error_details_json)

Companion NodeJS stack (databricks/databricks-sql-nodejs): 8 PRs — root #378 (sea-abstraction) → #380 → #377 → #379 → #382 → #381 → #384 → #383 (tip).

Policy: new PRs always stack on the current tip. No sibling/parallel topology. No force-pushes on existing PRs unless absolutely necessary; if a PR's content is wrong, add a fix-up commit on top of the stack tip rather than rewriting history.


This PR is position 3/8.

⚠️ Must merge together with PR #29

In isolation, this PR ships a known cancel-lifecycle bug: the first call to Statement.cancel() from JS returns KernelError(InvalidStatementHandle) instead of cancelling the in-flight statement.

Root cause — Connection::execute_statement (napi/src/connection.rs:99-104) builds a local kernel Statement, awaits stmt.execute(), hands the resulting ExecutedStatement to the JS-side Statement wrapper, then drops the parent kernel Statement at end of the closure. The kernel's Drop for Statement (src/statement/mutable.rs:440-450) calls valid.invalidate() on the shared ValidityFlag. The next Statement.cancel() from JS reaches ExecutedStatement::cancel() → self.valid.check() → KernelError(InvalidStatementHandle).

Fix — PR #29 (next in the stack) wraps the inner state in a StatementInner { _parent: KernelStatement, executed: ExecutedStatement } struct that keeps the parent alive for the wrapper's lifetime. With #29 applied, the cancel lifecycle works correctly on the first call.

Stack-merge policy — these two PRs must merge as a pair (default Github stacked-PR flow handles this). Do not merge #25 to main without #29 in the same merge train. Reviewers approving #25 in isolation should approve #29 as part of the same approval pass.

Summary

Adds the four user-facing #[napi] classes that expose the kernel's v0 surface to JS consumers. ~504 LOC across 4 files plus a 4-line lib.rs update to declare the new modules.

Classes:

  • Database — Database.open() returns a Session handle
  • Connection — Connection.execute_statement() returns a Statement handle
  • Statement — fetchNextBatch() / schema() / cancel() / close()
  • ResultStream (internal) — used by Statement; not directly exposed

Results cross the FFI as Arrow IPC bytes (see result.rs); the TS adapter decodes via apache-arrow.

Together with the skeleton PR #27, this delivers the full Round 2 napi surface.

Test plan

  • cargo check -p databricks-sea-native clean
  • Downstream NodeJS npm run build:native produces a working .node artifact against this stack
  • Downstream OAuth M2M e2e green at sea-auth-u2m@e7c979d building against this binding

Tracking

Co-authored-by: Isaac

@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-classes branch from b463a3f to 9916ab1 Compare May 17, 2026 13:15
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch from ead5002 to cd3a7fc Compare May 17, 2026 13:15
@msrathore-db msrathore-db changed the title feat(napi): Database / Connection / Statement / ResultStream napi classes feat(napi): Database / Connection / Statement / ResultStream napi classes (stack 3/8) May 17, 2026
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch from cd3a7fc to f530142 Compare May 20, 2026 10:36
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-classes branch from 9916ab1 to 898e46c Compare May 20, 2026 10:36
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch from f530142 to 02b6773 Compare May 20, 2026 16:55
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-classes branch from 898e46c to 51cc7f1 Compare May 20, 2026 16:55
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch from 02b6773 to 2154fb5 Compare May 20, 2026 20:22
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-classes branch from 51cc7f1 to 4517677 Compare May 20, 2026 20:22
msrathore-db added a commit that referenced this pull request May 21, 2026
…de_str

The crate's `crate-type = ["cdylib", "rlib"]` (chosen specifically
to enable `cargo test` of the lib internals) was paying its cost
but not its keep — only `error.rs::envelope_*` had any tests. Adds
9 new tests across all four modules of the skeleton:

- `util::tests` — 5 cases for `guarded`:
    * happy-path Ok pass-through
    * Err pass-through (separating it from the panic path)
    * `&'static str` panic recovery
    * owned `String` panic recovery (via `format!`)
    * non-string panic payload (via `panic_any(i32)`)
  This exercises both arms of `panic_payload_msg`'s downcast plus
  the fallback. Caught zero bugs in the skeleton but pre-emptively
  closes the test-coverage gap before the napi-classes PR fans out
  `guarded` to every async entry.

- `runtime::tests` — `try_get_handle_returns_none_before_init`
  verifies the cold-cache accessor that Drop impls (landing in PR
  #25) rely on for GC-thread short-circuit cleanup. `get_handle`
  itself remains intentionally untested at the unit level (requires
  a tokio runtime context that this in-process test harness can't
  fabricate cleanly).

- `lib::tests` — `version_matches_cargo_pkg_version` is the explicit
  smoke contract for the JS-side loader's binding-loaded probe.

- `error::tests` — `error_code_str_covers_all_known_variants` is the
  regression guard for the `_ => "Unknown"` fallback: any new kernel
  `ErrorCode` variant that lands without a mirrored slug here will
  still pass the existing tests but will silently degrade to
  "Unknown" on the wire. The test forces an audit trail when a new
  variant is added. `status_from_kernel_code_maps_special_cases`
  pins the three meaningful Status arms.

Crate-level `cfg_attr(not(test), allow(dead_code))` added in
lib.rs so the lib-only build (no test cfg) is silent on the skeleton
helpers that have no production callers until PR #25 — without
suppressing dead_code on the test code itself.

Test count: 2 -> 11. All passing under `cargo fmt + clippy
--all-targets -- -D warnings + cargo test`.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-classes branch from 4517677 to 350a0ec Compare May 21, 2026 00:03
@msrathore-db
msrathore-db marked this pull request as ready for review May 21, 2026 16:11
msrathore-db added a commit that referenced this pull request May 23, 2026
…de_str

The crate's `crate-type = ["cdylib", "rlib"]` (chosen specifically
to enable `cargo test` of the lib internals) was paying its cost
but not its keep — only `error.rs::envelope_*` had any tests. Adds
9 new tests across all four modules of the skeleton:

- `util::tests` — 5 cases for `guarded`:
    * happy-path Ok pass-through
    * Err pass-through (separating it from the panic path)
    * `&'static str` panic recovery
    * owned `String` panic recovery (via `format!`)
    * non-string panic payload (via `panic_any(i32)`)
  This exercises both arms of `panic_payload_msg`'s downcast plus
  the fallback. Caught zero bugs in the skeleton but pre-emptively
  closes the test-coverage gap before the napi-classes PR fans out
  `guarded` to every async entry.

- `runtime::tests` — `try_get_handle_returns_none_before_init`
  verifies the cold-cache accessor that Drop impls (landing in PR
  #25) rely on for GC-thread short-circuit cleanup. `get_handle`
  itself remains intentionally untested at the unit level (requires
  a tokio runtime context that this in-process test harness can't
  fabricate cleanly).

- `lib::tests` — `version_matches_cargo_pkg_version` is the explicit
  smoke contract for the JS-side loader's binding-loaded probe.

- `error::tests` — `error_code_str_covers_all_known_variants` is the
  regression guard for the `_ => "Unknown"` fallback: any new kernel
  `ErrorCode` variant that lands without a mirrored slug here will
  still pass the existing tests but will silently degrade to
  "Unknown" on the wire. The test forces an audit trail when a new
  variant is added. `status_from_kernel_code_maps_special_cases`
  pins the three meaningful Status arms.

Crate-level `cfg_attr(not(test), allow(dead_code))` added in
lib.rs so the lib-only build (no test cfg) is silent on the skeleton
helpers that have no production callers until PR #25 — without
suppressing dead_code on the test code itself.

Test count: 2 -> 11. All passing under `cargo fmt + clippy
--all-targets -- -D warnings + cargo test`.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch from dbdf7ef to 619cfdc Compare May 23, 2026 11:03
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-classes branch from 350a0ec to d8f7a27 Compare May 23, 2026 11:03
@msrathore-db
msrathore-db changed the base branch from msrathore/kernel-napi-skeleton-to-main to main May 25, 2026 10:07
Comment thread napi/src/statement.rs
Ok(ArrowSchema {
ipc_bytes: bytes.into(),
})
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH CONFIDENCE — flagged by security, language, devils-advocate, ops, architecture] · HIGH

Every other #[napi] async fn in this file wraps its body in guarded(async move { ... }).await — fetch_next_batch (l120), cancel (l197), close (l216). schema() is the lone exception.

Per PR #27's design, napi-rs does NOT auto-wrap; a panic in arrow_ipc::StreamWriter::try_new / writer.finish (allocator OOM, debug_asserts on malformed Field metadata, future arrow-ipc-version regressions) propagates as an unwind through napi-rs into V8 and aborts the Node process. util::guarded's catch_unwind exists precisely to prevent this.

Suggested fix:

Suggested change
}
#[napi]
pub async fn schema(&self) -> napi::Result<ArrowSchema> {
let schema = self.schema.clone();
guarded(async move {
let bytes = encode_ipc_stream(&schema, None)?;
Ok(ArrowSchema { ipc_bytes: bytes.into() })
}).await
}

Better still — drop async (see companion finding F2): the body has no .await. Pure CPU work doesn't need a Promise boundary.

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.

Verdict: VALID — fixed. Combined with F2 (I2): dropped async from Statement::schema() and removed the #[napi] async path entirely. Body is pure CPU work over a cached Arc<Schema> so neither the Promise tax nor util::guarded is justified. napi-rs handles panic conversion for sync #[napi] entry points via its own macro-expanded boundary. Mirrors pyo3/src/statement.rs::arrow_schema (sync) per the pyo3-wins convention.

Fixed in 9c56fbe — napi/src/statement.rs:172-186.

Comment thread napi/src/statement.rs Outdated
/// materialises the schema eagerly so JS callers can build error
/// reports against a disposed statement.
#[napi]
pub async fn schema(&self) -> napi::Result<ArrowSchema> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH CONFIDENCE — flagged by language, agent-compat, architecture] · MEDIUM

Pure CPU work — clones an Arc<Schema> and runs encode_ipc_stream synchronously. Marking it async forces napi-rs to wrap as Promise<ArrowSchema> on the JS side and routes through the tokio handle for no I/O.

Once JS callers learn await stmt.schema(), switching to a sync method is a breaking change to the TS adapter. Compare with statementId (sync #[napi(getter)]) and pyo3's sibling arrow_schema (pyo3/src/statement.rs:225, sync).

Suggested fix: drop async, or convert to #[napi(getter)] fn schema(&self) -> Result<ArrowSchema>:

Suggested change
pub async fn schema(&self) -> napi::Result<ArrowSchema> {
#[napi]
pub fn schema(&self) -> napi::Result<ArrowSchema> {
let bytes = encode_ipc_stream(&self.schema, None)?;
Ok(ArrowSchema { ipc_bytes: bytes.into() })
}

(Note: if you keep it async, F1's guarded wrap still applies.)

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.

Verdict: VALID — fixed. Dropped async from Statement::schema(). Body has no .await and matches pyo3/src/statement.rs::arrow_schema (sync) per the pyo3-wins convention. Avoids the per-call Promise allocation + cross-thread bounce for what is microsecond CPU work over a cached Arc<Schema>.

Fixed in 9c56fbe — napi/src/statement.rs:172-186.

Comment thread src/statement/executed.rs
async {
if self.closed.swap(true, Ordering::AcqRel) {
if self.closed.load(Ordering::Acquire) {
return Ok(());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH CONFIDENCE — flagged by language, maintainability, ops, architecture] · HIGH

This file's ExecutedStatement::close was changed to load → call wire → store true only on success, with the comment claiming "Mirrors Session::close" and enabling retry-on-failure via Drop.

But the sibling ExecutedAsyncStatement::close at src/statement/executed_async.rs:381 (verified at head SHA) still uses the OLD self.closed.swap(true, Ordering::AcqRel) pattern:

async fn close(&self) -> Result<()> {
    async {
        if self.closed.swap(true, Ordering::AcqRel) {  // ← OLD pattern
            return Ok(());
        }
        self.session.transport().close_statement(&self.statement_id).await
    }
    .instrument(self.session.log_span().clone()).await
}

Both implement the same trait (ExecutedStatementHandle::close); the contract is now inconsistent across the two impls:

  • ExecutedStatement::close failure → closed=false → Drop retries → server cleaned up
  • ExecutedAsyncStatement::close failure → closed=true already → Drop short-circuits → server-side statement leaks until session expiry

Callers running Statement::submit() → ExecutedAsyncStatement::close() (used by pyo3 at pyo3/src/executed_async.rs:151) get silently different durability guarantees than Statement::execute() → ExecutedStatement::close().

Suggested fix: apply the same load-then-store-on-success pattern to executed_async.rs:376-385. The trait doc at src/statement/handle.rs:46-48 ("Implementations make close idempotent — a second call is a no-op success") also needs updating to reflect the &self-race contract.

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.

Verdict: VALID — fixed. Mirrored the load → wire → store-on-success pattern from ExecutedStatement::close into ExecutedAsyncStatement::close. Both sibling impls of the ExecutedStatementHandle::close trait now share the same retry-on-failure contract. Trait doc at src/statement/handle.rs:46-48 remains accurate (idempotent on success).

Note: the retry branch is currently dead code because the SEA transport at src/client/sea.rs:660-679 swallows wire errors (Ignore errors on statement close (best effort cleanup) — verified by live probe against pecotesting). The pattern is forward-prep with identical observable behavior to the previous swap until the transport surfaces real errors — tracked as a follow-up kernel PR at sea-workflow/jira-candidates/2026-05-25-kernel-sea-close-statement-surface-errors.md.

Fixed in 9c56fbe — src/statement/executed_async.rs:376-411.

Comment thread napi/src/connection.rs
impl Drop for Connection {
fn drop(&mut self) {
// Best-effort cleanup: schedule a drop of the kernel handle on
// the captured tokio runtime. JS callers who need a

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH CONFIDENCE — flagged by devils-advocate, ops, architecture] · MEDIUM

guard.take() happens BEFORE the wire close await. If executed.close().await errors:

  1. The napi-side inner is already None.
  2. The JS caller sees the error and decides to retry.
  3. The retry sees inner = None → returns Ok(()) silently.
  4. The kernel-side Drop retries fire-and-forget once, but JS never sees that outcome.

The JSDoc claims "Idempotent — a second call on an already-closed connection returns Ok" — technically true but misleads callers into thinking retry-on-error works.

Same pattern exists in napi/src/statement.rs:647-662.

Suggested fix: either (a) mirror Session::close ordering (take-on-success only — close first, take only if Ok), or (b) document explicitly that "close() errors are terminal; only the kernel's Drop retry will run, JS callers cannot retry."

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.

Verdict: VALID — fixed (JSDoc honesty path). Rewrote both Connection.close() and Statement.close() JSDoc to honestly state "Errors are terminal from the JS side." The kernel handle is .take()-ed before the wire call (because Session::close consumes self by value, and ExecutedStatement::close is structurally similar), so a JS-side retry sees an already-closed wrapper and returns Ok(()). Only the kernel's Drop fires-and-forgets a single retry on the captured runtime. The previous JSDoc implied callers could observe and retry close failures via Drop — that was misleading.

The structural fix (take-on-success ordering) requires the kernel to expose a &self-callable close path, which is part of the lock-shape refactor tracked at sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md.

Fixed in 9c56fbe — napi/src/connection.rs:109-127, napi/src/statement.rs:213-240.

Comment thread napi/src/connection.rs
/// JS caller can observe failures (auth revoked mid-session,
/// warehouse stopped, network error). Idempotent — a second call
/// on an already-closed connection returns `Ok`.
///

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH CONFIDENCE — flagged by devils-advocate, architecture] · MEDIUM

The Mutex held across stmt.execute().await has two consequences the deferred-spec only acknowledges one of:

  1. Promise.all([conn.executeStatement(q1), conn.executeStatement(q2)]) is silently serial — even though the kernel's Session::statement() is &self-callable.
  2. Connection.close() will block behind any in-flight executeStatement — a long Spark query blocks teardown (signal handlers, test cleanup) for the duration of the query. There is no path to abort.

The author documents (1) as a known limitation deferred to sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md. But that follow-up focuses on cancel-during-fetch (the PR #29 scope) and doesn't mention the close-during-execute symptom.

Combined with the cancel-lifecycle bug PR #29 fixes, the Connection-shutdown story is broken: you can't close, and you can't cancel mid-fetch.

Suggested fix: scope the follow-up to address BOTH symptoms; the recommended Arc<Session> + &self-callable cancel/close shape would fix both at once.

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.

Verdict: VALID — deferred to follow-up. Live-confirmed via probe: two concurrent Session::statement().execute() calls against the same Session ran fully in parallel (~269ms total for two SELECT round-trips), so the kernel does not serialise — the napi mutex is the constraint. Both symptoms (Promise.all serialisation AND close-blocks-behind-execute) are real.

Structural fix needs a kernel-side Arc<Session> + &self-callable accessor that doesn't require consuming self for close. Substantial refactor — deferred to dedicated follow-up.

The existing JIRA candidate at sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md already covers both the cancel-during-fetch symptom AND the close-during-execute symptom you flagged — see the "Connection-side" section + the third test-plan scenario Connection.close during in-flight execute. No new JIRA needed.

Comment thread src/statement/executed.rs
async {
if self.closed.swap(true, Ordering::AcqRel) {
if self.closed.load(Ordering::Acquire) {
return Ok(());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW CONFIDENCE — flagged by devils-advocate, verified by orchestrator] · MEDIUM

The PR comment justifies the new close-flag pattern as "keeps closed=false on wire failure so Drop's fire-and-forget retry path runs as a fallback."

But verified at head SHA — src/client/sea.rs:660-674:

async fn close_statement(&self, statement_id: &str) -> Result<()> {
    ...
    // Ignore errors on statement close (best effort cleanup)
    let _ = self.http_client.execute(request, RequestType::CloseStatement).await;
    debug!("Closed statement: {}", statement_id);
    Ok(())
}

The transport always returns Ok. So transport.close_statement(...).await? never errors. The "retry on wire failure" branch the new pattern enables is unreachable with the current transport — defensive-coding-for-the-future, not load-bearing today.

That's not a bug per se. But:

  • It's a kernel-core change shipped in a binding PR, with a justification that doesn't hold today.
  • Affects pyo3 too (both bindings share ExecutedStatement), but pyo3 isn't tested against the new behavior in this PR.
  • The &self "two callers race and both hit the wire" claim — napi wraps the executed in Arc<Mutex<Option<...>>>, so napi-internal callers serialize.

Suggested fix: either (a) fix the transport to surface real errors (so the new close() pattern is meaningful and testable in a wiremock test), or (b) revert this hunk and ship the kernel change separately when the transport change lands.

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.

Verdict: VALID — confirmed via live wire probe. Empirically reproduced your finding: opened a session, executed SELECT 1, closed the session first (so the statement's parent session is gone server-side), then called executed.close(). The wire DELETE /statements/{id} hit a server that no longer recognised the session_id, but executed.close() returned Ok(()) — the transport's Ignore errors on statement close (best effort cleanup) swallow at src/client/sea.rs:660-679 is load-bearing. The new load → wire → store-on-success pattern at executed.rs:128-156 is forward-prep code; the retry branch is unreachable today.

Chose option (b): kept the new pattern, mirrored it into ExecutedAsyncStatement::close (addresses F3), and filed a follow-up kernel PR to flip the transport so the pattern becomes load-bearing — sea-workflow/jira-candidates/2026-05-25-kernel-sea-close-statement-surface-errors.md covers the change with wiremock coverage spec'd. Until that lands, the new pattern has identical observable behavior to the previous swap.

F3 fix in 9c56fbe — src/statement/executed_async.rs:376-411.

Comment thread napi/src/statement.rs
executed.cancel().await.map_err(napi_err_from_kernel)
})
.await
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH CONFIDENCE — flagged by ops, architecture] · MEDIUM

pub async fn cancel(&self) -> napi::Result<()> {
    if self.finished.load(Ordering::Acquire) { return Ok(()); }   // ← checked outside lock
    let inner = Arc::clone(&self.inner);
    guarded(async move {
        let guard = inner.lock().await;
        // ← no re-check of finished
        executed.cancel().await...
    }).await
}

Race:

  1. JS fires fetch_next_batch() → takes mutex → stream.next_batch() returns None → not yet stored true.
  2. JS fires cancel() concurrently → reads finished=false → queues behind mutex.
  3. fetch sets finished=true → releases mutex.
  4. cancel acquires mutex (no re-check) → dispatches cancel_statement against an already-naturally-completed statement → server returns an error.

Also: two cancel() calls in sequence both hit the wire — no idempotency. Two server-side CancelStatement calls on the same statement may produce different responses (server-side state-machine dependent). Compare with close() which IS idempotent via take().

Suggested fix: re-check finished after acquiring the lock, OR route cancel through a cancelled AtomicBool symmetric with finished and short-circuit on it.

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.

Verdict: PARTIALLY VALID — deferred (wire-benign). TOCTOU is structurally real but live-probed against the pecotesting SEA backend: kernel-level cancel() against a naturally-completed statement returned Ok(()), and a second cancel() also returned Ok(()). The server treats CancelStatement against a terminal statement as a no-op success — no error surfaced to the caller, no retryable failure.

Worst-case visible cost on the TOCTOU race: one redundant ~50–100 ms CancelStatement RPC. The non-idempotency concern (two cancels both hit the wire) has the same wire-benign outcome.

Cheap polish (re-check finished inside the lock + add a symmetric cancelled: AtomicBool) deferred to follow-up at sea-workflow/jira-candidates/2026-05-25-napi-cancel-toctou-and-idempotency.md. Lands cleanly under the lock-shape refactor's new shape (one AtomicBool symmetric with finished).

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Code Review Squad — Multi-Agent Review

Merge Safety Score: 22 / 100 — CRITICAL RISK

8/9 reviewers delivered. The test slot went idle 1 minute after spawn and never produced a SendMessage — no full test audit. Coverage uncapped (max 88).

The score reflects real merge-blocking issues, not score inflation. The PR ships:

  1. Self-acknowledged bug that must merge with PR fix(napi): propagate StatementInner ValidityFlag fix from sea-operation (stack 4/8) #29 — but with no regression test in either PR (F9).
  2. One node-process-aborting panic risk — schema() is the lone #[napi] async fn not wrapped in util::guarded (F1).
  3. Kernel-side change inconsistent with its sibling — ExecutedStatement::close got the new retry pattern; ExecutedAsyncStatement::close did NOT (F3).
  4. Unresolved lock-in TODO that PR feat(napi): napi-rs binding crate skeleton — Cargo + lib + error envelope + util + runtime + logger (stack 2/8) #27 explicitly said feat(napi): openSession / Connection / Statement napi surface (stack 3/8) #25 was the deadline for — napi_add_async_cleanup_hook (F4).
  5. Two follow-ups deferred-from-PR-feat(napi): napi-rs binding crate skeleton — Cargo + lib + error envelope + util + runtime + logger (stack 2/8) #27 didn't land — typed-error refactor (F5) and TS-adapter scripts (still gitignored, no devDep).

Block on: F1 (schema guarded), F3 (sibling-API symmetry), F4 (cleanup hook OR JIRA with concrete target PR), F5 (typed-error refactor OR JIRA), F9 (fold #29 OR add regression test).

Strongly recommend in this PR: F2 (drop async from schema), F6 (parameter binding plan), F7 (close-on-Err semantics), F10 (kernel change with transport fix or move out of this PR).

Recommend follow-up: F8 (Connection lock-shape), F11 (cancel TOCTOU), F12 (bindings-common).

Polish: F13–F20.

Caller-compatibility audit confirms no out-of-tree breakage. The kernel ExecutedStatement::close signature is unchanged (only semantics); pyo3 statement.rs:276 and the kernel's own callers absorb the new behavior correctly.

Cross-reviewer convergence is strong on F1 (5 reviewers), F2 (3), F3 (4), F7 (3), F11 (2), F15 (3). Test-slot coverage gap noted — no reviewer specifically audited what regression tests are missing; flagged incidentally by other reviewers (no cancel-lifecycle test, no wiremock test for the new close semantics).


Findings Without Inline Location

F4 · HIGH — napi_add_async_cleanup_hook TODO from PR #27 left unresolved — first user-facing Drop impls leak server-side state on process exit

[HIGH CONFIDENCE — flagged by devils-advocate, ops] · HIGH

napi/src/runtime.rs:94-104 carries an explicit TODO from PR #27:

"spawning cleanup work on the captured handle from a Drop impl is racy at Node-process teardown — the runtime may already be in shutdown when the V8 GC reaches our objects, and a Handle::spawn on a halting runtime drops the future silently. PR #25 introduces the first real Drop impls; this is the lock-in point where the choice must be made (raw spawn vs. cleanup hook)."

PR #25 adds the Drop impls (napi/src/connection.rs:140-166, napi/src/statement.rs:232-258) and chooses raw handle.spawn without addressing the TODO. On Node process exit (process.exit(), SIGTERM in containers, OOM teardown, k8s pod scale-down, Lambda cold-stop), V8 GCs Connection/Statement → Drop schedules cleanup → process exits before the spawn polls → server-side Session lives until idle-timeout reclaim (minutes to hours), and the Statement lives until its parent Session closes.

At scale this leaks server-side handles continuously, consuming warehouse-side per-session resources and inflating the active-statement count on dashboards.

pyo3 sidesteps this by owning a per-Session tokio Runtime (pyo3/src/session.rs:111-124) — dropping the Arc<Runtime> invokes Tokio's runtime shutdown, which waits for spawned tasks. napi uses the process-global napi-rs runtime that outlives any individual Connection; nothing forces a graceful drain.

Suggested fix: implement napi::env::Env::add_async_cleanup_hook (or equivalent) before this PR ships, OR file an actual JIRA tracking it (not just a parked design doc) and document the leak window in CLAUDE.md / close() JSDoc.


F5 · HIGH — Typed-error envelope still active — the __databricks_error__:<json> refactor deferred from PR #27 was supposed to land in #25

[HIGH CONFIDENCE — flagged by agent-compat; deferred-spec from PR #27 follow-up] · HIGH

PR #27's follow-up audit explicitly deferred the typed-error refactor to "PR #25 when async entry points exist" — design parked at sea-workflow/jira-candidates/2026-05-23-napi-typed-error-refactor.md.

PR #25 adds the async entry points but does not land the typed-error refactor. Every new error path in connection.rs, statement.rs, database.rs funnels through napi_err_from_kernel → the __databricks_error__:<json> envelope. No Env::create_error / set_named_property anywhere.

An LLM writing JS against just the generated .d.ts will see err.message/err.code lookups returning undefined; the envelope is hidden in err.reason as a sentinel-prefixed JSON string. No TS adapter ships from this repo.

Compare with pyo3's setattr typed-attrs pattern at pyo3/src/errors.rs:78-86 which has worked since the pyo3 binding shipped.

Suggested fix: either land the typed-error refactor in this PR, OR file an actual JIRA with a concrete target PR (not just a parked design doc) and call out the continued deferral in the PR description. The deferred-spec has been parked for 2+ days as of this re-review.


F6 · HIGH — Connection.executeStatement(sql) exposes only the SQL string — no parameter binding, forces string-concat SQL by default

[HIGH CONFIDENCE — flagged by agent-compat] · HIGH

executeStatement(sql: String) is the only API surface for executing statements. No parameter-binding overload, no bind method, no StatementSpec exposure. Every JS caller (including LLM-generated code) is forced into string-concat SQL — the canonical SQL-injection footgun.

pyo3 surfaces parameter binding via set_params / bind_param(ordinal, value_str, sql_type) at pyo3/src/statement.rs:96-127. The kernel's StatementSpec supports parameter binding internally. The Node driver this binding feeds has parameterized statements in its existing JS API.

napi punts. The JSDoc claim "No per-statement options" conflates connection-level config (catalog/schema/sessionConf) with parameter binding.

Suggested fix: add a parameter-binding overload now (e.g., executeStatementWithParams(sql, params: TypedValue[])) before the wire shape is committed, OR document the deferral explicitly in the JSDoc and PR description with a tracking JIRA.


F9 · MEDIUM — PR ships a known cancel-lifecycle bug, no regression test detects it

[LOW CONFIDENCE — flagged by devils-advocate] · MEDIUM

The PR description acknowledges the cancel-lifecycle bug (kernel Statement drops at end of Connection::execute_statement, invalidating ValidityFlag, so Statement.cancel() from JS short-circuits to InvalidStatementHandle). Fixed in PR #29.

But:

Once #29 lands, nothing in this repo will catch a regression that re-introduces the same shape unless a test is added.

Suggested fix: fold #29 into #25, OR enforce merge-as-pair AND add a regression test that constructs the napi Statement via the real Connection::execute_statement path and asserts cancel().await does not return InvalidStatementHandle.


F12 · MEDIUM — Five patterns duplicated between pyo3 and napi — bindings-common extraction overdue

[LOW CONFIDENCE — flagged by maintainability] · MEDIUM (track as follow-up, not blocker)

Five concrete patterns now duplicated across pyo3 and napi:

Concern pyo3 napi (this PR)
ErrorCode → string slug pyo3/src/errors.rs::code_str 13 arms napi/src/error.rs::error_code_str 13 arms — verbatim
Auth-config marshaling pyo3/src/auth.rs::build_auth_config inline in database.rs::open_session
Builder wiring (defaults + session_conf) pyo3/src/session.rs:131-143 napi/src/database.rs:332-339 — character-for-character
Closed-state error builder pyo3/src/errors.rs::closed_err (single fn + alive! macros) Two separate fns: connection_closed_err, statement_closed_err
Drop-spawn pattern (try_get_handle → spawn → take) n/a (per-Session Runtime) 1:1 copy between Connection Drop (l140-166) and Statement Drop (l665-692)

Plus an in-file repetition: the 5x identical Arc::clone + guarded + lock + as_ref/mut/take preamble in napi/src/statement.rs (3 sites) + connection.rs (2 sites). A macro mirroring pyo3's alive!/alive_mut! would collapse this.

The strongest single quick win: lift error_code_str into the kernel itself (via #[derive(strum::AsRefStr)] on ErrorCode or pub fn ErrorCode::slug(&self) -> &'static str). ~20 LOC in the kernel, deletes 30 LOC each from pyo3 and napi, makes drift structurally impossible.

Track as a bindings-common follow-up before PR #29 or in a separate refactor PR.


F13 · LOW — statement.rs 443 LOC — 5x identical lifecycle preamble; pyo3 has alive! macro precedent

[LOW CONFIDENCE — flagged by maintainability] · LOW

Three async methods on Statement (fetch_next_batch, cancel, close) plus two on Connection (execute_statement, close) repeat:

let inner = Arc::clone(&self.inner);
guarded(async move {
    let guard = inner.lock().await;
    let executed = guard.as_ref().ok_or_else(statement_closed_err)?;
    ...
}).await

pyo3 collapsed this pattern with alive!/alive_mut! macros in pyo3/src/macros.rs. napi doesn't have an equivalent.

Suggested fix: extract a macro like guarded_with_inner!(mut self, err, |g| { body }) covering the 5 call sites.


F15 · LOW — Arrow IPC per-batch schema redundancy — architectural decision worth benchmarking before locking in

[MODERATE CONFIDENCE — flagged by devils-advocate, architecture, performance] · LOW (architectural, documented trade)

napi/src/statement.rs:631-646 (encode_ipc_stream) emits a self-contained IPC stream per batch (schema header + 1 record-batch message). The comment owns the trade-off: "wasteful header-wise but lets the JS adapter stay stateless."

For a 1000-batch result with a 30-column schema, that's potentially ~30KB of redundant header overhead just on the kernel→JS hop. pyo3's path is zero-copy via arrow_pyarrow::ToPyArrow + Arrow C Data Interface.

Architectural alternative: emit schema once on Statement::schema() (already does this), have the JS adapter open one RecordBatchReader per Statement from that schema, then send "data only" payloads per batch. This is what JDBC/ODBC drivers do natively.

Suggested action: benchmark a typical 10-column / 1000-batch query vs the pyo3 equivalent before shipping the wire shape — it's hard to change later without an API break. Track as a follow-up performance investigation.


F16 · LOW — PR title misleads — only ONE new class shipped (Statement + Connection); no Database or ResultStream class

[LOW CONFIDENCE — flagged by architecture] · LOW (cosmetic but misleading)

PR title claims "Database / Connection / Statement / ResultStream napi classes." Actual surface:

Claimed Actual
Database class Not a class — openSession() free function (justified in database.rs:14-25)
Connection class Yes
Statement class Yes
ResultStream class Not exposed — batches stream via Statement.fetchNextBatch()

The justifications are reasonable AND documented in module docs, but the PR title and lib.rs header overpromise. pyo3 does expose a separate ResultStream pyclass, so the divergence is real.

Suggested fix: update the PR title or lib.rs module header to match the actual surface.


F17 · LOW — Misleading DefaultOpts is #[non_exhaustive] comment in database.rs::open_session (and mirrored in pyo3)

[LOW CONFIDENCE — flagged by language] · LOW

napi/src/database.rs::open_session has a comment claiming DefaultOpts is #[non_exhaustive] — but verified at head SHA, src/config.rs::DefaultOpts is a plain #[derive(Default)] struct, not #[non_exhaustive]. (SessionConfig is #[non_exhaustive], hence the builder — that part is correct.)

The same misleading comment appears in pyo3/src/session.rs, so this is mirrored slop, not net-new — but it makes a future maintainer trust a false constraint.

Suggested fix: either use struct-init syntax (DefaultOpts { catalog, schema } directly) or, if there's intent to make DefaultOpts #[non_exhaustive] later, add that attribute now and keep the comment.


F18 · LOW — ArrowBatch.ipcBytes / ArrowSchema.ipcBytes missing field-level /// for .d.ts discoverability

[LOW CONFIDENCE — flagged by agent-compat] · LOW

napi/src/result.rs:417-427 declares the IPC-bytes fields without /// doc comments. napi-rs forwards /// rustdoc into the generated .d.ts. Without field-level docs, the surfaced types are bare:

export class ArrowBatch { ipcBytes: Buffer; }
export class ArrowSchema { ipcBytes: Buffer; }

A JS-side LLM consumer has no signal that "this is an Arrow IPC stream payload, decode with apache-arrow's RecordBatchReader." The info is on the surrounding Statement.fetchNextBatch method only.

Suggested fix: add 1-line field docs:

/// Arrow IPC stream payload. Decode with apache-arrow `RecordBatchReader`.
pub ipc_bytes: Buffer,

F19 · LOW — Status mapping collapses InvalidStatementHandle to napi Status::InvalidArg — debugging gotcha if JS bypasses the TS reviver

[LOW CONFIDENCE — flagged by ops] · LOW (intentional, documented; flagging as a footgun)

napi/src/error.rs:154-160 maps InvalidStatementHandle to Status::InvalidArg. Per the doc, this is intentional — the TS reviver discriminates on envelope code, not on status.

Operational consequence: any napi consumer that bypasses the TS adapter and just reads err.code (which would be the napi Status, not the kernel code) will see InvalidArg for both true argument errors AND statement-state errors. Indistinguishable at that layer.

Suggested action: acceptable trade-off; flagged for awareness. The PR's own test (statement.rs:817-825) pins the mapping.


F20 · LOW — Sentinel debug_assert! collision check stripped from release builds (inherited from PR #27)

[LOW CONFIDENCE — flagged by ops] · LOW (subsumed by F5 typed-error refactor)

napi/src/error.rs:108-111 carries a debug_assert! against a kernel Error::message starting with __databricks_error__:. Release builds compile it out.

Today's kernel never emits such a message, but an external/wrapped error chain (e.g. an upstream error string passed through Error::with_source(...).message(...)) starting with the sentinel would corrupt the wire envelope on a indexOf-style TS reviver.

The PR #27 author intentionally reverted a hardening change (b692d34 was rolled back in PR #27's 377632a0) with the reasoning that "the envelope itself is the workaround — the right fix is typed errors in PR #25." But F5 confirms the typed-error refactor still hasn't landed.

Suggested action: subsumed by F5. If typed errors don't land in this PR, the debug_assert! should be promoted to a release-build escape branch (as I recommended in the PR #27 audit and the author rolled back).


Could not post inline comment for: F14 — see body below

F14 · LOW — encode_ipc_stream uses Vec::new() without capacity hint — ~17 reallocs per 500KB batch

[LOW CONFIDENCE — flagged by performance] · LOW

The IPC buffer starts at Vec::new() (default Vec capacity = 0). For a 500KB batch, that's ~17 reallocations as the Vec grows (doubling: 1 → 2 → 4 → ... → 524288). Each realloc copies all bytes already written.

Single-digit % CPU win on bulk fetch.

Suggested fix (in napi/src/statement.rs, encode_ipc_stream):

let estimated_size = record_batch.map(|rb| rb.get_array_memory_size()).unwrap_or(0) + 4096;
let mut buffer = Vec::with_capacity(estimated_size);
let mut writer = StreamWriter::try_new(&mut buffer, schema)?;

… classes

Lands the four #[napi] classes that expose the kernel's v0 surface:
- Database.open() returns a Database handle (Session)
- Connection.execute_statement() returns a Statement handle
- Statement.fetch_next_batch() / .schema() / .cancel() / .close()
- ResultStream (used internally; not directly exposed)

Results cross the FFI as Arrow IPC bytes (see result.rs); the TS
adapter decodes them via apache-arrow.

Builds on the skeleton commit; cargo check is clean.

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
…xecuteOptions

JS callers passing initialCatalog/initialSchema/sessionConfig on
executeStatement were silently no-op'd: the kernel does not read
StatementSpec::statement_conf (zero readers across src/), and the SEA
wire ExecuteStatementRequest has no per-statement catalog/schema/conf
fields. They were stuffed into a dead HashMap and the statement ran
against whatever the session was opened with.

Mirror pyo3's design: expose catalog/schema/sessionConf on
ConnectionOptions (openSession), routed through
Session::builder().defaults(DefaultOpts) and .session_conf(HashMap) —
the kernel APIs that actually populate SEA CreateSession.catalog /
.schema / .session_confs. Drop ExecuteOptions entirely; executeStatement
takes only the SQL.

Cross-checked: JDBC SEA carries catalog/schema only on CreateSession,
not ExecuteStatement (databricks-jdbc/.../sqlexec/CreateSessionRequest
.java vs ExecuteStatementRequest.java). pyo3 exposes them only on
Session.__new__ (pyo3/src/session.rs:73-141) and explicitly defers
statement_conf to "later phases" (pyo3/src/statement.rs:39-40).

BREAKING: napi executeStatement signature changes from
(sql, options) -> (sql). NodeJS driver consumers must move
initialCatalog/initialSchema/sessionConfig from per-statement
forwarding to per-session openSession() options. Tracked downstream.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
…ailures

Connection::close was fire-and-forget on the premise that the kernel's
Session::close().await holds a !Send EnteredSpan across an .await.
Reading the kernel: Session::close uses .instrument(span).await, which
keeps the future Send. The kernel also has a compile-time
assert_send(&session.close()) test that fails the build if anyone
flips that pattern.

Fix: await session.close() and map errors. The kernel docstring on
Session::close says it exists specifically so callers can observe a
DeleteSession failure — restore that contract. On Err, the kernel
leaves its closed flag false so Drop's fire-and-forget cleanup retries
as a fallback; the caller still gets the error to surface.

Drop stays fire-and-forget — Drop can't .await, period — but the
stale !Send rationale comment is removed.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
- statement.rs: two round-trip tests pinning the Arrow IPC wire-format
  contract between the binding and the JS-side `apache-arrow` adapter.
  Schema-only payload yields 0 batches; schema+batch yields 1 batch
  with input rows preserved. Collapse 3 identical error-wrap lambdas
  into a local `arrow_err` helper.
- statement.rs: docstring contracts — `fetchNextBatch` post-error
  recovery (close and discard); `cancel` is non-idempotent against
  natural completion (kernel hits the wire every time).
- connection.rs / statement.rs: `Drop` impls memorialize the
  napi-rs-runtime-alive invariant so any future process-exit reorder
  surfaces the assumption rather than silently leaking handles.
- Prune milestone roadmap markers from module-level docs; keep the
  technical WHY comments (Arc/Mutex rationale, #[non_exhaustive] arms,
  Send-safety).

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
… cached fields, idempotent cancel, kernel close retry contract

Summary of changes across kernel + binding:

- Kernel src/statement/executed.rs: reorder ExecutedStatement::close
  to set `closed=true` only after a successful wire call, mirroring
  Session::close. On wire failure the flag stays false so Drop's
  fire-and-forget retry runs as a fallback — without this a transient
  close failure silently leaks the server-side statement until session
  expiry. Allows two callers racing through `&self` to both hit the
  wire (server-side close is idempotent), trading one redundant RPC
  for the retry contract.

- napi/src/statement.rs:
  * Cache `schema: Arc<Schema>` and `statement_id: String` on the
    wrapper at construction so they survive close() — JS callers
    can still build error reports against a disposed Statement.
  * Add `statementId` getter via #[napi(getter)].
  * Idempotent cancel via `finished: AtomicBool` — set when
    fetch_next_batch observes the natural end of stream, short-circuits
    cancel() to Ok(()) so a defensive cancel after natural completion
    no longer surfaces an opaque server-side error.
  * Route closed-state errors through napi_err_from_kernel(
    KernelError::invalid_statement_handle()) via a single
    statement_closed_err() helper — TS adapter reviver gets typed
    KernelError(code='InvalidStatementHandle') instead of raw
    Status::InvalidArg with substring-only discrimination.
  * Route the non-Arrow ResultBatch fallback through the envelope too,
    include CARGO_PKG_VERSION so JS-side error reports pin which
    binding version was in use.
  * 6 new #[cfg(test)] unit tests pinning closed-state error envelope
    shape, cached-field survival, Arc cheapness, and finished-flag
    toggle.

- napi/src/connection.rs:
  * Add `session_id: String` cached on the wrapper, exposed as
    #[napi(getter)] — survives close() for log correlation.
  * Same envelope-routed closed-state error via connection_closed_err()
    helper.
  * 3 new #[cfg(test)] unit tests for the closed-state envelope shape
    and session_id survival.

- Both wrappers: soften Drop comments to "best-effort cleanup; we do
  not guarantee delete_session / close_statement on process exit"
  rather than asserting the uncited "unreachable under napi-rs's
  current process-exit ordering."
- Both wrappers: rewrite the `inner` field doc-comments to honestly
  describe the current single-mutex serialisation behaviour and link
  the follow-up JIRA candidate that tracks the lock-shape split.
- napi/src/database.rs: rationale for free-fn-over-static-method
  rewritten as the positive choice (no Database state to wrap) instead
  of an uncited claim about napi-rs codegen fragility.
- napi/src/lib.rs: module-level surface description updated to match
  the actual exports (openSession free fn + Connection + Statement +
  ArrowBatch/ArrowSchema POJOs — no Database class, no ResultStream
  class).

Test suite: 24/24 pass (was 16/16). All gates clean: cargo fmt
--check, cargo clippy --all-targets -- -D warnings, cargo test --lib.

The single-mutex concurrency limitation (cancel queues behind
fetchNextBatch; concurrent executeStatement calls serialise) is
documented but unfixed — the proper fix needs a kernel-side accessor
to expose ExecutedStatement as a shared Arc<dyn ExecutedStatementHandle>
plus a separate ResultStream slot. Tracked at
sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md.

Also-deferred: typed error refactor (LOW; existing JIRA candidate
2026-05-23-napi-typed-error-refactor.md), submit/async-consumption
path (LOW; M1 scope), parameter binding (LOW; M1 scope), fetchAll
convenience (LOW; JS-side SeaResultsProvider already wraps the
streaming primitive).

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Was: KernelError::internal() — pages oncall on telemetry false-positives
because Internal-category errors are interpreted as kernel bugs.

Now: KernelError::invalid_argument() — this isn't a kernel bug, it's
"binding too old for the kernel it's linked against" (the kernel rolled
a new ResultBatch variant that this binding's decode path doesn't know
how to handle). Matches the sibling-binding convention at
pyo3/src/fetch.rs:43,58.

The error message retains env!("CARGO_PKG_VERSION") so the JS-side
adapter surfaces actionable version-skew context to the user.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db msrathore-db changed the title feat(napi): Database / Connection / Statement / ResultStream napi classes (stack 3/8) feat(napi): openSession / Connection / Statement napi surface (stack 3/8) May 25, 2026
…honesty, IPC capacity, field docs, executed_async close parity, cancel-after-parent-drop regression test

Addresses 7 of the 20 review findings on PR #25 directly. Remaining
findings are tracked as JIRA candidates in the NodeJS workflow repo
under sea-workflow/jira-candidates/.

- F1+F2 (napi/src/statement.rs):
  drop async from Statement::schema(). The body is pure CPU work over
  a cached Arc<Schema> and matches pyo3/src/statement.rs::arrow_schema
  (sync). napi-rs handles panic conversion for sync #[napi] entry
  points, so the util::guarded wrapper used by the remaining async
  methods is not required here.

- F7/I4 (napi/src/{connection,statement}.rs):
  rewrite the close() JSDoc to honestly state that errors are
  terminal from the JS side. The kernel handle is .take()-ed before
  the wire call (because both Session::close and
  ExecutedStatement::close consume the handle by value or via the
  close-flag pattern), so a JS-side retry sees an already-closed
  wrapper and returns Ok(()). Only the kernel-level Drop fires a
  single fire-and-forget retry. The old JSDoc claim that callers
  could observe and retry close failures was misleading.

- F14 (napi/src/statement.rs::encode_ipc_stream):
  pre-size the IPC buffer with Vec::with_capacity(
  batch.map(get_array_memory_size).unwrap_or(0) + 4096) instead of
  Vec::new(). Removes ~17 reallocations on a typical 500 KB batch;
  4 KiB slack covers schema header + IPC framing overhead.

- F18 (napi/src/result.rs):
  add /// field-level docs on ArrowBatch.ipc_bytes and
  ArrowSchema.ipc_bytes so the generated .d.ts carries the "Decode
  with apache-arrow's RecordBatchReader" hint.

- F3+F10 (src/statement/executed_async.rs):
  mirror the new load -> wire -> store-on-success close pattern from
  ExecutedStatement::close into ExecutedAsyncStatement::close.
  Restores symmetric retry-on-failure contract across both executed
  handles. The retry branch is currently dead code because the SEA
  transport (src/client/sea.rs::close_statement) swallows errors;
  tracked as a follow-up kernel PR in the JIRA candidate file. Until
  the transport surfaces errors, the new pattern is forward-prep with
  identical observable behavior to the previous swap pattern.

- F9 (tests/v0_execute_wiremock.rs):
  add kernel_invariant_parent_drop_invalidates_executed_cancel. Pins
  the kernel-level invariant that PR #29's binding-side fix is
  designed around: dropping the parent Statement invalidates any
  outstanding ExecutedStatement's validity flag, so a subsequent
  cancel() short-circuits locally with InvalidStatementHandle. PR
  #29's StatementInner { _parent, executed } shape keeps the parent
  alive to avoid hitting this short-circuit. This test fails loudly
  if the kernel ever weakens the parent-drop semantic.

Refs: vikrantpuppala PR #25 review at 2026-05-25T15:40-15:44Z
(F1/F2/F3/F7/F9/F10/F14/F18).

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-classes branch from e684c4c to 9c56fbe Compare May 25, 2026 19:09
@msrathore-db

Copy link
Copy Markdown
Collaborator Author

Review round-3 response — addressed in 9c56fbe

PR title rewritten (F16) to feat(napi): openSession / Connection / Statement napi surface (stack 3/8) reflecting the actual surface.

Fixed in this PR

  • F1+F2 (I1+I2): sync Statement::schema(). Replies on threads.
  • F3+F10 (I3+I6): mirrored close pattern into ExecutedAsyncStatement + filed transport-fix JIRA. Replies on threads.
  • F7 (I4): close() JSDoc rewritten for errors-are-terminal honesty. Reply on thread.
  • F9: kernel-level regression test kernel_invariant_parent_drop_invalidates_executed_cancel added to tests/v0_execute_wiremock.rs. Pins the kernel invariant PR fix(napi): propagate StatementInner ValidityFlag fix from sea-operation (stack 4/8) #29's binding-side fix is designed around — fails loudly if the parent-drop semantic ever weakens.
  • F14: encode_ipc_stream now uses Vec::with_capacity(get_array_memory_size + 4096).
  • F18: field-level /// docs on ArrowBatch.ipc_bytes and ArrowSchema.ipc_bytes.
  • F16: PR title updated.

Deferred to follow-up JIRAs

  • F4 (napi_add_async_cleanup_hook) → sea-workflow/jira-candidates/2026-05-25-napi-cleanup-hook-vs-drop-spawn.md
  • F5 (typed-error refactor) → existing sea-workflow/jira-candidates/2026-05-23-napi-typed-error-refactor.md (Target-PR field updated to reflect deferral)
  • F6 (parameter binding — note: kernel now has named-binding on main post feat(reader): comparator parity — re-land of #64 (intervals_as_string, empty-result schema, composite types, TIMESTAMP tz, metadata reshape, named params) #72, so the gap is positional + named) → sea-workflow/jira-candidates/2026-05-25-napi-parameter-binding.md
  • F8 (I5) (lock-shape refactor) → existing sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md covers both cancel-during-fetch AND close-during-execute symptoms; F13 macro extraction folded in
  • F11 (I7) (cancel TOCTOU / idempotency polish) → sea-workflow/jira-candidates/2026-05-25-napi-cancel-toctou-and-idempotency.md (wire-benign per live probe; deferred as polish)
  • F12 (bindings-common extraction, starting with kernel-side ErrorCode::slug()) → sea-workflow/jira-candidates/2026-05-25-bindings-common-extraction.md
  • F15 (Arrow IPC per-batch schema redundancy — benchmark first) → sea-workflow/jira-candidates/2026-05-25-napi-arrow-ipc-schema-redundancy.md

Pushed back

  • F17: false positive. src/config.rs:174 confirms DefaultOpts IS #[non_exhaustive]. The comment in napi/src/database.rs:107-108 is accurate. No fix needed.

Subsumed

  • F13 (alive!/alive_mut! macro) — folded into the lock-shape refactor JIRA (the new shape changes the macro footprint, so extracting now would be wasted work).
  • F19, F20 — documented intentional / subsumed by F5. No fix.

Cascade

Rebase onto main (post-PR #72) completed cleanly with the rebase-cascade playbook's duplicate-commit skip pattern handling the PR #26/#27 squash-merge artifacts. New tips:

PR Old SHA New SHA
#25 kernel-napi-classes e684c4c 9c56fbe
#29 kernel-napi-statement-validity 9c04b0b 4acde6a
#28 kernel-oauth-error-class 185096c 09472d7
#30 krn-connection-pool-default-bump 122e6d3 c14c1ff
#24 krn-tls-public-api ba63971 8c0aabc
#23 krn-status-fields 99ef7ea 5265c75
(metadata-exposure) ba6bed1 6cda5ec

Gates green at every branch tip (cargo clippy --all-targets -- -D warnings, cargo test --lib = 24/24 napi + 446–448 kernel). Note: pre-existing fmt drift in src/reader/mod.rs and src/metadata/type_mapping.rs from PR #72 not introduced by this cascade.

@msrathore-db
msrathore-db enabled auto-merge (squash) May 26, 2026 08:59
@vikrantpuppala
vikrantpuppala disabled auto-merge May 26, 2026 09:08
@vikrantpuppala
vikrantpuppala merged commit ea4d398 into main May 26, 2026
vikrantpuppala pushed a commit that referenced this pull request May 26, 2026
…on (stack 4/8) (#29)

## Stack

Linear stack of 8 PRs on `databricks/databricks-sql-kernel` landing the
**SEA-driver kernel-side enablement** work. Merge in order from base ↑
to tip. The tip branch (`msrathore/krn-status-fields`, PR
[#23](#23)) is
the single snapshot containing every kernel-side change in flight.

| Pos | PR | Branch | Scope |
|---|---|---|---|
| 1/8 |
[#26](#26) |
`kernel-async-public-api` | Remove `block_on` from ResultStream +
Send-safety on Statement + rustls-tls + e2e test ported from
[#20](#20) |
| 2/8 |
[#27](#27) |
`kernel-napi-skeleton` | napi-rs binding crate skeleton: Cargo manifest
+ lib + error envelope + util + runtime + logger |
| 3/8 |
[#25](#25) |
`kernel-napi-classes` | Database / Connection / Statement / ResultStream
napi classes |
| 4/8 |
[#29](#29) |
`kernel-napi-statement-validity` | StatementInner ValidityFlag fix
propagated from sea-operation |
| 5/8 |
[#28](#28) |
`kernel-oauth-error-class` | Reclassify OAuth token-exchange failures as
`Error::unauthenticated()` (2-line fix in auth/oauth/m2m.rs + u2m.rs) |
| 6/8 |
[#30](#30) |
`krn-connection-pool-default-bump` | Bump
`HttpConfig.pool_max_idle_per_host` default from 10 → 100 |
| 7/8 |
[#24](#24) |
`krn-tls-public-api` | Expose `TlsConfig` fields (custom_ca_cert +
accept_self_signed + skip_hostname_verification) + stop discarding in
session.rs |
| 8/8 |
[#23](#23) |
`krn-status-fields` **← TIP** | Expose 5 status accessors on
`ExecutedStatement` (num_modified_rows / progress / display_message /
diagnostic_info / error_details_json) |

**Companion NodeJS stack** (`databricks/databricks-sql-nodejs`): 8 PRs —
root
[#378](databricks/databricks-sql-nodejs#378)
(sea-abstraction) →
[#380](databricks/databricks-sql-nodejs#380) →
[#377](databricks/databricks-sql-nodejs#377) →
[#379](databricks/databricks-sql-nodejs#379) →
[#382](databricks/databricks-sql-nodejs#382) →
[#381](databricks/databricks-sql-nodejs#381) →
[#384](databricks/databricks-sql-nodejs#384) →
[#383](databricks/databricks-sql-nodejs#383)
(tip).

**Policy:** new PRs always stack on the current tip. No sibling/parallel
topology. No force-pushes on existing PRs unless absolutely necessary;
if a PR's content is wrong, add a fix-up commit on top of the stack tip
rather than rewriting history.

---

**This PR is position 4/8.**

## Why this PR is structurally required (not redundant with PR #25)

Reviewers may notice this PR's diff against the new PR
[#25](#25) tip
looks like a follow-up nicety — it is not. It is a **correctness fix**
for a real lifecycle bug PR #25 ships in isolation.

**The bug** — PR #25's `Connection::execute_statement` builds a local
kernel `Statement`, awaits `stmt.execute()`, hands the resulting
`ExecutedStatement` to the JS-side `Statement` wrapper, then drops the
parent kernel `Statement` at end of the closure. The kernel's `Drop for
Statement` (`src/statement/mutable.rs:440-450`) calls
`valid.invalidate()` on the shared `ValidityFlag` between the parent and
the executed handle. The next `Statement.cancel()` from JS reaches
`ExecutedStatement::cancel()` → `self.valid.check()` →
`KernelError(InvalidStatementHandle)` — the **first** cancel call is
broken.

**The fix** — this PR wraps the inner state in `StatementInner {
_parent: KernelStatement, executed: ExecutedStatement }`, keeping the
parent alive for the JS wrapper's lifetime. The shared `ValidityFlag`
stays set, so cancel works on the first call.

**Stack-merge policy** — PR #25 and this PR must merge as a pair
(default Github stacked-PR flow handles this). The PR #25 description
carries a corresponding warning. Do not merge #25 to main without this
PR in the same merge train.

No new tests are added here — the closed-state assertions on PR #25's
`Statement::cancel()` pin the typed-error contract for the
parent-dropped case, and the cancel-after-completion idempotency tests
pin the JDBC contract. Both continue to pass on the merged state.
End-to-end cancel-during-fetch coverage is tracked as part of the
lock-shape refactor follow-up at
`sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`.

## Summary

Ports the StatementInner ValidityFlag fix from the NodeJS sea-operation
worktree into the kernel-side napi crate (~89 LOC, 2 files). Adds the
parent-Statement-keep-alive wrapper to `napi::Statement`'s inner state
so the executed handle's `ValidityFlag` stays set for the JS wrapper's
lifetime.

The fix was originally authored downstream in the NodeJS worktree's
vendored napi copy; landing it on the kernel-side napi crate keeps the
two consistent until D-006 consolidation closes the vendoring gap.

## Test plan

- `cargo test` clean (24/24 lib tests pass against the merged PR #25 +
#29 state)
- Downstream NodeJS `sea-operation` feature already validates the fix in
JS-side unit tests

## Tracking

- [PECOBLR-2917](https://databricks.atlassian.net/browse/PECOBLR-2917) —
Fix napi binding SIGSEGV — StatementInner ValidityFlag
- Parent epic:
[PECOBLR-2666](https://databricks.atlassian.net/browse/PECOBLR-2666)

Co-authored-by: Isaac

[PECOBLR-2917]:
https://databricks.atlassian.net/browse/PECOBLR-2917?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
msrathore-db added a commit that referenced this pull request May 26, 2026
…on (re-target to main) (#78)

## Summary

Re-targets the StatementInner ValidityFlag fix that was originally
landed in PR #29 against `main`.

PR #29 (`fix(napi): propagate StatementInner ValidityFlag fix from
sea-operation (stack 4/8)`) was inadvertently merged into the
stack-parent branch `msrathore/kernel-napi-classes` instead of into
`main`. Since `msrathore/kernel-napi-classes` (PR #25) has since been
squash-merged into `main`, the validity fix never reached `main` —
`ea4d398` on `main` is just the PR #25 squash, missing the validity flag
fix.

## What's in this PR

Two commits:

1. **`bdc1e2a` — cherry-pick of PR #29's commit `4acde6a`** ("napi:
propagate StatementInner ValidityFlag fix from sea-operation").
Untouched content; pure cherry-pick. Changes `napi/src/connection.rs` +
`napi/src/statement.rs` (90 lines).

2. **`4245a2c` — `cargo fmt --all` chore-fixup** to clear inherited
rustfmt drift on `src/metadata/static_data.rs`,
`src/metadata/type_mapping.rs`, `src/reader/mod.rs`. These files are
pre-existing on `main` at `ea4d398` (confirmed by running `cargo +stable
fmt --all -- --check` against `origin/main`). Pure mechanical fmt; no
semantic change.

## Why the validity fix matters

From PR #29's commit message: kernel `Statement::Drop` invalidates its
produced `ExecutedStatement` via a shared `ValidityFlag`. The parent
kernel `Statement` constructed in `Connection::execute_statement` was
dropping at the end of that function, rendering every subsequent
`cancel()`/`close()` on the executed handle a no-op throwing
`InvalidStatementHandle`.

This PR introduces `StatementInner { _parent: KernelStatement, executed
}` so both lifetimes are tied. `Statement::from_executed` now takes the
parent statement alongside the executed handle.
`Connection::execute_statement` passes both in. `ValidityFlag` stays set
for as long as JS holds the wrapper.

## Gates

Verified on this branch (`4245a2c`):
- `cargo +stable fmt --all -- --check` — EXIT 0
- `cargo clippy --all-targets -- -D warnings` — EXIT 0
- `cargo test --lib` — 441/441 passing

## History

- Original PR:
[#29](#29)
(merged to `msrathore/kernel-napi-classes` at `f4fa428` instead of
`main`).
- Tracking JIRA: PECOBLR-2917 (concurrency / SIGSEGV class of issues
this fix addresses).

---------

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
msrathore-db added a commit that referenced this pull request May 26, 2026
…ted (stack 5/8) (#28)

## Stack

Linear stack of 8 PRs on `databricks/databricks-sql-kernel` landing the
**SEA-driver kernel-side enablement** work. Merge in order from base ↑
to tip. The tip branch (`msrathore/krn-status-fields`, PR
[#23](#23)) is
the single snapshot containing every kernel-side change in flight.

| Pos | PR | Branch | Scope |
|---|---|---|---|
| 1/8 |
[#26](#26) |
`kernel-async-public-api` | Remove `block_on` from ResultStream +
Send-safety on Statement + rustls-tls + e2e test ported from
[#20](#20) |
| 2/8 |
[#27](#27) |
`kernel-napi-skeleton` | napi-rs binding crate skeleton: Cargo manifest
+ lib + error envelope + util + runtime + logger |
| 3/8 |
[#25](#25) |
`kernel-napi-classes` | Database / Connection / Statement / ResultStream
napi classes |
| 4/8 |
[#29](#29) |
`kernel-napi-statement-validity` | StatementInner ValidityFlag fix
propagated from sea-operation |
| 5/8 |
[#28](#28) |
`kernel-oauth-error-class` | Reclassify OAuth token-exchange failures as
`Error::unauthenticated()` (2-line fix in auth/oauth/m2m.rs + u2m.rs) |
| 6/8 |
[#30](#30) |
`krn-connection-pool-default-bump` | Bump
`HttpConfig.pool_max_idle_per_host` default from 10 → 100 |
| 7/8 |
[#24](#24) |
`krn-tls-public-api` | Expose `TlsConfig` fields (custom_ca_cert +
accept_self_signed + skip_hostname_verification) + stop discarding in
session.rs |
| 8/8 |
[#23](#23) |
`krn-status-fields` **← TIP** | Expose 5 status accessors on
`ExecutedStatement` (num_modified_rows / progress / display_message /
diagnostic_info / error_details_json) |

**Companion NodeJS stack** (`databricks/databricks-sql-nodejs`): 8 PRs —
root
[#378](databricks/databricks-sql-nodejs#378)
(sea-abstraction) →
[#380](databricks/databricks-sql-nodejs#380) →
[#377](databricks/databricks-sql-nodejs#377) →
[#379](databricks/databricks-sql-nodejs#379) →
[#382](databricks/databricks-sql-nodejs#382) →
[#381](databricks/databricks-sql-nodejs#381) →
[#384](databricks/databricks-sql-nodejs#384) →
[#383](databricks/databricks-sql-nodejs#383)
(tip).

**Policy:** new PRs always stack on the current tip. No sibling/parallel
topology. No force-pushes on existing PRs unless absolutely necessary;
if a PR's content is wrong, add a fix-up commit on top of the stack tip
rather than rewriting history.

---

**This PR is position 5/8.**

## Summary

**Two-line fix.** Changes `Error::io()` → `Error::unauthenticated()` in
two OAuth token-exchange catch arms:
- `src/auth/oauth/m2m.rs:270`
- `src/auth/oauth/u2m.rs:433`

## Why

The previous classification surfaced OAuth credential rejections as a
generic IO error → downstream JS `SeaErrorMapping` decoder produced
`HiveDriverError`. The correct semantics are `AuthenticationError`
(typed). This 2-line change unblocks the NodeJS M2M bad-secret e2e at
`sea-auth-u2m@e7c979d` (which now correctly raises `instanceof
AuthenticationError`).

## Deferred follow-up

Precise classification of `oauth2::RequestTokenError` subtypes (5xx
token-endpoint failures, transport errors → `NetworkError` instead of
`Unauthenticated`). Tracked as NF3-1 in the NodeJS round-3 review chain;
non-blocking today because JS-side retry policy isn't yet wired through
SEA.

## Tracking

- [PECOBLR-2878](https://databricks.atlassian.net/browse/PECOBLR-2878) —
Error class hierarchy expansion — reclassify OAuth as Unauthenticated
- Parent epic:
[PECOBLR-2666](https://databricks.atlassian.net/browse/PECOBLR-2666)

Co-authored-by: Isaac

[PECOBLR-2878]:
https://databricks.atlassian.net/browse/PECOBLR-2878?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
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