Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 219 additions & 13 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -96,6 +96,64 @@ impl MetadataOperation {
struct ExecutionRequest {
request_type: RequestType,
metadata_operation: Option<MetadataOperation>,
/// 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::<String>()
.to_ascii_uppercase();
matches!(
verb.as_str(),
"SELECT" | "WITH" | "VALUES" | "TABLE" | "FROM" | "SHOW" | "DESCRIBE" | "DESC" | "EXPLAIN"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium — WITH and FROM don't always mean a read-only statement in Spark/Databricks SQL. WITH cte AS (...) INSERT INTO t SELECT * FROM cte is valid, and so is the Hive-style multi-insert FROM src INSERT INTO t1 SELECT ... INSERT INTO t2 SELECT .... Both pass is_read_only_query, so the doc comment's claim that re-running is side-effect free doesn't hold for them.

Today a DML result (affected-row counts) is tiny, so the overflow/truncation re-run is unlikely to fire. But the overflow re-run path in execute_statement depends on this check to be safe, and any server-side truncation or byte-limit error on such a statement would execute the insert twice. Two fixes would work: look past a leading WITH/FROM for an INSERT/MERGE/UPDATE/DELETE keyword, or drop FROM (which is rare as a leading verb for reads) and document the WITH caveat. Also add a negative case like WITH t AS (SELECT 1) INSERT INTO x SELECT * FROM t to read_only_query_detection_skips_comments_and_parentheses.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 023b734. WITH and FROM now count as read-only only when no INSERT, MERGE, UPDATE or DELETE token appears anywhere in the text. A false negative only skips the optimization. The unit test has new negative cases: WITH t AS (SELECT 1) INSERT INTO x ..., WITH ... MERGE ... UPDATE SET *, and the Hive multi-insert FROM src INSERT INTO t1 ... INSERT INTO t2 .... It also has a positive case where a column is named updated_at.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't find the change described for 023b734 in the current head. is_read_only_query (line 115) still ends in the same matches! on the leading verb, with "WITH" and "FROM" accepted unconditionally. Grepping src/client/sea.rs finds no INSERT/MERGE/UPDATE/DELETE token scan inside that function. The test has no WITH t AS (SELECT 1) INSERT INTO x ... case, no Hive multi-insert case and no updated_at case either; the only WITH case is the read-only WITH t AS (SELECT 1) SELECT * FROM t. The commit may not have been pushed to this branch, or it may have landed somewhere else. Once it's on the PR head, I'll re-check it. The approach you described (treat WITH/FROM as read-only only when no DML keyword appears, and accept the occasional false negative) addresses the concern.

)
}

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<i64>) -> 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.
Expand Down Expand Up @@ -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<HashMap<u64, std::time::Instant>>,
reader_factory: OnceLock<ResultReaderFactory>,
runtime_handle: OnceLock<RuntimeHandle>,
}
Expand Down Expand Up @@ -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(),
}
Expand Down Expand Up @@ -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<SessionVersion> {
let version_id = self.session_version.load(Ordering::SeqCst);
(version_id != NO_SESSION_VERSION).then_some(SessionVersion { version_id })
Expand Down Expand Up @@ -660,6 +765,7 @@ impl SeaRestTransport {
params: &ExecuteParams,
request_type: RequestType,
metadata_operation: Option<MetadataOperation>,
inline: bool,
) -> Result<ExecuteResponse> {
let url = format!("{}/statements", self.base_url());

Expand All @@ -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"
Expand Down Expand Up @@ -816,6 +922,7 @@ impl SeaRestTransport {
params,
request.request_type,
request.metadata_operation,
request.inline,
)
.await
.map_err(|error| TerminalExecutionFailure {
Expand Down Expand Up @@ -908,6 +1015,30 @@ impl SeaRestTransport {
metadata_operation: Option<MetadataOperation>,
timeout: ExecutionTimeout,
) -> Result<ExecuteResult> {
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<MetadataOperation>,
timeout: ExecutionTimeout,
inline: bool,
) -> Result<ExecuteResult> {
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
Expand Down Expand Up @@ -935,6 +1066,7 @@ impl SeaRestTransport {
ExecutionRequest {
request_type,
metadata_operation,
inline,
},
timeout,
&status_request_in_flight,
Expand Down Expand Up @@ -1008,6 +1140,20 @@ impl SeaRestTransport {
return Err(error);
}
};
if inline

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium — The new truncated-manifest check runs whenever inline is true, and inline also covers the existing inline_disposition fallback (CloudFetch disabled, warehouse rejected can_cloud_download). That fallback applies to standard sessions too, and to metadata calls that go through execute_and_read.

Before this PR, those sessions returned the inline result as-is when manifest.truncated was set. Now they get a hard data_loss error and the statement is closed. No retry happens for them, because only execute_statement retries and only when prefers_inline was true. This contradicts the PR description's "Standard (non-Real-Time) sessions are unchanged", and no test covers it. If the change is intended (refusing silently truncated data is arguably better), call it out in the description and add a wiremock test for the CloudFetch-disabled path. If not, apply the check only to the adaptive-inline attempt (pass the caller's inline flag separately from the effective disposition).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept on purpose: with CloudFetch disabled there are no links to re-run with, and returning a server-truncated result as complete is the data-loss case ES-2127499 describes. In 023b734 the PR description calls this out as a behavior change for the #456 fallback, and the new wiremock test cloudfetch_disabled_inline_fallback_rejects_truncated_result pins it. A row_limit that explains the truncation still passes through unchanged.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting server-truncated inline results when CloudFetch is disabled seems like a reasonable call, and I'm fine with keeping the behavior change. What I can't confirm is the follow-through. In the checked-out head, nothing matches cloudfetch_disabled_inline_fallback_rejects_truncated_result, and the only references to inline_result_truncated are its definition (line 154) and the call at line 1147 in src/client/sea.rs. No test exercises the CloudFetch-disabled path. Commit 023b734 may not be in this checkout yet, or the test may not have been pushed. Once the test and the description note are on the branch, I'm happy to close this out.

&& 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
Expand Down Expand Up @@ -1300,15 +1446,40 @@ impl Transport for SeaRestTransport {
params: &ExecuteParams,
timeout: ExecutionTimeout,
) -> Result<ExecuteResult> {
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(
Expand All @@ -1335,6 +1506,7 @@ impl Transport for SeaRestTransport {
&params,
RequestType::ExecuteStatement,
None,
false,
)
.await
}
Expand All @@ -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();

Expand Down Expand Up @@ -2122,6 +2301,7 @@ mod tests {
ExecutionRequest {
request_type: RequestType::ExecuteStatement,
metadata_operation: None,
inline: false,
},
ExecutionTimeout::Unlimited,
&AtomicBool::new(false),
Expand Down Expand Up @@ -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();
Expand Down
3 changes: 3 additions & 0 deletions src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
}
}
}
Expand Down
Loading
Loading