From 9207851e1e7fe2c96d687d26113a2802a952c5b3 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 2 Oct 2026 16:27:19 +0000 Subject: [PATCH 1/9] feat(session): use warehouse URLs for realtime sessions Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 2 + src/c_abi/session.rs | 4 +- src/client/sea.rs | 422 ++++++++++++++++-- src/client/transport.rs | 2 + src/reader/cloudfetch/link_fetcher.rs | 94 +++- src/reader/inline/streaming.rs | 19 +- src/reader/mod.rs | 136 ++++-- src/session.rs | 16 +- tests/klog_bridge.rs | 2 +- tests/token_federation_wiremock.rs | 2 +- tests/v0_async_execute_wiremock.rs | 4 +- tests/v0_c_abi_canceller_wiremock.rs | 2 +- .../v0_c_abi_metadata_table_types_wiremock.rs | 2 +- tests/v0_c_abi_result_config_wiremock.rs | 2 +- ..._c_abi_result_stream_canceller_wiremock.rs | 2 +- tests/v0_c_abi_session_close_wiremock.rs | 2 +- tests/v0_c_abi_session_test_wiremock.rs | 6 +- tests/v0_execute_wiremock.rs | 4 +- tests/v0_logging_wiremock.rs | 2 +- tests/v0_metadata_wiremock.rs | 2 +- tests/v0_session_wiremock.rs | 34 +- tests/v0_statement_canceller_reexecute.rs | 2 +- 22 files changed, 610 insertions(+), 153 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..f587f9cd 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -13,6 +13,8 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- SQL sessions open through the warehouse sessions URL and use warehouse statement URLs when the create response enables real-time routing. + ### Updated ### Fixed diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 0be472fc..a4473e63 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -2770,7 +2770,7 @@ mod tests { let server = MockServer::start().await; let counter = attempts.clone(); Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(move |_req: &wiremock::Request| { // First attempt 503 (retryable); a retrying policy would // then see the 200 below. @@ -3140,7 +3140,7 @@ mod tests { let (server, session, exporter) = rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-cabi-telemetry-close","warehouse_id":"test_wh"}"#, )) diff --git a/src/client/sea.rs b/src/client/sea.rs index 62b967cb..0d71fe06 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -49,6 +49,7 @@ 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"; +const REALTIME_SESSION_HEADER: &str = "x-databricks-rt-session"; /// DBSQL omits session versions, while server-issued FAST versions start at 1. const NO_SESSION_VERSION: i64 = 0; @@ -114,6 +115,12 @@ enum StatementOutcome { Err(Error), } +#[derive(Debug)] +enum SessionRoute { + Standard, + Realtime(String), +} + /// Mapped terminal outcome from the synchronous execution phase. /// /// `statement_id` is captured from the initial execute response for cleanup; @@ -171,6 +178,7 @@ pub(crate) struct SeaRestTransport { host: String, warehouse_id: String, config: TransportConfig, + session_route: OnceLock, session_version: AtomicI64, reader_factory: OnceLock, runtime_handle: OnceLock, @@ -212,6 +220,7 @@ impl SeaRestTransport { host: host.into(), warehouse_id: warehouse_id.into(), config, + session_route: OnceLock::new(), session_version: AtomicI64::new(NO_SESSION_VERSION), reader_factory: OnceLock::new(), runtime_handle: OnceLock::new(), @@ -234,11 +243,38 @@ impl SeaRestTransport { }) } - /// Build the base URL for API requests. fn base_url(&self) -> String { format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) } + fn warehouse_sessions_url(&self) -> String { + format!( + "{}/api/2.0/warehouses/{}/sessions", + self.host.trim_end_matches('/'), + self.warehouse_id + ) + } + + fn realtime_session_id(&self) -> Option<&str> { + match self.session_route.get() { + Some(SessionRoute::Realtime(session_id)) => Some(session_id), + _ => None, + } + } + + fn statements_url(&self, session_attribution: SessionAttribution) -> String { + if session_attribution == SessionAttribution::Current { + if let Some(session_id) = self.realtime_session_id() { + return format!( + "{}/{}/statements", + self.warehouse_sessions_url(), + session_id + ); + } + } + format!("{}/statements", self.base_url()) + } + 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 }) @@ -293,23 +329,29 @@ impl SeaRestTransport { /// when adding more. /// /// See: - fn result_chunks_url(&self, statement_id: &str, chunk_index: i64, row_offset: i64) -> String { + fn result_chunks_url( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + session_attribution: SessionAttribution, + ) -> String { debug_assert!( row_offset >= 0, "row_offset must be non-negative on the SEA wire (got {row_offset})", ); if row_offset > 0 { format!( - "{}/statements/{}/result/chunks/{}?row_offset={}", - self.base_url(), + "{}/{}/result/chunks/{}?row_offset={}", + self.statements_url(session_attribution), statement_id, chunk_index, row_offset ) } else { format!( - "{}/statements/{}/result/chunks/{}", - self.base_url(), + "{}/{}/result/chunks/{}", + self.statements_url(session_attribution), statement_id, chunk_index ) @@ -348,7 +390,11 @@ impl SeaRestTransport { statement_id: &str, session_attribution: SessionAttribution, ) -> Result { - let url = format!("{}/statements/{}", self.base_url(), statement_id); + let url = format!( + "{}/{}", + self.statements_url(session_attribution), + statement_id + ); debug!("Getting statement status at {}", url); @@ -404,7 +450,8 @@ impl SeaRestTransport { let mut response = self .get_statement_status_raw(statement_id, session_attribution) .await?; - self.enrich_num_modified_rows(&mut response).await; + self.enrich_num_modified_rows(&mut response, session_attribution) + .await; Ok(response) } @@ -420,7 +467,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; } @@ -435,7 +486,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, @@ -611,7 +662,7 @@ impl SeaRestTransport { request_type: RequestType, metadata_operation: Option, ) -> Result { - let url = format!("{}/statements", self.base_url()); + let url = self.statements_url(SessionAttribution::Current); // Select the result disposition per statement from the // connection-level CloudFetch setting, mirroring the reference @@ -833,7 +884,11 @@ impl SeaRestTransport { // rewrite in the same pass and can eagerly download CloudFetch chunk 0 // to extract its schema. let reader = reader_factory - .create_reader(&response.statement_id, &response) + .create_reader( + &response.statement_id, + &response, + SessionAttribution::Current, + ) .await?; // Carry the full status forward so the executed handle can skip a @@ -971,7 +1026,8 @@ impl SeaRestTransport { // after terminal mapping, keeping this result work out of the execution // phase without shifting it onto the public result stream. if response_from_poll { - self.enrich_num_modified_rows(&mut response).await; + self.enrich_num_modified_rows(&mut response, SessionAttribution::Current) + .await; } let reader_factory = self.reader_factory()?; @@ -1101,7 +1157,7 @@ impl Transport for SeaRestTransport { schema: Option<&str>, session_config: HashMap, ) -> Result { - let url = format!("{}/sessions", self.base_url()); + let url = self.warehouse_sessions_url(); let request_body = CreateSessionRequest { warehouse_id: self.warehouse_id.clone(), @@ -1128,6 +1184,11 @@ impl Transport for SeaRestTransport { .http_client .execute(request, RequestType::CreateSession) .await?; + let realtime = response + .headers() + .get(REALTIME_SESSION_HEADER) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.eq_ignore_ascii_case("true")); let body = response .text() .await @@ -1138,7 +1199,14 @@ impl Transport for SeaRestTransport { "Failed to parse session response: {e} - body: {body}" )) })?; - + let route = if realtime { + SessionRoute::Realtime(session_response.session_id.clone()) + } else { + SessionRoute::Standard + }; + self.session_route.set(route).map_err(|_| { + Error::invalid_state().message("SQL transport already created a session") + })?; self.observe_session_version(session_response.session_version); debug!("Created session: {}", session_response.session_id); @@ -1149,18 +1217,16 @@ impl Transport for SeaRestTransport { } async fn delete_session(&self, session_id: &str) -> Result<()> { - // SEA requires `warehouse_id` as a query parameter on - // `DELETE /api/2.0/sql/sessions/{id}`. Without it the server - // returns HTTP 400 ("Required field is not specified: - // warehouse_id"), the session never gets cleaned up via the - // explicit close path, and instead waits for the idle-timeout - // reaper to drop it. - let url = format!( - "{}/sessions/{}?warehouse_id={}", - self.base_url(), - session_id, - self.warehouse_id - ); + let url = if let Some(realtime_session_id) = self.realtime_session_id() { + format!("{}/{}", self.warehouse_sessions_url(), realtime_session_id) + } else { + format!( + "{}/sessions/{}?warehouse_id={}", + self.base_url(), + session_id, + self.warehouse_id + ) + }; debug!("Deleting session at {}", url); @@ -1280,7 +1346,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)") @@ -1322,7 +1391,9 @@ impl Transport for SeaRestTransport { 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 { @@ -1353,8 +1424,10 @@ 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); + let url = + self.result_chunks_url(statement_id, chunk_index, row_offset, session_attribution); debug!("Getting result chunks at {}", url); @@ -1398,6 +1471,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 @@ -1415,8 +1489,8 @@ impl Transport for SeaRestTransport { ); let row_offset = row_offset.max(0); let url = format!( - "{}/statements/{}/result/chunks/{}?row_offset={}", - self.base_url(), + "{}/{}/result/chunks/{}?row_offset={}", + self.statements_url(session_attribution), statement_id, chunk_index, row_offset, @@ -1519,7 +1593,11 @@ impl Transport for SeaRestTransport { } async fn cancel_statement(&self, statement_id: &str) -> Result<()> { - let url = format!("{}/statements/{}/cancel", self.base_url(), statement_id); + let url = format!( + "{}/{}/cancel", + self.statements_url(SessionAttribution::Current), + statement_id + ); debug!("Canceling statement at {}", url); @@ -1542,7 +1620,11 @@ impl Transport for SeaRestTransport { } async fn close_statement(&self, statement_id: &str) -> Result<()> { - let url = format!("{}/statements/{}", self.base_url(), statement_id); + let url = format!( + "{}/{}", + self.statements_url(SessionAttribution::Current), + statement_id + ); debug!("Closing statement at {}", url); @@ -2539,7 +2621,7 @@ mod tests { // CloudFetch path: row_offset=0 is the kernel default and must // produce the legacy URL shape (no `?row_offset=...`). assert_eq!( - client.result_chunks_url("01abc", 7, 0), + client.result_chunks_url("01abc", 7, 0, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/7" ); } @@ -2560,7 +2642,7 @@ mod tests { // the right rowOffset. let client = create_test_client(); assert_eq!( - client.result_chunks_url("01abc", 3, 12345), + client.result_chunks_url("01abc", 3, 12345, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/3?row_offset=12345" ); } @@ -2572,7 +2654,7 @@ mod tests { // would still match `12345` and `i64::MAX`) is caught. let client = create_test_client(); assert_eq!( - client.result_chunks_url("01abc", 3, 1), + client.result_chunks_url("01abc", 3, 1, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/3?row_offset=1" ); } @@ -2585,7 +2667,7 @@ mod tests { // offsets at request-time. The URL builder must not panic // or truncate for the legal range. let client = create_test_client(); - let url = client.result_chunks_url("01abc", 0, i64::MAX); + let url = client.result_chunks_url("01abc", 0, i64::MAX, SessionAttribution::Current); assert!( url.ends_with(&format!("?row_offset={}", i64::MAX)), "i64::MAX must serialise as decimal: got {url}", @@ -2610,6 +2692,262 @@ mod tests { ) } + #[tokio::test] + async fn realtime_session_uses_warehouse_urls_for_owned_lifecycle() { + 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/warehouses/warehouse-123/sessions")) + .respond_with( + ResponseTemplate::new(200) + .insert_header(REALTIME_SESSION_HEADER, "true") + .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/warehouses/warehouse-123/sessions/session-1/statements", + )) + .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/warehouses/warehouse-123/sessions/session-1/statements/statement-1", + )) + .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/warehouses/warehouse-123/sessions/session-1/statements/statement-1/result/chunks/0")) + .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/warehouses/warehouse-123/sessions/session-1/statements/inline-statement/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==", + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/warehouses/warehouse-123/sessions/session-1/statements/statement-1/cancel")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path( + "/api/2.0/warehouses/warehouse-123/sessions/session-1/statements/statement-1", + )) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/warehouses/warehouse-123/sessions/session-1")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let transport = create_test_client_against(&server.uri()); + 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 close = requests + .iter() + .find(|request| { + request.method == Method::DELETE + && request.url.path() == "/api/2.0/warehouses/warehouse-123/sessions/session-1" + }) + .expect("session close request must be recorded"); + assert!(close.url.query().is_none()); + assert!(requests + .iter() + .all(|request| request.headers.get(REALTIME_SESSION_HEADER).is_none())); + } + + #[tokio::test] + async fn create_session_response_selects_session_statement_urls() { + use wiremock::matchers::{method, path, query_param}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let cases = [(Some("TRUE"), true), (Some("false"), false), (None, false)]; + + for (header_value, realtime) in cases { + let server = MockServer::start().await; + let mut create_response = ResponseTemplate::new(200).set_body_json(json!({ + "session_id": "session-1", + })); + if let Some(value) = header_value { + create_response = create_response.insert_header(REALTIME_SESSION_HEADER, value); + } + + Mock::given(method("POST")) + .and(path("/api/2.0/warehouses/warehouse-123/sessions")) + .respond_with(create_response) + .expect(1) + .mount(&server) + .await; + let statement_path = if realtime { + "/api/2.0/warehouses/warehouse-123/sessions/session-1/statements" + } else { + "/api/2.0/sql/statements" + }; + Mock::given(method("POST")) + .and(path(statement_path)) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-1", + "status": { "state": "PENDING" }, + }))) + .expect(1) + .mount(&server) + .await; + let close_path = if realtime { + "/api/2.0/warehouses/warehouse-123/sessions/session-1" + } else { + "/api/2.0/sql/sessions/session-1" + }; + let mut close_mock = Mock::given(method("DELETE")).and(path(close_path)); + if !realtime { + close_mock = close_mock.and(query_param("warehouse_id", "warehouse-123")); + } + close_mock + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let transport = create_test_client_against(&server.uri()); + 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 + .delete_session(&session.session_id) + .await + .expect("session close must succeed"); + + server.verify().await; + let requests = server.received_requests().await.unwrap(); + assert!(requests + .iter() + .any(|request| request.url.path() == statement_path)); + assert!(requests + .iter() + .any(|request| request.url.path() == close_path)); + } + } + + #[tokio::test] + async fn detached_statement_requests_use_standard_urls() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/warehouses/warehouse-123/sessions")) + .respond_with( + ResponseTemplate::new(200) + .insert_header(REALTIME_SESSION_HEADER, "true") + .set_body_json(json!({ "session_id": "session-1" })), + ) + .expect(1) + .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" }, + }))) + .expect(1) + .mount(&server) + .await; + + let transport = create_test_client_against(&server.uri()); + 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"); + + let requests = server.received_requests().await.unwrap(); + let detached = requests + .iter() + .find(|request| request.url.path() == "/api/2.0/sql/statements/detached") + .expect("detached status request must be recorded"); + assert!(detached.headers.get(REALTIME_SESSION_HEADER).is_none()); + } + #[tokio::test] async fn exchanges_session_versions_on_create_and_execute() { use serde_json::json; @@ -2618,7 +2956,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/warehouse-123/sessions")) .and(body_json(json!({ "warehouse_id": "warehouse-123", "execution_mode": "FAST", @@ -2725,7 +3063,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/warehouse-123/sessions")) .respond_with( ResponseTemplate::new(200).set_body_string(r#"{"session_id":"session-1"}"#), ) @@ -2841,7 +3179,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"); @@ -2879,7 +3217,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 4415f78d..b8e3ba30 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -398,6 +398,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 @@ -419,6 +420,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/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 2ee9314a..81b9cfc9 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() } } @@ -1195,7 +1246,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()); @@ -1222,6 +1278,7 @@ mod tests { _statement_id: &str, _chunk_index: i64, _row_offset: i64, + _session_attribution: SessionAttribution, ) -> Result { unimplemented!("get_inline_chunk not used by the link-fetcher mock") } @@ -1488,6 +1545,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 0ae25e2e..f70a7785 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; @@ -78,10 +78,7 @@ use tracing::instrument; /// Narrow source trait for inline-chunk fetches. /// -/// Lets the streaming provider depend on just the one method it -/// needs (so tests don't have to build a full `Transport` mock with -/// `unreachable!()` for the 20-odd metadata RPCs). Production code -/// uses the blanket impl on `Arc`. +/// Keeps reader tests independent of the full transport interface. #[async_trait] pub(crate) trait InlineChunkSource: Send + Sync + std::fmt::Debug { async fn get_inline_chunk( @@ -92,18 +89,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 3ee1e7c4..5c1f97c8 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -25,13 +25,15 @@ 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::config::GeospatialResultRepresentation; 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}; @@ -45,6 +47,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. @@ -105,8 +132,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, @@ -125,6 +153,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 { @@ -216,6 +245,7 @@ impl ResultReaderFactory { external_links, total_chunk_count, compression, + session_attribution, ); } } @@ -330,6 +360,7 @@ impl ResultReaderFactory { Some(next_idx), compression, manifest_schema, + session_attribution, ); } @@ -517,6 +548,7 @@ impl ResultReaderFactory { external_links: &[CloudFetchLink], total_chunk_count: Option, compression: CompressionCodec, + session_attribution: SessionAttribution, ) -> Result> { crate::klog::debug!( statement_id, @@ -533,13 +565,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)); @@ -602,6 +635,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={}, \ @@ -612,19 +646,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(), @@ -1899,12 +1924,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 { @@ -1958,7 +1983,13 @@ mod tests { ) -> Result { unreachable!() } - async fn get_result_chunks(&self, _: &str, _: i64, _: i64) -> Result { + async fn get_result_chunks( + &self, + _: &str, + _: i64, + _: i64, + _: SessionAttribution, + ) -> Result { unreachable!() } async fn get_inline_chunk( @@ -1966,8 +1997,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() @@ -2072,7 +2108,7 @@ mod tests { ); let runtime = tokio::runtime::Handle::current(); ResultReaderFactory::new( - Arc::new(PanickingTransport), + Arc::new(PanickingTransport::default()), http_client, CloudFetchConfig::default(), PostProcessOptions::default(), @@ -2081,6 +2117,21 @@ 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, @@ -2137,10 +2188,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"), @@ -2178,7 +2230,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(_) => {} @@ -2214,10 +2266,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"), @@ -2244,10 +2297,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"), @@ -2291,7 +2345,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(), @@ -2316,7 +2370,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()); } @@ -2351,7 +2405,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 8a8ae6f0..887935d6 100644 --- a/src/session.rs +++ b/src/session.rs @@ -2119,10 +2119,10 @@ mod is_open_tests { use wiremock::{Mock, MockServer, ResponseTemplate}; #[tokio::test] - async fn sessions_enable_version_exchange_on_standard_path() { + async fn sessions_enable_version_exchange() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .and(body_json(json!({ "warehouse_id": "test_wh", "execution_mode": "FAST", @@ -2149,7 +2149,7 @@ mod is_open_tests { }) .open() .await - .expect("FAST session must open on the standard path"); + .expect("FAST session must open"); session.close().await.expect("FAST session must close"); } @@ -2166,7 +2166,7 @@ mod is_open_tests { async fn is_open_flips_true_to_false_on_delete() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-is-open","warehouse_id":"test_wh"}"#), @@ -2217,7 +2217,7 @@ mod is_open_tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test-conn","warehouse_id":"test_wh"}"#), @@ -2309,7 +2309,7 @@ mod is_open_tests { async fn test_connection_fails_when_server_unreachable() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-dead","warehouse_id":"test_wh"}"#), @@ -2360,7 +2360,7 @@ mod is_open_tests { async fn transaction_controls_are_noop_when_ignored() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-txn","warehouse_id":"test_wh"}"#), @@ -3555,7 +3555,7 @@ mod is_open_tests { async fn mount_session_create_delete(server: &MockServer, session_id: &str) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string(format!( r#"{{"session_id":"{session_id}","warehouse_id":"test_wh"}}"# ))) diff --git a/tests/klog_bridge.rs b/tests/klog_bridge.rs index efd36c7a..bc36653c 100644 --- a/tests/klog_bridge.rs +++ b/tests/klog_bridge.rs @@ -159,7 +159,7 @@ async fn empty_logging_config_open_does_not_install_subscriber() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-gate-213","warehouse_id":"test_wh"}"#), diff --git a/tests/token_federation_wiremock.rs b/tests/token_federation_wiremock.rs index 086f6fe3..a9641121 100644 --- a/tests/token_federation_wiremock.rs +++ b/tests/token_federation_wiremock.rs @@ -227,7 +227,7 @@ async fn auth_config_federation_client_id_reaches_exchange() { .mount(&server) .await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/warehouse-id/sessions")) .and(header("authorization", "Bearer wif-token")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "session_id": "session-id", diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 82675e24..40e047bd 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -55,7 +55,7 @@ async fn open_session(server: &MockServer) -> Session { async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), @@ -375,7 +375,7 @@ async fn submit_returns_pending_handle_without_polling() { 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(path("/api/2.0/warehouses/test_wh/sessions")) .and(body_json(json!({ "warehouse_id": "test_wh", "execution_mode": "FAST", diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 9bff47ec..6cde1ab1 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -712,7 +712,7 @@ fn async_c_abi_get_result_stream_state_guards() { async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_c_abi_metadata_table_types_wiremock.rs b/tests/v0_c_abi_metadata_table_types_wiremock.rs index 2ca95dea..1ef1fe67 100644 --- a/tests/v0_c_abi_metadata_table_types_wiremock.rs +++ b/tests/v0_c_abi_metadata_table_types_wiremock.rs @@ -51,7 +51,7 @@ fn list_table_types_returns_table_type_column() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-table-types","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index ce834d42..fc2d0766 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -44,7 +44,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_c_abi_result_stream_canceller_wiremock.rs b/tests/v0_c_abi_result_stream_canceller_wiremock.rs index e05c99bb..0835ea3b 100644 --- a/tests/v0_c_abi_result_stream_canceller_wiremock.rs +++ b/tests/v0_c_abi_result_stream_canceller_wiremock.rs @@ -85,7 +85,7 @@ fn exported_canceller_aborts_the_stream() { let server = rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-rs-cancel","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_c_abi_session_close_wiremock.rs b/tests/v0_c_abi_session_close_wiremock.rs index a06ab437..23a5e1b2 100644 --- a/tests/v0_c_abi_session_close_wiremock.rs +++ b/tests/v0_c_abi_session_close_wiremock.rs @@ -48,7 +48,7 @@ fn session_close_initiates_delete_with_statement_still_open() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-c-abi-close","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_c_abi_session_test_wiremock.rs b/tests/v0_c_abi_session_test_wiremock.rs index 6160b907..5b606208 100644 --- a/tests/v0_c_abi_session_test_wiremock.rs +++ b/tests/v0_c_abi_session_test_wiremock.rs @@ -118,7 +118,7 @@ fn session_test_returns_success_when_server_reachable() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-c-abi-test","warehouse_id":"test_wh"}"#, )) @@ -179,7 +179,7 @@ fn session_test_returns_error_when_server_unreachable() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-c-abi-dead","warehouse_id":"test_wh"}"#, )) @@ -216,7 +216,7 @@ fn session_test_honours_per_call_timeout() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-c-abi-slow","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 1e9a14fe..5ef93727 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -133,7 +133,7 @@ async fn recorded_execute_disposition(server: &MockServer) -> String { async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), @@ -985,7 +985,7 @@ async fn execute_geospatial_string_mode_uses_manifest_tags_for_untagged_arrow_ip let requests = server.received_requests().await.unwrap(); let create = requests .iter() - .find(|request| request.url.path() == "/api/2.0/sql/sessions") + .find(|request| request.url.path() == "/api/2.0/warehouses/test_wh/sessions") .expect("create-session request"); let body: serde_json::Value = serde_json::from_slice(&create.body).unwrap(); let forwarded_geo_setting = body diff --git a/tests/v0_logging_wiremock.rs b/tests/v0_logging_wiremock.rs index 69705006..76056194 100644 --- a/tests/v0_logging_wiremock.rs +++ b/tests/v0_logging_wiremock.rs @@ -42,7 +42,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; /// Mount a successful CreateSession stub. async fn mock_create_session_ok(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-log-213","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 8ba43918..7e301828 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -74,7 +74,7 @@ async fn open_session_with_default_catalog(server: &MockServer, catalog: Option< async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index 62130046..1ee4ecfa 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -14,14 +14,6 @@ //! Wiremock end-to-end tests for `Session::open` HTTP-status mapping. //! -//! Stubs the SEA `POST /api/2.0/sql/sessions` endpoint with each -//! status code in the migration plan's mapping table and asserts the -//! resulting `kernel_error::Error` carries the right `ErrorCode` and -//! `retryable` flag. This is the §7 follow-up that PR 1 deferred — -//! `Session::open` is the natural place to drive it because it -//! exercises the full HTTP path (auth header injection, request -//! dispatch, response decoding) end to end. -//! //! Retries are disabled because these tests verify status mapping, not //! retry orchestration (which has dedicated coverage in the HTTP client //! tests). This keeps retryable responses from sleeping through the @@ -58,7 +50,7 @@ async fn open_session_against(server: &MockServer) -> databricks_sql_kernel::Res /// Mount a single-response mock for the create-session endpoint. async fn mock_create_session_returns(server: &MockServer, status: u16, body: &'static str) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(status).set_body_string(body)) .mount(server) .await; @@ -104,7 +96,7 @@ async fn create_session_404_maps_to_not_found() { async fn create_session_429_maps_to_resource_exhausted_retryable() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(429).set_body_string("rate limited")) .mount(&server) .await; @@ -120,7 +112,7 @@ async fn create_session_429_maps_to_resource_exhausted_retryable() { async fn create_session_503_maps_to_unavailable_retryable() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(503).set_body_string("warehouse cold")) .mount(&server) .await; @@ -136,7 +128,7 @@ async fn create_session_503_maps_to_unavailable_retryable() { async fn create_session_504_maps_to_timeout_retryable() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(504).set_body_string("upstream timeout")) .mount(&server) .await; @@ -168,7 +160,7 @@ async fn create_session_500_maps_to_internal() { // Internal per the plan's mapping table. let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(500).set_body_string("server bug")) .mount(&server) .await; @@ -364,7 +356,9 @@ async fn assert_no_can_cloud_download_on_create(server: &MockServer) { .expect("server must have request log enabled"); let create = recorded .iter() - .find(|r| r.url.path() == "/api/2.0/sql/sessions" && r.method.as_str() == "POST") + .find(|r| { + r.url.path() == "/api/2.0/warehouses/test_wh/sessions" && r.method.as_str() == "POST" + }) .expect("a POST /sessions request was made"); let body: serde_json::Value = serde_json::from_slice(&create.body).expect("create-session body must be valid JSON"); @@ -388,7 +382,9 @@ async fn create_session_body(server: &MockServer) -> serde_json::Value { .expect("server must have request log enabled"); let create = recorded .iter() - .find(|r| r.url.path() == "/api/2.0/sql/sessions" && r.method.as_str() == "POST") + .find(|r| { + r.url.path() == "/api/2.0/warehouses/test_wh/sessions" && r.method.as_str() == "POST" + }) .expect("a POST /sessions request was made"); serde_json::from_slice(&create.body).expect("create-session body must be valid JSON") } @@ -405,7 +401,7 @@ async fn create_session_with_cloudfetch_disabled_omits_can_cloud_download() { // opens and the poisoned conf never reaches the wire. let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-cf-off","warehouse_id":"test_wh"}"#), @@ -431,7 +427,7 @@ async fn create_session_forwards_user_supplied_session_conf_unchanged() { // through unchanged; validation belongs to the server. let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-dropped","warehouse_id":"test_wh"}"#), @@ -496,7 +492,7 @@ async fn open_session_with_geospatial_config( async fn mount_geospatial_session(server: &MockServer, session_id: &str) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "session_id": session_id, "warehouse_id": "test_wh", @@ -615,7 +611,7 @@ async fn create_session_with_cloudfetch_enabled_omits_can_cloud_download() { // here on either branch now. let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-cf-on","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_statement_canceller_reexecute.rs b/tests/v0_statement_canceller_reexecute.rs index 26fed249..9f6404e3 100644 --- a/tests/v0_statement_canceller_reexecute.rs +++ b/tests/v0_statement_canceller_reexecute.rs @@ -58,7 +58,7 @@ async fn open_session(server: &MockServer) -> Session { async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), From 346782a42b606ad0c6c0ac09bf922c6d61b4b675 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 2 Oct 2026 17:57:39 +0000 Subject: [PATCH 2/9] fix(session): use SQL warehouse URL prefix Signed-off-by: Aakash Saravanan --- src/c_abi/session.rs | 4 +-- src/client/sea.rs | 35 ++++++++++--------- src/session.rs | 12 +++---- tests/klog_bridge.rs | 2 +- tests/token_federation_wiremock.rs | 2 +- tests/v0_async_execute_wiremock.rs | 4 +-- tests/v0_c_abi_canceller_wiremock.rs | 2 +- .../v0_c_abi_metadata_table_types_wiremock.rs | 2 +- tests/v0_c_abi_result_config_wiremock.rs | 2 +- ..._c_abi_result_stream_canceller_wiremock.rs | 2 +- tests/v0_c_abi_session_close_wiremock.rs | 2 +- tests/v0_c_abi_session_test_wiremock.rs | 6 ++-- tests/v0_execute_wiremock.rs | 4 +-- tests/v0_logging_wiremock.rs | 2 +- tests/v0_metadata_wiremock.rs | 2 +- tests/v0_session_wiremock.rs | 24 +++++++------ tests/v0_statement_canceller_reexecute.rs | 2 +- 17 files changed, 57 insertions(+), 52 deletions(-) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index a4473e63..73764e74 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -2770,7 +2770,7 @@ mod tests { let server = MockServer::start().await; let counter = attempts.clone(); Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(move |_req: &wiremock::Request| { // First attempt 503 (retryable); a retrying policy would // then see the 200 below. @@ -3140,7 +3140,7 @@ mod tests { let (server, session, exporter) = rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-cabi-telemetry-close","warehouse_id":"test_wh"}"#, )) diff --git a/src/client/sea.rs b/src/client/sea.rs index 0d71fe06..0a16a8d5 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -249,7 +249,7 @@ impl SeaRestTransport { fn warehouse_sessions_url(&self) -> String { format!( - "{}/api/2.0/warehouses/{}/sessions", + "{}/api/2.0/sql/warehouses/{}/sessions", self.host.trim_end_matches('/'), self.warehouse_id ) @@ -2699,7 +2699,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/warehouse-123/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) .respond_with( ResponseTemplate::new(200) .insert_header(REALTIME_SESSION_HEADER, "true") @@ -2714,7 +2714,7 @@ mod tests { Mock::given(method("POST")) .and(path( - "/api/2.0/warehouses/warehouse-123/sessions/session-1/statements", + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements", )) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "statement_id": "statement-1", @@ -2725,7 +2725,7 @@ mod tests { .await; Mock::given(method("GET")) .and(path( - "/api/2.0/warehouses/warehouse-123/sessions/session-1/statements/statement-1", + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/statement-1", )) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "statement_id": "statement-1", @@ -2735,7 +2735,7 @@ mod tests { .mount(&server) .await; Mock::given(method("GET")) - .and(path("/api/2.0/warehouses/warehouse-123/sessions/session-1/statements/statement-1/result/chunks/0")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/statement-1/result/chunks/0")) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "external_links": [], "next_chunk_index": null, @@ -2745,7 +2745,7 @@ mod tests { .await; Mock::given(method("GET")) .and(path( - "/api/2.0/warehouses/warehouse-123/sessions/session-1/statements/inline-statement/result/chunks/1", + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/inline-statement/result/chunks/1", )) .and(query_param("row_offset", "3")) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ @@ -2759,21 +2759,23 @@ mod tests { .mount(&server) .await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/warehouse-123/sessions/session-1/statements/statement-1/cancel")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/statement-1/cancel")) .respond_with(ResponseTemplate::new(200)) .expect(1) .mount(&server) .await; Mock::given(method("DELETE")) .and(path( - "/api/2.0/warehouses/warehouse-123/sessions/session-1/statements/statement-1", + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/statement-1", )) .respond_with(ResponseTemplate::new(200)) .expect(1) .mount(&server) .await; Mock::given(method("DELETE")) - .and(path("/api/2.0/warehouses/warehouse-123/sessions/session-1")) + .and(path( + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1", + )) .respond_with(ResponseTemplate::new(200)) .expect(1) .mount(&server) @@ -2819,7 +2821,8 @@ mod tests { .iter() .find(|request| { request.method == Method::DELETE - && request.url.path() == "/api/2.0/warehouses/warehouse-123/sessions/session-1" + && request.url.path() + == "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1" }) .expect("session close request must be recorded"); assert!(close.url.query().is_none()); @@ -2845,13 +2848,13 @@ mod tests { } Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/warehouse-123/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) .respond_with(create_response) .expect(1) .mount(&server) .await; let statement_path = if realtime { - "/api/2.0/warehouses/warehouse-123/sessions/session-1/statements" + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements" } else { "/api/2.0/sql/statements" }; @@ -2865,7 +2868,7 @@ mod tests { .mount(&server) .await; let close_path = if realtime { - "/api/2.0/warehouses/warehouse-123/sessions/session-1" + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1" } else { "/api/2.0/sql/sessions/session-1" }; @@ -2911,7 +2914,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/warehouse-123/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) .respond_with( ResponseTemplate::new(200) .insert_header(REALTIME_SESSION_HEADER, "true") @@ -2956,7 +2959,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/warehouse-123/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) .and(body_json(json!({ "warehouse_id": "warehouse-123", "execution_mode": "FAST", @@ -3063,7 +3066,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/warehouse-123/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) .respond_with( ResponseTemplate::new(200).set_body_string(r#"{"session_id":"session-1"}"#), ) diff --git a/src/session.rs b/src/session.rs index 887935d6..eba86ce6 100644 --- a/src/session.rs +++ b/src/session.rs @@ -2122,7 +2122,7 @@ mod is_open_tests { async fn sessions_enable_version_exchange() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .and(body_json(json!({ "warehouse_id": "test_wh", "execution_mode": "FAST", @@ -2166,7 +2166,7 @@ mod is_open_tests { async fn is_open_flips_true_to_false_on_delete() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-is-open","warehouse_id":"test_wh"}"#), @@ -2217,7 +2217,7 @@ mod is_open_tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test-conn","warehouse_id":"test_wh"}"#), @@ -2309,7 +2309,7 @@ mod is_open_tests { async fn test_connection_fails_when_server_unreachable() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-dead","warehouse_id":"test_wh"}"#), @@ -2360,7 +2360,7 @@ mod is_open_tests { async fn transaction_controls_are_noop_when_ignored() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-txn","warehouse_id":"test_wh"}"#), @@ -3555,7 +3555,7 @@ mod is_open_tests { async fn mount_session_create_delete(server: &MockServer, session_id: &str) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string(format!( r#"{{"session_id":"{session_id}","warehouse_id":"test_wh"}}"# ))) diff --git a/tests/klog_bridge.rs b/tests/klog_bridge.rs index bc36653c..80612026 100644 --- a/tests/klog_bridge.rs +++ b/tests/klog_bridge.rs @@ -159,7 +159,7 @@ async fn empty_logging_config_open_does_not_install_subscriber() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-gate-213","warehouse_id":"test_wh"}"#), diff --git a/tests/token_federation_wiremock.rs b/tests/token_federation_wiremock.rs index a9641121..50c008b7 100644 --- a/tests/token_federation_wiremock.rs +++ b/tests/token_federation_wiremock.rs @@ -227,7 +227,7 @@ async fn auth_config_federation_client_id_reaches_exchange() { .mount(&server) .await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/warehouse-id/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-id/sessions")) .and(header("authorization", "Bearer wif-token")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "session_id": "session-id", diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 40e047bd..b7618730 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -55,7 +55,7 @@ async fn open_session(server: &MockServer) -> Session { async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), @@ -375,7 +375,7 @@ async fn submit_returns_pending_handle_without_polling() { 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/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .and(body_json(json!({ "warehouse_id": "test_wh", "execution_mode": "FAST", diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 6cde1ab1..4d3df1ee 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -712,7 +712,7 @@ fn async_c_abi_get_result_stream_state_guards() { async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_c_abi_metadata_table_types_wiremock.rs b/tests/v0_c_abi_metadata_table_types_wiremock.rs index 1ef1fe67..220c2ac0 100644 --- a/tests/v0_c_abi_metadata_table_types_wiremock.rs +++ b/tests/v0_c_abi_metadata_table_types_wiremock.rs @@ -51,7 +51,7 @@ fn list_table_types_returns_table_type_column() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-table-types","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index fc2d0766..3c4b1515 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -44,7 +44,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_c_abi_result_stream_canceller_wiremock.rs b/tests/v0_c_abi_result_stream_canceller_wiremock.rs index 0835ea3b..a2e51467 100644 --- a/tests/v0_c_abi_result_stream_canceller_wiremock.rs +++ b/tests/v0_c_abi_result_stream_canceller_wiremock.rs @@ -85,7 +85,7 @@ fn exported_canceller_aborts_the_stream() { let server = rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-rs-cancel","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_c_abi_session_close_wiremock.rs b/tests/v0_c_abi_session_close_wiremock.rs index 23a5e1b2..e1b98189 100644 --- a/tests/v0_c_abi_session_close_wiremock.rs +++ b/tests/v0_c_abi_session_close_wiremock.rs @@ -48,7 +48,7 @@ fn session_close_initiates_delete_with_statement_still_open() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-c-abi-close","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_c_abi_session_test_wiremock.rs b/tests/v0_c_abi_session_test_wiremock.rs index 5b606208..0c633b7c 100644 --- a/tests/v0_c_abi_session_test_wiremock.rs +++ b/tests/v0_c_abi_session_test_wiremock.rs @@ -118,7 +118,7 @@ fn session_test_returns_success_when_server_reachable() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-c-abi-test","warehouse_id":"test_wh"}"#, )) @@ -179,7 +179,7 @@ fn session_test_returns_error_when_server_unreachable() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-c-abi-dead","warehouse_id":"test_wh"}"#, )) @@ -216,7 +216,7 @@ fn session_test_honours_per_call_timeout() { rt.block_on(async { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_string( r#"{"session_id":"sess-c-abi-slow","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 5ef93727..d006aa83 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -133,7 +133,7 @@ async fn recorded_execute_disposition(server: &MockServer) -> String { async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), @@ -985,7 +985,7 @@ async fn execute_geospatial_string_mode_uses_manifest_tags_for_untagged_arrow_ip let requests = server.received_requests().await.unwrap(); let create = requests .iter() - .find(|request| request.url.path() == "/api/2.0/warehouses/test_wh/sessions") + .find(|request| request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions") .expect("create-session request"); let body: serde_json::Value = serde_json::from_slice(&create.body).unwrap(); let forwarded_geo_setting = body diff --git a/tests/v0_logging_wiremock.rs b/tests/v0_logging_wiremock.rs index 76056194..ecb126a5 100644 --- a/tests/v0_logging_wiremock.rs +++ b/tests/v0_logging_wiremock.rs @@ -42,7 +42,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; /// Mount a successful CreateSession stub. async fn mock_create_session_ok(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-log-213","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 7e301828..ff86086b 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -74,7 +74,7 @@ async fn open_session_with_default_catalog(server: &MockServer, catalog: Option< async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index 1ee4ecfa..7dccb80e 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -50,7 +50,7 @@ async fn open_session_against(server: &MockServer) -> databricks_sql_kernel::Res /// Mount a single-response mock for the create-session endpoint. async fn mock_create_session_returns(server: &MockServer, status: u16, body: &'static str) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(status).set_body_string(body)) .mount(server) .await; @@ -96,7 +96,7 @@ async fn create_session_404_maps_to_not_found() { async fn create_session_429_maps_to_resource_exhausted_retryable() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(429).set_body_string("rate limited")) .mount(&server) .await; @@ -112,7 +112,7 @@ async fn create_session_429_maps_to_resource_exhausted_retryable() { async fn create_session_503_maps_to_unavailable_retryable() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(503).set_body_string("warehouse cold")) .mount(&server) .await; @@ -128,7 +128,7 @@ async fn create_session_503_maps_to_unavailable_retryable() { async fn create_session_504_maps_to_timeout_retryable() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(504).set_body_string("upstream timeout")) .mount(&server) .await; @@ -160,7 +160,7 @@ async fn create_session_500_maps_to_internal() { // Internal per the plan's mapping table. let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(500).set_body_string("server bug")) .mount(&server) .await; @@ -357,7 +357,8 @@ async fn assert_no_can_cloud_download_on_create(server: &MockServer) { let create = recorded .iter() .find(|r| { - r.url.path() == "/api/2.0/warehouses/test_wh/sessions" && r.method.as_str() == "POST" + r.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" + && r.method.as_str() == "POST" }) .expect("a POST /sessions request was made"); let body: serde_json::Value = @@ -383,7 +384,8 @@ async fn create_session_body(server: &MockServer) -> serde_json::Value { let create = recorded .iter() .find(|r| { - r.url.path() == "/api/2.0/warehouses/test_wh/sessions" && r.method.as_str() == "POST" + r.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" + && r.method.as_str() == "POST" }) .expect("a POST /sessions request was made"); serde_json::from_slice(&create.body).expect("create-session body must be valid JSON") @@ -401,7 +403,7 @@ async fn create_session_with_cloudfetch_disabled_omits_can_cloud_download() { // opens and the poisoned conf never reaches the wire. let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-cf-off","warehouse_id":"test_wh"}"#), @@ -427,7 +429,7 @@ async fn create_session_forwards_user_supplied_session_conf_unchanged() { // through unchanged; validation belongs to the server. let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-dropped","warehouse_id":"test_wh"}"#), @@ -492,7 +494,7 @@ async fn open_session_with_geospatial_config( async fn mount_geospatial_session(server: &MockServer, session_id: &str) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "session_id": session_id, "warehouse_id": "test_wh", @@ -611,7 +613,7 @@ async fn create_session_with_cloudfetch_enabled_omits_can_cloud_download() { // here on either branch now. let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-cf-on","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_statement_canceller_reexecute.rs b/tests/v0_statement_canceller_reexecute.rs index 9f6404e3..be0b54d6 100644 --- a/tests/v0_statement_canceller_reexecute.rs +++ b/tests/v0_statement_canceller_reexecute.rs @@ -58,7 +58,7 @@ async fn open_session(server: &MockServer) -> Session { async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) - .and(path("/api/2.0/warehouses/test_wh/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), From 8f8400b667e68b4928d39d60c24de1f98d46095b Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 19 Oct 2026 20:04:22 +0000 Subject: [PATCH 3/9] fix(session): keep warehouse session parent IDs in URLs Omit duplicate parent IDs from warehouse session request bodies while preserving standard SQL payloads and session versions. Store the selected realtime session URL once and share statement URL construction. Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 1 + src/client/sea.rs | 130 +++++++++++++---------- src/session.rs | 6 +- src/types/sea.rs | 12 ++- tests/v0_async_execute_wiremock.rs | 1 - tests/v0_c_abi_result_config_wiremock.rs | 3 +- 6 files changed, 86 insertions(+), 67 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index f587f9cd..fc37c4e6 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -14,6 +14,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed - SQL sessions open through the warehouse sessions URL and use warehouse statement URLs when the create response enables real-time routing. +- Warehouse session requests carry parent IDs only in the URL. The Rust wire request structs now use `Option` for `warehouse_id`; use `Some(id)` when building a standard SQL request body. ### Updated diff --git a/src/client/sea.rs b/src/client/sea.rs index 0a16a8d5..274a95c0 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -118,7 +118,7 @@ enum StatementOutcome { #[derive(Debug)] enum SessionRoute { Standard, - Realtime(String), + Realtime { session_url: String }, } /// Mapped terminal outcome from the synchronous execution phase. @@ -249,30 +249,31 @@ impl SeaRestTransport { fn warehouse_sessions_url(&self) -> String { format!( - "{}/api/2.0/sql/warehouses/{}/sessions", - self.host.trim_end_matches('/'), + "{}/warehouses/{}/sessions", + self.base_url(), self.warehouse_id ) } - fn realtime_session_id(&self) -> Option<&str> { - match self.session_route.get() { - Some(SessionRoute::Realtime(session_id)) => Some(session_id), - _ => None, - } + fn session_route(&self) -> &SessionRoute { + self.session_route.get().unwrap_or(&SessionRoute::Standard) } fn statements_url(&self, session_attribution: SessionAttribution) -> String { - if session_attribution == SessionAttribution::Current { - if let Some(session_id) = self.realtime_session_id() { - return format!( - "{}/{}/statements", - self.warehouse_sessions_url(), - session_id - ); + match (self.session_route(), session_attribution) { + (SessionRoute::Realtime { session_url }, SessionAttribution::Current) => { + format!("{session_url}/statements") } + _ => format!("{}/statements", self.base_url()), } - format!("{}/statements", self.base_url()) + } + + fn statement_url(&self, statement_id: &str, session_attribution: SessionAttribution) -> String { + format!( + "{}/{}", + self.statements_url(session_attribution), + statement_id + ) } fn current_session_version(&self) -> Option { @@ -340,21 +341,15 @@ impl SeaRestTransport { row_offset >= 0, "row_offset must be non-negative on the SEA wire (got {row_offset})", ); + let url = format!( + "{}/result/chunks/{}", + self.statement_url(statement_id, session_attribution), + chunk_index + ); if row_offset > 0 { - format!( - "{}/{}/result/chunks/{}?row_offset={}", - self.statements_url(session_attribution), - statement_id, - chunk_index, - row_offset - ) + format!("{url}?row_offset={row_offset}") } else { - format!( - "{}/{}/result/chunks/{}", - self.statements_url(session_attribution), - statement_id, - chunk_index - ) + url } } @@ -390,11 +385,7 @@ impl SeaRestTransport { statement_id: &str, session_attribution: SessionAttribution, ) -> Result { - let url = format!( - "{}/{}", - self.statements_url(session_attribution), - statement_id - ); + let url = self.statement_url(statement_id, session_attribution); debug!("Getting statement status at {}", url); @@ -688,10 +679,17 @@ impl SeaRestTransport { } else { "INLINE" }; + let (warehouse_id, session_id) = match self.session_route() { + SessionRoute::Standard => ( + Some(self.warehouse_id.clone()), + Some(session_id.to_string()), + ), + SessionRoute::Realtime { .. } => (None, None), + }; let request_body = ExecuteStatementRequest { - warehouse_id: self.warehouse_id.clone(), + warehouse_id, statement: sql.to_string(), - session_id: Some(session_id.to_string()), + session_id, session_version: self.current_session_version(), catalog: params.catalog.clone(), schema: params.schema.clone(), @@ -1160,7 +1158,7 @@ impl Transport for SeaRestTransport { let url = self.warehouse_sessions_url(); let request_body = CreateSessionRequest { - warehouse_id: self.warehouse_id.clone(), + warehouse_id: None, catalog: catalog.map(|s| s.to_string()), schema: schema.map(|s| s.to_string()), session_confs: session_config, @@ -1200,7 +1198,9 @@ impl Transport for SeaRestTransport { )) })?; let route = if realtime { - SessionRoute::Realtime(session_response.session_id.clone()) + SessionRoute::Realtime { + session_url: format!("{}/{}", url, session_response.session_id), + } } else { SessionRoute::Standard }; @@ -1217,15 +1217,14 @@ impl Transport for SeaRestTransport { } async fn delete_session(&self, session_id: &str) -> Result<()> { - let url = if let Some(realtime_session_id) = self.realtime_session_id() { - format!("{}/{}", self.warehouse_sessions_url(), realtime_session_id) - } else { - format!( + let url = match self.session_route() { + SessionRoute::Realtime { session_url } => session_url.clone(), + SessionRoute::Standard => format!( "{}/sessions/{}?warehouse_id={}", self.base_url(), session_id, self.warehouse_id - ) + ), }; debug!("Deleting session at {}", url); @@ -1489,9 +1488,8 @@ impl Transport for SeaRestTransport { ); let row_offset = row_offset.max(0); let url = format!( - "{}/{}/result/chunks/{}?row_offset={}", - self.statements_url(session_attribution), - statement_id, + "{}/result/chunks/{}?row_offset={}", + self.statement_url(statement_id, session_attribution), chunk_index, row_offset, ); @@ -1594,9 +1592,8 @@ impl Transport for SeaRestTransport { async fn cancel_statement(&self, statement_id: &str) -> Result<()> { let url = format!( - "{}/{}/cancel", - self.statements_url(SessionAttribution::Current), - statement_id + "{}/cancel", + self.statement_url(statement_id, SessionAttribution::Current) ); debug!("Canceling statement at {}", url); @@ -1620,11 +1617,7 @@ impl Transport for SeaRestTransport { } async fn close_statement(&self, statement_id: &str) -> Result<()> { - let url = format!( - "{}/{}", - self.statements_url(SessionAttribution::Current), - statement_id - ); + let url = self.statement_url(statement_id, SessionAttribution::Current); debug!("Closing statement at {}", url); @@ -2694,12 +2687,13 @@ mod tests { #[tokio::test] async fn realtime_session_uses_warehouse_urls_for_owned_lifecycle() { - use wiremock::matchers::{method, path, query_param}; + use wiremock::matchers::{body_json, method, path, query_param}; use wiremock::{Mock, MockServer, ResponseTemplate}; let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) + .and(body_json(json!({ "execution_mode": "FAST" }))) .respond_with( ResponseTemplate::new(200) .insert_header(REALTIME_SESSION_HEADER, "true") @@ -2716,6 +2710,15 @@ mod tests { .and(path( "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements", )) + .and(body_json(json!({ + "statement": "SELECT 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" }, @@ -2833,7 +2836,7 @@ mod tests { #[tokio::test] async fn create_session_response_selects_session_statement_urls() { - use wiremock::matchers::{method, path, query_param}; + use wiremock::matchers::{body_json, method, path, query_param}; use wiremock::{Mock, MockServer, ResponseTemplate}; let cases = [(Some("TRUE"), true), (Some("false"), false), (None, false)]; @@ -2849,6 +2852,7 @@ mod tests { Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) + .and(body_json(json!({ "execution_mode": "FAST" }))) .respond_with(create_response) .expect(1) .mount(&server) @@ -2858,8 +2862,21 @@ mod tests { } else { "/api/2.0/sql/statements" }; + let mut statement_body = json!({ + "statement": "SELECT 1", + "disposition": "INLINE_OR_EXTERNAL_LINKS", + "format": "ARROW_STREAM", + "wait_timeout": "0s", + "on_wait_timeout": "CONTINUE", + "result_compression": "LZ4_FRAME", + }); + if !realtime { + statement_body["warehouse_id"] = json!("warehouse-123"); + statement_body["session_id"] = json!("session-1"); + } Mock::given(method("POST")) .and(path(statement_path)) + .and(body_json(statement_body)) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "statement_id": "statement-1", "status": { "state": "PENDING" }, @@ -2961,7 +2978,6 @@ mod tests { Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) .and(body_json(json!({ - "warehouse_id": "warehouse-123", "execution_mode": "FAST", }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ diff --git a/src/session.rs b/src/session.rs index eba86ce6..4d1e82a5 100644 --- a/src/session.rs +++ b/src/session.rs @@ -2124,7 +2124,6 @@ mod is_open_tests { Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .and(body_json(json!({ - "warehouse_id": "test_wh", "execution_mode": "FAST", }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ @@ -2551,7 +2550,7 @@ mod is_open_tests { .iter() .position(|request| { request.method.as_str() == "POST" - && request.url.path() == "/api/2.0/sql/sessions" + && request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" }) .expect("CreateSession must be sent"); assert!( @@ -2581,7 +2580,8 @@ mod is_open_tests { let create_session_requests = requests .iter() .filter(|request| { - request.method.as_str() == "POST" && request.url.path() == "/api/2.0/sql/sessions" + request.method.as_str() == "POST" + && request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" }) .count(); assert_eq!(feature_flag_requests, 1, "sessions share the flag cache"); diff --git a/src/types/sea.rs b/src/types/sea.rs index 177b987e..977a7b02 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -382,7 +382,8 @@ pub struct QueryTag { /// Request body for statement execution. #[derive(Debug, Clone, Serialize)] pub struct ExecuteStatementRequest { - pub warehouse_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub warehouse_id: Option, pub statement: String, #[serde(skip_serializing_if = "Option::is_none")] pub session_id: Option, @@ -473,7 +474,8 @@ pub struct SessionVersion { /// Request body for session creation. #[derive(Debug, Clone, Serialize)] pub struct CreateSessionRequest { - pub warehouse_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub warehouse_id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub catalog: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -556,7 +558,7 @@ mod tests { let mut confs = HashMap::new(); confs.insert("USE_CACHED_RESULT".to_string(), "false".to_string()); let req = CreateSessionRequest { - warehouse_id: "wh-1".to_string(), + warehouse_id: None, catalog: None, schema: None, session_confs: confs, @@ -585,7 +587,7 @@ mod tests { #[test] fn test_execute_statement_request_serialization() { let req = ExecuteStatementRequest { - warehouse_id: "abc123".to_string(), + warehouse_id: Some("abc123".to_string()), statement: "SELECT 1".to_string(), session_id: Some("session-1".to_string()), session_version: None, @@ -612,7 +614,7 @@ mod tests { #[test] fn test_execute_statement_request_serializes_query_tags_as_array() { let req = ExecuteStatementRequest { - warehouse_id: "abc123".to_string(), + warehouse_id: Some("abc123".to_string()), statement: "SELECT 1".to_string(), session_id: Some("session-1".to_string()), session_version: None, diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index b7618730..582e7775 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -377,7 +377,6 @@ async fn owning_async_status_advances_session_version_for_next_execute() { Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .and(body_json(json!({ - "warehouse_id": "test_wh", "execution_mode": "FAST", }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index 3c4b1515..76fefb7c 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -207,7 +207,8 @@ fn recorded_create_session_geospatial_conf(enabled: bool) -> Option { let create = recorded .iter() .find(|request| { - request.url.path() == "/api/2.0/sql/sessions" && request.method.as_str() == "POST" + request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" + && request.method.as_str() == "POST" }) .expect("a POST /sessions request was made"); let body: serde_json::Value = From 5fd3fd09874324804782670cd5e8d715d98bed76 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 19 Oct 2026 23:00:01 +0000 Subject: [PATCH 4/9] refactor(session): centralize SQL URL routing Use the prefix selected by CreateSession for all SQL RPCs, including same-session attached reads. Restore the existing transport and reader interfaces, retain session-version attribution, and cover attached inline continuations under both URL families. Signed-off-by: Aakash Saravanan --- src/client/sea.rs | 155 +++++++++++--------------- src/client/transport.rs | 2 - src/reader/cloudfetch/link_fetcher.rs | 94 ++-------------- src/reader/inline/streaming.rs | 19 +++- src/reader/mod.rs | 136 +++++++--------------- src/session.rs | 10 +- tests/v0_async_execute_wiremock.rs | 86 ++++++++++++++ 7 files changed, 219 insertions(+), 283 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 274a95c0..df77a06d 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -244,13 +244,18 @@ impl SeaRestTransport { } fn base_url(&self) -> String { - format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) + match self.session_route() { + SessionRoute::Realtime { session_url } => session_url.clone(), + SessionRoute::Standard => { + format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) + } + } } fn warehouse_sessions_url(&self) -> String { format!( - "{}/warehouses/{}/sessions", - self.base_url(), + "{}/api/2.0/sql/warehouses/{}/sessions", + self.host.trim_end_matches('/'), self.warehouse_id ) } @@ -259,23 +264,6 @@ impl SeaRestTransport { self.session_route.get().unwrap_or(&SessionRoute::Standard) } - fn statements_url(&self, session_attribution: SessionAttribution) -> String { - match (self.session_route(), session_attribution) { - (SessionRoute::Realtime { session_url }, SessionAttribution::Current) => { - format!("{session_url}/statements") - } - _ => format!("{}/statements", self.base_url()), - } - } - - fn statement_url(&self, statement_id: &str, session_attribution: SessionAttribution) -> String { - format!( - "{}/{}", - self.statements_url(session_attribution), - statement_id - ) - } - 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 }) @@ -330,26 +318,26 @@ impl SeaRestTransport { /// when adding more. /// /// See: - fn result_chunks_url( - &self, - statement_id: &str, - chunk_index: i64, - row_offset: i64, - session_attribution: SessionAttribution, - ) -> String { + fn result_chunks_url(&self, statement_id: &str, chunk_index: i64, row_offset: i64) -> String { debug_assert!( row_offset >= 0, "row_offset must be non-negative on the SEA wire (got {row_offset})", ); - let url = format!( - "{}/result/chunks/{}", - self.statement_url(statement_id, session_attribution), - chunk_index - ); if row_offset > 0 { - format!("{url}?row_offset={row_offset}") + format!( + "{}/statements/{}/result/chunks/{}?row_offset={}", + self.base_url(), + statement_id, + chunk_index, + row_offset + ) } else { - url + format!( + "{}/statements/{}/result/chunks/{}", + self.base_url(), + statement_id, + chunk_index + ) } } @@ -385,7 +373,7 @@ impl SeaRestTransport { statement_id: &str, session_attribution: SessionAttribution, ) -> Result { - let url = self.statement_url(statement_id, session_attribution); + let url = format!("{}/statements/{}", self.base_url(), statement_id); debug!("Getting statement status at {}", url); @@ -441,8 +429,7 @@ impl SeaRestTransport { let mut response = self .get_statement_status_raw(statement_id, session_attribution) .await?; - self.enrich_num_modified_rows(&mut response, session_attribution) - .await; + self.enrich_num_modified_rows(&mut response).await; Ok(response) } @@ -458,11 +445,7 @@ 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, - session_attribution: SessionAttribution, - ) { + async fn enrich_num_modified_rows(&self, response: &mut ExecuteResponse) { if response.status.num_modified_rows.is_some() { return; } @@ -477,7 +460,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, session_attribution) + .create_reader(&response.statement_id, response) .await { Ok(r) => r, @@ -653,7 +636,7 @@ impl SeaRestTransport { request_type: RequestType, metadata_operation: Option, ) -> Result { - let url = self.statements_url(SessionAttribution::Current); + let url = format!("{}/statements", self.base_url()); // Select the result disposition per statement from the // connection-level CloudFetch setting, mirroring the reference @@ -882,11 +865,7 @@ impl SeaRestTransport { // rewrite in the same pass and can eagerly download CloudFetch chunk 0 // to extract its schema. let reader = reader_factory - .create_reader( - &response.statement_id, - &response, - SessionAttribution::Current, - ) + .create_reader(&response.statement_id, &response) .await?; // Carry the full status forward so the executed handle can skip a @@ -1024,8 +1003,7 @@ impl SeaRestTransport { // after terminal mapping, keeping this result work out of the execution // phase without shifting it onto the public result stream. if response_from_poll { - self.enrich_num_modified_rows(&mut response, SessionAttribution::Current) - .await; + self.enrich_num_modified_rows(&mut response).await; } let reader_factory = self.reader_factory()?; @@ -1345,10 +1323,7 @@ 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, SessionAttribution::Current) - .await - { + let reader = match reader_factory.create_reader(&r.statement_id, &r).await { Ok(reader) => reader, Err(e) => { self.close_orphaned_statement(&statement_id, "create_reader (direct)") @@ -1390,9 +1365,7 @@ impl Transport for SeaRestTransport { match Self::terminal_outcome(response) { StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; - let reader = reader_factory - .create_reader(&r.statement_id, &r, session_attribution) - .await?; + let reader = reader_factory.create_reader(&r.statement_id, &r).await?; let telemetry_result_format = Self::telemetry_result_format(&r); let telemetry_is_compressed = Self::telemetry_is_compressed(&r); Ok(Some(ExecuteResult { @@ -1423,10 +1396,8 @@ 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, session_attribution); + let url = self.result_chunks_url(statement_id, chunk_index, row_offset); debug!("Getting result chunks at {}", url); @@ -1470,7 +1441,6 @@ 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 @@ -1488,8 +1458,9 @@ impl Transport for SeaRestTransport { ); let row_offset = row_offset.max(0); let url = format!( - "{}/result/chunks/{}?row_offset={}", - self.statement_url(statement_id, session_attribution), + "{}/statements/{}/result/chunks/{}?row_offset={}", + self.base_url(), + statement_id, chunk_index, row_offset, ); @@ -1591,10 +1562,7 @@ impl Transport for SeaRestTransport { } async fn cancel_statement(&self, statement_id: &str) -> Result<()> { - let url = format!( - "{}/cancel", - self.statement_url(statement_id, SessionAttribution::Current) - ); + let url = format!("{}/statements/{}/cancel", self.base_url(), statement_id); debug!("Canceling statement at {}", url); @@ -1617,7 +1585,7 @@ impl Transport for SeaRestTransport { } async fn close_statement(&self, statement_id: &str) -> Result<()> { - let url = self.statement_url(statement_id, SessionAttribution::Current); + let url = format!("{}/statements/{}", self.base_url(), statement_id); debug!("Closing statement at {}", url); @@ -2614,7 +2582,7 @@ mod tests { // CloudFetch path: row_offset=0 is the kernel default and must // produce the legacy URL shape (no `?row_offset=...`). assert_eq!( - client.result_chunks_url("01abc", 7, 0, SessionAttribution::Current), + client.result_chunks_url("01abc", 7, 0), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/7" ); } @@ -2635,7 +2603,7 @@ mod tests { // the right rowOffset. let client = create_test_client(); assert_eq!( - client.result_chunks_url("01abc", 3, 12345, SessionAttribution::Current), + client.result_chunks_url("01abc", 3, 12345), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/3?row_offset=12345" ); } @@ -2647,7 +2615,7 @@ mod tests { // would still match `12345` and `i64::MAX`) is caught. let client = create_test_client(); assert_eq!( - client.result_chunks_url("01abc", 3, 1, SessionAttribution::Current), + client.result_chunks_url("01abc", 3, 1), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/3?row_offset=1" ); } @@ -2660,7 +2628,7 @@ mod tests { // offsets at request-time. The URL builder must not panic // or truncate for the legal range. let client = create_test_client(); - let url = client.result_chunks_url("01abc", 0, i64::MAX, SessionAttribution::Current); + let url = client.result_chunks_url("01abc", 0, i64::MAX); assert!( url.ends_with(&format!("?row_offset={}", i64::MAX)), "i64::MAX must serialise as decimal: got {url}", @@ -2798,11 +2766,11 @@ mod tests { .await .expect("owned status must succeed"); transport - .get_result_chunks("statement-1", 0, 0, SessionAttribution::Current) + .get_result_chunks("statement-1", 0, 0) .await .expect("owned chunk fetch must succeed"); transport - .get_inline_chunk("inline-statement", 1, 3, SessionAttribution::Current) + .get_inline_chunk("inline-statement", 1, 3) .await .expect("owned inline chunk fetch must succeed"); transport @@ -2925,7 +2893,7 @@ mod tests { } #[tokio::test] - async fn detached_statement_requests_use_standard_urls() { + async fn attached_statement_reads_use_session_prefix_without_advancing_session_version() { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -2935,16 +2903,24 @@ mod tests { .respond_with( ResponseTemplate::new(200) .insert_header(REALTIME_SESSION_HEADER, "true") - .set_body_json(json!({ "session_id": "session-1" })), + .set_body_json(json!({ + "session_id": "session-1", + "session_version": { "version_id": 7 }, + })), ) .expect(1) .mount(&server) .await; Mock::given(method("GET")) - .and(path("/api/2.0/sql/statements/detached")) + .and(path( + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/attached", + )) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "statement_id": "detached", - "status": { "state": "RUNNING" }, + "statement_id": "attached", + "status": { + "state": "RUNNING", + "session_version": { "version_id": 11 }, + }, }))) .expect(1) .mount(&server) @@ -2956,16 +2932,15 @@ mod tests { .await .expect("session creation must succeed"); transport - .get_statement_status("detached", SessionAttribution::Detached) + .get_statement_status("attached", SessionAttribution::Detached) .await - .expect("detached status must succeed"); + .expect("attached status must succeed"); - let requests = server.received_requests().await.unwrap(); - let detached = requests - .iter() - .find(|request| request.url.path() == "/api/2.0/sql/statements/detached") - .expect("detached status request must be recorded"); - assert!(detached.headers.get(REALTIME_SESSION_HEADER).is_none()); + assert_eq!( + transport.current_session_version(), + Some(SessionVersion { version_id: 7 }) + ); + server.verify().await; } #[tokio::test] @@ -3198,7 +3173,7 @@ mod tests { let transport = create_test_client_against(&server.uri()); let _ = transport - .get_result_chunks("01abc", 3, 100, SessionAttribution::Current) + .get_result_chunks("01abc", 3, 100) .await .expect("get_result_chunks must succeed against the mock"); @@ -3236,7 +3211,7 @@ mod tests { let transport = create_test_client_against(&server.uri()); let _ = transport - .get_result_chunks("01abc", 3, 0, SessionAttribution::Current) + .get_result_chunks("01abc", 3, 0) .await .expect("get_result_chunks must succeed against the mock"); diff --git a/src/client/transport.rs b/src/client/transport.rs index b8e3ba30..4415f78d 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -398,7 +398,6 @@ 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 @@ -420,7 +419,6 @@ 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/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 81b9cfc9..2ee9314a 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, SessionAttribution, Transport}; +use crate::client::{ChunkLinkFetchResult, Transport}; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, error}; use crate::types::cloudfetch::CloudFetchLink; @@ -157,7 +157,6 @@ 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 @@ -359,7 +358,6 @@ 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, @@ -367,26 +365,6 @@ 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(); @@ -455,7 +433,6 @@ 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), @@ -770,12 +747,7 @@ impl SeaChunkLinkFetcher { match self .client - .get_result_chunks( - &self.statement_id, - server_fetch_idx, - row_offset, - self.session_attribution, - ) + .get_result_chunks(&self.statement_id, server_fetch_idx, row_offset) .await { Ok(result) => { @@ -968,12 +940,7 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { ); let result = fetcher .client - .get_result_chunks( - &fetcher.statement_id, - start_chunk_index, - start_row_offset, - fetcher.session_attribution, - ) + .get_result_chunks(&fetcher.statement_id, start_chunk_index, start_row_offset) .await?; // Cache the new links. @@ -1036,12 +1003,7 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { let result = self .inner .client - .get_result_chunks( - &self.inner.statement_id, - chunk_index, - 0, - self.inner.session_attribution, - ) + .get_result_chunks(&self.inner.statement_id, chunk_index, 0) .await?; let link = result @@ -1066,12 +1028,7 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { let result = self .inner .client - .get_result_chunks( - &self.inner.statement_id, - chunk_index, - row_offset, - self.inner.session_attribution, - ) + .get_result_chunks(&self.inner.statement_id, chunk_index, row_offset) .await?; // The SEA contract today caps the number of links in a @@ -1143,25 +1100,17 @@ mod tests { use crate::types::sea::{ExecuteParams, StatementState, StatementStatus}; use arrow_schema::Schema; use std::collections::HashMap; - use std::sync::{Arc as StdArc, Mutex as StdMutex}; + use std::sync::Arc as StdArc; /// Mock Transport for testing #[derive(Debug)] struct MockDatabricksClient { chunks: Vec>, - session_attributions: StdMutex>, } impl MockDatabricksClient { fn new(chunks: Vec>) -> Self { - Self { - chunks, - session_attributions: StdMutex::new(Vec::new()), - } - } - - fn session_attributions(&self) -> Vec { - self.session_attributions.lock().unwrap().clone() + Self { chunks } } } @@ -1246,12 +1195,7 @@ 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()); @@ -1278,7 +1222,6 @@ mod tests { _statement_id: &str, _chunk_index: i64, _row_offset: i64, - _session_attribution: SessionAttribution, ) -> Result { unimplemented!("get_inline_chunk not used by the link-fetcher mock") } @@ -1545,29 +1488,6 @@ 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 f70a7785..0ae25e2e 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; +use crate::client::{InlineChunkFetchResult, Transport}; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, error}; use crate::reader::cloudfetch::parse_arrow_ipc; @@ -78,7 +78,10 @@ use tracing::instrument; /// Narrow source trait for inline-chunk fetches. /// -/// Keeps reader tests independent of the full transport interface. +/// Lets the streaming provider depend on just the one method it +/// needs (so tests don't have to build a full `Transport` mock with +/// `unreachable!()` for the 20-odd metadata RPCs). Production code +/// uses the blanket impl on `Arc`. #[async_trait] pub(crate) trait InlineChunkSource: Send + Sync + std::fmt::Debug { async fn get_inline_chunk( @@ -89,6 +92,18 @@ 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 5c1f97c8..3ee1e7c4 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -25,15 +25,13 @@ pub mod post_processor; #[cfg(test)] pub(crate) mod test_utils; -use crate::client::{ - DatabricksHttpClient, ExecuteResponse, InlineChunkFetchResult, SessionAttribution, Transport, -}; +use crate::client::{DatabricksHttpClient, ExecuteResponse, Transport}; use crate::config::GeospatialResultRepresentation; 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, InlineChunkSource, InlineStreamingProvider}; +use crate::reader::inline::{InlineArrowProvider, InlineStreamingProvider}; use crate::reader::post_processor::{PostProcessOptions, ResultPostProcessor}; use crate::types::cloudfetch::{CloudFetchConfig, CloudFetchLink}; use crate::types::sea::{CompressionCodec, ResultManifest, StatementState}; @@ -47,31 +45,6 @@ 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. @@ -132,9 +105,8 @@ impl ResultReaderFactory { &self, statement_id: &str, response: &ExecuteResponse, - session_attribution: SessionAttribution, ) -> Result> { - let inner = self.create_inner_reader(statement_id, response, session_attribution)?; + let inner = self.create_inner_reader(statement_id, response)?; Ok(Box::new( ResultPostProcessor::new( inner, @@ -153,7 +125,6 @@ impl ResultReaderFactory { &self, statement_id: &str, response: &ExecuteResponse, - session_attribution: SessionAttribution, ) -> Result> { // Log manifest info for debugging if let Some(ref manifest) = response.manifest { @@ -245,7 +216,6 @@ impl ResultReaderFactory { external_links, total_chunk_count, compression, - session_attribution, ); } } @@ -360,7 +330,6 @@ impl ResultReaderFactory { Some(next_idx), compression, manifest_schema, - session_attribution, ); } @@ -548,7 +517,6 @@ impl ResultReaderFactory { external_links: &[CloudFetchLink], total_chunk_count: Option, compression: CompressionCodec, - session_attribution: SessionAttribution, ) -> Result> { crate::klog::debug!( statement_id, @@ -565,14 +533,13 @@ 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_with_attribution( + let fetcher = SeaChunkLinkFetcher::new( 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)); @@ -635,7 +602,6 @@ 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={}, \ @@ -646,10 +612,19 @@ impl ResultReaderFactory { self.config.inline_max_chunks_in_memory, ); - let source: Arc = Arc::new(AttributedInlineChunkSource { - client: self.client.clone(), - session_attribution, - }); + // 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 provider = InlineStreamingProvider::new( source, statement_id.to_string(), @@ -1924,12 +1899,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; - #[derive(Debug, Default)] - struct PanickingTransport { - inline_chunk_attributions: 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; #[async_trait] impl Transport for PanickingTransport { @@ -1983,13 +1958,7 @@ mod tests { ) -> Result { unreachable!() } - async fn get_result_chunks( - &self, - _: &str, - _: i64, - _: i64, - _: SessionAttribution, - ) -> Result { + async fn get_result_chunks(&self, _: &str, _: i64, _: i64) -> Result { unreachable!() } async fn get_inline_chunk( @@ -1997,13 +1966,8 @@ mod tests { _: &str, _: i64, _: i64, - session_attribution: SessionAttribution, ) -> Result { - self.inline_chunk_attributions - .lock() - .unwrap() - .push(session_attribution); - Err(Error::invalid_state().message("recorded inline chunk attribution")) + unreachable!() } fn poll_config(&self) -> TransportConfig { TransportConfig::default() @@ -2108,7 +2072,7 @@ mod tests { ); let runtime = tokio::runtime::Handle::current(); ResultReaderFactory::new( - Arc::new(PanickingTransport::default()), + Arc::new(PanickingTransport), http_client, CloudFetchConfig::default(), PostProcessOptions::default(), @@ -2117,21 +2081,6 @@ 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, @@ -2188,11 +2137,10 @@ mod tests { }), }; - let err = - match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { - Ok(_) => panic!("rollout-skew must surface as Err"), - Err(e) => e, - }; + let err = match factory.create_inner_reader("stmt-1", &response) { + Ok(_) => panic!("rollout-skew must surface as Err"), + Err(e) => e, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.contains("total_chunk_count"), @@ -2230,7 +2178,7 @@ mod tests { }), }; - match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { + match factory.create_inner_reader("stmt-1", &response) { // OK or any non-rollout-guard error is acceptable — // we're proving the guard is *not* the failure mode. Ok(_) => {} @@ -2266,11 +2214,10 @@ mod tests { }), }; - 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, - }; + 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, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.to_lowercase().contains("row_count"), @@ -2297,11 +2244,10 @@ mod tests { }), }; - 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, - }; + 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, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.to_lowercase().contains("chunk_index"), @@ -2345,7 +2291,7 @@ mod tests { }; let mut reader = factory - .create_inner_reader("stmt-1", &response, SessionAttribution::Current) + .create_inner_reader("stmt-1", &response) .expect("zero-chunk manifest must succeed without parsing inline bytes"); assert!( reader.next_batch().await.unwrap().is_none(), @@ -2370,7 +2316,7 @@ mod tests { }; let mut reader = factory - .create_inner_reader("stmt-1", &response, SessionAttribution::Current) + .create_inner_reader("stmt-1", &response) .expect("absent total_chunk_count + Succeeded state must yield empty reader"); assert!(reader.next_batch().await.unwrap().is_none()); } @@ -2405,7 +2351,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, SessionAttribution::Current) + .create_inner_reader("stmt-1", &response) .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 4d1e82a5..018ed317 100644 --- a/src/session.rs +++ b/src/session.rs @@ -675,13 +675,9 @@ impl Session { /// /// This is the resume path: a caller (or a different process) that /// holds only the statement id can re-attach and drive it to - /// completion, fetch its result, or read its terminal state. Server - /// statement state is keyed solely by the id — every - /// `GetStatementStatus` / `GetStatementResult` / cancel / close RPC - /// takes just the id — so the only thing the originating handle - /// carried that a bare id does not is *this session's* transport - /// (auth, retry, poll cadence). Binding the id to this session is - /// exactly what `attach` does. + /// completion, fetch its result, or read its terminal state. + /// Realtime sessions require a statement from this session because their + /// URLs include its session ID. /// /// Issues a single `GetStatementStatus` to seed the handle's initial /// status (mirrors how `submit` seeds it from the submit response), diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 582e7775..5ae1b344 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -1397,6 +1397,92 @@ async fn attach_seeds_status_and_reports_server_state() { assert!(matches!(status, StatementStatus::Running), "{status:?}"); } +#[tokio::test] +async fn attached_statement_inline_continuations_use_the_sessions_selected_prefix() { + use wiremock::matchers::query_param; + + for realtime in [true, false] { + let server = MockServer::start().await; + let mut create_response = + ResponseTemplate::new(200).set_body_json(json!({ "session_id": "sess-test" })); + if realtime { + create_response = create_response.insert_header("x-databricks-rt-session", "true"); + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with(create_response) + .expect(1) + .mount(&server) + .await; + + let prefix = if realtime { + "/api/2.0/sql/warehouses/test_wh/sessions/sess-test" + } else { + "/api/2.0/sql" + }; + let first_batch = int64_batch("n", vec![1, 2]); + let last_batch = int64_batch("n", vec![3, 4]); + let mut status: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-attach", &first_batch)).unwrap(); + status["manifest"]["total_chunk_count"] = json!(2); + status["manifest"]["total_row_count"] = json!(4); + status["result"]["next_chunk_index"] = json!(1); + Mock::given(method("GET")) + .and(path(format!("{prefix}/statements/stmt-attach"))) + .respond_with(ResponseTemplate::new(200).set_body_json(status)) + .expect(2) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!( + "{prefix}/statements/stmt-attach/result/chunks/1" + ))) + .and(query_param("row_offset", "2")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "chunk_index": 1, + "row_offset": 2, + "row_count": 2, + "attachment": STANDARD.encode(arrow_ipc_bytes(&last_batch)), + }))) + .expect(1) + .mount(&server) + .await; + let close_path = if realtime { + prefix.to_string() + } else { + format!("{prefix}/sessions/sess-test") + }; + Mock::given(method("DELETE")) + .and(path(close_path)) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let attached = session + .attach_async_statement("stmt-attach") + .await + .expect("attach"); + let mut stream = attached.fetch_result().await.expect("fetch_result"); + let batches = drain(&mut stream).await; + let values: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(values, vec![1, 2, 3, 4]); + session.close().await.expect("session close"); + server.verify().await; + } +} + #[tokio::test] async fn attach_reports_closed_for_a_closed_statement() { // The connector relies on this: a closed async command must report From 227c024fe731b119e8b877f443275d2d0949247c Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 20 Oct 2026 04:36:12 +0000 Subject: [PATCH 5/9] refactor(session): close the transport's own session Signed-off-by: Aakash Saravanan --- src/client/sea.rs | 54 ++++++++++++++------------- src/client/transport.rs | 4 +- src/reader/cloudfetch/link_fetcher.rs | 2 +- src/reader/mod.rs | 2 +- src/session.rs | 10 +---- 5 files changed, 34 insertions(+), 38 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index df77a06d..bffefa21 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -117,7 +117,7 @@ enum StatementOutcome { #[derive(Debug)] enum SessionRoute { - Standard, + Standard { session_url: String }, Realtime { session_url: String }, } @@ -244,9 +244,9 @@ impl SeaRestTransport { } fn base_url(&self) -> String { - match self.session_route() { - SessionRoute::Realtime { session_url } => session_url.clone(), - SessionRoute::Standard => { + match self.session_route.get() { + Some(SessionRoute::Realtime { session_url }) => session_url.clone(), + Some(SessionRoute::Standard { .. }) | None => { format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) } } @@ -260,10 +260,6 @@ impl SeaRestTransport { ) } - fn session_route(&self) -> &SessionRoute { - self.session_route.get().unwrap_or(&SessionRoute::Standard) - } - 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 }) @@ -662,12 +658,12 @@ impl SeaRestTransport { } else { "INLINE" }; - let (warehouse_id, session_id) = match self.session_route() { - SessionRoute::Standard => ( + let (warehouse_id, session_id) = match self.session_route.get() { + Some(SessionRoute::Standard { .. }) | None => ( Some(self.warehouse_id.clone()), Some(session_id.to_string()), ), - SessionRoute::Realtime { .. } => (None, None), + Some(SessionRoute::Realtime { .. }) => (None, None), }; let request_body = ExecuteStatementRequest { warehouse_id, @@ -1180,7 +1176,14 @@ impl Transport for SeaRestTransport { session_url: format!("{}/{}", url, session_response.session_id), } } else { - SessionRoute::Standard + SessionRoute::Standard { + session_url: format!( + "{}/sessions/{}?warehouse_id={}", + self.base_url(), + session_response.session_id, + self.warehouse_id + ), + } }; self.session_route.set(route).map_err(|_| { Error::invalid_state().message("SQL transport already created a session") @@ -1194,15 +1197,14 @@ impl Transport for SeaRestTransport { }) } - async fn delete_session(&self, session_id: &str) -> Result<()> { - let url = match self.session_route() { - SessionRoute::Realtime { session_url } => session_url.clone(), - SessionRoute::Standard => format!( - "{}/sessions/{}?warehouse_id={}", - self.base_url(), - session_id, - self.warehouse_id - ), + async fn delete_session(&self) -> Result<()> { + let route = self.session_route.get().ok_or_else(|| { + Error::invalid_state().message("SQL transport has not created a session") + })?; + let url = match route { + SessionRoute::Standard { session_url } | SessionRoute::Realtime { session_url } => { + session_url + } }; debug!("Deleting session at {}", url); @@ -1210,7 +1212,7 @@ impl Transport for SeaRestTransport { let request = self .http_client .inner() - .request(Method::DELETE, &url) + .request(Method::DELETE, url.as_str()) .build() .map_err(|e| { Error::invalid_argument().message(format!("Failed to build request: {e}")) @@ -1229,12 +1231,12 @@ impl Transport for SeaRestTransport { .await { crate::klog::warn!( - session_id = %session_id, + session_url = %url, error = %e, "delete_session failed after HTTP retries; server-side session will be reclaimed by idle timeout" ); } else { - debug!("Deleted session: {}", session_id); + debug!("Deleted session at {}", url); } Ok(()) @@ -2782,7 +2784,7 @@ mod tests { .await .expect("statement close must succeed"); transport - .delete_session(&session.session_id) + .delete_session() .await .expect("session close must succeed"); @@ -2877,7 +2879,7 @@ mod tests { .await .expect("execute must succeed"); transport - .delete_session(&session.session_id) + .delete_session() .await .expect("session close must succeed"); diff --git a/src/client/transport.rs b/src/client/transport.rs index 4415f78d..ea65216c 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -298,8 +298,8 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { session_config: HashMap, ) -> Result; - /// Delete/close a session. - async fn delete_session(&self, session_id: &str) -> Result<()>; + /// Close the session created by this transport. + async fn delete_session(&self) -> Result<()>; // --- Statement Execution --- diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 2ee9314a..31bf3eb8 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1127,7 +1127,7 @@ mod tests { }) } - async fn delete_session(&self, _session_id: &str) -> Result<()> { + async fn delete_session(&self) -> Result<()> { Ok(()) } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 3ee1e7c4..6f7c1f51 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1916,7 +1916,7 @@ mod tests { ) -> Result { unreachable!("PanickingTransport: not used by these tests") } - async fn delete_session(&self, _: &str) -> Result<()> { + async fn delete_session(&self) -> Result<()> { unreachable!() } async fn execute_statement( diff --git a/src/session.rs b/src/session.rs index 018ed317..c6a8d8e6 100644 --- a/src/session.rs +++ b/src/session.rs @@ -239,9 +239,8 @@ impl SessionInner { return; // already closed / closing } let transport = Arc::clone(&self.transport); - let session_id = self.session_id.clone(); self.runtime_handle.spawn(async move { - let _ = transport.delete_session(&session_id).await; + let _ = transport.delete_session().await; }); } } @@ -786,12 +785,7 @@ impl Session { async { let telemetry = self.inner.telemetry.connection(); let delete_started = Instant::now(); - if let Err(error) = self - .inner - .transport - .delete_session(&self.inner.session_id) - .await - { + if let Err(error) = self.inner.transport.delete_session().await { telemetry.emit_operation( OperationType::DeleteSession, delete_started.elapsed(), From 1bf5b12b82af2c16d0e7972c7ad2059ad13f40fb Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 23 Oct 2026 21:28:18 +0000 Subject: [PATCH 6/9] fix(session): use standard URLs for detached reads Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 2 +- src/client/sea.rs | 127 +++++++++++++++++------- src/client/transport.rs | 2 + src/reader/cloudfetch/link_fetcher.rs | 57 ++++++++++- src/reader/inline/streaming.rs | 17 +--- src/reader/mod.rs | 98 +++++++++++++------ src/session.rs | 4 +- tests/v0_async_execute_wiremock.rs | 134 ++++++++++++++++++++++++-- 8 files changed, 343 insertions(+), 98 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index fc37c4e6..78db0f2e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -13,7 +13,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed -- SQL sessions open through the warehouse sessions URL and use warehouse statement URLs when the create response enables real-time routing. +- SQL sessions open through the warehouse sessions URL and use warehouse statement URLs for owned statements when the create response enables real-time routing. Detached statement reads use standard SQL URLs. - Warehouse session requests carry parent IDs only in the URL. The Rust wire request structs now use `Option` for `warehouse_id`; use `Some(id)` when building a standard SQL request body. ### Updated diff --git a/src/client/sea.rs b/src/client/sea.rs index bffefa21..b96d2de9 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -260,6 +260,15 @@ impl SeaRestTransport { ) } + fn statement_read_base_url(&self, session_attribution: SessionAttribution) -> String { + match session_attribution { + SessionAttribution::Current => self.base_url(), + SessionAttribution::Detached => { + 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 }) @@ -314,7 +323,13 @@ impl SeaRestTransport { /// when adding more. /// /// See: - fn result_chunks_url(&self, statement_id: &str, chunk_index: i64, row_offset: i64) -> String { + fn result_chunks_url( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + session_attribution: SessionAttribution, + ) -> String { debug_assert!( row_offset >= 0, "row_offset must be non-negative on the SEA wire (got {row_offset})", @@ -322,7 +337,7 @@ impl SeaRestTransport { if row_offset > 0 { format!( "{}/statements/{}/result/chunks/{}?row_offset={}", - self.base_url(), + self.statement_read_base_url(session_attribution), statement_id, chunk_index, row_offset @@ -330,7 +345,7 @@ impl SeaRestTransport { } else { format!( "{}/statements/{}/result/chunks/{}", - self.base_url(), + self.statement_read_base_url(session_attribution), statement_id, chunk_index ) @@ -369,7 +384,11 @@ impl SeaRestTransport { statement_id: &str, session_attribution: SessionAttribution, ) -> Result { - let url = format!("{}/statements/{}", self.base_url(), statement_id); + let url = format!( + "{}/statements/{}", + self.statement_read_base_url(session_attribution), + statement_id + ); debug!("Getting statement status at {}", url); @@ -425,7 +444,8 @@ impl SeaRestTransport { let mut response = self .get_statement_status_raw(statement_id, session_attribution) .await?; - self.enrich_num_modified_rows(&mut response).await; + self.enrich_num_modified_rows(&mut response, session_attribution) + .await; Ok(response) } @@ -441,7 +461,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; } @@ -456,7 +480,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, @@ -861,7 +885,11 @@ impl SeaRestTransport { // rewrite in the same pass and can eagerly download CloudFetch chunk 0 // to extract its schema. let reader = reader_factory - .create_reader(&response.statement_id, &response) + .create_reader( + &response.statement_id, + &response, + SessionAttribution::Current, + ) .await?; // Carry the full status forward so the executed handle can skip a @@ -999,7 +1027,8 @@ impl SeaRestTransport { // after terminal mapping, keeping this result work out of the execution // phase without shifting it onto the public result stream. if response_from_poll { - self.enrich_num_modified_rows(&mut response).await; + self.enrich_num_modified_rows(&mut response, SessionAttribution::Current) + .await; } let reader_factory = self.reader_factory()?; @@ -1325,7 +1354,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)") @@ -1367,7 +1399,9 @@ impl Transport for SeaRestTransport { 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 { @@ -1398,8 +1432,10 @@ 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); + let url = + self.result_chunks_url(statement_id, chunk_index, row_offset, session_attribution); debug!("Getting result chunks at {}", url); @@ -1443,6 +1479,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 @@ -1461,7 +1498,7 @@ impl Transport for SeaRestTransport { let row_offset = row_offset.max(0); let url = format!( "{}/statements/{}/result/chunks/{}?row_offset={}", - self.base_url(), + self.statement_read_base_url(session_attribution), statement_id, chunk_index, row_offset, @@ -2584,7 +2621,7 @@ mod tests { // CloudFetch path: row_offset=0 is the kernel default and must // produce the legacy URL shape (no `?row_offset=...`). assert_eq!( - client.result_chunks_url("01abc", 7, 0), + client.result_chunks_url("01abc", 7, 0, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/7" ); } @@ -2605,7 +2642,7 @@ mod tests { // the right rowOffset. let client = create_test_client(); assert_eq!( - client.result_chunks_url("01abc", 3, 12345), + client.result_chunks_url("01abc", 3, 12345, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/3?row_offset=12345" ); } @@ -2617,7 +2654,7 @@ mod tests { // would still match `12345` and `i64::MAX`) is caught. let client = create_test_client(); assert_eq!( - client.result_chunks_url("01abc", 3, 1), + client.result_chunks_url("01abc", 3, 1, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/3?row_offset=1" ); } @@ -2630,7 +2667,7 @@ mod tests { // offsets at request-time. The URL builder must not panic // or truncate for the legal range. let client = create_test_client(); - let url = client.result_chunks_url("01abc", 0, i64::MAX); + let url = client.result_chunks_url("01abc", 0, i64::MAX, SessionAttribution::Current); assert!( url.ends_with(&format!("?row_offset={}", i64::MAX)), "i64::MAX must serialise as decimal: got {url}", @@ -2768,11 +2805,11 @@ mod tests { .await .expect("owned status must succeed"); transport - .get_result_chunks("statement-1", 0, 0) + .get_result_chunks("statement-1", 0, 0, SessionAttribution::Current) .await .expect("owned chunk fetch must succeed"); transport - .get_inline_chunk("inline-statement", 1, 3) + .get_inline_chunk("inline-statement", 1, 3, SessionAttribution::Current) .await .expect("owned inline chunk fetch must succeed"); transport @@ -2895,8 +2932,8 @@ mod tests { } #[tokio::test] - async fn attached_statement_reads_use_session_prefix_without_advancing_session_version() { - use wiremock::matchers::{method, path}; + async fn attached_dml_reads_use_standard_urls_without_advancing_session_version() { + use wiremock::matchers::{method, path, query_param}; use wiremock::{Mock, MockServer, ResponseTemplate}; let server = MockServer::start().await; @@ -2913,31 +2950,51 @@ mod tests { .expect(1) .mount(&server) .await; + + let mut response: serde_json::Value = + serde_json::from_str(&succeeded_inline_dml_body("attached", 9)).unwrap(); + let mut chunk = response["result"].clone(); + chunk["chunk_index"] = json!(1); + let schema = Schema::new(vec![Field::new( + "num_affected_rows", + DataType::Int64, + false, + )]); + let mut empty_ipc = Vec::new(); + StreamWriter::try_new(&mut empty_ipc, &schema) + .unwrap() + .finish() + .unwrap(); + response["status"]["session_version"] = json!({ "version_id": 11 }); + response["manifest"]["total_chunk_count"] = json!(2); + response["result"]["attachment"] = json!(STANDARD.encode(&empty_ipc)); + response["result"]["row_count"] = json!(0); + response["result"]["next_chunk_index"] = json!(1); Mock::given(method("GET")) - .and(path( - "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/attached", - )) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "statement_id": "attached", - "status": { - "state": "RUNNING", - "session_version": { "version_id": 11 }, - }, - }))) + .and(path("/api/2.0/sql/statements/attached")) + .respond_with(ResponseTemplate::new(200).set_body_json(response)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/attached/result/chunks/1")) + .and(query_param("row_offset", "0")) + .respond_with(ResponseTemplate::new(200).set_body_json(chunk)) .expect(1) .mount(&server) .await; - let transport = create_test_client_against(&server.uri()); + let transport = create_ready_test_client_against(&server.uri(), TransportConfig::default()); transport .create_session(None, None, HashMap::new()) .await .expect("session creation must succeed"); - transport + let status = transport .get_statement_status("attached", SessionAttribution::Detached) .await .expect("attached status must succeed"); + assert_eq!(status.status.num_modified_rows, Some(9)); assert_eq!( transport.current_session_version(), Some(SessionVersion { version_id: 7 }) @@ -3175,7 +3232,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"); @@ -3213,7 +3270,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 ea65216c..8f58cfe7 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -398,6 +398,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 @@ -419,6 +420,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/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 31bf3eb8..c0fcf8ac 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 @@ -365,6 +366,7 @@ impl SeaChunkLinkFetcher { 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 +435,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 +750,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 +948,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 +1016,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 +1046,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 @@ -1195,6 +1218,7 @@ mod tests { _statement_id: &str, chunk_index: i64, _row_offset: i64, + _session_attribution: SessionAttribution, ) -> Result { let index = chunk_index as usize; if index >= self.chunks.len() { @@ -1222,6 +1246,7 @@ mod tests { _statement_id: &str, _chunk_index: i64, _row_offset: i64, + _session_attribution: SessionAttribution, ) -> Result { unimplemented!("get_inline_chunk not used by the link-fetcher mock") } @@ -1391,6 +1416,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1427,6 +1453,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1451,6 +1478,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1477,6 +1505,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1499,6 +1528,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1535,6 +1565,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1566,6 +1597,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1601,6 +1633,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1651,6 +1684,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1679,6 +1713,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Should be marked as all fetched since we have all chunks @@ -1711,6 +1746,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert!( fetcher.all_links_fetched(), @@ -1743,6 +1779,7 @@ mod tests { None, /* link_prefetch_window = */ 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Wrap directly in the handle without triggering the prefetch // bell — `link_prefetch_window=0` keeps it idle anyway. @@ -1805,6 +1842,7 @@ mod tests { None, /* link_prefetch_window = */ 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert_eq!( fetcher.next_row_offset.load(Ordering::Acquire), @@ -1853,6 +1891,7 @@ mod tests { /* total_chunk_count = */ Some(2), 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Crucial: fetcher must NOT mark all_links_fetched at // construction even though the per-link signal would say so. @@ -1990,6 +2029,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert!( fetcher.next_server_fetch_index.load(Ordering::Acquire) >= 6, @@ -2019,6 +2059,7 @@ mod tests { None, // total_chunk_count also absent 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert!( fetcher.silent_eos_warned.load(Ordering::Acquire), @@ -2044,6 +2085,7 @@ mod tests { Some(1), // total says we're at the last chunk 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert!( !fetcher.silent_eos_warned.load(Ordering::Acquire), @@ -2065,6 +2107,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Each warn helper takes the swap-true path on first @@ -2097,6 +2140,7 @@ mod tests { Some(50), 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // 10 × 50 = 500, but floor = 10_000 wins assert_eq!(with_small_total.runaway_prefetch_ceiling(), 10_000); @@ -2108,6 +2152,7 @@ mod tests { Some(5_000), 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // 10 × 5_000 = 50_000 beats the floor assert_eq!(with_large_total.runaway_prefetch_ceiling(), 50_000); @@ -2119,6 +2164,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // No hint → hard floor only assert_eq!(without_total.runaway_prefetch_ceiling(), 10_000); @@ -2137,6 +2183,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Pre-seed the cursor to a high value (simulates a fast diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index 0ae25e2e..79a1c933 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; @@ -80,8 +80,7 @@ use tracing::instrument; /// /// Lets the streaming provider depend on just the one method it /// needs (so tests don't have to build a full `Transport` mock with -/// `unreachable!()` for the 20-odd metadata RPCs). Production code -/// uses the blanket impl on `Arc`. +/// `unreachable!()` for the 20-odd metadata RPCs). #[async_trait] pub(crate) trait InlineChunkSource: Send + Sync + std::fmt::Debug { async fn get_inline_chunk( @@ -92,18 +91,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 6f7c1f51..c9532fbf 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -25,7 +25,9 @@ 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::config::GeospatialResultRepresentation; use crate::kernel_error::{Error, Result}; use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; @@ -105,8 +107,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, @@ -125,6 +128,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 { @@ -216,6 +220,7 @@ impl ResultReaderFactory { external_links, total_chunk_count, compression, + session_attribution, ); } } @@ -330,6 +335,7 @@ impl ResultReaderFactory { Some(next_idx), compression, manifest_schema, + session_attribution, ); } @@ -517,6 +523,7 @@ impl ResultReaderFactory { external_links: &[CloudFetchLink], total_chunk_count: Option, compression: CompressionCodec, + session_attribution: SessionAttribution, ) -> Result> { crate::klog::debug!( statement_id, @@ -540,6 +547,7 @@ impl ResultReaderFactory { 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)); @@ -602,6 +610,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={}, \ @@ -612,19 +621,11 @@ 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()); + Arc::new(AttributedInlineChunkSource { + client: Arc::clone(&self.client), + session_attribution, + }); let provider = InlineStreamingProvider::new( source, statement_id.to_string(), @@ -643,6 +644,31 @@ impl ResultReaderFactory { } } +#[derive(Debug)] +struct AttributedInlineChunkSource { + client: Arc, + session_attribution: SessionAttribution, +} + +#[async_trait] +impl inline::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 + } +} + /// Trait for result readers. /// /// Readers are `Send + Sync` so a `Box` can live @@ -1958,7 +1984,13 @@ mod tests { ) -> Result { unreachable!() } - async fn get_result_chunks(&self, _: &str, _: i64, _: i64) -> Result { + async fn get_result_chunks( + &self, + _: &str, + _: i64, + _: i64, + _: SessionAttribution, + ) -> Result { unreachable!() } async fn get_inline_chunk( @@ -1966,6 +1998,7 @@ mod tests { _: &str, _: i64, _: i64, + _: SessionAttribution, ) -> Result { unreachable!() } @@ -2137,10 +2170,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"), @@ -2178,7 +2212,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(_) => {} @@ -2214,10 +2248,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"), @@ -2244,10 +2279,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"), @@ -2291,7 +2327,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(), @@ -2316,7 +2352,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()); } @@ -2351,7 +2387,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 c6a8d8e6..c3741e94 100644 --- a/src/session.rs +++ b/src/session.rs @@ -675,8 +675,8 @@ impl Session { /// This is the resume path: a caller (or a different process) that /// holds only the statement id can re-attach and drive it to /// completion, fetch its result, or read its terminal state. - /// Realtime sessions require a statement from this session because their - /// URLs include its session ID. + /// Attached reads use standard SQL URLs because the statement ID does not + /// identify its originating session. /// /// Issues a single `GetStatementStatus` to seed the handle's initial /// status (mirrors how `submit` seeds it from the submit response), diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 5ae1b344..402b8120 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -1398,7 +1398,7 @@ async fn attach_seeds_status_and_reports_server_state() { } #[tokio::test] -async fn attached_statement_inline_continuations_use_the_sessions_selected_prefix() { +async fn attached_statement_inline_reads_use_standard_urls() { use wiremock::matchers::query_param; for realtime in [true, false] { @@ -1415,7 +1415,7 @@ async fn attached_statement_inline_continuations_use_the_sessions_selected_prefi .mount(&server) .await; - let prefix = if realtime { + let session_prefix = if realtime { "/api/2.0/sql/warehouses/test_wh/sessions/sess-test" } else { "/api/2.0/sql" @@ -1428,15 +1428,13 @@ async fn attached_statement_inline_continuations_use_the_sessions_selected_prefi status["manifest"]["total_row_count"] = json!(4); status["result"]["next_chunk_index"] = json!(1); Mock::given(method("GET")) - .and(path(format!("{prefix}/statements/stmt-attach"))) + .and(path("/api/2.0/sql/statements/stmt-attach")) .respond_with(ResponseTemplate::new(200).set_body_json(status)) - .expect(2) + .expect(3) .mount(&server) .await; Mock::given(method("GET")) - .and(path(format!( - "{prefix}/statements/stmt-attach/result/chunks/1" - ))) + .and(path("/api/2.0/sql/statements/stmt-attach/result/chunks/1")) .and(query_param("row_offset", "2")) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "chunk_index": 1, @@ -1448,9 +1446,9 @@ async fn attached_statement_inline_continuations_use_the_sessions_selected_prefi .mount(&server) .await; let close_path = if realtime { - prefix.to_string() + session_prefix.to_string() } else { - format!("{prefix}/sessions/sess-test") + format!("{session_prefix}/sessions/sess-test") }; Mock::given(method("DELETE")) .and(path(close_path)) @@ -1458,12 +1456,33 @@ async fn attached_statement_inline_continuations_use_the_sessions_selected_prefi .expect(1) .mount(&server) .await; + Mock::given(method("POST")) + .and(path(format!("{session_prefix}/statements"))) + .respond_with(ResponseTemplate::new(200).set_body_string(pending_body("stmt-owned"))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("{session_prefix}/statements/stmt-owned"))) + .respond_with(ResponseTemplate::new(200).set_body_string(running_body("stmt-owned"))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path(format!("{session_prefix}/statements/stmt-owned"))) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; let session = open_session(&server).await; let attached = session .attach_async_statement("stmt-attach") .await .expect("attach"); + assert!(matches!( + attached.status().await.expect("status"), + StatementStatus::Succeeded + )); let mut stream = attached.fetch_result().await.expect("fetch_result"); let batches = drain(&mut stream).await; let values: Vec = batches @@ -1478,11 +1497,108 @@ async fn attached_statement_inline_continuations_use_the_sessions_selected_prefi }) .collect(); assert_eq!(values, vec![1, 2, 3, 4]); + let mut statement = session.statement(); + statement.spec().sql("SELECT 5"); + let owned = statement.submit().await.expect("owned submit"); + assert!(matches!( + owned.status().await.expect("owned status"), + StatementStatus::Running + )); + owned.close().await.expect("owned close"); session.close().await.expect("session close"); server.verify().await; } } +#[tokio::test] +async fn attached_cloudfetch_pagination_and_refresh_use_standard_urls() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("x-databricks-rt-session", "true") + .set_body_json(json!({ "session_id": "session-b" })), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions/session-b")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let batches = [int64_batch("n", vec![1, 2]), int64_batch("n", vec![3, 4])]; + let mut links = Vec::new(); + for (index, batch) in batches.iter().enumerate() { + let bytes = arrow_ipc_bytes(batch); + let chunk_path = format!("/cloud-fetch/chunk-{index}.arrow"); + links.push(json!({ + "external_link": format!("{}{chunk_path}", server.uri()), + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": index, + "row_offset": index * 2, + "row_count": 2, + "byte_count": bytes.len(), + "next_chunk_index": if index == 0 { Some(1) } else { None }, + })); + Mock::given(method("GET")) + .and(path(chunk_path)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!( + "/api/2.0/sql/statements/statement-a/result/chunks/{index}" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "external_links": [links[index].clone()], + }))) + .expect(1..) + .mount(&server) + .await; + } + let mut expired_link = links[0].clone(); + expired_link["external_link"] = json!(format!("{}/expired-link", server.uri())); + expired_link["expiration"] = json!("2000-01-01T00:00:00.000Z"); + let mut response: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("statement-a", &batches[0])).unwrap(); + response["manifest"]["total_chunk_count"] = json!(2); + response["manifest"]["total_row_count"] = json!(4); + response["result"] = json!({ "external_links": [expired_link] }); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/statement-a")) + .respond_with(ResponseTemplate::new(200).set_body_json(response)) + .expect(2) + .mount(&server) + .await; + + let session = open_session(&server).await; + let attached = session + .attach_async_statement("statement-a") + .await + .expect("attach"); + let mut stream = attached.fetch_result().await.expect("fetch_result"); + let fetched = drain(&mut stream).await; + let values: Vec = fetched + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(values, vec![1, 2, 3, 4]); + session.close().await.expect("session close"); + server.verify().await; +} + #[tokio::test] async fn attach_reports_closed_for_a_closed_statement() { // The connector relies on this: a closed async command must report From ebebf528bf7baef3f70ec7ca405cc0014482f9c0 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 27 Oct 2026 04:24:33 +0000 Subject: [PATCH 7/9] feat(statement): add independent async statement readers Preserve session attribution and parent invalidation in derived read-only handles without transferring cleanup or execution telemetry ownership. Expose the reader API through PyO3 and cover routing, independent reads, timeout and drop safety, error mapping, and runtime retention. Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 4 +- pyo3/NEXT_CHANGELOG.md | 2 + pyo3/src/executed_async.rs | 72 +++++++-- pyo3/src/lib.rs | 1 + pyo3/src/session.rs | 10 +- pyo3/tests/test_async.py | 128 ++++++++++++++++ pyo3/tests/test_module.py | 1 + src/client/sea.rs | 1 + src/lib.rs | 8 +- src/session.rs | 32 ++-- src/statement/executed_async.rs | 92 ++++++++++-- src/statement/mod.rs | 4 +- tests/v0_async_execute_wiremock.rs | 233 ++++++++++++++++++++++++++++- 13 files changed, 537 insertions(+), 51 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 78db0f2e..a2fe0cb9 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,9 +11,11 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- `ExecutedAsyncStatement::reader()` creates independent read-only handles that retain session routing without owning cancellation, cleanup or execution telemetry. + ### Changed -- SQL sessions open through the warehouse sessions URL and use warehouse statement URLs for owned statements when the create response enables real-time routing. Detached statement reads use standard SQL URLs. +- SQL sessions open through the warehouse sessions URL and use warehouse statement URLs for owned statements when the create response enables real-time routing. Detached statement reads use standard SQL URLs. Lakehouse Real-Time supports asynchronous execution through the original session and statement handle; cross-session polling and fetching are not supported. - Warehouse session requests carry parent IDs only in the URL. The Rust wire request structs now use `Option` for `warehouse_id`; use `Some(id)` when building a standard SQL request body. ### Updated diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..968da6ca 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,8 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `ExecutedAsyncStatement.reader()` returns an independent `AsyncStatementReader` for status and result reads with the source handle's session routing. + ### Changed ### Updated diff --git a/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs index 1189c9db..03463172 100644 --- a/pyo3/src/executed_async.rs +++ b/pyo3/src/executed_async.rs @@ -24,6 +24,7 @@ use crate::errors::to_py_err; use crate::result_stream::ResultStream; use crate::runtime::KernelRuntime; use databricks_sql_kernel::{ + AsyncStatementReader as KAsyncStatementReader, ExecutedAsyncStatement as KExecutedAsyncStatement, ExecutedStatementHandle, StatementStatus, }; use pyo3::prelude::*; @@ -58,6 +59,16 @@ impl ExecutedAsyncStatement { &self.statement_id } + /// Create an independent read-only handle retaining this statement's session routing. + /// The owning handle controls cancellation, cleanup and execution telemetry. + fn reader(&self, py: Python<'_>) -> PyResult { + let inner = alive!(self, "ExecutedAsyncStatement"); + Ok(AsyncStatementReader { + inner: inner.exec.reader().map_err(|error| to_py_err(py, error))?, + runtime: Arc::clone(&inner.runtime), + }) + } + /// Single-shot status check. Returns a tuple /// `(state: str, failure: Optional[KernelError])` where: /// @@ -78,22 +89,7 @@ impl ExecutedAsyncStatement { let inner = alive!(self, "ExecutedAsyncStatement"); let runtime = inner.runtime.clone(); let status = run_kernel!(py, runtime, inner.exec.status())?; - // String mapping lives on the kernel `StatementStatus::as_str` - // so all bindings share one taxonomy. - let state = status.as_str(); - let failure: Bound<'py, PyAny> = match &status { - StatementStatus::Failed(err) => { - // Build the KernelError instance the same way every - // other failure path does, then hand it to Python as - // a plain value (not raised). Callers read .code / - // .sql_state / .query_id directly. - let py_err = to_py_err(py, err.clone()); - py_err.value(py).clone().into_any() - } - _ => py.None().into_bound(py), - }; - let tuple = pyo3::types::PyTuple::new(py, [state.into_pyobject(py)?.into_any(), failure])?; - Ok(tuple.into_any()) + status_to_python(py, status) } /// Block until the statement reaches a terminal state, then @@ -151,3 +147,47 @@ impl ExecutedAsyncStatement { ) } } + +/// Independent status and result access without server lifecycle ownership. +#[pyclass(name = "AsyncStatementReader")] +pub(crate) struct AsyncStatementReader { + inner: KAsyncStatementReader, + runtime: Arc, +} + +#[pymethods] +impl AsyncStatementReader { + #[getter] + fn statement_id(&self) -> &str { + self.inner.statement_id() + } + + /// Read server status as `(state, failure)`. + fn status<'py>(&self, py: Python<'py>) -> PyResult> { + let status = run_kernel!(py, Arc::clone(&self.runtime), self.inner.status())?; + status_to_python(py, status) + } + + /// Poll until terminal and return a fresh result stream. Interrupted reads do not cancel. + fn await_result(&self, py: Python<'_>) -> PyResult { + let runtime = Arc::clone(&self.runtime); + let stream = run_kernel!(py, runtime, self.inner.await_result())?; + Ok(ResultStream::new(stream, runtime)) + } + + /// Return a fresh result stream; raises InvalidState if execution is not terminal. + fn fetch_result(&self, py: Python<'_>) -> PyResult { + let runtime = Arc::clone(&self.runtime); + let stream = run_kernel!(py, runtime, self.inner.fetch_result())?; + Ok(ResultStream::new(stream, runtime)) + } +} + +fn status_to_python<'py>(py: Python<'py>, status: StatementStatus) -> PyResult> { + let state = status.as_str(); + let failure = match &status { + StatementStatus::Failed(err) => to_py_err(py, err.clone()).value(py).clone().into_any(), + _ => py.None().into_bound(py), + }; + Ok(pyo3::types::PyTuple::new(py, [state.into_pyobject(py)?.into_any(), failure])?.into_any()) +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index adafe292..f42ffa85 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -84,6 +84,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_function(wrap_pyfunction!(init_logging, m)?)?; diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 291c054b..c626ee89 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -695,13 +695,9 @@ impl Session { /// Re-attach to an already-submitted server statement by its id, /// returning an `ExecutedAsyncStatement` the caller can poll - /// (`status()`), await (`await_result()`), or cancel/close — without - /// having been the handle that submitted it. - /// - /// This is the resume path the connector uses for - /// `get_query_state` / `get_async_execution_result`: server - /// statement state is keyed solely by the id, so a caller holding - /// only the id can recover a working handle bound to this session. + /// (`status()`) or await (`await_result()`) without lifecycle ownership. + /// ID-only reads use standard SQL URLs. Use `ExecutedAsyncStatement.reader()` + /// to retain the originating session's routing for independent reads. /// /// Issues one `GetStatementStatus` to seed the handle. Raises /// `KernelError` with code `NotFound` if the server doesn't diff --git a/pyo3/tests/test_async.py b/pyo3/tests/test_async.py index e793e0de..233b05ab 100644 --- a/pyo3/tests/test_async.py +++ b/pyo3/tests/test_async.py @@ -17,9 +17,15 @@ from __future__ import annotations +import base64 +import json +import threading import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import databricks_sql_kernel as k +import pyarrow as pa +import pytest from conftest import live @@ -114,3 +120,125 @@ def test_use_after_close_raises_kernel_error(session): else: raise AssertionError("expected KernelError on use-after-close") stmt.close() + + +@pytest.mark.parametrize("failed", [False, True], ids=["succeeded", "failed"]) +def test_reader_preserves_session_and_maps_errors(failed): + requests = [] + statement_path = "/api/2.0/sql/warehouses/test-wh/sessions/test-session/statements/test-statement" + response = { + "statement_id": "test-statement", + "status": { + "state": "FAILED", + "sql_state": "42P01", + "error": {"message": "invalid query", "error_code": "TABLE_OR_VIEW_NOT_FOUND"}, + }, + } + if not failed: + batch = pa.record_batch([pa.array([1, 2], type=pa.int64())], names=["n"]) + buffer = pa.BufferOutputStream() + with pa.ipc.new_stream(buffer, batch.schema) as writer: + writer.write_batch(batch) + attachment = base64.b64encode(buffer.getvalue()).decode() + response = { + "statement_id": "test-statement", + "status": {"state": "SUCCEEDED"}, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 1, + "columns": [{"name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0}], + }, + "total_chunk_count": 1, + "total_row_count": 2, + }, + "result": {"chunk_index": 0, "row_offset": 0, "row_count": 2, "attachment": attachment}, + } + + class Handler(BaseHTTPRequestHandler): + def respond(self, body, realtime=False): + requests.append((self.command, self.path)) + self.rfile.read(int(self.headers.get("Content-Length", 0))) + payload = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(payload))) + if realtime: + self.send_header("x-databricks-rt-session", "true") + self.end_headers() + self.wfile.write(payload) + + def do_POST(self): + if self.path.endswith("/sessions"): + self.respond({"session_id": "test-session"}, realtime=True) + else: + self.respond({"statement_id": "test-statement", "status": {"state": "PENDING"}}) + + def do_GET(self): + self.respond(response) + + def do_DELETE(self): + self.respond({}) + + def log_message(self, *_args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + session = None + try: + session = k.Session( + host=f"http://127.0.0.1:{server.server_port}", + http_path="/sql/1.0/warehouses/test-wh", + access_token="test-token", + telemetry_enabled=False, + ) + stmt = session.statement() + stmt.set_sql("SELECT 1") + owner = stmt.submit() + before_reader = len(requests) + reader = owner.reader() + assert len(requests) == before_reader + assert isinstance(reader, k.AsyncStatementReader) + assert reader.statement_id == owner.statement_id + assert not hasattr(reader, "cancel") + assert not hasattr(reader, "close") + state, failure = reader.status() + streams = [] + if failed: + assert state == "Failed" + assert isinstance(failure, k.KernelError) + assert failure.code == "SqlError" + assert failure.sql_state == "42P01" + for read in (reader.await_result, reader.fetch_result): + with pytest.raises(k.KernelError) as error: + read() + assert error.value.code == "SqlError" + assert error.value.sql_state == "42P01" + del read + else: + assert (state, failure) == ("Succeeded", None) + streams = [reader.await_result(), reader.fetch_result()] + assert all(isinstance(stream, k.ResultStream) for stream in streams) + expected_reads = 3 if failed else 4 + assert [path for method, path in requests if method == "GET"] == [statement_path] * expected_reads + stmt.close() + with pytest.raises(k.KernelError) as error: + owner.reader() + assert error.value.code == "InvalidStatementHandle" + owner.close() + session.close() + session = None + del owner, stmt + with pytest.raises(k.KernelError) as error: + reader.status() + assert error.value.code == "InvalidStatementHandle" + del reader + for stream in streams: + assert stream.fetch_all_arrow().to_pydict() == {"n": [1, 2]} + stream.close() + finally: + if session is not None: + session.close() + server.shutdown() + worker.join(timeout=5) diff --git a/pyo3/tests/test_module.py b/pyo3/tests/test_module.py index d059dfab..4ea65618 100644 --- a/pyo3/tests/test_module.py +++ b/pyo3/tests/test_module.py @@ -30,6 +30,7 @@ def test_exports_expected_classes(): "Statement", "ExecutedStatement", "ExecutedAsyncStatement", + "AsyncStatementReader", "Metadata", "ResultStream", "KernelError", diff --git a/src/client/sea.rs b/src/client/sea.rs index b96d2de9..2a490aac 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -1206,6 +1206,7 @@ impl Transport for SeaRestTransport { } } else { SessionRoute::Standard { + // SEA requires warehouse_id on standard session close to avoid HTTP 400. session_url: format!( "{}/sessions/{}?warehouse_id={}", self.base_url(), diff --git a/src/lib.rs b/src/lib.rs index 76c91b48..00340e94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -149,7 +149,7 @@ pub use result_stream::{OwnedBatchIter, ResultBatch, ResultStream, Row, SchemaRe pub use session::{Session, SessionBuilder}; pub use statement::executed::ExecutedStatement; pub use statement::executed_async::{ - AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus, + AsyncStatementCanceller, AsyncStatementReader, ExecutedAsyncStatement, StatementStatus, }; pub use statement::handle::ExecutedStatementHandle; pub use statement::mutable::{DirectStatement, Statement, StatementCanceller}; @@ -175,6 +175,7 @@ const _: fn() = || { assert_send_sync::(); assert_send_sync::(); assert_send_sync::(); + assert_send_sync::(); assert_send_sync::(); assert_send_sync::(); @@ -216,6 +217,11 @@ const _: fn() = || { assert_send(&exec.await_result()); assert_send(&exec.fetch_result()); }; + let _: fn(&AsyncStatementReader) = |reader| { + assert_send(&reader.status()); + assert_send(&reader.await_result()); + assert_send(&reader.fetch_result()); + }; let _: fn(Session) = |session| { assert_send(&session.close()); }; diff --git a/src/session.rs b/src/session.rs index c3741e94..72d63d64 100644 --- a/src/session.rs +++ b/src/session.rs @@ -668,9 +668,8 @@ impl Session { } /// Adopt an already-submitted server statement by its id, producing - /// an [`ExecutedAsyncStatement`] that can poll [`status`] / await - /// results / cancel — without having been the handle that submitted - /// it. + /// an [`ExecutedAsyncStatement`] that can poll [`status`] and fetch + /// results without having been the handle that submitted it. /// /// This is the resume path: a caller (or a different process) that /// holds only the statement id can re-attach and drive it to @@ -678,6 +677,12 @@ impl Session { /// Attached reads use standard SQL URLs because the statement ID does not /// identify its originating session. /// + /// Lakehouse Real-Time supports asynchronous execution through the handle + /// returned by [`Statement::submit`]. Retain that handle for polling and result + /// fetching, or derive independent readers with [`ExecutedAsyncStatement::reader`]. + /// Polling or fetching a Lakehouse Real-Time statement from another session + /// is not supported. + /// /// Issues a single `GetStatementStatus` to seed the handle's initial /// status (mirrors how `submit` seeds it from the submit response), /// so the extended-status accessors return useful values before the @@ -2884,6 +2889,17 @@ mod is_open_tests { stmt.spec().sql("SELECT 1 AS n"); let async_exec = stmt.submit().await.expect("submit succeeds"); let _ = async_exec.status().await.expect("status succeeds"); + let reader = async_exec.reader().expect("reader"); + let _ = reader.status().await.expect("reader status"); + let mut read_stream = reader.await_result().await.expect("reader result"); + while read_stream + .next_batch() + .await + .expect("reader batch") + .is_some() + {} + drop(read_stream); + drop(reader); let mut stream = async_exec.await_result().await.expect("await succeeds"); assert!(stream.next_batch().await.expect("first batch").is_some()); assert!(stream @@ -2909,12 +2925,10 @@ mod is_open_tests { statement_log["entry"]["sql_driver_log"]["sql_statement_id"], "stmt-telemetry-async" ); - assert!( - detail["n_operation_status_calls"] - .as_i64() - .unwrap_or_default() - >= 2, - "status() plus await_result() should record status polls" + assert_eq!( + detail["n_operation_status_calls"].as_i64(), + Some(2), + "only owning status and await polls contribute to execution telemetry" ); assert!( detail["operation_status_latency_millis"] diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 78afc2b1..8af08243 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -199,6 +199,7 @@ pub struct ExecutedAsyncStatement { /// server-side cancel. (`Drop` / `close()` are already inert on /// attached handles via `closed=true`.) owning: bool, + session_attribution: SessionAttribution, /// Last SEA `StatementStatus` observed by this handle (initial /// `submit_statement` response or any subsequent `status()` / /// `await_result` poll). Read by the `num_modified_rows()` / @@ -284,14 +285,6 @@ impl ExecutedAsyncStatement { error } - 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 @@ -332,6 +325,7 @@ impl ExecutedAsyncStatement { closed, // The submitting handle owns the statement lifecycle. owning: true, + session_attribution: SessionAttribution::Current, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), @@ -363,14 +357,31 @@ impl ExecutedAsyncStatement { session: Arc, statement_id: String, initial_status: crate::types::sea::StatementStatus, + ) -> Self { + Self::new_read_only( + session, + statement_id, + ValidityFlag::new(), + SessionAttribution::Detached, + initial_status, + ) + } + + fn new_read_only( + session: Arc, + statement_id: String, + valid: ValidityFlag, + session_attribution: SessionAttribution, + initial_status: crate::types::sea::StatementStatus, ) -> Self { let initial_terminal = initial_status.state.is_terminal(); Self { session, statement_id, - valid: ValidityFlag::new(), + valid, closed: Arc::new(AtomicBool::new(true)), owning: false, + session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), @@ -381,6 +392,25 @@ impl ExecutedAsyncStatement { } } + /// Create an independent [`AsyncStatementReader`] without a server request. + pub fn reader(&self) -> Result { + self.valid.check()?; + let status = self + .latest_status + .lock() + .map_err(|error| Error::internal().message(format!("Statement status lock: {error}")))? + .clone(); + Ok(AsyncStatementReader { + inner: Self::new_read_only( + Arc::clone(&self.session), + self.statement_id.clone(), + self.valid.clone(), + self.session_attribution, + status, + ), + }) + } + /// Number of rows modified by the statement (UPDATE / INSERT / /// DELETE / MERGE). Reflects the most recent SEA /// `StatementStatus` this handle has seen (initial submit @@ -521,7 +551,7 @@ impl ExecutedAsyncStatement { let poll = self .session .transport() - .statement_status(&self.statement_id, self.session_attribution()); + .statement_status(&self.statement_id, self.session_attribution); let response = match self.client_deadline { Some(deadline) if enforce_deadline => { let poll_deadline = deadline @@ -655,7 +685,7 @@ impl ExecutedAsyncStatement { let poll = self .session .transport() - .statement_status(&self.statement_id, self.session_attribution()); + .statement_status(&self.statement_id, self.session_attribution); let response = match self.client_deadline { Some(deadline) if enforce_deadline => { let poll_deadline = deadline @@ -788,7 +818,7 @@ impl ExecutedAsyncStatement { match self .session .transport() - .fetch_completed_result(&self.statement_id, self.session_attribution()) + .fetch_completed_result(&self.statement_id, self.session_attribution) .await? { Some(result) => { @@ -836,7 +866,7 @@ impl ExecutedAsyncStatement { let observed = match self .session .transport() - .statement_status(&self.statement_id, self.session_attribution()) + .statement_status(&self.statement_id, self.session_attribution) .await { Ok(r) => match r.status.state { @@ -857,6 +887,42 @@ impl ExecutedAsyncStatement { } } +/// Independent read access to an asynchronous statement, created by +/// [`ExecutedAsyncStatement::reader`]. +/// +/// Session attribution is inherited from the source handle, including unknown +/// attribution for ID-only attachments. The reader shares parent-statement +/// invalidation but has independent status and result state. It does not inherit +/// the execution deadline or emit execution telemetry. Dropping a reader never +/// cancels or closes the statement; the owner controls its server lifetime. +pub struct AsyncStatementReader { + inner: ExecutedAsyncStatement, +} + +impl AsyncStatementReader { + pub fn statement_id(&self) -> &str { + &self.inner.statement_id + } + + /// Read the current server status. See [`ExecutedAsyncStatement::status`]. + pub async fn status(&self) -> Result { + self.inner.status().await + } + + /// Poll until terminal and return a fresh result stream. + /// + /// The session's polling timeout applies to this read. Timing out or + /// dropping the future leaves the server statement running. + pub async fn await_result(&self) -> Result { + self.inner.await_result().await + } + + /// Return a fresh result stream, or `InvalidState` if execution is not terminal. + pub async fn fetch_result(&self) -> Result { + self.inner.fetch_result().await + } +} + /// RAII guard that fires a fire-and-forget `cancel_statement` on /// drop unless [`defuse`](AwaitResultCancelGuard::defuse) was called. /// diff --git a/src/statement/mod.rs b/src/statement/mod.rs index 2c20d9a9..4f2f92df 100644 --- a/src/statement/mod.rs +++ b/src/statement/mod.rs @@ -40,7 +40,9 @@ pub(crate) mod validity; // of the deeper submodule paths. The crate-root re-exports in `lib.rs` // also resolve here, so both paths work. pub use executed::ExecutedStatement; -pub use executed_async::{AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus}; +pub use executed_async::{ + AsyncStatementCanceller, AsyncStatementReader, ExecutedAsyncStatement, StatementStatus, +}; pub use handle::ExecutedStatementHandle; pub use mutable::{DirectStatement, Statement, StatementCanceller}; pub use spec::{ResultFormat, StatementSpec, TypedValue}; diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 402b8120..625cd5c7 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -641,6 +641,7 @@ async fn re_submit_invalidates_prior_async_handle() { stmt.spec().sql("SELECT 1"); let async_exec_x = stmt.submit().await.expect("submit X"); assert_eq!(async_exec_x.statement_id(), "stmt-X"); + let reader = async_exec_x.reader().expect("reader"); // Re-submit invalidates async_exec_x. let _async_exec_y = stmt.submit().await.expect("submit Y"); @@ -649,6 +650,22 @@ async fn re_submit_invalidates_prior_async_handle() { .await .expect_err("stale async handle cancel must fail"); assert_eq!(err.code, ErrorCode::InvalidStatementHandle); + assert_eq!( + reader.status().await.unwrap_err().code, + ErrorCode::InvalidStatementHandle + ); + assert_eq!( + reader.await_result().await.err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + assert_eq!( + reader.fetch_result().await.err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + assert_eq!( + async_exec_x.reader().err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); } #[tokio::test] @@ -1374,6 +1391,214 @@ async fn async_await_result_cancelled_carries_extended_status_fields_onto_error( let _ = ErrorCode::SqlError; // silence unused-import warning if the assert above changes } +#[tokio::test] +async fn async_readers_preserve_session_routes() { + use wiremock::matchers::{body_partial_json, query_param}; + + for (realtime, cloudfetch) in [(false, false), (false, true), (true, false), (true, true)] { + let server = MockServer::start().await; + let session_prefix = if realtime { + "/api/2.0/sql/warehouses/test_wh/sessions/sess-test" + } else { + "/api/2.0/sql" + }; + let mut create_response = + ResponseTemplate::new(200).set_body_json(json!({ "session_id": "sess-test" })); + if realtime { + create_response = create_response.insert_header("x-databricks-rt-session", "true"); + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with(create_response) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(format!("{session_prefix}/statements"))) + .and(body_partial_json(json!({ "wait_timeout": "0s" }))) + .respond_with(ResponseTemplate::new(200).set_body_string(pending_body("stmt-result"))) + .expect(1) + .mount(&server) + .await; + + let batches = [int64_batch("n", vec![1, 2]), int64_batch("n", vec![3, 4])]; + let mut response: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-result", &batches[0])).unwrap(); + response["manifest"]["total_chunk_count"] = json!(2); + response["manifest"]["total_row_count"] = json!(4); + response["result"]["next_chunk_index"] = json!(1); + let mut continuation = json!({ + "chunk_index": 1, + "row_offset": 2, + "row_count": 2, + "attachment": STANDARD.encode(arrow_ipc_bytes(&batches[1])), + }); + if cloudfetch { + let mut links = Vec::new(); + for (index, batch) in batches.iter().enumerate() { + let bytes = arrow_ipc_bytes(batch); + let chunk_path = format!("/cloud-fetch/chunk-{index}.arrow"); + links.push(json!({ + "external_link": format!("{}{chunk_path}", server.uri()), + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": index, + "row_offset": index * 2, + "row_count": 2, + "byte_count": bytes.len(), + "next_chunk_index": if index == 0 { Some(1) } else { None }, + })); + Mock::given(method("GET")) + .and(path(chunk_path)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(3) + .mount(&server) + .await; + } + Mock::given(method("GET")) + .and(path(format!( + "{session_prefix}/statements/stmt-result/result/chunks/0" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "external_links": [links[0].clone()], + }))) + .expect(3) + .mount(&server) + .await; + let mut expired_link = links[0].clone(); + expired_link["external_link"] = json!(format!("{}/expired-link", server.uri())); + expired_link["expiration"] = json!("2000-01-01T00:00:00.000Z"); + response["result"] = json!({ "external_links": [expired_link] }); + continuation = json!({ "external_links": [links[1].clone()] }); + } + Mock::given(method("GET")) + .and(path(format!("{session_prefix}/statements/stmt-result"))) + .respond_with(ResponseTemplate::new(200).set_body_json(&response)) + .expect(7) + .mount(&server) + .await; + let chunk_mock = Mock::given(method("GET")).and(path(format!( + "{session_prefix}/statements/stmt-result/result/chunks/1" + ))); + let chunk_mock = if cloudfetch { + chunk_mock + } else { + chunk_mock.and(query_param("row_offset", "2")) + }; + chunk_mock + .respond_with(ResponseTemplate::new(200).set_body_json(&continuation)) + .expect(1..) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path(format!("{session_prefix}/statements/stmt-result"))) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path(if realtime { + session_prefix.to_string() + } else { + format!("{session_prefix}/sessions/sess-test") + })) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT n FROM range(1, 5) AS t(n)"); + let owned = statement.submit().await.expect("owned submit"); + let owned_stream = owned.await_result().await.expect("owned result"); + let reader = owned.reader().expect("reader"); + let refetch = owned.reader().expect("refetch reader"); + assert_eq!(reader.statement_id(), owned.statement_id()); + let (reader_status, owned_status) = tokio::join!(reader.status(), owned.status()); + assert!(matches!(reader_status.unwrap(), StatementStatus::Succeeded)); + assert!(matches!(owned_status.unwrap(), StatementStatus::Succeeded)); + let (read_stream, refetch_stream) = + tokio::join!(reader.await_result(), refetch.fetch_result()); + for mut stream in [owned_stream, read_stream.unwrap(), refetch_stream.unwrap()] { + let fetched = drain(&mut stream).await; + assert_eq!(fetched.len(), 2); + let values: Vec = fetched + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(values, vec![1, 2, 3, 4]); + } + drop(reader); + drop(refetch); + owned.close().await.expect("owned close"); + session.close().await.expect("session close"); + server.verify().await; + } +} + +#[tokio::test] +async fn reader_timeout_and_drop_leave_statement_owned() { + use std::time::Duration; + + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_submit(&server, pending_body("stmt-reader")).await; + mount_status_once(&server, "stmt-reader", running_body("stmt-reader")).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-reader/cancel")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT 1"); + let owned = statement + .submit_with_timeout(Duration::from_secs(1)) + .await + .unwrap(); + let reader = owned.reader().unwrap(); + let no_close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-reader")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount_as_scoped(&server) + .await; + + tokio::time::sleep(Duration::from_secs(1)).await; + assert!(matches!( + reader.status().await.unwrap(), + StatementStatus::Running + )); + assert!( + tokio::time::timeout(Duration::from_millis(100), reader.await_result()) + .await + .is_err() + ); + drop(reader); + tokio::time::sleep(Duration::from_millis(150)).await; + drop(no_close); + + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-reader")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + owned.close().await.unwrap(); + session.close().await.unwrap(); + server.verify().await; +} + // ─── attach_async_statement (resume-by-id) ────────────────────────── #[tokio::test] @@ -1479,11 +1704,12 @@ async fn attached_statement_inline_reads_use_standard_urls() { .attach_async_statement("stmt-attach") .await .expect("attach"); + let reader = attached.reader().expect("reader"); assert!(matches!( - attached.status().await.expect("status"), + reader.status().await.expect("status"), StatementStatus::Succeeded )); - let mut stream = attached.fetch_result().await.expect("fetch_result"); + let mut stream = reader.fetch_result().await.expect("fetch_result"); let batches = drain(&mut stream).await; let values: Vec = batches .iter() @@ -1581,7 +1807,8 @@ async fn attached_cloudfetch_pagination_and_refresh_use_standard_urls() { .attach_async_statement("statement-a") .await .expect("attach"); - let mut stream = attached.fetch_result().await.expect("fetch_result"); + let reader = attached.reader().expect("reader"); + let mut stream = reader.fetch_result().await.expect("fetch_result"); let fetched = drain(&mut stream).await; let values: Vec = fetched .iter() From eff7ff5dbb51fd3c4d07ed61f94b0ec11d3adef6 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 27 Oct 2026 17:53:13 +0000 Subject: [PATCH 8/9] fix(statement): invalidate readers when their owner is released Preserve valid auto-closed results and detached reader lifetimes. Correct stale CreateSession mocks and documentation, and run binding checks for root source changes. Signed-off-by: Aakash Saravanan --- .github/workflows/napi-checks.yml | 2 + .github/workflows/pyo3-checks.yml | 2 + .../designs/cloudfetch-implementation-plan.md | 2 +- napi/src/connection.rs | 2 +- napi/src/metadata.rs | 2 +- pyo3/tests/test_async.py | 11 ++- src/statement/executed_async.rs | 57 ++++++++++--- tests/v0_async_execute_wiremock.rs | 84 ++++++++++++++++++- tests/v0_c_abi_result_config_wiremock.rs | 2 +- tests/v0_execute_wiremock.rs | 2 +- tests/v0_metadata_wiremock.rs | 2 +- tests/v0_session_wiremock.rs | 4 +- 12 files changed, 149 insertions(+), 23 deletions(-) diff --git a/.github/workflows/napi-checks.yml b/.github/workflows/napi-checks.yml index f4959728..6a31d1ff 100644 --- a/.github/workflows/napi-checks.yml +++ b/.github/workflows/napi-checks.yml @@ -32,6 +32,7 @@ on: branches: [main] paths: - "napi/**" + - "src/**" # Root Cargo.toml change can affect napi via its `path = ".."` # kernel dep, so this workflow re-runs to catch mismatches. - "Cargo.toml" @@ -40,6 +41,7 @@ on: branches: [main] paths: - "napi/**" + - "src/**" - "Cargo.toml" - ".github/workflows/napi-checks.yml" diff --git a/.github/workflows/pyo3-checks.yml b/.github/workflows/pyo3-checks.yml index 3eaef161..1dda66f7 100644 --- a/.github/workflows/pyo3-checks.yml +++ b/.github/workflows/pyo3-checks.yml @@ -22,6 +22,7 @@ on: branches: [main] paths: - "pyo3/**" + - "src/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/pyo3-checks.yml" @@ -29,6 +30,7 @@ on: branches: [main] paths: - "pyo3/**" + - "src/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/pyo3-checks.yml" diff --git a/docs/designs/cloudfetch-implementation-plan.md b/docs/designs/cloudfetch-implementation-plan.md index 415501e9..cee2a99f 100644 --- a/docs/designs/cloudfetch-implementation-plan.md +++ b/docs/designs/cloudfetch-implementation-plan.md @@ -124,7 +124,7 @@ Implements `DatabricksClient` for the Databricks SQL Statement Execution API (RE | Endpoint | Purpose | |----------|---------| -| `POST /api/2.0/sql/sessions` | Create session | +| `POST /api/2.0/sql/warehouses/{warehouse_id}/sessions` | Create session | | `DELETE /api/2.0/sql/sessions/{id}` | Delete session | | `POST /api/2.0/sql/statements` | Execute statement | | `GET /api/2.0/sql/statements/{id}` | Get status | diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 5333e1ec..7aba91ff 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -706,7 +706,7 @@ mod tests { async fn build_statement_forwards_raw_params_and_rejects_mixed_binding() { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200).set_body_json(json!({ "session_id": "sess-napi-raw" })), ) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index b4cfeef5..fc835eca 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -405,7 +405,7 @@ mod tests { async fn open_mock_connection(server: &MockServer) -> Connection { Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) .respond_with( ResponseTemplate::new(200) .set_body_json(json!({ "session_id": "sess-napi-metadata" })), diff --git a/pyo3/tests/test_async.py b/pyo3/tests/test_async.py index 233b05ab..c26cb682 100644 --- a/pyo3/tests/test_async.py +++ b/pyo3/tests/test_async.py @@ -222,11 +222,18 @@ def log_message(self, *_args): assert all(isinstance(stream, k.ResultStream) for stream in streams) expected_reads = 3 if failed else 4 assert [path for method, path in requests if method == "GET"] == [statement_path] * expected_reads - stmt.close() + owner.close() + before_release_reads = len(requests) + for read in (reader.status, reader.await_result, reader.fetch_result): + with pytest.raises(k.KernelError) as error: + read() + assert error.value.code == "InvalidStatementHandle" + del read with pytest.raises(k.KernelError) as error: owner.reader() assert error.value.code == "InvalidStatementHandle" - owner.close() + assert len(requests) == before_release_reads + stmt.close() session.close() session = None del owner, stmt diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 8af08243..cf6429c4 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -182,6 +182,8 @@ pub struct ExecutedAsyncStatement { /// short-circuited) `close()`. Tells `Drop` to skip its /// fire-and-forget cleanup. closed: Arc, + /// Server auto-close can retain results, so owner release has a separate flag. + owner_released: Arc, /// Whether this handle *owns* the server statement's lifecycle. /// /// `true` for handles produced by [`Statement::submit`] (the @@ -323,6 +325,7 @@ impl ExecutedAsyncStatement { statement_id, valid, closed, + owner_released: Arc::new(AtomicBool::new(false)), // The submitting handle owns the statement lifecycle. owning: true, session_attribution: SessionAttribution::Current, @@ -362,6 +365,7 @@ impl ExecutedAsyncStatement { session, statement_id, ValidityFlag::new(), + Arc::new(AtomicBool::new(false)), SessionAttribution::Detached, initial_status, ) @@ -371,6 +375,7 @@ impl ExecutedAsyncStatement { session: Arc, statement_id: String, valid: ValidityFlag, + owner_released: Arc, session_attribution: SessionAttribution, initial_status: crate::types::sea::StatementStatus, ) -> Self { @@ -380,6 +385,7 @@ impl ExecutedAsyncStatement { statement_id, valid, closed: Arc::new(AtomicBool::new(true)), + owner_released, owning: false, session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), @@ -395,6 +401,7 @@ impl ExecutedAsyncStatement { /// Create an independent [`AsyncStatementReader`] without a server request. pub fn reader(&self) -> Result { self.valid.check()?; + self.check_owner_available()?; let status = self .latest_status .lock() @@ -405,12 +412,30 @@ impl ExecutedAsyncStatement { Arc::clone(&self.session), self.statement_id.clone(), self.valid.clone(), + Arc::clone(&self.owner_released), self.session_attribution, status, ), }) } + fn check_owner_available(&self) -> Result<()> { + if self.owner_released.load(Ordering::Acquire) { + return Err(Error::invalid_statement_handle() + .message("the owning asynchronous statement has been closed or dropped") + .with_query_id(&self.statement_id)); + } + Ok(()) + } + + fn check_read_validity(&self) -> Result<()> { + self.valid.check()?; + if !self.owning { + self.check_owner_available()?; + } + Ok(()) + } + /// Number of rows modified by the statement (UPDATE / INSERT / /// DELETE / MERGE). Reflects the most recent SEA /// `StatementStatus` this handle has seen (initial submit @@ -530,7 +555,7 @@ impl ExecutedAsyncStatement { pub async fn status(&self) -> Result { let span = self.session.log_span().clone(); let result = async { - self.valid.check()?; + self.check_read_validity()?; // The client deadline governs only the pre-terminal window // ("initial submit through observed terminal status"). Once // this handle has observed a terminal state, `status()` @@ -569,6 +594,7 @@ impl ExecutedAsyncStatement { } _ => poll.await?, }; + self.check_read_validity()?; self.statement_telemetry .record_poll(status_started.elapsed()); // Cache the wire status so the extended-field accessors @@ -633,7 +659,7 @@ impl ExecutedAsyncStatement { pub async fn await_result(&self) -> Result { let span = self.session.log_span().clone(); let result = async { - self.valid.check()?; + self.check_read_validity()?; let cfg = self.session.transport().poll_config(); let start = std::time::Instant::now(); @@ -660,7 +686,7 @@ impl ExecutedAsyncStatement { }; loop { - self.valid.check()?; + self.check_read_validity()?; // The client deadline governs only the pre-terminal // window. Once this handle has observed a terminal state // (here or via a prior `status()` / initial-submit @@ -710,6 +736,7 @@ impl ExecutedAsyncStatement { } _ => poll.await?, }; + self.check_read_validity()?; self.statement_telemetry .record_poll(status_started.elapsed()); // Cache the wire status so the extended-field @@ -797,12 +824,7 @@ impl ExecutedAsyncStatement { /// when the caller has already confirmed completion themselves. pub async fn fetch_result(&self) -> Result { let span = self.session.log_span().clone(); - let result = async { - self.valid.check()?; - self.materialise_result().await - } - .instrument(span) - .await; + let result = self.materialise_result().instrument(span).await; if let Err(error) = &result { self.statement_telemetry.finalize(Some(error)); } @@ -815,12 +837,14 @@ impl ExecutedAsyncStatement { /// status so callers don't have to re-query, and points at the /// actionable follow-up. async fn materialise_result(&self) -> Result { - match self + self.check_read_validity()?; + let result = self .session .transport() .fetch_completed_result(&self.statement_id, self.session_attribution) - .await? - { + .await?; + self.check_read_validity()?; + match result { Some(result) => { self.statement_telemetry.on_result_metadata( result.telemetry_result_format, @@ -854,6 +878,7 @@ impl ExecutedAsyncStatement { } } } + self.check_read_validity()?; self.result_stream_owns_success_telemetry .store(true, Ordering::Release); Ok(stream) @@ -876,6 +901,7 @@ impl ExecutedAsyncStatement { }, Err(_) => "non-terminal", }; + self.check_read_validity()?; Err(Error::invalid_state().message(format!( "Statement {} is not terminal yet (status: {}); call await_result() to \ block until done, or poll status() and re-call fetch_result() once it \ @@ -895,6 +921,7 @@ impl ExecutedAsyncStatement { /// invalidation but has independent status and result state. It does not inherit /// the execution deadline or emit execution telemetry. Dropping a reader never /// cancels or closes the statement; the owner controls its server lifetime. +/// Closing or dropping the owner invalidates derived readers. pub struct AsyncStatementReader { inner: ExecutedAsyncStatement, } @@ -1025,6 +1052,9 @@ impl ExecutedAsyncStatement { } async fn close_server_statement(&self) -> Result<()> { + if self.owning { + self.owner_released.store(true, Ordering::Release); + } // Idempotent on success: a prior successful close sets // `closed=true` and subsequent calls short-circuit. // @@ -1147,6 +1177,9 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { + if self.owning { + self.owner_released.store(true, Ordering::Release); + } // Ensure submit-and-drop / status-only async statements still // emit one terminal telemetry event. Once a result stream has // been returned, that stream owns success finalization so it can diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 625cd5c7..4e516cfd 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -15,7 +15,7 @@ //! Wiremock tests for the v0 `Statement::submit` / `ExecutedAsyncStatement` //! path. //! -//! Each test stubs SEA's `POST /sessions`, `POST /statements`, and the +//! Each test stubs SEA's `CreateSession`, `POST /statements`, and the //! `GET /statements/{id}` / `POST /statements/{id}/cancel` / //! `DELETE /statements/{id}` endpoints as needed, then drives a //! `Statement::submit()` through the async pipeline: @@ -1543,6 +1543,84 @@ async fn async_readers_preserve_session_routes() { } } +#[tokio::test] +async fn owner_release_invalidates_readers() { + use std::time::Duration; + use tokio::sync::Notify; + + for close_owner in [true, false] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_submit(&server, pending_body("stmt-reader")).await; + let polled = Arc::new(Notify::new()); + let notify = Arc::clone(&polled); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-reader")) + .respond_with(move |_: &wiremock::Request| { + notify.notify_one(); + ResponseTemplate::new(200).set_body_string(running_body("stmt-reader")) + }) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-reader/cancel")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-reader")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT 1"); + let mut owner = Some(statement.submit().await.unwrap()); + let reader = owner.as_ref().unwrap().reader().unwrap(); + let release_owner = async { + polled.notified().await; + if close_owner { + let owner = owner.as_mut().unwrap(); + owner.close().await.unwrap(); + assert_eq!( + owner.reader().err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + } else { + drop(owner.take()); + } + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(reader.await_result(), release_owner) + }) + .await + .expect("reader stops polling after owner release"); + assert_eq!( + result.err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + for result in [ + reader.status().await.map(|_| ()), + reader.await_result().await.map(|_| ()), + reader.fetch_result().await.map(|_| ()), + ] { + assert_eq!(result.unwrap_err().code, ErrorCode::InvalidStatementHandle); + } + assert_eq!( + wait_for_close_delete(&server, "stmt-reader", 1, Duration::from_secs(5)).await, + 1 + ); + statement.close().await.unwrap(); + session.close().await.unwrap(); + server.verify().await; + } +} + #[tokio::test] async fn reader_timeout_and_drop_leave_statement_owned() { use std::time::Duration; @@ -1808,6 +1886,7 @@ async fn attached_cloudfetch_pagination_and_refresh_use_standard_urls() { .await .expect("attach"); let reader = attached.reader().expect("reader"); + drop(attached); let mut stream = reader.fetch_result().await.expect("fetch_result"); let fetched = drain(&mut stream).await; let values: Vec = fetched @@ -2046,6 +2125,9 @@ async fn await_result_closed_status_skips_close_statement() { .value(0), 7 ); + let reader = async_exec.reader().expect("reader after server auto-close"); + let mut refetched = reader.fetch_result().await.expect("refetch closed result"); + assert_eq!(drain(&mut refetched).await, batches); // An explicit close() on a CLOSED statement must also be a no-op. async_exec.close().await.expect("close"); // async_exec (and stmt) drop here — a redundant close guard fires now. diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index 76fefb7c..442ff88e 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -210,7 +210,7 @@ fn recorded_create_session_geospatial_conf(enabled: bool) -> Option { request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" && request.method.as_str() == "POST" }) - .expect("a POST /sessions request was made"); + .expect("a CreateSession request was made"); let body: serde_json::Value = serde_json::from_slice(&create.body).expect("create-session body must be valid JSON"); body.pointer("/session_confs/EnableGeoSpatialSupport") diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index d006aa83..e428abf3 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -14,7 +14,7 @@ //! Wiremock tests for the v0 `Statement::execute` path. //! -//! Each test stubs SEA's `POST /sessions`, `POST /statements`, and +//! Each test stubs SEA's `CreateSession`, `POST /statements`, and //! (where needed) `GET /statements/{id}`, then drives a //! `Statement::execute()` through the full pipeline: //! Session::open → Statement::execute → ExecutedStatement → diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index ff86086b..e23914ef 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -15,7 +15,7 @@ //! Wiremock end-to-end tests for the v0 `Metadata::*` surface. //! //! For each wire-driven `Metadata::*` RPC, we stub the SEA -//! `POST /sessions` and `POST /statements` endpoints, encoding a +//! `CreateSession` and `POST /statements` endpoints, encoding a //! synthesised Databricks Arrow batch as inline base64. We then drive //! the call through `Session::open` + `Metadata::*` and assert that //! the returned `ResultStream` exposes the **Thrift-compatible** diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index 7dccb80e..d04d0629 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -360,7 +360,7 @@ async fn assert_no_can_cloud_download_on_create(server: &MockServer) { r.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" && r.method.as_str() == "POST" }) - .expect("a POST /sessions request was made"); + .expect("a CreateSession request was made"); let body: serde_json::Value = serde_json::from_slice(&create.body).expect("create-session body must be valid JSON"); if let Some(obj) = body.get("session_confs").and_then(|v| v.as_object()) { @@ -387,7 +387,7 @@ async fn create_session_body(server: &MockServer) -> serde_json::Value { r.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" && r.method.as_str() == "POST" }) - .expect("a POST /sessions request was made"); + .expect("a CreateSession request was made"); serde_json::from_slice(&create.body).expect("create-session body must be valid JSON") } From b2cda261dc44a59947de0855b352e2af7f882430 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 27 Oct 2026 18:37:55 +0000 Subject: [PATCH 9/9] fix(statement): invalidate readers on owner query timeout Signed-off-by: Aakash Saravanan --- src/statement/executed_async.rs | 3 +- tests/v0_async_execute_wiremock.rs | 62 ++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index cf6429c4..59b8379e 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -278,6 +278,7 @@ impl ExecutedAsyncStatement { /// best-effort server cleanup when a deadline retained across /// caller-driven status polls expires. pub(crate) fn expire_client_query_timeout(&self) -> Error { + self.owner_released.store(true, Ordering::Release); if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { self.session .dispatch_timeout_cleanup(Some(self.statement_id.clone())); @@ -921,7 +922,7 @@ impl ExecutedAsyncStatement { /// invalidation but has independent status and result state. It does not inherit /// the execution deadline or emit execution telemetry. Dropping a reader never /// cancels or closes the statement; the owner controls its server lifetime. -/// Closing or dropping the owner invalidates derived readers. +/// Derived readers become invalid when the owner closes, drops, or starts timeout cleanup. pub struct AsyncStatementReader { inner: ExecutedAsyncStatement, } diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 4e516cfd..18d53cbd 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -1621,6 +1621,68 @@ async fn owner_release_invalidates_readers() { } } +#[tokio::test] +async fn owner_query_timeout_invalidates_readers() { + use std::time::Duration; + + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_submit(&server, pending_body("stmt-reader-timeout")).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-reader-timeout")) + .respond_with( + ResponseTemplate::new(200).set_body_string(closed_body("stmt-reader-timeout")), + ) + .expect(0) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-reader-timeout/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT 1"); + let owner = statement + .submit_with_timeout(Duration::from_secs(1)) + .await + .unwrap(); + let reader = owner.reader().unwrap(); + + tokio::time::sleep(Duration::from_secs(1)).await; + let error = owner.status().await.unwrap_err(); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert_eq!( + owner.reader().err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + for result in [ + reader.status().await.map(|_| ()), + reader.await_result().await.map(|_| ()), + reader.fetch_result().await.map(|_| ()), + ] { + assert_eq!(result.unwrap_err().code, ErrorCode::InvalidStatementHandle); + } + let error = owner.await_result().await.err().unwrap(); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert_eq!( + wait_for_close_delete(&server, "stmt-reader-timeout", 1, Duration::from_secs(5)).await, + 1 + ); + + owner.close().await.unwrap(); + statement.close().await.unwrap(); + session.close().await.unwrap(); + server.verify().await; +} + #[tokio::test] async fn reader_timeout_and_drop_leave_statement_owned() { use std::time::Duration;