Skip to content

feat(statement): expose 5 status accessors on ExecutedStatement (stack 8/8) - #23

Merged
msrathore-db merged 9 commits into
mainfrom
msrathore/krn-status-fields
May 29, 2026
Merged

msrathore-db merged 9 commits into
mainfrom
msrathore/krn-status-fields

Conversation

@msrathore-db

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

Copy link
Copy Markdown
Collaborator

Summary

Combined PR carrying kernel-stack positions 7/8 (TLS public API) and 8/8 (SEA status accessors) as a single 2-commit diff rebased onto main, plus follow-up review-response commits. PR #24 (original 7/8) was closed; its content is the first commit here.

The sync and async kernel execution handles (ExecutedStatement from Statement::execute(), ExecutedAsyncStatement from Statement::submit()) now both expose the same four extended SEA status accessors — matching the Thrift IOperation.status() contract where the field set is available on the same handle regardless of how the caller drove polling. The kernel Error type carries those fields onto terminal-error states (FAILED / CANCELED / CLOSED-no-data) so wrappers see the same fields Thrift surfaced on TGetOperationStatusResp for failed statements. The napi binding (databricks-sea-native) exposes the matching JS surface (5 method/getter additions on Statement, 3 envelope keys on the JS Error) so JS callers migrating from the Thrift driver see the same field set they used to read from TGetOperationStatusResp. The pyo3 binding is intentionally untouched here.

What this PR ships

Public surface (kernel)

config::TlsConfig — was an empty #[non_exhaustive] placeholder; now carries:

  • custom_ca_cert: Option<Vec<u8>> (PEM bytes, in-memory — no tempfile shim for napi-rs / pyo3)
  • accept_self_signed: bool
  • skip_hostname_verification: bool

Multi-cert bundle support (reqwest::Certificate::from_pem_bundle) covers root+intermediate concatenations on both tls-native and tls-rustls backends. session.rs::build_http_client_config honours the caller-supplied TlsConfig instead of discarding it. Custom Debug impls redact PEM byte counts.

types::sea::StatementStatus is now #[non_exhaustive] (external Rust callers can't struct-literal it; new fields stay non-breaking). Adds:

  • num_modified_rows: Option<i64>
  • display_message: Option<String>
  • diagnostic_info: Option<String>
  • error_details_json: Option<String>

Custom redacting Debug truncates the three unbounded server strings to <N chars> so a ?status in a tracing span doesn't dump multi-MB blobs.

ExecutedStatement (sync handle, from Statement::execute()) exposes 4 accessors mirroring the above fields — populated from the terminal SEA StatementStatus captured at construction. Reachable on Succeeded / Closed-with-inline-data paths.

ExecutedAsyncStatement (async handle, from Statement::submit()) mirrors the same 4 accessors. Internally caches latest_status: Arc<std::sync::Mutex<SeaStatementStatus>>, seeded with the initial submit_statement response and overwritten on every status() / await_result() poll. Same Thrift IOperation.status() contract on both consumption modes.

kernel_error::Error gains three additive optional fields — display_message, diagnostic_info, error_details_json — plus matching builder setters. Populated by carry_extended_status() in client/sea.rs::terminal_outcome on Failed / Cancelled / Closed-no-data arms so the extended fields flow through to wrappers on the failure path.

napi binding (databricks-sea-native)

The JS-visible Statement class adds 4 async accessor methods mirroring Thrift's TGetOperationStatusResp field names: numModifiedRows(), displayMessage(), diagnosticInfo(), errorDetailsJson().

The JS Error envelope (napi/src/error.rs) becomes a strict superset of the pyo3 set — in addition to the 8 pyo3-aligned keys (code / message / sqlState / errorCode / vendorCode / httpStatus / retryable / queryId), it carries displayMessage / diagnosticInfo / errorDetailsJson whenever the kernel Error has them populated. JS callers catching errors get the same field surface they used to read from Thrift's failed-operation status.

pyo3 binding

Untouched. The kernel's Error gains new fields but pyo3's attach_attrs continues attaching only the original 8; the three Thrift-parity fields can be wired up later in a pyo3-specific follow-up if Python consumers want them. The async-handle accessor additions follow through to ExecutedAsyncStatement regardless (pyo3 wraps the kernel handle).

