Skip to content

fix(reader): cloudfetch reader nests block_on under enclosing runtime - #20

Merged
vikrantpuppala merged 2 commits into
mainfrom
fix/reader-nested-block-on
May 18, 2026
Merged

vikrantpuppala merged 2 commits into
mainfrom
fix/reader-nested-block-on

Conversation

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Fixes #19.

Summary

`CloudFetchResultReader::next_batch` (and `schema`) call `self.runtime_handle.block_on(...)` from a sync trait method. That's safe when invoked from outside any tokio runtime, but the PyO3 wrapper drives every kernel call from inside its own `runtime.block_on(...)` — the inner `block_on` is then nested under the same runtime context, and tokio panics:

```
thread '...' panicked at src/reader/mod.rs:321:29:
Cannot start a runtime from within a runtime.
```

Surfaced by the connector benchmark in databricks/databricks-sql-python#790 on `range(1000000)` — the shape that crosses the CloudFetch threshold on Dogfood. Existing kernel e2e (`multi_batch_range_succeeds` at `range(100000)`) didn't trip because that row count stays inline.

Fix

`block_on_in_runtime(handle, fut)` helper dispatches on `Handle::try_current()`:

  • Inside a runtime (the wrapper case): `tokio::task::block_in_place` + `Handle::current().block_on(fut)`. `block_in_place` tells the runtime "I'm about to block; move other tasks elsewhere," then `block_on` is safe.
  • Outside any runtime (direct Rust-crate use, e.g. the C-ABI shim's sync entry points): `block_on` the captured handle directly. `block_in_place` would panic on a current-thread runtime that some direct callers might be on.

Same pattern the kernel already uses for OAuth in `auth/oauth/m2m.rs` and `auth/oauth/u2m.rs`.

`InlineArrowReader` / `InMemoryReader` / `EmptyReader` don't touch the runtime — fix is scoped to `CloudFetchResultReader`.

Regression test

New `cloudfetch_drain_does_not_nest_block_on` in `tests/v0_execute_e2e.rs`, gated to `flavor = "multi_thread"` (matches the PyO3 wrapper's runtime shape) and to `range(1000000)` so it reliably hits CloudFetch on Dogfood. Panics without the fix; passes in ~5.7s with it.

Bench numbers post-fix

Median of 5 samples, Dogfood, via databricks-sql-python's bench script:

Shape Thrift drain Kernel drain Ratio
`range(1M)` 15.0s 7.3s 0.49× (2×!)
`range(10k)` 1.11s 1.40s 1.26×
`wide-uuid(100k)` 9.78s 9.78s 1.00×
`metadata.catalogs` 0.42s 0.55s 1.30×
`SELECT 1` 0.40s 1.08s 2.69×

The 2× speedup on `range(1M)` is the headline — CloudFetch is the shape SEA is supposed to be fastest at, and it was completely broken on the kernel path until this fix.

The ~700ms fixed TTFR overhead on `SELECT 1` is a separate finding from the bench (probably per-session tokio runtime construction) and is not addressed here.

Test plan

  • `cargo build --workspace`
  • `cargo clippy --workspace --all-targets -- -D warnings`
  • `cargo +stable fmt --all -- --check`
  • `cargo test --workspace` — full suite clean (66 tests + 4 doc tests)
  • `cargo test --test v0_execute_e2e cloudfetch_drain_does_not_nest_block_on -- --ignored` — panics before, passes after (5.7s drain of 1M rows)
  • Bench re-run on the kernel-backed connector path — `range(1M)` now drains in ~7.3s end-to-end (was a hard panic)

This pull request and its description were written by Isaac.

msrathore-db added a commit that referenced this pull request May 16, 2026
Adds an e2e regression guard for issue #19 — drains 1M rows from
inside a #[tokio::test(flavor = "multi_thread")] to verify that
the Option-1 async-trait fix in this branch doesn't regress into a
nested-block_on panic.

Adapted from PR #20 (author @vikrantpuppala) which proposed Option 2
(block_in_place + Handle::current().block_on as a stopgap). Our
branch picks Option 1 (make ResultReader trait async) per issue #19's
own "right answer" recommendation. The test is independent of the
fix mechanism — it just asserts the panic doesn't return.

#[ignore]'d by default per kernel convention for live-Databricks
e2e tests; run via:
  DATABRICKS_HOST=... DATABRICKS_HTTP_PATH=... DATABRICKS_TOKEN=... \
    cargo test --test v0_execute_e2e cloudfetch_drain_does_not_nest_block_on -- --ignored

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Comment thread src/reader/mod.rs Outdated
where
F: std::future::Future,
{
if tokio::runtime::Handle::try_current().is_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.

Handle::try_current().is_ok() is fine, but the captured runtime_handle is now unused on the inside-a-runtime branch

mod.rs:355-365:
if tokio::runtime::Handle::try_current().is_ok() {
tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(fut))
} else {
runtime_handle.block_on(fut)
}

The comment on lines 358-361 says "The captured runtime_handle and the current one are the same in practice (the kernel captures it at Session::open time)." That's true today — but the captured handle on the
inside-a-runtime branch is silently ignored, replaced by Handle::current(). If a future refactor introduces a case where the captured handle differs from the current one (e.g., a side-channel session reused
across runtimes), the behavior here diverges from what the field name "runtime_handle" suggests.

Suggestion: either:

  • (a) Use the captured handle on both branches: runtime_handle.clone() on inside-runtime, with block_in_place(|| runtime_handle.block_on(fut)). Per tokio docs, Handle::block_on is safe inside block_in_place
    — and this preserves the documented invariant that runtime_handle is the source of truth.
  • (b) Drop the runtime_handle argument entirely from this function and use Handle::current() unconditionally; keep runtime_handle only in the no-runtime branch via a different helper.

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.

Done in 1b81dc8 — the helper now uses the captured runtime_handle on both branches (block_in_place(|| runtime_handle.block_on(fut))). Per the tokio docs, Handle::block_on is safe inside block_in_place, and this honors the documented invariant that runtime_handle is the source of truth.

Comment thread src/reader/mod.rs Outdated
/// do something blocking; move other tasks to a different worker
/// thread." After that, `Handle::current().block_on(fut)` is safe
/// because the runtime considers this thread off-budget. Same
/// pattern the kernel already uses for OAuth in

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.

OAuth m2m/u2m have the less safe version of this pattern — follow-up worth filing

Verified at src/auth/oauth/m2m.rs:245-246 and src/auth/oauth/u2m.rs:296-297:

tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(async { ... })
})

