diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index ae2bb3d0..14a1d627 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/http.rs b/src/client/http.rs index cf290925..c192ff32 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -26,6 +26,7 @@ use crate::auth::AuthProvider; use crate::client::retry::{ calculate_backoff, RequestCategory, RequestType, RetryConfig, RetryStrategy, }; +use crate::client::DIRECT_ROUTING_HEADER; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; use crate::types::sea::ServiceError; @@ -852,11 +853,9 @@ impl DatabricksHttpClient { // kernel's own auth / routing headers (set last, below) take // precedence — matching the Thrift connector, where // `auth_provider.add_headers` runs after the custom-header - // dict. We SKIP any custom header named `Authorization` or - // `x-databricks-org-id` (case-insensitive) so a stray caller - // header can't sit alongside the kernel's (reqwest appends - // same-named headers rather than replacing, which for those - // two would send a duplicate and could confuse the server). + // dict. Kernel-managed authentication and routing headers are + // skipped here so caller values cannot coexist with the values + // selected by the kernel. // `User-Agent` is NOT in this map — it was folded into the // client's effective UA in `new()` (a caller UA replaces the // base, which then becomes reqwest's default UA header). @@ -869,7 +868,10 @@ impl DatabricksHttpClient { // transport, IdP calls included. for (name, value) in &self.config.custom_headers { let lname = name.to_ascii_lowercase(); - if lname == "authorization" || lname == "x-databricks-org-id" { + if lname == "authorization" + || lname == "x-databricks-org-id" + || lname == DIRECT_ROUTING_HEADER + { warn!( header = %name, "ignoring caller-supplied custom header; this name is \ @@ -1114,7 +1116,7 @@ mod tests { } #[tokio::test] - async fn test_custom_headers_applied_with_auth_winning() { + async fn test_custom_headers_applied_with_kernel_headers_winning() { use wiremock::matchers::{header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -1151,6 +1153,7 @@ mod tests { "Authorization".to_string(), "Bearer caller-bogus".to_string(), ), + (DIRECT_ROUTING_HEADER.to_string(), "true".to_string()), ], ..HttpClientConfig::default() }; @@ -1167,6 +1170,8 @@ mod tests { .await .expect("request should succeed against the mock"); assert_eq!(resp.status().as_u16(), 200); + let requests = server.received_requests().await.unwrap(); + assert!(requests[0].headers.get(DIRECT_ROUTING_HEADER).is_none()); // If the matchers above didn't all match, wiremock returns the // default 404 and the status assert fails — so a 200 confirms // custom header + caller UA present AND auth = real-token. diff --git a/src/client/mod.rs b/src/client/mod.rs index 74c85085..30789717 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -36,6 +36,8 @@ pub mod retry; pub mod sea; pub(crate) mod transport; +pub(crate) const DIRECT_ROUTING_HEADER: &str = "x-databricks-direct-routing"; + // Public surface — kept stable for advanced wrappers that tune HTTP. pub use http::{DatabricksHttpClient, HttpClientConfig, ProxyConfig}; pub use retry::{ @@ -46,5 +48,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..563f1919 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, DIRECT_ROUTING_HEADER, }; 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,9 @@ pub(crate) struct SeaRestTransport { host: String, warehouse_id: String, config: TransportConfig, + direct_routing_eligible: bool, + direct_routing_enabled: OnceLock, + session_version: AtomicI64, reader_factory: OnceLock, runtime_handle: OnceLock, } @@ -85,6 +93,8 @@ impl std::fmt::Debug for SeaRestTransport { .field("host", &self.host) .field("warehouse_id", &self.warehouse_id) .field("config", &self.config) + .field("direct_routing_enabled", &self.should_direct_route()) + .field("session_version", &self.current_session_version()) .field( "reader_factory", &if self.reader_factory.get().is_some() { @@ -108,12 +118,16 @@ impl SeaRestTransport { host: impl Into, warehouse_id: impl Into, config: TransportConfig, + direct_routing_eligible: bool, ) -> Self { Self { http_client, host: host.into(), warehouse_id: warehouse_id.into(), config, + direct_routing_eligible, + direct_routing_enabled: OnceLock::new(), + session_version: AtomicI64::new(NO_SESSION_VERSION), reader_factory: OnceLock::new(), runtime_handle: OnceLock::new(), } @@ -140,6 +154,36 @@ impl SeaRestTransport { format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) } + fn should_direct_route(&self) -> bool { + self.direct_routing_eligible && self.direct_routing_enabled.get().copied().unwrap_or(false) + } + + fn follow_up_request( + &self, + method: Method, + url: &str, + session_attribution: SessionAttribution, + ) -> reqwest::RequestBuilder { + let builder = self.http_client.inner().request(method, url); + if session_attribution == SessionAttribution::Current && self.should_direct_route() { + builder.header(DIRECT_ROUTING_HEADER, "true") + } else { + builder + } + } + + 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,15 +273,17 @@ 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); let request = self - .http_client - .inner() - .request(Method::GET, &url) + .follow_up_request(Method::GET, &url, session_attribution) .build() .map_err(|e| { Error::invalid_argument().message(format!("Failed to build request: {e}")) @@ -259,13 +305,18 @@ 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 ); let mut response = Self::convert_response(sea_response)?; - self.enrich_num_modified_rows(&mut response).await; + self.enrich_num_modified_rows(&mut response, session_attribution) + .await; Ok(response) } @@ -281,7 +332,11 @@ impl SeaRestTransport { /// /// Gated on the manifest's column signature so SELECTs (real columns) never /// hit the decode path; a DML-count result is always tiny and inline. - async fn enrich_num_modified_rows(&self, response: &mut ExecuteResponse) { + async fn enrich_num_modified_rows( + &self, + response: &mut ExecuteResponse, + session_attribution: SessionAttribution, + ) { if response.status.num_modified_rows.is_some() { return; } @@ -296,7 +351,7 @@ impl SeaRestTransport { // any later fetch the caller makes (a fresh GetStatement builds its own // reader), so result consumption is unaffected. let reader = match factory - .create_reader(&response.statement_id, response) + .create_reader(&response.statement_id, response, session_attribution) .await { Ok(r) => r, @@ -417,7 +472,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 +518,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(), @@ -476,9 +534,7 @@ impl SeaRestTransport { debug!("Executing statement at {}: {}", url, sql); let mut builder = self - .http_client - .inner() - .request(Method::POST, &url) + .follow_up_request(Method::POST, &url, SessionAttribution::Current) .header("Content-Type", "application/json"); // Signal that a metadata query may be served fully synchronously, so @@ -519,6 +575,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 @@ -640,7 +698,11 @@ impl SeaRestTransport { // GEOMETRY/GEOGRAPHY → Utf8). The post-processor also handles // the optional complex-types-as-JSON rewrite in the same pass. let reader = match reader_factory - .create_reader(&response.statement_id, &response) + .create_reader( + &response.statement_id, + &response, + SessionAttribution::Current, + ) .await { Ok(r) => r, @@ -790,6 +852,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 +883,13 @@ impl Transport for SeaRestTransport { )) })?; + self.direct_routing_enabled + .set(session_response.direct_routing_enabled) + .map_err(|_| { + Error::invalid_state().message("SEA transport already created a session") + })?; + self.observe_session_version(session_response.session_version); + debug!("Created session: {}", session_response.session_id); Ok(SessionInfo { @@ -844,9 +914,7 @@ impl Transport for SeaRestTransport { debug!("Deleting session at {}", url); let request = self - .http_client - .inner() - .request(Method::DELETE, &url) + .follow_up_request(Method::DELETE, &url, SessionAttribution::Current) .build() .map_err(|e| { Error::invalid_argument().message(format!("Failed to build request: {e}")) @@ -945,7 +1013,10 @@ impl Transport for SeaRestTransport { // reader from the inline result (no extra GetStatementResult). StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; - let reader = match reader_factory.create_reader(&r.statement_id, &r).await { + let reader = match reader_factory + .create_reader(&r.statement_id, &r, SessionAttribution::Current) + .await + { Ok(reader) => reader, Err(e) => { self.close_orphaned_statement(&statement_id, "create_reader (direct)") @@ -976,12 +1047,20 @@ 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()?; - let reader = reader_factory.create_reader(&r.statement_id, &r).await?; + let reader = reader_factory + .create_reader(&r.statement_id, &r, session_attribution) + .await?; let telemetry_result_format = Self::telemetry_result_format(&r); let telemetry_is_compressed = Self::telemetry_is_compressed(&r); Ok(Some(ExecuteResult { @@ -998,8 +1077,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( @@ -1007,15 +1091,14 @@ impl Transport for SeaRestTransport { statement_id: &str, chunk_index: i64, row_offset: i64, + session_attribution: SessionAttribution, ) -> Result { let url = self.result_chunks_url(statement_id, chunk_index, row_offset); debug!("Getting result chunks at {}", url); let request = self - .http_client - .inner() - .request(Method::GET, &url) + .follow_up_request(Method::GET, &url, session_attribution) .build() .map_err(|e| { Error::invalid_argument().message(format!("Failed to build request: {e}")) @@ -1052,6 +1135,7 @@ impl Transport for SeaRestTransport { statement_id: &str, chunk_index: i64, row_offset: i64, + session_attribution: SessionAttribution, ) -> Result { // Same endpoint as CloudFetch chunk-link fetching, but on // the inline-Arrow path the response carries Arrow IPC bytes @@ -1082,9 +1166,7 @@ impl Transport for SeaRestTransport { ); let request = self - .http_client - .inner() - .request(Method::GET, &url) + .follow_up_request(Method::GET, &url, session_attribution) .build() .map_err(|e| { Error::invalid_argument().message(format!("Failed to build request: {e}")) @@ -1173,9 +1255,7 @@ impl Transport for SeaRestTransport { debug!("Canceling statement at {}", url); let request = self - .http_client - .inner() - .request(Method::POST, &url) + .follow_up_request(Method::POST, &url, SessionAttribution::Current) .build() .map_err(|e| { Error::invalid_argument().message(format!("Failed to build request: {e}")) @@ -1196,9 +1276,7 @@ impl Transport for SeaRestTransport { debug!("Closing statement at {}", url); let request = self - .http_client - .inner() - .request(Method::DELETE, &url) + .follow_up_request(Method::DELETE, &url, SessionAttribution::Current) .build() .map_err(|e| { Error::invalid_argument().message(format!("Failed to build request: {e}")) @@ -1455,6 +1533,7 @@ mod tests { "https://test.databricks.com", "warehouse-123", TransportConfig::default(), + false, ) } @@ -1490,6 +1569,7 @@ mod tests { sql_state: None, }), sql_state: None, + session_version: None, num_modified_rows: None, display_message: None, diagnostic_info: None, @@ -1523,6 +1603,7 @@ mod tests { "https://test.databricks.com/", "warehouse-123", TransportConfig::default(), + false, ); assert_eq!(client.base_url(), "https://test.databricks.com/api/2.0/sql"); } @@ -1576,6 +1657,7 @@ mod tests { state: StatementState::Succeeded, error: None, sql_state: None, + session_version: None, num_modified_rows: None, display_message: None, diagnostic_info: None, @@ -1830,6 +1912,13 @@ mod tests { /// host so we can assert wire-level behaviour rather than just /// URL-string output. fn create_test_client_against(host: &str) -> SeaRestTransport { + create_test_client_against_with_eligibility(host, false) + } + + fn create_test_client_against_with_eligibility( + host: &str, + direct_routing_eligible: bool, + ) -> SeaRestTransport { let retry_configs = build_retry_configs(&RetryConfig::default(), &HashMap::new()); let http_client = Arc::new( DatabricksHttpClient::new(HttpClientConfig::default(), retry_configs).unwrap(), @@ -1841,9 +1930,483 @@ mod tests { host, "warehouse-123", TransportConfig::default(), + direct_routing_eligible, ) } + #[tokio::test] + async fn direct_routing_header_covers_owned_follow_up_lifecycle() { + use serde_json::json; + use wiremock::matchers::{body_json, header, method, path, query_param}; + 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_json(json!({ + "session_id": "session-1", + "session_version": { "version_id": 7 }, + "direct_routing_enabled": true, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(header(DIRECT_ROUTING_HEADER, "true")) + .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")) + .and(header(DIRECT_ROUTING_HEADER, "true")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-1", + "status": { "state": "RUNNING" }, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/statement-1/result/chunks/0")) + .and(header(DIRECT_ROUTING_HEADER, "true")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "external_links": [], + "next_chunk_index": null, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/sql/statements/inline-statement/result/chunks/1", + )) + .and(query_param("row_offset", "3")) + .and(header(DIRECT_ROUTING_HEADER, "true")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "chunk_index": 1, + "row_offset": 3, + "row_count": 1, + "next_chunk_index": null, + "attachment": "AQ==", + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/statement-1/cancel")) + .and(header(DIRECT_ROUTING_HEADER, "true")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/statement-1")) + .and(header(DIRECT_ROUTING_HEADER, "true")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/session-1")) + .and(header(DIRECT_ROUTING_HEADER, "true")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let transport = create_test_client_against_with_eligibility(&server.uri(), true); + let session = transport + .create_session(None, None, HashMap::new()) + .await + .expect("session creation must succeed"); + transport + .submit_statement(&session.session_id, "SELECT 1", &ExecuteParams::default()) + .await + .expect("execute must succeed"); + transport + .get_statement_status("statement-1", SessionAttribution::Current) + .await + .expect("owned status must succeed"); + transport + .get_result_chunks("statement-1", 0, 0, SessionAttribution::Current) + .await + .expect("owned chunk fetch must succeed"); + transport + .get_inline_chunk("inline-statement", 1, 3, SessionAttribution::Current) + .await + .expect("owned inline chunk fetch must succeed"); + transport + .cancel_statement("statement-1") + .await + .expect("cancel must succeed"); + transport + .close_statement("statement-1") + .await + .expect("statement close must succeed"); + transport + .delete_session(&session.session_id) + .await + .expect("session close must succeed"); + + server.verify().await; + let requests = server.received_requests().await.unwrap(); + let create = requests + .iter() + .find(|request| request.url.path() == "/api/2.0/sql/sessions") + .expect("CreateSession request must be recorded"); + assert!(create.headers.get(DIRECT_ROUTING_HEADER).is_none()); + } + + #[tokio::test] + async fn direct_routing_header_requires_both_negotiation_and_client_eligibility() { + use serde_json::json; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let cases = [ + (json!({ "session_id": "session-1" }), true), + ( + json!({ + "session_id": "session-1", + "direct_routing_enabled": false, + }), + true, + ), + ( + json!({ + "session_id": "session-1", + "direct_routing_enabled": true, + }), + false, + ), + ]; + + for (create_response, direct_routing_eligible) in cases { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_json(create_response)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .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_with_eligibility(&server.uri(), direct_routing_eligible); + let session = transport + .create_session(None, None, HashMap::new()) + .await + .expect("session creation must succeed"); + transport + .submit_statement(&session.session_id, "SELECT 1", &ExecuteParams::default()) + .await + .expect("execute must succeed"); + + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 2); + assert!(requests + .iter() + .all(|request| request.headers.get(DIRECT_ROUTING_HEADER).is_none())); + } + } + + #[tokio::test] + async fn detached_statement_requests_ignore_the_session_route() { + use serde_json::json; + use wiremock::matchers::{method, path, query_param}; + 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_json(json!({ + "session_id": "session-1", + "direct_routing_enabled": true, + }))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/detached")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "detached", + "status": { "state": "RUNNING" }, + }))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/detached/result/chunks/0")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "external_links": [], + "next_chunk_index": null, + }))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/sql/statements/inline-detached/result/chunks/1", + )) + .and(query_param("row_offset", "3")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "chunk_index": 1, + "row_offset": 3, + "row_count": 1, + "next_chunk_index": null, + "attachment": "AQ==", + }))) + .mount(&server) + .await; + + let transport = create_test_client_against_with_eligibility(&server.uri(), true); + transport + .create_session(None, None, HashMap::new()) + .await + .expect("session creation must succeed"); + transport + .get_statement_status("detached", SessionAttribution::Detached) + .await + .expect("detached status must succeed"); + transport + .get_result_chunks("detached", 0, 0, SessionAttribution::Detached) + .await + .expect("detached chunk fetch must succeed"); + transport + .get_inline_chunk("inline-detached", 1, 3, SessionAttribution::Detached) + .await + .expect("detached inline chunk fetch must succeed"); + + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 4); + assert!(requests + .iter() + .all(|request| request.headers.get(DIRECT_ROUTING_HEADER).is_none())); + } + + #[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 @@ -1873,7 +2436,7 @@ mod tests { let transport = create_test_client_against(&server.uri()); let _ = transport - .get_result_chunks("01abc", 3, 100) + .get_result_chunks("01abc", 3, 100, SessionAttribution::Current) .await .expect("get_result_chunks must succeed against the mock"); @@ -1911,7 +2474,7 @@ mod tests { let transport = create_test_client_against(&server.uri()); let _ = transport - .get_result_chunks("01abc", 3, 0) + .get_result_chunks("01abc", 3, 0, SessionAttribution::Current) .await .expect("get_result_chunks must succeed against the mock"); diff --git a/src/client/transport.rs b/src/client/transport.rs index 783b1bc1..36a31cca 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) --- @@ -363,6 +380,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { statement_id: &str, chunk_index: i64, row_offset: i64, + session_attribution: SessionAttribution, ) -> Result; /// Fetch one inline-Arrow chunk by `chunk_index` (+ server-side @@ -384,6 +402,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { statement_id: &str, chunk_index: i64, row_offset: i64, + session_attribution: SessionAttribution, ) -> Result; /// Polling cadence + ceiling the kernel should use when driving diff --git a/src/config.rs b/src/config.rs index 3e88473c..b5b36b00 100644 --- a/src/config.rs +++ b/src/config.rs @@ -444,6 +444,13 @@ pub enum AuthConfig { } impl AuthConfig { + pub(crate) fn is_direct_routing_eligible(&self) -> bool { + matches!( + self, + Self::OAuthM2M { .. } | Self::OAuthM2MPrivateKey { .. } + ) + } + /// Construct a [`AuthConfig::Pat`] from an optional token, validating /// that it is present and non-empty. /// @@ -784,14 +791,10 @@ pub struct HttpConfig { /// which also carries the composed `User-Agent`) onto the kernel's /// HTTP stack. /// - /// **`Authorization` / `x-databricks-org-id` are reserved:** a - /// caller entry for either name is **silently dropped (with a - /// `warn!`)** — it never reaches the wire. The kernel always adds - /// its own `Authorization` (from the auth provider) and, when set, - /// `x-databricks-org-id`, so auth and multi-tenant routing can't be - /// hijacked by a caller header. (This mirrors the Thrift connector, - /// where `auth_provider.add_headers` runs after the custom-header - /// dict and overwrites those names.) + /// **`Authorization`, `x-databricks-org-id`, and + /// `x-databricks-direct-routing` are reserved.** Caller entries for + /// these names are silently dropped with a `warn!`. The kernel owns + /// their values so callers cannot override authentication or routing. /// /// **`User-Agent` is special-cased:** a caller `User-Agent` here /// **replaces** the kernel's base UA entirely — it is folded into the @@ -1742,6 +1745,52 @@ mod tests { } } + #[test] + fn direct_routing_eligibility_is_limited_to_databricks_oauth_m2m() { + let eligible = [ + AuthConfig::OAuthM2M { + client_id: "client-id".to_string(), + client_secret: "client-secret".to_string(), + scopes: None, + token_url_override: None, + identity_federation_client_id: None, + }, + AuthConfig::OAuthM2MPrivateKey { + client_id: "client-id".to_string(), + jwt_key_file: "/key.pem".to_string(), + jwt_kid: "key-id".to_string(), + jwt_passphrase: None, + jwt_algorithm: None, + scopes: None, + token_url_override: None, + }, + ]; + assert!(eligible.iter().all(AuthConfig::is_direct_routing_eligible)); + + let ineligible = [ + AuthConfig::Pat { + token: "token".to_string(), + identity_federation_client_id: None, + }, + AuthConfig::oauth_u2m(None, None, None, None, None, None, None), + AuthConfig::AzureServicePrincipal { + azure_client_id: "client-id".to_string(), + azure_client_secret: "client-secret".to_string(), + azure_tenant_id: None, + azure_workspace_resource_id: None, + identity_federation_client_id: None, + }, + AuthConfig::OAuthFederation { + subject_token: "token".to_string(), + subject_token_type: "type".to_string(), + audience: "audience".to_string(), + }, + ]; + assert!(ineligible + .iter() + .all(|auth| !auth.is_direct_routing_eligible())); + } + // ─── OAuthM2MPrivateKey (JWT) constructor ────────────────────── // Mirrors JDBC's builder null-checks (should_ThrowException_When_*). 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..6da3c546 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -40,7 +40,7 @@ //! 3. Check if prefetch should be triggered (async, non-blocking) //! 4. Background task fetches links and caches them -use crate::client::{ChunkLinkFetchResult, Transport}; +use crate::client::{ChunkLinkFetchResult, SessionAttribution, Transport}; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, error}; use crate::types::cloudfetch::CloudFetchLink; @@ -157,6 +157,7 @@ pub(crate) struct SeaChunkLinkFetcher { client: Arc, /// Statement ID this fetcher is bound to statement_id: String, + session_attribution: SessionAttribution, /// Cached links by chunk index links: DashMap, /// Next chunk index to ask the server for. Initialised from the @@ -358,6 +359,7 @@ impl SeaChunkLinkFetcher { /// confident the bounded-API server is live. /// * `link_prefetch_window` - Number of chunks to prefetch ahead of consumer /// * `runtime_handle` - Tokio runtime handle for spawning prefetch tasks + #[cfg(test)] pub(crate) fn new( client: Arc, statement_id: impl Into, @@ -365,6 +367,26 @@ impl SeaChunkLinkFetcher { total_chunk_count: Option, link_prefetch_window: i64, runtime_handle: tokio::runtime::Handle, + ) -> Self { + Self::new_with_attribution( + client, + statement_id, + initial_links, + total_chunk_count, + link_prefetch_window, + runtime_handle, + SessionAttribution::Current, + ) + } + + pub(crate) fn new_with_attribution( + client: Arc, + statement_id: impl Into, + initial_links: &[CloudFetchLink], + total_chunk_count: Option, + link_prefetch_window: i64, + runtime_handle: tokio::runtime::Handle, + session_attribution: SessionAttribution, ) -> Self { let statement_id = statement_id.into(); let links = DashMap::new(); @@ -433,6 +455,7 @@ impl SeaChunkLinkFetcher { let fetcher = Self { client, statement_id, + session_attribution, links, next_server_fetch_index: AtomicI64::new(next_server_fetch_index), all_links_fetched: AtomicBool::new(all_links_fetched), @@ -747,7 +770,12 @@ impl SeaChunkLinkFetcher { match self .client - .get_result_chunks(&self.statement_id, server_fetch_idx, row_offset) + .get_result_chunks( + &self.statement_id, + server_fetch_idx, + row_offset, + self.session_attribution, + ) .await { Ok(result) => { @@ -940,7 +968,12 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { ); let result = fetcher .client - .get_result_chunks(&fetcher.statement_id, start_chunk_index, start_row_offset) + .get_result_chunks( + &fetcher.statement_id, + start_chunk_index, + start_row_offset, + fetcher.session_attribution, + ) .await?; // Cache the new links. @@ -1003,7 +1036,12 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { let result = self .inner .client - .get_result_chunks(&self.inner.statement_id, chunk_index, 0) + .get_result_chunks( + &self.inner.statement_id, + chunk_index, + 0, + self.inner.session_attribution, + ) .await?; let link = result @@ -1028,7 +1066,12 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { let result = self .inner .client - .get_result_chunks(&self.inner.statement_id, chunk_index, row_offset) + .get_result_chunks( + &self.inner.statement_id, + chunk_index, + row_offset, + self.inner.session_attribution, + ) .await?; // The SEA contract today caps the number of links in a @@ -1100,17 +1143,25 @@ mod tests { use crate::types::sea::{ExecuteParams, StatementState, StatementStatus}; use arrow_schema::Schema; use std::collections::HashMap; - use std::sync::Arc as StdArc; + use std::sync::{Arc as StdArc, Mutex as StdMutex}; /// Mock Transport for testing #[derive(Debug)] struct MockDatabricksClient { chunks: Vec>, + session_attributions: StdMutex>, } impl MockDatabricksClient { fn new(chunks: Vec>) -> Self { - Self { chunks } + Self { + chunks, + session_attributions: StdMutex::new(Vec::new()), + } + } + + fn session_attributions(&self) -> Vec { + self.session_attributions.lock().unwrap().clone() } } @@ -1147,6 +1198,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 +1227,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 +1235,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") } @@ -1191,7 +1245,12 @@ mod tests { _statement_id: &str, chunk_index: i64, _row_offset: i64, + session_attribution: SessionAttribution, ) -> Result { + self.session_attributions + .lock() + .unwrap() + .push(session_attribution); let index = chunk_index as usize; if index >= self.chunks.len() { return Ok(ChunkLinkFetchResult::end_of_stream()); @@ -1218,6 +1277,7 @@ mod tests { _statement_id: &str, _chunk_index: i64, _row_offset: i64, + _session_attribution: crate::client::SessionAttribution, ) -> Result { unimplemented!("get_inline_chunk not used by the link-fetcher mock") } @@ -1484,6 +1544,29 @@ mod tests { assert!(handle.inner.has_link(1)); } + #[tokio::test] + async fn detached_attribution_is_preserved_for_lazy_link_fetches() { + let links = vec![vec![create_test_link_terminal(0)]]; + let client = Arc::new(MockDatabricksClient::new(links)); + let fetcher = SeaChunkLinkFetcher::new_with_attribution( + client.clone(), + "test-statement", + &[], + None, + -1, + tokio::runtime::Handle::current(), + SessionAttribution::Detached, + ); + let handle = SeaChunkLinkFetcherHandle::new(fetcher); + + handle.refetch_link(0, 0).await.unwrap(); + + assert_eq!( + client.session_attributions(), + vec![SessionAttribution::Detached] + ); + } + #[tokio::test] async fn test_sea_link_fetcher_refetch_link_not_found() { let links = vec![vec![create_test_link_terminal(0)]]; diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index fad6cf68..27ae5be0 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -63,7 +63,7 @@ //! respectively. End-of-stream is the absence of `next_chunk_index` //! on a fetched chunk — never synthesised from `chunk_index + 1`. -use crate::client::{InlineChunkFetchResult, Transport}; +use crate::client::InlineChunkFetchResult; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, error}; use crate::reader::cloudfetch::parse_arrow_ipc; @@ -92,18 +92,6 @@ pub(crate) trait InlineChunkSource: Send + Sync + std::fmt::Debug { ) -> Result; } -#[async_trait] -impl InlineChunkSource for Arc { - async fn get_inline_chunk( - &self, - statement_id: &str, - chunk_index: i64, - row_offset: i64, - ) -> Result { - Transport::get_inline_chunk(self.as_ref(), statement_id, chunk_index, row_offset).await - } -} - /// One pre-decoded inline-Arrow chunk sitting in the rolling window. #[derive(Debug)] struct InlineChunkEntry { diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 02704873..a896dde0 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -25,12 +25,14 @@ pub mod post_processor; #[cfg(test)] pub(crate) mod test_utils; -use crate::client::{DatabricksHttpClient, ExecuteResponse, Transport}; +use crate::client::{ + DatabricksHttpClient, ExecuteResponse, InlineChunkFetchResult, SessionAttribution, Transport, +}; use crate::kernel_error::{Error, Result}; use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; use crate::reader::cloudfetch::link_fetcher::{SeaChunkLinkFetcher, SeaChunkLinkFetcherHandle}; use crate::reader::cloudfetch::streaming_provider::StreamingCloudFetchProvider; -use crate::reader::inline::{InlineArrowProvider, InlineStreamingProvider}; +use crate::reader::inline::{InlineArrowProvider, InlineChunkSource, InlineStreamingProvider}; use crate::reader::post_processor::{PostProcessOptions, ResultPostProcessor}; use crate::types::cloudfetch::{CloudFetchConfig, CloudFetchLink}; use crate::types::sea::{CompressionCodec, ResultManifest, StatementState}; @@ -42,6 +44,31 @@ use std::time::Duration; pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader; +#[derive(Debug)] +struct AttributedInlineChunkSource { + client: Arc, + session_attribution: SessionAttribution, +} + +#[async_trait] +impl InlineChunkSource for AttributedInlineChunkSource { + async fn get_inline_chunk( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + ) -> Result { + self.client + .get_inline_chunk( + statement_id, + chunk_index, + row_offset, + self.session_attribution, + ) + .await + } +} + /// Factory that creates the appropriate reader based on the response type. /// /// Encapsulates the decision of CloudFetch vs inline vs other result formats. @@ -99,8 +126,9 @@ impl ResultReaderFactory { &self, statement_id: &str, response: &ExecuteResponse, + session_attribution: SessionAttribution, ) -> Result> { - let inner = self.create_inner_reader(statement_id, response)?; + let inner = self.create_inner_reader(statement_id, response, session_attribution)?; Ok(Box::new( ResultPostProcessor::new( inner, @@ -119,6 +147,7 @@ impl ResultReaderFactory { &self, statement_id: &str, response: &ExecuteResponse, + session_attribution: SessionAttribution, ) -> Result> { // Log manifest info for debugging if let Some(ref manifest) = response.manifest { @@ -210,6 +239,7 @@ impl ResultReaderFactory { external_links, total_chunk_count, compression, + session_attribution, ); } } @@ -324,6 +354,7 @@ impl ResultReaderFactory { Some(next_idx), compression, manifest_schema, + session_attribution, ); } @@ -433,6 +464,7 @@ impl ResultReaderFactory { external_links: &[CloudFetchLink], total_chunk_count: Option, compression: CompressionCodec, + session_attribution: SessionAttribution, ) -> Result> { crate::klog::debug!( statement_id, @@ -449,13 +481,14 @@ impl ResultReaderFactory { // transition-period guard for servers that haven't rolled // out the per-link field yet — see // `SeaChunkLinkFetcher::decode_continuation`. - let fetcher = SeaChunkLinkFetcher::new( + let fetcher = SeaChunkLinkFetcher::new_with_attribution( self.client.clone(), statement_id.to_string(), external_links, total_chunk_count, self.config.link_prefetch_window as i64, self.runtime_handle.clone(), + session_attribution, ); let link_fetcher: Arc = Arc::new(SeaChunkLinkFetcherHandle::new(fetcher)); @@ -522,6 +555,7 @@ impl ResultReaderFactory { next_chunk_index: Option, compression: CompressionCodec, manifest_schema: Option, + session_attribution: SessionAttribution, ) -> Result> { crate::klog::debug!( "Creating inline-Arrow streaming reader: stmt={}, initial_chunk={}, \ @@ -532,19 +566,10 @@ impl ResultReaderFactory { self.config.inline_max_chunks_in_memory, ); - // Note: `Arc::new(self.client.clone())` produces - // `Arc>` because the blanket impl of - // `InlineChunkSource` is on `Arc` (not on - // `dyn Transport`), and trait-objects of different traits - // don't share a vtable so direct coercion - // `Arc` → `Arc` - // isn't legal. The outer `Arc::new` is the price of using a - // narrow trait so test mocks don't have to stub the full - // 20-method `Transport` surface; net cost is one extra - // pointer + one extra deref per RPC, negligible vs the SEA - // round-trip. - let source: Arc = - Arc::new(self.client.clone()); + let source: Arc = Arc::new(AttributedInlineChunkSource { + client: self.client.clone(), + session_attribution, + }); let provider = InlineStreamingProvider::new( source, statement_id.to_string(), @@ -1455,12 +1480,12 @@ mod tests { use crate::reader::post_processor::PostProcessOptions; use crate::types::sea::{ExecuteParams, ServiceError, StatementStatus}; use std::collections::HashMap; + use std::sync::Mutex as StdMutex; - /// Transport stub that panics on every method. Adequate for - /// tests that exercise the *factory's* synchronous control - /// flow before any RPC fires (e.g. the rollout-skew guard). - #[derive(Debug)] - struct PanickingTransport; + #[derive(Debug, Default)] + struct PanickingTransport { + inline_chunk_attributions: StdMutex>, + } #[async_trait] impl Transport for PanickingTransport { @@ -1499,13 +1524,27 @@ 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 { + async fn get_result_chunks( + &self, + _: &str, + _: i64, + _: i64, + _: crate::client::SessionAttribution, + ) -> Result { unreachable!() } async fn get_inline_chunk( @@ -1513,8 +1552,13 @@ mod tests { _: &str, _: i64, _: i64, + session_attribution: SessionAttribution, ) -> Result { - unreachable!() + self.inline_chunk_attributions + .lock() + .unwrap() + .push(session_attribution); + Err(Error::invalid_state().message("recorded inline chunk attribution")) } fn poll_config(&self) -> TransportConfig { TransportConfig::default() @@ -1619,7 +1663,7 @@ mod tests { ); let runtime = tokio::runtime::Handle::current(); ResultReaderFactory::new( - Arc::new(PanickingTransport), + Arc::new(PanickingTransport::default()), http_client, CloudFetchConfig::default(), PostProcessOptions::default(), @@ -1627,11 +1671,27 @@ mod tests { ) } + #[tokio::test] + async fn inline_chunk_source_preserves_detached_attribution() { + let transport = Arc::new(PanickingTransport::default()); + let source = AttributedInlineChunkSource { + client: transport.clone(), + session_attribution: SessionAttribution::Detached, + }; + + assert!(source.get_inline_chunk("statement", 1, 3).await.is_err()); + assert_eq!( + *transport.inline_chunk_attributions.lock().unwrap(), + vec![SessionAttribution::Detached] + ); + } + fn ok_status() -> StatementStatus { StatementStatus { state: StatementState::Succeeded, error: None::, sql_state: None, + session_version: None, num_modified_rows: None, display_message: None, diagnostic_info: None, @@ -1680,10 +1740,11 @@ mod tests { }), }; - let err = match factory.create_inner_reader("stmt-1", &response) { - Ok(_) => panic!("rollout-skew must surface as Err"), - Err(e) => e, - }; + let err = + match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { + Ok(_) => panic!("rollout-skew must surface as Err"), + Err(e) => e, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.contains("total_chunk_count"), @@ -1721,7 +1782,7 @@ mod tests { }), }; - match factory.create_inner_reader("stmt-1", &response) { + match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { // OK or any non-rollout-guard error is acceptable — // we're proving the guard is *not* the failure mode. Ok(_) => {} @@ -1757,10 +1818,11 @@ mod tests { }), }; - let err = match factory.create_inner_reader("stmt-1", &response) { - Ok(_) => panic!("missing row_count on streaming response must surface as Err"), - Err(e) => e, - }; + let err = + match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { + Ok(_) => panic!("missing row_count on streaming response must surface as Err"), + Err(e) => e, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.to_lowercase().contains("row_count"), @@ -1787,10 +1849,11 @@ mod tests { }), }; - let err = match factory.create_inner_reader("stmt-1", &response) { - Ok(_) => panic!("missing chunk_index on streaming response must surface as Err"), - Err(e) => e, - }; + let err = + match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { + Ok(_) => panic!("missing chunk_index on streaming response must surface as Err"), + Err(e) => e, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.to_lowercase().contains("chunk_index"), @@ -1834,7 +1897,7 @@ mod tests { }; let mut reader = factory - .create_inner_reader("stmt-1", &response) + .create_inner_reader("stmt-1", &response, SessionAttribution::Current) .expect("zero-chunk manifest must succeed without parsing inline bytes"); assert!( reader.next_batch().await.unwrap().is_none(), @@ -1859,7 +1922,7 @@ mod tests { }; let mut reader = factory - .create_inner_reader("stmt-1", &response) + .create_inner_reader("stmt-1", &response, SessionAttribution::Current) .expect("absent total_chunk_count + Succeeded state must yield empty reader"); assert!(reader.next_batch().await.unwrap().is_none()); } @@ -1894,7 +1957,7 @@ mod tests { // a parse error. If the short-circuit had fired, this would // return `Ok` and we'd never reach the IPC parser. let err = factory - .create_inner_reader("stmt-1", &response) + .create_inner_reader("stmt-1", &response, SessionAttribution::Current) .err() .expect("non-zero total_chunk_count + garbage inline must surface parse error"); assert!( diff --git a/src/session.rs b/src/session.rs index 2618e4f5..bfb174b0 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, @@ -345,6 +345,7 @@ impl Session { host.clone(), warehouse_id.clone(), transport_config, + config.auth.is_direct_routing_eligible(), )); let reader_factory = ResultReaderFactory::new( sea.clone() as Arc, @@ -653,7 +654,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 @@ -1912,9 +1913,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..178c5a01 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,17 @@ 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, + #[serde(default)] + pub direct_routing_enabled: bool, } /// Response from fetching result chunks. @@ -484,12 +505,32 @@ 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 }) + ); + assert!(!response.direct_routing_enabled); + + let response: CreateSessionResponse = + serde_json::from_str(r#"{"session_id":"session-1","direct_routing_enabled":true}"#) + .unwrap(); + assert!(response.direct_routing_enabled); } #[test] @@ -498,6 +539,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 +555,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 +566,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;