Skip to content

fix(kernel,napi): surface close_statement errors + non-blocking concurrent executeStatement - #99

Closed
msrathore-db wants to merge 32 commits into
mainfrom
msrathore/kernel-statement-lifecycle
Closed

msrathore-db wants to merge 32 commits into
mainfrom
msrathore/kernel-statement-lifecycle

Conversation

@msrathore-db

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

Copy link
Copy Markdown
Collaborator

What

Main-based kernel stack-head PR for the SEA parity surface plus statement lifecycle/concurrency fixes. This branch was merged with latest main so reviewers see the real diff against current main.

Current real diff after merging latest main: about 2294 additions / 79 deletions across 15 files.

Included Changes

This PR intentionally includes the broad SEA kernel/napi parity surface also represented in #101:

  • napi connection/database/statement wiring for the SEA backend
  • metadata exposure through napi and metadata_v0
  • parameter codec support for positional/named parameters and richer typed values
  • statement option plumbing for statement conf, query tags, row limit, and timeout support
  • reader/inline provider updates and HTTP/config/session plumbing needed by the SEA path

Specific to this PR on top of the bundled parity surface:

  • Surfaces close_statement errors instead of swallowing them, so close failures can be observed by callers/tests.
  • Adjusts statement lifecycle handling around outstanding executed handles.
  • Moves the napi connection execution path toward non-blocking concurrent executeStatement behavior instead of serializing unrelated statements behind one long-held lock.
  • Carries latest main, including fix(sea): close orphaned statement when execute_and_read fails #92's orphaned-statement cleanup, so stale duplicate hunks from the old stack are removed.

Review Notes

This is intentionally a large main-based stack-head PR. It overlaps heavily with #101 because the old stacked base has been flattened for agent review. Reviewers should focus on close/error propagation and connection execution concurrency when comparing this PR to #101.

Testing

CI is validating the current main-merged branch. Component validation before flattening included Rust fmt, clippy, unit tests, and napi tests on the affected branches.

This pull request and its description were written by Isaac.

… 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>
…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>
When the binding's Statement wrapper was first written it held only
the kernel's ExecutedStatement. The sea-operation feature surfaced a
bug: kernel Statement::Drop invalidates its produced ExecutedStatement
via a shared ValidityFlag, so the parent kernel Statement constructed
in Connection::execute_statement was dropping at the end of that
function and rendering every subsequent cancel()/close() on the
executed handle a no-op throwing InvalidStatementHandle.

Fix: introduce StatementInner { _parent: KernelStatement, executed }
in the wrapper 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.

Originally landed in the nodejs sea-operation worktree (e06a5e8);
relocated here as part of the napi-source move into the kernel
workspace. The integration branch's version was the authoritative one
because it had all downstream feature merges layered in.

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

Per src/kernel_error.rs:74-77 doc-comment, Unauthenticated is the
intended ErrorCode for "Server returned HTTP 401 (or OIDC discovery
rejected the token request)". M2M and U2M token-exchange paths were
using Error::io() (-> Internal), which is reserved for kernel-side
I/O / parsing failures. The misclassification caused authentication
failures to surface in NodeJS as HiveDriverError instead of
AuthenticationError (D-015).

Fix: m2m.rs:270 and u2m.rs:433 swap Error::io() -> Error::unauthenticated().
No kernel unit tests assert ErrorCode::Internal on these paths
(verified by grep) so no test updates are needed. The U2M test
`test_u2m_cache_miss_with_expired_refresh` asserts only `result.is_err()`,
which remains true.

Deferred (worth a follow-up): distinguish oauth2::RequestTokenError
subtypes so 5xx token-endpoint failures get NetworkError while
invalid_client / invalid_grant / unauthorized_client stay
Unauthenticated. The current change correctly handles the dominant
case (bad-credentials -> 400/401 from server) and matches the
existing kernel doc-comment intent.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Matches the JDBC driver's `HttpConnectionPoolSize` default (100) and the
kernel-internal `HttpClientConfig` default. Closes ~9x of the throughput
gap with the NodeJS thrift driver's `maxSockets: Infinity` default for
high-concurrency workloads (bursty parallel executeStatement, parallel
CloudFetch chunk downloads). reqwest/hyper does not bound this; the prior
10 was a kernel-side conservative choice.

