From 45d15abaee43b2a25afb7f742f79d6362915d47c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 19:00:45 +0000 Subject: [PATCH] perf(statement): request INLINE results for small repeat queries on Real-Time sessions With the INLINE_OR_EXTERNAL_LINKS disposition, Lakehouse Real-Time persists every result to cloud storage, even small inline ones, and keeps its internal result stream open while it does. At a few hundred concurrent statements this stalls the warehouse and fails statements with "h2 protocol error" / "execution already exists". On Real-Time sessions, a read-only statement now requests INLINE once the same SQL text has returned a small result (<= 4 MiB) in the last 10 minutes. If the result outgrows the inline limit (BAD_REQUEST or a truncated manifest), the statement runs again once with INLINE_OR_EXTERNAL_LINKS. The client conf realtime_inline_small_results=false turns this off. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/client/sea.rs | 232 ++++++++++++++++++++++++++++++-- src/client/transport.rs | 3 + src/config.rs | 15 +++ src/session.rs | 1 + tests/v0_execute_wiremock.rs | 253 +++++++++++++++++++++++++++++++++++ 5 files changed, 491 insertions(+), 13 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index c2a0fb70..b8eaf061 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -31,8 +31,8 @@ use crate::telemetry::ExecutionResultFormat; use crate::types::cloudfetch::CloudFetchLink; use crate::types::sea::{ CompressionCodec, CreateSessionRequest, CreateSessionResponse, ExecuteParams, - ExecuteStatementRequest, GetChunksResponse, SessionExecutionMode, SessionVersion, - StatementExecutionResponse, StatementState, + ExecuteStatementRequest, GetChunksResponse, ResultManifest, SessionExecutionMode, + SessionVersion, StatementExecutionResponse, StatementState, }; use async_trait::async_trait; use reqwest::Method; @@ -96,6 +96,64 @@ impl MetadataOperation { struct ExecutionRequest { request_type: RequestType, metadata_operation: Option, + /// Request `INLINE` instead of `INLINE_OR_EXTERNAL_LINKS`. + inline: bool, +} + +/// Largest result (uncompressed `total_byte_count`) that lets a SQL text use +/// `INLINE` on its next execution: far below the server's 25 MiB inline limit. +const SMALL_RESULT_BYTES: i64 = 4 * 1024 * 1024; +/// Bound on remembered SQL texts per session; the set is cleared when full. +const SMALL_RESULT_MEMO_CAP: usize = 1024; +/// How long a small result keeps a SQL text on `INLINE`. +const SMALL_RESULT_TTL: std::time::Duration = std::time::Duration::from_secs(600); +const INLINE_BYTE_LIMIT_MESSAGE: &str = "Inline byte limit exceeded"; +const INLINE_TRUNCATED_MESSAGE: &str = "Server truncated the INLINE result"; + +/// Whether `sql` starts with a verb that only reads (after comments, whitespace +/// and opening parentheses). Re-running such a statement is side-effect free. +fn is_read_only_query(sql: &str) -> bool { + let mut rest = sql; + loop { + rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == '('); + if let Some(after) = rest.strip_prefix("--") { + rest = after.split_once('\n').map_or("", |(_, tail)| tail); + } else if let Some(after) = rest.strip_prefix("/*") { + rest = after.split_once("*/").map_or("", |(_, tail)| tail); + } else { + break; + } + } + let verb: String = rest + .chars() + .take_while(|c| c.is_ascii_alphabetic()) + .collect::() + .to_ascii_uppercase(); + matches!( + verb.as_str(), + "SELECT" | "WITH" | "VALUES" | "TABLE" | "FROM" | "SHOW" | "DESCRIBE" | "DESC" | "EXPLAIN" + ) +} + +fn sql_key(sql: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + sql.hash(&mut hasher); + hasher.finish() +} + +/// `INLINE` result over the server's limit: either rejected outright, or (on +/// servers without the rejection) returned with `manifest.truncated`. +fn is_inline_overflow(error: &Error) -> bool { + error.message.contains(INLINE_TRUNCATED_MESSAGE) + || (error.error_code.as_deref() == Some("BAD_REQUEST") + && error.message.contains(INLINE_BYTE_LIMIT_MESSAGE)) +} + +/// A truncated manifest that the caller's `row_limit` does not explain. +fn inline_result_truncated(manifest: &ResultManifest, row_limit: Option) -> bool { + manifest.truncated + && !row_limit.is_some_and(|limit| manifest.total_row_count.is_some_and(|n| n >= limit)) } /// Internal terminal-outcome for a single SEA statement response. @@ -184,6 +242,10 @@ pub(crate) struct SeaRestTransport { /// `can_cloud_download` session conf (Reyden does): the session then /// requests `INLINE` results instead of paged inline results. inline_disposition: AtomicBool, + /// SQL texts (hashed) whose last result was small. On a realtime session, + /// these run with `INLINE`, which avoids the server persisting every hybrid + /// result to cloud storage while it holds the result stream open. + small_results: std::sync::Mutex>, reader_factory: OnceLock, runtime_handle: OnceLock, } @@ -227,6 +289,7 @@ impl SeaRestTransport { session_route: OnceLock::new(), session_version: AtomicI64::new(NO_SESSION_VERSION), inline_disposition: AtomicBool::new(false), + small_results: std::sync::Mutex::new(HashMap::new()), reader_factory: OnceLock::new(), runtime_handle: OnceLock::new(), } @@ -274,6 +337,48 @@ impl SeaRestTransport { } } + fn adaptive_inline_enabled(&self) -> bool { + self.config.cloudfetch_enabled + && self.config.realtime_inline_small_results + && matches!( + self.session_route.get(), + Some(SessionRoute::Realtime { .. }) + ) + } + + /// Whether a user statement should request `INLINE`: realtime session, + /// read-only verb, and a small result for the same SQL text recently. + fn prefers_inline(&self, sql: &str) -> bool { + self.adaptive_inline_enabled() + && is_read_only_query(sql) + && self.small_results.lock().is_ok_and(|memo| { + memo.get(&sql_key(sql)) + .is_some_and(|seen| seen.elapsed() < SMALL_RESULT_TTL) + }) + } + + fn remember_result_size(&self, sql: &str, result: &ExecuteResult) { + if !self.adaptive_inline_enabled() { + return; + } + let small = result.telemetry_result_format != ExecutionResultFormat::ExternalLinks + && result + .manifest + .as_ref() + .and_then(|m| m.total_byte_count) + .is_some_and(|bytes| bytes <= SMALL_RESULT_BYTES); + if let Ok(mut memo) = self.small_results.lock() { + if small { + if memo.len() >= SMALL_RESULT_MEMO_CAP { + memo.clear(); + } + memo.insert(sql_key(sql), std::time::Instant::now()); + } else { + memo.remove(&sql_key(sql)); + } + } + } + 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 }) @@ -660,6 +765,7 @@ impl SeaRestTransport { params: &ExecuteParams, request_type: RequestType, metadata_operation: Option, + inline: bool, ) -> Result { let url = format!("{}/statements", self.base_url()); @@ -677,7 +783,7 @@ impl SeaRestTransport { session_version: self.current_session_version(), catalog: params.catalog.clone(), schema: params.schema.clone(), - disposition: if self.inline_disposition.load(Ordering::Relaxed) { + disposition: if inline || self.inline_disposition.load(Ordering::Relaxed) { "INLINE" } else { "INLINE_OR_EXTERNAL_LINKS" @@ -816,6 +922,7 @@ impl SeaRestTransport { params, request.request_type, request.metadata_operation, + request.inline, ) .await .map_err(|error| TerminalExecutionFailure { @@ -908,6 +1015,30 @@ impl SeaRestTransport { metadata_operation: Option, timeout: ExecutionTimeout, ) -> Result { + self.execute_and_read_with( + session_id, + sql, + params, + request_type, + metadata_operation, + timeout, + false, + ) + .await + } + + #[allow(clippy::too_many_arguments)] + async fn execute_and_read_with( + &self, + session_id: &str, + sql: &str, + params: &ExecuteParams, + request_type: RequestType, + metadata_operation: Option, + timeout: ExecutionTimeout, + inline: bool, + ) -> Result { + let inline = inline || self.inline_disposition.load(Ordering::Relaxed); // After call_execute_api succeeds, the SEA statement is open // on the server. Any subsequent failure before we hand back // an ExecuteResult (which wraps it in an ExecutedStatement @@ -935,6 +1066,7 @@ impl SeaRestTransport { ExecutionRequest { request_type, metadata_operation, + inline, }, timeout, &status_request_in_flight, @@ -1008,6 +1140,20 @@ impl SeaRestTransport { return Err(error); } }; + if inline + && response + .manifest + .as_ref() + .is_some_and(|m| inline_result_truncated(m, params.row_limit)) + { + self.close_orphaned_statement(&statement_id, "inline_truncated") + .await; + return Err(Error::data_loss() + .message(format!( + "{INLINE_TRUNCATED_MESSAGE}; enable CloudFetch to fetch the full result" + )) + .with_query_id(&statement_id)); + } // Preserve the old sync behavior: a terminal GetStatementStatus response // is DML-enriched before the result reader is handed off. It now happens // after terminal mapping, keeping this result work out of the execution @@ -1300,15 +1446,40 @@ impl Transport for SeaRestTransport { params: &ExecuteParams, timeout: ExecutionTimeout, ) -> Result { - self.execute_and_read( - session_id, - sql, - params, - RequestType::ExecuteStatement, - None, - timeout, - ) - .await + let inline = self.prefers_inline(sql); + let mut result = self + .execute_and_read_with( + session_id, + sql, + params, + RequestType::ExecuteStatement, + None, + timeout, + inline, + ) + .await; + if inline && result.as_ref().is_err_and(is_inline_overflow) { + // The result outgrew INLINE. The statement is read-only, so run it + // again with links; it will not use INLINE again until small. + debug!("INLINE result exceeded the inline limit; re-running with external links"); + if let Ok(mut memo) = self.small_results.lock() { + memo.remove(&sql_key(sql)); + } + result = self + .execute_and_read( + session_id, + sql, + params, + RequestType::ExecuteStatement, + None, + timeout, + ) + .await; + } + if let Ok(result) = &result { + self.remember_result_size(sql, result); + } + result } async fn submit_statement( @@ -1335,6 +1506,7 @@ impl Transport for SeaRestTransport { ¶ms, RequestType::ExecuteStatement, None, + false, ) .await } @@ -1357,7 +1529,14 @@ impl Transport for SeaRestTransport { // internal poll loop: a query that outlasts the inline wait // comes back `Running` for the caller to poll/cancel. let response = self - .call_execute_api(session_id, sql, params, RequestType::ExecuteStatement, None) + .call_execute_api( + session_id, + sql, + params, + RequestType::ExecuteStatement, + None, + false, + ) .await?; let statement_id = response.statement_id.clone(); @@ -2122,6 +2301,7 @@ mod tests { ExecutionRequest { request_type: RequestType::ExecuteStatement, metadata_operation: None, + inline: false, }, ExecutionTimeout::Unlimited, &AtomicBool::new(false), @@ -2502,6 +2682,32 @@ mod tests { assert!(!rejects_can_cloud_download(&no_status)); } + #[test] + fn read_only_query_detection_skips_comments_and_parentheses() { + for sql in [ + "SELECT 1", + " select 1", + "-- note\nWITH t AS (SELECT 1) SELECT * FROM t", + "/* hint */ (VALUES (1))", + "SHOW TABLES", + "describe t", + "EXPLAIN SELECT 1", + ] { + assert!(is_read_only_query(sql), "{sql:?}"); + } + for sql in [ + "INSERT INTO t VALUES (1)", + "CALL p()", + "MERGE INTO t USING s ON true WHEN MATCHED THEN DELETE", + "-- SELECT\nDELETE FROM t", + "/* unterminated SELECT", + "", + "SELECTED", + ] { + assert!(!is_read_only_query(sql), "{sql:?}"); + } + } + #[test] fn test_list_table_types() { let client = create_test_client(); diff --git a/src/client/transport.rs b/src/client/transport.rs index 90f91a75..8091eb8f 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -70,6 +70,8 @@ pub(crate) struct TransportConfig { /// When false, session creation requests paged inline results without /// cloud-storage downloads. The value is fixed for the session lifetime. pub cloudfetch_enabled: bool, + /// Mirrors [`crate::config::ResultConfig::realtime_inline_small_results`]. + pub realtime_inline_small_results: bool, } impl Default for TransportConfig { @@ -79,6 +81,7 @@ impl Default for TransportConfig { poll_interval: Duration::from_millis(500), // Mirror `ResultConfig::default().cloudfetch_enabled`. cloudfetch_enabled: true, + realtime_inline_small_results: true, } } } diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..2050017a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1151,6 +1151,14 @@ pub struct ResultConfig { /// /// Default `false`. pub intervals_as_string: bool, + + /// On Lakehouse Real-Time sessions, run a read-only statement with the + /// `INLINE` result disposition once its SQL text has returned a small + /// result. The hybrid disposition makes the server persist every result to + /// cloud storage, which costs throughput and causes failures at high + /// concurrency. A result that outgrows the inline limit is detected and the + /// statement runs again with the hybrid disposition. Default `true`. + pub realtime_inline_small_results: bool, } impl Default for ResultConfig { @@ -1162,6 +1170,7 @@ impl Default for ResultConfig { inline_max_chunks_in_memory: 4, complex_types_as_json: false, intervals_as_string: false, + realtime_inline_small_results: true, } } } @@ -1193,6 +1202,7 @@ pub(crate) enum ClientConfKey { InlineMaxChunksInMemory, ComplexTypesAsJson, IntervalsAsString, + RealtimeInlineSmallResults, } impl ClientConfKey { @@ -1205,6 +1215,7 @@ impl ClientConfKey { Self::InlineMaxChunksInMemory, Self::ComplexTypesAsJson, Self::IntervalsAsString, + Self::RealtimeInlineSmallResults, ]; /// The canonical wire spelling of this key. @@ -1216,6 +1227,7 @@ impl ClientConfKey { Self::InlineMaxChunksInMemory => "inline_max_chunks_in_memory", Self::ComplexTypesAsJson => "complex_types_as_json", Self::IntervalsAsString => "intervals_as_string", + Self::RealtimeInlineSmallResults => "realtime_inline_small_results", } } @@ -1324,6 +1336,9 @@ impl ResultConfig { ClientConfKey::IntervalsAsString => { self.intervals_as_string = parse_bool(value)?; } + ClientConfKey::RealtimeInlineSmallResults => { + self.realtime_inline_small_results = parse_bool(value)?; + } } Ok(()) } diff --git a/src/session.rs b/src/session.rs index ccb3fd0d..22e27094 100644 --- a/src/session.rs +++ b/src/session.rs @@ -392,6 +392,7 @@ impl Session { let defaults = config.defaults.clone().unwrap_or_default(); let transport_config = TransportConfig { cloudfetch_enabled: config.result.cloudfetch_enabled, + realtime_inline_small_results: config.result.realtime_inline_small_results, ..TransportConfig::default() }; let sea = Arc::new(SeaRestTransport::new( diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 404dde5f..a666271d 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -1681,6 +1681,259 @@ async fn execute_with_cloudfetch_disabled_supports_paged_arrow_results() { ); } +const RT_STATEMENTS: &str = "/api/2.0/sql/warehouses/test_wh/sessions/rt-sess/statements"; + +/// A realtime (Reyden) session: the CreateSession response carries the +/// realtime header and statements go to the warehouse-session route. +async fn open_realtime_session(server: &MockServer) -> Session { + 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": "rt-sess", "session_version": {"version_id": 1}}), + ), + ) + .mount(server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(server) + .await; + open_session_with_result(server, ResultConfig::default()).await +} + +async fn recorded_execute_dispositions(server: &MockServer) -> Vec { + server + .received_requests() + .await + .expect("wiremock received_requests must be available") + .iter() + .filter(|r| r.method.as_str() == "POST" && r.url.path().ends_with("/statements")) + .map(|r| { + let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap(); + body["disposition"].as_str().unwrap().to_string() + }) + .collect() +} + +async fn run_and_drain(session: &Session, sql: &str) -> databricks_sql_kernel::Result { + let mut stmt = session.statement(); + stmt.spec().sql(sql); + let mut exec = stmt.execute().await?; + let rows = drain(exec.result_stream_mut()) + .await + .iter() + .map(|b| b.num_rows()) + .sum(); + exec.close().await?; + Ok(rows) +} + +#[tokio::test] +async fn realtime_repeat_select_with_small_result_uses_inline() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(RT_STATEMENTS)) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(succeeded_inline_body("stmt-1", &int64_batch("n", vec![7]))), + ) + .mount(&server) + .await; + let session = open_realtime_session(&server).await; + for sql in [ + "SELECT 7 AS n", + "SELECT 7 AS n", + " -- comment\n(SELECT 8 AS n)", + " -- comment\n(SELECT 8 AS n)", + "INSERT INTO t VALUES (1)", + "INSERT INTO t VALUES (1)", + ] { + assert_eq!(run_and_drain(&session, sql).await.expect(sql), 1); + } + assert_eq!( + recorded_execute_dispositions(&server).await, + [ + "INLINE_OR_EXTERNAL_LINKS", + "INLINE", + "INLINE_OR_EXTERNAL_LINKS", + "INLINE", + "INLINE_OR_EXTERNAL_LINKS", + "INLINE_OR_EXTERNAL_LINKS", + ] + ); + session.close().await.expect("close session"); +} + +#[tokio::test] +async fn realtime_inline_overflow_reruns_with_external_links() { + use wiremock::matchers::body_string_contains; + let server = MockServer::start().await; + let mut overflow: serde_json::Value = serde_json::from_str(&failed_body( + "stmt-inline", + "Inline byte limit exceeded", + "42000", + )) + .unwrap(); + overflow["status"]["error"]["error_code"] = json!("BAD_REQUEST"); + Mock::given(method("POST")) + .and(path(RT_STATEMENTS)) + .and(body_string_contains(r#""disposition":"INLINE""#)) + .respond_with(ResponseTemplate::new(200).set_body_json(overflow)) + .with_priority(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(RT_STATEMENTS)) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(succeeded_inline_body("stmt-1", &int64_batch("n", vec![7]))), + ) + .with_priority(2) + .mount(&server) + .await; + let session = open_realtime_session(&server).await; + assert_eq!(run_and_drain(&session, "SELECT 7 AS n").await.unwrap(), 1); + assert_eq!( + run_and_drain(&session, "SELECT 7 AS n") + .await + .expect("re-run must succeed"), + 1 + ); + assert_eq!( + recorded_execute_dispositions(&server).await, + [ + "INLINE_OR_EXTERNAL_LINKS", + "INLINE", + "INLINE_OR_EXTERNAL_LINKS" + ] + ); + session.close().await.expect("close session"); +} + +#[tokio::test] +async fn realtime_truncated_inline_result_reruns_with_external_links() { + use wiremock::matchers::body_string_contains; + let server = MockServer::start().await; + let mut truncated: serde_json::Value = serde_json::from_str(&succeeded_inline_body( + "stmt-inline", + &int64_batch("n", vec![7]), + )) + .unwrap(); + truncated["manifest"]["truncated"] = json!(true); + Mock::given(method("POST")) + .and(path(RT_STATEMENTS)) + .and(body_string_contains(r#""disposition":"INLINE""#)) + .respond_with(ResponseTemplate::new(200).set_body_json(truncated)) + .with_priority(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(RT_STATEMENTS)) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_inline_body( + "stmt-1", + &int64_batch("n", vec![7, 8]), + )), + ) + .with_priority(2) + .mount(&server) + .await; + let session = open_realtime_session(&server).await; + assert_eq!(run_and_drain(&session, "SELECT n FROM t").await.unwrap(), 2); + assert_eq!(run_and_drain(&session, "SELECT n FROM t").await.unwrap(), 2); + assert_eq!( + recorded_execute_dispositions(&server).await, + [ + "INLINE_OR_EXTERNAL_LINKS", + "INLINE", + "INLINE_OR_EXTERNAL_LINKS" + ] + ); + session.close().await.expect("close session"); +} + +#[tokio::test] +async fn realtime_inline_small_results_can_be_disabled_through_session_conf() { + 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": "rt-sess", "session_version": {"version_id": 1}}), + ), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(RT_STATEMENTS)) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(succeeded_inline_body("stmt-1", &int64_batch("n", vec![7]))), + ) + .mount(&server) + .await; + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh").unwrap(), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .session_conf(std::collections::HashMap::from([( + "realtime_inline_small_results".into(), + "false".into(), + )])) + .open() + .await + .expect("session open"); + run_and_drain(&session, "SELECT 7 AS n").await.unwrap(); + run_and_drain(&session, "SELECT 7 AS n").await.unwrap(); + assert_eq!( + recorded_execute_dispositions(&server).await, + ["INLINE_OR_EXTERNAL_LINKS", "INLINE_OR_EXTERNAL_LINKS"] + ); + let create = server + .received_requests() + .await + .unwrap() + .into_iter() + .find(|r| r.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions") + .unwrap(); + assert!(!String::from_utf8_lossy(&create.body).contains("realtime_inline_small_results")); + session.close().await.expect("close session"); +} + +#[tokio::test] +async fn standard_route_never_uses_inline() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_execute( + &server, + succeeded_inline_body("stmt-1", &int64_batch("n", vec![7])), + ) + .await; + let session = open_session_with_result(&server, ResultConfig::default()).await; + run_and_drain(&session, "SELECT 7 AS n").await.unwrap(); + run_and_drain(&session, "SELECT 7 AS n").await.unwrap(); + assert_eq!( + recorded_execute_dispositions(&server).await, + ["INLINE_OR_EXTERNAL_LINKS", "INLINE_OR_EXTERNAL_LINKS"] + ); + session.close().await.expect("close session"); +} + #[tokio::test] async fn cloudfetch_disabled_falls_back_to_inline_when_warehouse_rejects_can_cloud_download() { use wiremock::matchers::body_string_contains;