diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 4c7c1a14..e57612e1 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Add execution-scoped client query deadlines to the Rust and C APIs. - Add an opt-in `release-with-debuginfo` Cargo profile and cross-platform symbol smoke checks for statically linked native consumers. - Create SQL Exec API sessions in FAST mode and exchange the maximum observed session version. @@ -22,6 +23,10 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- Client query deadlines now allow an already-running statement-status request + up to five seconds to return a terminal result; no new poll starts after the + configured deadline. + ### Updated ### Fixed diff --git a/docs/spec-v0.md b/docs/spec-v0.md index 16fd8a75..4cbb0530 100644 --- a/docs/spec-v0.md +++ b/docs/spec-v0.md @@ -644,10 +644,18 @@ impl Statement { /// Read-only access (for logging or assertion). pub fn spec_ref(&self) -> &StatementSpec; - /// Wait-for-result execution. Auto-cancels + closes any prior handle. - /// Spec is unchanged after the call; can be re-executed. + /// Wait-for-result execution with the existing 600s polling ceiling. pub async fn execute(&mut self) -> Result; + /// Execute with a client deadline through terminal-state mapping. + /// Zero and Duration::MAX select unlimited execution; result materialisation + /// is excluded. An in-flight status request gets a fixed five-second grace + /// period, but no new status request starts after the deadline. + pub async fn execute_with_timeout( + &mut self, + timeout: std::time::Duration, + ) -> Result; + /// Submit-and-return. Auto-cancels + closes any prior handle. pub async fn submit(&mut self) -> Result; } @@ -950,4 +958,3 @@ string (`[error_code STATEMENT_NOT_FOUND]`) since `adbc_core::error::Error` has no string-shaped slot for it. Lossy bridge — wrappers that consume `kernel_error::Error` directly (PyO3, napi-rs, the C ABI) get the structured field. - diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 525f2f8b..4cb46c60 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -85,6 +85,9 @@ #include #include +/* Largest finite value accepted by kernel_statement_execute_with_timeout_ms. */ +#define DATABRICKS_KERNEL_MAX_CLIENT_QUERY_TIMEOUT_MS UINT64_C(9223372036854) + #ifdef __cplusplus extern "C" { #endif @@ -705,12 +708,33 @@ KernelStatusCode kernel_statement_set_query_tags(kernel_statement_t* stmt, const char* query_tags); /* - * Wait-for-result execution. On success, `*out` holds an executed handle - * released with `kernel_executed_statement_close`. + * Wait-for-result execution with the existing 600-second polling ceiling and + * no caller-supplied deadline. On success, release `*out` with + * `kernel_executed_statement_close`. */ KernelStatusCode kernel_statement_execute(kernel_statement_t* stmt, kernel_executed_statement_t** out); +/* + * Wait-for-result execution with a client-side deadline in milliseconds. + * Zero selects unlimited execution; values above + * DATABRICKS_KERNEL_MAX_CLIENT_QUERY_TIMEOUT_MS return InvalidArgument. A finite + * deadline starts on entry and covers execution through terminal-state mapping, + * and excludes result materialisation and fetching. A status request already in + * flight at the deadline may finish within a fixed five-second grace period; no + * new status request starts after the deadline. The deadline is never sent to + * the server. + * + * Timeout returns KernelStatusCode_Timeout with SQLSTATE HYT00 and leaves + * `*out` NULL. Cleanup is best effort and asynchronous; `stmt` remains reusable. + * + * This function has the same handle invalidation and panic contract as + * kernel_statement_execute. + */ +KernelStatusCode kernel_statement_execute_with_timeout_ms( + kernel_statement_t* stmt, uint64_t timeout_ms, + kernel_executed_statement_t** out); + /* * Submit-and-return (async). DEFERRED in v0: this always returns * `KernelStatusCode_InvalidArgument` (with an explanatory last error) and diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 8fe65d6f..471426b0 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -38,6 +38,7 @@ use super::error::{store_and_code, store_invalid_arg}; use super::result::{into_raw_executed_stream, kernel_result_stream_t}; use super::{block_on_ffi, catch_ffi, KernelStatusCode}; +use crate::client::ExecutionTimeout; use crate::kernel_error::Error; use crate::statement::executed::ExecutedStatement; use crate::statement::mutable::Statement; @@ -45,6 +46,8 @@ use crate::statement::spec::TypedValue; use crate::statement::validity::ValidityFlag; use std::ffi::{c_char, CStr, CString}; +pub use crate::statement::timeout::MAX_CLIENT_QUERY_TIMEOUT_MS; + /// Upper bound on a positional parameter ordinal accepted over the C ABI. /// /// `StatementSpec::param` grows `positional_params` with @@ -450,6 +453,56 @@ pub unsafe extern "C" fn kernel_statement_execute( return store_invalid_arg("kernel_statement_execute: out must not be null"); } + execute_with_timeout_mode(stmt, ExecutionTimeout::Default, out) +} + +/// Wait-for-result execution with a client deadline in milliseconds. +/// +/// Zero selects unlimited execution. A finite deadline starts at native entry, +/// ends after terminal mapping, and excludes result materialisation. A status request +/// already in flight at the deadline may finish within a fixed five-second grace +/// period. Timeout returns [`KernelStatusCode::Timeout`] with `HYT00` and leaves +/// `*out` null. +/// +/// # Safety +/// `stmt` must be a live statement handle; `out` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_execute_with_timeout_ms( + stmt: *mut kernel_statement_t, + timeout_ms: u64, + out: *mut *mut kernel_executed_statement_t, +) -> KernelStatusCode { + // Include validation and runtime queueing in the deadline. + let entered_at = std::time::Instant::now(); + crate::c_abi::error::clear_error(); + if out.is_null() { + return store_invalid_arg("kernel_statement_execute_with_timeout_ms: out must not be null"); + } + std::ptr::write(out, std::ptr::null_mut()); + let Some(stmt) = statement_mut(stmt) else { + return store_invalid_arg( + "kernel_statement_execute_with_timeout_ms: stmt must not be null", + ); + }; + let timeout = match crate::statement::timeout::deadline_from_timeout_at( + std::time::Duration::from_millis(timeout_ms), + entered_at, + ) { + Ok(deadline) => ExecutionTimeout::from_explicit_deadline(deadline), + Err(error) => return store_and_code(error), + }; + + execute_with_timeout_mode(stmt, timeout, out) +} + +/// Run synchronous execution after entry-point validation. +/// +/// The timeout entry point clears `out`; the existing entry point does not. +unsafe fn execute_with_timeout_mode( + stmt: &mut Statement, + timeout: ExecutionTimeout, + out: *mut *mut kernel_executed_statement_t, +) -> KernelStatusCode { // `Statement::execute` borrows `&mut self`; we need that borrow to // live across the `block_on`. Raw-pointer the statement so the // closure can re-borrow it inside the runtime without entangling @@ -458,7 +511,7 @@ pub unsafe extern "C" fn kernel_statement_execute( let stmt_ptr: *mut Statement = stmt; let executed = block_on_ffi(move || { let stmt: &mut Statement = unsafe { &mut *stmt_ptr }; - Box::pin(async move { stmt.execute().await }) + Box::pin(async move { stmt.execute_with_timeout_mode(timeout).await }) }); match executed { Ok(exec) => { diff --git a/src/client/mod.rs b/src/client/mod.rs index 8f453016..e2f59a71 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -46,5 +46,6 @@ pub use retry::{ pub(crate) use sea::SeaRestTransport; pub(crate) use transport::{ ChunkLinkFetchResult, DirectOutcome, ExecuteResponse, ExecuteResult, ExecuteResultData, - InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport, TransportConfig, + ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport, + TransportConfig, }; diff --git a/src/client/sea.rs b/src/client/sea.rs index 094b53f4..114e4457 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -20,8 +20,8 @@ use crate::client::retry::RequestType; use crate::client::{ ChunkLinkFetchResult, DatabricksHttpClient, DirectOutcome, ExecuteResponse, ExecuteResult, - ExecuteResultData, InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport, - TransportConfig, + ExecuteResultData, ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo, + Transport, TransportConfig, }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -37,7 +37,7 @@ use crate::types::sea::{ use async_trait::async_trait; use reqwest::Method; use std::collections::HashMap; -use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; use std::sync::{Arc, OnceLock}; use tokio::runtime::Handle as RuntimeHandle; @@ -95,6 +95,26 @@ enum TerminalExecutionOutcome { Failed(Error), } +/// Execution failure and any statement id available for cleanup. +#[derive(Debug)] +struct TerminalExecutionFailure { + statement_id: Option, + error: Error, +} + +/// Read the statement id used to attribute and clean up a client timeout. +/// Recovering a poisoned observer preserves best-effort cleanup after a panic. +fn timeout_query_id(params: &ExecuteParams) -> Option { + params.inflight_id_observer.as_ref().and_then(|slot| { + slot.lock() + .unwrap_or_else(|poisoned| { + warn!("in-flight statement id lock poisoned; recovering for timeout cleanup"); + poisoned.into_inner() + }) + .clone() + }) +} + /// SEA client for the Databricks SQL Statement Execution API. /// /// This client implements the `Transport` trait using REST endpoints. @@ -468,38 +488,60 @@ impl SeaRestTransport { } } - /// Poll until the server reports a raw terminal statement state. - /// - /// This phase deliberately stops before terminal error mapping, reader creation, - /// schema extraction, or DML-count materialisation. The existing polling budget is - /// retained here; client-configurable execution deadlines are a separate change. + /// Poll until the server reports a raw terminal state. async fn wait_for_terminal( &self, response: ExecuteResponse, + timeout: ExecutionTimeout, + status_request_in_flight: &AtomicBool, ) -> Result<(ExecuteResponse, bool)> { - let start = std::time::Instant::now(); + let started = std::time::Instant::now(); let mut current_response = response; let mut response_from_poll = false; loop { match current_response.status.state { StatementState::Pending | StatementState::Running => { - if start.elapsed() > self.config.poll_timeout { + if matches!(timeout, ExecutionTimeout::Default) + && started.elapsed() > self.config.poll_timeout + { return Err(Error::timeout().message("Statement execution timed out")); } - + if matches!( + timeout, + ExecutionTimeout::Deadline(deadline) + if std::time::Instant::now() >= deadline + ) { + return Err(crate::statement::timeout::client_query_timeout_error(Some( + ¤t_response.statement_id, + ))); + } tokio::time::sleep(self.config.poll_interval).await; + // When the execution future is resumed during status grace, + // do not turn a completed poll sleep into a new status call. + if matches!( + timeout, + ExecutionTimeout::Deadline(deadline) + if std::time::Instant::now() >= deadline + ) { + return Err(crate::statement::timeout::client_query_timeout_error(Some( + ¤t_response.statement_id, + ))); + } debug!( statement_id = %current_response.statement_id, state = ?current_response.status.state, "Polling statement status" ); - current_response = self + status_request_in_flight.store(true, Ordering::Release); + let status_result = self .get_statement_status_raw( ¤t_response.statement_id, SessionAttribution::Current, ) - .await?; + .await; + status_request_in_flight.store(false, Ordering::Release); + current_response = status_result?; response_from_poll = true; } StatementState::Succeeded @@ -671,10 +713,16 @@ impl SeaRestTransport { sql: &str, params: &ExecuteParams, request_type: RequestType, - ) -> Result { + timeout: ExecutionTimeout, + status_request_in_flight: &AtomicBool, + ) -> std::result::Result { let response = self .call_execute_api(session_id, sql, params, request_type) - .await?; + .await + .map_err(|error| TerminalExecutionFailure { + statement_id: None, + error, + })?; let statement_id = response.statement_id.clone(); // Publish the server statement id to the caller's canceller slot before @@ -685,14 +733,13 @@ impl SeaRestTransport { } } - let (response, response_from_poll) = match self.wait_for_terminal(response).await { - Ok(terminal) => terminal, - Err(error) => { - self.close_orphaned_statement(&statement_id, "wait_for_terminal") - .await; - return Err(error); - } - }; + let (response, response_from_poll) = self + .wait_for_terminal(response, timeout, status_request_in_flight) + .await + .map_err(|error| TerminalExecutionFailure { + statement_id: Some(statement_id.clone()), + error, + })?; let outcome = match Self::terminal_outcome(response) { StatementOutcome::Done(response) => TerminalExecutionOutcome::Succeeded(response), @@ -755,6 +802,7 @@ impl SeaRestTransport { sql: &str, params: &ExecuteParams, request_type: RequestType, + timeout: ExecutionTimeout, ) -> Result { // After call_execute_api succeeds, the SEA statement is open // on the server. Any subsequent failure before we hand back @@ -775,9 +823,71 @@ impl SeaRestTransport { // downloading chunk 0 to extract the result schema; a // non-retriable 4xx / 5xx on that GET propagates up. // - let terminal = self - .execute_to_terminal(session_id, sql, params, request_type) - .await?; + let status_request_in_flight = AtomicBool::new(false); + let execution = self.execute_to_terminal( + session_id, + sql, + params, + request_type, + timeout, + &status_request_in_flight, + ); + tokio::pin!(execution); + let execution_result = match timeout { + ExecutionTimeout::Deadline(deadline) => { + let deadline = tokio::time::Instant::from_std(deadline); + match tokio::time::timeout_at(deadline, &mut execution).await { + Ok(result) => result, + Err(_) if status_request_in_flight.load(Ordering::Acquire) => { + let grace_deadline = deadline + .checked_add( + crate::statement::timeout::CLIENT_QUERY_TIMEOUT_STATUS_GRACE, + ) + .unwrap_or(deadline); + match tokio::time::timeout_at(grace_deadline, &mut execution).await { + // Terminal server errors are mapped into a successful + // TerminalExecution, so only that shape may beat the + // client timeout during grace. + Ok(Ok(terminal)) => Ok(terminal), + Ok(Err(_)) | Err(_) => { + let query_id = timeout_query_id(params); + return Err(crate::statement::timeout::client_query_timeout_error( + query_id.as_deref(), + )); + } + } + } + Err(_) => { + let query_id = timeout_query_id(params); + return Err(crate::statement::timeout::client_query_timeout_error( + query_id.as_deref(), + )); + } + } + } + ExecutionTimeout::Default | ExecutionTimeout::Unlimited => execution.await, + }; + let terminal = match execution_result { + Ok(terminal) => terminal, + Err(TerminalExecutionFailure { + statement_id, + error, + }) => { + // The deadline can become ready in the same scheduler tick as + // the poll sleep. If the inner check wins, preserve the normal + // timeout contract: the statement layer dispatches bounded + // cancel/close cleanup without delaying this return. + if crate::statement::timeout::is_client_query_timeout(&error) { + return Err(error); + } + if let Some(statement_id) = statement_id { + self.close_orphaned_statement(&statement_id, "wait_for_terminal") + .await; + } + return Err(error); + } + }; + let TerminalExecution { statement_id, outcome, @@ -1027,9 +1137,16 @@ impl Transport for SeaRestTransport { session_id: &str, sql: &str, params: &ExecuteParams, + timeout: ExecutionTimeout, ) -> Result { - self.execute_and_read(session_id, sql, params, RequestType::ExecuteStatement) - .await + self.execute_and_read( + session_id, + sql, + params, + RequestType::ExecuteStatement, + timeout, + ) + .await } async fn submit_statement( @@ -1397,6 +1514,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1417,6 +1535,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1441,6 +1560,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1464,6 +1584,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1483,6 +1604,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1501,6 +1623,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1525,6 +1648,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1543,6 +1667,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1579,6 +1704,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await } @@ -1744,6 +1870,7 @@ mod tests { "UPDATE t SET x = x + 1", &ExecuteParams::default(), RequestType::ExecuteStatement, + ExecutionTimeout::Default, ) .await .expect("polled DML execution must succeed"); @@ -1806,6 +1933,8 @@ mod tests { "SELEKT 1", &ExecuteParams::default(), RequestType::ExecuteStatement, + ExecutionTimeout::Unlimited, + &AtomicBool::new(false), ) .await .expect("terminal server failure is a mapped execution outcome"); @@ -1825,13 +1954,13 @@ mod tests { } #[tokio::test] - async fn execute_to_terminal_timeout_preserves_error_and_cleanup() { + async fn default_execute_retains_poll_timeout() { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; let server = MockServer::start().await; let running = json!({ - "statement_id": "stmt-timeout", + "statement_id": "stmt-default-timeout", "status": { "state": "RUNNING" }, }); Mock::given(method("POST")) @@ -1841,12 +1970,13 @@ mod tests { .mount(&server) .await; Mock::given(method("GET")) - .and(path("/api/2.0/sql/statements/stmt-timeout")) - .respond_with(ResponseTemplate::new(200).set_body_json(running)) + .and(path("/api/2.0/sql/statements/stmt-default-timeout")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) + .expect(0) .mount(&server) .await; Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/statements/stmt-timeout")) + .and(path("/api/2.0/sql/statements/stmt-default-timeout")) .respond_with(ResponseTemplate::new(200).set_body_string("{}")) .expect(1) .mount(&server) @@ -1861,15 +1991,123 @@ mod tests { }, ); let error = match transport - .execute_to_terminal( + .execute_and_read( + "sess-test", + "SELECT 1", + &ExecuteParams::default(), + RequestType::ExecuteStatement, + ExecutionTimeout::Default, + ) + .await + { + Ok(_) => panic!("default execution must retain the transport poll timeout"), + Err(error) => error, + }; + + assert_eq!(error.code, crate::kernel_error::ErrorCode::Timeout); + assert_eq!(error.message, "Statement execution timed out"); + assert!(error.retryable); + assert_eq!(error.sql_state, None); + assert_eq!(error.query_id, None); + server.verify().await; + } + + #[tokio::test] + async fn explicit_unlimited_execute_bypasses_poll_timeout() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + let running = json!({ + "statement_id": "stmt-explicit-unlimited", + "status": { "state": "RUNNING" }, + }); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_json(running)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-explicit-unlimited")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(succeeded_inline_dml_body("stmt-explicit-unlimited", 1)), + ) + .expect(1) + .mount(&server) + .await; + + let transport = create_ready_test_client_against( + &server.uri(), + TransportConfig { + poll_timeout: std::time::Duration::ZERO, + poll_interval: std::time::Duration::ZERO, + ..TransportConfig::default() + }, + ); + transport + .execute_and_read( "sess-test", "SELECT 1", &ExecuteParams::default(), RequestType::ExecuteStatement, + ExecutionTimeout::Unlimited, + ) + .await + .expect("an explicit unlimited timeout must bypass the default ceiling"); + + server.verify().await; + } + + #[tokio::test] + async fn metadata_execute_retains_poll_timeout() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + let running = json!({ + "statement_id": "stmt-metadata-timeout", + "status": { "state": "RUNNING" }, + }); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_json(running)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-metadata-timeout")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) + .expect(0) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-metadata-timeout")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount(&server) + .await; + + let transport = create_ready_test_client_against( + &server.uri(), + TransportConfig { + poll_timeout: std::time::Duration::ZERO, + poll_interval: std::time::Duration::ZERO, + ..TransportConfig::default() + }, + ); + let error = match transport + .execute_and_read( + "sess-test", + "SHOW CATALOGS", + &ExecuteParams::default(), + RequestType::ExecuteMetadataQuery, + ExecutionTimeout::Default, ) .await { - Ok(_) => panic!("perpetually running statement must time out"), + Ok(_) => panic!("metadata execution must retain its poll timeout"), Err(error) => error, }; diff --git a/src/client/transport.rs b/src/client/transport.rs index a65e815d..96ed383a 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -31,10 +31,27 @@ use crate::types::cloudfetch::CloudFetchLink; use crate::types::sea::{ExecuteParams, ResultManifest, StatementStatus}; use async_trait::async_trait; use std::collections::HashMap; -use std::time::Duration; +use std::time::{Duration, Instant}; // ─── Transport-shared config ──────────────────────────────────────── +/// Timeout policy for synchronous execution. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ExecutionTimeout { + /// Preserve the transport's pre-existing polling ceiling. + Default, + /// The caller explicitly disabled the client timeout. + Unlimited, + /// Apply one absolute client deadline. + Deadline(Instant), +} + +impl ExecutionTimeout { + pub(crate) fn from_explicit_deadline(deadline: Option) -> Self { + deadline.map_or(Self::Unlimited, Self::Deadline) + } +} + /// Backend-agnostic configuration for [`Transport`] implementations. /// /// Contains polling settings shared across SEA REST, SEA gRPC, and @@ -43,7 +60,7 @@ use std::time::Duration; /// never reads it. #[derive(Debug, Clone)] pub(crate) struct TransportConfig { - /// Maximum time to wait for statement completion (default: 600s). + /// Default polling ceiling for sync, async, and metadata execution (600s). pub poll_timeout: Duration, /// Interval between status polls (default: 500ms). pub poll_interval: Duration, @@ -295,6 +312,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { session_id: &str, sql: &str, params: &ExecuteParams, + timeout: ExecutionTimeout, ) -> Result; /// Execute a SQL statement relying on the server's default inline wait diff --git a/src/lib.rs b/src/lib.rs index e7272cda..b386628b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -147,6 +147,7 @@ pub use statement::handle::ExecutedStatementHandle; pub use statement::mutable::{DirectStatement, Statement, StatementCanceller}; pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; +pub use statement::{MAX_CLIENT_QUERY_TIMEOUT, MAX_CLIENT_QUERY_TIMEOUT_MS}; pub use telemetry::DriverSystemConfiguration; // === Compile-time guarantees on auto-traits === diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index c48907f3..2ee9314a 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1095,7 +1095,7 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { #[cfg(test)] mod tests { use super::*; - use crate::client::{ExecuteResult, SessionInfo}; + use crate::client::{ExecuteResult, ExecutionTimeout, SessionInfo}; use crate::reader::EmptyReader; use crate::types::sea::{ExecuteParams, StatementState, StatementStatus}; use arrow_schema::Schema; @@ -1136,6 +1136,7 @@ mod tests { _session_id: &str, _sql: &str, _params: &ExecuteParams, + _timeout: ExecutionTimeout, ) -> Result { Ok(ExecuteResult { statement_id: "mock-statement".to_string(), @@ -1238,7 +1239,7 @@ mod tests { } async fn list_catalogs(&self, _session_id: &str) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1248,7 +1249,7 @@ mod tests { _catalog: Option<&str>, _schema_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1260,7 +1261,7 @@ mod tests { _table_pattern: Option<&str>, _table_types: Option<&[&str]>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1272,7 +1273,7 @@ mod tests { _table_pattern: Option<&str>, _column_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1283,7 +1284,7 @@ mod tests { _schema_pattern: Option<&str>, _procedure_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1294,7 +1295,7 @@ mod tests { _schema_pattern: Option<&str>, _function_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1306,7 +1307,7 @@ mod tests { _procedure_pattern: Option<&str>, _column_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1317,7 +1318,7 @@ mod tests { _schema: &str, _table: &str, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1331,7 +1332,7 @@ mod tests { _foreign_schema: &str, _foreign_table: &str, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 1c14d82a..8d28c969 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1449,7 +1449,8 @@ mod tests { use crate::client::{ ChunkLinkFetchResult, DatabricksHttpClient, ExecuteResponse, ExecuteResult, - ExecuteResultData, HttpClientConfig, InlineChunkFetchResult, SessionInfo, TransportConfig, + ExecuteResultData, ExecutionTimeout, HttpClientConfig, InlineChunkFetchResult, SessionInfo, + TransportConfig, }; use crate::kernel_error::ErrorCode; use crate::reader::post_processor::PostProcessOptions; @@ -1480,6 +1481,7 @@ mod tests { _: &str, _: &str, _: &ExecuteParams, + _: ExecutionTimeout, ) -> Result { unreachable!() } diff --git a/src/session.rs b/src/session.rs index 80b9b6c2..74214243 100644 --- a/src/session.rs +++ b/src/session.rs @@ -68,6 +68,7 @@ use crate::metadata_v0::Metadata; use crate::reader::ResultReaderFactory; use crate::statement::executed_async::ExecutedAsyncStatement; use crate::statement::mutable::Statement; +use crate::statement::timeout::TimeoutCleanupManager; use crate::telemetry::{DriverSystemConfiguration, OperationType, TelemetryRuntime}; use std::collections::HashMap; use std::sync::Arc; @@ -100,6 +101,9 @@ pub(crate) struct SessionInner { /// (e.g. the [`Drop`] impl below). runtime_handle: tokio::runtime::Handle, + /// Admission control for timeout cleanup. + timeout_cleanup: TimeoutCleanupManager, + /// Tracing span tagged with `session_id`. Every public method /// enters this span via `let _g = self.inner.log_span.enter();` /// so log lines tied to a session are visibly grouped. @@ -166,6 +170,14 @@ impl SessionInner { &self.runtime_handle } + pub(crate) fn dispatch_timeout_cleanup(&self, statement_id: Option) { + self.timeout_cleanup.dispatch( + &self.runtime_handle, + Arc::clone(&self.transport), + statement_id, + ); + } + pub(crate) fn statement_telemetry_observer( &self, statement_type: crate::telemetry::StatementType, @@ -412,6 +424,7 @@ impl Session { session_id: session_info.session_id, config, runtime_handle, + timeout_cleanup: TimeoutCleanupManager::default(), log_span, telemetry, closed: std::sync::atomic::AtomicBool::new(false), diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index d412f0a1..028659a5 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -436,10 +436,8 @@ impl ExecutedAsyncStatement { } /// Block until the server reaches a terminal state, then return - /// the result stream. Internally polls with backoff using the - /// session's [`crate::client::TransportConfig`] cadence (the - /// same `poll_interval` / `poll_timeout` the sync `execute()` - /// path uses). + /// the result stream. Internally polls using the session's + /// [`crate::client::TransportConfig`] cadence and ceiling. /// /// **Drop-cancellation.** Dropping the returned future before /// it resolves to a terminal state (e.g. a winning branch in @@ -451,8 +449,7 @@ impl ExecutedAsyncStatement { /// /// **Polling timeout.** When the transport's /// `TransportConfig.poll_timeout` elapses without reaching a - /// terminal state, returns `Error::timeout()` (same shape the - /// sync polling path produces). For owning handles this also + /// terminal state, returns `Error::timeout()`. For owning handles this also /// drops the armed cancel guard, which sends a best-effort /// server-side cancel; attached read-only handles do not cancel. pub async fn await_result(&self) -> Result { @@ -460,9 +457,6 @@ impl ExecutedAsyncStatement { let result = async { self.valid.check()?; - // Poll cadence + ceiling come from the transport's config — - // same source the sync `wait_for_completion` path uses, so - // a caller's `SessionBuilder` tuning applies to both modes. let cfg = self.session.transport().poll_config(); let start = std::time::Instant::now(); diff --git a/src/statement/mod.rs b/src/statement/mod.rs index 330fd759..2c20d9a9 100644 --- a/src/statement/mod.rs +++ b/src/statement/mod.rs @@ -33,6 +33,7 @@ pub mod params; pub mod params_codec; pub mod spec; +pub(crate) mod timeout; pub(crate) mod validity; // Re-exports so wrappers can write `crate::statement::Statement` instead @@ -43,3 +44,4 @@ pub use executed_async::{AsyncStatementCanceller, ExecutedAsyncStatement, Statem pub use handle::ExecutedStatementHandle; pub use mutable::{DirectStatement, Statement, StatementCanceller}; pub use spec::{ResultFormat, StatementSpec, TypedValue}; +pub use timeout::{MAX_CLIENT_QUERY_TIMEOUT, MAX_CLIENT_QUERY_TIMEOUT_MS}; diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 4f018300..1e678fc4 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -54,7 +54,7 @@ //! stale handle short-circuits locally — no network round-trip. See //! `crate::statement::validity` for the flag implementation. -use crate::client::DirectOutcome; +use crate::client::{DirectOutcome, ExecutionTimeout}; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; use crate::result_stream::ResultStream; @@ -68,6 +68,7 @@ use crate::telemetry::{OperationType, StatementTelemetry, StatementType}; use crate::types::sea::{ExecuteParams, QueryTag, StatementState}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; +use std::time::Duration; use tracing::Instrument; /// Outcome of [`Statement::execute_direct`] — the Thrift/JDBC directResults @@ -305,7 +306,8 @@ impl Statement { /// `CloseStatement`) and adds ~150–260ms to the response — /// observed against Dogfood; see PR description for the bench /// numbers. The kernel polls internally if the query needs - /// longer than 10s. + /// longer than 10s. This entry point retains the transport's 600s polling + /// ceiling; use [`Statement::execute_with_timeout`] to choose another limit. /// /// If a prior executed handle is still tracked by this `Statement`, /// the kernel spawns a fire-and-forget `CloseStatement` against it @@ -315,6 +317,27 @@ impl Statement { /// calls on it short-circuit to `InvalidStatementHandle` without /// hitting the wire. pub async fn execute(&mut self) -> Result { + self.execute_with_timeout_mode(ExecutionTimeout::Default) + .await + } + + /// Execute with a client deadline through terminal-state mapping. + /// + /// Result materialisation is excluded. `Duration::ZERO` and `Duration::MAX` + /// explicitly select unlimited execution. A status request already in flight + /// at the deadline may finish within a fixed five-second grace period; no new + /// poll starts after the deadline. + pub async fn execute_with_timeout(&mut self, timeout: Duration) -> Result { + let deadline = crate::statement::timeout::deadline_from_timeout(timeout)?; + self.execute_with_timeout_mode(ExecutionTimeout::from_explicit_deadline(deadline)) + .await + } + + /// Internal form used by the Rust and C ABI entry points. + pub(crate) async fn execute_with_timeout_mode( + &mut self, + timeout: ExecutionTimeout, + ) -> Result { // `instrument` (rather than `.entered()`) so the resulting // future stays `Send` — napi-rs's `execute_tokio_future` and // `tokio::spawn` both require `Send`, and `EnteredSpan` is @@ -349,11 +372,22 @@ impl Statement { // SeaRestTransport::execute_statement polls to completion // (10s server-side wait_timeout, then GetStatementStatus // loop until terminal). - let result = self + let result = match self .session .transport() - .execute_statement(self.session.session_id(), &sql, &exec_params) - .await?; + .execute_statement(self.session.session_id(), &sql, &exec_params, timeout) + .await + { + Ok(result) => result, + Err(error) if crate::statement::timeout::is_client_query_timeout(&error) => { + // Cleanup owns only the attempt id; defuse the duplicate guard. + guard.defuse(); + self.session + .dispatch_timeout_cleanup(error.query_id.clone()); + return Err(error); + } + Err(error) => return Err(error), + }; telemetry_for_body.on_statement_submitted(&result.statement_id); telemetry_for_body.on_result_metadata( result.telemetry_result_format, @@ -413,8 +447,8 @@ impl Statement { /// Returns immediately once the server hands back a /// `statement_id` — the caller drives polling via /// [`ExecutedAsyncStatement::status`] / `await_result` / - /// `fetch_result`. Long-running queries that would blow past - /// `execute()`'s sync polling budget belong on this path. + /// `fetch_result`. Use this path when the caller needs an explicit + /// poll/cancel handle instead of waiting synchronously for terminal state. pub async fn submit(&mut self) -> Result { let span = self.session.log_span().clone(); // Clear the shared in-flight-id slot before the first `.await` diff --git a/src/statement/timeout.rs b/src/statement/timeout.rs new file mode 100644 index 00000000..5e5f2033 --- /dev/null +++ b/src/statement/timeout.rs @@ -0,0 +1,210 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Client query-timeout primitives shared by the Rust and C-ABI surfaces. + +use crate::client::Transport; +use crate::kernel_error::{Error, ErrorCode, Result}; +use crate::klog::warn; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +/// Largest finite timeout, constrained to signed 64-bit nanoseconds. +pub const MAX_CLIENT_QUERY_TIMEOUT_MS: u64 = 9_223_372_036_854; + +/// Rust form of [`MAX_CLIENT_QUERY_TIMEOUT_MS`]. +pub const MAX_CLIENT_QUERY_TIMEOUT: Duration = Duration::from_millis(MAX_CLIENT_QUERY_TIMEOUT_MS); + +pub(crate) const CLIENT_QUERY_TIMEOUT_SQL_STATE: &str = "HYT00"; + +/// Maximum time an already-running status request may finish after the client +/// query deadline. No new status request starts once the deadline has passed. +pub(crate) const CLIENT_QUERY_TIMEOUT_STATUS_GRACE: Duration = Duration::from_secs(5); + +/// Maximum detached cleanup tasks per session. +const MAX_CONCURRENT_TIMEOUT_CLEANUPS: usize = 64; + +/// Independent budget for detached cancel and close. +const TIMEOUT_CLEANUP_BUDGET: Duration = Duration::from_secs(30); + +/// Convert a public relative timeout into one absolute monotonic deadline. +/// +/// Zero and [`Duration::MAX`] mean unlimited. +pub(crate) fn deadline_from_timeout(timeout: Duration) -> Result> { + deadline_from_timeout_at(timeout, Instant::now()) +} + +/// Convert a timeout using a caller-supplied entry instant. +pub(crate) fn deadline_from_timeout_at( + timeout: Duration, + entered_at: Instant, +) -> Result> { + if timeout.is_zero() || timeout == Duration::MAX { + return Ok(None); + } + if timeout > MAX_CLIENT_QUERY_TIMEOUT { + return Err(Error::invalid_argument().message(format!( + "client query timeout exceeds the maximum of {MAX_CLIENT_QUERY_TIMEOUT_MS} ms" + ))); + } + entered_at + .checked_add(timeout) + .map(Some) + .ok_or_else(|| Error::invalid_argument().message("client query timeout is out of range")) +} + +pub(crate) fn client_query_timeout_error(query_id: Option<&str>) -> Error { + let mut error = Error::timeout() + .message("Client query timeout expired") + .with_sql_state(CLIENT_QUERY_TIMEOUT_SQL_STATE) + .with_retryable(false); + if let Some(query_id) = query_id.filter(|id| !id.is_empty()) { + error = error.with_query_id(query_id); + } + error +} + +pub(crate) fn is_client_query_timeout(error: &Error) -> bool { + error.code == ErrorCode::Timeout + && error.sql_state.as_deref() == Some(CLIENT_QUERY_TIMEOUT_SQL_STATE) + && !error.retryable +} + +/// Per-session admission control for detached cleanup. +pub(crate) struct TimeoutCleanupManager { + permits: Arc, +} + +impl Default for TimeoutCleanupManager { + fn default() -> Self { + Self::with_capacity(MAX_CONCURRENT_TIMEOUT_CLEANUPS) + } +} + +impl TimeoutCleanupManager { + fn with_capacity(capacity: usize) -> Self { + Self { + permits: Arc::new(tokio::sync::Semaphore::new(capacity)), + } + } + + /// Spawn best-effort cleanup without waiting for capacity. + pub(crate) fn dispatch( + &self, + runtime: &tokio::runtime::Handle, + transport: Arc, + statement_id: Option, + ) { + let Some(statement_id) = statement_id.filter(|id| !id.is_empty()) else { + return; + }; + let permit = match Arc::clone(&self.permits).try_acquire_owned() { + Ok(permit) => permit, + Err(_) => { + warn!( + statement_id = %statement_id, + max_concurrent = MAX_CONCURRENT_TIMEOUT_CLEANUPS, + "client query-timeout cleanup saturated; dropping best-effort cancel/close" + ); + return; + } + }; + + runtime.spawn(async move { + let _permit = permit; + let cleanup = async { + if let Err(error) = transport.cancel_statement(&statement_id).await { + warn!( + statement_id = %statement_id, + error = %error, + "client query-timeout cancel failed; continuing best-effort close" + ); + } + if let Err(error) = transport.close_statement(&statement_id).await { + warn!( + statement_id = %statement_id, + error = %error, + "client query-timeout close failed; server will reclaim the statement" + ); + } + }; + if tokio::time::timeout(TIMEOUT_CLEANUP_BUDGET, cleanup) + .await + .is_err() + { + warn!( + statement_id = %statement_id, + budget_ms = TIMEOUT_CLEANUP_BUDGET.as_millis(), + "client query-timeout cleanup exceeded its background budget" + ); + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::client::ExecutionTimeout; + + #[test] + fn zero_and_duration_max_are_unlimited() { + for timeout in [Duration::ZERO, Duration::MAX] { + let deadline = deadline_from_timeout(timeout).unwrap(); + assert_eq!(deadline, None); + assert_eq!( + ExecutionTimeout::from_explicit_deadline(deadline), + ExecutionTimeout::Unlimited + ); + } + } + + #[test] + fn supplied_entry_instant_is_the_deadline_origin() { + let entered_at = Instant::now(); + let timeout = Duration::from_millis(25); + assert_eq!( + deadline_from_timeout_at(timeout, entered_at).unwrap(), + entered_at.checked_add(timeout) + ); + } + + #[test] + fn finite_range_is_shared_with_c_abi() { + assert!(deadline_from_timeout(MAX_CLIENT_QUERY_TIMEOUT).is_ok()); + let oversized = MAX_CLIENT_QUERY_TIMEOUT + .checked_add(Duration::from_millis(1)) + .unwrap(); + let error = deadline_from_timeout(oversized).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + } + + #[test] + fn timeout_error_has_stable_client_contract() { + let error = client_query_timeout_error(Some("stmt-123")); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert!(!error.retryable); + assert_eq!(error.query_id.as_deref(), Some("stmt-123")); + } + + #[test] + fn cleanup_admission_is_bounded_and_non_blocking() { + let manager = TimeoutCleanupManager::with_capacity(1); + let permit = Arc::clone(&manager.permits).try_acquire_owned().unwrap(); + assert!(Arc::clone(&manager.permits).try_acquire_owned().is_err()); + drop(permit); + assert!(Arc::clone(&manager.permits).try_acquire_owned().is_ok()); + } +} diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 0584d6ad..f29bc018 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -77,6 +77,11 @@ static void test_null_guards(void) { rc = kernel_statement_set_query_tags(NULL, "team:eng"); CHECK(rc == KernelStatusCode_InvalidArgument, "statement_set_query_tags(NULL) → InvalidArgument"); + kernel_executed_statement_t* exec = (kernel_executed_statement_t*)0x1; + rc = kernel_statement_execute_with_timeout_ms(NULL, 1, &exec); + CHECK(rc == KernelStatusCode_InvalidArgument, + "statement_execute_with_timeout_ms(NULL) → InvalidArgument"); + CHECK(exec == NULL, "statement_execute_with_timeout_ms failure clears out"); rc = kernel_result_stream_close(NULL); CHECK(rc == KernelStatusCode_InvalidArgument, "result_stream_close(NULL) → InvalidArgument"); diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index b7f86ab7..e27b8e66 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -12,11 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Wiremock tests for the C ABI's detached statement canceller -//! (`kernel_statement_canceller_new` / `_cancel` / `_free`). The null-guard -//! unit test in `src/c_abi/statement.rs` only pins the bad-pointer paths; these -//! tests drive the entry points against a mock SEA server to cover the behavior -//! that actually matters: +//! Wiremock tests for the C ABI's detached statement canceller and client query +//! timeout. The tests drive the native entry points against a mock SEA server: //! //! - `canceller_cancels_a_running_execute_from_another_thread`: the headline //! contract — one thread blocks in `kernel_statement_execute` while another @@ -34,6 +31,7 @@ //! after its statement AND session are closed — the cancel still dispatches //! (`dispatched == true`) and its POST reaches the server, proving the cloned //! session `Arc` keeps the client-side session alive past `kernel_session_close`. +//! - `client_timeout_c_abi_contract_and_reuse`: timeout contract and reuse. //! //! The C ABI drives its own process-wide tokio runtime inside `block_on_ffi`, //! so the entry points must be called from plain (non-async) threads — hence @@ -44,7 +42,7 @@ use std::ffi::CString; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, Instant}; use databricks_sql_kernel::c_abi::error::{kernel_get_last_error, KernelError}; use databricks_sql_kernel::c_abi::session::{ @@ -57,7 +55,8 @@ use databricks_sql_kernel::c_abi::statement::{ kernel_executed_statement_t, kernel_statement_bind_parameter, kernel_statement_canceller_cancel, kernel_statement_canceller_free, kernel_statement_canceller_new, kernel_statement_canceller_t, kernel_statement_close, - kernel_statement_execute, kernel_statement_set_sql, kernel_statement_t, + kernel_statement_execute, kernel_statement_execute_with_timeout_ms, kernel_statement_set_sql, + kernel_statement_t, MAX_CLIENT_QUERY_TIMEOUT_MS, }; use databricks_sql_kernel::c_abi::KernelStatusCode; use serde_json::json; @@ -129,8 +128,7 @@ fn succeeded_empty_body(statement_id: &str) -> String { /// on a fixed timer. `cancelled` is shared with the cancel POST mock, which sets /// it when the cancel RPC arrives. A poll cap is a safety valve: if a broken /// cancel never fires, the responder still flips to `CANCELED` after `max_running` -/// polls so the test fails its causal assertion instead of hanging on the -/// kernel's 600s poll timeout. +/// polls so the test fails its causal assertion instead of hanging indefinitely. struct CancelAwareStatus { statement_id: String, cancelled: Arc, @@ -1626,3 +1624,118 @@ fn retained_canceller_noops_in_the_reexecute_handoff_window() { the re-execute handoff" ); } + +#[test] +fn client_timeout_c_abi_contract_and_reuse() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let second_started = Arc::new(AtomicBool::new(false)); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(SequencedExecute { + first: running_body("stmt-c-timeout"), + rest: succeeded_empty_body("stmt-c-reused"), + calls: AtomicUsize::new(0), + second_started: Arc::clone(&second_started), + }) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-c-timeout/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT 1").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + + let mut out = std::ptr::dangling_mut::(); + let started = Instant::now(); + assert_eq!( + kernel_statement_execute_with_timeout_ms(stmt, 75, &mut out), + KernelStatusCode::Timeout + ); + assert!(out.is_null(), "the C output must be null on timeout"); + assert!( + started.elapsed() < Duration::from_millis(400), + "background timeout cleanup must not delay the native call" + ); + + let mut raw_error = std::mem::MaybeUninit::::uninit(); + assert!(kernel_get_last_error(raw_error.as_mut_ptr())); + let raw_error = raw_error.assume_init(); + assert_eq!(raw_error.code, KernelStatusCode::Timeout as i32); + assert!(!raw_error.retryable); + assert_eq!( + std::ffi::CStr::from_ptr(raw_error.sql_state) + .to_str() + .unwrap(), + "HYT00" + ); + assert_eq!( + std::ffi::CStr::from_ptr(raw_error.query_id) + .to_str() + .unwrap(), + "stmt-c-timeout" + ); + + out = std::ptr::dangling_mut::(); + assert_eq!( + kernel_statement_execute_with_timeout_ms( + stmt, + MAX_CLIENT_QUERY_TIMEOUT_MS + 1, + &mut out, + ), + KernelStatusCode::InvalidArgument + ); + assert!(out.is_null()); + + for timeout_ms in [MAX_CLIENT_QUERY_TIMEOUT_MS, 0] { + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute_with_timeout_ms(stmt, timeout_ms, &mut exec), + KernelStatusCode::Success + ); + assert!(!exec.is_null()); + assert_eq!( + kernel_executed_statement_close(exec), + KernelStatusCode::Success + ); + } + + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } + + let execute_posts = rt.block_on(async { + server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .filter(|request| { + request.method.as_str() == "POST" && request.url.path() == "/api/2.0/sql/statements" + }) + .count() + }); + assert_eq!( + execute_posts, 3, + "the oversized timeout must be rejected without an execute RPC" + ); +} diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 67d3bde4..7e64c03b 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -26,13 +26,15 @@ use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, ResultBatch, ResultConfig, - Session, TypedValue, + AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, HttpConfig, ResultBatch, + ResultConfig, Session, TypedValue, MAX_CLIENT_QUERY_TIMEOUT, }; use serde_json::json; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::time::{Duration, Instant}; use wiremock::matchers::{method, path}; -use wiremock::{Mock, MockServer, ResponseTemplate}; +use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; // ─── Helpers ──────────────────────────────────────────────────────── @@ -69,6 +71,22 @@ async fn open_session_with_result(server: &MockServer, result: ResultConfig) -> .expect("Session::open should succeed") } +async fn open_session_with_http(server: &MockServer, http: HttpConfig) -> Session { + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .http(http) + .open() + .await + .expect("Session::open should succeed") +} + /// Read the `disposition` sent on the recorded POST /statements request. async fn recorded_execute_disposition(server: &MockServer) -> String { let recorded = server @@ -195,6 +213,26 @@ fn running_body(statement_id: &str) -> String { .to_string() } +/// Delay only the first execute response. +struct DelayedFirstExecute { + first: String, + later: String, + first_delay: Duration, + calls: AtomicUsize, +} + +impl Respond for DelayedFirstExecute { + fn respond(&self, _request: &Request) -> ResponseTemplate { + if self.calls.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(200) + .set_body_string(self.first.clone()) + .set_delay(self.first_delay) + } else { + ResponseTemplate::new(200).set_body_string(self.later.clone()) + } + } +} + /// Poll `server.received_requests()` until `expected` `DELETE`s to the /// given statement endpoint are observed, or `timeout` elapses; returns /// the final observed count. Mirrors the metadata suite's helper: for a @@ -325,6 +363,14 @@ async fn drain(stream: &mut databricks_sql_kernel::ResultStream) -> Vec) { + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.message, "Client query timeout expired"); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert!(!error.retryable); + assert_eq!(error.query_id.as_deref(), query_id); +} + // ─── Tests ────────────────────────────────────────────────────────── #[tokio::test] @@ -1339,3 +1385,423 @@ async fn execute_succeeded_inline_still_closes_statement() { ); // `_close` also verifies expect(1) when it drops at end of scope. } + +// ─── Client query timeout ─────────────────────────────────────────── + +#[tokio::test] +async fn client_timeout_covers_initial_post_and_statement_is_immediately_reusable() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("n", vec![1]); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(DelayedFirstExecute { + first: running_body("stmt-delayed-post"), + later: closed_inline_body("stmt-reused", &batch), + first_delay: Duration::from_millis(500), + calls: AtomicUsize::new(0), + }) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + + let started = Instant::now(); + let error = stmt + .execute_with_timeout(Duration::from_millis(75)) + .await + .err() + .expect("the delayed initial POST must consume the client deadline"); + assert_client_query_timeout(&error, None); + assert!( + started.elapsed() < Duration::from_millis(400), + "the 500ms POST must be abandoned near the 75ms deadline" + ); + + for timeout in [Duration::ZERO, Duration::MAX, MAX_CLIENT_QUERY_TIMEOUT] { + let exec = stmt + .execute_with_timeout(timeout) + .await + .expect("statement must be reusable after an initial-POST timeout"); + exec.close().await.expect("close reused execution"); + } + + let oversized = MAX_CLIENT_QUERY_TIMEOUT + .checked_add(Duration::from_millis(1)) + .unwrap(); + let error = stmt + .execute_with_timeout(oversized) + .await + .err() + .expect("a finite timeout above the public maximum must be rejected"); + assert_eq!(error.code, ErrorCode::InvalidArgument); + + let execute_posts = server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .filter(|request| { + request.method == wiremock::http::Method::POST + && request.url.path() == "/api/2.0/sql/statements" + }) + .count(); + assert_eq!( + execute_posts, 4, + "range validation must reject before issuing a fifth execute RPC" + ); +} + +#[tokio::test] +async fn client_timeout_covers_poll_sleep_and_cleanup_does_not_delay_return() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let running = Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string(running_body("stmt-poll-sleep"))) + .expect(1) + .mount_as_scoped(&server) + .await; + let no_status_poll = Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-poll-sleep")) + .respond_with(ResponseTemplate::new(200).set_body_string(running_body("stmt-poll-sleep"))) + .expect(0) + .mount_as_scoped(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-poll-sleep/cancel")) + .respond_with( + ResponseTemplate::new(404) + .set_body_string("already gone") + .set_delay(Duration::from_millis(750)), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-poll-sleep")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + + let started = Instant::now(); + let error = stmt + .execute_with_timeout(Duration::from_millis(75)) + .await + .err() + .expect("the first 500ms poll sleep must be bounded"); + assert_client_query_timeout(&error, Some("stmt-poll-sleep")); + assert!( + started.elapsed() < Duration::from_millis(400), + "slow cancel/close cleanup must run in the background" + ); + drop(no_status_poll); + drop(running); + + let batch = int64_batch("n", vec![2]); + mount_execute(&server, closed_inline_body("stmt-after-timeout", &batch)).await; + let exec = stmt + .execute_with_timeout(Duration::ZERO) + .await + .expect("statement must be reusable before background cleanup finishes"); + exec.close().await.expect("close reused execution"); + + let closes = wait_for_close_delete(&server, "stmt-poll-sleep", 1, Duration::from_secs(2)).await; + assert_eq!(closes, 1, "timeout cleanup must eventually close the query"); + let cancel_count = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|request| { + request.method == wiremock::http::Method::POST + && request.url.path() == "/api/2.0/sql/statements/stmt-poll-sleep/cancel" + }) + .count(); + assert_eq!(cancel_count, 1, "timeout cleanup must not dispatch twice"); +} + +#[tokio::test] +async fn client_timeout_allows_inflight_terminal_status_to_win_during_grace() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_execute(&server, running_body("stmt-delayed-terminal")).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-delayed-terminal")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(failed_body( + "stmt-delayed-terminal", + "server failure", + "42000", + )) + .set_delay(Duration::from_millis(600)), + ) + .expect(1) + .mount(&server) + .await; + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT broken"); + let error = stmt + .execute_with_timeout(Duration::from_millis(700)) + .await + .err() + .expect("the terminal server failure must win during status grace"); + assert_eq!(error.code, ErrorCode::SqlError); + assert_eq!(error.message, "server failure. SQLSTATE: 42000"); + assert_eq!(error.sql_state.as_deref(), Some("42000")); + assert_eq!(error.query_id.as_deref(), Some("stmt-delayed-terminal")); + + let closes = + wait_for_close_delete(&server, "stmt-delayed-terminal", 1, Duration::from_secs(1)).await; + assert_eq!(closes, 1); +} + +#[tokio::test] +async fn client_timeout_does_not_repoll_after_nonterminal_status_during_grace() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_execute(&server, running_body("stmt-running-during-grace")).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-running-during-grace")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(running_body("stmt-running-during-grace")) + .set_delay(Duration::from_millis(600)), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path( + "/api/2.0/sql/statements/stmt-running-during-grace/cancel", + )) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT still_running"); + let error = stmt + .execute_with_timeout(Duration::from_millis(700)) + .await + .err() + .expect("a non-terminal response during grace must preserve the timeout"); + assert_client_query_timeout(&error, Some("stmt-running-during-grace")); + + let closes = wait_for_close_delete( + &server, + "stmt-running-during-grace", + 1, + Duration::from_secs(1), + ) + .await; + assert_eq!(closes, 1); + server.verify().await; +} + +#[tokio::test] +async fn client_timeout_caps_inflight_status_grace() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_execute(&server, running_body("stmt-stalled-status")).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-stalled-status")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(failed_body("stmt-stalled-status", "too late", "42000")) + .set_delay(Duration::from_secs(10)), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-stalled-status/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT stalled_status"); + let started = Instant::now(); + let error = stmt + .execute_with_timeout(Duration::from_millis(700)) + .await + .err() + .expect("a status request must not outlive the fixed grace window"); + let elapsed = started.elapsed(); + assert_client_query_timeout(&error, Some("stmt-stalled-status")); + assert!( + elapsed >= Duration::from_secs(5) && elapsed < Duration::from_secs(9), + "timeout returned after {elapsed:?}, expected the five-second status grace" + ); + + let closes = + wait_for_close_delete(&server, "stmt-stalled-status", 1, Duration::from_secs(1)).await; + assert_eq!(closes, 1); + server.verify().await; +} + +#[tokio::test] +async fn client_timeout_is_cumulative_across_retry_backoff() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(429).append_header("Retry-After", "0")) + .mount(&server) + .await; + + let mut http = HttpConfig::default(); + http.retry_min_wait = Duration::from_millis(250); + http.retry_max_wait = Duration::from_millis(250); + http.retry_max_retries = 1; + let session = open_session_with_http(&server, http).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + + let error = stmt + .execute_with_timeout(Duration::from_millis(75)) + .await + .err() + .expect("client deadline must interrupt retry backoff"); + assert_client_query_timeout(&error, None); + let execute_posts = server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .filter(|request| { + request.method == wiremock::http::Method::POST + && request.url.path() == "/api/2.0/sql/statements" + }) + .count(); + assert_eq!(execute_posts, 1, "no retry may start after the deadline"); +} + +#[tokio::test] +async fn terminal_error_mapping_is_inside_the_client_timeout_phase() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_execute( + &server, + failed_body("stmt-terminal-error", "bad SQL", "42000"), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT broken"); + let error = stmt + .execute_with_timeout(Duration::from_secs(1)) + .await + .err() + .expect("terminal FAILED must be mapped before materialisation"); + assert_eq!(error.code, ErrorCode::SqlError); + assert_eq!(error.sql_state.as_deref(), Some("42000")); + assert_eq!(error.query_id.as_deref(), Some("stmt-terminal-error")); +} + +#[tokio::test] +async fn client_timeout_excludes_cloudfetch_materialisation() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let statement_id = "stmt-slow-materialisation"; + let chunk_path = format!("/cloud-fetch/{statement_id}/chunk-0.arrow"); + let chunk_url = format!("{}{}", server.uri(), chunk_path); + let batch = int64_batch("n", vec![42]); + let ipc = arrow_ipc_bytes(&batch); + let execute_body = json!({ + "statement_id": statement_id, + "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": 1, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "external_links": [{ + "external_link": chunk_url, + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": 0, + "row_offset": 0, + "row_count": 1, + "byte_count": ipc.len() as i64, + }], + }, + }) + .to_string(); + mount_execute(&server, execute_body).await; + Mock::given(method("GET")) + .and(path(chunk_path.as_str())) + .respond_with( + ResponseTemplate::new(200) + .set_body_bytes(ipc) + .set_delay(Duration::from_millis(700)), + ) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 42 AS n"); + let started = Instant::now(); + let mut exec = stmt + .execute_with_timeout(Duration::from_millis(300)) + .await + .expect("CloudFetch reader materialisation must be outside the deadline"); + assert!( + started.elapsed() >= Duration::from_millis(650), + "execute should wait for delayed reader materialisation after execution is terminal" + ); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches.len(), 1); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 42 + ); + exec.close().await.expect("close"); +}