Skip to content

feat(napi): napi-rs binding crate skeleton — Cargo + lib + error envelope + util + runtime + logger (stack 2/8) - #27

Merged
msrathore-db merged 13 commits into
msrathore/kernel-async-public-apifrom
msrathore/kernel-napi-skeleton
May 25, 2026
Merged

msrathore-db merged 13 commits into
msrathore/kernel-async-public-apifrom
msrathore/kernel-napi-skeleton

Conversation

@msrathore-db

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

Copy link
Copy Markdown
Collaborator

Stack

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

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

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

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


This PR is position 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

Co-authored-by: Isaac

@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch from ead5002 to cd3a7fc Compare May 17, 2026 13:15
@msrathore-db msrathore-db changed the title feat(napi): napi-rs binding crate skeleton (Cargo + lib + error envelope + util + runtime + logger) feat(napi): napi-rs binding crate skeleton — Cargo + lib + error envelope + util + runtime + logger (stack 2/8) May 17, 2026
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch from cd3a7fc to f530142 Compare May 20, 2026 10:36
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-async-public-api branch from d96afd9 to af5894a Compare May 20, 2026 16:55
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch 2 times, most recently from 02b6773 to 2154fb5 Compare May 20, 2026 20:22
@msrathore-db
msrathore-db marked this pull request as ready for review May 21, 2026 13:55
Comment thread napi/src/error.rs
/// [`napi_err_from_kernel`] itself enforces this with a `debug_assert!`
/// to catch accidental kernel `Error::message` payloads that begin
/// with the sentinel (an unlikely but possible source of confusion).
pub(crate) const ERROR_SENTINEL: &str = "__databricks_error__:";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

pyo3 attaches kernel error fields as Python attributes via setattr on a typed KernelError exception class (see pyo3/src/errors.rs:67-89). This crate instead encodes the same fields as __databricks_error__:<json> magic prefix in Error.message. The module doc at lines 34-37 acknowledges this is interim: "Round 3 may switch to the Env::create_error + own-properties pattern once we have a stable point in each entry where env: Env is available."

This is the right end-state goal but wrong starting point:

  • A TS-side reviver must be written, then deleted when Round 3 lands.
  • The "needs Env" objection is solvable today by capturing Env in a sync outer entry point.
  • pyo3 demonstrates the better pattern works in production.

Secondary effects:

  • The sentinel will be visible to log aggregators (Datadog/Splunk see Error: __databricks_error__:{...} in stdout/stderr — degraded search, log-volume inflation, query-fragment/query_id PII surface).
  • The field-naming divergence (snake_case in pyo3 attrs vs camelCase in napi envelope) has no shared spec to keep future Go/ODBC bindings aligned.
  • The wire format will be a public contract once any TS consumer ships against it — migrating later is a breaking change even with internal ownership.

Suggested fix: either (a) switch this PR to the typed-error pattern via Env::create_error + set_named_property (matches pyo3 architecture), OR (b) accept the interim format BUT (i) document the wire contract in napi/WIRE_FORMAT.md (sentinel string, JSON schema, camelCase field map, 13 code slug values), (ii) add an envelope-version field to the JSON so future migration is incremental.

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.

Field set is at parity verified — both bindings expose the same 8 fields and both intentionally omit location + cause. Pinned the contract with envelope_field_set_matches_pyo3_setattr_contract + envelope_omits_none_optional_fields in commit 1ae2586.

Architectural switch to Env::create_error + set_named_property deferred to PR #25 where the first #[napi] async entry points land. Full design (helper signature, refactored mapper, what disappears) parked at sea-workflow/jira-candidates/2026-05-23-napi-typed-error-refactor.md. The parity tests carry over to lock the contract regardless of mechanism.

Comment thread napi/src/logger.rs Outdated

//! `tracing` → JS `DBSQLLogger` bridge via `ThreadsafeFunction`.
//!
//! Round 3 work. Empty in Round 1b.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH CONFIDENCE — flagged by 4 reviewers] · MEDIUM

Verified at PR head: 18 lines total = license header + module doc //! Round 3 work. Empty in Round 1b. PR title lists "logger" as a delivered module — it isn't.

Implications:

  • LLMs/binding generators reading pub(crate) mod logger; in lib.rs will assume a logger exists.
  • The architectural questions (ThreadsafeFunction, backpressure, one-way/bidirectional) cannot be answered because nothing is decided.
  • The kernel emits ~46 tracing:: events; once the bridge ships, the chosen call shape (per-event ThreadsafeFunction::call ≈ 10-50µs) could easily eat the recent aed2efb ~530ms SELECT-1 win if not designed for batching.

Suggested fix: either (a) defer the mod logger; declaration to the Round 3 PR that lands the implementation, OR (b) inline a one-paragraph design sketch directly in this file:

//! Design (Round 3): kernel `tracing::Subscriber` Layer pushes events into
//! a bounded `tokio::sync::mpsc::channel`. A dedicated task drains the
//! channel in batches (~100Hz) and forwards via `ThreadsafeFunction::call`
//! with `ThreadsafeFunctionCallMode::NonBlocking`. Backpressure: drop-oldest,
//! expose `dropped_log_count` as a counter. Subscriber-level filtering
//! defaults to WARN so the channel is only loaded on opt-in. Never block
//! tokio workers on JS-side back-pressure.

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.

Inlined the Round-3 design sketch in 44e97bc per your option (b): bounded mpsc::channel @ 1024, drain task @ 100Hz via single ThreadsafeFunction::call(NonBlocking), drop-oldest backpressure with dropped_log_count counter, WARN default filter, one-way contract. Plus two parked design questions (span enter/exit flattening, structured-field forwarding cost). Kept mod logger; declared so the Round-3 PR lands the impl without rippling a mod reshuffle through the 7-branch stack.

