Skip to content

feat(napi): async execute — submitStatement + AsyncStatement/AsyncResultHandle - #76

Closed
msrathore-db wants to merge 4 commits into
mainfrom
msrathore/krn-async-execute
Closed

msrathore-db wants to merge 4 commits into
mainfrom
msrathore/krn-async-execute

Conversation

@msrathore-db

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

Copy link
Copy Markdown
Collaborator

Summary

Surfaces the kernel's submit/poll/await_result path through napi as two new opaque classes plus a new method on Connection. Zero kernel-core changes — everything builds on the existing Statement::submit(), ExecutedAsyncStatement, ResultStream, and ExecutedStatementHandle trait.

New surface

  • Connection.submitStatement(sql, options?) -> AsyncStatement — calls Statement::submit() (wait_timeout=0s). Server returns immediately with a statement_id while the query is still Pending/Running. Shares ExecuteOptions (statementConf + queryTags) with the sync path.

  • AsyncStatement.status() -> string — one-shot GetStatementStatus, mapped to a JS string enum 'Pending' | 'Running' | 'Succeeded' | 'Failed' | 'Cancelled' | 'Closed' | 'Unknown'. The Unknown variant is the forward-compat arm for #[non_exhaustive] StatementStatus — a future kernel variant surfaces deterministically instead of panicking.

  • AsyncStatement.awaitResult() -> AsyncResultHandle — blocks until terminal state, returns a fetchable handle.

  • AsyncStatement.cancel() / .close() — same shape as sync Statement via shared ExecutedStatementHandle trait.

  • AsyncResultHandle.fetchNextBatch() / .schema() / .statementId — byte-identical IPC payload to sync Statement.fetchNextBatch() / .schema() for the same query. No cancel() / close() — the parent AsyncStatement owns server-side lifecycle.

Drop-cancel safety (ULTRATHINK applied)

The kernel's AwaitResultCancelGuard (src/statement/executed_async.rs:305-356) already covers the drop-cancel case: if the JS Promise's underlying tokio future is dropped mid-poll (Promise.race loser, AbortController, timeout wrapper), the kernel fires a fire-and-forget cancel_statement so the server stops charging DBUs on the orphaned query. The napi util::guarded catch_unwind covers V8 panic-across-boundary on top.

The Arc<Mutex<Option<…>>> shape matches Connection and Statement so Drop's fire-and-forget cleanup behaves consistently.

Tests

  • cargo test --lib — 35 pass (3 new F3b unit tests + 32 baseline)
  • New unit tests:
    • status_to_string covers all 6 named StatementStatus variants + the non_exhaustive Unknown arm
    • closed_err envelope shape (sentinel prefix + InvalidStatementHandle code + human message)
    • closed_err status collapses to napi InvalidArg

Stack

