From 90a40663fd77f6df7cc888dc6d8970bfb22a516e Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sat, 16 May 2026 13:54:26 +0000 Subject: [PATCH 1/7] krn-tls-public-api: expose TlsConfig fields + stop discarding in session.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) 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 ("") 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 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 --- src/client/http.rs | 133 +++++++++++++++++++++++++++++++++++++++++++++ src/config.rs | 89 ++++++++++++++++++++++++++++-- src/session.rs | 15 +++-- 3 files changed, 224 insertions(+), 13 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 3bc4a8bb..a074dcdb 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -93,6 +93,42 @@ pub struct TlsConfig { pub allow_hostname_mismatch: Option, /// Path to a PEM-encoded CA certificate file to add to the trust store. pub trusted_certificate_path: Option, + /// PEM-encoded CA certificate bytes to add to the trust store. + /// Alternative to `trusted_certificate_path` for callers that + /// have the cert in-memory (e.g. foreign-language wrappers + /// passing `Buffer` / `bytes` without a tempfile shim). When + /// both are set, the path is read first, then the in-memory PEM + /// is added as an additional root. + pub trusted_certificate_pem: Option>, +} + +impl TlsConfig { + /// Project the public [`crate::config::TlsConfig`] onto the internal + /// HTTP-client TLS struct. Public fields land on their internal + /// counterparts; internal-only fields (`enabled`, + /// `trusted_certificate_path`) stay at their defaults. + /// + /// `accept_self_signed` / `skip_hostname_verification` are booleans + /// on the public surface (default: stricter); the internal layer + /// uses `Option` so the existing `None == default` semantics + /// are preserved. We map a `false` to `None` rather than + /// `Some(false)` to keep `Debug` output / RUST_LOG noise free of + /// no-op overrides. + pub fn from_public(cfg: &crate::config::TlsConfig) -> Self { + Self { + enabled: None, + allow_self_signed: cfg.accept_self_signed.then_some(true), + allow_hostname_mismatch: cfg.skip_hostname_verification.then_some(true), + trusted_certificate_path: None, + trusted_certificate_pem: cfg.custom_ca_cert.clone(), + } + } +} + +impl From<&crate::config::TlsConfig> for TlsConfig { + fn from(cfg: &crate::config::TlsConfig) -> Self { + Self::from_public(cfg) + } } /// Configuration for the HTTP client. @@ -213,6 +249,18 @@ impl DatabricksHttpClient { debug!("Added custom CA certificate from: {}", cert_path); } + if let Some(ref pem) = config.tls.trusted_certificate_pem { + let cert = reqwest::Certificate::from_pem(pem).map_err(|e| { + Error::invalid_argument() + .message(format!("Invalid in-memory PEM certificate: {}", e)) + })?; + builder = builder.add_root_certificate(cert); + debug!( + "Added custom CA certificate from in-memory bytes ({} bytes)", + pem.len() + ); + } + // Apply proxy configuration if let Some(ref proxy_url) = config.proxy.url { // Validate proxy URL scheme @@ -811,6 +859,91 @@ lGrv15pBcePj assert!(err_msg.contains("Invalid PEM certificate")); } + #[test] + fn test_http_client_with_in_memory_pem_bytes() { + // Public-API path: PEM bytes pass through the internal + // `trusted_certificate_pem` field directly (no tempfile shim + // required by foreign-language wrappers). + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(TEST_CA_CERT_PEM.as_bytes().to_vec()); + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!(client.is_ok()); + } + + #[test] + fn test_tls_config_from_public_maps_all_fields() { + // accept_self_signed=true maps to Some(true); + // skip_hostname_verification=true maps to Some(true); + // custom_ca_cert maps to trusted_certificate_pem. + let public = crate::config::TlsConfig { + custom_ca_cert: Some(b"pem-bytes".to_vec()), + accept_self_signed: true, + skip_hostname_verification: true, + }; + let internal = TlsConfig::from_public(&public); + assert_eq!(internal.allow_self_signed, Some(true)); + assert_eq!(internal.allow_hostname_mismatch, Some(true)); + assert_eq!( + internal.trusted_certificate_pem, + Some(b"pem-bytes".to_vec()) + ); + // `enabled` and `trusted_certificate_path` stay at internal + // defaults — the public surface doesn't expose them. + assert!(internal.enabled.is_none()); + assert!(internal.trusted_certificate_path.is_none()); + } + + #[test] + fn test_tls_config_from_public_default_is_strict() { + // A default public TlsConfig produces an internal config that + // does NOT relax any default — `None` everywhere on the + // permissive switches so log output stays clean. + let internal = TlsConfig::from_public(&crate::config::TlsConfig::default()); + assert!(internal.allow_self_signed.is_none()); + assert!(internal.allow_hostname_mismatch.is_none()); + assert!(internal.trusted_certificate_pem.is_none()); + assert!(internal.trusted_certificate_path.is_none()); + } + + #[test] + fn test_http_client_via_public_tls_config_with_self_signed_accepts_build() { + // End-to-end builder check: a Session-style construction + // (public TlsConfig -> from_public -> HttpClientConfig -> + // reqwest builder) succeeds when accept_self_signed is set. + let public = crate::config::TlsConfig { + custom_ca_cert: None, + accept_self_signed: true, + skip_hostname_verification: false, + }; + let config = HttpClientConfig { + tls: TlsConfig::from_public(&public), + ..HttpClientConfig::default() + }; + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!( + client.is_ok(), + "reqwest client construction should succeed when accept_self_signed=true is set" + ); + } + + #[test] + fn test_http_client_via_public_tls_config_with_custom_ca_accepts_build() { + let public = crate::config::TlsConfig { + custom_ca_cert: Some(TEST_CA_CERT_PEM.as_bytes().to_vec()), + accept_self_signed: false, + skip_hostname_verification: false, + }; + let config = HttpClientConfig { + tls: TlsConfig::from_public(&public), + ..HttpClientConfig::default() + }; + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!( + client.is_ok(), + "reqwest client construction should succeed when custom_ca_cert is set with a valid PEM" + ); + } + #[test] fn test_proxy_config_debug_redacts_password() { let config = ProxyConfig { diff --git a/src/config.rs b/src/config.rs index 288e8d61..58048c11 100644 --- a/src/config.rs +++ b/src/config.rs @@ -343,13 +343,64 @@ impl Default for HttpConfig { #[derive(Debug, Clone, Default)] pub struct ProxyConfig {} -// ─── TLS (reserved) ───────────────────────────────────────────────────────── +// ─── TLS ──────────────────────────────────────────────────────────────────── -/// Reserved for v0.1. Fields land once the TLS story (custom CA bundles, -/// cert pinning, FIPS mode) is settled. +/// TLS settings for the HTTP client. +/// +/// All defaults match the most secure stance: validate the system trust +/// store, require a valid certificate chain, and verify hostnames. Any +/// non-default field is a *relaxation* — flip these for dev / on-prem +/// boxes with self-signed certs, never against production. +/// +/// The kernel exposes only fields that the internal rustls plumbing +/// already supports — cert pinning and FIPS mode are *not* in scope. #[non_exhaustive] -#[derive(Debug, Clone, Default)] -pub struct TlsConfig {} +#[derive(Clone, Default)] +pub struct TlsConfig { + /// PEM-encoded CA certificate bytes to add to the trust store on + /// top of the system roots. Use this when connecting through a + /// corporate proxy that re-signs TLS or to an on-prem Databricks + /// deployment using an internal CA. + /// + /// Carrying bytes (rather than a path) keeps the surface friendly + /// for foreign-language wrappers — napi-rs / pyo3 callers pass a + /// `Buffer` / `bytes` directly without needing to materialise a + /// tempfile. + pub custom_ca_cert: Option>, + + /// Accept self-signed server certificates. + /// + /// Note: the underlying reqwest backend does not distinguish + /// "self-signed only" from "fully unvalidated" — setting this to + /// `true` disables ALL chain validation (CA trust, expiration, + /// etc.) via `danger_accept_invalid_certs(true)`. Use only in + /// development. + pub accept_self_signed: bool, + + /// Skip the certificate-hostname-vs-SNI match check. Use only + /// when connecting via an IP literal or a hostname the cert + /// wasn't issued for in a development / lab environment. + pub skip_hostname_verification: bool, +} + +impl std::fmt::Debug for TlsConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TlsConfig") + .field( + "custom_ca_cert", + &self + .custom_ca_cert + .as_ref() + .map(|b| format!("<{} bytes>", b.len())), + ) + .field("accept_self_signed", &self.accept_self_signed) + .field( + "skip_hostname_verification", + &self.skip_hostname_verification, + ) + .finish() + } +} // ─── Result management (CloudFetch + future result knobs) ─────────────────── @@ -640,4 +691,32 @@ mod tests { assert!(s.contains("")); assert!(s.contains("databricks")); } + + // ─── TlsConfig ───────────────────────────────────────────────── + + #[test] + fn tls_config_default_is_strict() { + let tls = TlsConfig::default(); + assert!(tls.custom_ca_cert.is_none()); + assert!(!tls.accept_self_signed); + assert!(!tls.skip_hostname_verification); + } + + #[test] + fn tls_config_debug_redacts_ca_cert_bytes() { + // The PEM bytes themselves aren't secret, but a multi-kB blob + // in every log line is unhelpful — Debug should summarise. + let tls = TlsConfig { + custom_ca_cert: Some(b"-----BEGIN CERTIFICATE-----...".to_vec()), + accept_self_signed: false, + skip_hostname_verification: false, + }; + let s = format!("{tls:?}"); + assert!(s.contains("<"), "expected byte-count summary, got: {s}"); + assert!( + s.contains("bytes>"), + "expected byte-count summary, got: {s}" + ); + assert!(!s.contains("BEGIN CERTIFICATE"), "raw bytes leaked: {s}"); + } } diff --git a/src/session.rs b/src/session.rs index f630d06a..fd2be786 100644 --- a/src/session.rs +++ b/src/session.rs @@ -518,11 +518,11 @@ impl SessionBuilder { /// Translate the public [`HttpConfig`] (+ proxy / TLS / org_id) into /// the internal [`HttpClientConfig`] the HTTP client expects. /// -/// v0's [`ProxyConfig`] and [`TlsConfig`] are empty `#[non_exhaustive]` -/// reservation structs — they don't carry fields yet. We pass through -/// the internal [`HttpProxyConfig::default`] / [`HttpTlsConfig::default`] -/// for now; PR follow-ups will wire the real fields when the v0 -/// proxy/TLS shape lands. +/// The public [`ProxyConfig`] is still a reserved `#[non_exhaustive]` +/// struct (no fields wired yet); the public [`TlsConfig`] now carries +/// `custom_ca_cert` / `accept_self_signed` / +/// `skip_hostname_verification` and is projected onto the internal +/// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`]. fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { let mut hcc = HttpClientConfig { connect_timeout: Duration::from_secs(30), @@ -531,15 +531,14 @@ fn build_http_client_config(config: &SessionConfig, org_id: Option) -> H read_timeout: config.http.request_timeout, max_connections_per_host: config.http.pool_max_idle_per_host, proxy: HttpProxyConfig::default(), - tls: HttpTlsConfig::default(), + tls: HttpTlsConfig::from_public(&config.tls), org_id, ..HttpClientConfig::default() }; - // Touch the v0 reserved configs so a future field addition + // Touch the still-reserved proxy config so a future field addition // (without setting it through here) shows up as a compile error // rather than a silently-dropped option. let ProxyConfig { .. } = config.proxy.clone().unwrap_or_default(); - let TlsConfig { .. } = config.tls.clone(); let _ = &mut hcc; hcc } From f2af099a064268dc8db28dd44c1eb872f6951554 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sat, 16 May 2026 13:44:11 +0000 Subject: [PATCH 2/7] krn-status-fields: expose 5 status accessors on ExecutedStatement 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 --- src/client/sea.rs | 14 +-- src/client/transport.rs | 34 +++--- src/reader/cloudfetch/link_fetcher.rs | 12 ++- src/statement/executed.rs | 44 ++++++++ src/statement/mutable.rs | 3 +- src/types/sea.rs | 74 +++++++++++++ tests/v0_execute_wiremock.rs | 145 ++++++++++++++++++++++++++ 7 files changed, 303 insertions(+), 23 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 0dd732cd..8dd0f015 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -381,15 +381,16 @@ impl SeaRestTransport { .create_reader(&response.statement_id, &response) .await?; - // `server_state` carries the terminal state forward so the - // executed handle can skip a redundant CloseStatement when - // the server already cleaned up (state=Closed). - let server_state = response.status.state; + // The full `status` is carried forward so the executed handle + // can skip a redundant CloseStatement when the server already + // cleaned up (status.state=Closed) AND expose + // num_modified_rows / progress / etc. without a second + // GetStatementStatus round-trip. Ok(ExecuteResult { statement_id: response.statement_id, reader, manifest: response.manifest, - server_state, + status: response.status, }) } } @@ -533,12 +534,11 @@ impl Transport for SeaRestTransport { StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; let reader = reader_factory.create_reader(&r.statement_id, &r).await?; - let server_state = r.status.state; Ok(Some(ExecuteResult { statement_id: r.statement_id, reader, manifest: r.manifest, - server_state, + status: r.status, })) } StatementOutcome::NotReady(_) => Ok(None), diff --git a/src/client/transport.rs b/src/client/transport.rs index 85e1257e..b5837007 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -27,7 +27,7 @@ use crate::kernel_error::Result; use crate::reader::ResultReader; use crate::types::cloudfetch::CloudFetchLink; -use crate::types::sea::{ExecuteParams, ResultManifest, StatementState, StatementStatus}; +use crate::types::sea::{ExecuteParams, ResultManifest, StatementStatus}; use async_trait::async_trait; use std::collections::HashMap; use std::time::Duration; @@ -67,22 +67,30 @@ pub(crate) struct SessionInfo { /// Result from [`Transport::execute_statement`]. Contains the /// statement ID (for cancellation/cleanup), a reader over the result -/// data, and optionally the SEA manifest for metadata propagation. +/// data, optionally the SEA manifest for metadata propagation, and +/// the terminal `StatementStatus` so callers can surface +/// `num_modified_rows` / `progress` / etc. without a second +/// GetStatementStatus round-trip. pub(crate) struct ExecuteResult { pub statement_id: String, pub reader: Box, pub manifest: Option, - /// Terminal state the server reported in its final response. - /// `Closed` means the server has already cleaned up the - /// statement on its end — the kernel must NOT issue a + /// Terminal status the server reported in its final response. + /// + /// `status.state == Closed` means the server has already cleaned + /// up the statement on its end — the kernel must NOT issue a /// separate `CloseStatement` for it (the server returns 404 - /// `STATEMENT_NOT_FOUND` on such redundant closes). This is - /// the common case when the kernel omits `wait_timeout` from - /// the execute request: the server holds the connection for - /// its default wait, returns inline data with `state=CLOSED`, - /// and is done. Setting a concrete `wait_timeout` yields - /// `Succeeded` instead and requires an explicit close. - pub server_state: StatementState, + /// `STATEMENT_NOT_FOUND` on such redundant closes). This is the + /// common case when the kernel omits `wait_timeout` from the + /// execute request: the server holds the connection for its + /// default wait, returns inline data with `state=CLOSED`, and is + /// done. Setting a concrete `wait_timeout` yields `Succeeded` + /// instead and requires an explicit close. + /// + /// The full status is carried (not just the state) so the + /// `ExecutedStatement` can expose `num_modified_rows` / `progress` + /// / etc. without a second GetStatementStatus round-trip. + pub status: StatementStatus, } impl std::fmt::Debug for ExecuteResult { @@ -91,7 +99,7 @@ impl std::fmt::Debug for ExecuteResult { .field("statement_id", &self.statement_id) .field("reader", &"") .field("manifest", &self.manifest) - .field("server_state", &self.server_state) + .field("status", &self.status) .finish() } } diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 8aacaf74..29f7df0f 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -547,7 +547,7 @@ mod tests { use super::*; use crate::client::{ExecuteResult, SessionInfo}; use crate::reader::EmptyReader; - use crate::types::sea::{ExecuteParams, StatementState}; + use crate::types::sea::{ExecuteParams, StatementState, StatementStatus}; use arrow_schema::Schema; use std::collections::HashMap; use std::sync::Arc as StdArc; @@ -591,7 +591,15 @@ mod tests { statement_id: "mock-statement".to_string(), reader: Box::new(EmptyReader::new(StdArc::new(Schema::empty()))), manifest: None, - server_state: StatementState::Succeeded, + status: StatementStatus { + state: StatementState::Succeeded, + error: None, + num_modified_rows: None, + progress: None, + display_message: None, + diagnostic_info: None, + error_details_json: None, + }, }) } diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 0213dacd..087a1a15 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -33,6 +33,7 @@ use crate::result_stream::{ResultStream, SchemaRef}; use crate::session::SessionInner; use crate::statement::handle::ExecutedStatementHandle; use crate::statement::validity::ValidityFlag; +use crate::types::sea::StatementStatus as SeaStatementStatus; use async_trait::async_trait; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -47,6 +48,11 @@ pub struct ExecutedStatement { /// stale calls locally with no network round-trip. valid: ValidityFlag, result_stream: ResultStream, + /// Terminal SEA `StatementStatus` captured at construction. + /// Kept as the wire-shape struct so the accessor methods can + /// hand back individual fields without re-querying the server. + /// Mutated only at construction; no interior mutability. + status: SeaStatementStatus, /// Flips to `true` after the first successful (or the first /// duplicate-call short-circuited) `close()`. Tells `Drop` to /// skip its fire-and-forget cleanup so an explicit close @@ -69,6 +75,7 @@ impl ExecutedStatement { valid: ValidityFlag, result_stream: ResultStream, closed: Arc, + status: SeaStatementStatus, ) -> Self { Self { session, @@ -76,6 +83,7 @@ impl ExecutedStatement { valid, result_stream, closed, + status, } } @@ -101,6 +109,42 @@ impl ExecutedStatement { pub fn result_stream_mut(&mut self) -> &mut ResultStream { &mut self.result_stream } + + /// Rows modified by the statement (UPDATE / INSERT / DELETE / + /// MERGE). Absent for SELECT and on warehouses that don't surface + /// the counter. + pub fn num_modified_rows(&self) -> Option { + self.status.num_modified_rows + } + + /// 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 { + self.status.progress + } + + /// Server-supplied user-facing message. Distinct from the + /// `error.message` carried inside `Failed` — populated on + /// non-error states too (e.g. cancellation reasons, progress + /// hints). + pub fn display_message(&self) -> Option<&str> { + self.status.display_message.as_deref() + } + + /// Server-supplied diagnostic detail — multi-line text with + /// stack frames or operator context. Intended for log / support + /// surfaces; not user-facing. + pub fn diagnostic_info(&self) -> Option<&str> { + self.status.diagnostic_info.as_deref() + } + + /// Server-supplied JSON blob with extended error details. + /// Pass-through string — wrappers parse if they need structured + /// access. + pub fn error_details_json(&self) -> Option<&str> { + self.status.error_details_json.as_deref() + } } #[async_trait] diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index cb48b5c6..7f43c106 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -170,7 +170,7 @@ impl Statement { // path. See `prepare_for_dispatch` for why omitting // `wait_timeout` typically yields `Closed` on the inline-result // fast path. - let already_closed = result.server_state == StatementState::Closed; + let already_closed = result.status.state == StatementState::Closed; let closed = Arc::new(AtomicBool::new(already_closed)); self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); @@ -183,6 +183,7 @@ impl Statement { valid, result_stream, closed, + result.status, )) } .instrument(span) diff --git a/src/types/sea.rs b/src/types/sea.rs index 294113e9..fc79392a 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -38,6 +38,30 @@ pub struct StatementStatus { pub state: StatementState, #[serde(default)] pub error: Option, + /// Number of rows modified by the statement (UPDATE / INSERT / + /// DELETE / MERGE). Absent on SELECT and on warehouses that don't + /// surface the counter. + #[serde(default)] + pub num_modified_rows: Option, + /// Fractional completion in `[0.0, 1.0]`. Populated on analytics + /// warehouses; absent (or always 1.0 on terminal) elsewhere. + #[serde(default)] + pub progress: Option, + /// Server-supplied user-facing message (e.g. "Statement was + /// canceled by the user" or progress hints). Distinct from + /// `error.message`; populated on non-error states too. + #[serde(default)] + pub display_message: Option, + /// Server-supplied diagnostic detail — multi-line text with + /// stack frames or operator context. Intended for log / support + /// surfaces, not user-facing strings. + #[serde(default)] + pub diagnostic_info: Option, + /// Server-supplied JSON blob with extended error details. + /// Pass-through string — wrappers parse if they need structured + /// access. + #[serde(default)] + pub error_details_json: Option, } /// Possible states of a statement during execution. @@ -503,6 +527,56 @@ mod tests { assert_eq!(manifest.total_row_count, Some(0)); } + #[test] + fn test_statement_status_with_extended_fields() { + // SEA response with all five extended status fields populated. + let json = r#"{ + "statement_id": "stmt-extended", + "status": { + "state": "SUCCEEDED", + "num_modified_rows": 42, + "progress": 0.875, + "display_message": "Statement completed", + "diagnostic_info": "operator=Scan; rows=42", + "error_details_json": "{\"trace\":\"...\"}" + } + }"#; + + let response: StatementExecutionResponse = serde_json::from_str(json).unwrap(); + assert_eq!(response.status.state, StatementState::Succeeded); + assert_eq!(response.status.num_modified_rows, Some(42)); + assert_eq!(response.status.progress, Some(0.875)); + assert_eq!( + response.status.display_message, + Some("Statement completed".to_string()) + ); + assert_eq!( + response.status.diagnostic_info, + Some("operator=Scan; rows=42".to_string()) + ); + assert_eq!( + response.status.error_details_json, + Some(r#"{"trace":"..."}"#.to_string()) + ); + } + + #[test] + fn test_statement_status_extended_fields_absent() { + // Minimal SEA response — extended fields are optional and + // default to None when the server omits them. + let json = r#"{ + "statement_id": "stmt-min", + "status": { "state": "SUCCEEDED" } + }"#; + + let response: StatementExecutionResponse = serde_json::from_str(json).unwrap(); + assert_eq!(response.status.num_modified_rows, None); + assert_eq!(response.status.progress, None); + assert_eq!(response.status.display_message, None); + assert_eq!(response.status.diagnostic_info, None); + assert_eq!(response.status.error_details_json, None); + } + #[test] fn test_column_info_with_interval_type() { let json = r#"{ diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index fcab664f..5d7eb8c1 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -593,3 +593,148 @@ async fn kernel_invariant_parent_drop_invalidates_executed_cancel() { .expect_err("cancel after parent Statement drop must short-circuit"); assert_eq!(err.code, ErrorCode::InvalidStatementHandle); } + +// ─── ExecutedStatement extended status accessors (PR #23) ───────── + +/// Build a SEA `SUCCEEDED` body with the 5 extended status fields +/// populated. Mirrors `succeeded_inline_body` but injects status +/// fields the kernel surfaces via `ExecutedStatement::*` getters. +#[allow(clippy::too_many_arguments)] +fn succeeded_inline_body_with_status( + statement_id: &str, + batch: &RecordBatch, + num_modified_rows: Option, + progress: Option, + display_message: Option<&str>, + diagnostic_info: Option<&str>, + error_details_json: Option<&str>, +) -> String { + let ipc = arrow_ipc_bytes(batch); + let attachment = STANDARD.encode(&ipc); + let columns: Vec<_> = batch + .schema() + .fields() + .iter() + .enumerate() + .map(|(i, f)| { + json!({ + "name": f.name(), + "type_name": match f.data_type() { + DataType::Int64 => "BIGINT", + DataType::Utf8 => "STRING", + _ => "STRING", + }, + "type_text": match f.data_type() { + DataType::Int64 => "BIGINT", + DataType::Utf8 => "STRING", + _ => "STRING", + }, + "position": i as i32, + }) + }) + .collect(); + + let mut status = json!({ "state": "SUCCEEDED" }); + let status_obj = status.as_object_mut().unwrap(); + if let Some(n) = num_modified_rows { + status_obj.insert("num_modified_rows".to_string(), json!(n)); + } + if let Some(p) = progress { + status_obj.insert("progress".to_string(), json!(p)); + } + if let Some(m) = display_message { + status_obj.insert("display_message".to_string(), json!(m)); + } + if let Some(d) = diagnostic_info { + status_obj.insert("diagnostic_info".to_string(), json!(d)); + } + if let Some(e) = error_details_json { + status_obj.insert("error_details_json".to_string(), json!(e)); + } + + json!({ + "statement_id": statement_id, + "status": status, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": batch.num_columns() as i32, + "columns": columns, + }, + "total_chunk_count": 1, + "total_row_count": batch.num_rows() as i64, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows() as i64, + "byte_count": ipc.len() as i64, + "attachment": attachment, + }, + }) + .to_string() +} + +#[tokio::test] +async fn executed_statement_surfaces_extended_status_fields() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("n", vec![1]); + mount_execute( + &server, + succeeded_inline_body_with_status( + "stmt-status", + &batch, + Some(7), + Some(1.0), + Some("All good"), + Some("operator=Scan"), + Some(r#"{"k":"v"}"#), + ), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("UPDATE t SET x = 1"); + let exec = stmt.execute().await.expect("execute"); + + assert_eq!(exec.num_modified_rows(), Some(7)); + assert_eq!(exec.progress(), Some(1.0)); + assert_eq!(exec.display_message(), Some("All good")); + assert_eq!(exec.diagnostic_info(), Some("operator=Scan")); + assert_eq!(exec.error_details_json(), Some(r#"{"k":"v"}"#)); + + exec.close().await.expect("close"); +} + +#[tokio::test] +async fn executed_statement_status_fields_default_to_none() { + // When the server omits the extended fields (the common case for + // SELECT on classic warehouses), all five accessors return None. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("n", vec![1]); + mount_execute(&server, succeeded_inline_body("stmt-empty-status", &batch)).await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let exec = stmt.execute().await.expect("execute"); + + assert_eq!(exec.num_modified_rows(), None); + assert_eq!(exec.progress(), None); + assert_eq!(exec.display_message(), None); + assert_eq!(exec.diagnostic_info(), None); + assert_eq!(exec.error_details_json(), None); + + exec.close().await.expect("close"); +} From 10a852e2f4733000ac9f8f13f2ec515efece5f65 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 27 May 2026 10:07:52 +0000 Subject: [PATCH 3/7] krn-status-fields: review fixes + napi Thrift-parity surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 `` 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>` 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 --- napi/src/error.rs | 148 ++++++++++++++++++++++----- napi/src/statement.rs | 100 +++++++++++++++++++ src/client/http.rs | 171 ++++++++++++++++++++++++++------ src/client/sea.rs | 39 +++++++- src/config.rs | 32 +++++- src/kernel_error.rs | 57 +++++++++++ src/session.rs | 25 ++++- src/statement/executed.rs | 48 +++++++-- src/statement/executed_async.rs | 25 +++++ src/types/sea.rs | 41 +++++++- tests/v0_execute_e2e.rs | 88 ++++++++++++++++ 11 files changed, 695 insertions(+), 79 deletions(-) diff --git a/napi/src/error.rs b/napi/src/error.rs index 3467d247..afd5c3bc 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -76,13 +76,20 @@ use serde_json::{json, Map, Value}; pub(crate) const ERROR_SENTINEL: &str = "__databricks_error__:"; /// Map a kernel [`Error`] into a `napi::Error`. Preserves the kernel -/// `ErrorCode` (mapped to the closest napi `Status`), and stuffs eight -/// of the ten structured kernel-`Error` fields (`code`, `message`, -/// `sql_state`, `error_code`, `vendor_code`, `http_status`, `retryable`, -/// `query_id`) into a JSON envelope on the reason so the TS layer can -/// reconstruct the typed error class. `location` and `cause` are -/// intentionally omitted from the v1 envelope — see the module-level -/// doc for rationale. +/// `ErrorCode` (mapped to the closest napi `Status`), and stuffs the +/// structured kernel-`Error` fields into a JSON envelope on the reason +/// so the TS layer can reconstruct the typed error class. `location` +/// and `cause` are intentionally omitted from the v1 envelope — see +/// the module-level doc for rationale. +/// +/// **Wire-shape superset of pyo3 for Thrift parity:** the envelope +/// also carries `displayMessage` / `diagnosticInfo` / `errorDetailsJson` +/// — the three SEA extended-status fields that ride on the wire across +/// terminal-error states. These mirror the same-named fields on the +/// NodeJS Thrift driver's `TGetOperationStatusResp`, so JS callers +/// migrating from Thrift to the SEA-backed binding see the same field +/// set on a failed statement. The pyo3 binding does NOT (yet) attach +/// these — pyo3's `attach_attrs` stays at the original 8 fields. /// /// The whole JSON-envelope-on-`reason` scheme is interim. The follow-up /// PR that lands the first `#[napi]` entry points (PR #25) is expected @@ -136,6 +143,21 @@ pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { if let Some(qid) = e.query_id { obj.insert("queryId".to_owned(), Value::from(qid)); } + // Thrift-parity extended status fields: surfaced on the napi + // envelope so a JS caller's catch-block sees the same fields the + // Thrift driver's `TGetOperationStatusResp` exposes. Only + // populated on terminal-error states (`FAILED` / `CANCELED` / + // `CLOSED-no-data`) — the kernel's + // `terminal_outcome::carry_extended_status` is the upstream. + if let Some(dm) = e.display_message { + obj.insert("displayMessage".to_owned(), Value::from(dm)); + } + if let Some(di) = e.diagnostic_info { + obj.insert("diagnosticInfo".to_owned(), Value::from(di)); + } + if let Some(ej) = e.error_details_json { + obj.insert("errorDetailsJson".to_owned(), Value::from(ej)); + } // `to_string` on a JSON object is infallible: every field above is // a `String` / `i64` / `u16` / `bool` whose serialization can't fail. @@ -291,21 +313,26 @@ mod tests { ); } - /// Parity guard: the napi envelope must surface the same kernel + /// Parity guard: the napi envelope must carry the same kernel /// `Error` field set that pyo3's typed `KernelError` exposes via /// `setattr`. The two bindings diverge on *wire mechanism* (typed /// exception attrs vs JSON envelope) and on *naming convention* - /// (snake_case attrs in pyo3 vs camelCase JSON keys in napi) — but - /// the *field set* must stay aligned or downstream wrappers that - /// claim Python ↔ Node parity will silently drop information when - /// crossing the language boundary. + /// (snake_case attrs in pyo3 vs camelCase JSON keys in napi). + /// + /// **Thrift-parity superset.** The napi envelope is a strict + /// superset of pyo3's field set: it adds `displayMessage` / + /// `diagnosticInfo` / `errorDetailsJson` so JS consumers see the + /// same fields the NodeJS Thrift driver's `TGetOperationStatusResp` + /// exposes on terminal-error states. The pyo3 binding may grow + /// these later via a separate `attach_attrs` extension; the two + /// bindings stay in sync on the *pyo3-side 8 fields*, and napi + /// extends from there for its host-language's contract. /// /// pyo3 attaches via `attach_attrs(...)` in `pyo3/src/errors.rs:67`: /// `code, message, sql_state, error_code, vendor_code, http_status, /// retryable, query_id`. Both bindings intentionally omit `location` /// (kernel-internal `file:line` for `Internal` errors) and `cause` - /// (recursive — needs an explicit schema decision). This test pins - /// the envelope to that 8-field contract. + /// (recursive — needs an explicit schema decision). /// /// Reviewer-flagged at PR #27 / error.rs:76 — see comment text /// `pyo3 attaches kernel error fields as Python attributes…`. @@ -321,6 +348,11 @@ mod tests { e.http_status = Some(503); e.retryable = true; e.query_id = Some("01eedeadbeefdeadbeefdeadbeefdead".to_string()); + // Thrift-parity extension fields: populated too so the + // superset relation is exercised in the same fixture. + e.display_message = Some("Statement failed at operator Scan".to_string()); + e.diagnostic_info = Some("operator=Scan; stage=Compile".to_string()); + e.error_details_json = Some(r#"{"errorClass":"COMPILE_FAILURE"}"#.to_string()); // Set the *intentionally-omitted* fields too — the test should // confirm they do NOT appear on the wire. e.location = Some("kernel/src/foo.rs:42".to_string()); @@ -335,10 +367,10 @@ mod tests { .as_object() .expect("envelope payload must be a JSON object"); - // Mirrors pyo3's `attach_attrs` field list, in pyo3's snake_case - // → napi's camelCase. Update both lists together when the - // contract changes. - let expected_keys: &[&str] = &[ + // pyo3's `attach_attrs` field list, in pyo3's snake_case → + // napi's camelCase. These 8 keys must stay in lockstep across + // bindings — any divergence on these is a parity regression. + let pyo3_parity_keys: &[&str] = &[ "code", // pyo3: "code" "message", // pyo3: "message" "sqlState", // pyo3: "sql_state" @@ -348,7 +380,7 @@ mod tests { "retryable", // pyo3: "retryable" "queryId", // pyo3: "query_id" ]; - for k in expected_keys { + for k in pyo3_parity_keys { assert!( obj.contains_key(*k), "envelope is missing the `{k}` key — pyo3 sets this via \ @@ -356,6 +388,22 @@ mod tests { ); } + // Thrift-parity superset: these 3 are napi-only today (pyo3 + // may add them later via attach_attrs). They mirror the + // same-named optional fields on the NodeJS Thrift + // `TGetOperationStatusResp`. + let thrift_parity_keys: &[&str] = &[ + "displayMessage", // Thrift: displayMessage + "diagnosticInfo", // Thrift: diagnosticInfo + "errorDetailsJson", // Thrift: errorDetailsJson + ]; + for k in thrift_parity_keys { + assert!( + obj.contains_key(*k), + "envelope is missing the Thrift-parity key `{k}`. payload: {payload}" + ); + } + // Intentionally-omitted fields must NOT leak into the wire // shape (the module doc and the kernel `Error` struct both // identify `location` and `cause` as v1-omitted). If a future @@ -369,18 +417,63 @@ mod tests { ); } - // No surprise keys: the wire shape stays the documented set - // (exact-size check, not subset). A future field addition - // requires updating both pyo3's attach_attrs and this list. + // No surprise keys: the wire shape stays the documented set. + // Exact-size check (not subset) catches accidental additions. + let expected_total = pyo3_parity_keys.len() + thrift_parity_keys.len(); assert_eq!( obj.len(), - expected_keys.len(), - "envelope has unexpected extra keys vs the pyo3 parity set. \ - expected: {expected_keys:?}, got: {:?}", + expected_total, + "envelope has unexpected extra keys. expected pyo3 parity \ + {pyo3_parity_keys:?} + thrift parity {thrift_parity_keys:?}, \ + got: {:?}", obj.keys().collect::>() ); } + /// Thrift parity: on a non-terminal-error code (where the kernel + /// doesn't populate the SEA extended fields) the three Thrift + /// extension keys are omitted from the envelope. Mirrors the + /// optional-field-omitted-when-None convention the existing + /// envelope already enforces for the pyo3-parity fields. + #[test] + fn envelope_omits_thrift_extension_fields_when_unpopulated() { + let e = KernelError::invalid_argument().message("bad arg"); + let napi_err = napi_err_from_kernel(e); + let payload = &napi_err.reason.to_string()[ERROR_SENTINEL.len()..]; + let v: serde_json::Value = serde_json::from_str(payload).unwrap(); + let obj = v.as_object().unwrap(); + for absent in &["displayMessage", "diagnosticInfo", "errorDetailsJson"] { + assert!( + !obj.contains_key(*absent), + "key `{absent}` should be omitted when kernel field is \ + None, got: {payload}" + ); + } + } + + /// Wire round-trip for the Thrift parity fields: when the kernel + /// `Error` carries the 3 extended-status strings, the envelope + /// surfaces them under their camelCase keys with verbatim content. + /// Pins the exact key names so the TS adapter's typed-error + /// reviver can rely on them. + #[test] + fn envelope_surfaces_thrift_extension_fields_verbatim() { + let dm = "Statement was canceled by user; runtime 42s"; + let di = "operator=Scan->Filter->Project; stage=Execute; thread=0xfe"; + let ej = r#"{"errorClass":"USER_CANCELLATION","detail":{"reason":"sigint"}}"#; + let e = KernelError::sql_error() + .message("canceled") + .with_display_message(dm) + .with_diagnostic_info(di) + .with_error_details_json(ej); + let napi_err = napi_err_from_kernel(e); + let payload = &napi_err.reason.to_string()[ERROR_SENTINEL.len()..]; + let v: serde_json::Value = serde_json::from_str(payload).unwrap(); + assert_eq!(v["displayMessage"], dm); + assert_eq!(v["diagnosticInfo"], di); + assert_eq!(v["errorDetailsJson"], ej); + } + /// Optional fields are omitted from the wire shape when `None` (no /// `null` entries). This keeps the envelope compact AND means a TS /// reviver doesn't need to special-case `null` separately from @@ -404,6 +497,11 @@ mod tests { "httpStatus", "retryable", "queryId", + // Thrift-parity extension fields also follow the + // omit-when-None convention. + "displayMessage", + "diagnosticInfo", + "errorDetailsJson", ] { assert!( !obj.contains_key(*absent), diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 2377addc..7da46227 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -140,6 +140,106 @@ impl Statement { &self.statement_id } + // ─── SEA extended status accessors (Thrift parity) ───────────────── + // + // Mirror the same-named optional fields on the NodeJS Thrift + // driver's `TGetOperationStatusResp`. Populated whenever the SEA + // server sets them on the terminal `StatementStatus` envelope; the + // kernel stores the status struct once at construction so the + // accessors are read-only and lock-free at the kernel layer. + // + // These methods are `async` because the napi binding's inner + // state sits inside `Arc>>` and the + // lock shape mirrors `fetchNextBatch` / `cancel` — a brief tokio + // mutex held across the kernel accessor call. After `close()` the + // inner state has been taken; the accessors throw an + // `InvalidStatementHandle` error in that case, matching the + // existing `cancel()` semantics. + + /// Number of rows modified by the statement (UPDATE / INSERT / + /// DELETE / MERGE). `null` for SELECT and on warehouses that don't + /// surface the counter. Mirrors Thrift's + /// `TGetOperationStatusResp.numModifiedRows`. + #[napi] + pub async fn num_modified_rows(&self) -> napi::Result> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; + Ok(inner_state.executed.num_modified_rows()) + }) + .await + } + + /// Fractional completion as reported by the server, intended to be + /// in `[0.0, 1.0]`. `null` outside analytics warehouses. Not + /// clamped — JS callers rendering progress bars should validate. + /// The SEA wire field corresponds to Thrift's richer + /// `TProgressUpdateResp` task-completion ratio. + #[napi] + pub async fn progress(&self) -> napi::Result> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; + Ok(inner_state.executed.progress()) + }) + .await + } + + /// Server-supplied user-facing message. Mirrors Thrift's + /// `TGetOperationStatusResp.displayMessage`. **PII / sensitive- + /// data note:** may contain SQL fragments or parameter values — + /// redact before centralised logging. + /// + /// Populated on `Succeeded` / `Closed-with-inline-data` paths. + /// On terminal-error states (`Failed` / `Cancelled` / + /// `Closed-no-data`) the kernel returns an Error instead of a + /// `Statement`, and the same field rides on the JS Error envelope + /// under the same `displayMessage` key. + #[napi] + pub async fn display_message(&self) -> napi::Result> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; + Ok(inner_state.executed.display_message().map(str::to_owned)) + }) + .await + } + + /// Server-supplied diagnostic detail — multi-line operator / + /// stack context. Mirrors Thrift's + /// `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, + /// not user-facing. Same reachability + PII caveats as + /// `displayMessage`. + #[napi] + pub async fn diagnostic_info(&self) -> napi::Result> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; + Ok(inner_state.executed.diagnostic_info().map(str::to_owned)) + }) + .await + } + + /// Server-supplied JSON blob with extended error details. Mirrors + /// Thrift's `TGetOperationStatusResp.errorDetailsJson`. + /// Pass-through string — JS callers parse with `JSON.parse` if + /// they need structured access. **Unbounded:** server can return + /// a multi-MB blob; size before logging. + #[napi] + pub async fn error_details_json(&self) -> napi::Result> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; + Ok(inner_state.executed.error_details_json().map(str::to_owned)) + }) + .await + } + /// Pull the next batch of results. Returns `null` when the stream /// is exhausted. The returned `ArrowBatch.ipcBytes` is a complete /// Arrow IPC stream (schema header + 1 record-batch message) diff --git a/src/client/http.rs b/src/client/http.rs index a074dcdb..3a32a2db 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -71,7 +71,7 @@ impl std::fmt::Debug for ProxyConfig { /// All fields default to the most secure settings (`None` = use defaults). /// Relaxing any of these options should only be done in development/testing /// environments. -#[derive(Debug, Clone, Default)] +#[derive(Clone, Default)] pub struct TlsConfig { /// Enable TLS for connections. When `false`, allows plain HTTP. /// Default: true (TLS enabled). @@ -102,35 +102,56 @@ pub struct TlsConfig { pub trusted_certificate_pem: Option>, } +impl std::fmt::Debug for TlsConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Mirrors the redacting Debug on the public + // `crate::config::TlsConfig`. The PEM bytes themselves aren't + // secret, but dumping a multi-kB blob into every `?http_client` + // tracing span is unhelpful, and a future field that DOES hold + // secret material (mTLS client_key, etc.) finds the redacting + // pattern already in place. + f.debug_struct("TlsConfig") + .field("enabled", &self.enabled) + .field("allow_self_signed", &self.allow_self_signed) + .field("allow_hostname_mismatch", &self.allow_hostname_mismatch) + .field("trusted_certificate_path", &self.trusted_certificate_path) + .field( + "trusted_certificate_pem", + &self + .trusted_certificate_pem + .as_ref() + .map(|b| format!("<{} bytes>", b.len())), + ) + .finish() + } +} + impl TlsConfig { /// Project the public [`crate::config::TlsConfig`] onto the internal /// HTTP-client TLS struct. Public fields land on their internal /// counterparts; internal-only fields (`enabled`, /// `trusted_certificate_path`) stay at their defaults. /// - /// `accept_self_signed` / `skip_hostname_verification` are booleans - /// on the public surface (default: stricter); the internal layer - /// uses `Option` so the existing `None == default` semantics - /// are preserved. We map a `false` to `None` rather than - /// `Some(false)` to keep `Debug` output / RUST_LOG noise free of - /// no-op overrides. + /// `accept_self_signed` / `skip_hostname_verification` map a + /// `bool` from the public surface to `Some(bool)` — including + /// `Some(false)` for the strict path. The internal `Option` + /// shape preserves the "field unset → use backend default" + /// semantics for in-tree consumers that don't go through the + /// public projection, while still letting a public caller + /// **force-disable** a permissive mode if a future internal + /// default were ever to flip lenient. Cost: an extra `Some(false)` + /// in `RUST_LOG=debug` output for default sessions. pub fn from_public(cfg: &crate::config::TlsConfig) -> Self { Self { enabled: None, - allow_self_signed: cfg.accept_self_signed.then_some(true), - allow_hostname_mismatch: cfg.skip_hostname_verification.then_some(true), + allow_self_signed: Some(cfg.accept_self_signed), + allow_hostname_mismatch: Some(cfg.skip_hostname_verification), trusted_certificate_path: None, trusted_certificate_pem: cfg.custom_ca_cert.clone(), } } } -impl From<&crate::config::TlsConfig> for TlsConfig { - fn from(cfg: &crate::config::TlsConfig) -> Self { - Self::from_public(cfg) - } -} - /// Configuration for the HTTP client. #[derive(Debug, Clone)] pub struct HttpClientConfig { @@ -222,15 +243,22 @@ impl DatabricksHttpClient { // reqwest does not support accepting only self-signed certs while still // validating the trust chain — danger_accept_invalid_certs(true) disables - // ALL certificate validation (CA trust, expiration, etc.). + // ALL certificate validation (CA trust, expiration, etc.). Attach + // `org_id` to the warning so a central log store can attribute the + // relaxation back to the workspace that opted in. if config.tls.allow_self_signed.unwrap_or(false) { - warn!("TLS certificate validation is disabled — this is insecure and should only be used in development"); - warn!("allow_self_signed is enabled — note: reqwest does not distinguish self-signed from fully unvalidated; this disables ALL certificate validation"); + warn!( + org_id = ?config.org_id, + "TLS certificate validation is disabled — this is insecure and should only be used in development. Note: reqwest does not distinguish self-signed from fully unvalidated; this disables ALL certificate validation." + ); builder = builder.danger_accept_invalid_certs(true); } if config.tls.allow_hostname_mismatch.unwrap_or(false) { - warn!("TLS hostname verification is disabled — this is insecure and should only be used in development"); + warn!( + org_id = ?config.org_id, + "TLS hostname verification is disabled — this is insecure and should only be used in development" + ); builder = builder.danger_accept_invalid_hostnames(true); } @@ -241,22 +269,61 @@ impl DatabricksHttpClient { cert_path, e )) })?; - let cert = reqwest::Certificate::from_pem(&pem).map_err(|e| { + // `from_pem_bundle` (not `from_pem`) so a concatenated + // root + intermediate bundle loads every certificate. + // Under `tls-native`, the single-cert `from_pem` would + // silently drop everything past the first `-----END + // CERTIFICATE-----`, which is exactly the corporate + // re-signing TLS case the custom-CA surface targets. + let certs = reqwest::Certificate::from_pem_bundle(&pem).map_err(|e| { Error::invalid_argument() .message(format!("Invalid PEM certificate '{}': {}", cert_path, e)) })?; - builder = builder.add_root_certificate(cert); - debug!("Added custom CA certificate from: {}", cert_path); + // `from_pem_bundle` returns Ok(empty Vec) for input that + // contains no `-----BEGIN CERTIFICATE-----` blocks + // (garbage, JSON, etc.). Surface that as an explicit + // error rather than silently doing nothing. + if certs.is_empty() { + return Err(Error::invalid_argument().message(format!( + "Invalid PEM certificate '{}': no certificates found in file", + cert_path + ))); + } + let cert_count = certs.len(); + for cert in certs { + builder = builder.add_root_certificate(cert); + } + debug!( + "Added {} custom CA certificate(s) from: {}", + cert_count, cert_path + ); } if let Some(ref pem) = config.tls.trusted_certificate_pem { - let cert = reqwest::Certificate::from_pem(pem).map_err(|e| { - Error::invalid_argument() - .message(format!("Invalid in-memory PEM certificate: {}", e)) + // `from_pem_bundle` so root + intermediate concatenations + // (the common corporate-CA case) load fully. See the + // `trusted_certificate_path` branch above for why. + let certs = reqwest::Certificate::from_pem_bundle(pem).map_err(|e| { + Error::invalid_argument().message(format!( + "Invalid PEM bytes in TlsConfig.custom_ca_cert: {}", + e + )) })?; - builder = builder.add_root_certificate(cert); + // See the path branch above: empty bundle on non-empty + // input is a caller error (garbage / wrong format), not + // a silent no-op. + if certs.is_empty() { + return Err(Error::invalid_argument().message( + "Invalid PEM bytes in TlsConfig.custom_ca_cert: no certificates found", + )); + } + let cert_count = certs.len(); + for cert in certs { + builder = builder.add_root_certificate(cert); + } debug!( - "Added custom CA certificate from in-memory bytes ({} bytes)", + "Added {} custom CA certificate(s) from in-memory bytes ({} bytes)", + cert_count, pem.len() ); } @@ -856,7 +923,43 @@ lGrv15pBcePj let result = DatabricksHttpClient::new(config, default_retry_configs()); assert!(result.is_err()); let err_msg = format!("{:?}", result.unwrap_err()); - assert!(err_msg.contains("Invalid PEM certificate")); + // `from_pem_bundle` returns Ok(empty Vec) for input with no + // `-----BEGIN CERTIFICATE-----` markers; the kernel surfaces + // that as "no certificates found". + assert!( + err_msg.contains("Invalid PEM certificate") + && err_msg.contains("no certificates found"), + "expected 'Invalid PEM certificate' + 'no certificates found', got: {err_msg}" + ); + } + + #[test] + fn test_http_client_with_multi_cert_pem_bundle() { + // Corporate-CA case: concatenated root + intermediate. Both + // must load (regression guard against the single-cert + // `from_pem` path that silently dropped the second cert on + // the `tls-native` backend). + let bundle = format!("{TEST_CA_CERT_PEM}{TEST_CA_CERT_PEM}"); + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(bundle.into_bytes()); + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!(client.is_ok(), "multi-cert bundle should load cleanly"); + } + + #[test] + fn test_http_client_with_empty_pem_bytes_errors() { + // Empty / non-PEM input via `custom_ca_cert` is an explicit + // error, not a silent no-op. + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(b"not pem at all".to_vec()); + let result = DatabricksHttpClient::new(config, default_retry_configs()); + assert!(result.is_err()); + let err_msg = format!("{:?}", result.unwrap_err()); + assert!( + err_msg.contains("TlsConfig.custom_ca_cert") + && err_msg.contains("no certificates found"), + "expected error to name the public field + 'no certificates found', got: {err_msg}" + ); } #[test] @@ -896,11 +999,15 @@ lGrv15pBcePj #[test] fn test_tls_config_from_public_default_is_strict() { // A default public TlsConfig produces an internal config that - // does NOT relax any default — `None` everywhere on the - // permissive switches so log output stays clean. + // **explicitly** force-disables every permissive switch + // (`Some(false)`), not `None`. The reason: if a future + // internal default were to flip lenient, a public caller + // relying on `TlsConfig::default()` must still get strict TLS + // — `None` here would inherit the (hypothetical) lenient + // default, `Some(false)` overrides it. let internal = TlsConfig::from_public(&crate::config::TlsConfig::default()); - assert!(internal.allow_self_signed.is_none()); - assert!(internal.allow_hostname_mismatch.is_none()); + assert_eq!(internal.allow_self_signed, Some(false)); + assert_eq!(internal.allow_hostname_mismatch, Some(false)); assert!(internal.trusted_certificate_pem.is_none()); assert!(internal.trusted_certificate_path.is_none()); } diff --git a/src/client/sea.rs b/src/client/sea.rs index 8dd0f015..74049d4c 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -53,6 +53,24 @@ enum StatementOutcome { Err(Error), } +/// Copy the SEA extended status fields (`display_message`, +/// `diagnostic_info`, `error_details_json`) from a wire status onto a +/// kernel `Error`. Mirrors the Thrift `TGetOperationStatusResp` / +/// `TStatus` contract where the same fields ride on the operation +/// status across terminal-error states. +fn carry_extended_status(mut error: Error, status: &crate::types::sea::StatementStatus) -> Error { + if let Some(msg) = status.display_message.as_ref() { + error = error.with_display_message(msg); + } + if let Some(info) = status.diagnostic_info.as_ref() { + error = error.with_diagnostic_info(info); + } + if let Some(json) = status.error_details_json.as_ref() { + error = error.with_error_details_json(json); + } + error +} + /// SEA client for the Databricks SQL Statement Execution API. /// /// This client implements the `Transport` trait using REST endpoints. @@ -230,10 +248,16 @@ impl SeaRestTransport { } } - StatementOutcome::Err(error) + // Carry the extended status fields onto the Error so + // wrappers see what Thrift's `TGetOperationStatusResp` + // surfaces on terminal-error states. + StatementOutcome::Err(carry_extended_status(error, &response.status)) } StatementState::Canceled => { - StatementOutcome::Err(Error::invalid_state().message("Statement was canceled")) + let error = Error::invalid_state() + .message("Statement was canceled") + .with_query_id(&response.statement_id); + StatementOutcome::Err(carry_extended_status(error, &response.status)) } StatementState::Closed => { // Closed with result data is valid for inline results @@ -243,7 +267,10 @@ impl SeaRestTransport { if response.result.is_some() { StatementOutcome::Done(response) } else { - StatementOutcome::Err(Error::invalid_state().message("Statement was closed")) + let error = Error::invalid_state() + .message("Statement was closed") + .with_query_id(&response.statement_id); + StatementOutcome::Err(carry_extended_status(error, &response.status)) } } StatementState::Pending | StatementState::Running => { @@ -267,7 +294,11 @@ impl SeaRestTransport { } tokio::time::sleep(self.config.poll_interval).await; - debug!("Polling statement status: {}", r.statement_id); + debug!( + statement_id = %r.statement_id, + progress = ?r.status.progress, + "Polling statement status" + ); current_response = self.get_statement_status(&r.statement_id).await?; } } diff --git a/src/config.rs b/src/config.rs index 58048c11..fe6a19a7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -36,12 +36,13 @@ //! - [`LoggingConfig`] (filter, file) //! - [`TransportMode`] //! -//! Configs whose shape we are still settling are reserved as empty -//! `#[non_exhaustive]` structs so the public type names exist (and -//! `SessionBuilder` setters compile) without committing to fields: +//! [`TlsConfig`] now carries custom-CA + self-signed / hostname +//! relaxation knobs; configs whose shape we are still settling stay +//! as empty `#[non_exhaustive]` structs so the public type names +//! exist (and `SessionBuilder` setters compile) without committing +//! to fields: //! //! - [`ProxyConfig`] -//! - [`TlsConfig`] //! - [`TelemetryConfig`] //! //! All structs are `#[non_exhaustive]` so v1+ can grow new fields @@ -354,6 +355,24 @@ pub struct ProxyConfig {} /// /// The kernel exposes only fields that the internal rustls plumbing /// already supports — cert pinning and FIPS mode are *not* in scope. +/// +/// ```no_run +/// # use databricks_sql_kernel::TlsConfig; +/// // From a file path: +/// let from_file = TlsConfig { +/// custom_ca_cert: Some(std::fs::read("/etc/ssl/corp-ca.pem").unwrap()), +/// ..TlsConfig::default() +/// }; +/// +/// // From an in-memory buffer (the napi-rs `Buffer` / pyo3 `bytes` +/// // path — no tempfile shim needed): +/// let pem_bytes: Vec = b"-----BEGIN CERTIFICATE-----\n...".to_vec(); +/// let from_bytes = TlsConfig { +/// custom_ca_cert: Some(pem_bytes), +/// ..TlsConfig::default() +/// }; +/// # let _ = (from_file, from_bytes); +/// ``` #[non_exhaustive] #[derive(Clone, Default)] pub struct TlsConfig { @@ -366,6 +385,11 @@ pub struct TlsConfig { /// for foreign-language wrappers — napi-rs / pyo3 callers pass a /// `Buffer` / `bytes` directly without needing to materialise a /// tempfile. + /// + /// **Multi-cert bundles (root + intermediate):** the kernel splits + /// the PEM into individual certificates and adds each as a root, + /// so a concatenated `cat root.pem intermediate.pem` blob works + /// transparently regardless of the active TLS backend. pub custom_ca_cert: Option>, /// Accept self-signed server certificates. diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 6e6819da..bc360f82 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -187,6 +187,32 @@ pub struct Error { /// not parsed. pub location: Option, + /// Server-supplied user-facing message captured from the SEA + /// `StatementStatus.display_message` envelope on terminal-error + /// statements (`FAILED` / `CANCELED` / `CLOSED-no-data`). Mirrors + /// the same-named field on the Thrift `TGetOperationStatusResp` so + /// wrappers that surface a Thrift-shaped operation status to their + /// host language can populate it on the error envelope too. + /// + /// Independent of [`Error::message`] — `message` is the + /// kernel-formatted summary, `display_message` is the raw + /// server-supplied string. + pub display_message: Option, + + /// Server-supplied diagnostic detail captured from the SEA + /// `StatementStatus.diagnostic_info` envelope on terminal-error + /// statements. Multi-line text with stack frames or operator + /// context. Intended for support / log surfaces, not user-facing. + /// Mirrors the same-named Thrift field. + pub diagnostic_info: Option, + + /// Server-supplied JSON blob with extended error details, captured + /// from the SEA `StatementStatus.error_details_json` envelope on + /// terminal-error statements. Pass-through string — wrappers parse + /// if they need structured access. Mirrors the same-named Thrift + /// field. + pub error_details_json: Option, + /// Underlying cause. Boxed to keep the struct stack-friendly. pub cause: Option>, } @@ -207,6 +233,9 @@ impl Error { retryable: false, query_id: None, location: None, + display_message: None, + diagnostic_info: None, + error_details_json: None, cause: None, } } @@ -399,6 +428,34 @@ impl Error { self } + /// Attach the server-supplied `display_message` from a terminal- + /// error SEA `StatementStatus` envelope. Wrappers surfacing a + /// Thrift-shaped operation-status object to their host language + /// should populate this on the error so callers see the same + /// field they would have read from `TGetOperationStatusResp` on + /// the Thrift path. + pub fn with_display_message(mut self, msg: impl Into) -> Self { + self.display_message = Some(msg.into()); + self + } + + /// Attach the server-supplied `diagnostic_info` from a terminal- + /// error SEA `StatementStatus` envelope. Multi-line operator / + /// stack context; for support surfaces, not user-facing. + pub fn with_diagnostic_info(mut self, info: impl Into) -> Self { + self.diagnostic_info = Some(info.into()); + self + } + + /// Attach the server-supplied `error_details_json` blob from a + /// terminal-error SEA `StatementStatus` envelope. Unbounded + /// pass-through string; wrappers parse if they need structured + /// access. + pub fn with_error_details_json(mut self, json: impl Into) -> Self { + self.error_details_json = Some(json.into()); + self + } + pub fn with_cause(mut self, cause: Error) -> Self { self.cause = Some(Box::new(cause)); self diff --git a/src/session.rs b/src/session.rs index fd2be786..6e373ff0 100644 --- a/src/session.rs +++ b/src/session.rs @@ -434,9 +434,22 @@ impl SessionBuilder { self } - /// TLS settings (custom CA, hostname-mismatch tolerance, …). - /// Reserved in v0 (`#[non_exhaustive]` empty struct); fields land - /// in v0.1. + /// TLS settings — custom CA bundle, self-signed acceptance, + /// hostname-verification skip. See [`TlsConfig`] for the field + /// list. Default is the most secure stance: validate against the + /// system trust store, require a valid certificate chain, and + /// verify hostnames. + /// + /// ```no_run + /// # use databricks_sql_kernel::{TlsConfig, Session}; + /// # fn build() -> Result<(), Box> { + /// let tls = TlsConfig { + /// custom_ca_cert: Some(std::fs::read("/etc/ssl/corp-ca.pem")?), + /// ..TlsConfig::default() + /// }; + /// let _builder = Session::builder().tls(tls); + /// # Ok(()) } + /// ``` pub fn tls(mut self, tls: TlsConfig) -> Self { self.tls = Some(tls); self @@ -537,8 +550,10 @@ fn build_http_client_config(config: &SessionConfig, org_id: Option) -> H }; // Touch the still-reserved proxy config so a future field addition // (without setting it through here) shows up as a compile error - // rather than a silently-dropped option. - let ProxyConfig { .. } = config.proxy.clone().unwrap_or_default(); + // rather than a silently-dropped option. Explicit `ProxyConfig {}` + // (NOT `{ .. }`) — the `..` rest pattern would defeat the + // tripwire by silently accepting any new field. + let ProxyConfig {} = config.proxy.clone().unwrap_or_default(); let _ = &mut hcc; hcc } diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 087a1a15..5d5cfbbc 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -113,28 +113,53 @@ impl ExecutedStatement { /// Rows modified by the statement (UPDATE / INSERT / DELETE / /// MERGE). Absent for SELECT and on warehouses that don't surface /// the counter. + /// + /// Reachable only on the `Succeeded` / `Closed-with-inline-data` + /// paths — the kernel returns `Err` (no `ExecutedStatement`) on + /// `Failed` / `Cancelled` / `Closed-no-data`. pub fn num_modified_rows(&self) -> Option { self.status.num_modified_rows } - /// 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. + /// Fractional completion as reported by the server, intended to be + /// 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. + /// + /// **Not clamped:** the value is passed through verbatim. Wrappers + /// rendering progress bars should clamp or treat NaN as absent + /// before display. pub fn progress(&self) -> Option { self.status.progress } /// Server-supplied user-facing message. Distinct from the - /// `error.message` carried inside `Failed` — populated on - /// non-error states too (e.g. cancellation reasons, progress - /// hints). + /// `error.message` that the kernel folds into `Error::sql_error()` + /// on the `Failed` path. + /// + /// **Reachability:** populated on `Succeeded` / `Closed-with-inline-data` + /// only. Failed / Cancelled / Closed-no-data return `Err` before + /// the `ExecutedStatement` is constructed, so cancellation-reason + /// messages from those paths are NOT reachable here — they flow + /// through the `Error` instead. + /// + /// **PII / sensitive-data note:** server-supplied free-form text + /// may include SQL fragments or parameter values. Redact before + /// centralised logging. pub fn display_message(&self) -> Option<&str> { self.status.display_message.as_deref() } - /// Server-supplied diagnostic detail — multi-line text with - /// stack frames or operator context. Intended for log / support + /// Server-supplied diagnostic detail — multi-line text with stack + /// frames or operator context. Intended for log / support /// surfaces; not user-facing. + /// + /// **Reachability:** populated on `Succeeded` / `Closed-with-inline-data` + /// only — same caveat as [`Self::display_message`]. + /// + /// **PII / sensitive-data note:** like `display_message`, this is + /// server-supplied free-form text and may include SQL fragments + /// or values. Redact before centralised logging. pub fn diagnostic_info(&self) -> Option<&str> { self.status.diagnostic_info.as_deref() } @@ -142,6 +167,13 @@ impl ExecutedStatement { /// Server-supplied JSON blob with extended error details. /// Pass-through string — wrappers parse if they need structured /// access. + /// + /// **Reachability:** populated on `Succeeded` / `Closed-with-inline-data` + /// only. The corresponding details for Failed statements flow + /// through the returned `Error`, not this accessor. + /// + /// **Unbounded:** the server can return a multi-MB blob. Wrappers + /// surfacing this should bound size before logging. pub fn error_details_json(&self) -> Option<&str> { self.status.error_details_json.as_deref() } diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 91aad839..c4e7f3cd 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -25,6 +25,21 @@ //! the handle short-circuits to `InvalidStatementHandle` locally when //! the parent `Statement` is re-executed, avoiding wasted network //! round-trips on zombie handles. +//! +//! ## Extended SEA status fields (`num_modified_rows`, `progress`, +//! `display_message`, `diagnostic_info`, `error_details_json`) +//! +//! These accessors live on the **sync** [`crate::ExecutedStatement`] +//! handle only. Async-consumption callers who need them should use +//! [`crate::statement::mutable::Statement::execute`] (which drives the +//! polling loop internally and returns a sync handle) rather than +//! `submit()`. The async surface is shaped for the +//! poll-loop-without-metadata use case; mirroring the 5 accessors here +//! requires storing a status snapshot per-poll, which is tracked as a +//! follow-up. Wrappers presenting a Thrift-shaped operation API to +//! their host language (e.g. the napi binding's `Statement` class +//! mirroring `IOperation`) route through the sync handle so the +//! extended fields are available alongside fetch / cancel / close. use crate::client::ExecuteResponse; use crate::kernel_error::Error; @@ -43,6 +58,16 @@ use tracing::{warn, Instrument}; /// /// Mirrors the SEA `Status` enum. `Failed` carries the underlying /// `Error` so callers see `vendor_code` / `sql_state` / etc. +// +// `large_enum_variant`: `Failed(Error)` is intentionally inline rather +// than boxed. `Error` has grown to ~216 bytes after picking up the +// Thrift-parity `display_message` / `diagnostic_info` / +// `error_details_json` fields, but this enum is constructed at most +// once per `status()` poll and immediately matched on by the caller — +// the per-call size is irrelevant in practice, and boxing here would +// force every pyo3 / direct-Rust caller pattern-matching on +// `Failed(err)` to update. +#[allow(clippy::large_enum_variant)] #[non_exhaustive] #[derive(Debug)] pub enum StatementStatus { diff --git a/src/types/sea.rs b/src/types/sea.rs index fc79392a..0b6fe1df 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -33,7 +33,13 @@ pub struct StatementExecutionResponse { } /// Status of a statement execution. -#[derive(Debug, Clone, Deserialize)] +/// +/// `#[non_exhaustive]` — external Rust callers can read fields directly +/// but cannot use a struct literal. Adding new wire-shape fields stays +/// non-breaking for downstream crates (in-crate construction is +/// unaffected). +#[non_exhaustive] +#[derive(Clone, Deserialize)] pub struct StatementStatus { pub state: StatementState, #[serde(default)] @@ -50,20 +56,53 @@ pub struct StatementStatus { /// Server-supplied user-facing message (e.g. "Statement was /// canceled by the user" or progress hints). Distinct from /// `error.message`; populated on non-error states too. + /// + /// **PII / sensitive-data note:** server-supplied free-form text + /// may include fragments of the original SQL or parameter values. + /// Wrappers forwarding this to centralised logs should redact or + /// truncate per their own PII policy. #[serde(default)] pub display_message: Option, /// Server-supplied diagnostic detail — multi-line text with /// stack frames or operator context. Intended for log / support /// surfaces, not user-facing strings. + /// + /// **PII / sensitive-data note:** like `display_message`, this is + /// server-supplied free-form text and may include SQL fragments + /// or values. Redact before centralised logging. #[serde(default)] pub diagnostic_info: Option, /// Server-supplied JSON blob with extended error details. /// Pass-through string — wrappers parse if they need structured /// access. + /// + /// **Unbounded:** the server can return a multi-MB blob. Wrappers + /// surfacing this should bound size before logging. #[serde(default)] pub error_details_json: Option, } +impl std::fmt::Debug for StatementStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Truncate unbounded server-supplied free-form strings so a + // `?status` in a tracing span doesn't dump multi-MB blobs. + // Presence + length are the load-bearing signal; the content + // itself goes through dedicated accessors on `ExecutedStatement`. + fn summarise(s: &Option) -> Option { + s.as_ref().map(|v| format!("<{} chars>", v.len())) + } + f.debug_struct("StatementStatus") + .field("state", &self.state) + .field("error", &self.error) + .field("num_modified_rows", &self.num_modified_rows) + .field("progress", &self.progress) + .field("display_message", &summarise(&self.display_message)) + .field("diagnostic_info", &summarise(&self.diagnostic_info)) + .field("error_details_json", &summarise(&self.error_details_json)) + .finish() + } +} + /// Possible states of a statement during execution. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 204bbdcc..7a16739f 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -743,3 +743,91 @@ async fn complex_types_as_json_flag_stringifies_complex_columns() { session.close().await.expect("session close (json)"); } } + +// ─── PR #23 extended-status fields against a live warehouse ────────── +// +// Validates the end-to-end behaviour the PR ships: +// +// 1. On Succeeded: the 5 accessors on `ExecutedStatement` are wired +// correctly and return server-supplied values (when populated) or +// `None` (when the server omits them — the common case for SELECT). +// 2. On Failed: the kernel `Error` carries `display_message` / +// `diagnostic_info` / `error_details_json` from the SEA wire +// envelope (the F4 carry-over), so a Thrift-migrating wrapper sees +// the same fields its old code path used to see on +// `TGetOperationStatusResp`. + +#[tokio::test] +#[ignore] +async fn live_select_status_accessors_default_to_none() { + // SELECT on a classic warehouse should not populate the extended + // fields. Pins the accessor wiring + serde-default behaviour + // against a real server response. + let session = live_session().await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let exec = stmt.execute().await.expect("execute SELECT 1"); + + // num_modified_rows is None for SELECT. + assert_eq!( + exec.num_modified_rows(), + None, + "num_modified_rows expected None for SELECT, got {:?}", + exec.num_modified_rows() + ); + // progress is None on the SQL warehouse path (only analytics + // warehouses populate it). + // display_message / diagnostic_info / error_details_json are None + // on success — these flow only when the server has something to + // surface. + let dm = exec.display_message(); + let di = exec.diagnostic_info(); + let edj = exec.error_details_json(); + eprintln!( + "live SELECT status snapshot: progress={:?} display_message={:?} diagnostic_info={:?} error_details_json={:?}", + exec.progress(), + dm, + di, + edj + ); + + exec.close().await.expect("close"); + session.close().await.expect("session close"); +} + +#[tokio::test] +#[ignore] +async fn live_failed_statement_error_envelope_carries_extended_fields() { + // Deliberately fail a statement and confirm the resulting + // kernel `Error` either carries the server-supplied extended + // fields (when populated) or leaves them `None` (when the server + // omits them — graceful degradation). Both the sql_state and the + // error_code on the envelope are the legacy contract; the 3 new + // fields are the F4 / Thrift-parity addition. + let session = live_session().await; + let mut stmt = session.statement(); + // Reference a definitely-nonexistent table to provoke a SqlError. + stmt.spec() + .sql("SELECT * FROM nonexistent_kernel_pr23_test_table_xyz_123"); + let err = match stmt.execute().await { + Ok(_) => panic!("execute against nonexistent table must fail"), + Err(e) => e, + }; + + assert_eq!(err.code, ErrorCode::SqlError); + + eprintln!( + "live FAILED envelope: message={:?} sql_state={:?} error_code={:?} display_message={:?} diagnostic_info={:?} error_details_json={:?}", + err.message, err.sql_state, err.error_code, err.display_message, err.diagnostic_info, err.error_details_json + ); + + // The new Thrift-parity fields must be readable on the Error, + // even if the server didn't populate them (we accept None here — + // the test pins the *wire shape* of the kernel Error, not the + // server's behaviour). + let _: &Option = &err.display_message; + let _: &Option = &err.diagnostic_info; + let _: &Option = &err.error_details_json; + + session.close().await.expect("session close"); +} From 752d1fad62310dd8ef2994ae6db646eacd2e5ed1 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 27 May 2026 10:14:27 +0000 Subject: [PATCH 4/7] krn-status-fields: clarify TLS doc + add polling-path status test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/client/http.rs | 25 +++++++++++---- tests/v0_execute_wiremock.rs | 62 ++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 3a32a2db..da714288 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -91,14 +91,27 @@ pub struct TlsConfig { /// for dev/test only. /// Default: false. pub allow_hostname_mismatch: Option, - /// Path to a PEM-encoded CA certificate file to add to the trust store. + /// Path to a PEM-encoded CA certificate file to add to the trust + /// store. Internal-only — the public [`crate::config::TlsConfig`] + /// surface does not expose a path-based loader; the only public + /// path to a custom CA is `custom_ca_cert: Vec` (mapped to + /// `trusted_certificate_pem` below). Direct-Rust kernel consumers + /// that need file-based loading can construct an + /// [`HttpClientConfig`] manually. pub trusted_certificate_path: Option, /// PEM-encoded CA certificate bytes to add to the trust store. - /// Alternative to `trusted_certificate_path` for callers that - /// have the cert in-memory (e.g. foreign-language wrappers - /// passing `Buffer` / `bytes` without a tempfile shim). When - /// both are set, the path is read first, then the in-memory PEM - /// is added as an additional root. + /// Populated from the public [`crate::config::TlsConfig::custom_ca_cert`] + /// field — foreign-language wrappers (napi-rs `Buffer`, pyo3 + /// `bytes`) pass the cert in-memory without needing a tempfile + /// shim. + /// + /// When BOTH `trusted_certificate_path` AND + /// `trusted_certificate_pem` are set on an internally-constructed + /// `HttpClientConfig`, the file is loaded first and then the + /// in-memory PEM is added as an additional root. From the public + /// surface only the in-memory variant is reachable (the path + /// field has no public projection), so the "both set" case is + /// unreachable for `SessionBuilder` callers today. pub trusted_certificate_pem: Option>, } diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 5d7eb8c1..3aefd386 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -738,3 +738,65 @@ async fn executed_statement_status_fields_default_to_none() { exec.close().await.expect("close"); } + +#[tokio::test] +async fn polling_path_carries_terminal_status_not_initial() { + // Regression guard against the kernel surfacing the FIRST status + // response instead of the TERMINAL one. + // + // Setup: the POST /statements returns RUNNING with no extended + // fields. The polling GET /statements/{id} then returns SUCCEEDED + // with all 5 extended fields populated. The kernel's + // `wait_for_completion` loop must hand the **terminal** status + // (the final GET) to `ExecutedStatement::new`, not the initial + // POST response. If the kernel ever regresses to carrying forward + // the first response, this test fails because the accessors will + // see `None` instead of the populated terminal values. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + // Initial execute returns RUNNING — no extended fields. The + // kernel must NOT latch this onto the ExecutedStatement. + mount_execute(&server, running_body("stmt-poll-status")).await; + + // Polled GET returns SUCCEEDED with the 5 extended fields + // populated. This is the status the kernel must carry forward. + let batch = int64_batch("n", vec![42]); + mount_status( + &server, + "stmt-poll-status", + succeeded_inline_body_with_status( + "stmt-poll-status", + &batch, + Some(11), + Some(1.0), + Some("Done after retry"), + Some("operator=Project; stage=Execute"), + Some(r#"{"errorClass":"NONE"}"#), + ), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("UPDATE t SET x = 1"); + let exec = stmt + .execute() + .await + .expect("execute should poll to terminal SUCCEEDED"); + + // All 5 must reflect the TERMINAL poll, not the initial RUNNING + // response (which had no extended fields). + assert_eq!(exec.num_modified_rows(), Some(11)); + assert_eq!(exec.progress(), Some(1.0)); + assert_eq!(exec.display_message(), Some("Done after retry")); + assert_eq!( + exec.diagnostic_info(), + Some("operator=Project; stage=Execute") + ); + assert_eq!(exec.error_details_json(), Some(r#"{"errorClass":"NONE"}"#)); + + exec.close().await.expect("close"); +} From af3a80a95c17ebe82ed46cfeb7d2cc0199c8efcb Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 27 May 2026 11:03:06 +0000 Subject: [PATCH 5/7] krn-status-fields: drop speculative progress field + clarify TLS Thrift intent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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` 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` 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 --- napi/src/statement.rs | 25 ++++++--------- src/client/sea.rs | 4 +-- src/client/transport.rs | 7 +++-- src/config.rs | 26 ++++++++++++++++ src/reader/cloudfetch/link_fetcher.rs | 1 - src/statement/executed.rs | 23 +++++++------- src/statement/executed_async.rs | 4 +-- src/types/sea.rs | 44 +++++++++++++++++++++------ tests/v0_execute_e2e.rs | 9 ++---- tests/v0_execute_wiremock.rs | 16 ++-------- 10 files changed, 96 insertions(+), 63 deletions(-) diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 7da46227..bdc3b49b 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -171,21 +171,16 @@ impl Statement { .await } - /// Fractional completion as reported by the server, intended to be - /// in `[0.0, 1.0]`. `null` outside analytics warehouses. Not - /// clamped — JS callers rendering progress bars should validate. - /// The SEA wire field corresponds to Thrift's richer - /// `TProgressUpdateResp` task-completion ratio. - #[napi] - pub async fn progress(&self) -> napi::Result> { - let inner = Arc::clone(&self.inner); - guarded(async move { - let guard = inner.lock().await; - let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.progress()) - }) - .await - } + // TODO(pr23-followup): mirror a `progress()` accessor here once + // the kernel exposes one. Empirically, the SEA server does not + // populate progress today (verified 2026-05-27 against pecotesting: + // a 37s heavy TPC-H query polled 7 times with + // `getProgressUpdate=true` on the Thrift NodeJS path returned + // `progressUpdateResponse = null` on every poll). When the server + // grows progress support, expose it here under the same name JS + // callers expect from Thrift's `TGetOperationStatusResp.progressUpdateResponse` + // — likely as a struct mirroring `TProgressUpdateResp`, not a bare + // float. /// Server-supplied user-facing message. Mirrors Thrift's /// `TGetOperationStatusResp.displayMessage`. **PII / sensitive- diff --git a/src/client/sea.rs b/src/client/sea.rs index 74049d4c..a0d87f69 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -296,7 +296,7 @@ impl SeaRestTransport { tokio::time::sleep(self.config.poll_interval).await; debug!( statement_id = %r.statement_id, - progress = ?r.status.progress, + state = ?r.status.state, "Polling statement status" ); current_response = self.get_statement_status(&r.statement_id).await?; @@ -415,7 +415,7 @@ impl SeaRestTransport { // The full `status` is carried forward so the executed handle // can skip a redundant CloseStatement when the server already // cleaned up (status.state=Closed) AND expose - // num_modified_rows / progress / etc. without a second + // num_modified_rows / display_message / etc. without a second // GetStatementStatus round-trip. Ok(ExecuteResult { statement_id: response.statement_id, diff --git a/src/client/transport.rs b/src/client/transport.rs index b5837007..8740037d 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -69,7 +69,7 @@ pub(crate) struct SessionInfo { /// statement ID (for cancellation/cleanup), a reader over the result /// data, optionally the SEA manifest for metadata propagation, and /// the terminal `StatementStatus` so callers can surface -/// `num_modified_rows` / `progress` / etc. without a second +/// `num_modified_rows` / `display_message` / etc. without a second /// GetStatementStatus round-trip. pub(crate) struct ExecuteResult { pub statement_id: String, @@ -88,8 +88,9 @@ pub(crate) struct ExecuteResult { /// instead and requires an explicit close. /// /// The full status is carried (not just the state) so the - /// `ExecutedStatement` can expose `num_modified_rows` / `progress` - /// / etc. without a second GetStatementStatus round-trip. + /// `ExecutedStatement` can expose `num_modified_rows` / + /// `display_message` / etc. without a second GetStatementStatus + /// round-trip. pub status: StatementStatus, } diff --git a/src/config.rs b/src/config.rs index fe6a19a7..c0c63ac4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -373,6 +373,32 @@ pub struct ProxyConfig {} /// }; /// # let _ = (from_file, from_bytes); /// ``` +// +// TODO(pr23-followup): the public Thrift NodeJS driver does NOT +// expose programmatic TLS config — its `ConnectionOptions` has no +// `ca` / `cert` / `key` field, and its `HttpConnection.createHttpsAgent` +// builds the agent with `rejectUnauthorized: false` HARDCODED +// (verified at `~/databricks-sql-nodejs/lib/connection/connections/HttpConnection.ts:67-77`, +// 2026-05-27). The only "TLS knobs" Thrift NodeJS users have today +// are the Node process-level env vars `NODE_EXTRA_CA_CERTS` and +// `NODE_TLS_REJECT_UNAUTHORIZED`, and even those are inert against +// the Thrift driver's hardcoded-permissive agent. +// +// The kernel surface here is intentionally STRICTER than Thrift's +// (default = full validation, opt-in relaxations) and richer (custom +// CA bundles, programmatic mTLS room). Motivated by: +// 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). +// +// Revisit when (a) the napi binding wires these onto `ConnectionOptions` +// for JS callers, and (b) we decide whether to honour Node's +// `NODE_EXTRA_CA_CERTS` env var on the SEA path the way Node's own +// https stack does — likely yes, for ergonomic parity with the rest +// of the Node ecosystem. #[non_exhaustive] #[derive(Clone, Default)] pub struct TlsConfig { diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 29f7df0f..c3202f97 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -595,7 +595,6 @@ mod tests { state: StatementState::Succeeded, error: None, num_modified_rows: None, - progress: None, display_message: None, diagnostic_info: None, error_details_json: None, diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 5d5cfbbc..b80ff909 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -121,17 +121,18 @@ impl ExecutedStatement { self.status.num_modified_rows } - /// Fractional completion as reported by the server, intended to be - /// 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. - /// - /// **Not clamped:** the value is passed through verbatim. Wrappers - /// rendering progress bars should clamp or treat NaN as absent - /// before display. - pub fn progress(&self) -> Option { - self.status.progress - } + // TODO(pr23-followup): add `progress()` once the SEA server emits + // a progress field. Verified empirically on 2026-05-27 that a 37s + // TPC-H query against a SQL warehouse returns no + // `progressUpdateResponse` even on the Thrift path that explicitly + // requests it (`getProgressUpdate=true`). The SDK Java + // `StatementStatus` model also has no progress field. Adding an + // accessor that always returns None would mislead callers; revisit + // when the SEA server grows progress support, ideally surfacing + // the same struct shape Thrift uses + // (`TProgressUpdateResp { headerNames, rows, footerSummary, + // progressedPercentage, status, startTime }`) rather than a bare + // `Option`. /// Server-supplied user-facing message. Distinct from the /// `error.message` that the kernel folds into `Error::sql_error()` diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index c4e7f3cd..9264779b 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -26,7 +26,7 @@ //! the parent `Statement` is re-executed, avoiding wasted network //! round-trips on zombie handles. //! -//! ## Extended SEA status fields (`num_modified_rows`, `progress`, +//! ## Extended SEA status fields (`num_modified_rows`, //! `display_message`, `diagnostic_info`, `error_details_json`) //! //! These accessors live on the **sync** [`crate::ExecutedStatement`] @@ -34,7 +34,7 @@ //! [`crate::statement::mutable::Statement::execute`] (which drives the //! polling loop internally and returns a sync handle) rather than //! `submit()`. The async surface is shaped for the -//! poll-loop-without-metadata use case; mirroring the 5 accessors here +//! poll-loop-without-metadata use case; mirroring the accessors here //! requires storing a status snapshot per-poll, which is tracked as a //! follow-up. Wrappers presenting a Thrift-shaped operation API to //! their host language (e.g. the napi binding's `Statement` class diff --git a/src/types/sea.rs b/src/types/sea.rs index 0b6fe1df..0ae95e82 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -38,6 +38,18 @@ pub struct StatementExecutionResponse { /// but cannot use a struct literal. Adding new wire-shape fields stays /// non-breaking for downstream crates (in-crate construction is /// unaffected). +// +// TODO(pr23-followup): add a `progress` field once the SEA server +// actually emits one. Empirically verified against pecotesting on +// 2026-05-27 — a 37s heavy TPC-H query against a SQL warehouse, polled +// 7 times with `getProgressUpdate=true` on the Thrift path, returned +// `progressUpdateResponse = null` on every poll. Adding the field to +// the kernel before the wire supports it ships an Option<...> that's +// always None, locks us into a shape (`f64`) that doesn't match +// Thrift's `TProgressUpdateResp` struct (headerNames / rows / +// footerSummary / progressedPercentage), and creates user-visible +// API churn when the server finally does grow progress support. Hold +// off until then. #[non_exhaustive] #[derive(Clone, Deserialize)] pub struct StatementStatus { @@ -49,10 +61,6 @@ pub struct StatementStatus { /// surface the counter. #[serde(default)] pub num_modified_rows: Option, - /// Fractional completion in `[0.0, 1.0]`. Populated on analytics - /// warehouses; absent (or always 1.0 on terminal) elsewhere. - #[serde(default)] - pub progress: Option, /// Server-supplied user-facing message (e.g. "Statement was /// canceled by the user" or progress hints). Distinct from /// `error.message`; populated on non-error states too. @@ -95,7 +103,6 @@ impl std::fmt::Debug for StatementStatus { .field("state", &self.state) .field("error", &self.error) .field("num_modified_rows", &self.num_modified_rows) - .field("progress", &self.progress) .field("display_message", &summarise(&self.display_message)) .field("diagnostic_info", &summarise(&self.diagnostic_info)) .field("error_details_json", &summarise(&self.error_details_json)) @@ -568,13 +575,16 @@ mod tests { #[test] fn test_statement_status_with_extended_fields() { - // SEA response with all five extended status fields populated. + // SEA response with the extended status fields populated. The + // wire field `progress` was empirically absent on the SQL + // warehouse path (see the field-level TODO in `StatementStatus`) + // and has been dropped from the kernel until a server-side + // shape is settled. let json = r#"{ "statement_id": "stmt-extended", "status": { "state": "SUCCEEDED", "num_modified_rows": 42, - "progress": 0.875, "display_message": "Statement completed", "diagnostic_info": "operator=Scan; rows=42", "error_details_json": "{\"trace\":\"...\"}" @@ -584,7 +594,6 @@ mod tests { let response: StatementExecutionResponse = serde_json::from_str(json).unwrap(); assert_eq!(response.status.state, StatementState::Succeeded); assert_eq!(response.status.num_modified_rows, Some(42)); - assert_eq!(response.status.progress, Some(0.875)); assert_eq!( response.status.display_message, Some("Statement completed".to_string()) @@ -610,12 +619,29 @@ mod tests { let response: StatementExecutionResponse = serde_json::from_str(json).unwrap(); assert_eq!(response.status.num_modified_rows, None); - assert_eq!(response.status.progress, None); assert_eq!(response.status.display_message, None); assert_eq!(response.status.diagnostic_info, None); assert_eq!(response.status.error_details_json, None); } + #[test] + fn test_statement_status_ignores_unknown_progress_field() { + // Forward-compat: if the SEA server starts emitting a + // `progress` field, the kernel must not break — it's just an + // unknown JSON key today and `serde(default)` on the modelled + // fields means we ignore it. Pin this behaviour so a future + // strict-mode bump can't silently break the kernel. + let json = r#"{ + "statement_id": "stmt-progress", + "status": { + "state": "RUNNING", + "progress": 0.5 + } + }"#; + let response: StatementExecutionResponse = serde_json::from_str(json).unwrap(); + assert_eq!(response.status.state, StatementState::Running); + } + #[test] fn test_column_info_with_interval_type() { let json = r#"{ diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 7a16739f..1cfee5e4 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -775,8 +775,6 @@ async fn live_select_status_accessors_default_to_none() { "num_modified_rows expected None for SELECT, got {:?}", exec.num_modified_rows() ); - // progress is None on the SQL warehouse path (only analytics - // warehouses populate it). // display_message / diagnostic_info / error_details_json are None // on success — these flow only when the server has something to // surface. @@ -784,11 +782,8 @@ async fn live_select_status_accessors_default_to_none() { let di = exec.diagnostic_info(); let edj = exec.error_details_json(); eprintln!( - "live SELECT status snapshot: progress={:?} display_message={:?} diagnostic_info={:?} error_details_json={:?}", - exec.progress(), - dm, - di, - edj + "live SELECT status snapshot: display_message={:?} diagnostic_info={:?} error_details_json={:?}", + dm, di, edj ); exec.close().await.expect("close"); diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 3aefd386..d0f8313a 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -599,12 +599,10 @@ async fn kernel_invariant_parent_drop_invalidates_executed_cancel() { /// Build a SEA `SUCCEEDED` body with the 5 extended status fields /// populated. Mirrors `succeeded_inline_body` but injects status /// fields the kernel surfaces via `ExecutedStatement::*` getters. -#[allow(clippy::too_many_arguments)] fn succeeded_inline_body_with_status( statement_id: &str, batch: &RecordBatch, num_modified_rows: Option, - progress: Option, display_message: Option<&str>, diagnostic_info: Option<&str>, error_details_json: Option<&str>, @@ -639,9 +637,6 @@ fn succeeded_inline_body_with_status( if let Some(n) = num_modified_rows { status_obj.insert("num_modified_rows".to_string(), json!(n)); } - if let Some(p) = progress { - status_obj.insert("progress".to_string(), json!(p)); - } if let Some(m) = display_message { status_obj.insert("display_message".to_string(), json!(m)); } @@ -691,7 +686,6 @@ async fn executed_statement_surfaces_extended_status_fields() { "stmt-status", &batch, Some(7), - Some(1.0), Some("All good"), Some("operator=Scan"), Some(r#"{"k":"v"}"#), @@ -705,7 +699,6 @@ async fn executed_statement_surfaces_extended_status_fields() { let exec = stmt.execute().await.expect("execute"); assert_eq!(exec.num_modified_rows(), Some(7)); - assert_eq!(exec.progress(), Some(1.0)); assert_eq!(exec.display_message(), Some("All good")); assert_eq!(exec.diagnostic_info(), Some("operator=Scan")); assert_eq!(exec.error_details_json(), Some(r#"{"k":"v"}"#)); @@ -731,7 +724,6 @@ async fn executed_statement_status_fields_default_to_none() { let exec = stmt.execute().await.expect("execute"); assert_eq!(exec.num_modified_rows(), None); - assert_eq!(exec.progress(), None); assert_eq!(exec.display_message(), None); assert_eq!(exec.diagnostic_info(), None); assert_eq!(exec.error_details_json(), None); @@ -761,7 +753,7 @@ async fn polling_path_carries_terminal_status_not_initial() { // kernel must NOT latch this onto the ExecutedStatement. mount_execute(&server, running_body("stmt-poll-status")).await; - // Polled GET returns SUCCEEDED with the 5 extended fields + // Polled GET returns SUCCEEDED with the extended fields // populated. This is the status the kernel must carry forward. let batch = int64_batch("n", vec![42]); mount_status( @@ -771,7 +763,6 @@ async fn polling_path_carries_terminal_status_not_initial() { "stmt-poll-status", &batch, Some(11), - Some(1.0), Some("Done after retry"), Some("operator=Project; stage=Execute"), Some(r#"{"errorClass":"NONE"}"#), @@ -787,10 +778,9 @@ async fn polling_path_carries_terminal_status_not_initial() { .await .expect("execute should poll to terminal SUCCEEDED"); - // All 5 must reflect the TERMINAL poll, not the initial RUNNING - // response (which had no extended fields). + // All accessors must reflect the TERMINAL poll, not the initial + // RUNNING response (which had no extended fields). assert_eq!(exec.num_modified_rows(), Some(11)); - assert_eq!(exec.progress(), Some(1.0)); assert_eq!(exec.display_message(), Some("Done after retry")); assert_eq!( exec.diagnostic_info(), From 43183aeb41aa88bf6db7afebc909fd923c207618 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 27 May 2026 11:22:06 +0000 Subject: [PATCH 6/7] krn-status-fields: mirror extended-status accessors on async handle + errorDetailsJson gating doc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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` - `display_message() -> Option` - `diagnostic_info() -> Option` - `error_details_json() -> Option` 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>` 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` 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 --- napi/src/statement.rs | 13 +- src/kernel_error.rs | 8 + src/statement/executed.rs | 14 +- src/statement/executed_async.rs | 142 ++++++++++++++-- src/statement/mutable.rs | 7 + src/types/sea.rs | 13 ++ tests/v0_async_execute_e2e.rs | 46 +++++ tests/v0_async_execute_wiremock.rs | 259 +++++++++++++++++++++++++++++ 8 files changed, 487 insertions(+), 15 deletions(-) diff --git a/napi/src/statement.rs b/napi/src/statement.rs index bdc3b49b..deef3dad 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -222,8 +222,17 @@ impl Statement { /// Server-supplied JSON blob with extended error details. Mirrors /// Thrift's `TGetOperationStatusResp.errorDetailsJson`. /// Pass-through string — JS callers parse with `JSON.parse` if - /// they need structured access. **Unbounded:** server can return - /// a multi-MB blob; size before logging. + /// they need structured access. + /// + /// **Server-side gating:** populated only when the workspace has + /// `spark.databricks.sql.errorDetailsJson.enabled = true` on the + /// underlying SQL cluster. The flag is internal-only / default- + /// false in the Databricks runtime, so for most JS callers this + /// will return `null`. Admin-enabled workspaces return content + /// shaped like `{"errorClass": "...", "messageTemplate": "..."}`. + /// + /// **Unbounded:** when populated, server can return a multi-MB + /// blob; size before logging. #[napi] pub async fn error_details_json(&self) -> napi::Result> { let inner = Arc::clone(&self.inner); diff --git a/src/kernel_error.rs b/src/kernel_error.rs index bc360f82..06774cff 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -211,6 +211,14 @@ pub struct Error { /// terminal-error statements. Pass-through string — wrappers parse /// if they need structured access. Mirrors the same-named Thrift /// field. + /// + /// **Server-side gating:** populated only when the workspace has + /// `spark.databricks.sql.errorDetailsJson.enabled = true` on the + /// SQL cluster (`internal()`, default false in + /// `DatabricksSQLConf.scala` — not settable via session-conf). + /// Most workspaces will return `None` here even on terminal- + /// error statements; admin-enabled workspaces return content + /// shaped like `{"errorClass": "...", "messageTemplate": "..."}`. pub error_details_json: Option, /// Underlying cause. Boxed to keep the struct stack-friendly. diff --git a/src/statement/executed.rs b/src/statement/executed.rs index b80ff909..32f5c375 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -173,8 +173,18 @@ impl ExecutedStatement { /// only. The corresponding details for Failed statements flow /// through the returned `Error`, not this accessor. /// - /// **Unbounded:** the server can return a multi-MB blob. Wrappers - /// surfacing this should bound size before logging. + /// **Server-side gating:** populated only when the workspace has + /// `spark.databricks.sql.errorDetailsJson.enabled = true` set on + /// the underlying SQL cluster. The flag is `internal()` and + /// false-by-default in `DatabricksSQLConf.scala`, so it is NOT + /// settable from a client session-configuration request. Most + /// workspaces will return `None` here; admin-enabled workspaces + /// return content shaped like + /// `{"errorClass": "...", "messageTemplate": "..."}`. + /// + /// **Unbounded:** when populated, the server can return a + /// multi-MB blob. Wrappers surfacing this should bound size + /// before logging. pub fn error_details_json(&self) -> Option<&str> { self.status.error_details_json.as_deref() } diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 9264779b..d8e41dbf 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -29,17 +29,20 @@ //! ## Extended SEA status fields (`num_modified_rows`, //! `display_message`, `diagnostic_info`, `error_details_json`) //! -//! These accessors live on the **sync** [`crate::ExecutedStatement`] -//! handle only. Async-consumption callers who need them should use -//! [`crate::statement::mutable::Statement::execute`] (which drives the -//! polling loop internally and returns a sync handle) rather than -//! `submit()`. The async surface is shaped for the -//! poll-loop-without-metadata use case; mirroring the accessors here -//! requires storing a status snapshot per-poll, which is tracked as a -//! follow-up. Wrappers presenting a Thrift-shaped operation API to -//! their host language (e.g. the napi binding's `Statement` class -//! mirroring `IOperation`) route through the sync handle so the -//! extended fields are available alongside fetch / cancel / close. +//! Mirrored from the sync [`crate::ExecutedStatement`] handle: +//! [`ExecutedAsyncStatement::num_modified_rows`] / +//! [`ExecutedAsyncStatement::display_message`] / +//! [`ExecutedAsyncStatement::diagnostic_info`] / +//! [`ExecutedAsyncStatement::error_details_json`] all return the value +//! from the most recent SEA `StatementStatus` this handle has +//! observed (initial `submit_statement` response or any subsequent +//! `status()` / `await_result` poll). The Thrift `IOperation.status()` +//! contract — same field set available on the same handle regardless +//! of how the caller drove polling — is preserved on both kernel +//! consumption modes. Wrappers presenting a Thrift-shaped operation +//! API to their host language (e.g. the napi binding's `Statement` +//! class) can route through whichever handle their language idiom +//! prefers; field availability is identical. use crate::client::ExecuteResponse; use crate::kernel_error::Error; @@ -143,6 +146,25 @@ pub struct ExecutedAsyncStatement { /// short-circuited) `close()`. Tells `Drop` to skip its /// fire-and-forget cleanup. closed: Arc, + /// Last SEA `StatementStatus` observed by this handle (initial + /// `submit_statement` response or any subsequent `status()` / + /// `await_result` poll). Read by the `num_modified_rows()` / + /// `display_message()` / `diagnostic_info()` / `error_details_json()` + /// accessors — matching the same field set the sync + /// [`crate::ExecutedStatement`] exposes so the napi binding's + /// `Statement` JS class (which mirrors the Thrift + /// `TGetOperationStatusResp` field set) sees a uniform contract + /// whether the kernel handle was produced via `execute()` or + /// `submit()`. + /// + /// `std::sync::Mutex` (not `tokio::sync::Mutex`): the guard is + /// only held across the cheap `Option::clone()` / + /// `Option::replace` paths inside the accessors and the poll + /// loop's post-await write. Holding it across `.await` would + /// pessimise scheduling without buying anything — the accessors + /// don't `.await` and the poll loop releases the lock before + /// every network round-trip. + latest_status: Arc>, } impl ExecutedAsyncStatement { @@ -154,17 +176,107 @@ impl ExecutedAsyncStatement { /// `wait_timeout=0s`, so the server returns `Pending`/`Running` and /// the flag starts `false`; the share-and-flip pattern still /// applies once the caller (or `Drop`) closes either handle. + /// + /// `initial_status` is the SEA `StatementStatus` from the + /// `submit_statement` response — the very first observation the + /// kernel has of this server-side statement. Stored so accessors + /// return useful values even before the caller drives a single + /// `status()` / `await_result()` poll (e.g. when the server + /// already finished by the time `submit` returned). pub(crate) fn new( session: Arc, statement_id: String, valid: ValidityFlag, closed: Arc, + initial_status: crate::types::sea::StatementStatus, ) -> Self { Self { session, statement_id, valid, closed, + latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + } + } + + /// Number of rows modified by the statement (UPDATE / INSERT / + /// DELETE / MERGE). Reflects the most recent SEA + /// `StatementStatus` this handle has seen (initial submit + /// response, or any subsequent `status()` / `await_result()` + /// poll). Absent on SELECT and on warehouses that don't surface + /// the counter. + /// + /// Mirrors the same-named accessor on the sync + /// [`crate::ExecutedStatement`] and the same-named optional field + /// on the Thrift `TGetOperationStatusResp`. + pub fn num_modified_rows(&self) -> Option { + self.latest_status + .lock() + .ok() + .and_then(|s| s.num_modified_rows) + } + + /// Server-supplied user-facing message. Reflects the most recent + /// SEA `StatementStatus` this handle has seen. + /// + /// **PII / sensitive-data note:** server-supplied free-form text + /// may include SQL fragments or parameter values. Redact before + /// centralised logging. + pub fn display_message(&self) -> Option { + self.latest_status + .lock() + .ok() + .and_then(|s| s.display_message.clone()) + } + + /// Server-supplied diagnostic detail — multi-line operator / + /// stack context. Reflects the most recent SEA `StatementStatus` + /// this handle has seen. + /// + /// **PII / sensitive-data note:** like `display_message`, this is + /// server-supplied free-form text and may include SQL fragments + /// or values. Redact before centralised logging. + pub fn diagnostic_info(&self) -> Option { + self.latest_status + .lock() + .ok() + .and_then(|s| s.diagnostic_info.clone()) + } + + /// Server-supplied JSON blob with extended error details. + /// Reflects the most recent SEA `StatementStatus` this handle has + /// seen. + /// + /// **Server-side gating:** populated only when the workspace has + /// `spark.databricks.sql.errorDetailsJson.enabled = true` set on + /// the cluster (per `DatabricksSQLConf` — internal flag, default + /// false, not settable via session-conf). Outside of admin- + /// enabled workspaces the field is always None even on Failed + /// statements that otherwise populate `display_message` / + /// `diagnostic_info`. + /// + /// **Unbounded:** when populated, content is `{"errorClass": "...", + /// "messageTemplate": "..."}` server-side, but the kernel passes + /// the string through verbatim — wrappers parse if they need + /// structured access and bound size before logging. + pub fn error_details_json(&self) -> Option { + self.latest_status + .lock() + .ok() + .and_then(|s| s.error_details_json.clone()) + } + + /// Internal helper — overwrite the cached `StatementStatus` with + /// a fresh poll's response. Called by `status()` / + /// `await_result()` after every successful + /// `statement_status` RPC. Lock poisoning is intentionally + /// swallowed: a poisoned lock here would only happen if a panic + /// landed mid-write, and the recovery path is to keep the prior + /// status visible (worse: a fresh poll's status lost; better: + /// the handle's accessor surface keeps working). + fn record_latest_status(&self, fresh: crate::types::sea::StatementStatus) { + if let Ok(mut guard) = self.latest_status.lock() { + *guard = fresh; } } @@ -181,6 +293,10 @@ impl ExecutedAsyncStatement { .transport() .statement_status(&self.statement_id) .await?; + // Cache the wire status so the extended-field accessors + // reflect what THIS handle has observed (instead of the + // stale initial-submit snapshot). + self.record_latest_status(response.status.clone()); Ok(StatementStatus::from_sea_response(&response)) } .instrument(span) @@ -232,6 +348,10 @@ impl ExecutedAsyncStatement { .transport() .statement_status(&self.statement_id) .await?; + // Cache the wire status so the extended-field + // accessors reflect THIS poll's observation — not the + // initial-submit snapshot that's now stale by minutes. + self.record_latest_status(response.status.clone()); match StatementStatus::from_sea_response(&response) { StatementStatus::Succeeded | StatementStatus::Closed => { cancel_guard.defuse(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 7f43c106..12b89441 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -230,6 +230,13 @@ impl Statement { response.statement_id, valid, closed, + // Seed the executed handle with the SEA status the + // server returned on the initial `submit_statement` + // response. Subsequent `status()` / `await_result()` + // polls overwrite it, but accessors return useful + // values immediately even before the caller drives + // the first poll. + response.status, )) } .instrument(span) diff --git a/src/types/sea.rs b/src/types/sea.rs index 0ae95e82..fda2f6be 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -84,6 +84,19 @@ pub struct StatementStatus { /// Pass-through string — wrappers parse if they need structured /// access. /// + /// **Server-side gating:** populated only when the workspace has + /// `spark.databricks.sql.errorDetailsJson.enabled = true` set on + /// the underlying SQL cluster. The flag is declared in + /// `DatabricksSQLConf.scala` as `internal()` with + /// `createWithDefault(false)`, so it is NOT settable from a + /// client session-configuration request (verified empirically on + /// 2026-05-27: pecotesting returns `[CONFIG_NOT_AVAILABLE] + /// SQLSTATE: 42K0I` when the client attempts to SET it). When the + /// flag is off the field is `None` even on terminal-error + /// statements that otherwise populate `display_message` / + /// `diagnostic_info`. When populated, the content format is + /// `{"errorClass": "...", "messageTemplate": "..."}`. + /// /// **Unbounded:** the server can return a multi-MB blob. Wrappers /// surfacing this should bound size before logging. #[serde(default)] diff --git a/tests/v0_async_execute_e2e.rs b/tests/v0_async_execute_e2e.rs index b7a637ff..c28c218c 100644 --- a/tests/v0_async_execute_e2e.rs +++ b/tests/v0_async_execute_e2e.rs @@ -236,3 +236,49 @@ async fn re_submit_invalidates_prior_async_handle() { async_exec_y.close().await.expect("close Y"); session.close().await.expect("session close"); } + +// ─── PR #23: extended status accessors on the async handle ────────── +// +// These mirror the sync-handle live-warehouse tests in +// `v0_execute_e2e.rs`. They run a real submit + await_result against +// pecotesting (or whatever workspace `DATABRICKS_*` env vars point +// at) and assert that the four extended-field accessors on +// `ExecutedAsyncStatement` reflect the terminal poll's status. +// +// As with the sync e2e, the SEA SQL warehouse path does NOT populate +// these fields on a simple SELECT today — the test asserts the +// accessor wiring (no panic, accessor returns the wire-shape `None`) +// rather than expecting non-None values from the server. + +#[tokio::test] +#[ignore] +async fn live_async_handle_exposes_extended_status_accessors() { + let session = live_session().await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let async_exec = stmt.submit().await.expect("submit SELECT 1"); + + // Drive to terminal so the cached status reflects the final + // wire response (not the initial `PENDING` / `RUNNING` from + // submit). + let _stream = async_exec + .await_result() + .await + .expect("await_result should reach SUCCEEDED on SELECT 1"); + + // The accessors must compile and resolve without panicking. The + // SEA wire emits None for these on SQL-warehouse SELECT today; + // log the snapshot so a future server-side expansion is visible + // in the test output without flipping the assertion. + eprintln!( + "live async_exec status snapshot: num_modified_rows={:?} display_message={:?} diagnostic_info={:?} error_details_json={:?}", + async_exec.num_modified_rows(), + async_exec.display_message(), + async_exec.diagnostic_info(), + async_exec.error_details_json(), + ); + assert_eq!(async_exec.num_modified_rows(), None); + + async_exec.close().await.expect("close"); + session.close().await.expect("session close"); +} diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index c86f79e4..9c429405 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -563,3 +563,262 @@ async fn await_result_drop_fires_cancel_statement() { "await_result drop should fire at least one cancel_statement; got {cancel_calls}" ); } + +// ─── Extended SEA status fields on the async handle (PR #23) ──────── +// +// The accessors `num_modified_rows()` / `display_message()` / +// `diagnostic_info()` / `error_details_json()` on +// `ExecutedAsyncStatement` reflect the most recent +// `StatementStatus` this handle has observed (initial submit +// response, or any subsequent `status()` / `await_result` poll). +// The tests below pin three load-bearing properties: +// +// 1. After `await_result()` resolves to terminal SUCCEEDED, the +// accessors return the TERMINAL poll's extended fields, not the +// initial PENDING / RUNNING ones. +// 2. When `submit()` returns immediately with an already-terminal +// response (server completed the query during the wait window), +// the accessors expose those fields even without the caller +// driving a single `status()` poll. +// 3. A `status()` call updates the cached snapshot — a later +// accessor reflects that poll, not the initial-submit response. + +fn succeeded_inline_body_with_status( + statement_id: &str, + batch: &RecordBatch, + num_modified_rows: Option, + display_message: Option<&str>, + diagnostic_info: Option<&str>, + error_details_json: Option<&str>, +) -> String { + let ipc = arrow_ipc_bytes(batch); + let attachment = STANDARD.encode(&ipc); + let columns: Vec<_> = batch + .schema() + .fields() + .iter() + .enumerate() + .map(|(i, f)| { + json!({ + "name": f.name(), + "type_name": match f.data_type() { + DataType::Int64 => "BIGINT", + _ => "STRING", + }, + "type_text": match f.data_type() { + DataType::Int64 => "BIGINT", + _ => "STRING", + }, + "position": i as i32, + }) + }) + .collect(); + + let mut status = json!({ "state": "SUCCEEDED" }); + let status_obj = status.as_object_mut().unwrap(); + if let Some(n) = num_modified_rows { + status_obj.insert("num_modified_rows".to_string(), json!(n)); + } + if let Some(m) = display_message { + status_obj.insert("display_message".to_string(), json!(m)); + } + if let Some(d) = diagnostic_info { + status_obj.insert("diagnostic_info".to_string(), json!(d)); + } + if let Some(e) = error_details_json { + status_obj.insert("error_details_json".to_string(), json!(e)); + } + + json!({ + "statement_id": statement_id, + "status": status, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": batch.num_columns() as i32, + "columns": columns, + }, + "total_chunk_count": 1, + "total_row_count": batch.num_rows() as i64, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows() as i64, + "byte_count": ipc.len() as i64, + "attachment": attachment, + }, + }) + .to_string() +} + +#[tokio::test] +async fn async_await_result_caches_terminal_status_for_accessors() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + // Initial submit returns PENDING — no extended fields. + mount_submit(&server, pending_body("stmt-async-status")).await; + + // First poll RUNNING (no fields), then terminal SUCCEEDED with + // all extended fields populated. The handle must reflect the + // terminal poll's values, not the initial PENDING snapshot. + let batch = int64_batch("n", vec![1]); + mount_status_sequence( + &server, + "stmt-async-status", + vec![ + running_body("stmt-async-status"), + succeeded_inline_body_with_status( + "stmt-async-status", + &batch, + Some(17), + Some("All good (terminal)"), + Some("operator=Scan; stage=Execute"), + Some(r#"{"errorClass":"NONE"}"#), + ), + ], + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("UPDATE t SET x = 1"); + let async_exec = stmt.submit().await.expect("submit"); + + // Before any poll: accessors reflect the initial PENDING + // submit response, which had no extended fields. + assert_eq!(async_exec.num_modified_rows(), None); + assert_eq!(async_exec.display_message(), None); + + // Drive polling to completion. The poll loop overwrites the + // cached status on every wire response — the terminal poll's + // extended fields must now be visible. + let _stream = async_exec + .await_result() + .await + .expect("await_result should reach SUCCEEDED"); + + assert_eq!(async_exec.num_modified_rows(), Some(17)); + assert_eq!( + async_exec.display_message().as_deref(), + Some("All good (terminal)") + ); + assert_eq!( + async_exec.diagnostic_info().as_deref(), + Some("operator=Scan; stage=Execute") + ); + assert_eq!( + async_exec.error_details_json().as_deref(), + Some(r#"{"errorClass":"NONE"}"#) + ); + + async_exec.close().await.expect("close"); +} + +#[tokio::test] +async fn async_submit_caches_initial_terminal_status() { + // If the server completes the query inside the + // `submit_statement` request (returns SUCCEEDED on the initial + // response with all fields populated), the accessors expose + // those values immediately — no poll needed. This matches + // Thrift's behaviour where `executeStatement` with direct + // results already carries the operation status fields. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("n", vec![1]); + mount_submit( + &server, + succeeded_inline_body_with_status( + "stmt-async-fast", + &batch, + Some(5), + Some("Done at submit time"), + None, + None, + ), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("UPDATE t SET x = 1"); + let async_exec = stmt.submit().await.expect("submit"); + + // Without a single poll, accessors must already expose what the + // initial submit response carried. + assert_eq!(async_exec.num_modified_rows(), Some(5)); + assert_eq!( + async_exec.display_message().as_deref(), + Some("Done at submit time") + ); + assert_eq!(async_exec.diagnostic_info(), None); + assert_eq!(async_exec.error_details_json(), None); + + async_exec.close().await.expect("close"); +} + +#[tokio::test] +async fn async_status_call_refreshes_cached_status() { + // `status()` must refresh the cached snapshot used by the + // extended-field accessors, not just return the enum. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + // Submit returns PENDING (no extended fields). + mount_submit(&server, pending_body("stmt-async-refresh")).await; + + // A status() poll returns SUCCEEDED with extended fields. The + // status() call itself must overwrite the cached snapshot. + let batch = int64_batch("n", vec![1]); + mount_status_sequence( + &server, + "stmt-async-refresh", + vec![succeeded_inline_body_with_status( + "stmt-async-refresh", + &batch, + Some(99), + Some("Refreshed via status()"), + None, + None, + )], + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("UPDATE t SET x = 1"); + let async_exec = stmt.submit().await.expect("submit"); + + // Before status(): accessors reflect PENDING (no fields). + assert_eq!(async_exec.num_modified_rows(), None); + + let s = async_exec.status().await.expect("status"); + // The terminal status arm of the enum. + assert!( + matches!( + s, + databricks_sql_kernel::StatementStatus::Succeeded + | databricks_sql_kernel::StatementStatus::Closed + ), + "expected Succeeded/Closed enum variant, got {s:?}" + ); + + // After status(): accessors reflect the status() poll's values. + assert_eq!(async_exec.num_modified_rows(), Some(99)); + assert_eq!( + async_exec.display_message().as_deref(), + Some("Refreshed via status()") + ); + + async_exec.close().await.expect("close"); +} From 38ab40de238b8d61a35881bb085d691cc32125b8 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Wed, 27 May 2026 18:42:35 +0000 Subject: [PATCH 7/7] krn-status-fields: lift carry_extended_status to shared helper + cover async error paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/client/sea.rs | 33 +++--- src/kernel_error.rs | 37 +++++++ src/statement/executed_async.rs | 26 ++++- tests/v0_async_execute_wiremock.rs | 161 +++++++++++++++++++++++++++++ tests/v0_execute_wiremock.rs | 79 ++++++++++++++ 5 files changed, 312 insertions(+), 24 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index a0d87f69..f3f6cab7 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -53,24 +53,6 @@ enum StatementOutcome { Err(Error), } -/// Copy the SEA extended status fields (`display_message`, -/// `diagnostic_info`, `error_details_json`) from a wire status onto a -/// kernel `Error`. Mirrors the Thrift `TGetOperationStatusResp` / -/// `TStatus` contract where the same fields ride on the operation -/// status across terminal-error states. -fn carry_extended_status(mut error: Error, status: &crate::types::sea::StatementStatus) -> Error { - if let Some(msg) = status.display_message.as_ref() { - error = error.with_display_message(msg); - } - if let Some(info) = status.diagnostic_info.as_ref() { - error = error.with_diagnostic_info(info); - } - if let Some(json) = status.error_details_json.as_ref() { - error = error.with_error_details_json(json); - } - error -} - /// SEA client for the Databricks SQL Statement Execution API. /// /// This client implements the `Transport` trait using REST endpoints. @@ -251,13 +233,19 @@ impl SeaRestTransport { // Carry the extended status fields onto the Error so // wrappers see what Thrift's `TGetOperationStatusResp` // surfaces on terminal-error states. - StatementOutcome::Err(carry_extended_status(error, &response.status)) + StatementOutcome::Err(crate::kernel_error::carry_extended_status( + error, + &response.status, + )) } StatementState::Canceled => { let error = Error::invalid_state() .message("Statement was canceled") .with_query_id(&response.statement_id); - StatementOutcome::Err(carry_extended_status(error, &response.status)) + StatementOutcome::Err(crate::kernel_error::carry_extended_status( + error, + &response.status, + )) } StatementState::Closed => { // Closed with result data is valid for inline results @@ -270,7 +258,10 @@ impl SeaRestTransport { let error = Error::invalid_state() .message("Statement was closed") .with_query_id(&response.statement_id); - StatementOutcome::Err(carry_extended_status(error, &response.status)) + StatementOutcome::Err(crate::kernel_error::carry_extended_status( + error, + &response.status, + )) } } StatementState::Pending | StatementState::Running => { diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 06774cff..2a07e2d0 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -617,6 +617,43 @@ impl From for Error { /// Convenience alias. pub type Result = std::result::Result; +// ─── SEA extended-status carry helpers ────────────────────────────── + +/// Copy the SEA extended status fields (`display_message`, +/// `diagnostic_info`, `error_details_json`) from a wire status onto a +/// kernel [`Error`]. +/// +/// Mirrors the Thrift `TGetOperationStatusResp` / `TStatus` contract +/// where the same fields ride on the operation status across +/// terminal-error states. Called by both the sync polling path +/// (`client::sea::SeaRestTransport::terminal_outcome`) and the async +/// poll-driver paths (`statement::executed_async::StatementStatus:: +/// from_sea_response`'s `Failed` arm + `await_result`'s `Cancelled` +/// arm) so a Thrift-migrating wrapper sees the same field set on the +/// returned `Error` regardless of which kernel handle the caller is +/// driving. +/// +/// `pub(crate)` — internal to the kernel; downstream consumers should +/// read the fields off the returned `Error` directly. The wire-shape +/// `types::sea::StatementStatus` is referenced by full path to avoid +/// pulling the dependency into the `kernel_error` module's public +/// imports. +pub(crate) fn carry_extended_status( + mut error: Error, + status: &crate::types::sea::StatementStatus, +) -> Error { + if let Some(msg) = status.display_message.as_ref() { + error = error.with_display_message(msg); + } + if let Some(info) = status.diagnostic_info.as_ref() { + error = error.with_diagnostic_info(info); + } + if let Some(json) = status.error_details_json.as_ref() { + error = error.with_error_details_json(json); + } + error +} + // ─── SQLSTATE extraction helpers ──────────────────────────────────── /// Extract a SQLSTATE from a free-form error message. diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index d8e41dbf..c8fe7a24 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -128,7 +128,17 @@ impl StatementStatus { error = error.with_error_code(ec); } } - StatementStatus::Failed(error) + // Mirror the sync path: carry the SEA extended status + // fields (display_message / diagnostic_info / + // error_details_json) onto the returned Error so the + // napi binding's JS Error envelope sees the same field + // set Thrift's `TGetOperationStatusResp` exposed on + // failed operations, regardless of which kernel handle + // surfaced the failure. + StatementStatus::Failed(crate::kernel_error::carry_extended_status( + error, + &response.status, + )) } } } @@ -365,8 +375,18 @@ impl ExecutedAsyncStatement { } StatementStatus::Cancelled => { cancel_guard.defuse(); - return Err(Error::invalid_state() - .message(format!("Statement {} was cancelled", self.statement_id))); + // Carry the SEA extended status fields onto + // the returned Error — mirrors the sync + // `terminal_outcome::Canceled` arm so the + // Cancelled-state envelope contract is + // identical across kernel handles. + let error = Error::invalid_state() + .message(format!("Statement {} was cancelled", self.statement_id)) + .with_query_id(&self.statement_id); + return Err(crate::kernel_error::carry_extended_status( + error, + &response.status, + )); } StatementStatus::Pending | StatementStatus::Running => { if start.elapsed() > cfg.poll_timeout { diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 9c429405..e94e9463 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -170,6 +170,54 @@ fn failed_body(statement_id: &str, message: &str, sql_state: &str) -> String { .to_string() } +/// `FAILED` body with the three SEA extended status fields populated. +/// Pins the async polling path's `Error.display_message` / +/// `diagnostic_info` / `error_details_json` carry — the async +/// equivalent of the sync `failed_body_with_extended_fields`. +fn failed_body_with_extended_fields( + statement_id: &str, + message: &str, + sql_state: &str, + display_message: &str, + diagnostic_info: &str, + error_details_json: &str, +) -> String { + json!({ + "statement_id": statement_id, + "status": { + "state": "FAILED", + "error": { + "error_code": "INVALID_PARAMETER_VALUE", + "message": format!("{message}. SQLSTATE: {sql_state}"), + }, + "display_message": display_message, + "diagnostic_info": diagnostic_info, + "error_details_json": error_details_json, + }, + }) + .to_string() +} + +/// `CANCELED` body with the three SEA extended status fields +/// populated. Used to pin the async path's +/// `await_result::StatementStatus::Cancelled` arm carrying the +/// extended fields onto the returned `Error`. +fn cancelled_body_with_extended_fields( + statement_id: &str, + display_message: &str, + diagnostic_info: &str, +) -> String { + json!({ + "statement_id": statement_id, + "status": { + "state": "CANCELED", + "display_message": display_message, + "diagnostic_info": diagnostic_info, + }, + }) + .to_string() +} + fn cancelled_body(statement_id: &str) -> String { json!({ "statement_id": statement_id, @@ -822,3 +870,116 @@ async fn async_status_call_refreshes_cached_status() { async_exec.close().await.expect("close"); } + +#[tokio::test] +async fn async_await_result_failed_carries_extended_status_fields_onto_error() { + // Pins the async polling path's terminal-error contract, + // companion to the sync-path `execute_failed_carries_extended_status_fields_onto_error` + // in `tests/v0_execute_wiremock.rs`. Regression guard for the + // `executed_async.rs::from_sea_response::Failed` carry. Prior to + // the carry being added, the kernel `Error` returned from + // `await_result()` would have NONE of these three fields populated + // even when the SEA wire response did — silently breaking the + // Thrift-parity contract documented at `napi/src/error.rs`. + use databricks_sql_kernel::ErrorCode; + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_submit(&server, pending_body("stmt-async-fail-ext")).await; + mount_status_sequence( + &server, + "stmt-async-fail-ext", + vec![failed_body_with_extended_fields( + "stmt-async-fail-ext", + "table not found", + "42P01", + "User-facing reason from server", + "operator=Scan; stage=Analyze; full stack ...", + r#"{"errorClass":"TABLE_OR_VIEW_NOT_FOUND"}"#, + )], + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT * FROM does_not_exist"); + let async_exec = stmt.submit().await.expect("submit"); + + let err = match async_exec.await_result().await { + Ok(_) => panic!("await_result on FAILED should error"), + Err(e) => e, + }; + + assert_eq!(err.code, ErrorCode::SqlError); + assert_eq!(err.sql_state.as_deref(), Some("42P01")); + assert_eq!( + err.display_message.as_deref(), + Some("User-facing reason from server"), + "async await_result must carry display_message from FAILED wire envelope (Thrift-parity contract)" + ); + assert_eq!( + err.diagnostic_info.as_deref(), + Some("operator=Scan; stage=Analyze; full stack ...") + ); + assert_eq!( + err.error_details_json.as_deref(), + Some(r#"{"errorClass":"TABLE_OR_VIEW_NOT_FOUND"}"#) + ); +} + +#[tokio::test] +async fn async_await_result_cancelled_carries_extended_status_fields_onto_error() { + // Pins the Cancelled arm of `await_result`. The server can + // include `display_message` (e.g. "Statement was canceled by the + // user") on a CANCELED response; the kernel must carry it onto + // the returned Error. Regression guard for the + // `executed_async.rs::await_result` Cancelled-arm carry. + use databricks_sql_kernel::ErrorCode; + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_submit(&server, pending_body("stmt-async-cancel-ext")).await; + mount_status_sequence( + &server, + "stmt-async-cancel-ext", + vec![cancelled_body_with_extended_fields( + "stmt-async-cancel-ext", + "Statement was canceled by the user", + "operator=Scan; cancelled-mid-execute", + )], + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + let async_exec = stmt.submit().await.expect("submit"); + + let err = match async_exec.await_result().await { + Ok(_) => panic!("await_result on CANCELED should error"), + Err(e) => e, + }; + // Cancelled maps to InvalidArgument per the kernel's invalid-state + // helper today; assert the message + extended fields rather than + // pinning the code (the categorisation may move under ErrorCode + // taxonomy expansion). + assert!( + err.message.contains("cancelled"), + "message should mention cancellation, got: {}", + err.message + ); + assert_eq!( + err.display_message.as_deref(), + Some("Statement was canceled by the user"), + "Cancelled arm must carry display_message from CANCELED wire envelope" + ); + assert_eq!( + err.diagnostic_info.as_deref(), + Some("operator=Scan; cancelled-mid-execute") + ); + let _ = ErrorCode::SqlError; // silence unused-import warning if the assert above changes +} diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index d0f8313a..7c1c5a89 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -162,6 +162,33 @@ fn failed_body(statement_id: &str, message: &str, sql_state: &str) -> String { .to_string() } +/// `FAILED` body with the three SEA extended status fields populated. +/// Pins the kernel's `Error.display_message` / `diagnostic_info` / +/// `error_details_json` carry on the sync polling path. +fn failed_body_with_extended_fields( + statement_id: &str, + message: &str, + sql_state: &str, + display_message: &str, + diagnostic_info: &str, + error_details_json: &str, +) -> String { + json!({ + "statement_id": statement_id, + "status": { + "state": "FAILED", + "error": { + "error_code": "INVALID_PARAMETER_VALUE", + "message": format!("{message}. SQLSTATE: {sql_state}"), + }, + "display_message": display_message, + "diagnostic_info": diagnostic_info, + "error_details_json": error_details_json, + }, + }) + .to_string() +} + async fn mount_execute(server: &MockServer, body: String) { Mock::given(method("POST")) .and(path("/api/2.0/sql/statements")) @@ -790,3 +817,55 @@ async fn polling_path_carries_terminal_status_not_initial() { exec.close().await.expect("close"); } + +#[tokio::test] +async fn execute_failed_carries_extended_status_fields_onto_error() { + // Pins the sync polling path's terminal-error contract: when the + // SEA wire response on a FAILED statement includes + // `display_message` / `diagnostic_info` / `error_details_json`, + // the kernel `Error` returned from `Statement::execute()` carries + // all three. Mirrors the Thrift `TGetOperationStatusResp` field + // set so a Thrift-migrating wrapper (e.g. the napi binding's JS + // Error envelope) sees identical content regardless of which + // path surfaced the failure. Regression guard for the + // `terminal_outcome::Failed → carry_extended_status` wiring at + // `src/client/sea.rs`. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let body = failed_body_with_extended_fields( + "stmt-fail-ext", + "table not found", + "42P01", + "User-facing reason from server", + "operator=Scan; stage=Analyze; full stack ...", + r#"{"errorClass":"TABLE_OR_VIEW_NOT_FOUND","messageTemplate":"..."}"#, + ); + mount_execute(&server, body).await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT * FROM does_not_exist"); + let err = match stmt.execute().await { + Ok(_) => panic!("execute should fail on FAILED state"), + Err(e) => e, + }; + + assert_eq!(err.code, ErrorCode::SqlError); + assert_eq!(err.sql_state.as_deref(), Some("42P01")); + assert_eq!( + err.display_message.as_deref(), + Some("User-facing reason from server"), + "display_message must carry through from FAILED wire envelope" + ); + assert_eq!( + err.diagnostic_info.as_deref(), + Some("operator=Scan; stage=Analyze; full stack ...") + ); + assert_eq!( + err.error_details_json.as_deref(), + Some(r#"{"errorClass":"TABLE_OR_VIEW_NOT_FOUND","messageTemplate":"..."}"#) + ); +}