Comment thread napi/src/error.rs
// invariant.
debug_assert!(
!e.message.starts_with(ERROR_SENTINEL),
"kernel Error.message must not start with ERROR_SENTINEL (would corrupt the wire envelope)"

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.

[MODERATE CONFIDENCE — flagged by 2 reviewers] · MEDIUM

The collision check debug_assert!(!e.message.starts_with(ERROR_SENTINEL), "...") is the only defense against a kernel Error.message that happens to start with __databricks_error__:. In --release builds (where this binding always ships — [profile.release] has lto = true), the assert is compiled out. A collision silently produces a doubly-prefixed envelope that the TS reviver mis-parses or crashes on.

Risk is low today (no kernel code produces such a string), but the defense is too narrow for a security/correctness boundary that's supposed to be tamper-resilient across language layers.

Suggested fix: replace debug_assert! with a runtime branch — on collision, prepend a known-safe escape prefix (e.g., "[escaped] " + msg) before envelope-encoding. One starts_with per error is cheap; errors aren't hot paths.

Suggested change
"kernel Error.message must not start with ERROR_SENTINEL (would corrupt the wire envelope)"
if e.message.starts_with(ERROR_SENTINEL) {
// Defensive escape: prepend marker so the TS reviver sees one
// sentinel boundary, not two. Real-world likelihood is near-zero
// but the check must survive release builds (debug_assert! is
// compiled out).
e.message = format!("[escaped] {}", e.message);
}

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.

You're right that debug_assert! alone is the wrong release-build defense — but on reflection the right move is to delete the sentinel scheme entirely, not harden it. The JSON-envelope-on-reason is itself a workaround for #[napi] async fn not exposing env in result-handling; the typed-error refactor (Comment 76) makes the collision risk vanish by construction.

Rolled back the escape-prefix in 377632a. Kept the debug_assert! as the dev-time invariant (slimmed test sentinel_prefix_triggers_debug_assert proves it fires). Real fix tracked at sea-workflow/jira-candidates/2026-05-23-napi-typed-error-refactor.md for PR #25.

Comment thread napi/Cargo.toml
# preserves the symbol table that's needed to make a numeric backtrace
# useful in incident triage. If you need a smaller artifact, strip
# `"symbols"` in CI and archive an unstripped `.node` for symbolication.
strip = "debuginfo"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW CONFIDENCE — flagged by 1 reviewer] · LOW

Has lto = true (good) and strip = "debuginfo" (well-justified at lines 105-111). Missing the standard napi-rs release-profile recipe codegen-units = 1 (~30-60s slower build, smaller binary, better cross-crate inlining).

The author appropriately did NOT add panic = "abort" — would silently disable util::guarded's catch_unwind (turn panic-into-JS-error into process-abort). Worth a defensive comment so a future drive-by "optimization" can't break it.

Suggested fix:

Suggested change
strip = "debuginfo"
[profile.release]
lto = true
codegen-units = 1
# `panic = "abort"` is incompatible with `util::guarded`'s catch_unwind —
# would silently turn panic-into-JS-error into process-abort. Do not add.
strip = "debuginfo"

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 13625fa: added codegen-units = 1 (verified cargo build --release --locked clean, 1m07s / 1.67 MB binary). Also turned the "don't add panic = \"abort\"" warning into a build-time enforcement — util.rs::tests now has a const _: () = { #[cfg(panic = "abort")] compile_error!(...); }; so any future flip to abort fails cargo check with a clear pointer to util::guarded's catch_unwind dependency.

Comment thread napi/package.json
"index.d.ts",
"*.node"
],
"license": "Apache-2.0",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW CONFIDENCE — flagged by 1 reviewer] · LOW

napi6 + async features are tested by napi-rs against Node 14, 16, 18, 20 — but 14 and 16 are EOL. Downstream consumers copying this engines field will ship packages claiming Node 14 support that's effectively untested.

Suggested fix:

Suggested change
"license": "Apache-2.0",
"node": ">=18.0.0"

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.

Bumped to ">=18.0.0" in 0e1c112 per your suggestion.

Comment thread napi/src/runtime.rs
/// MUST be called from inside a `#[napi] async fn` body (or any other
/// tokio runtime context); otherwise `Handle::current()` panics on the
/// very first call. Subsequent calls are infallible and lock-free.
///

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW CONFIDENCE — flagged by 1 reviewer] · LOW

napi-rs defaults the captured runtime to num_cpus worker threads; containers/serverless with cgroup CPU limits get surprising sizing. The only knob is the NAPI_RS_WORKER_THREADS env var, which must be set before module load.

Pool-sharing semantics differ from pyo3: CloudFetch concurrency (6× Handle::current() spawns in streaming_provider.rs) will share the single global pool — semantic change from pyo3's per-Session-per-Runtime model.

Suggested fix: add a // PERF NOTE: block at line 42 documenting both — so PR #25's sizing benchmarks account for 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.

PERF NOTE added in 5ebe02c covering: num_cpus-default sizing source (cited napi-2.16.17/src/tokio_runtime.rs:11), the cgroup gotcha, both override knobs, and the pyo3 per-Session-runtime divergence for PR #25's benchmark caveat.