Unconditional. Panics if called outside any runtime. Today that's fine because the kernel's auth flow only runs during Session::open, which is itself driven on the session runtime. But:

  • The future C ABI shim will eventually call into kernel from a non-tokio thread (it has its own process-wide runtime); the C ABI's sync entry points re-enter kernel via Handle::block_on(...) which is fine,
    but if they ever invoke an auth path without a current runtime context, m2m/u2m panic.
  • The PR's new helper is the correct version. Drift between the two patterns will bite someone.

Suggestion: file a follow-up to refactor m2m/u2m to use block_on_in_runtime (or to inline the same try_current dispatch). Not blocking this PR.

A nice next step would be to lift block_on_in_runtime to a small pub(crate) helper module (e.g. src/util/runtime.rs) so both reader and auth share 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.

Addressed in 1b81dc8 in this PR instead of as a follow-up. The helper is now at src/util/runtime.rs as pub(crate), and auth/oauth/m2m.rs and auth/oauth/u2m.rs have been migrated to use it.

The providers capture Handle::current() inside their async fn new_with_full_config (so a runtime is guaranteed at capture time) and reuse it from get_auth_header via the helper. No public-API signature changes and no test call-site cascades, which kept the diff small.

This closes the panic-outside-runtime risk you flagged for the future C ABI shim.

Fixes #19.

