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 b1dcbf0d..84c734e2 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -140,6 +140,110 @@ 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 + } + + // 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- + /// 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. + /// + /// **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); + 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 3bc4a8bb..da714288 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). @@ -91,8 +91,78 @@ 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. + /// 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>, +} + +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` 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: 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(), + } + } } /// Configuration for the HTTP client. @@ -186,15 +256,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); } @@ -205,12 +282,63 @@ 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 { + // `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 + )) + })?; + // 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(s) from in-memory bytes ({} bytes)", + cert_count, + pem.len() + ); } // Apply proxy configuration @@ -808,7 +936,132 @@ 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] + 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 + // **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_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()); + } + + #[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] diff --git a/src/client/sea.rs b/src/client/sea.rs index 8c891f65..a962937b 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -295,10 +295,22 @@ 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(crate::kernel_error::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(crate::kernel_error::carry_extended_status( + error, + &response.status, + )) } StatementState::Closed => { // Closed with result data is valid for inline results @@ -308,7 +320,13 @@ 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(crate::kernel_error::carry_extended_status( + error, + &response.status, + )) } } StatementState::Pending | StatementState::Running => { @@ -332,7 +350,11 @@ impl SeaRestTransport { } tokio::time::sleep(self.config.poll_interval).await; - debug!("Polling statement status: {}", r.statement_id); + debug!( + statement_id = %r.statement_id, + state = ?r.status.state, + "Polling statement status" + ); current_response = self.get_statement_status(&r.statement_id).await?; } } @@ -447,15 +469,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 / display_message / etc. without a second + // GetStatementStatus round-trip. Ok(ExecuteResult { statement_id: response.statement_id, reader, manifest: response.manifest, - server_state, + status: response.status, }) } } @@ -668,12 +691,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 d30fb0fc..41040dca 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,31 @@ 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` / `display_message` / 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` / + /// `display_message` / etc. without a second GetStatementStatus + /// round-trip. + pub status: StatementStatus, } impl std::fmt::Debug for ExecuteResult { @@ -91,7 +100,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/config.rs b/src/config.rs index 73501734..0d9fbb84 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 @@ -343,13 +344,113 @@ 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. +/// +/// ```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); +/// ``` +// +// 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(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. + /// + /// **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. + /// + /// 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) ─────────────────── @@ -787,4 +888,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/kernel_error.rs b/src/kernel_error.rs index 6e6819da..2a07e2d0 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -187,6 +187,40 @@ 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. + /// + /// **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. pub cause: Option>, } @@ -207,6 +241,9 @@ impl Error { retryable: false, query_id: None, location: None, + display_message: None, + diagnostic_info: None, + error_details_json: None, cause: None, } } @@ -399,6 +436,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 @@ -552,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/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 1de17ba9..a536b488 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1097,7 +1097,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; @@ -1141,7 +1141,14 @@ 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, + display_message: None, + diagnostic_info: None, + error_details_json: None, + }, }) } diff --git a/src/session.rs b/src/session.rs index 82e4fadb..f9b3cb5c 100644 --- a/src/session.rs +++ b/src/session.rs @@ -478,9 +478,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 @@ -562,11 +575,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), @@ -575,15 +588,16 @@ 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(); + // 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 0213dacd..32f5c375 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,85 @@ 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. + /// + /// 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 + } + + // 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()` + /// 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 + /// 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() + } + + /// 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. + /// + /// **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() + } } #[async_trait] diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 91aad839..c8fe7a24 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -25,6 +25,24 @@ //! 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`, +//! `display_message`, `diagnostic_info`, `error_details_json`) +//! +//! 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; @@ -43,6 +61,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 { @@ -100,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, + )) } } } @@ -118,6 +156,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 { @@ -129,17 +186,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; } } @@ -156,6 +303,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) @@ -207,6 +358,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(); @@ -220,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/src/statement/mutable.rs b/src/statement/mutable.rs index cb48b5c6..12b89441 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) @@ -229,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 2a27ccb3..0608363e 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -33,11 +33,94 @@ 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). +// +// 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 { 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, + /// 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. + /// + /// **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)] + 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("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. @@ -571,6 +654,75 @@ mod tests { assert_eq!(manifest.total_row_count, Some(0)); } + #[test] + fn test_statement_status_with_extended_fields() { + // 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, + "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.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.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_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..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, @@ -563,3 +611,375 @@ 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"); +} + +#[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_e2e.rs b/tests/v0_execute_e2e.rs index a6f0ef85..ff778f79 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -828,3 +828,86 @@ 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() + ); + // 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: display_message={:?} diagnostic_info={:?} error_details_json={:?}", + 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"); +} diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index fcab664f..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")) @@ -593,3 +620,252 @@ 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. +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", + 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(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("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.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.display_message(), None); + assert_eq!(exec.diagnostic_info(), None); + assert_eq!(exec.error_details_json(), 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 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("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 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.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"); +} + +#[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":"..."}"#) + ); +}