PR 11 of the SEA stack. Stacks on msrathore/krn-statement-options (PR #75 — F3). Corresponding NodeJS side at msrathore/sea-async-execute.

Downstream fixes / reviewer note

Test plan

  • cargo build ✓
  • cargo clippy --all-targets -- -D warnings ✓
  • cargo test --lib ✓ (35/35)
  • napi build --platform regenerates index.d.ts with new AsyncStatement / AsyncResultHandle classes + Connection.submitStatement(...) method
  • Live e2e — covered by the NodeJS PR

@msrathore-db
msrathore-db force-pushed the msrathore/krn-async-execute branch 2 times, most recently from 97c6b18 to 48e4714 Compare May 25, 2026 22:51
@msrathore-db
msrathore-db force-pushed the msrathore/krn-async-execute branch from 48e4714 to 4aab137 Compare May 25, 2026 23:05
msrathore-db added a commit that referenced this pull request May 26, 2026
…nf map

Add a Quick-reference section at the top mapping the six implementation
PRs (#74/#75/#76/#392/#393/#394) to features + test counts, plus a
Python comparison table showing how each feature maps to Python's
`use_sea=True` / `use_kernel=True` reference implementations.

Scope-down the Statement conf map + Query tags rows in Section 3 to
clarify the implementation is napi-only — the public NodeJS
`ExecuteStatementOptions` surface does not yet expose them. Wiring to
public API is a follow-up increment. Documented as Note 7. Addresses
DA's round-3 PR #77 review point on Statement conf map scope.

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

Copy link
Copy Markdown
Collaborator Author

Re-review requested — F1-F4 stack underneath this PR is now DA-approved at round-3; this PR (F3b kernel async-execute) is the next adversarial-review target.

Round-3 final tip: 4aab137f7dc81a4d455d749a6b108bd158f58f73

This PR was parked behind the F1-F4 quality bar per team-lead's hard-stop directive. With F1-F4 + matrix now in APPROVED FOR MERGE state, F3b adversarial review starts. Findings will be addressed per the same protocol (round-1 → round-2 → round-3 ground-truth verification).

Rebased on top of the F3 round-3 fmt fix (e5c53da) for clean stack hygiene.

Co-authored-by: Isaac

… + 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>
…ultHandle

Surfaces the kernel's submit/poll/await_result path through napi as
two new opaque classes plus a new method on `Connection`:

- `Connection.submitStatement(sql, options?) -> AsyncStatement` —
  calls the kernel `Statement::submit()` (wait_timeout=0s) so the
  server returns immediately with a statement_id while the query
  is still Pending/Running. Long-running queries that would blow
  past the sync `executeStatement` polling budget go through this
  path. Shares `ExecuteOptions` (statementConf + queryTags) with
  the sync path via the existing `build_merged_statement_conf`.

- `AsyncStatement.status() -> string` — one-shot
  GetStatementStatus, mapped to a JS string enum
  `'Pending' | 'Running' | 'Succeeded' | 'Failed' | 'Cancelled' |
   'Closed' | 'Unknown'`. The `Unknown` variant is a forward-compat
  arm for `#[non_exhaustive]` `StatementStatus` — a future kernel
  variant surfaces deterministically instead of panicking. The
  `Failed` variant collapses to the string; callers needing the
  typed error envelope (sql_state / error_code / query_id) get it
  via `awaitResult()`'s rejection.

- `AsyncStatement.awaitResult() -> AsyncResultHandle` — blocks
  until the server reaches a terminal state, then returns a
  fetchable handle over the materialised `ResultStream`. The
  kernel's `AwaitResultCancelGuard` already covers drop-cancel
  safety: if the JS Promise's underlying tokio future is dropped
  mid-poll (Promise.race loser, timeout wrapper, AbortController),
  the kernel fires a fire-and-forget `cancel_statement` so the
  server stops charging DBUs on the orphaned query. The
  `util::guarded` `catch_unwind` wrapper covers V8 panic-across-
  boundary on top.

- `AsyncStatement.cancel()` / `.close()` — same shape as the sync
  `Statement` methods via the shared `ExecutedStatementHandle`
  trait. Idempotent close; cancel is a no-op against a
  terminal-state server.

- `AsyncResultHandle.fetchNextBatch() -> Option<ArrowBatch>` /
  `.schema() -> ArrowSchema` — byte-identical IPC payload to the
  sync `Statement.fetchNextBatch()` / `.schema()` for the same
  query. No `cancel()` / `close()` — the parent `AsyncStatement`
  owns server-side lifecycle (avoids dual-ownership of the same
  statement_id with inconsistent close semantics).

Zero kernel-core changes — the kernel's `ExecutedAsyncStatement` +
`ResultStream` + `ExecutedStatementHandle` trait already provide
everything this napi surface needs.

Concurrency shape mirrors the sync Statement: every method takes
`inner.lock()` and holds the guard across the kernel `.await`.
tokio `Mutex` is FIFO. Cancel/close queue behind any in-flight
`awaitResult()`. The kernel covers the drop-the-future case
independently.

The IPC encoder is duplicated between `statement.rs` and
`async_statement.rs` — both call sites produce byte-identical
output, so re-emitting it is cheaper than expanding the surface of
`statement` for one re-use site. If a third caller appears, this
becomes the trigger to lift into `bindings_common`.

Tests:
- `status_to_string` covers all `StatementStatus` variants (including
  the non_exhaustive Unknown arm)
- `closed_err` envelope shape (sentinel prefix + InvalidStatementHandle
  code + human message)
- `closed_err` status collapses to napi `InvalidArg`

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db force-pushed the msrathore/krn-async-execute branch from 4aab137 to 3e784ef Compare June 1, 2026 01:14
@vikrantpuppala
vikrantpuppala changed the base branch from msrathore/krn-statement-options to main June 1, 2026 05:16
@msrathore-db

Copy link
Copy Markdown
Collaborator Author

Closing as superseded by #101, which is now the main-based kernel SEA parity mega PR for agent review. The branch is preserved and this can be reopened if we decide to return to smaller stacked reviews.

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