Spec: sea-workflow/specs/07-errors-retries/connection-pool-default-mismatch.md
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
…ion.rs

The kernel has had working reqwest plumbing for custom CA certs,
self-signed acceptance, and hostname-verification skip at
client/http.rs since the original TLS migration. That implementation
has been unreachable from any public wrapper because (a) the public
TlsConfig struct in config.rs was empty and (b) session.rs explicitly
discarded any caller-supplied TlsConfig and replaced with default.

This commit:
- Adds custom_ca_cert / accept_self_signed /
  skip_hostname_verification fields to public TlsConfig
- Adds a trusted_certificate_pem field to the internal
  HttpTlsConfig so the public custom_ca_cert (Vec<u8>) can flow
  through without a tempfile shim — foreign-language wrappers
  (napi-rs Buffer / pyo3 bytes) get a direct path
- Adds HttpTlsConfig::from_public / From<&public::TlsConfig> to
  project the public surface onto the internal layer
- Wires session.rs::build_http_client_config to call
  HttpTlsConfig::from_public(&config.tls) instead of discarding
- Adds a custom Debug impl on the public TlsConfig that
  summarises the cert bytes ("<N bytes>") instead of dumping the
  whole PEM into log lines
- Adds builder-introspection tests that construct a
  DatabricksHttpClient via the public -> internal mapping with
  each flag in turn and verify the reqwest builder succeeds

Public TlsConfig defaults remain strict: accept_self_signed=false,
skip_hostname_verification=false, custom_ca_cert=None. The default
projection produces an internal config with `None` everywhere on
the permissive switches so RUST_LOG output stays free of no-op
overrides.

Unblocks NodeJS-side TLS Buffer->tempfile shim row (kernel now
accepts Vec<u8> directly; no tempfile needed) and is a prereq for
future mTLS work (client_cert / client_key remain unwired — that's
a separate follow-up).

The pre-existing lib-test failure in client::http::tests::
test_http_client_with_invalid_pem (D-016: reqwest::Certificate::
from_pem accepts garbage strings under the rustls-tls backend) is
unrelated to this commit and reproduces on the krn-napi-binding
base.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Adds num_modified_rows(), progress(), display_message(),
diagnostic_info(), and error_details_json() getters on
ExecutedStatement. Data is parsed from the SEA
GET /sql/statements/{id} response in client/sea.rs; this
commit only exposes the accessors so the napi binding
(and Python pyo3 binding) can surface them.

Structural change: the wire-protocol StatementStatus in
types/sea.rs was previously decoding only `state` and
`error`; the five new fields are added as `Option<...>`
behind `#[serde(default)]` so they remain backward-
compatible with the absent-field SEA responses today's
classic-warehouse fixtures emit. The status struct flows
through ExecuteResult (already carrying manifest) into
ExecutedStatement, which stores it once at construction
and hands out cheap field-level accessors.

Unblocks NodeJS Operation.status() field synthesis
(feature-tracker line 39 / kernel carry-over row).

Tests:
- types::sea::tests::test_statement_status_with_extended_fields
- types::sea::tests::test_statement_status_extended_fields_absent
- tests/v0_execute_wiremock::executed_statement_surfaces_extended_status_fields
- tests/v0_execute_wiremock::executed_statement_status_fields_default_to_none

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Adds Statement::from_result_stream (internal constructor wrapping a
bare ResultStream) and a new napi/src/metadata.rs that wires all 10
kernel Metadata methods onto the JS Connection class:

  listCatalogs, listSchemas, listTables, listColumns,
  listFunctions, listProcedures, listTableTypes, listTypeInfo,
  getPrimaryKeys, getCrossReference