What is NOT in this PR

  • progress accessor — removed from this PR. Empirical evidence: SDK Java's StatementStatus has no progress field, the live SEA wire doesn't populate one, and the live Thrift wire returned progressUpdateResponse = null on every poll of a 37s heavy TPC-H query against pecotesting (verified 2026-05-27). A TODO(pr23-followup) block at the kernel + napi sites documents the empirical evidence and the shape constraints for re-introduction (mirror Thrift's TProgressUpdateResp struct, not a bare Option<f64>). A forward-compat test (test_statement_status_ignores_unknown_progress_field) pins that the kernel won't break if the SEA server later starts emitting a progress JSON key.

  • errorDetailsJson server-side behaviour — gated server-side by spark.databricks.sql.errorDetailsJson.enabled, declared internal() and default-false in DatabricksSQLConf.scala. NOT settable via client session-conf (verified: pecotesting returns [CONFIG_NOT_AVAILABLE] SQLSTATE: 42K0I when SET). The kernel's wire-shape behaviour is correct already (passes through whatever the server sends); docstrings on all surfaces (types::sea, ExecutedStatement, Error, napi Statement.errorDetailsJson) explicitly call out this gating so users understand why the field is None on most workspaces.

  • Public TLS surface on the napi binding — the kernel side is built; the napi Connection.openSession({ tls: ... }) plumbing remains a follow-up PR. The kernel surface is intentionally stricter (default = full validation, opt-in relaxations) than the existing NodeJS Thrift driver's hardcoded rejectUnauthorized: false; motivation is Python connector parity (Python exposes _tls_no_verify / _tls_verify_hostname / _tls_trusted_ca_file / _tls_client_cert_*) + better-than-Thrift defaults on SEA NodeJS. A TODO(pr23-followup) block on config::TlsConfig documents the Thrift evidence and the rationale.

  • Two publicly-reachable TlsConfig types (config::TlsConfig + client::http::TlsConfig) — client::http::TlsConfig is technically reachable via client::http being a pub mod. Documented (internal-only path field), deferred to a follow-up that gates the internal struct to pub(crate) after a downstream-consumer audit.

Live-warehouse validation (pecotesting via DATABRICKS_PECOTESTING_TOKEN_PERSONAL)

Empirical probes captured on 2026-05-27:

  • Sync handle, SELECT 1 against SQL warehouse: all 4 accessors reachable, all return None (server-omitted on classic SQL warehouse SELECT). Accessor wiring confirmed.
  • Sync handle, SELECT * FROM nonexistent_table (FAILED): kernel Error carries sql_state=Some("42P01"), error_code=Some("BAD_REQUEST"); the 3 extended fields are None because the SEA server emits less than Thrift on that error class (Thrift populated both displayMessage and diagnosticInfo for the same query — a real SEA-vs-Thrift wire divergence the kernel correctly passes through without inventing values).
  • Async handle, SELECT 1 via submit() + await_result(): all 4 accessors reachable, return None.
  • Async handle wiremock coverage: initial-submit-terminal status caching, terminal-poll caching across await_result, and explicit status() cache refresh — all pinned by 3 new tests.
  • numModifiedRows via Thrift on a real INSERT/UPDATE: populated correctly (3 for INSERT VALUES (1),(2),(3), 2 for UPDATE ... WHERE n>1). SEA equivalent behaves the same because the kernel passes the wire field through verbatim.
  • errorDetailsJson via Thrift across 8 distinct error classes (parser, analyzer, runtime, raise_error, assert, function-lookup, group-by, table-not-found): null on every one because spark.databricks.sql.errorDetailsJson.enabled is off in the workspace. Confirms the server-side gating documented in the docstrings.
  • Baseline regression check (select_one_round_trip + select_with_positional_params): still pass against live warehouse after all kernel-side changes.

Commits

  1. 90a40663 — krn-tls-public-api: expose TlsConfig fields + stop discarding in session.rs (was PR feat(config): expose TlsConfig fields + stop discarding in session.rs (stack 7/8) #24)
  2. f2af099a — krn-status-fields: expose 5 status accessors on ExecutedStatement (note: Statement::execute() constructs ExecutedStatement::new with 6 positional args, not 5 — the original commit message off-by-one; subsequent commits use the correct count)
  3. 132e904 — Merge main into branch (pulls in PR feat(napi): expose maxConnections on openSession ConnectionOptions #74 napi maxConnections)
  4. 10a852e — krn-status-fields: review fixes + napi Thrift-parity surface — addresses F1 / F4 / F5 / F6 / F7 / F8 / F9 / F10 / F15 / F16 / F18 / F19 / F20 / F22 / F24 from the ultrareview, plus the napi-side Thrift-parity exposure (5 JS accessor methods + 3 envelope keys + parity test update from "strict 8" to "superset of pyo3 + 3 Thrift fields")
  5. 752d1fa — krn-status-fields: clarify TLS doc + add polling-path status test — P2.3 + P2.4
  6. af3a80a — krn-status-fields: drop speculative progress field + clarify TLS Thrift intent — R2 (live-warehouse evidence) + R1 (Thrift TLS investigation)
  7. 43183ae — krn-status-fields: mirror extended-status accessors on async handle + errorDetailsJson gating doc — P1.2 (async-handle mirror) + errorDetailsJson server-flag documentation

Tests

Combined branch on latest commit: 453/453 lib + 14/14 wiremock + 14/14 async-execute-wiremock + 16/16 integration + 26/26 napi passing.

New in this PR (across all commits):

  • tls_config_default_is_strict (commit 1)
  • tls_config_debug_redacts_ca_cert_bytes (commit 1)
  • test_statement_status_with_extended_fields (commit 2 + updates)
  • test_statement_status_extended_fields_absent (commit 2 + updates)
  • test_statement_status_ignores_unknown_progress_field (commit 6 — forward-compat)
  • executed_statement_surfaces_extended_status_fields (commit 2)
  • executed_statement_status_fields_default_to_none (commit 2)
  • polling_path_carries_terminal_status_not_initial (commit 5)
  • test_http_client_with_multi_cert_pem_bundle (commit 4 — TLS bundle fix)
  • test_http_client_with_empty_pem_bytes_errors (commit 4)
  • test_tls_config_from_public_default_is_strict (commit 4 — strict-Some(false) mapping)
  • envelope_field_set_matches_pyo3_setattr_contract (updated in commit 4 to reflect Thrift-parity superset)
  • envelope_omits_thrift_extension_fields_when_unpopulated (commit 4)
  • envelope_surfaces_thrift_extension_fields_verbatim (commit 4)
  • async_await_result_caches_terminal_status_for_accessors (commit 7)
  • async_submit_caches_initial_terminal_status (commit 7)
  • async_status_call_refreshes_cached_status (commit 7)
  • Live e2e: live_select_status_accessors_default_to_none (commit 4)
  • Live e2e: live_failed_statement_error_envelope_carries_extended_fields (commit 4)
  • Live e2e: live_async_handle_exposes_extended_status_accessors (commit 7)

Gates

  • cargo +stable fmt --all -- --check — exit 0
  • cargo clippy --all-targets -- -D warnings — exit 0 (kernel + napi)
  • cargo test --lib — 453/453 passing
  • cargo test --tests — all non-ignored passing
  • cargo test --test v0_async_execute_wiremock — 14/14 passing
  • napi cargo test — 26/26 passing
  • pyo3 cargo build — clean (untouched)

Tracking

Co-authored-by: Isaac

@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from 56f08d5 to eba6410 Compare May 16, 2026 14:39
@msrathore-db
msrathore-db changed the base branch from msrathore/krn-napi-binding to msrathore/kernel-async-public-api May 16, 2026 14:40
@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from eba6410 to 2683b3a Compare May 17, 2026 13:15
@msrathore-db
msrathore-db changed the base branch from msrathore/kernel-async-public-api to msrathore/krn-tls-public-api May 17, 2026 13:15
@msrathore-db msrathore-db changed the title [SEA-Kernel] krn-status-fields — expose 5 status accessors on ExecutedStatement feat(statement): expose 5 status accessors on ExecutedStatement (stack 8/8) May 17, 2026
@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from 2683b3a to f2a650c Compare May 20, 2026 10:36
@msrathore-db
msrathore-db force-pushed the msrathore/krn-tls-public-api branch 2 times, most recently from 5cda909 to 1ff2cf5 Compare May 20, 2026 16:55
@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from f2a650c to 7295fce Compare May 20, 2026 16:55
@msrathore-db
msrathore-db force-pushed the msrathore/krn-tls-public-api branch from 1ff2cf5 to c94be53 Compare May 20, 2026 20:22
@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from 7295fce to 1ab68d9 Compare May 20, 2026 20:22
@msrathore-db
msrathore-db force-pushed the msrathore/krn-tls-public-api branch from c94be53 to d8ffe65 Compare May 21, 2026 00:03
@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from 1ab68d9 to 6f0017a Compare May 21, 2026 00:03
@msrathore-db
msrathore-db force-pushed the msrathore/krn-tls-public-api branch from d8ffe65 to 86551cc Compare May 23, 2026 11:03
@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from 6f0017a to 1264c5e Compare May 23, 2026 11:03
@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from 99ef7ea to 5265c75 Compare May 25, 2026 19:20
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>
msrathore-db added a commit that referenced this pull request May 26, 2026
## Summary

Surfaces the kernel's `HttpConfig::pool_max_idle_per_host` knob to the
napi-rs JS surface as `maxConnections?: number` on the
`ConnectionOptions` interface for `openSession()`. When absent, the
kernel default of 100 (set in `c14c1ff` on this stack) applies.

Mirrors the Python connector's `max_connections` kwarg on the SEA
backend. The NodeJS Thrift backend does NOT expose this knob; this is a
SEA-only extension. No parity break.

## Implementation

- Adds `max_connections: Option<u32>` to
`napi/src/database.rs::ConnectionOptions`
- Wires it through
`SessionBuilder::http(HttpConfig{pool_max_idle_per_host: max as usize,
..default})`
- napi-rs serialises `Option<u32>` as JS `number | undefined`; values up
to `2^32 - 1` round-trip safely

Kernel-side change is zero — `HttpConfig` already carries the field, the
builder already accepts it. This PR is napi-only.

## Stack

This is PR 9 of the SEA stack, branched off
`msrathore/krn-status-fields` (PR #23). The corresponding NodeJS side
lives in branch `msrathore/sea-max-connections` (pushed to
databricks-sql-nodejs).

## Test plan

- [x] `cargo build` passes
- [x] `cargo clippy --all-targets -- -D warnings` passes
- [x] `napi build --platform` regenerates `index.d.ts` with
`maxConnections?: number` on `ConnectionOptions`
- [x] Linked NodeJS PR carries
`tests/unit/sea/auth-max-connections.test.ts` — 9 cases passing (omit,
valid, boundary, 0-reject, neg-reject, non-int-reject, NaN-reject, M2M
arm, U2M arm)
- [ ] Live warehouse e2e — pending merge of this PR + the NodeJS side

---------

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db changed the base branch from msrathore/krn-tls-public-api to main May 26, 2026 10:16
@msrathore-db
msrathore-db force-pushed the msrathore/krn-status-fields branch from 5265c75 to f2af099 Compare May 26, 2026 10:16
Pull in PR #74 (napi maxConnections with per-binding default 100).

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db marked this pull request as ready for review May 26, 2026 10:30
@gopalldb

Copy link
Copy Markdown
Collaborator

P1 — Important

  1. Status fields silently dropped on FAILED / CANCELED paths — src/client/sea.rs:196-253 (terminal_outcome) + :256-275 (wait_for_completion) + src/statement/mutable.rs:156-160
    When the server returns state=FAILED or CANCELED, terminal_outcome builds an Err from service_error.{message, error_code, sql_state} and drops the surrounding response.status on the floor. Statement::execute
    propagates via ?, so no ExecutedStatement is ever constructed → callers never see display_message / diagnostic_info / error_details_json on failure. This is the exact case those fields exist for (enriching
    Python/Node exception hierarchies). The PR's stated motivation works for SUCCEEDED but is a silent no-op on the load-bearing path.
    Fix: either (a) attach display_message / diagnostic_info / error_details_json to the Error built in terminal_outcome (mirror existing with_sql_state / with_error_code builder), or (b) document explicitly in
    the accessor docstrings + PR description that these surface on success path only and live inside the Error on failure.

  2. ExecutedAsyncStatement doesn't expose the 5 new accessors — src/statement/executed_async.rs:184-302
    fetch_completed_result (sea.rs:531) populates result.status on the async path too, but materialise_result only extracts result.reader and returns a bare ResultStream — the 5 status fields are visible on the
    wire but no accessor surfaces them. Submit-then-await callers can't see num_modified_rows() even though the data is available.
    Fix: mirror the 5 accessors onto ExecutedAsyncStatement (small mechanical change — capture status in materialise_result), or call out the deferred work in the PR description.

P2 — Minor

  1. trusted_certificate_pem doc comment references "both" paths but public surface only exposes one — src/client/http.rs:98-102
    Internal struct supports trusted_certificate_path + trusted_certificate_pem, but from_public always leaves the path None. Doc comment "when both are set, the path is read first" can't fire from public
    callers.
    Suggestion: clarify the comment is for non-public callers.

  2. Wiremock tests only cover inline-result SUCCEEDED path — tests/v0_execute_wiremock.rs:710-786
    Strong assertions (assert_eq!(exec.num_modified_rows(), Some(7))), but no polling-path variant, no submit → fetch_completed_result variant. Coverage doesn't confirm the kernel carries forward the terminal
    status, not the initial one.
    Suggestion: add a polling-path test where extended fields arrive only on the final GetStatementStatus.

  3. PR description / commit message off-by-one on constructor arg position
    Description says "takes status as its 5th arg"; signature is (session, statement_id, valid, result_stream, closed, status) — 6th positional.

Comment thread src/client/http.rs Outdated
Self {
enabled: None,
allow_self_signed: cfg.accept_self_signed.then_some(true),
allow_hostname_mismatch: cfg.skip_hostname_verification.then_some(true),

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.

do we support all these configs from NodeJS driver?

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.

Empirically, NodeJS Thrift does not expose programmatic TLS to users. Verified against the OSS driver source on 2026-05-27:

  • lib/contracts/IDBSQLClient.ts:67-77 — the public ConnectionOptions type has no ca / cert / key / rejectUnauthorized field
  • lib/connection/contracts/IConnectionOptions.ts — the INTERNAL options interface declares ca / cert / key, but DBSQLClient.getConnectionOptions() translator at lib/DBSQLClient.ts:114-127 never sets them from public options
  • lib/connection/connections/HttpConnection.ts:67-77 — createHttpsAgent() builds the agent with rejectUnauthorized: false hardcoded, so even Node's process-level NODE_EXTRA_CA_CERTS / NODE_TLS_REJECT_UNAUTHORIZED env vars are inert against the driver's agent.

The kernel surface here is intentionally stricter (default = full validation) and richer (programmatic CA bundle) than Thrift's hardcoded-permissive default. The motivation is:

  1. Python connector parity — databricks-sql-connector exposes _tls_no_verify / _tls_verify_hostname / _tls_trusted_ca_file / _tls_client_cert_* (~/databricks-sql-python/src/databricks/sql/session.py:86-92). The kernel must back those when pyo3 wires them up.
  2. Better-than-Thrift defaults on the SEA NodeJS path — the napi binding can do TLS correctly rather than replicating Thrift's hardcoded-insecure baseline.

A TODO(pr23-followup) block on config::TlsConfig (commit af3a80a) documents this rationale and points future maintainers at the empirical Thrift evidence so the choice is auditable. Happy to defer the actual NodeJS-facing TLS expansion to a follow-up PR — the kernel surface here is the prerequisite, not a behaviour change on its own.

Resolved by:

  • 10a852e — initial public TLS surface + napi envelope plumbing
  • 752d1fa — clarified internal-only path field doc (the "both set" case is unreachable from the public surface)
  • af3a80a — TODO block documenting Thrift evidence + Python parity motivation

Comment thread src/statement/executed.rs Outdated
/// Fractional completion in `[0.0, 1.0]`. Populated on analytics
/// warehouses; absent elsewhere. On a terminal `ExecutedStatement`
/// this is typically `Some(1.0)` when populated at all.
pub fn progress(&self) -> Option<f64> {

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.

is this supported by server? How will you compute this?

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.

Excellent question. Empirical evidence collected on 2026-05-27 against pecotesting via NodeJS Thrift with getProgressUpdate=true on the wire:

SEA wire model (Databricks SDK Java v0.69.0): com.databricks.sdk.service.sql.StatementStatus has only error + state. No progress field. Confirmed via javap on the SDK jar at ~/.m2/repository/com/databricks/databricks-sdk-java/0.69.0/.

Live SQL warehouse probe (37s TPC-H query, samples.tpch.lineitem GROUP BY): Thrift NodeJS callback observed 7 polls. progressUpdateResponse was populated 0 / 7 polls — the SQL warehouse path does not emit TProgressUpdateResp even when the client explicitly opts in via getProgressUpdate=true. The Thrift-side progress field is populated by Spark interactive clusters running long-running jobs, not by SQL warehouses.

Shape mismatch: Thrift's TProgressUpdateResp is a struct (headerNames / rows[][] / footerSummary / progressedPercentage / status / startTime); the kernel's previous progress: Option<f64> was the wrong shape and would lock us into API churn when the SEA server eventually grows progress support.

Resolution (commit af3a80a): removed the progress() accessor end-to-end (ExecutedStatement::progress, the wire-shape types::sea::StatementStatus.progress field, the napi Statement.progress() method, all tests + assertions). A TODO(pr23-followup) block at both definition sites documents the empirical evidence and the shape constraint for re-introduction (should mirror Thrift's struct, not a bare float).

A new forward-compat regression test test_statement_status_ignores_unknown_progress_field pins that the kernel won't break if the SEA server starts emitting a progress JSON key on the wire — #[serde(default)] silently ignores unknown keys, so the field can be re-added without a coordinated wire migration.

Addresses the multi-reviewer feedback on PR #23 and extends the napi
binding's `Statement` class so JS callers migrating from the Thrift
driver see the same operation-status fields they used to read off
`TGetOperationStatusResp`.

## Kernel-side review fixes (hygiene + correctness)

- **F1** `#[non_exhaustive]` on `types::sea::StatementStatus` so adding
  the 5 wire fields stays a non-breaking change for external Rust
  callers that build the struct via `Default + field assignment`.
  Custom `Debug` impl truncates the three unbounded server-supplied
  strings (`display_message` / `diagnostic_info` / `error_details_json`)
  to `<N chars>` so a `?status` in a tracing span never dumps a
  multi-MB blob. PII / size caveats documented per field.

- **F5** (correctness, cross-backend divergence): swap
  `reqwest::Certificate::from_pem` → `Certificate::from_pem_bundle`
  in both `trusted_certificate_path` and `trusted_certificate_pem`
  loaders. The old `from_pem` parsed exactly one certificate under
  the kernel's default `tls-native` feature — root + intermediate
  bundles silently lost the intermediate. Under `tls-rustls` (napi
  binding) it happened to work because reqwest's rustls path reads
  multiple PEMs from the buffer. This commit makes the behaviour
  uniform across both backends and surfaces an explicit error when
  the input contains zero PEM blocks (previously a silent no-op).
  New tests: `test_http_client_with_multi_cert_pem_bundle` and
  `test_http_client_with_empty_pem_bytes_errors`.

- **F6**: replace the stale `SessionBuilder::tls()` docstring
  ("Reserved in v0; fields land in v0.1") with the actual field
  list + a working `no_run` example. The `config.rs` module-doc
  scope-of-v0 section also updated — TlsConfig is no longer in the
  reserved-empty list.

- **F7**: custom redacting `Debug` impl on the internal
  `client::http::TlsConfig` mirroring the public one — defense in
  depth so a future `?http_client` tracing span never dumps cert
  bytes verbatim.

- **F8** (security force-disable): `HttpTlsConfig::from_public` now
  maps a public `bool` to `Some(bool)` (was `bool.then_some(true)`,
  i.e. `false → None`). A future internal default flipping lenient
  would otherwise have inherited through `None`, defeating a
  strict-config caller. Cost is one extra `Some(false)` line in
  `RUST_LOG=debug` for default sessions.

- **F9**: TLS-relaxation `warn!` lines now include `org_id =
  ?config.org_id` so a fleet log store can attribute the dangerous
  flag back to the workspace that opted in. Previously logged with
  no attribution.

- **F10**: `ExecutedStatement::progress()` docstring tightened —
  the value is passed through verbatim from the server, NOT clamped.
  Callers rendering progress bars should clamp or treat NaN as
  absent before display.

- **F15**: PII / sensitive-data caveats on `display_message` /
  `diagnostic_info` accessors and the field-level docs in
  `types::sea::StatementStatus` — these are free-form server text
  that may include SQL fragments or parameter values.

- **F16**: TlsConfig doc gains a working "I have CA cert in a
  Buffer / bytes" example for the napi-rs / pyo3 wrapper use case
  that motivated the PEM-bytes field.

- **F18**: custom `Debug` on `StatementStatus` (see F1) covers the
  unbounded-blob log-leak path the reviewer flagged.

- **F19**: dropped the unused
  `From<&public::TlsConfig> for http::TlsConfig` impl —
  `from_public` is the named API, no `.into()` callers exist.

- **F20**: `let ProxyConfig {}` (explicit, no `..` rest pattern) in
  `session.rs::build_http_client_config` so the destructure-as-
  tripwire actually fires when ProxyConfig grows a field.

- **F22**: cert-load error message now names the public field —
  "Invalid PEM bytes in TlsConfig.custom_ca_cert: ..." instead of
  "Invalid in-memory PEM certificate: ...".

- **F24**: poll-loop `debug!(progress = ..., statement_id = ...)`
  emission inside `wait_for_completion` — progress is otherwise
  near-useless because the terminal value is always `Some(1.0)`
  or `None`.

## F4 / Thrift parity — kernel `Error` carries extended status fields

Adds three additive optional `String` fields to `kernel_error::Error`:
`display_message`, `diagnostic_info`, `error_details_json`. Mirrors
the same-named optional fields on the NodeJS Thrift driver's
`TGetOperationStatusResp` and `TStatus`. A new
`carry_extended_status()` helper in `client/sea.rs::terminal_outcome`
populates these on `Failed` / `Cancelled` / `Closed-no-data` arms
so wrappers see the same field set Thrift surfaced on terminal-
error states (the kernel previously dropped these on the floor when
folding `Failed` into `Result::Err(Error)`).

Public-API impact: strictly additive — the `Error` struct is
documented as "pattern-matchable, new fields land via additive
setters, no `#[non_exhaustive]`" so the three new fields fit the
existing contract. Boxing the existing
`statement::executed_async::StatementStatus::Failed(Error)` variant
would have rippled into pyo3 / direct-Rust callers; an
`#[allow(clippy::large_enum_variant)]` keeps it inline with a
rationale comment.

## napi binding — Thrift-parity Statement surface

The JS-visible `Statement` class on the napi binding now mirrors the
NodeJS Thrift driver's `IOperation` extended-status surface:

- `numModifiedRows()` — `TGetOperationStatusResp.numModifiedRows`
- `progress()` — `TGetOperationStatusResp.progressUpdateResponse`
  (kernel surfaces just the ratio today)
- `displayMessage()` — `TGetOperationStatusResp.displayMessage`
- `diagnosticInfo()` — `TGetOperationStatusResp.diagnosticInfo`
- `errorDetailsJson()` — `TGetOperationStatusResp.errorDetailsJson`

All five are async `#[napi]` methods that take the existing inner
`Arc<Mutex<...>>` lock briefly. After `close()` they return
`InvalidStatementHandle` matching the existing accessor semantics.

On the error path the JS Error envelope (`napi/src/error.rs`) is
extended to a Thrift-parity superset of the pyo3 envelope: in
addition to the 8 pyo3-aligned keys, the envelope now also carries
`displayMessage` / `diagnosticInfo` / `errorDetailsJson` whenever
the kernel's `Error` has them populated. The previous strict
pyo3 ↔ napi parity invariant becomes "napi is a superset of pyo3
for Thrift parity"; the test `envelope_field_set_matches_pyo3_setattr_contract`
is updated to reflect this. Two new tests
(`envelope_omits_thrift_extension_fields_when_unpopulated`,
`envelope_surfaces_thrift_extension_fields_verbatim`) pin the wire
shape.

## What is intentionally NOT changed

- **pyo3 binding** — left untouched per design. Pyo3's
  `attach_attrs` continues to attach the original 8 fields; the
  three Thrift extension fields are reachable via the existing
  `e.args[0]` message for now and can be added in a later commit if
  Python users need them. The kernel-side `Error` carries them, so
  the upgrade path is purely additive on the pyo3 side.

- **`ExecutedAsyncStatement`** — does not gain the 5 accessors.
  A module-level docstring note explicitly points async-consumption
  callers at the sync `ExecutedStatement` handle when they need the
  extended fields. The napi binding only uses the sync handle, so
  Thrift parity is unaffected by this asymmetry.

- **`config::TlsConfig` vs `client::http::TlsConfig` duplication**
  (review F3) — deferred to a follow-up. Gating the internal struct
  to `pub(crate)` needs a downstream-consumer audit and is out of
  scope here.

## Live-warehouse validation (pecotesting)

Two new ignored e2e tests in `tests/v0_execute_e2e.rs`:

- `live_select_status_accessors_default_to_none` — confirmed
  against pecotesting: a `SELECT 1` round-trip returns
  `progress=None, display_message=None, diagnostic_info=None,
  error_details_json=None`. The 5 accessors are reachable
  end-to-end and degrade gracefully when the server omits them.

- `live_failed_statement_error_envelope_carries_extended_fields` —
  confirmed against pecotesting: a `SELECT * FROM nonexistent_*`
  returns `Error { code: SqlError, sql_state: Some("42P01"),
  error_code: Some("BAD_REQUEST"), display_message: None,
  diagnostic_info: None, error_details_json: None }`. The wire
  envelope from the server doesn't populate the three extended
  fields on `TABLE_OR_VIEW_NOT_FOUND` today, so the kernel passes
  through `None` — the contract (kernel never drops what the
  server sends) is satisfied.

Baseline regression check: `select_one_round_trip` and
`select_with_positional_params` still pass against the live
warehouse after the kernel-side changes.

## Gates (all workspace-wide)

- `cargo +stable fmt --all -- --check` — exit 0
- `cargo clippy --all-targets -- -D warnings` — exit 0 (kernel + napi)
- `cargo test --lib` — 452 / 452 passing (kernel)
- `cargo test --tests` — 16 / 16 passing (kernel integration)
- `cargo test --test v0_execute_wiremock` — 14 / 14 passing
- napi `cargo test` — 26 / 26 passing
- pyo3 `cargo build` — clean (no pyo3 source touched)

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
Addresses two minor review comments on PR #23 from @gopalldb:

- P2.3 (`src/client/http.rs`): the internal `TlsConfig` docstring on
  `trusted_certificate_pem` said "when both [path AND pem] are set,
  the path is read first". That branch is unreachable from the
  public `SessionBuilder` surface — `HttpTlsConfig::from_public`
  always leaves `trusted_certificate_path = None`. Doc is rewritten
  to explicitly identify `trusted_certificate_path` as the internal-
  only file-loader (no public projection) and note that the
  "both set" case is only reachable for direct-Rust callers that
  construct `HttpClientConfig` manually. No behaviour change.

- P2.4 (`tests/v0_execute_wiremock.rs`): adds
  `polling_path_carries_terminal_status_not_initial`. The existing
  status-field tests covered only the inline-result SUCCEEDED path
  where the initial POST /statements response is also the terminal
  one. The new test stages a RUNNING response on POST and a
  SUCCEEDED-with-populated-status response on the polling GET. The
  test pins the contract that `ExecutedStatement` is constructed
  from the TERMINAL status (the final GET), not the initial POST —
  if the kernel ever regresses to latching the first response onto
  the executed handle, the accessors would see None and the test
  fails loudly.

## Gates

- `cargo +stable fmt --all -- --check` — exit 0
- `cargo clippy --all-targets -- -D warnings` — exit 0
- `cargo test --test v0_execute_wiremock` — 15 / 15 passing (the
  new polling-path test included)

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

Two PR #23 review responses, both grounded in live-warehouse evidence
captured against pecotesting on 2026-05-27.

## Drop `progress` from the kernel surface (reviewer R2)

The accessor `ExecutedStatement::progress() -> Option<f64>` and the
underlying `types::sea::StatementStatus.progress` field are removed
end-to-end. The reviewer asked the right question: is this actually
supported on the SEA wire, and if not, why add it?

Empirical evidence:

1. The Databricks SDK Java v0.69.0 `StatementStatus` model has only
   `error` + `state`. No `progress` field is documented or generated
   from the SEA OpenAPI spec.

2. Against pecotesting (a SQL warehouse), I ran a 37s heavy TPC-H
   query through the **NodeJS Thrift driver** with the Thrift-side
   `progress: true` opt-in (which sets `getProgressUpdate=true` on
   the wire). Across 7 polls observed by the user callback:
       progressUpdateResponse populated: 0 / 7
       taskStatus           populated: 0 / 7
   The SQL warehouse simply does not emit Thrift's
   `TProgressUpdateResp` either — even though the same query takes
   half a minute.

3. The kernel's existing `progress: Option<f64>` shape doesn't even
   match what Thrift produces. Thrift's `TProgressUpdateResp` is a
   struct (`headerNames` / `rows[][]` / `footerSummary` /
   `progressedPercentage` / `status` / `startTime`); a bare float
   would be the wrong shape when the SEA server eventually grows
   progress support.

Adding a field that's always `None` against today's wire, with a
shape that doesn't match the established Thrift contract, would lock
us into API churn. Removing it now keeps the kernel honest. A
`TODO(pr23-followup)` block is added at the `StatementStatus` and
`ExecutedStatement` definitions explaining the rationale and the
shape-design constraint for when the field comes back.

Forward-compat regression test:
`test_statement_status_ignores_unknown_progress_field` pins the
behaviour that the kernel will not break if the SEA server starts
emitting `progress` on the wire — serde `#[serde(default)]` on the
modelled fields silently ignores unknown keys, so the field can be
re-introduced without a coordinated wire migration.

## Clarify TLS contract intent (reviewer R1)

The Thrift NodeJS driver does NOT expose programmatic TLS config to
users — its `ConnectionOptions` lacks any `ca` / `cert` / `key` /
`rejectUnauthorized` field, and its `HttpConnection.createHttpsAgent`
builds the agent with `rejectUnauthorized: false` HARDCODED
(verified at
`~/databricks-sql-nodejs/lib/connection/connections/HttpConnection.ts:67-77`).
The only TLS knobs Thrift NodeJS users have today are Node's process-
level env vars (`NODE_EXTRA_CA_CERTS` /
`NODE_TLS_REJECT_UNAUTHORIZED`), and even those are inert against the
hardcoded-permissive agent.

The kernel's TLS surface is intentionally stricter (default = full
validation) and richer (programmatic CA bundle, mTLS room) than
Thrift's hardcoded-insecure default. The motivation is:

  1. Python connector parity — `databricks-sql-connector` exposes
     `_tls_no_verify` / `_tls_verify_hostname` /
     `_tls_trusted_ca_file` / `_tls_client_cert_*`. The kernel must
     back those when pyo3 wires them up.
  2. Doing better than Thrift's hardcoded-insecure default on the
     SEA NodeJS path (napi binding).

A `TODO(pr23-followup)` block on `config::TlsConfig` documents this
intent and the empirical Thrift evidence, so a future maintainer
following Thrift-parity-only reasoning has the context to either (a)
loosen the kernel to match Thrift (likely wrong) or (b) keep the
strict-by-default behaviour and grow the surface (likely right).

## Gates

- `cargo +stable fmt --all -- --check` — exit 0
- `cargo clippy --all-targets -- -D warnings` — exit 0 (kernel + napi)
- `cargo test --lib` — 453 / 453 passing (kernel)
- `cargo test --tests` — 16 / 16 passing (kernel integration)
- napi `cargo test` — 26 / 26 passing
- Live pecotesting e2e tests (with TOKEN_PERSONAL) — pass

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

## Async-handle extended-status accessors (resolves reviewer P1.2)

`ExecutedAsyncStatement` now mirrors the four extended-status
accessors that live on `ExecutedStatement`:

- `num_modified_rows() -> Option<i64>`
- `display_message() -> Option<String>`
- `diagnostic_info() -> Option<String>`
- `error_details_json() -> Option<String>`

This matches the Thrift `IOperation.status()` contract — same field
set available on the same handle regardless of how the caller drove
polling (sync-style `execute()` vs poll-loop `submit()` + `status()` /
`await_result()`).

Plumbing: `ExecutedAsyncStatement` gains a
`latest_status: Arc<std::sync::Mutex<SeaStatementStatus>>` field
seeded with the `submit_statement` response's status and overwritten
on every successful `status()` / `await_result()` poll. The mutex is
`std::sync::Mutex` (not `tokio::sync::Mutex`): the lock is only held
across the cheap field clones the accessors do, and across the
post-await write in the poll loop — never across `.await`, so the
sync mutex is sound and cheaper than the tokio variant. Lock
poisoning is swallowed on write (a fresh poll's status is lost but
the prior snapshot stays visible — better than panicking the
handle's accessor surface).

The async-execute pyo3 path keeps working unchanged — pyo3's
`ExecutedAsyncStatement` is a separate type that wraps the kernel
one; the kernel constructor gains a 5th `initial_status` arg, the
single in-tree callsite at `Statement::submit` passes
`response.status` through.

## errorDetailsJson server-side gating doc (resolves "how can we get this field?")

Empirical investigation (2026-05-27, pecotesting via Thrift):
`errorDetailsJson` is server-gated by
`spark.databricks.sql.errorDetailsJson.enabled`, declared in
`~/runtime/sql/catalyst/.../DatabricksSQLConf.scala` as `internal()`
with `createWithDefault(false)`. The flag is NOT settable from a
client `session_conf` request — verified the SET fails with
`[CONFIG_NOT_AVAILABLE] SQLSTATE: 42K0I` against pecotesting. The
flag can only be turned on by a workspace admin via cluster-level
`sparkConfigs`.

I probed 8 distinct error classes (TABLE_NOT_FOUND, COLUMN_NOT_FOUND,
SYNTAX_ERROR, TYPE_MISMATCH, DIV_BY_ZERO, ARRAY_OOB, FUNC_NOT_FOUND,
GROUP_BY, RAISE_ERROR, ASSERT_TRUE) against pecotesting via the
NodeJS Thrift driver. `displayMessage` and `diagnosticInfo` were
populated on every failure; `errorDetailsJson` was **null on every
one** because the flag is off in the workspace.

The kernel's wire-shape behaviour was already correct (`#[serde(default)]`
on `Option<String>` means we pass through `None` when the server
omits it, the actual content when it's present). The change here is
purely documentation: the docstrings on
`types::sea::StatementStatus.error_details_json`,
`ExecutedStatement::error_details_json`, `Error::error_details_json`,
and napi `Statement.errorDetailsJson()` now explicitly call out the
server-side flag, its internal-only / default-false state, and what
the content shape looks like when it IS populated
(`{"errorClass": "...", "messageTemplate": "..."}`). Users see why
the field is None on their workspace without re-deriving the
DatabricksSQLConf gating from scratch.

## Gates

- `cargo +stable fmt --all -- --check` — exit 0
- `cargo clippy --all-targets -- -D warnings` — exit 0 (kernel + napi)
- `cargo test --lib` — 453 / 453 passing
- `cargo test --test v0_async_execute_wiremock` — 14 / 14 passing
  (3 new tests for the async-handle accessor wiring)
- pyo3 `cargo build` — clean (untouched)
- Live pecotesting e2e: sync + async tests pass with TOKEN_PERSONAL

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

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review — addressed all 5 points across commits 10a852e, 752d1fa, af3a80a, 43183ae. Empirical evidence collected against pecotesting on 2026-05-27 with DATABRICKS_PECOTESTING_TOKEN_PERSONAL.

P1.1 — Status fields silently dropped on FAILED / CANCELED — resolved (option a)

Commit 10a852e adds display_message, diagnostic_info, error_details_json as flat Option<String> fields on kernel_error::Error (additive — the existing pattern-matching-friendly contract of Error is preserved). A new helper carry_extended_status() in src/client/sea.rs::terminal_outcome populates these on the Failed / Cancelled / Closed-no-data arms before the outcome becomes StatementOutcome::Err. The napi Statement JS Error envelope (napi/src/error.rs) extends to a Thrift-parity superset of the pyo3 set, carrying the same 3 fields on the JS Error so callers migrating from Thrift see the same field set Thrift's TGetOperationStatusResp exposes.

P1.2 — ExecutedAsyncStatement doesn't expose the new accessors — resolved in commit 43183ae

Mirrored on the async handle:

  • ExecutedAsyncStatement::num_modified_rows()
  • ExecutedAsyncStatement::display_message()
  • ExecutedAsyncStatement::diagnostic_info()
  • ExecutedAsyncStatement::error_details_json()

A new latest_status: Arc<std::sync::Mutex<SeaStatementStatus>> field is seeded with the initial submit_statement response and overwritten on every successful status() / await_result() poll. The mutex is std::sync (not tokio::sync) because the lock is only held across cheap field clones — never across .await. Three new wiremock tests in tests/v0_async_execute_wiremock.rs pin the contract:

  • async_await_result_caches_terminal_status_for_accessors — terminal poll wins, not initial PENDING
  • async_submit_caches_initial_terminal_status — server-completed-on-submit case (Thrift direct-results parity)
  • async_status_call_refreshes_cached_status — status() updates the cache

A live-warehouse e2e test (live_async_handle_exposes_extended_status_accessors) runs the full submit + await_result loop against pecotesting.

progress was removed. I missed flagging that on the original 5-accessor list — the live-warehouse probe (37s TPC-H query against pecotesting) returned progressUpdateResponse = null on every Thrift poll because SQL warehouses don't emit it, and the SDK Java model has no progress field. Details in the per-comment reply on src/statement/executed.rs:132. The async handle therefore mirrors exactly 4 accessors, matching the sync handle.

P2.3 — trusted_certificate_pem doc references unreachable "both set" case — resolved in 752d1fa

Doc rewritten to explicitly identify trusted_certificate_path as internal-only (no public projection), and to note the "both set" case is only reachable for direct-Rust callers constructing HttpClientConfig manually. No behaviour change.

P2.4 — Wiremock tests only cover inline-result SUCCEEDED — resolved in 752d1fa

New test polling_path_carries_terminal_status_not_initial stages POST /statements → RUNNING (no extended fields), then GET /statements/{id} → SUCCEEDED with all fields populated. Pins the kernel-must-carry-terminal contract — regression guard against latching the first response onto ExecutedStatement.

P2.5 — Off-by-one in original commit msg ("5th arg" vs 6th) — acknowledged

The original commit message at f2af099a says "takes status as its 5th arg"; signature is (session, statement_id, valid, result_stream, closed, status) — 6th positional. New commits use the correct count; the historical message can't be fixed without git --amend + force-push, which the team policy prohibits outside cascade rebases.

Additional empirical investigation surfaced separately

errorDetailsJson is server-gated by an internal Spark conf

spark.databricks.sql.errorDetailsJson.enabled is declared in ~/runtime/sql/catalyst/src/main/scala/com/databricks/sql/DatabricksSQLConf.scala as internal() with createWithDefault(false). Not settable via session-conf — pecotesting returns [CONFIG_NOT_AVAILABLE] SQLSTATE: 42K0I when the client SETs it. Probed 8 distinct error classes via Thrift — errorDetailsJson was null on every single one because the flag is off in the workspace. The kernel passes through whatever the server sends (so when an admin enables the flag, the kernel surfaces it); commit 43183ae adds explicit docstrings on all 4 surfaces (types::sea, ExecutedStatement, Error, napi Statement.errorDetailsJson) documenting this gating so users understand why the field is None on their workspace.

NodeJS Thrift has no public TLS config

Verified by inspecting lib/contracts/IDBSQLClient.ts:67-77 (public ConnectionOptions has no ca/cert/key), lib/DBSQLClient.ts:114-127 (translator never sets the internal ca/cert/key fields), lib/connection/connections/HttpConnection.ts:67-77 (rejectUnauthorized: false hardcoded on the agent). Even Node's process-level NODE_EXTRA_CA_CERTS is inert against the driver's hardcoded-permissive agent. The kernel surface is intentionally stricter for Python parity + better-than-Thrift defaults on the napi binding; a TODO(pr23-followup) block on config::TlsConfig documents this.

Test summary

  • cargo +stable fmt --all -- --check — exit 0
  • cargo clippy --all-targets -- -D warnings — exit 0 (kernel + napi)
  • cargo test --lib — 453 / 453 passing
  • cargo test --tests — all non-ignored integration tests passing
  • cargo test --test v0_async_execute_wiremock — 14 / 14 passing
  • napi cargo test — 26 / 26 passing
  • pyo3 cargo build — clean (untouched)
  • Live pecotesting e2e (with TOKEN_PERSONAL):
    • live_select_status_accessors_default_to_none ✓
    • live_failed_statement_error_envelope_carries_extended_fields ✓
    • live_async_handle_exposes_extended_status_accessors ✓
    • select_one_round_trip (baseline regression check) ✓

Ready for re-review.

@gopalldb

Copy link
Copy Markdown
Collaborator

A. Status of prior 5 findings

┌──────┬───────────────────────────────────┬───────────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ # │ Prior finding │ Status │ Evidence │
├──────┼───────────────────────────────────┼───────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ P1-1 │ Status fields dropped on │ PARTIAL │ Sync FIXED — src/client/sea.rs:61-72 introduces carry_extended_status, invoked on Failed (:254), Canceled (:260), Closed-no-data (:273). │
│ │ FAILED/CANCELED paths │ │ Error grew 3 Option fields at kernel_error.rs:200-222 with with_* setters. Async NOT FIXED — see new P1 below │
├──────┼───────────────────────────────────┼───────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ P1-2 │ ExecutedAsyncStatement lacks │ FIXED │ src/statement/executed_async.rs:212-267 exposes the 4 accessors (sans dropped progress()); latest_status cached at :167,277-281, │
│ │ accessors │ │ refreshed on every poll. Wiremock tests at tests/v0_async_execute_wiremock.rs:657-824 │
├──────┼───────────────────────────────────┼───────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ P2-3 │ trusted_certificate_pem doc │ FIXED │ src/client/http.rs:94-114 clearly states internal-only trusted_certificate_path has no public projection │
├──────┼───────────────────────────────────┼───────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ P2-4 │ Polling-path wiremock coverage │ FIXED │ polling_path_carries_terminal_status_not_initial at tests/v0_execute_wiremock.rs:766-792 │
├──────┼───────────────────────────────────┼───────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ P2-5 │ PR description off-by-one │ Cosmetic; not │ │
│ │ │ re-verified │ │
└──────┴───────────────────────────────────┴───────────────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

The progress field drop (af3a80a) is clean — no orphan calls anywhere; forward-compat serde test at src/types/sea.rs:641-656 pins ignore-unknown-field behavior so the kernel won't break when the server later
emits progress.

B. New findings

P1

  1. Async await_result() / status() error path drops extended status fields — src/statement/executed_async.rs:109-132 (Failed arm of from_sea_response) + :366-370 (Cancelled arm of await_result)
    from_sea_response::Failed rebuilds the Error from response.status.error (SQLSTATE + error_code + query_id only) and never reads display_message / diagnostic_info / error_details_json. The sync helper
    carry_extended_status (src/client/sea.rs:61-72) is module-private to sea.rs and not called. Same gap in the Cancelled arm of await_result. The Thrift-parity contract documented in napi/src/error.rs:85-92
    ("envelope carries displayMessage/diagnosticInfo/errorDetailsJson...") therefore breaks on the async path the napi binding will use. The fields are readable from the handle's accessors (because
    record_latest_status runs before from_sea_response), but that requires a "always read from accessors, not from the Error" rule that breaks symmetry with the sync path.
    Fix: move carry_extended_status to a crate-internal shared helper (e.g. src/kernel_error.rs or a new src/client/mod.rs entry) and call from both sea.rs::terminal_outcome AND
    executed_async.rs::from_sea_response::Failed + await_result's Cancelled arm.

  2. No wiremock test asserts content of extended fields on a FAILED body on either path — tests/v0_execute_wiremock.rs:625-636 (failed_body), tests/v0_async_execute_wiremock.rs:159-171
    The failed_body helpers only set error.error_code and error.message; no wiremock test populates display_message/diagnostic_info/error_details_json on a FAILED body and asserts the carry into
    err.display_message. The only sync test (executed_statement_surfaces_extended_status_fields) covers only SUCCEEDED. The live e2e at v0_execute_e2e.rs:823-825 only checks readability (let _: &Option =
    ...), not content. The sync-path P1 Initial import: Databricks ADBC Rust driver as databricks-sql-kernel #1 fix is therefore untested at the content level, and a future regression would slip through CI.
    Fix: add a failed_body_with_extended_fields helper, call execute(), and assert_eq!(err.display_message.as_deref(), Some("...")). Mirror on the async path (which will fail today per Initial import: Databricks ADBC Rust driver as databricks-sql-kernel #1).

P2

  1. Error struct lacks #[non_exhaustive] despite growing public fields — src/kernel_error.rs:150-226
    Explicitly NOT #[non_exhaustive] (documented at :44-49,142-149 as intentional). Adding 3 new public fields is technically a breaking change for any out-of-tree caller that constructs Error { ... } with a
    struct literal. In-tree nobody does this; downstream wrappers haven't been audited.
    Suggestion: add a CHANGELOG note for pyo3/napi consumers, OR add #[non_exhaustive] to the struct (the doc's "destructure with .." rationale still works on non-exhaustive structs from within the defining
    crate).

  2. TODO-only progress() accessor on napi Statement — napi/src/statement.rs:174-183
    TODO documents that SEA doesn't emit progress today. Pragmatic; not a defect.

  3. errorDetailsJson "gating doc" is documentation-only — src/kernel_error.rs:217-222, executed.rs:176-183, executed_async.rs:250-256, types/sea.rs:85-101, napi/statement.rs:227-232
    No Rust-side gating, no feature flag, no panic. Field is always readable; returns None for most workspaces because the server gates on spark.databricks.sql.errorDetailsJson.enabled. Empirical verification
    documented inline.

C. Final recommendation

REQUEST CHANGES. The rewrite is well-scoped and most of the new code is high-quality: kernel_error.rs cleanly adds 3 optional fields with no panics, executed_async.rs correctly mirrors the sync accessor
surface, the napi Thrift-parity envelope test is strong, the progress drop is surgical with a forward-compat serde test, and the polling-path wiremock test is exactly the regression guard requested. The
blocker is that prior P1 #1 is only half-closed: terminal_outcome carries the extended fields on the sync path but executed_async.rs::from_sea_response::Failed (and the Cancelled arm) duplicates the
error-building logic without invoking the carry, so the napi binding's documented "envelope carries displayMessage etc." contract silently breaks on the async path. The companion gap — no wiremock test
asserts content of the extended fields on a FAILED body on either path — means CI won't catch a regression. Both are mechanical fixes (extract carry_extended_status to a shared crate-internal helper, add one
FAILED-with-fields wiremock test per path); the rest of the PR is ready.

…r async error paths

Resolves the two merge-blockers from @gopalldb's follow-up review on PR #23
(issue comment #4556514565).

## NB1 — Lift `carry_extended_status` to a crate-internal shared helper

Prior to this commit, `carry_extended_status` lived as a private `fn` in
`src/client/sea.rs` and was reachable only from `terminal_outcome` (the
sync polling path). The async polling driver in
`src/statement/executed_async.rs` duplicated the Error-building logic
in two arms — `from_sea_response::Failed` and `await_result::Cancelled` —
without invoking the carry. The Thrift-parity contract documented at
`napi/src/error.rs` (the JS Error envelope surfaces
`displayMessage` / `diagnosticInfo` / `errorDetailsJson` on failure)
therefore broke silently on the async path: the kernel handle's
accessors (`async_exec.display_message()` etc.) returned the cached
field correctly because `record_latest_status` runs before
`from_sea_response`, but the `Error` returned from `status()` /
`await_result()` had those fields stripped. Symmetry across the two
kernel handles was broken, and any wrapper that read the `Error`
envelope (rather than re-reading from the handle) would lose the
fields silently.

The helper is now `pub(crate) fn carry_extended_status` in
`src/kernel_error.rs` next to the `extract_sqlstate_from_message`
fallback — same module, same shape, both pure SEA→`Error` carry
helpers. Three callsites are updated:

  - `src/client/sea.rs::terminal_outcome` Failed / Canceled /
    Closed-no-data arms (already wired; now reaches through the
    new path)
  - `src/statement/executed_async.rs::from_sea_response::Failed`
    (newly wired — the symmetry fix)
  - `src/statement/executed_async.rs::await_result::Cancelled`
    (newly wired — also gains `with_query_id` for parity with the
    sync `terminal_outcome::Canceled` arm)

## NB2 — Wiremock content-assertions on FAILED bodies for both paths

Prior to this commit, the existing `failed_body` helpers in both
wiremock test files set only `error.error_code` and `error.message`.
No test populated `display_message` / `diagnostic_info` /
`error_details_json` on a FAILED body and asserted that the kernel
`Error` returned from `execute()` / `await_result()` carried those
values. A future regression in `carry_extended_status` wiring would
slip through CI.

Two new test helpers (`failed_body_with_extended_fields` in each
wiremock file, plus `cancelled_body_with_extended_fields` in the
async file) inject all three fields. Three new tests pin the
content-assertion contract:

  - `execute_failed_carries_extended_status_fields_onto_error`
    (sync, in tests/v0_execute_wiremock.rs)
  - `async_await_result_failed_carries_extended_status_fields_onto_error`
    (async, in tests/v0_async_execute_wiremock.rs) — this WOULD HAVE
    FAILED before NB1's fix and is the regression guard
  - `async_await_result_cancelled_carries_extended_status_fields_onto_error`
    (async Cancelled arm)

## NB3 — Acknowledged

Reviewer's #[non_exhaustive]-on-Error question is a defensible
either-way call (the existing kernel_error.rs:142-149 doc explicitly
calls out the pattern-matching trade-off). Deferring to the reviewer's
preference on the PR thread reply.

## Gates

- `cargo +stable fmt --all -- --check` — exit 0
- `cargo clippy --all-targets -- -D warnings` — exit 0 (kernel + napi)
- `cargo test --lib` — 453 / 453 passing
- `cargo test --test v0_execute_wiremock` — 16 / 16 passing
  (1 new test: `execute_failed_carries_extended_status_fields_onto_error`)
- `cargo test --test v0_async_execute_wiremock` — 16 / 16 passing
  (2 new tests: failed + cancelled content-assertion)
- napi `cargo test --lib` — 26 / 26 passing
- pyo3 `cargo build` — clean (untouched)
- Live pecotesting e2e (TOKEN_PERSONAL): sync + async tests pass

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

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough follow-up — both blockers are mechanical fixes, addressed in commit 38ab40d.

NB1 — Async error path now carries extended status fields

Lifted carry_extended_status out of src/client/sea.rs (it was a private fn) and into src/kernel_error.rs as pub(crate) fn carry_extended_status(error, &SeaStatementStatus) -> Error — same module as extract_sqlstate_from_message, same shape, both pure SEA→Error carry helpers.

Three callsites are now wired through the shared helper:

  • src/client/sea.rs::terminal_outcome — Failed / Canceled / Closed-no-data arms (already wired before, now routes through the new path).
  • src/statement/executed_async.rs::from_sea_response::Failed — newly wired (this was the symmetry break).
  • src/statement/executed_async.rs::await_result::Cancelled — newly wired; also gains with_query_id for parity with the sync terminal_outcome::Canceled arm.

NB2 — Wiremock content-assertions on FAILED bodies for both paths

New test helpers (failed_body_with_extended_fields in both wiremock files, plus cancelled_body_with_extended_fields in the async file) inject display_message / diagnostic_info / error_details_json on a FAILED/CANCELED wire body. Three new tests pin the content-assertion contract:

  • execute_failed_carries_extended_status_fields_onto_error — sync polling path (tests/v0_execute_wiremock.rs).
  • async_await_result_failed_carries_extended_status_fields_onto_error — async polling path. This test would have FAILED before NB1's fix. It's the regression guard.
  • async_await_result_cancelled_carries_extended_status_fields_onto_error — async Cancelled arm.

NB3 — #[non_exhaustive] on Error

Defensible either way; I'd lean toward leaving as-is for the reason in the existing doc at kernel_error.rs:142-149 (the pattern-matching ergonomic the kernel deliberately preserves for wrappers writing host-language exception adapters). But if your strong preference is the #[non_exhaustive] marker, I'll add it — the doc's ..-with-#[non_exhaustive] rationale still works for in-crate code as you noted. Let me know.

Gates (all green on 38ab40d)

  • cargo +stable fmt --all -- --check — exit 0
  • cargo clippy --all-targets -- -D warnings — exit 0 (kernel + napi)
  • cargo test --lib — 453 / 453 passing
  • cargo test --test v0_execute_wiremock — 16 / 16 (1 new test)
  • cargo test --test v0_async_execute_wiremock — 16 / 16 (2 new tests)
  • napi cargo test --lib — 26 / 26 passing
  • pyo3 cargo build — clean (untouched)
  • Live pecotesting e2e via TOKEN_PERSONAL — sync + async tests pass

@gopalldb

Copy link
Copy Markdown
Collaborator
  1. Unbounded errorDetailsJson flows through napi error envelope without truncation
  • napi/src/error.rs:158-160 — envelope inserts errorDetailsJson verbatim via Value::from(ej). Kernel docstring already warns it can be multi-MB; the napi binding is the wrapper that's supposed to enforce
    truncation. On workspaces with spark.databricks.sql.errorDetailsJson.enabled=true, every failed statement could push a multi-MB string into Error.message allocation.
  • Fix: truncate at the envelope boundary (e.g. 64 KB prefix + "... truncated") — matches the redacting Debug impl that's already in the kernel.
  1. Cancelled message text diverges between sync and async paths
  • Sync (src/client/sea.rs:243): "Statement was canceled" (one l, no id)
  • Async (src/statement/executed_async.rs:384): "Statement {id} was cancelled" (two l's, with id)
  • The PR's docs advertise "identical envelope across handles" but Error.message differs. The wiremock test happens to match on "cancelled", masking the divergence.
  • Fix: pick one spelling (SEA protocol uses Canceled — one l), mirror on both paths, update tests.

P2 — Minor (defer if you like)

  • Async-handle initial-Failed-status case undocumented (executed_async.rs:222-277) — submit() doesn't error on a Failed initial response; accessors can return populated server text from a handle that hasn't
    surfaced any Err yet. Add a sentence.
  • Concurrent status() / await_result() callers can stash a stale poll (executed_async.rs:287-291) — writes aren't ordered by wire-response time. Mostly cosmetic; either document the actual contract or add an
    observation epoch.
  • Multi-MB StatementStatus cloned every poll (executed_async.rs:309, 364) — response.status.clone() copies the full struct. Use std::mem::replace after destructuring, or wrap in Arc.
  • from_pem_bundle error reporting (client/http.rs:291-294, 319-324) — short-circuits on first bad cert without saying which cert index failed. Harder to debug corporate-CA chain issues. Defer.
  • StatementStatus::Cancelled doesn't carry the Error directly (executed_async.rs:88, 376-389) — Failed(Error) carries extended fields, Cancelled is bare. Asymmetric. Document or unify in a follow-up
    (changing variant shape is a public-API break).

@gopalldb gopalldb left a comment

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.

Some minor comments

@msrathore-db
msrathore-db merged commit 1ffc72f into main May 29, 2026
msrathore-db added a commit that referenced this pull request Jun 1, 2026
Rebasing the metadata-methods work onto main surfaced a clean conflict:
main's status accessors (num_modified_rows / display_message /
diagnostic_info / error_details_json, merged via PR #23) read
`inner_state.executed` directly, but the metadata work wraps the
Statement inner in an `AnyInner::{Executed, Metadata}` enum (the
Metadata variant holds a bare ResultStream from `Metadata::list_*`).

Match on the enum: the Executed variant delegates to the executed
handle as before; the Metadata variant returns None — metadata result
streams carry no operation-status fields.

Co-authored-by: Isaac
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