`CloudFetchResultReader::next_batch` (and its `schema()` sibling)
calls `self.runtime_handle.block_on(...)` from a sync trait
method. That's safe when called from outside any tokio runtime,
but the PyO3 wrapper drives every kernel call from inside its
own `runtime.block_on(...)` — the inner `block_on` is then
nested under the same runtime context, and tokio panics:

    thread '...' panicked at src/reader/mod.rs:321:29:
    Cannot start a runtime from within a runtime.

The connector's e2e tests use `range(10000)`, which is too small
to flip the server to external-links disposition, so they always
hit the in-memory `InlineArrowReader` path that never block_on's.
The bench script's `range(1000000)` shape (which crosses the
CloudFetch threshold on Dogfood) is what surfaced it.

Fix: new `block_on_in_runtime(runtime_handle, fut)` helper that
dispatches on `Handle::try_current()`. If we're already inside a
runtime, escape via `tokio::task::block_in_place` +
`Handle::current().block_on`. If we're not in a runtime (direct
Rust-crate use), `block_on` the captured handle directly —
`block_in_place` would panic on a current-thread runtime which
some direct callers might be on.

Same pattern the kernel already uses for OAuth in
`auth/oauth/m2m.rs` and `auth/oauth/u2m.rs`.

Regression test: new `cloudfetch_drain_does_not_nest_block_on` in
tests/v0_execute_e2e.rs, gated to `flavor = "multi_thread"`
(matches the PyO3 wrapper's runtime shape). The test panics
without the fix; passes with it. 1M rows drain in ~5.7s.

Bench numbers post-fix (median of 5 samples, dogfood):

| Shape           | Thrift drain | Kernel drain | Ratio       |
|-----------------|--------------|--------------|-------------|
| range(1M)       | 15.0s        | 7.3s         | 0.49× (2×!) |
| range(10k)      | 1.11s        | 1.40s        | 1.26×       |
| SELECT 1        | 0.40s        | 1.08s        | 2.69×       |

The 2× speedup on range(1M) is the headline: CloudFetch is the
shape SEA is supposed to be fastest at, and it was completely
broken on the kernel path until this. The ~700ms fixed TTFR
overhead on SELECT 1 is a separate issue (probably per-session
tokio runtime construction) and not addressed here.

cargo clippy/fmt/test workspace-wide clean.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Two follow-ups from gopalldb's review of PR 20:

1. **Use the captured `runtime_handle` on the inside-runtime branch.**
   The previous version of `block_on_in_runtime` silently substituted
   `Handle::current()` for the captured handle when called from inside
   a tokio runtime, breaking the documented invariant that the field
   is the source of truth. Per tokio docs, `Handle::block_on` is safe
   inside `block_in_place`, so honor the captured handle on both
   branches.

2. **Lift the helper to `src/util/runtime.rs` and migrate
   `auth/oauth/m2m.rs` and `auth/oauth/u2m.rs` to use it.** The OAuth
   providers previously used an unconditional
   `block_in_place + Handle::current().block_on(...)`, which would
   panic if ever invoked outside a runtime (e.g. the future C ABI
   shim's sync entry points). The shared helper dispatches on
   `Handle::try_current()` so the OAuth path is safe from both
   contexts.

The OAuth providers capture `Handle::current()` inside
`new_with_full_config` (which is `async`, so a runtime is guaranteed)
and reuse it from `get_auth_header`. No public-API signature changes;
no test call-site cascades.

Test plan:
- cargo +stable fmt --all
- cargo clippy --all-targets -- -D warnings
- cargo test — 366 unit + 4 + 11×3 + 15 integration + 6 doc-tests, all
  pass

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala force-pushed the fix/reader-nested-block-on branch from 7d07dbb to 1b81dc8 Compare May 18, 2026 05:48
@vikrantpuppala
vikrantpuppala merged commit 21ac4fb into main May 18, 2026
vikrantpuppala added a commit that referenced this pull request May 18, 2026
…dant CloseStatement (#21)

## Summary

SELECT-1 through the kernel was ~700ms TTFR vs Thrift's ~400ms. This PR
removes two avoidable sources of that fixed overhead on the
**sync-execute path** (`Statement::execute`):

1. **Drop `wait_timeout=10s`** from the request. Direct HTTP probes
showed the server's own no-timeout default already waits up to ~10s
anyway, but on a trivial query the `wait_timeout=10s` path returns
~260ms slower (~655ms vs ~397ms) — and more importantly, with
`wait_timeout` set the server returns `state=SUCCEEDED` (statement still
alive), forcing an explicit `CloseStatement` round-trip. Without it, the
server returns `state=CLOSED` for inline-result fast-path queries and
reclaims server-side resources itself.

2. **Skip `CancelStatement` + `CloseStatement` when the server already
returned `state=CLOSED`.** Plumb `server_state` through `ExecuteResult`
and share an `Arc<AtomicBool> closed` flag between `Statement` and
`ExecutedStatement`. When the server reports CLOSED in its execute
response, the flag is pre-set to `true`; explicit `close()` on either
handle, the lifecycle owner's `invalidate_prior` cleanup path, and
`Drop`'s fire-and-forget cleanup all short-circuit. (The PySQL connector
calls `Statement.close()` after every `execute()`, so without sharing
the flag the savings from #1 are immediately undone by an extra
round-trip in the lifecycle close.)

`Statement::submit` still passes `wait_timeout=0s` explicitly — that
path is defined by "return immediately with a PENDING/RUNNING
statement_id", so omitting it would change behaviour rather than just
speed it up.

## Benchmark results

`scripts/bench_kernel_vs_thrift.py` against Dogfood, median over 5
samples (warm-up dropped).

**Before this PR (`fix/reader-nested-block-on`, the PR #20 baseline this
stacks on):**

| shape | thrift TTFR | kernel TTFR | delta |
|---|---|---|---|
| SELECT 1 | 397 ms | **925 ms** | +528 ms |
| range(10k) | 1095 ms | 1186 ms | +91 ms |
| metadata.catalogs | 406 ms | 519 ms | +113 ms |

**After this PR:**

| shape | thrift TTFR | kernel TTFR | delta |
|---|---|---|---|
| SELECT 1 | 389 ms | **395 ms** | +6 ms |
| range(10k) | 1100 ms | **646 ms** | –454 ms |
| metadata.catalogs | 414 ms | 542 ms | +128 ms |

SELECT 1 is now at parity with Thrift. `range(10k)` got a much larger
lift than expected (kernel now beats Thrift) — same root cause: the
server can return inline-result + `state=CLOSED` on small results, and
both round-trips we used to fire are now redundant.

## Test plan
- [x] `cargo build && cargo clippy --all-targets -- -D warnings`
- [x] `cargo test --lib` — 366 passed
- [x] Re-benched against Dogfood — numbers in the table above
- [x] Connector e2e (kernel backend) green via
`bench_kernel_vs_thrift.py` (each cell opens a fresh connection,
executes, drains, closes — so it exercises the full statement lifecycle
including the close path)

## Stacked on
- #20 (`fix/reader-nested-block-on`)

This pull request and its description were written by Claude Code.

---------

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
msrathore-db added a commit that referenced this pull request May 20, 2026
Adds an e2e regression guard for issue #19 — drains 1M rows from
inside a #[tokio::test(flavor = "multi_thread")] to verify that
the Option-1 async-trait fix in this branch doesn't regress into a
nested-block_on panic.

Adapted from PR #20 (author @vikrantpuppala) which proposed Option 2
(block_in_place + Handle::current().block_on as a stopgap). Our
branch picks Option 1 (make ResultReader trait async) per issue #19's
own "right answer" recommendation. The test is independent of the
fix mechanism — it just asserts the panic doesn't return.

e2e tests; run via:
  DATABRICKS_HOST=... DATABRICKS_HTTP_PATH=... DATABRICKS_TOKEN=... \
    cargo test --test v0_execute_e2e cloudfetch_drain_does_not_nest_block_on -- --ignored

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
gopalldb added a commit that referenced this pull request May 21, 2026
…ning (#31)

## Summary

Implements the SHA-pinning portion of
[go/hardened-gha](https://docs.google.com/document/d/1zoHgolfZO_IUBIU3w40NmYsoZ9eTRdAmjlfwYOxkj70/edit)
and adopts the
[go/pinning-python-deps](https://docs.google.com/document/d/1thJsoOBW3NzvRV6pWpujcD8mn4KOXgAW8t10iw6Z6LA/edit)
externally-published-library guidance for the pyo3 sub-crate.

Background: per the hardened-runners policy, direct access to public
package registries (crates.io, PyPI) is blocked at the
Databricks-protected runner. Everything goes through
`databricks.jfrog.io`. This is also why repo Actions runs have been
silently 0 — workflows would have hit blocked registries even if Actions
were enabled.

## Composite action — `.github/actions/setup-jfrog`

Encapsulates the OIDC token exchange + cargo / uv index-URL writes.
Workflows that need crates.io or PyPI access call:

```yaml
- uses: ./.github/actions/setup-jfrog
  with:
    cargo: "true"  # write ~/.cargo/config.toml -> db-cargo-remote
    uv: "true"     # export UV_INDEX_URL / PIP_INDEX_URL -> db-pypi
```

Both pull from `databricks.jfrog.io` via a GitHub-OIDC-minted access
token. The composite requires `permissions: id-token: write` on the
calling job.

## Workflow updates

| Workflow | Cargo proxy | uv proxy | Notes |
|---|---|---|---|
| `pr-checks.yml` | clippy + test | — | fmt doesn't fetch deps, skipped
|
| `coverage.yml` | ✅ | — | `cargo-llvm-cov` via `taiki-e/install-action`
downloads from GitHub Releases (no registry hit) |
| `license-check.yml` | ✅ | — | for `cargo deny check` |
| `rust-e2e.yml` | ✅ | — | live workspace creds unchanged |
| `pyo3-checks.yml` | ✅ | ✅ | bootstrap shifts from `pip install
'maturin>=...' pytest` to `astral-sh/setup-uv` + `uv sync --group dev` |

All five workflows gain `permissions: id-token: write` (some already had
it from prior OIDC integrations).

## Python pinning — `pyo3/pyproject.toml`

The pyo3 wheel ships externally as `databricks-sql-kernel`. Per the
**externally-published-library** section of `go/pinning-python-deps`:

> *"Do add an upper bound on the major version of your dependencies."*
> *"Do not add exact version pins for all of your dependencies. Doing
this makes your library harder for your end users to install."*

So:
- **`[project].dependencies`** gains a major-version upper bound:
`pyarrow>=14` → `pyarrow>=14,<19`.
- **`[dependency-groups].dev`** (PEP 735) lists `maturin>=1.7,<2.0` and
`pytest>=8.3,<9.0`. uv reads this natively for `uv sync --group dev`.
- **No `uv.lock` committed**, no `--frozen` flag in CI. uv re-resolves
each run within the major-version bounds.

The `db-pypi` proxy's 7-day age filter is the baseline supply-chain
protection at the registry layer.

## CLAUDE.md

Adds a "Supply-chain hardening" section documenting:
- SHA-pinning policy (actions, cargo).
- Python dep pinning rule (published-library: major-bound, no exact
pins, no lockfile).
- How the composite works.

## Test plan

- [x] All 6 workflow files + the composite action parse as valid YAML.
- [x] No new third-party dependencies introduced beyond
`astral-sh/setup-uv` (SHA-pinned to v8.1.0).
- [ ] **Needs**: org admin to enable GitHub Actions on this repo (see
#20 comment thread — `GET /repos/.../actions/permissions` returns
`enabled: false` today). Without that, none of these workflows fire.

## References

-
[go/hardened-gha](https://docs.google.com/document/d/1zoHgolfZO_IUBIU3w40NmYsoZ9eTRdAmjlfwYOxkj70/edit)
-
[go/pinning-python-deps](https://docs.google.com/document/d/1thJsoOBW3NzvRV6pWpujcD8mn4KOXgAW8t10iw6Z6LA/edit)
- [go/pypi-registry-access,
go/crates-io-registry-access](https://docs.google.com/document/d/1hnR9y7MJZeRIqyb4ujsNjMzRFKZDZsZ2gWB8DT9XFxc/edit)

This pull request was AI-assisted by Isaac.

---------

Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
msrathore-db added a commit that referenced this pull request May 22, 2026
…on for CloudFetch drain

Addresses MEDIUM-severity findings F7 and F8 from the PR #26 review.

F7 — CI was running only `cargo clippy --all-targets -- -D warnings`
and `cargo test --workspace`, both with default features (which
resolves to `tls-native`). The downstream napi binding opts INTO
`tls-rustls`. Without a CI job for that build, a feature-gated cfg
typo or a dep update that breaks rustls compilation would only
surface when the napi crate's CI broke — long after the kernel PR
landed. Added `check-tls-rustls` job: `cargo check
--no-default-features --features tls-rustls` plus a clippy run with
the same flags, so warnings caught under tls-native stay honest
under tls-rustls and vice versa.

F8 — the existing `cloudfetch_drain_does_not_nest_block_on` test
uses `#[tokio::test(flavor = "multi_thread")]`. That flavor was
required under PR #20's Option-2 (`block_in_place` stopgap); under
Option-1 (this PR's async trait), the fix is supposed to be
runtime-flavor-independent. A future refactor that reintroduced a
sync→async `block_on` bridge protected by `block_in_place` would
still pass `multi_thread` but `current_thread` is the worst case
(`block_in_place` panics there). Added a sibling
`cloudfetch_drain_works_on_current_thread_runtime` test annotated
`flavor = "current_thread"` as the discriminating regression
guard. Both tests stay `#[ignore]` — they require a live workspace
and CloudFetch-disposition results, same as before.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
vikrantpuppala pushed a commit that referenced this pull request May 25, 2026
…tement + rustls-tls (stack 1/8) (#26)

## 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 switch via Cargo features + e2e
test ported from
[#20](#20) |
| 2/8 |
[#27](#27) |
`kernel-napi-skeleton` | napi-rs binding crate skeleton (opts INTO
`tls-rustls` feature from creation) |
| 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()` |
| 6/8 |
[#30](#30) |
`krn-connection-pool-default-bump` | Bump
`HttpConfig.pool_max_idle_per_host` default 10 → 100 |
| 7/8 |
[#24](#24) |
`krn-tls-public-api` | Expose `TlsConfig` fields (custom_ca_cert +
accept_self_signed + skip_hostname_verification) |
| 8/8 |
[#23](#23) |
`krn-status-fields` **← TIP** | Expose 5 status accessors on
`ExecutedStatement` |

**Policy:** new PRs always stack on the current tip. No sibling/parallel
topology.

---

**This PR is position 1/8 (ROOT of the kernel stack).**

## Summary

Four commits in this PR. Two kernel correctness fixes that unblock async
consumers (napi, pyo3), a Cargo-feature-based TLS backend split to
preserve ODBC compatibility, plus a regression test for the block_on
fix:

- `49ffdcb` — `fix(kernel): remove block_on from ResultStream async
public surface` (305 LOC, 7 files). The previous `ResultStream`
accessors used `tokio::block_on` internally, which panics with "Cannot
start a runtime from within a runtime" when called from inside an
enclosing tokio runtime — exactly what napi-rs's `execute_tokio_future`
and PyO3's wrapper runtime do. Fix: make the `ResultReader` trait itself
`async` via `async_trait`. **This is Option 1 in [issue
#19](#19 —
the documented "right answer" — vs the Option 2 stopgap in [PR
#20](#20).
- `622a59a` — `krn-async-public-api: make Statement::execute/submit Send
and switch to rustls-tls` (137 LOC, 2 files). Made the futures Send +
switched reqwest's TLS backend to rustls-tls.
- `7c4755a` — `test(reader): port
cloudfetch_drain_does_not_nest_block_on from PR #20`. E2e regression
test (49 LOC) drains 1M rows from inside a `#[tokio::test(flavor =
"multi_thread")]`.
- `d96afd9` — `feat(config): make TLS backend selectable via Cargo
features` (NEW). Splits the prior unconditional rustls switch into two
opt-in features:
- `default = ["tls-native"]` — direct-Rust users, C-ABI / future ODBC
path get the historical `native-tls` backend.
- `tls-rustls` — napi-rs binding crate (added in next PR in this stack)
opts in to avoid OpenSSL-symbol clash with Node.js.

## Why the TLS-feature commit was needed

`622a59a` hardcoded rustls-tls because the napi binding loaded into Node
segfaults on OpenSSL 1.1 symbol clash. But that pre-empted the choice
for ODBC consumers who historically use native-tls. The new `d96afd9`
commit makes the backend configurable so each consumer picks its own.
**Default kept as native-tls** so existing direct-Rust callers + the
C-ABI / ODBC path see no behavior change.

Verified locally:
- `cargo check -p databricks-sql-kernel` (default tls-native): clean
- `cargo check --workspace` (kernel native-tls + napi rustls-tls in same
workspace): clean
- `cargo test --lib --workspace`: **376 passed / 0 failed**

Side benefit: the pre-existing PEM flake
`test_http_client_with_invalid_pem` (D-016 in the workflow) which was
failing on the rustls-tls build now passes on native-tls. CI default is
back to a fully-green state.

## Test plan

- `cargo test` — full lib tests still green (376 passing)
- `cargo clippy --all-targets -- -D warnings` clean
- Downstream napi binding builds against this surface; M2M e2e green at
`sea-auth-u2m@e7c979d` on databricks-sql-nodejs

## Tracking

- [PECOBLR-2670](https://databricks.atlassian.net/browse/PECOBLR-2670) —
Make the async interface for rust kernel
- [PECOBLR-2917](https://databricks.atlassian.net/browse/PECOBLR-2917) —
Fix napi binding SIGSEGV on concurrent openSession
- Parent epic:
[PECOBLR-2666](https://databricks.atlassian.net/browse/PECOBLR-2666)

Co-authored-by: Isaac

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

---------

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
msrathore-db added a commit that referenced this pull request May 25, 2026
…lope + util + runtime + logger (stack 2/8) (#27)

## 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 2/8.**

## Summary

Lands the napi-rs binding crate as a workspace member with
**infrastructure only**: no exported classes yet. ~442 LOC across 10
files.

**Files added:**
- `Cargo.toml` — workspace membership declaration
- `napi/Cargo.toml`, `napi/build.rs`, `napi/package.json`,
`napi/.gitignore` — crate manifest + napi-rs build glue
- `napi/src/lib.rs` — entry point declaring 4 infra modules (no class
modules yet); exports a smoke-test `version()` fn
- `napi/src/error.rs` — formatter for the `__databricks_error__:<json>`
napi error envelope decoded by the JS-side adapter
- `napi/src/util.rs` — shared helpers
- `napi/src/runtime.rs` — tokio multi-thread runtime helper
- `napi/src/logger.rs` — `tracing`-to-JS logger bridge stub

## Compilability

`cargo check -p databricks-sea-native` is clean. The crate compiles
standalone and exposes only the `version()` probe — the JS-side loader
would find a valid `.node` but no functional API yet. This split makes
the infra layer reviewable on its own; the next PR adds the user-facing
surface.

## Tracking

- [PECOBLR-2670](https://databricks.atlassian.net/browse/PECOBLR-2670) —
Make the async interface for rust kernel — napi crate skeleton
- Parent epic:
[PECOBLR-2666](https://databricks.atlassian.net/browse/PECOBLR-2666)

Co-authored-by: Isaac

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

---------

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
vikrantpuppala pushed a commit that referenced this pull request May 26, 2026
…3/8) (#25)

## 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 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](#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](#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

- [PECOBLR-2670](https://databricks.atlassian.net/browse/PECOBLR-2670) —
Make the async interface for rust kernel — napi classes
- Parent epic:
[PECOBLR-2666](https://databricks.atlassian.net/browse/PECOBLR-2666)

Co-authored-by: Isaac

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

---------

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

kernel panics with nested block_on when called from a tokio runtime context (CloudFetch reader)

3 participants