Each returns the same Statement type as executeStatement so the JS
SeaOperationBackend wraps them uniformly. Cancel on metadata-derived
Statements is a no-op (no server-side cancellation surface today).

The kernel Metadata methods hold a tracing::EnteredSpan (!Send) across
their await points. The fix: acquire the session lock, clone the Send
Metadata handle, drop the lock, then run the !Send future inside
tokio::task::spawn_blocking via Handle::block_on — a standard
pattern for escaping the Send bound without LocalSet.

Also fixes:
- pre-existing unused StatementState import in src/client/transport.rs
- pre-existing dead_code lint on open_session + ConnectionOptions in
  napi/src/database.rs (exported via napi macro codegen, not called
  from Rust directly)
- AnyInner::Executed variant boxed to satisfy large_enum_variant lint

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

H1: `run_on_blocking`'s closure type was `FnOnce(Handle) -> Fut`, giving callers
access to the runtime handle inside a `spawn_blocking` thread. Any future caller
using that handle to call `block_on_in_runtime` would trigger `block_in_place`
inside a blocking thread — the PECOBLR-2917 abort vector. Drop the parameter;
callers that needed it for `Handle::block_on` already have a captured `handle`.
All 10 call sites updated from `move |_h|` to `move ||`.

H2: `Identifier::new` and `LikePattern::new` accepted whitespace-only strings
(e.g., `"   "`) that would produce meaningless or empty tokens at the SQL layer.
Add `s.trim().is_empty()` guard after the `s.is_empty()` check in both. Two unit
tests added covering space, tab, newline, and mixed whitespace inputs.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Databricks SHOW TABLES does not accept a table-type filter server-side;
the kernel applies it client-side after the result returns. Mirror the
language already present in src/metadata_v0.rs:310-313 so napi callers
are not misled into expecting server-side enforcement.

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

The whitespace-only check was added in code but the /// Rejects: bullet
list in each constructor docblock didn't mention it. Add a bullet to both
Identifier::new and LikePattern::new explaining the rejection and the
reason (blank token / use None for "match all").

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Leftover from the H1 fixup that removed the `Handle` parameter from
`run_on_blocking`'s signature. With no callers of `Handle` as a type
remaining in metadata.rs, the import is dead and trips
`cargo clippy --all-targets -- -D warnings`.

Doc-comment references to `Handle::block_on` and `Handle::current()`
remain (they describe behavior, not Rust paths).

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

Surfaces two of the kernel `StatementSpec` knobs through napi so
JS callers can pass per-statement Spark conf and query tags:

- `statementConf: Record<string, string>` — per-statement conf
  overlay; merged on top of the session-level `sessionConf` at
  execute time. The kernel's `StatementSpec::statement_conf()`
  setter accepts this verbatim and forwards to SEA `parameters` /
  Thrift `confOverlay`.
- `queryTags: Record<string, string>` — convenience wrapper that
  JSON-encodes the tag map into the `query_tags` conf overlay key,
  matching NodeJS Thrift's `serializeQueryTags` shape
  (`{"k":"v","k2":"v2"}`). Passing both `queryTags` and an explicit
  `statementConf["query_tags"]` raises `InvalidArgument` to
  surface the ambiguity to the caller.

Deferred (require kernel-side `StatementSpec` extensions or napi
TypedValue mapping — separate PRs):
- Positional / named parameters (TypedValue mapping)
- Row limit, wait timeout (need `StatementSpec.row_limit` /
  `wait_timeout` fields — currently only on internal `ExecuteParams`)
- Async execute (kernel has `submit()`; needs new napi wrapper class)

The new `ExecuteOptions` napi-object is `Option<…>` so existing
callers (`executeStatement(sql)`) keep working — napi-rs emits
`options?: ExecuteOptions | undefined | null` on the JS-side d.ts.
Empty maps (`{statementConf: {}}`) are treated the same as
omission so the wire shape stays stable for the common case.

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
DA round 1 findings on F3:

H1 (clippy `err_expect`): the
`merged_conf_rejects_dual_query_tags_definition` test used
`.err().expect(...)` which clippy 1.95+ flags. Switch to
`.expect_err(...)` per the suggested help text. Behaviour
unchanged; this was a stylistic clippy lint, not a logic
defect.

H2 (rustfmt): the
`merged_conf_query_tags_escape_backslash_in_keys` test
expressed a long `assert_eq!` on one line that exceeded
rustfmt's max width. Break across three lines per the cargo
fmt diff. Behaviour unchanged.

Why I missed these initially: my prior gate verification ran
inside a different worktree on the same branch (the F3b
worktree, which had an in-progress amend), so my local
`cargo clippy` + `cargo fmt --check` both reported green
there. The origin branch (this PR's HEAD `79bba34`) didn't
carry that amend. Lesson: never trust gate verification
across worktrees without confirming the working tree matches
the pushed SHA.

Verified post-fix:
- `cargo clippy --all-targets -- -D warnings` ✓
- `cargo +stable fmt --check` ✓
- `cargo test --lib` ✓ (32/32, same as before the fix)

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
DA round 2 findings on F3 (statement options + query tags):

M1 docs: prior docstring claimed `queryTags` is "JSON-encoded
into the conf overlay" — wrong. The actual implementation
serialises to comma-separated `key:value` matching NodeJS
Thrift's `serializeQueryTags` wire shape (`lib/utils/queryTags.ts`).
Updated three sites that carried the stale "JSON" reference:
- `ExecuteOptions` struct doc
- `query_tags` field doc
- `Connection::execute_statement` method doc + inline comment

M2 dead code: the napi `queryTags` field is intentionally
exported even though the JS adapter today pre-serialises via the
Thrift helper and writes into `statementConf["query_tags"]`
directly. The field stays as an alternate API surface for non-
NodeJS consumers (future pyo3 reuse, direct napi consumers); the
NodeJS adapter path is documented as the byte-identical-Thrift-
parity route. Updated the struct doc to spell out the dual paths
and their parity contracts.

M4 parity: added a struct-level "Tag-order caveat" doc block
that documents the HashMap-iteration-order vs `Object.keys`-
insertion-order divergence between the napi `queryTags` path
and Thrift's `serializeQueryTags`. The SEA server is order-
insensitive on conf values so the two are functionally
equivalent; callers needing byte-identical Thrift parity use the
JS adapter path. Added 5 new Rust unit tests pinning the per-tag
byte shape against the Thrift algorithm:
- single-tag deterministic case
- value-side escape ordering (`\` `:` `,`)
- key-side backslash-only escape (NOT colons/commas — Thrift
  asymmetry pinned so a future "uniformity" refactor fails the
  test)
- empty-map edge case
- multi-tag order-insensitive set equality

M3 lint: already clean — `cargo clippy --all-targets -- -D warnings`
passes locally on this branch's tip.

Test count: 32 → 37 (5 new). All passing.

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Mirror pyo3/src/params.rs in the napi binding so the JS side can bind
positional parameters via Connection.executeStatement(sql, { positional_params }).
Each parameter is a { sql_type, value } pair — value is the string-encoded
literal or null for SQL NULL. The decoder parses through the same
validation surface pyo3 uses (DECIMAL precision/scale, non-finite
FLOAT/DOUBLE rejection, compound/BINARY rejection), so the two
language bindings stay aligned on what the kernel sees on the wire.

ExecuteOptions is exposed as a JS-visible object so future
statement-level knobs (named params, conf overlay, result format)
can land non-breakingly.

Tests cover the 10-type C5 matrix (INT, BIGINT, FLOAT, DOUBLE,
STRING, BOOLEAN, DATE, TIMESTAMP, DECIMAL, BINARY-rejected) plus
the eager-failure + null-value contracts at the helper level.

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

Closes the SEA↔Thrift parity rows 2.15 (row_limit) and 2.17 (server
statement timeout) from the cross-driver feature matrix. Both are
exercised by Python `use_sea` (row_limit=, wait_timeout=) but were not
reachable through the kernel's public StatementSpec, so NodeJS SEA and
Python use_kernel could not offer them.

- StatementSpec gains `row_limit: Option<i64>` and
  `query_timeout_secs: Option<u32>` with fluent setters. The SEA wire
  request already carried `row_limit` / `wait_timeout` / `on_wait_timeout`
  (types::sea::ExecuteParams); this only surfaces them on the public spec
  and threads them through `prepare_for_dispatch` — no new wire surface.

- Server statement timeout maps to SEA `wait_timeout` with
  `on_wait_timeout = CANCEL` so the statement is cancelled on elapse
  (JDBC setQueryTimeout / Python use_sea wait_timeout semantics), distinct
  from the connection-level transport `overall_timeout`. The wait-timeout
  precedence (async-submit "0s" respected verbatim vs sync-execute honoring
  the spec timeout vs server default) is extracted into the pure
  `resolve_wait_timeout` helper and unit-tested.

- napi `ExecuteOptions` exposes `rowLimit` + `queryTimeoutSecs`, threaded
  onto the spec; the scalars are read before `options` is consumed by the
  query-tags merge.

Validation: cargo fmt + clippy clean; new unit tests cover the spec
setters, the wait-timeout precedence (3 cases), and the unchanged
query-tags merge. The SEA server clamps wait_timeout at 50s; the kernel
forwards the requested value verbatim.

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
With a row_limit applied, the SEA server returns one extra look-ahead
Arrow row beyond the logical result size and marks the manifest
`truncated = true` with `total_row_count = N` (the requested limit). The
inline reader decoded the raw Arrow stream verbatim, so `row_limit = N`
surfaced N+1 rows — verified live (limit 10 → 11 rows, ids 0..10; limit 5
→ 6) and against the SEA response manifest, which reports `total_row_count
= 10, truncated = true` for a limit of 10.

The manifest count — not the raw Arrow row count — is the authoritative
result size. `InlineArrowProvider::new` now takes the manifest's
`total_row_count` and clamps the decoded batches to it (slicing the batch
that crosses the boundary), mirroring the Python SEA connector, which
bounds its `ArrowQueue` by `total_row_count`. This makes `row_limit`
return exactly N rows — parity with Python use_sea and Thrift.

`None` (count absent) leaves batches unclamped; an above-actual count is a
no-op. The clamp arithmetic is a pure, unit-tested helper.

Verified live: row_limit 10 → 10 rows, 5 → 5 rows; non-limited queries
unchanged. New unit tests cover None-passthrough, cross-batch slicing,
above-actual no-op, and the N+1 look-ahead clamp.

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

The kernel implements OAuth M2M (client-credentials) and U2M (auth-code +
PKCE) in `AuthConfig::OAuthM2M` / `OAuthU2M`, but the napi binding only
wired `AuthConfig::Pat` — so NodeJS SEA (and pyo3, which has the same gap)
could not offer OAuth even though the kernel fully supports it. This
surfaces it on the binding.

- New `#[napi(string_enum)] AuthMode { Pat, OAuthM2m, OAuthU2m }` whose
  string values (`'Pat'` / `'OAuthM2m'` / `'OAuthU2m'`) match what the
  NodeJS SEA adapter (`SeaAuth`) already expects verbatim.
- `ConnectionOptions` gains `authMode` (default Pat — back-compat for
  existing PAT callers that pass only `token`), `oauthClientId`,
  `oauthClientSecret`, `oauthRedirectPort`, `oauthScopes`. `token` is now
  optional (required only for Pat).
- `build_auth_config` maps the JS options onto the kernel `AuthConfig`,
  enforcing per-mode required fields at the binding boundary (fail-fast
  `InvalidArgument` before any network) so the kernel always receives a
  fully-formed variant. Pure + unit-tested. OAuth `Federation` / `External`
  are intentionally not exposed (kernel marks federation unimplemented;
  External is a Rust-trait escape hatch with no JS-callback bridge).

Validation: cargo fmt + clippy clean; 4 new unit tests (Pat default +
empty-token reject, M2M required-field validation, U2M all-optional with
override threading); 41 napi unit tests green. Live: OAuth M2M
client-credentials grant against pecotesting authenticated successfully
(server then applied warehouse-level authorization); PAT continues to work
both with an explicit `authMode: Pat` and with `authMode` omitted.

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

# Conflicts:
#	napi/src/connection.rs
#	napi/src/database.rs
#	napi/src/lib.rs
#	napi/src/statement.rs
#	tests/v0_execute_wiremock.rs
…clamp) — local integration branch for the node SEA comparator
Surface the kernel's ResultConfig.intervals_as_string and
complex_types_as_json knobs on the napi ConnectionOptions, threaded onto
the SessionBuilder via `builder.result(ResultConfig)` (mirrors the pyo3
Session.__new__ surface). Omitted ⇒ kernel default (native Arrow
month_interval / duration[us] and native nested types).

Motivation: the NodeJS Thrift driver surfaces INTERVAL columns as strings,
so the SEA driver needs intervals_as_string=true for byte-compatible
result parity (verified via the node comparator — interval columns then
match Thrift in both type code and value). complex_types_as_json is
exposed alongside for completeness; the SEA driver leaves it at the
native-Arrow default (which already decodes identically to Thrift).

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
…dec' into msrathore/krn-all-integration

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

# Conflicts:
#	napi/src/connection.rs
#	napi/src/lib.rs
…ions

Adds namedParams (Array<{name, sqlType, value?}>) alongside positionalParams,
decoded via the same parse_typed_value codec and bound with
StatementSpec::param_named. Named is the SEA-spec-required public param form.

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

Two statement/connection lifecycle robustness fixes from the jira-candidate
triage:

- kernel `SeaTransport::close_statement` (src/client/sea.rs) now BUBBLES the
  post-retry wire error instead of `let _ = …` swallowing it. The
  `ExecutedStatement::close` / `ExecutedAsyncStatement::close` "store-on-success
  retry" pattern only flips the `closed` flag on success, so the swallow made
  the failure branch dead code and a failed explicit close looked successful.
  Both pyo3 and napi inherit the fix; the Drop fire-and-forget fallback close
  still runs on error. (jira 2026-05-25-kernel-sea-close-statement-surface-errors)

- napi `Connection.executeStatement` no longer holds the session mutex across
  `execute().await`. `Session::statement()` returns an owned kernel `Statement`
  (it clones the session's internal Arc), so we build the statement under the
  lock and release it before the wire round-trip. This unblocks concurrent
  `Promise.all([executeStatement(...)])` (they serialise only for the
  microsecond statement-build) and stops `close()` from blocking behind an
  in-flight execute. (jira 2026-05-24-napi-cancel-during-fetch, connection-side)

The statement-side half of the lock-shape refactor (cancel-during-fetch — split
the kernel ExecutedStatement into a lock-free cancel/close handle + a stream
slot) is deferred: it needs a kernel ExecutedStatement restructure and is
higher-risk; tracked separately.

Build + 69 napi tests + fmt + clippy clean.

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db changed the base branch from msrathore/krn-all-integration to main June 1, 2026 05:37
vikrantpuppala added a commit that referenced this pull request Jun 1, 2026
## Summary

After ``call_execute_api`` succeeds the SEA statement is open on the
server. Two paths into a leak that would otherwise persist until SQL
Gateway's ``CommandInactivityTimeout`` (~1h):

1. **``wait_for_completion`` returns ``Error::timeout``** while the
server still considers the statement live in PENDING / RUNNING. Terminal
FAILED / CANCELED is the server's own cleanup signal and doesn't need a
CloseStatement, but the polling-timeout path does.
2. **``create_reader`` fails.** The most likely sub-failure today is
``ResultPostProcessor::new`` →
``StreamingCloudFetchProvider::get_schema`` eagerly downloading chunk 0
to extract the result schema; a non-retriable 4xx / persistent 5xx on
that GET propagates up.

The kernel never issues ``DELETE /api/2.0/sql/statements/{id}`` in
either case.

### How the bug surfaced

Investigation triggered by
[databricks-driver-test#410](databricks/databricks-driver-test#410)
CLOUDFETCH-016. The proxy-test suite ran a perpetual ``cloudfetch_500``
scenario against ``SELECT id FROM range(2000000)`` and observed:

```
[baseline] raised=1 CloseStatement=0 DeleteSession=1
```

Session-level cleanup fires, but the per-statement handle is orphaned.
Traced down to ``execute_and_read``: it propagates ``create_reader``
errors via ``?`` without persisting the ``statement_id`` for later
cleanup.

## Fix

Capture the ``statement_id`` from the initial response (before
``wait_for_completion``) and fire a best-effort close on either failure
path via the ``Transport::close_statement`` trait method.
``close_statement`` already swallows its own errors; the wrapper here is
a logging seam that attributes which phase failed
(``wait_for_completion`` vs ``create_reader``) so traces stay
diagnosable.

## Validation

**Unit reproducer**
(``tests/v0_execute_wiremock.rs::execute_cloudfetch_chunk0_failure_closes_statement``):
mounts a SUCCEEDED execute response with ``external_links`` pointing at
the mock server, then 404s the chunk-0 GET. Asserts the mock observes a
``DELETE /api/2.0/sql/statements/{id}``.

- Baseline (before this PR): **FAIL** — 5 chunk-0 GET retries then no
DELETE.
- With fix: **PASS** in 6.03s.

**Full suite:** ``cargo test --workspace --lib --tests`` — 619 tests
pass, 0 failures, 0 new ignored. ``cargo clippy --all-targets`` clean
(no new warnings from the modified files; pre-existing fmt drift in
``src/reader/cloudfetch/arrow_parser.rs`` is unrelated and pre-existing
on ``main``).

**End-to-end via driver-test**: rebuilt the proxy-test venv against this
branch (``DATABRICKS_KERNEL_PATH=$BRANCH``) and re-ran the
CLOUDFETCH-016 equivalent path:

```
[verify] raised=1 CloseStatement=1 DeleteSession=1
```

## Out of scope (follow-ups)

- **Connector-side equivalent.** The Python connector
(``databricks-sql-python``) has the same shape of bug on the Thrift path
— ``ThriftDatabricksClient.execute_command`` constructs the ResultSet
inline, and a failing ``ThriftCloudFetchQueue.__init__`` (which eagerly
downloads chunk 0) propagates without calling ``close_command``. That
fix belongs in the connector repo and will be a separate PR.
- **Eager chunk-0 download in
``StreamingCloudFetchProvider::get_schema``.** The deeper design
question is whether ``get_schema`` should download chunk 0 to extract
the schema, or whether the schema can be derived from the SEA
``manifest`` alone. Lazy schema extraction would eliminate this entire
failure mode (no download until ``next_batch``). That's a larger change
worth its own PR.

This pull request and its description were written by Isaac.

## Downstream fixes / reviewer note

- 2026-06-01 close-cleanup note: Sibling note: #99 later changes
`Transport::close_statement` to surface post-retry wire errors instead
of swallowing them. This PR is still needed: it adds the missing
best-effort close call on `execute_and_read` failure paths. When
rebasing after #99, keep the cleanup behavior and explicitly log/ignore
close failures at this best-effort call site.

---------

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@msrathore-db

Copy link
Copy Markdown
Collaborator Author

Closing as superseded by #101. The #101 mega PR now contains this branch's statement lifecycle / non-blocking execute fixes in the single squashed main-based review commit.

This branch had an error being deployed

1 failed deployment
azure-prod — ae94dbe6 Deployed Jun 1, 2026 by msrathore-db via v0 E2E surface #15
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.

1 participant