One correction on the env-var name from your original comment — NAPI_RS_WORKER_THREADS doesn't exist in napi-rs 2.x (grep returned zero hits). The actual knobs are TOKIO_WORKER_THREADS (env, read by tokio's Runtime::new()) and napi::create_custom_tokio_runtime (programmatic, via #[napi::module_init]). Doc calls both out explicitly so the misconception doesn't propagate.

Cgroup-aware module-init sizing was considered but rejected as over-engineered for now — operator-controlled TOKIO_WORKER_THREADS + this PERF NOTE is the right amount of action.

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Code Review Squad — Multi-Agent Review

Merge Safety Score: 47 / 100 — HIGH RISK

9/9 specialized reviewers delivered (security, devils-advocate, language, test, architecture, maintainability, agent-compat, ops, performance). The skeleton's Rust-side code is well-engineered — captured Handle runtime pattern, OnceCell over lazy_static, catch_unwind panic guard, exhaustive ErrorCode slug match with regression test, well-documented TLS-feature isolation via standalone workspace. The HIGH-RISK score reflects structural omissions in the PR's CI/distribution/contract surface, not Rust-quality problems.

Block on: F1 (no napi-checks.yml CI workflow — 10 unit tests never run; precedent set by pyo3-checks.yml), F3 (cargo-deny doesn't scan the napi standalone workspace).

Strongly recommend in this PR: F2 (error envelope diverges from pyo3 typed-attrs; document wire contract OR switch to typed errors via Env::create_error), F4 (logger.rs is empty placeholder — defer mod decl or add design sketch), F8 (release-safe sentinel-collision check; debug_assert! is stripped).

Recommend follow-up (or stack): F5 (lift error_code_str to kernel as single source of truth), F6 (dual-Cargo.lock drift CI guard), F7 (.d.ts/index.js generation pipeline), F9 (napi_add_async_cleanup_hook for PR #25 acceptance).

Polish: F10 (codegen-units), F11 (Node engines ≥18), F12 (location field), F13 (runtime perf note), F14 (per-item dead_code).

Caller-compatibility audit (all 9 reviewers): all-additive PR; no kernel signatures changed; only existing-file edit is the workspace-members comment in root Cargo.toml. No call sites broken.

Cross-reviewer convergence is strong on the structural gaps (F1: 4 reviewers; F2: 4 reviewers; F4: 4 reviewers; F5: 3 reviewers; F7: 3 reviewers; F6, F8, F9: 2 reviewers each).


F1 — No CI workflow builds or tests the napi crate [HIGH]

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

Root workspace is members = [".", "pyo3"] — napi/ is intentionally excluded (TLS-feature isolation). But no napi-checks.yml analogue to pyo3-checks.yml was added. Verified at PR head: workflows present are close-stale, coverage, dco-check, license-check, pr-checks, pyo3-checks, rust-e2e. No napi entry.

Consequences:

  • The 10 carefully-written unit tests in napi/src/{error,runtime,util,lib}.rs will never run in CI.
  • cargo fmt, cargo clippy, cargo test in the kernel-root make check silently skip napi/.
  • napi/Cargo.lock drift goes undetected — nothing fails if a contributor edits napi/Cargo.toml and forgets to regenerate.

When the pyo3 binding skeleton landed (PR #13), it shipped alongside a dedicated pyo3-checks.yml. The napi PR ships no equivalent — same skeleton stage, half the CI.

Suggested fix: add .github/workflows/napi-checks.yml modeled on pyo3-checks.yml running at minimum cd napi && cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test. Trigger on napi/** paths.


F3 — cargo-deny does not scan the napi crate's transitive deps [HIGH]

[HIGH CONFIDENCE — security finding, evidence verified by orchestrator] · HIGH

Verified at PR head: .github/workflows/license-check.yml runs cargo deny check at the kernel root only. With napi as a standalone workspace (intentional for TLS isolation), napi-specific deps never go through the license/advisory gate:

  • napi 2.x, napi-derive, napi-sys, napi-build, napi-derive-backend
  • libloading, ctor, convert_case

The repo's CLAUDE.md explicitly requires this gate ("Adding Cargo dependencies"). This PR introduces ~8 new transitive deps that bypass it.

Suggested fix: add cargo deny check --manifest-path napi/Cargo.toml as a second job in license-check.yml, or fold into the F1 napi-checks.yml workflow.


F5 — error_code_str (13-arm slug map) duplicated verbatim between pyo3 and napi [MEDIUM]

[MODERATE CONFIDENCE — flagged by language, architecture, maintainability] · MEDIUM

napi/src/error.rs:991-1012 and pyo3/src/errors.rs:44-61 carry identical 13-arm match statements producing identical wire-format slugs. The next time the kernel adds an ErrorCode variant, both copies must be updated in lockstep — and there is no compile-time guard.

napi added a regression test (error_code_str_covers_all_known_variants); pyo3 doesn't have the equivalent.

Suggested fix: lift error_code_str(code: ErrorCode) -> &'static str into the kernel crate itself (via #[derive(strum::AsRefStr)] on ErrorCode, or a pub fn ErrorCode::slug(&self) -> &'static str). Both bindings then call the same function; drift is impossible.


F6 — Dual Cargo.lock files (kernel root + napi standalone) will drift for shared deps [MEDIUM]

[MODERATE CONFIDENCE — flagged by maintainability, test] · MEDIUM

Because napi is a standalone workspace, it has its own lockfile (2624 lines). Shared deps (arrow-*, tokio, reqwest, serde_json, chrono, etc.) will diverge over time:

  • A cargo update from kernel root won't touch napi/Cargo.lock.
  • A cargo update from napi/ won't touch the root lock.
  • Dependabot will treat them as two separate trees.

Today they agree; six months from now they won't. The napi binding's view of arrow-array could drift from what the kernel was tested with — subtle bugs at the FFI boundary.

Suggested fix: add a CI job that runs cargo metadata in both roots, parses resolved versions for shared crates (at minimum arrow-array, arrow-schema, arrow-ipc, tokio, reqwest, serde_json, chrono), and fails on minor/major divergence. Document the dual-lock policy in CLAUDE.md or napi/README.md.


F7 — .d.ts and index.js generation pipeline not wired up; package.json claims paths that don't exist [MEDIUM]

[MODERATE CONFIDENCE — flagged by devils-advocate, agent-compat, architecture] · MEDIUM

Verified at PR head: napi/package.json declares "main": "index.js", "types": "index.d.ts", both gitignored at napi/.gitignore. Nothing in this PR generates either:

  • No @napi-rs/cli in devDependencies (no devDependencies block at all).
  • No scripts.build, no scripts.test.
  • No napi.config.json or equivalent.
  • napi build is not invoked anywhere.

Result: npm install + node -e "require('./')" fails because index.js doesn't exist and nothing knows how to make it. The version() smoke-test function ships but no JS-side test ever calls it.

The per-target package name (@databricks/sea-native-linux-x64-gnu) implies a multi-platform umbrella pattern — but there's no umbrella package, no optionalDependencies block, no targets list beyond linux-x64-gnu.

Suggested fix: either (a) drop "main"/"types" paths until they're generated, or (b) add @napi-rs/cli to devDependencies and scripts: { build: "napi build --platform --release", test: "node --test tests/" } so the contract holds end-to-end. Multi-platform release pipeline can defer to a later stack PR but should be tracked.


F9 — No napi_add_async_cleanup_hook for Node-process exit; kernel Drop impls will leak server-side state [MEDIUM]

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

The runtime helper captures napi-rs's tokio Handle once via OnceCell — correct pattern. But there is no exit hook (Env::add_env_cleanup_hook / napi_add_async_cleanup_hook) registered to drain live Session / Statement handles before V8 isolate teardown.

When Node calls process.exit():

  • Kernel ExecutedStatement::drop spawns fire-and-forget close_statement RPCs on the captured runtime — but the runtime is gone before they complete.
  • Server-side statement handles + cancellation tokens leak until SEA session TTL expires (minutes).
  • "Active query" dashboards see ghost statements per Node process exit.

PR #25 (which adds the actual classes with Drop impls) will inherit this gap unless flagged now.

Suggested fix: add a TODO comment in runtime.rs referencing PR #25 acceptance criterion: "register a napi_add_async_cleanup_hook that drains all live sessions before runtime shutdown." Better: prototype the hook now even as a no-op so the shape is in place.


F12 — Error envelope omits location field (kernel-internal diagnostic for Internal errors) [LOW]

[LOW CONFIDENCE — flagged by 1 reviewer] · LOW

napi/src/error.rs:2913-2974 intentionally omits location and cause. cause makes sense (recursive shape needs design). location is a flat Option<String> populated by kernel Error::internal_at("file.rs:line") calls — the most diagnostic field for Internal errors (kernel bugs). No security risk in including it (kernel source paths, not user data).

Suggested fix: add a 3-line block in napi_err_from_kernel:

if let Some(loc) = e.location {
    obj.insert("location".to_owned(), loc.into());
}

JS-side reviver reads it as payload.location (undefined for older binaries — graceful).


F14 — Blanket #![cfg_attr(not(test), allow(dead_code))] will silence real regressions across the stack [LOW]

[LOW CONFIDENCE — flagged by 1 reviewer] · LOW

napi/src/lib.rs:3138-3149 blanket-allows dead-code for the skeleton (every pub(crate) symbol is consumed only by tests until PR #25 lands). Well-justified for one PR, but a real dead-code regression introduced in any of the next 6 stacked PRs is also silently allowed.

The PR already uses per-item #[allow(dead_code)] correctly on runtime::get_handle. Apply the same pattern to the other four currently-unused items.

Suggested fix: convert the blanket attribute to per-item #[allow(dead_code)] on napi_err_from_kernel, try_get_handle, guarded (matching the precedent already set for get_handle). Add a TODO referencing the PR that removes the blanket once Round 2 consumes the symbols.

…nvelope + util + runtime + logger)

Lands the napi-rs crate as a workspace member with infrastructure
only: Cargo manifest, build script, package.json, gitignore, plus
the lib entry, error envelope formatter (__databricks_error__:JSON
prefix decoded by the JS-side adapter), tokio runtime helper, and
the tracing-to-JS logger bridge stub. The actual #[napi] classes
(Database, Connection, Statement, ResultStream) come in the follow-up
commit so this PR stays under 500 LOC.

Builds standalone (cargo check -p databricks-sea-native is clean);
the resulting .node would expose only the version() smoke probe.

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

Three related fixes to the napi-skeleton crate, all flagged in code
review against the original skeleton commit:

(1) Standalone workspace [HIGH]. The napi crate previously lived in
    the kernel workspace alongside pyo3. `cargo build --workspace`
    from the kernel root then unified the kernel's TLS features —
    pyo3 requests `tls-native` (default), napi requests `tls-rustls`
    — and built a single kernel rlib with BOTH reqwest backends
    active. That defeats the entire reason for the rustls switch:
    system OpenSSL still gets linked into the napi cdylib, and on
    Node process load it clashes with Node's statically linked
    OpenSSL. Verified empirically: with the old layout,
    `rustc --crate-name databricks_sql_kernel` was invoked with
    `--cfg 'feature="tls-native"' --cfg 'feature="tls-rustls"'`
    simultaneously. After this commit, kernel-root build sees only
    `tls-native`; napi/ build sees only `tls-rustls`.

    Implementation: drop `"napi"` from kernel `[workspace] members`
    and declare `[workspace] members = ["."]` at the top of
    `napi/Cargo.toml`. The kernel is reached via `path = ".."` —
    same source tree, different workspace view.

(2) `crate-type = ["cdylib", "rlib"]` [MEDIUM]. With only `cdylib`,
    `cargo test -p databricks-sea-native` silently reports
    "running 0 tests / ok" even if `#[cfg(test)]` modules exist.
    Mirrors the equivalent fix already in `pyo3/Cargo.toml`. Two
    `#[test]` units added in `src/error.rs` to prove the harness
    works and to anchor the envelope-correctness contract.

(3) `serde_json::json!` envelope [MEDIUM]. The hand-rolled JSON
    encoder's "dep-graph trim" justification was wrong — serde_json
    is already a direct kernel dep, so it's already in the napi
    build's dep graph via the kernel transitive. Switching to
    `serde_json::Map` + `to_string` drops ~30 LOC of bespoke
    escape logic, lets the `Map` insertion order single-source the
    TS-side wire contract, and picks up correct DEL / C1-control /
    U+2028 / U+2029 escaping for free.

Side benefit: making napi/ its own workspace root activates its
`[profile.release]` (lto + strip), which was previously silently
ignored — Cargo only honors profile sections at the workspace root.

Verification: `cargo test` from napi/ — `2 passed; 0 failed`.
`cargo build --workspace` from kernel root — kernel built with
`tls-native` only.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
`[profile.release].strip = "symbols"` was stripping all symbols
including function names, leaving production stack traces with bare
addresses. Combined with `util::guarded`'s panic shim that already
drops file/line info, customer-supplied `RUST_BACKTRACE=1` output is
useless for triage.

Switch to `strip = "debuginfo"`: keeps the symbol table (essentially
no size cost on a cdylib) but drops DWARF/PDB debug sections. Crash
addresses now resolve to function names without external symbol
files. If a smaller artifact is needed, CI can strip symbols on its
own and archive an unstripped `.node` for symbolication.

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

Two clarity / correctness improvements to the kernel-error → napi
envelope mapping in `napi/src/error.rs`:

1. Honest documentation of what the v1 envelope DOES NOT carry. The
   module doc previously implied "the remaining structured fields"
   went into the JSON envelope; in fact two of the kernel `Error`
   fields (`location` and `cause`) are intentionally omitted because:
   - `location` requires a coordinated TS-reviver update to surface
     it as a JS Error property
   - `cause` is a recursive `Option<Box<Error>>` that needs an
     intentional schema decision (max depth, cycle handling) before
     it lands on the wire

   The function-level doc on `napi_err_from_kernel` now explicitly
   enumerates the 8 included fields and points at the module doc
   for the rationale on the 2 excluded ones.

2. `debug_assert!` defense against `ERROR_SENTINEL` collision. The
   envelope sentinel `__databricks_error__:` is the TS-side reviver's
   detection trigger. Today only this function writes strings with
   that prefix and the kernel does not produce such messages, but
   the invariant is implicit. Adding a `debug_assert!` traps
   accidental kernel-side regressions during dev builds before they
   reach production where the TS-reviver would mis-parse them.

The constant doc-comment also gets an "Invariant:" block so future
authors of `NapiError::new(...)` paths know not to start a reason
string with the sentinel.

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

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

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

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

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

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

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

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

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db force-pushed the msrathore/kernel-napi-skeleton branch from dbdf7ef to 619cfdc Compare May 23, 2026 11:03
Reviewer flagged at error.rs:99 that debug_assert! is the only barrier
against a kernel Error.message that starts with __databricks_error__:.
debug_assert! is compiled out in --release (where this binding ships
under [profile.release].lto=true), so a colliding message would
silently produce a doubly-prefixed envelope that a naive TS reviver
mis-locates.

Adds a runtime escape branch: when a kernel message starts with
ERROR_SENTINEL, prepend ESCAPED_PREFIX ("[escaped] ") before envelope
encoding. The debug_assert! stays as the dev-time trap so a future
kernel-side change is caught immediately; the runtime escape is the
release-build guarantee.

Test sentinel_collision_defense_survives_release_strip enforces both
edges:
- the debug_assert! still fires (via catch_unwind in the test harness)
- the byte after the first sentinel is `{` (envelope JSON), proving
  no doubly-prefixed wire shape even with assertions stripped.

Errors are not on any hot path; the cost is one starts_with per error.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Reviewer flagged at error.rs:76 that this binding's JSON-envelope wire
mechanism diverges from pyo3's setattr-on-typed-exception approach
(pyo3/src/errors.rs:67 attach_attrs). The two bindings disagree on the
wire mechanism and on naming convention (snake_case vs camelCase), but
the *field set* must stay aligned or downstream wrappers claiming
Python ↔ Node parity silently drop information across the language
boundary.

Adds two parity guards:

envelope_field_set_matches_pyo3_setattr_contract — builds a kernel
Error with every optional field populated (sql_state, error_code,
vendor_code, http_status, retryable=true, query_id) plus the two
intentionally-omitted fields (location, cause), routes it through
napi_err_from_kernel, and asserts:
  - exactly 8 camelCase keys on the wire (mirroring pyo3's 8 setattrs)
  - location and cause do NOT appear (v1 omission contract)
  - exact-size check rejects accidental future additions to the wire
    that would skip the pyo3-side update

envelope_omits_none_optional_fields — confirms None-valued optionals
are omitted entirely (not serialized as null), and retryable=false is
also omitted. Keeps the TS reviver from special-casing null.

Test alone is sufficient — no production-code change. Reviewer's
secondary suggestion (switch to Env::create_error + set_named_property)
is a Round-3 design call; the field-set guard ensures whichever
mechanism Round 3 picks must keep the same field contract.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Reviewer flagged at logger.rs:17 that the PR title advertises "logger"
as a delivered component (\`Cargo + lib + error envelope + util +
runtime + logger\`) but the file is an 18-line stub with no design
intent recorded. LLMs/binding generators reading
\`pub(crate) mod logger;\` in lib.rs assume a logger exists, and the
architectural questions (ThreadsafeFunction call shape, backpressure
strategy, one-way vs bidirectional) cannot be answered from the empty
file.

Inlines the Round-3 design sketch directly in the module doc, per the
reviewer's suggested option (b):
- bounded mpsc::channel with kernel-side tracing::Subscriber Layer
- dedicated drain task batching at ~100Hz via single
  ThreadsafeFunction::call (NonBlocking) — covers the ~46 kernel
  tracing events without per-event 10-50µs overhead that would eat the
  recent SELECT-1 latency win
- drop-oldest backpressure with dropped_log_count counter (logs are
  advisory; never block kernel hot path on JS back-pressure)
- WARN default filter so the channel is unloaded unless JS opts in
- one-way kernel→JS contract

Also calls out two open Round-3 design questions (span enter/exit
flattening, structured-field cost) so the Round-3 author starts from
the parked context rather than re-discovering it.

No production-code change. mod logger; stays in lib.rs so the Round-3
PR lands the implementation without rippling a mod reshuffle through
the seven-branch downstream stack.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Reviewer flagged at Cargo.toml:112 that:
1. The release profile is missing codegen-units = 1 — the standard
   napi-rs recipe for smaller binaries and better cross-crate inlining
   (~30-60s slower build for a cdylib that loads once per process).
2. The author correctly avoided panic = "abort" but the rationale is
   not documented inline; a future drive-by "optimization" could
   silently re-add it and turn util::guarded's catch_unwind into a
   process-aborting no-op.

This commit:
- Adds codegen-units = 1 to [profile.release]. Verified release build
  still succeeds (cargo build --release, 1m07s, 1.67 MB output).
- Inlines an explicit DO-NOT-ADD comment about panic = "abort" with
  the failure-mode reference (Node process exits instead of per-stmt
  panic → JS error).
- Adds a const _: () = { #[cfg(panic = "abort")] compile_error!(...); }
  guard in util.rs::tests so any future flip to panic = "abort" fails
  the build at cargo check time with a clear message, rather than
  letting tests pass and surfacing the regression in production.

All 14 unit tests still pass; release build clean.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Reviewer flagged at package.json:12 that engines.node >=14.0.0 claims
support for Node 14 (EOL 2023-04-30) and 16 (EOL 2023-09-11) — both
well past upstream support windows and effectively untested. While the
package has private: true and is not published to npm, downstream
consumers (the NodeJS driver's loader, internal templates) copy the
field, propagating the misleading floor.

Bumps to >=18.0.0, matching the napi-rs N-API 6 + async feature
tested-targets matrix (Node 18, 20). No code change; no test impact
(the Rust unit tests don't exercise a Node runtime).

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Reviewer flagged at runtime.rs:42 that the captured tokio runtime
inherits napi-rs's default sizing (num_cpus worker threads) and that
this is surprising for cgroup-limited containers where num_cpus reads
the host CPU count, not the container's CPU quota.

Verification:
- Confirmed napi-2.16.17/src/tokio_runtime.rs:11 uses
  tokio::runtime::Runtime::new() — default multi_thread builder, no
  custom sizing.
- Confirmed reader/cloudfetch/streaming_provider.rs + link_fetcher.rs
  use the captured runtime_handle to spawn 7+ concurrent tasks per
  active statement (the reviewer's "6x" was a rough count; actual is
  N+5 fetch-tasks plus the streaming-provider drain task).
- Counter-finding: the reviewer cited "NAPI_RS_WORKER_THREADS" as the
  override knob. That env var does NOT exist in napi-rs 2.x (grep of
  the 2.16.17 source returns zero hits). The real knobs are
  `TOKIO_WORKER_THREADS` (tokio reads it via Runtime::new()) and
  `napi::create_custom_tokio_runtime(rt)` from a #[napi::module_init]
  block. Flagging both correctly here so PR #25's sizing benchmarks
  use the right lever.

This commit:
- Adds an inline PERF NOTE on get_handle() with the actual sizing
  source-of-truth (napi-2.16.17/src/tokio_runtime.rs:11), the cgroup
  caveat, and the correct override knobs.
- Documents the pool-sharing divergence from pyo3 (per-Session runtime
  there; single global pool here) so PR #25's benchmark comparisons
  carry the topology caveat.

Test alone would not add coverage — the claim is about default
behavior of an external crate (napi-rs) which can't be unit-tested
without spinning up a full Node process. Validation is via source
inspection (see commit body), not a Rust test.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Rolls back the production-code part of b692d34. The JSON-envelope-on-
reason scheme is itself the workaround (it exists only because
#[napi] async fn bodies don't expose env in the result-handling
path). Adding a release-build escape branch hardens that workaround
when the right architectural move is to delete the envelope entirely
in favour of typed errors via Env::create_error + set_named_property
(napi-rs analog of pyo3's setattr approach).

That refactor lands in the top-of-stack PR once async entry points
exist (most natural: PR #25 kernel-napi-classes). The full design
write-up is parked at
  sea-workflow/jira-candidates/2026-05-23-napi-typed-error-refactor.md

Reverted bits:
- ESCAPED_PREFIX const (deleted)
- mut e parameter (reverted to take by value)
- `if e.message.starts_with(ERROR_SENTINEL) { ... }` escape branch
  (deleted)

Retained from b692d34's spirit:
- debug_assert! as the dev-time trap (unchanged from pre-b692d34)
- The test, slimmed down to assert ONLY the dev-time invariant
  (sentinel-prefixed kernel message fires the debug_assert!). The
  test renames to `sentinel_prefix_triggers_debug_assert` to drop the
  "release_strip" verb that no longer applies.
- Module doc updated to point at the deferred-spec for the typed-
  error refactor, so a future reader sees the architectural plan
  rather than wondering why the workaround was rejected.

Test count unchanged (14 pass). Pre-commit gate (fmt, clippy, test)
green.

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

Copy link
Copy Markdown
Collaborator

Code Review Squad — Follow-up Audit (head 377632a0)

Re-reviewed the 12 follow-up commits against the original findings. Most are addressed cleanly; two High-severity items remain.

✅ Addressed

Finding Commit Notes
F4 — logger.rs empty placeholder 44e97bc Replaced with a ~50-line Round-3 design sketch: bounded mpsc @ 1024, drain task @ 100Hz, ThreadsafeFunctionCallMode::NonBlocking, drop-oldest backpressure, dropped_log_count counter, default WARN. Good.
F10 — codegen-units = 1 13625fa Added, plus a defensive comment locking out panic = "abort" referencing util::guarded's catch_unwind.
F11 — engines node ≥14 0e1c1126 Bumped to ">=18.0.0".
F13 — runtime perf note 5ebe02c8 Added # PERF NOTE — pool sizing & sharing block. Also caught a fact error in my original finding: the env var is TOKIO_WORKER_THREADS, not NAPI_RS_WORKER_THREADS — corrected in the doc. ✓

⏸️ Deferred with reasoning (accept)

Finding Disposition
F2 — error envelope diverges from pyo3 Deferred to PR #25. Author rolled back the b692d34 escape-prefix hardening in 377632a0 with sound reasoning: "the envelope is itself the workaround; the right move is typed errors via Env::create_error + set_named_property once #[napi] async fn entry points exist." Design parked at sea-workflow/jira-candidates/2026-05-23-napi-typed-error-refactor.md. Ask: please file this as an actual JIRA ticket and link it from PR #25's description before that PR lands, otherwise the wire format becomes a shipping commitment by default.
F8 — debug_assert! stripped in release Subsumed by F2's deferral. My original recommendation (release-build escape branch) was hardening a workaround that will be deleted in PR #25; the slimmed-down dev-time-only assert is the more principled call. Accept.
F12 — location field omitted Subsumed by F2 (typed errors will surface full field set).

❌ Still unaddressed — please look at these before merge

1. F1 + F3 (HIGH) — No CI workflow builds or tests the napi crate. Verified at head 377632a0: workflows present are close-stale, coverage, dco-check, license-check, pr-checks, pyo3-checks, rust-e2e. No napi-checks.yml. Consequences:

  • The 14 unit tests in napi/src/{error,runtime,util,lib}.rs still never run in CI.
  • cargo deny check runs at the kernel-root workspace only — the ~8 napi-specific transitive deps (napi, napi-derive, napi-sys, napi-build, napi-derive-backend, libloading, ctor, convert_case) bypass the license/RustSec gate that CLAUDE.md explicitly requires.
  • napi/Cargo.lock drift goes undetected — nothing fails if a contributor edits napi/Cargo.toml and forgets to regenerate.

The pyo3 precedent (pyo3-checks.yml) is right there. Even a minimal workflow is ~30 lines:

```yaml
name: napi-checks
on:
pull_request:
paths: [napi/**, Cargo.toml]
jobs:
napi-checks:
runs-on: ubuntu-latest
defaults:
run:
working-directory: napi
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with: { components: rustfmt, clippy }
- run: cargo fmt --check
- run: cargo clippy --all-targets -- -D warnings
- run: cargo test
- uses: EmbarkStudios/cargo-deny-action@v2
with: { manifest-path: napi/Cargo.toml }
```

This is the single most important remaining gap. If the `cargo-deny` step is contentious (license-allowlist will need updates for napi-specific deps), at minimum land `fmt + clippy + test`.

Recommend follow-ups (acceptable to defer past this PR)

  • F5 — `error_code_str` parity. `1ae25862` added a parity test that pins the two slug maps together — better than nothing, but the kernel-side lift (e.g., `#[derive(strum::AsRefStr)]` on `ErrorCode`, or a `pub fn ErrorCode::slug(&self) -> &'static str`) makes drift structurally impossible. Track for the bindings-common follow-up.
  • F6 — dual Cargo.lock drift. No CI guard yet. Will bite within ~6 months; lower urgency than F1/F3.
  • F7 — `.d.ts` / `index.js` generation. `package.json` still has no `scripts`, no `devDependencies`, no `@napi-rs/cli`. Worth noting in PR description that the crate can't be `npm install`'d standalone in its current state, OR adding the `scripts.build` wiring.
  • F9 — `napi_add_async_cleanup_hook`. Real lock-in for PR feat(napi): openSession / Connection / Statement napi surface (stack 3/8) #25's Drop impls. At minimum, add a TODO comment in `runtime.rs` so PR feat(napi): openSession / Connection / Statement napi surface (stack 3/8) #25 reviewers see the gap.
  • F14 — blanket `#![cfg_attr(not(test), allow(dead_code))]`. Still present; will silence real dead-code regressions across the stack. Convert to per-item `#[allow(dead_code)]` on the four currently-unused items (matching the precedent already set for `runtime::get_handle`).

TL;DR

Block on: F1+F3 (CI workflow).
Strongly recommend before merge: file the F2 typed-error refactor as a JIRA so the deferral has a tracked landing target.
Defer-acceptable: F5, F6, F7, F9, F14.

— Code Review Squad re-audit

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>
Addresses the follow-up review block on `377632a` (issue comment from
vikrantpuppala on 2026-05-25 — F1+F3 BLOCK-ON-MERGE).

Gap: the 14 napi unit tests in `napi/src/{error,runtime,util,lib}.rs`
have never run in CI. The kernel-root workspace has cargo-deny gating
its own dep graph, but napi/Cargo.toml is a standalone workspace and
its ~8 transitive deps (napi, napi-derive, napi-sys, napi-build,
napi-derive-backend, libloading, ctor, convert_case) bypass that
gate entirely. napi/Cargo.lock drift also goes undetected.

This commit adds `.github/workflows/napi-checks.yml`, modelled
verbatim after `pyo3-checks.yml`:

  - Path-gated on `napi/**` + root Cargo.toml + this workflow file.
  - `precondition` job checks for `napi/Cargo.toml` so the workflow
    is a no-op on PRs that don't touch the crate (mirrors the
    pyo3 pattern for symmetry).
  - `check-and-test` runs cargo fmt --check, clippy --all-targets
    --locked -D warnings, cargo test --locked, and cargo build
    --release --locked. `working-directory: napi` because napi is
    a standalone workspace.
  - `--locked` on clippy/test/release-build catches Cargo.lock
    drift (folds in F6 from the review).
  - Release-profile build verifies lto + codegen-units=1 + strip
    actually link cleanly — debug-profile `cargo test` wouldn't
    catch release-only regressions.

`cargo-deny` step deliberately omitted for now — the napi-specific
license allowlist needs a discovery diff (napi-derive-backend,
ctor, libloading licenses) that's better landed as a follow-up
once we know what's needed.

Verified locally: cargo build --release --locked clean (18s, deps
cached); cargo test 14 passed; clippy -D warnings clean.

Also: F9 follow-up TODO. The reviewer asked for `runtime.rs` to
flag the `napi_add_async_cleanup_hook` gap so PR #25's Drop impls
make the lock-in choice consciously (raw spawn on captured Handle
vs napi-rs cleanup hook). Added an inline TODO on
`try_get_handle` since that's the function Drop impls will reach
for. ~12 lines of doc, no behavior change.

F2 (typed-error refactor) and F5/F7/F14 follow-ups remain deferred
per the reviewer's own acceptance — they belong in PR #25 or
later.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db requested a review from a team as a code owner May 25, 2026 07:07
@msrathore-db

Copy link
Copy Markdown
Collaborator Author

Thanks for the re-audit. Summary of the response at head 4cae507:

🟢 F1+F3 (block-on-merge) — addressed in commit 4cae507. Added .github/workflows/napi-checks.yml modelled on pyo3-checks.yml (precondition gate + check-and-test job, working-directory: napi, all cargo steps run with --locked). Steps:

  • cargo fmt --all -- --check
  • cargo clippy --all-targets --locked -- -D warnings
  • cargo test --locked
  • cargo build --release --locked (verifies the release-profile knobs actually link)

Folds in F6 (Cargo.lock drift) via the --locked flag. cargo-deny step deliberately omitted — the napi-specific license-allowlist needs a discovery diff (napi-derive-backend, ctor, libloading, …) that's cleaner as a follow-up than dropping into this PR. Verified locally: cargo build --release --locked clean (~18s with deps cached), 14 tests pass.

🟢 F9 (cleanup hook gap) — addressed in the same commit. Added a TODO on runtime::try_get_handle flagging napi_add_async_cleanup_hook as the proper lock-in for PR #25's Drop impls, with the failure mode written out (runtime shutdown swallowing cleanup spawns). PR #25 makes the choice consciously now.

🟡 F2 (typed-error refactor → JIRA promotion) — noted. I'll route the JIRA filing through team-lead since I don't have JIRA-create wired in this context. The deferred spec at sea-workflow/jira-candidates/2026-05-23-napi-typed-error-refactor.md carries the full design (spawn_with_env_resolver helper, refactored napi_err_from_kernel(env, e), entry-point pattern, what disappears) and is what PR #25's owner will work from. Confirming explicitly that the sentinel scheme is interim and will be deleted in PR #25 — the wire format does NOT become a shipping commitment.

Defer-acceptable per your own call (no action this PR):

  • F5 error_code_str parity — kernel-side pub fn ErrorCode::slug() would touch main src/ + add a strum dep. The existing test error_code_str_covers_all_known_variants catches drift at PR-review time. Tracked for bindings-common follow-up.
  • F7 .d.ts/index.js generation — adding @napi-rs/cli is a real toolchain dep. Will note in PR description that the crate isn't standalone-installable in current state.
  • F14 blanket cfg_attr(not(test), allow(dead_code)) — temporary; every gated item gets a real caller in PR feat(napi): openSession / Connection / Statement napi surface (stack 3/8) #25 and the blanket comes off then.

PR #27 tip is now 4cae507. Pre-commit gate clean. Downstream cascade deferred (PR #25 agent is editing the metadata-exposure worktree concurrently; cascading now would race with their work).

@msrathore-db
msrathore-db merged commit b73a688 into msrathore/kernel-async-public-api May 25, 2026
vikrantpuppala pushed a commit that referenced this pull request May 25, 2026
…in) (#66)

Re-targets
[#27](#27)
against `main`.

## What happened

PR #27 was stacked on PR #26's branch
(`msrathore/kernel-async-public-api`). When PR #26 squash-merged into
`main` (commit `f4a18ba`), PR #27's base was not re-pointed to `main`,
so merging PR #27 landed its content on the now-stale
`msrathore/kernel-async-public-api` branch (merge commit `b73a688`)
rather than on `main`. Result: the napi-skeleton content is not on
`main` despite #27 being marked as merged.

## What this PR does

Cherry-picks the squash commit from #27 (`b73a688`) onto a fresh branch
from current `main`. Content is identical to what #27 should have landed
— same 12 files, same `+3771 / -2` line counts.

## Review history

All review approval is on #27; this PR carries the identical diff.
Re-review is not required but pre-commit gate has been verified:

- `cargo fmt --all -- --check` — clean
- `cargo clippy --all-targets --locked -- -D warnings` — clean
- `cargo test --locked` — 14 / 14 pass
- `cargo build --release --locked` — clean

## Stack context

This is the second of an 8-PR kernel stack (PR #26 was the first;
#25/#29/#28/#30/#24/#23 follow). Each subsequent PR's base will need to
be updated to point at this PR's branch
(`msrathore/kernel-napi-skeleton-to-main`) once it merges to main,
mirroring the same re-target pattern.

## Files

- `.github/workflows/napi-checks.yml` — CI workflow for the napi crate
(fmt + clippy + test + release-build with `--locked`)
- `Cargo.toml` — root workspace tweak so the napi sub-crate's
standalone-workspace pattern works
- `napi/.gitignore`, `napi/Cargo.toml`, `napi/Cargo.lock`,
`napi/build.rs`, `napi/package.json` — crate manifest + napi-rs build
glue
- `napi/src/lib.rs` — crate root, `version()` napi export
- `napi/src/error.rs` — kernel `Error` → napi `Error` envelope mapper +
pyo3 field-parity guards
- `napi/src/util.rs` — `guarded()` panic-catching wrapper + `panic =
"abort"` compile-time guard
- `napi/src/runtime.rs` — captured tokio `Handle` accessor + PERF NOTE +
async-cleanup-hook TODO for PR #25
- `napi/src/logger.rs` — Round-3 logger bridge stub with inline design
sketch

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.

2 participants