diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 999283e6..4c7c1a14 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -13,6 +13,7 @@ changes go in their respective binding's NEXT_CHANGELOG. - Add an opt-in `release-with-debuginfo` Cargo profile and cross-platform symbol smoke checks for statically linked native consumers. +- Create SQL Exec API sessions in FAST mode and exchange the maximum observed session version. - Add a C ABI setter for the maximum idle HTTP connections retained per host. - C ABI: `kernel_statement_set_query_tags()` attaches per-statement query tags (serialized `key:value` wire form) to a statement's execution, letting C ABI diff --git a/src/client/mod.rs b/src/client/mod.rs index 74c85085..8f453016 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -46,5 +46,5 @@ pub use retry::{ pub(crate) use sea::SeaRestTransport; pub(crate) use transport::{ ChunkLinkFetchResult, DirectOutcome, ExecuteResponse, ExecuteResult, ExecuteResultData, - InlineChunkFetchResult, SessionInfo, Transport, TransportConfig, + InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport, TransportConfig, }; diff --git a/src/client/sea.rs b/src/client/sea.rs index 08160a58..79821ced 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -20,7 +20,8 @@ use crate::client::retry::RequestType; use crate::client::{ ChunkLinkFetchResult, DatabricksHttpClient, DirectOutcome, ExecuteResponse, ExecuteResult, - ExecuteResultData, InlineChunkFetchResult, SessionInfo, Transport, TransportConfig, + ExecuteResultData, InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport, + TransportConfig, }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -30,11 +31,13 @@ use crate::telemetry::ExecutionResultFormat; use crate::types::cloudfetch::CloudFetchLink; use crate::types::sea::{ CompressionCodec, CreateSessionRequest, CreateSessionResponse, ExecuteParams, - ExecuteStatementRequest, GetChunksResponse, StatementExecutionResponse, StatementState, + ExecuteStatementRequest, GetChunksResponse, SessionExecutionMode, SessionVersion, + StatementExecutionResponse, StatementState, }; use async_trait::async_trait; use reqwest::Method; use std::collections::HashMap; +use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::{Arc, OnceLock}; use tokio::runtime::Handle as RuntimeHandle; @@ -46,6 +49,8 @@ use tokio::runtime::Handle as RuntimeHandle; /// advisory — a server that does not recognise it ignores it — so there is /// nothing for a caller to configure. const SEA_SYNC_METADATA_HEADER: &str = "x-databricks-sea-can-run-fully-sync"; +/// DBSQL omits session versions, while server-issued FAST versions start at 1. +const NO_SESSION_VERSION: i64 = 0; /// Internal terminal-outcome for a single SEA statement response. /// @@ -75,6 +80,7 @@ pub(crate) struct SeaRestTransport { host: String, warehouse_id: String, config: TransportConfig, + session_version: AtomicI64, reader_factory: OnceLock, runtime_handle: OnceLock, } @@ -85,6 +91,7 @@ impl std::fmt::Debug for SeaRestTransport { .field("host", &self.host) .field("warehouse_id", &self.warehouse_id) .field("config", &self.config) + .field("session_version", &self.current_session_version()) .field( "reader_factory", &if self.reader_factory.get().is_some() { @@ -114,6 +121,7 @@ impl SeaRestTransport { host: host.into(), warehouse_id: warehouse_id.into(), config, + session_version: AtomicI64::new(NO_SESSION_VERSION), reader_factory: OnceLock::new(), runtime_handle: OnceLock::new(), } @@ -140,6 +148,18 @@ impl SeaRestTransport { format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) } + fn current_session_version(&self) -> Option { + let version_id = self.session_version.load(Ordering::SeqCst); + (version_id != NO_SESSION_VERSION).then_some(SessionVersion { version_id }) + } + + fn observe_session_version(&self, version: Option) { + if let Some(version) = version { + self.session_version + .fetch_max(version.version_id, Ordering::SeqCst); + } + } + /// Build the `/result/chunks/{idx}` URL, optionally with the /// `row_offset` query parameter set. /// @@ -229,7 +249,11 @@ impl SeaRestTransport { } /// Poll for statement status (private — used by wait_for_completion). - async fn get_statement_status(&self, statement_id: &str) -> Result { + async fn get_statement_status( + &self, + statement_id: &str, + session_attribution: SessionAttribution, + ) -> Result { let url = format!("{}/statements/{}", self.base_url(), statement_id); debug!("Getting statement status at {}", url); @@ -259,6 +283,10 @@ impl SeaRestTransport { )) })?; + if session_attribution == SessionAttribution::Current { + self.observe_session_version(sea_response.status.session_version); + } + debug!( "Status response: statement_id={}, status={:?}", sea_response.statement_id, sea_response.status.state @@ -417,7 +445,9 @@ impl SeaRestTransport { state = ?r.status.state, "Polling statement status" ); - current_response = self.get_statement_status(&r.statement_id).await?; + current_response = self + .get_statement_status(&r.statement_id, SessionAttribution::Current) + .await?; } } } @@ -461,6 +491,7 @@ impl SeaRestTransport { warehouse_id: self.warehouse_id.clone(), statement: sql.to_string(), session_id: Some(session_id.to_string()), + session_version: self.current_session_version(), catalog: params.catalog.clone(), schema: params.schema.clone(), disposition: disposition.to_string(), @@ -519,6 +550,8 @@ impl SeaRestTransport { )) })?; + self.observe_session_version(sea_response.status.session_version); + debug!( "Execute response: statement_id={}, status={:?}", sea_response.statement_id, sea_response.status.state @@ -790,6 +823,7 @@ impl Transport for SeaRestTransport { catalog: catalog.map(|s| s.to_string()), schema: schema.map(|s| s.to_string()), session_confs: session_config, + execution_mode: SessionExecutionMode::Fast, }; debug!("Creating session at {}", url); @@ -820,6 +854,8 @@ impl Transport for SeaRestTransport { )) })?; + self.observe_session_version(session_response.session_version); + debug!("Created session: {}", session_response.session_id); Ok(SessionInfo { @@ -976,8 +1012,14 @@ impl Transport for SeaRestTransport { } } - async fn fetch_completed_result(&self, statement_id: &str) -> Result> { - let response = self.get_statement_status(statement_id).await?; + async fn fetch_completed_result( + &self, + statement_id: &str, + session_attribution: SessionAttribution, + ) -> Result> { + let response = self + .get_statement_status(statement_id, session_attribution) + .await?; match Self::terminal_outcome(response) { StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; @@ -998,8 +1040,13 @@ impl Transport for SeaRestTransport { } } - async fn statement_status(&self, statement_id: &str) -> Result { - self.get_statement_status(statement_id).await + async fn statement_status( + &self, + statement_id: &str, + session_attribution: SessionAttribution, + ) -> Result { + self.get_statement_status(statement_id, session_attribution) + .await } async fn get_result_chunks( @@ -1490,6 +1537,7 @@ mod tests { sql_state: None, }), sql_state: None, + session_version: None, num_modified_rows: None, display_message: None, diagnostic_info: None, @@ -1576,6 +1624,7 @@ mod tests { state: StatementState::Succeeded, error: None, sql_state: None, + session_version: None, num_modified_rows: None, display_message: None, diagnostic_info: None, @@ -1844,6 +1893,208 @@ mod tests { ) } + #[tokio::test] + async fn exchanges_session_versions_on_create_and_execute() { + use serde_json::json; + use wiremock::matchers::{body_json, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .and(body_json(json!({ + "warehouse_id": "warehouse-123", + "execution_mode": "FAST", + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "session_id": "session-1", + "session_version": { "version_id": 7 }, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_json(json!({ + "warehouse_id": "warehouse-123", + "statement": "SELECT 1", + "session_id": "session-1", + "session_version": { "version_id": 7 }, + "disposition": "INLINE_OR_EXTERNAL_LINKS", + "format": "ARROW_STREAM", + "wait_timeout": "0s", + "on_wait_timeout": "CONTINUE", + "result_compression": "LZ4_FRAME", + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-1", + "status": { + "state": "PENDING", + }, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/statement-1")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-1", + "status": { + "state": "SUCCEEDED", + "session_version": { "version_id": 9 }, + }, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_json(json!({ + "warehouse_id": "warehouse-123", + "statement": "SELECT 2", + "session_id": "session-1", + "session_version": { "version_id": 9 }, + "disposition": "INLINE_OR_EXTERNAL_LINKS", + "format": "ARROW_STREAM", + "wait_timeout": "0s", + "on_wait_timeout": "CONTINUE", + "result_compression": "LZ4_FRAME", + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-2", + "status": { + "state": "PENDING", + }, + }))) + .expect(1) + .mount(&server) + .await; + + let transport = create_test_client_against(&server.uri()); + let session = transport + .create_session(None, None, HashMap::new()) + .await + .expect("FAST session creation must succeed"); + + transport + .submit_statement(&session.session_id, "SELECT 1", &ExecuteParams::default()) + .await + .expect("FAST execution must send the initial session version"); + transport + .get_statement_status("statement-1", SessionAttribution::Current) + .await + .expect("session-owned polling must observe the terminal version"); + assert_eq!( + transport.current_session_version(), + Some(SessionVersion { version_id: 9 }) + ); + + transport + .submit_statement(&session.session_id, "SELECT 2", &ExecuteParams::default()) + .await + .expect("FAST execution must send the maximum observed session version"); + transport.observe_session_version(Some(SessionVersion { version_id: 8 })); + assert_eq!( + transport.current_session_version(), + Some(SessionVersion { version_id: 9 }) + ); + } + + #[tokio::test] + async fn keeps_session_version_absent_when_server_omits_it() { + use serde_json::json; + use wiremock::matchers::{body_json, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200).set_body_string(r#"{"session_id":"session-1"}"#), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_json(json!({ + "warehouse_id": "warehouse-123", + "statement": "SELECT 1", + "session_id": "session-1", + "disposition": "INLINE_OR_EXTERNAL_LINKS", + "format": "ARROW_STREAM", + "wait_timeout": "0s", + "on_wait_timeout": "CONTINUE", + "result_compression": "LZ4_FRAME", + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-1", + "status": { + "state": "PENDING", + }, + }))) + .expect(1) + .mount(&server) + .await; + + let transport = create_test_client_against(&server.uri()); + let session = transport + .create_session(None, None, HashMap::new()) + .await + .expect("FAST session creation must accept a missing session version"); + assert_eq!(transport.current_session_version(), None); + + transport + .submit_statement(&session.session_id, "SELECT 1", &ExecuteParams::default()) + .await + .expect("execution without a session version must succeed"); + assert_eq!(transport.current_session_version(), None); + } + + #[tokio::test] + async fn advances_session_version_only_from_session_owned_polls() { + use serde_json::json; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + for (statement_id, version_id) in [("owned", 9), ("detached", 11)] { + Mock::given(method("GET")) + .and(path(format!("/api/2.0/sql/statements/{statement_id}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": statement_id, + "status": { + "state": "SUCCEEDED", + "session_version": { "version_id": version_id }, + }, + }))) + .expect(1) + .mount(&server) + .await; + } + + let transport = create_test_client_against(&server.uri()); + transport.observe_session_version(Some(SessionVersion { version_id: 7 })); + + transport + .get_statement_status("owned", SessionAttribution::Current) + .await + .expect("session-owned polling must succeed"); + assert_eq!( + transport.current_session_version(), + Some(SessionVersion { version_id: 9 }) + ); + + transport + .statement_status("detached", SessionAttribution::Detached) + .await + .expect("detached polling must succeed"); + assert_eq!( + transport.current_session_version(), + Some(SessionVersion { version_id: 9 }) + ); + } + #[tokio::test] async fn get_result_chunks_sends_row_offset_query_param_on_wire() { // Pin the wire shape of the inline-Arrow row_offset query diff --git a/src/client/transport.rs b/src/client/transport.rs index 783b1bc1..a65e815d 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -82,6 +82,15 @@ impl Default for TransportConfig { // ─── Trait input/output value types ───────────────────────────────── +/// Whether a statement is known to belong to this transport's session. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SessionAttribution { + /// The statement was submitted through this session, so its response may advance the session. + Current, + /// Only the statement ID is known; its response must not affect this session. + Detached, +} + /// Session information returned from [`Transport::create_session`]. #[derive(Debug, Clone)] pub(crate) struct SessionInfo { @@ -341,13 +350,21 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { /// /// Used by `ExecutedAsyncStatement::fetch_result` and inside the /// `await_result` poll loop. - async fn fetch_completed_result(&self, statement_id: &str) -> Result>; + async fn fetch_completed_result( + &self, + statement_id: &str, + session_attribution: SessionAttribution, + ) -> Result>; /// One-shot status check for an in-flight statement. Returns the /// full `ExecuteResponse` (status + manifest + initial result, if /// any). Used by `ExecutedAsyncStatement::status` and the /// `await_result` poll loop. - async fn statement_status(&self, statement_id: &str) -> Result; + async fn statement_status( + &self, + statement_id: &str, + session_attribution: SessionAttribution, + ) -> Result; // --- Result Fetching (CloudFetch) --- diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 32d8d455..6d08a56e 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -900,6 +900,7 @@ mod tests { sql_state: Some("42P01".to_string()), }), sql_state: None, + session_version: None, num_modified_rows: None, display_message: None, diagnostic_info: None, diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 53664e01..c48907f3 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1147,6 +1147,7 @@ mod tests { state: StatementState::Succeeded, error: None, sql_state: None, + session_version: None, num_modified_rows: None, display_message: None, diagnostic_info: None, @@ -1175,6 +1176,7 @@ mod tests { async fn fetch_completed_result( &self, _statement_id: &str, + _session_attribution: crate::client::SessionAttribution, ) -> Result> { unimplemented!("fetch_completed_result not used by the link-fetcher mock") } @@ -1182,6 +1184,7 @@ mod tests { async fn statement_status( &self, _statement_id: &str, + _session_attribution: crate::client::SessionAttribution, ) -> Result { unimplemented!("statement_status not used by the link-fetcher mock") } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 02704873..1c14d82a 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1499,10 +1499,18 @@ mod tests { ) -> Result { unreachable!() } - async fn fetch_completed_result(&self, _: &str) -> Result> { + async fn fetch_completed_result( + &self, + _: &str, + _: crate::client::SessionAttribution, + ) -> Result> { unreachable!() } - async fn statement_status(&self, _: &str) -> Result { + async fn statement_status( + &self, + _: &str, + _: crate::client::SessionAttribution, + ) -> Result { unreachable!() } async fn get_result_chunks(&self, _: &str, _: i64, _: i64) -> Result { @@ -1632,6 +1640,7 @@ mod tests { state: StatementState::Succeeded, error: None::, sql_state: None, + session_version: None, num_modified_rows: None, display_message: None, diagnostic_info: None, diff --git a/src/session.rs b/src/session.rs index 63590698..80b9b6c2 100644 --- a/src/session.rs +++ b/src/session.rs @@ -56,7 +56,7 @@ use crate::client::retry::{ use crate::client::transport::TransportConfig; use crate::client::{ DatabricksHttpClient, HttpClientConfig, ProxyConfig as HttpProxyConfig, SeaRestTransport, - Transport, + SessionAttribution, Transport, }; use crate::config::{ AuthConfig, ConnectionConfig, DefaultOpts, HttpConfig, LoggingConfig, ProxyConfig, @@ -660,7 +660,7 @@ impl Session { let response = self .inner .transport() - .statement_status(&statement_id) + .statement_status(&statement_id, SessionAttribution::Detached) .await .map_err(|e| e.with_query_id(&statement_id))?; // NON-OWNING read-only adopt: `new_attached` gives the handle @@ -2024,9 +2024,45 @@ mod is_open_tests { use serde_json::Value; use std::future::Future; use std::pin::Pin; - use wiremock::matchers::{body_string_contains, method, path, path_regex}; + use wiremock::matchers::{body_json, body_string_contains, method, path, path_regex}; use wiremock::{Mock, MockServer, ResponseTemplate}; + #[tokio::test] + async fn sessions_enable_version_exchange_on_standard_path() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .and(body_json(json!({ + "warehouse_id": "test_wh", + "execution_mode": "FAST", + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "session_id": "sess-fast", + "session_version": { "version_id": 1 }, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-fast")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let session = Session::builder() + .http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .open() + .await + .expect("FAST session must open on the standard path"); + + session.close().await.expect("FAST session must close"); + } + /// `Session::is_open` reports true for a freshly-opened session and /// false once its server-side delete has been initiated. This is the /// only place the false path is reachable — over the C ABI diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index d9a08632..d412f0a1 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -44,7 +44,7 @@ //! class) can route through whichever handle their language idiom //! prefers; field availability is identical. -use crate::client::ExecuteResponse; +use crate::client::{ExecuteResponse, SessionAttribution}; use crate::kernel_error::{Error, Result}; use crate::klog::warn; use crate::result_stream::ResultStream; @@ -225,6 +225,14 @@ pub struct ExecutedAsyncStatement { } impl ExecutedAsyncStatement { + fn session_attribution(&self) -> SessionAttribution { + if self.owning { + SessionAttribution::Current + } else { + SessionAttribution::Detached + } + } + /// Crate-internal constructor. Built by [`Statement::submit`]. /// /// `closed` is shared with the parent [`Statement`] so flipping it @@ -395,7 +403,7 @@ impl ExecutedAsyncStatement { let response = self .session .transport() - .statement_status(&self.statement_id) + .statement_status(&self.statement_id, self.session_attribution()) .await?; self.statement_telemetry .record_poll(status_started.elapsed()); @@ -485,7 +493,7 @@ impl ExecutedAsyncStatement { let response = self .session .transport() - .statement_status(&self.statement_id) + .statement_status(&self.statement_id, self.session_attribution()) .await?; self.statement_telemetry .record_poll(status_started.elapsed()); @@ -579,7 +587,7 @@ impl ExecutedAsyncStatement { match self .session .transport() - .fetch_completed_result(&self.statement_id) + .fetch_completed_result(&self.statement_id, self.session_attribution()) .await? { Some(result) => { @@ -627,7 +635,7 @@ impl ExecutedAsyncStatement { let observed = match self .session .transport() - .statement_status(&self.statement_id) + .statement_status(&self.statement_id, self.session_attribution()) .await { Ok(r) => match r.status.state { diff --git a/src/types/sea.rs b/src/types/sea.rs index 00b9d7de..572b7a90 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -68,6 +68,8 @@ pub struct StatementStatus { /// wire location used by Reyden and newer DBSQL responses. #[serde(default)] pub sql_state: Option, + #[serde(default)] + pub session_version: Option, /// Number of rows modified by the statement (UPDATE / INSERT / /// DELETE / MERGE). Absent on SELECT and on warehouses that don't /// surface the counter. @@ -128,6 +130,7 @@ impl std::fmt::Debug for StatementStatus { .field("state", &self.state) .field("error", &self.error) .field("sql_state", &self.sql_state) + .field("session_version", &self.session_version) .field("num_modified_rows", &self.num_modified_rows) .field("display_message", &summarise(&self.display_message)) .field("diagnostic_info", &summarise(&self.diagnostic_info)) @@ -327,6 +330,8 @@ pub struct ExecuteStatementRequest { #[serde(skip_serializing_if = "Option::is_none")] pub session_id: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub session_version: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub catalog: Option, #[serde(skip_serializing_if = "Option::is_none")] pub schema: Option, @@ -397,6 +402,17 @@ impl CompressionCodec { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum SessionExecutionMode { + Fast, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionVersion { + pub version_id: i64, +} + /// Request body for session creation. #[derive(Debug, Clone, Serialize)] pub struct CreateSessionRequest { @@ -407,12 +423,15 @@ pub struct CreateSessionRequest { pub schema: Option, #[serde(skip_serializing_if = "HashMap::is_empty")] pub session_confs: HashMap, + pub execution_mode: SessionExecutionMode, } /// Response from session creation. #[derive(Debug, Clone, Deserialize)] pub struct CreateSessionResponse { pub session_id: String, + #[serde(default)] + pub session_version: Option, } /// Response from fetching result chunks. @@ -484,12 +503,26 @@ mod tests { catalog: None, schema: None, session_confs: confs, + execution_mode: SessionExecutionMode::Fast, }; let json = serde_json::to_string(&req).unwrap(); assert!( json.contains("\"session_confs\""), "expected `session_confs` on the wire, got: {json}" ); + assert!(json.contains("\"execution_mode\":\"FAST\"")); + } + + #[test] + fn test_create_session_response_deserializes_session_version() { + let response: CreateSessionResponse = serde_json::from_str( + r#"{"session_id":"session-1","session_version":{"version_id":7}}"#, + ) + .unwrap(); + assert_eq!( + response.session_version, + Some(SessionVersion { version_id: 7 }) + ); } #[test] @@ -498,6 +531,7 @@ mod tests { warehouse_id: "abc123".to_string(), statement: "SELECT 1".to_string(), session_id: Some("session-1".to_string()), + session_version: None, catalog: None, schema: None, disposition: "EXTERNAL_LINKS".to_string(), @@ -513,6 +547,7 @@ mod tests { let json = serde_json::to_string(&req).unwrap(); assert!(json.contains("\"warehouse_id\":\"abc123\"")); assert!(json.contains("\"session_id\":\"session-1\"")); + assert!(!json.contains("\"session_version\"")); assert!(!json.contains("\"catalog\"")); // None should be skipped assert!(!json.contains("\"query_tags\"")); // empty should be skipped } @@ -523,6 +558,7 @@ mod tests { warehouse_id: "abc123".to_string(), statement: "SELECT 1".to_string(), session_id: Some("session-1".to_string()), + session_version: None, catalog: None, schema: None, disposition: "ARROW_STREAM".to_string(), diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 78738dc4..8fec1da0 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -33,7 +33,7 @@ use databricks_sql_kernel::{ }; use serde_json::json; use std::sync::Arc; -use wiremock::matchers::{method, path}; +use wiremock::matchers::{body_json, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; // ─── Helpers ──────────────────────────────────────────────────────── @@ -371,6 +371,86 @@ async fn submit_returns_pending_handle_without_polling() { assert!(matches!(status, StatementStatus::Pending), "{status:?}"); } +#[tokio::test] +async fn owning_async_status_advances_session_version_for_next_execute() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .and(body_json(json!({ + "warehouse_id": "test_wh", + "execution_mode": "FAST", + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "session_id": "sess-test", + "session_version": { "version_id": 7 }, + }))) + .expect(1) + .mount(&server) + .await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_json(json!({ + "warehouse_id": "test_wh", + "statement": "SELECT 1", + "session_id": "sess-test", + "session_version": { "version_id": 7 }, + "disposition": "INLINE_OR_EXTERNAL_LINKS", + "format": "ARROW_STREAM", + "wait_timeout": "0s", + "on_wait_timeout": "CONTINUE", + "result_compression": "LZ4_FRAME", + }))) + .respond_with(ResponseTemplate::new(200).set_body_string(pending_body("stmt-first"))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-first")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "stmt-first", + "status": { + "state": "SUCCEEDED", + "session_version": { "version_id": 9 }, + }, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_json(json!({ + "warehouse_id": "test_wh", + "statement": "SELECT 2", + "session_id": "sess-test", + "session_version": { "version_id": 9 }, + "disposition": "INLINE_OR_EXTERNAL_LINKS", + "format": "ARROW_STREAM", + "wait_timeout": "0s", + "on_wait_timeout": "CONTINUE", + "result_compression": "LZ4_FRAME", + }))) + .respond_with(ResponseTemplate::new(200).set_body_string(pending_body("stmt-second"))) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut first = session.statement(); + first.spec().sql("SELECT 1"); + let first_execution = first.submit().await.expect("first submit"); + assert!(matches!( + first_execution.status().await.expect("terminal status"), + StatementStatus::Succeeded + )); + + let mut second = session.statement(); + second.spec().sql("SELECT 2"); + second.submit().await.expect("second submit"); +} + #[tokio::test] async fn await_result_polls_until_succeeded() { let server = MockServer::start().await;