From 0ab1e0e5c224e6df187c4f61bb8b578c05cb095f Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Sat, 6 Jun 2026 12:13:41 +0000 Subject: [PATCH] feat(metadata/http/pyo3): case-insensitive table_types, parse HTTP error envelope, expose num_modified_rows, attach async statement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Batch-3 kernel changes backing the connector's use_kernel parity work: - metadata: ``filter_tables_by_type`` matches ``table_types`` case-insensitively (``eq_ignore_ascii_case``) so ``tables(['view'])`` matches a ``VIEW`` row regardless of server casing. - client/http: parse the SEA error envelope (``{error_code, message, sql_state}``, also the ``{"error": ...}`` wrapper) on transport-level HTTP errors, attaching ``error_code`` / ``sql_state`` to the returned ``Error`` instead of discarding them into the raw message. - pyo3: expose ``ExecutedStatement.num_modified_rows`` so the connector can surface DML rowcount. - session: add ``Session::attach_async_statement(id)`` (+ pyo3 getter) — re-attach to an already-submitted server statement by its id, yielding an ``ExecutedAsyncStatement`` that can poll ``status`` / await results without having been the submitting handle. SEA keys GetStatementStatus/Result purely on the id, so this enables resuming an async statement whose originating handle was dropped (or lives in another process). The handle is NON-OWNING: it does not close the server statement on ``Drop`` or ``close()`` (starts ``closed=true``), so re-attaching on every poll can't tear down the statement being watched. Seeds initial status from a ``GetStatementStatus``; an unknown/expired id surfaces ``ErrorCode::NotFound`` (404). Verified against a live SEA warehouse: GET after close returns 200 state=CLOSED until TTL, then 404 NOT_FOUND. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- pyo3/src/session.rs | 32 +++++++ pyo3/src/statement.rs | 17 ++++ src/client/http.rs | 143 +++++++++++++++++++++++++++-- src/metadata/thrift_shape.rs | 48 +++++++++- src/session.rs | 87 ++++++++++++++++++ tests/v0_async_execute_wiremock.rs | 135 +++++++++++++++++++++++++++ 6 files changed, 451 insertions(+), 11 deletions(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index d02709ba..4fcd0d79 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -21,6 +21,7 @@ //! pyclass alive longer than the user keeps a reference. use crate::auth::{build_auth_config, OAuthParams}; +use crate::executed_async::ExecutedAsyncStatement; use crate::metadata::Metadata; use crate::statement::Statement; use databricks_sql_kernel::Session as KSession; @@ -341,6 +342,37 @@ impl Session { Ok(Metadata::new(kmeta, inner.runtime.clone())) } + /// Re-attach to an already-submitted server statement by its id, + /// returning an `ExecutedAsyncStatement` the caller can poll + /// (`status()`), await (`await_result()`), or cancel/close — without + /// having been the handle that submitted it. + /// + /// This is the resume path the connector uses for + /// `get_query_state` / `get_async_execution_result`: server + /// statement state is keyed solely by the id, so a caller holding + /// only the id can recover a working handle bound to this session. + /// + /// Issues one `GetStatementStatus` to seed the handle. Raises + /// `KernelError` with code `NotFound` if the server doesn't + /// recognise the id (never submitted, or its result TTL elapsed). A + /// *closed* statement is not an error — the server keeps reporting + /// `CLOSED` (and terminal `SUCCEEDED`/`FAILED`) until GC, so the + /// returned handle's `status()` surfaces the real server state. + fn attach_async_statement( + &self, + py: Python<'_>, + statement_id: String, + ) -> PyResult { + let inner = alive!(self, "Session"); + let runtime = inner.runtime.clone(); + tracing::debug!( + target: crate::logging::PYO3_LOG_TARGET, + "Session.attach_async_statement: re-attaching by id (GIL released)" + ); + let exec = run_kernel!(py, runtime, inner.session.attach_async_statement(statement_id))?; + Ok(ExecutedAsyncStatement::new(exec, runtime)) + } + /// Explicitly close the session. Idempotent. Subsequent calls on /// this `Session` raise `KernelError`. fn close(&mut self, py: Python<'_>) -> PyResult<()> { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 40a2b24c..0810b117 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -279,6 +279,12 @@ pub(crate) struct ExecutedStatement { /// Cached schema. Pulled from the kernel once on construction — /// available even after `close()` so descriptions stay stable. schema: Arc, + /// Rows modified by the statement (DML: INSERT/UPDATE/DELETE/MERGE), + /// or `None` for SELECT / warehouses that don't report it. Cached at + /// construction (it's fixed once the statement completed) so it + /// survives `close()`, like `statement_id` / `schema`. The connector + /// surfaces this as `cursor.rowcount`. + num_modified_rows: Option, } struct ExecutedInner { @@ -291,9 +297,11 @@ impl ExecutedStatement { fn new(exec: KExecutedStatement, runtime: Arc) -> Self { let statement_id = exec.statement_id().to_owned(); let schema = exec.schema(); + let num_modified_rows = exec.num_modified_rows(); Self { statement_id, schema, + num_modified_rows, inner: Some(ExecutedInner { exec, runtime, @@ -310,6 +318,15 @@ impl ExecutedStatement { &self.statement_id } + /// Rows modified by the statement (DML), or `None` for SELECT / + /// warehouses that don't report it. The connector maps this to + /// `cursor.rowcount` (falling back to -1 when `None`). Available + /// after `close()` (cached at construction). + #[getter] + fn num_modified_rows(&self) -> Option { + self.num_modified_rows + } + /// Result schema as a `pyarrow.Schema`. Available even after /// `close()`. fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult> { diff --git a/src/client/http.rs b/src/client/http.rs index 46f81942..486ac680 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -28,12 +28,70 @@ use crate::client::retry::{ }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; +use crate::types::sea::ServiceError; use reqwest::{Client, NoProxy, Proxy, Request, Response}; use std::collections::HashMap; use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use tokio::time::sleep; +/// Build an `Error` for a transport-level non-2xx HTTP response, parsing +/// the SEA error envelope out of the response body when present. +/// +/// The SEA REST API returns a JSON error body — either a bare +/// `{"error_code", "message", "sql_state"}` ([`ServiceError`]) or a +/// `{"error": {...}}` wrapper. Mirrors the statement-level path +/// (`sea.rs terminal_outcome`) so transport-level failures surface the +/// structured `error_code` / `sql_state` instead of only the raw body +/// stuffed into the message. Falls back to `context` (the raw body) as +/// the message when the body isn't a recognised envelope. +/// +/// `context` is a caller-supplied prefix (e.g. "HTTP 400" / retry-timeout +/// detail) folded into the message so existing diagnostics are preserved. +fn http_error(status: u16, body: &str, context: impl std::fmt::Display) -> Error { + #[derive(serde::Deserialize)] + struct ErrorWrapper { + error: ServiceError, + } + // Try the bare envelope first, then the `{"error": ...}` wrapper. + let svc: Option = serde_json::from_str::(body) + .ok() + .filter(|e| e.error_code.is_some() || e.message.is_some() || e.sql_state.is_some()) + .or_else(|| { + serde_json::from_str::(body) + .ok() + .map(|w| w.error) + }); + + let mut err = Error::from_http_status(status); + match svc { + Some(svc) => { + // Prefer the server's structured message; keep the caller + // context as a prefix for continuity with existing logs. + let msg = svc.message.as_deref().unwrap_or(body); + err = err.message(format!("{context}: {msg}")); + if let Some(ec) = svc.error_code.as_deref().filter(|s| !s.is_empty()) { + err = err.with_error_code(ec); + } + // SQL state: explicit field, else the "SQLSTATE: XXXXX" + // pattern in the message — same precedence as terminal_outcome. + let sql_state = svc + .sql_state + .filter(|s| !s.is_empty()) + .or_else(|| crate::kernel_error::extract_sqlstate_from_message(msg)); + if let Some(s) = sql_state { + err = err.with_sql_state(s); + } + } + None => { + // Not a recognised envelope — preserve today's behavior + // (raw body folded into the message). + err = err.message(format!("{context}: {body}")); + } + } + err +} + /// Configuration for HTTP proxy. /// /// When `url` is set, the driver uses the specified proxy for all requests, @@ -781,13 +839,16 @@ impl DatabricksHttpClient { attempts, elapsed.as_secs_f64() ); - return Err(Error::from_http_status(status.as_u16()).message(format!( - "HTTP {} — retry timeout exceeded after {} attempts ({:.1}s): {}", + return Err(http_error( status.as_u16(), - attempts, - elapsed.as_secs_f64(), - error_body - ))); + &error_body, + format_args!( + "HTTP {} — retry timeout exceeded after {} attempts ({:.1}s)", + status.as_u16(), + attempts, + elapsed.as_secs_f64() + ), + )); } last_error = Some(format!("HTTP {}", status.as_u16())); @@ -812,11 +873,11 @@ impl DatabricksHttpClient { start_time.elapsed().as_secs_f64(), status.as_u16() ); - return Err(Error::from_http_status(status.as_u16()).message(format!( - "HTTP {} - {}", + return Err(http_error( status.as_u16(), - error_body - ))); + &error_body, + format_args!("HTTP {}", status.as_u16()), + )); } Err(e) => { if strategy.is_retryable_error(&e) && attempts < max_attempts { @@ -1597,6 +1658,68 @@ lGrv15pBcePj assert_eq!(attempt_count.load(Ordering::SeqCst), 1); } + #[tokio::test] + async fn test_http_error_parses_sea_error_envelope() { + // A transport-level 4xx whose body is the SEA error envelope + // must surface the structured error_code / sql_state on the + // returned Error (not just the raw body in the message), + // mirroring the statement-level terminal_outcome path. + let mock_server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/test")) + .respond_with(ResponseTemplate::new(400).set_body_string( + r#"{"error_code":"BAD_REQUEST","message":"bad thing happened","sql_state":"42000"}"#, + )) + .mount(&mock_server) + .await; + + let client = test_client(&mock_server, fast_retry_config(3)); + let request = client + .inner() + .get(format!("{}/test", mock_server.uri())) + .build() + .unwrap(); + let err = client + .execute(request, RequestType::GetStatementStatus) + .await + .expect_err("400 must error"); + + assert_eq!(err.error_code.as_deref(), Some("BAD_REQUEST")); + assert_eq!(err.sql_state.as_deref(), Some("42000")); + // The structured server message is folded into the message. + assert!( + err.message.contains("bad thing happened"), + "message should carry the server text, got: {}", + err.message + ); + } + + #[tokio::test] + async fn test_http_error_non_envelope_body_falls_back_to_raw() { + // A non-JSON body keeps today's behavior: raw body in the + // message, no structured error_code/sql_state. + let mock_server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/test")) + .respond_with(ResponseTemplate::new(400).set_body_string("plain text error")) + .mount(&mock_server) + .await; + + let client = test_client(&mock_server, fast_retry_config(3)); + let request = client + .inner() + .get(format!("{}/test", mock_server.uri())) + .build() + .unwrap(); + let err = client + .execute(request, RequestType::GetStatementStatus) + .await + .expect_err("400 must error"); + + assert!(err.error_code.is_none()); + assert!(err.message.contains("plain text error")); + } + #[tokio::test] async fn test_idempotent_no_retry_on_401() { let mock_server = MockServer::start().await; diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index 374bc2fc..0f82b304 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -657,7 +657,12 @@ fn filter_tables_by_type(batch: &RecordBatch, types: &[&str]) -> Result RecordBatch { + // Minimal batch carrying only the TABLE_TYPE column that + // `filter_tables_by_type` inspects. + let schema = Arc::new(Schema::new(vec![Field::new( + "TABLE_TYPE", + DataType::Utf8, + true, + )])); + let arr = StringArray::from(types.iter().map(|s| Some(*s)).collect::>()); + RecordBatch::try_new(schema, vec![Arc::new(arr)]).unwrap() + } + + fn kept_types(batch: &RecordBatch) -> Vec { + let arr = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + (0..batch.num_rows()) + .map(|i| arr.value(i).to_owned()) + .collect() + } + + #[test] + fn filter_tables_by_type_is_case_insensitive() { + // Warehouse reports canonical uppercase; a lowercase / mixed-case + // request must still match (JDBC getTables allows any case). + let batch = tables_with_types(&["TABLE", "VIEW", "SYSTEM_TABLE"]); + let out = filter_tables_by_type(&batch, &["view", "Table"]).unwrap(); + assert_eq!(kept_types(&out), vec!["TABLE", "VIEW"]); + } + + #[test] + fn filter_tables_by_type_drops_non_matching_and_nulls() { + let batch = tables_with_types(&["TABLE", "VIEW"]); + let out = filter_tables_by_type(&batch, &["MANAGED"]).unwrap(); + assert_eq!(out.num_rows(), 0); + } } diff --git a/src/session.rs b/src/session.rs index 58fb3494..21c759d8 100644 --- a/src/session.rs +++ b/src/session.rs @@ -63,8 +63,11 @@ use crate::kernel_error::{Error, Result}; use crate::klog::debug; use crate::metadata_v0::Metadata; use crate::reader::ResultReaderFactory; +use crate::statement::executed_async::ExecutedAsyncStatement; use crate::statement::mutable::Statement; +use crate::statement::validity::ValidityFlag; use std::collections::HashMap; +use std::sync::atomic::AtomicBool; use std::sync::Arc; use std::time::Duration; use tracing::{info_span, Instrument, Span}; @@ -341,6 +344,90 @@ impl Session { Metadata::new(Arc::clone(&self.inner)) } + /// Adopt an already-submitted server statement by its id, producing + /// an [`ExecutedAsyncStatement`] that can poll [`status`] / await + /// results / cancel — without having been the handle that submitted + /// it. + /// + /// This is the resume path: a caller (or a different process) that + /// holds only the statement id can re-attach and drive it to + /// completion, fetch its result, or read its terminal state. Server + /// statement state is keyed solely by the id — every + /// `GetStatementStatus` / `GetStatementResult` / cancel / close RPC + /// takes just the id — so the only thing the originating handle + /// carried that a bare id does not is *this session's* transport + /// (auth, retry, poll cadence). Binding the id to this session is + /// exactly what `attach` does. + /// + /// Issues a single `GetStatementStatus` to seed the handle's initial + /// status (mirrors how `submit` seeds it from the submit response), + /// so the extended-status accessors return useful values before the + /// caller drives a poll. **Errors with [`ErrorCode::NotFound`] if + /// the server doesn't recognise the id** (never submitted, or its + /// result TTL elapsed and the server garbage-collected it) — the SEA + /// server returns `404 NOT_FOUND` for an unknown-but-well-formed id, + /// which the transport maps to `NotFound`. A *closed* statement is + /// **not** an error: the server keeps reporting `CLOSED` (and a + /// terminal `SUCCEEDED`/`FAILED` statement keeps reporting that + /// state, with its result) until GC, so `attach` succeeds and + /// [`status`] surfaces the real server state. + /// + /// The returned handle is standalone and **non-owning**: its + /// [`ValidityFlag`] is fresh (not shared with any parent + /// `Statement`, since there is none), and it does **not** close the + /// server statement on `Drop` or via [`close`] — attach is a + /// read-only adopt. The statement's lifecycle stays with whatever + /// submitted it (or an explicit `close_statement`); a transient + /// handle a poller creates and drops must not tear it down. (This is + /// what lets `get_query_state` re-attach on every poll without the + /// poll loop closing the statement it's watching.) + /// + /// [`status`]: ExecutedAsyncStatement::status + /// [`close`]: ExecutedAsyncStatement::close + /// [`ErrorCode::NotFound`]: crate::kernel_error::ErrorCode::NotFound + pub async fn attach_async_statement( + &self, + statement_id: impl Into, + ) -> Result { + let statement_id = statement_id.into(); + let span = self.inner.log_span().clone(); + async { + // Seed initial_status from the wire — the same RPC + // `ExecutedAsyncStatement::status` makes. Surfaces NotFound + // here (rather than on the caller's first poll) for an + // unknown/expired id. + let response = self + .inner + .transport() + .statement_status(&statement_id) + .await?; + Ok(ExecutedAsyncStatement::new( + Arc::clone(&self.inner), + statement_id, + // Standalone handle: no parent Statement to share the + // flag with, so a re-execute elsewhere can't invalidate + // it. Starts valid. + ValidityFlag::new(), + // NON-OWNING: start `closed=true` so this handle never + // closes the server statement — neither on `Drop` (its + // `swap(true)` sees already-closed and skips the + // fire-and-forget `close_statement`) nor via an explicit + // `close()` (which short-circuits on the flag). Attach is + // a *read-only adopt*: the statement's lifecycle is owned + // by whatever submitted it (or by an explicit + // `close_statement`), NOT by a transient handle a poller + // creates and drops. Without this, every `status()` poll + // through a fresh attached handle would close the very + // statement it's polling on Drop — turning a poll loop + // into a self-close. + Arc::new(AtomicBool::new(true)), + response.status, + )) + } + .instrument(span) + .await + } + /// Server-issued session identifier. Stable for the life of the /// session. pub fn session_id(&self) -> &str { diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 8ac92ad2..94f12e0d 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -226,6 +226,43 @@ fn cancelled_body(statement_id: &str) -> String { .to_string() } +/// `CLOSED` status body — what the SEA server returns from +/// `GetStatementStatus` after the statement has been closed (verified +/// against a live warehouse: `GET` after `DELETE` → 200 `state: CLOSED`). +fn closed_body(statement_id: &str) -> String { + json!({ + "statement_id": statement_id, + "status": { "state": "CLOSED" }, + }) + .to_string() +} + +/// Mount a single `GetStatementStatus` (GET) response for `attach`'s +/// seeding call. +async fn mount_status_once(server: &MockServer, statement_id: &str, body: String) { + Mock::given(method("GET")) + .and(path(format!("/api/2.0/sql/statements/{statement_id}"))) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(server) + .await; +} + +/// Mount a `404 NOT_FOUND` for an unknown/expired statement id — the +/// SEA shape verified against a live warehouse for a well-formed but +/// unknown id. +async fn mount_status_not_found(server: &MockServer, statement_id: &str) { + let body = json!({ + "error_code": "NOT_FOUND", + "message": format!("The statement {statement_id} was not found."), + }) + .to_string(); + Mock::given(method("GET")) + .and(path(format!("/api/2.0/sql/statements/{statement_id}"))) + .respond_with(ResponseTemplate::new(404).set_body_string(body)) + .mount(server) + .await; +} + async fn mount_submit(server: &MockServer, body: String) { Mock::given(method("POST")) .and(path("/api/2.0/sql/statements")) @@ -983,3 +1020,101 @@ async fn async_await_result_cancelled_carries_extended_status_fields_onto_error( ); let _ = ErrorCode::SqlError; // silence unused-import warning if the assert above changes } + +// ─── attach_async_statement (resume-by-id) ────────────────────────── + +#[tokio::test] +async fn attach_seeds_status_and_reports_server_state() { + // attach issues one GetStatementStatus to seed the handle; the + // seeded state is whatever the server reports for the id. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_status_once(&server, "stmt-attach", running_body("stmt-attach")).await; + + let session = open_session(&server).await; + let async_exec = session + .attach_async_statement("stmt-attach") + .await + .expect("attach should succeed for a known id"); + assert_eq!(async_exec.statement_id(), "stmt-attach"); + + let status = async_exec.status().await.expect("status"); + assert!(matches!(status, StatementStatus::Running), "{status:?}"); +} + +#[tokio::test] +async fn attach_reports_closed_for_a_closed_statement() { + // The connector relies on this: a closed async command must report + // CLOSED from the *server*, not from connector-side bookkeeping. + // Verified against a live warehouse — GET after DELETE returns + // 200 state=CLOSED. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_status_once(&server, "stmt-closed", closed_body("stmt-closed")).await; + + let session = open_session(&server).await; + let async_exec = session + .attach_async_statement("stmt-closed") + .await + .expect("attach should succeed for a closed (but still known) id"); + + let status = async_exec.status().await.expect("status"); + assert!(matches!(status, StatementStatus::Closed), "{status:?}"); +} + +#[tokio::test] +async fn attach_errors_not_found_for_unknown_id() { + // An unknown / TTL-expired id returns 404 NOT_FOUND, which the + // transport maps to ErrorCode::NotFound. The connector keys its + // "command is gone → CLOSED" decision on this specific code, so + // assert the mapping holds (and is not, e.g., a generic SqlError). + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_status_not_found(&server, "stmt-gone").await; + + let session = open_session(&server).await; + let err = match session.attach_async_statement("stmt-gone").await { + Ok(_) => panic!("attach on an unknown id should error"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::NotFound, "got: {err:?}"); +} + +#[tokio::test] +async fn attached_handle_drop_does_not_close_statement() { + // An attached handle is non-owning: dropping it must NOT fire a + // CloseStatement. This is load-bearing — get_query_state re-attaches + // on every poll, so a self-closing attached handle would close the + // statement the poll loop is watching. Assert zero DELETEs reach the + // server after the handle drops. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_status_once(&server, "stmt-noclose", running_body("stmt-noclose")).await; + // Scoped expectation: NO DELETE on the statement endpoint. + let _no_close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-noclose")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(0) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let async_exec = session + .attach_async_statement("stmt-noclose") + .await + .expect("attach"); + let _ = async_exec.status().await.expect("status"); + // async_exec drops here. + } + // Give any (erroneously) spawned fire-and-forget close a chance to + // hit the wire before the scoped mock verifies expect(0) on drop. + tokio::time::sleep(std::time::Duration::from_millis(150)).await; + // `_no_close` verifies expect(0) when it drops at end of scope. +}