From 94b4cbb24af611e81dd6b19a035bef298f96ea8d Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 14 Sep 2026 23:01:11 +0000 Subject: [PATCH 1/8] feat(statement): add client query timeout Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/spec-v0.md | 13 +- include/databricks_kernel.h | 33 ++- src/c_abi/statement.rs | 64 ++++- src/client/sea.rs | 127 ++++++--- src/client/transport.rs | 7 +- src/lib.rs | 1 + src/reader/cloudfetch/link_fetcher.rs | 19 +- src/reader/mod.rs | 1 + src/session.rs | 14 + src/statement/executed_async.rs | 14 +- src/statement/mod.rs | 2 + src/statement/mutable.rs | 55 +++- src/statement/timeout.rs | 219 +++++++++++++++ tests/c/session_smoke.c | 5 + tests/v0_c_abi_canceller_wiremock.rs | 141 +++++++++- tests/v0_execute_wiremock.rs | 387 +++++++++++++++++++++++++- 16 files changed, 1024 insertions(+), 78 deletions(-) create mode 100644 src/statement/timeout.rs diff --git a/docs/spec-v0.md b/docs/spec-v0.md index 16fd8a75..54110d1f 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 no client query deadline. Auto-cancels + /// + closes any prior handle. Spec is unchanged; can be re-executed. pub async fn execute(&mut self) -> Result; + /// As execute(), with one client-side deadline through terminal-state + /// mapping. Zero and Duration::MAX disable the deadline; result + /// materialisation and fetching are outside it. + 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..a9ac20c0 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 @@ -706,11 +709,39 @@ KernelStatusCode kernel_statement_set_query_tags(kernel_statement_t* stmt, /* * Wait-for-result execution. On success, `*out` holds an executed handle - * released with `kernel_executed_statement_close`. + * released with `kernel_executed_statement_close`. This entry point has no + * client query deadline; use kernel_statement_execute_with_timeout_ms to apply + * one. */ KernelStatusCode kernel_statement_execute(kernel_statement_t* stmt, kernel_executed_statement_t** out); +/* + * Wait-for-result execution with a client-side query deadline. `timeout_ms` is + * an unsigned millisecond duration; 0 disables the deadline. Positive values + * must be <= DATABRICKS_KERNEL_MAX_CLIENT_QUERY_TIMEOUT_MS or InvalidArgument is + * returned before any RPC. The value is snapshotted per call and never sent as + * SEA wait_timeout or a server-side statement timeout. + * + * The deadline is captured on function entry and covers C-ABI runtime queueing, + * the initial ExecuteStatement request, execution/status retries and backoff, + * poll sleeps, GetStatementStatus requests, and terminal-state mapping. It ends + * before DML-count, reader/schema/result materialisation, result fetching, + * CloudFetch downloads, or post-terminal close work. + * + * On expiry this returns KernelStatusCode_Timeout and the last error carries + * SQLSTATE HYT00, retryable=false, and the query id when one was observed. + * `*out` is initialized to NULL and remains NULL on every failure. Server cancel + * and close are bounded best-effort background work and never delay this call. + * The statement 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..f9e7768e 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -45,6 +45,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 +452,66 @@ pub unsafe extern "C" fn kernel_statement_execute( return store_invalid_arg("kernel_statement_execute: out must not be null"); } + execute_with_deadline(stmt, None, out) +} + +/// Wait-for-result execution with an execution-scoped client deadline. +/// +/// `timeout_ms == 0` disables the client deadline. A positive timeout covers +/// C-ABI runtime admission, the initial ExecuteStatement request, retries and +/// backoff, poll sleeps, status requests, and terminal-state mapping. Reader / +/// schema materialisation and result fetching are outside it. The absolute +/// deadline is captured on this native entry thread before work is queued onto +/// the kernel runtime. +/// +/// On expiry this returns [`KernelStatusCode::Timeout`], stores a non-retryable +/// `HYT00` error (including the query id when already known), leaves `*out` +/// null, and admits best-effort cancel/close work without waiting for it. +/// +/// # 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 { + // Capture the monotonic origin at native entry, before validation, runtime + // initialisation, or queueing. Validation remains synchronous and RPC-free, + // but any time it consumes is still part of a positive caller budget. + 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", + ); + }; + // Validate against the same finite range as the Rust surface, then derive + // from the instant captured above. No runtime work or RPC precedes this. + let deadline = match crate::statement::timeout::deadline_from_timeout_at( + std::time::Duration::from_millis(timeout_ms), + entered_at, + ) { + Ok(deadline) => deadline, + Err(error) => return store_and_code(error), + }; + + execute_with_deadline(stmt, deadline, out) +} + +/// Shared sync-execute bridge after pointer/range validation and optional +/// deadline capture. The timeout entry point initializes `out` to null before +/// calling this helper; the legacy entry point deliberately preserves its +/// existing failure-path out-parameter behavior. +unsafe fn execute_with_deadline( + stmt: &mut Statement, + deadline: Option, + 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 +520,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_deadline(deadline).await }) }); match executed { Ok(exec) => { diff --git a/src/client/sea.rs b/src/client/sea.rs index 094b53f4..fba0755e 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -95,6 +95,17 @@ enum TerminalExecutionOutcome { Failed(Error), } +/// Failure while reaching a terminal response, plus the statement id when the +/// initial execute response had already published one. Keeping the id beside +/// the error lets the caller run orphan cleanup after the timed execution phase +/// has ended, so cleanup latency can neither consume the client deadline nor +/// replace the originating error with a client timeout. +#[derive(Debug)] +struct TerminalExecutionFailure { + statement_id: Option, + error: Error, +} + /// SEA client for the Databricks SQL Statement Execution API. /// /// This client implements the `Transport` trait using REST endpoints. @@ -471,23 +482,18 @@ 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. + /// schema extraction, or DML-count materialisation. Its caller applies the one + /// per-execution client deadline around the whole execute-and-poll future. async fn wait_for_terminal( &self, response: ExecuteResponse, ) -> Result<(ExecuteResponse, bool)> { - let start = 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 { - return Err(Error::timeout().message("Statement execution timed out")); - } - tokio::time::sleep(self.config.poll_interval).await; debug!( statement_id = %current_response.statement_id, @@ -671,10 +677,14 @@ impl SeaRestTransport { sql: &str, params: &ExecuteParams, request_type: RequestType, - ) -> Result { + ) -> 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 +695,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) + .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 +764,7 @@ impl SeaRestTransport { sql: &str, params: &ExecuteParams, request_type: RequestType, + client_deadline: Option, ) -> Result { // After call_execute_api succeeds, the SEA statement is open // on the server. Any subsequent failure before we hand back @@ -775,9 +785,40 @@ 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 execution = self.execute_to_terminal(session_id, sql, params, request_type); + let execution_result = match client_deadline { + Some(deadline) => { + match tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), execution) + .await + { + Ok(result) => result, + Err(_) => { + let query_id = params + .inflight_id_observer + .as_ref() + .and_then(|slot| slot.try_lock().ok().and_then(|id| id.clone())); + return Err(crate::statement::timeout::client_query_timeout_error( + query_id.as_deref(), + )); + } + } + } + None => execution.await, + }; + let terminal = match execution_result { + Ok(terminal) => terminal, + Err(TerminalExecutionFailure { + statement_id, + 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 +1068,16 @@ impl Transport for SeaRestTransport { session_id: &str, sql: &str, params: &ExecuteParams, + client_deadline: Option, ) -> Result { - self.execute_and_read(session_id, sql, params, RequestType::ExecuteStatement) - .await + self.execute_and_read( + session_id, + sql, + params, + RequestType::ExecuteStatement, + client_deadline, + ) + .await } async fn submit_statement( @@ -1397,6 +1445,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1417,6 +1466,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1441,6 +1491,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1464,6 +1515,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1483,6 +1535,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1501,6 +1554,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1525,6 +1579,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1543,6 +1598,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1579,6 +1635,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, + None, ) .await } @@ -1744,6 +1801,7 @@ mod tests { "UPDATE t SET x = x + 1", &ExecuteParams::default(), RequestType::ExecuteStatement, + None, ) .await .expect("polled DML execution must succeed"); @@ -1825,7 +1883,7 @@ mod tests { } #[tokio::test] - async fn execute_to_terminal_timeout_preserves_error_and_cleanup() { + async fn synchronous_execute_has_no_hidden_poll_timeout() { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -1842,12 +1900,10 @@ mod tests { .await; Mock::given(method("GET")) .and(path("/api/2.0/sql/statements/stmt-timeout")) - .respond_with(ResponseTemplate::new(200).set_body_json(running)) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .and(path("/api/2.0/sql/statements/stmt-timeout")) - .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(succeeded_inline_dml_body("stmt-timeout", 1)), + ) .expect(1) .mount(&server) .await; @@ -1860,7 +1916,7 @@ mod tests { ..TransportConfig::default() }, ); - let error = match transport + let terminal = transport .execute_to_terminal( "sess-test", "SELECT 1", @@ -1868,13 +1924,12 @@ mod tests { RequestType::ExecuteStatement, ) .await - { - Ok(_) => panic!("perpetually running statement must time out"), - Err(error) => error, - }; + .expect("sync execution must not inherit the async handle's poll timeout"); - assert_eq!(error.code, crate::kernel_error::ErrorCode::Timeout); - assert_eq!(error.message, "Statement execution timed out"); + assert!(matches!( + terminal.outcome, + TerminalExecutionOutcome::Succeeded(_) + )); server.verify().await; } diff --git a/src/client/transport.rs b/src/client/transport.rs index a65e815d..1b5c2719 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -31,7 +31,7 @@ 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 ──────────────────────────────────────── @@ -43,7 +43,9 @@ use std::time::Duration; /// never reads it. #[derive(Debug, Clone)] pub(crate) struct TransportConfig { - /// Maximum time to wait for statement completion (default: 600s). + /// Maximum time an async handle's `await_result` waits for statement + /// completion (default: 600s). Synchronous `Statement::execute()` has no + /// hidden ceiling; its optional client deadline is supplied per execution. pub poll_timeout: Duration, /// Interval between status polls (default: 500ms). pub poll_interval: Duration, @@ -295,6 +297,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { session_id: &str, sql: &str, params: &ExecuteParams, + client_deadline: Option, ) -> 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..2d0511eb 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1136,6 +1136,7 @@ mod tests { _session_id: &str, _sql: &str, _params: &ExecuteParams, + _client_deadline: Option, ) -> 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(), None) .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(), None) .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(), None) .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(), None) .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(), None) .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(), None) .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(), None) .await } @@ -1317,7 +1318,7 @@ mod tests { _schema: &str, _table: &str, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), None) .await } @@ -1331,7 +1332,7 @@ mod tests { _foreign_schema: &str, _foreign_table: &str, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default()) + self.execute_statement("", "", &ExecuteParams::default(), None) .await } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 1c14d82a..378cb560 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1480,6 +1480,7 @@ mod tests { _: &str, _: &str, _: &ExecuteParams, + _: Option, ) -> Result { unreachable!() } diff --git a/src/session.rs b/src/session.rs index 80b9b6c2..e4e1cbe5 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,10 @@ pub(crate) struct SessionInner { /// (e.g. the [`Drop`] impl below). runtime_handle: tokio::runtime::Handle, + /// Bounded, non-blocking admission for best-effort cancel/close work after + /// a client query deadline expires. + 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 +171,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 +425,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..34bc00e9 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -437,9 +437,9 @@ 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). + /// session's [`crate::client::TransportConfig`] cadence. This async-handle + /// ceiling is separate from the optional per-call client deadline on + /// synchronous `Statement::execute_with_timeout()`. /// /// **Drop-cancellation.** Dropping the returned future before /// it resolves to a terminal state (e.g. a winning branch in @@ -451,8 +451,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 +459,8 @@ 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. + // Poll cadence + ceiling come from the transport's config. The sync + // execute path instead takes an optional execution-scoped deadline. 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..f3fb08bd 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -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, Instant}; 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 has no client query deadline; + /// use [`Statement::execute_with_timeout`] to apply one. /// /// 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_deadline(None).await + } + + /// Wait-for-result execution bounded by one client-side deadline. + /// + /// The timeout starts at method entry and covers the initial execute RPC, + /// retry/backoff, polling sleeps and status RPCs through terminal-state + /// mapping. Result/schema materialisation and fetching happen after that + /// boundary and are not timed. `Duration::ZERO` and `Duration::MAX` disable + /// the client deadline; network and server-side timeouts remain independent. + pub async fn execute_with_timeout(&mut self, timeout: Duration) -> Result { + let deadline = crate::statement::timeout::deadline_from_timeout(timeout)?; + self.execute_with_deadline(deadline).await + } + + /// Absolute-deadline form used by the C ABI, which captures the deadline + /// before enqueueing work on its runtime. + pub(crate) async fn execute_with_deadline( + &mut self, + client_deadline: Option, + ) -> 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,31 @@ 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, + client_deadline, + ) + .await + { + Ok(result) => result, + Err(error) if crate::statement::timeout::is_client_query_timeout(&error) => { + // The transport future has been abandoned at its deadline. + // It cannot safely keep borrowing this reusable Statement; + // hand only its immutable, attempt-local id to bounded + // background cleanup and prevent the generic drop guard from + // dispatching a duplicate cancel. + 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 +456,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..f2cf17b2 --- /dev/null +++ b/src/statement/timeout.rs @@ -0,0 +1,219 @@ +// 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 client query timeout accepted by the kernel, in milliseconds. +/// +/// This is the largest whole-millisecond duration representable by a signed +/// 64-bit nanosecond budget. Keeping the public C-ABI range within this bound +/// gives every binding one portable limit and leaves deadline construction free +/// of integer wraparound. +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"; + +/// Bound background work created by client query timeouts per session. +/// +/// Timeout cleanup is best effort. Admission must never queue behind other +/// cleanup because doing so would put that wait back on the foreground timeout +/// path. Sixty-four concurrent attempts is deliberately generous for a single +/// session while still placing a hard ceiling on abandoned work. +const MAX_CONCURRENT_TIMEOUT_CLEANUPS: usize = 64; + +/// Fresh budget for the detached cancel-then-close sequence. +/// +/// This is independent of the expired query deadline. It bounds resources held +/// by a failed or stalled cleanup without delaying the caller-visible timeout. +const TIMEOUT_CLEANUP_BUDGET: Duration = Duration::from_secs(30); + +/// Convert a public relative timeout into one absolute monotonic deadline. +/// +/// `Duration::ZERO` and `Duration::MAX` are explicit unlimited sentinels on the +/// Rust surface. Other values above [`MAX_CLIENT_QUERY_TIMEOUT`] are rejected so +/// Rust and C callers share the same finite range. +pub(crate) fn deadline_from_timeout(timeout: Duration) -> Result> { + deadline_from_timeout_at(timeout, Instant::now()) +} + +/// Convert a relative timeout using a caller-supplied monotonic entry instant. +/// The C ABI uses this form so runtime initialization and queueing consume the +/// same budget captured at its native boundary. +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")) +} + +/// Build the caller-visible error for an expired client execution deadline. +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 +} + +/// Distinguish the local execution deadline from network/server timeout errors. +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, non-blocking admission control for timeout cleanup tasks. +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)), + } + } + + /// Admit and spawn best-effort cancel/close work without ever waiting for + /// queue capacity. Saturation intentionally drops the cleanup request. + 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::*; + + #[test] + fn zero_and_duration_max_are_unlimited() { + assert_eq!(deadline_from_timeout(Duration::ZERO).unwrap(), None); + assert_eq!(deadline_from_timeout(Duration::MAX).unwrap(), None); + } + + #[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..d043ca7a 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -12,11 +12,12 @@ // 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 statement execution controls: the detached +//! statement canceller (`kernel_statement_canceller_new` / `_cancel` / `_free`) +//! and the execution-scoped client query timeout. 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: //! //! - `canceller_cancels_a_running_execute_from_another_thread`: the headline //! contract — one thread blocks in `kernel_statement_execute` while another @@ -34,6 +35,8 @@ //! 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 status/error fields, +//! null output, finite-range validation, unlimited values, cleanup, 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 +47,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 +60,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 +133,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 +1629,123 @@ 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 + ); + + // The initial response publishes an id and enters the 500ms poll sleep. + // A 75ms client deadline must return promptly and null a non-null sentinel. + 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-of-range values fail before any RPC and still clear the output. + 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()); + + // The maximum finite value and zero (unlimited) are both accepted, and + // the same statement is reusable immediately after its timed execution. + 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..2d47ff57 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,28 @@ fn running_body(statement_id: &str) -> String { .to_string() } +/// Return a delayed response on the first execute and an immediate response on +/// later calls. This lets timeout tests prove the same mutable Statement can be +/// reused after its initial POST future is abandoned. +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 +365,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 +1387,336 @@ 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" + ); + + // Both public unlimited sentinels and the largest finite value remain usable + // after the timed future was dropped before a statement id was observed. + 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); + + // Reuse while cleanup for the timed-out id is still in flight. + 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_covers_delayed_terminal_status_and_mapping() { + 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; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-delayed-terminal/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 broken"); + let error = stmt + .execute_with_timeout(Duration::from_millis(700)) + .await + .err() + .expect("deadline must expire while the terminal status RPC is in flight"); + assert_client_query_timeout(&error, 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_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"); +} From 68bd788cb2397eaf03764bb1a3f16e106cac6c92 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 14 Sep 2026 23:34:34 +0000 Subject: [PATCH 2/8] fix(client): retain metadata polling timeout Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/spec-v0.md | 8 +-- include/databricks_kernel.h | 31 ++++------ src/c_abi/statement.rs | 28 +++------ src/client/sea.rs | 89 ++++++++++++++++++++++------ src/client/transport.rs | 4 +- src/session.rs | 3 +- src/statement/executed_async.rs | 8 +-- src/statement/mutable.rs | 22 +++---- src/statement/timeout.rs | 34 +++-------- tests/v0_c_abi_canceller_wiremock.rs | 16 +---- tests/v0_execute_wiremock.rs | 7 +-- 11 files changed, 115 insertions(+), 135 deletions(-) diff --git a/docs/spec-v0.md b/docs/spec-v0.md index 54110d1f..3a0dafa0 100644 --- a/docs/spec-v0.md +++ b/docs/spec-v0.md @@ -644,13 +644,11 @@ impl Statement { /// Read-only access (for logging or assertion). pub fn spec_ref(&self) -> &StatementSpec; - /// Wait-for-result execution with no client query deadline. Auto-cancels - /// + closes any prior handle. Spec is unchanged; can be re-executed. + /// Wait-for-result execution without a client deadline. pub async fn execute(&mut self) -> Result; - /// As execute(), with one client-side deadline through terminal-state - /// mapping. Zero and Duration::MAX disable the deadline; result - /// materialisation and fetching are outside it. + /// Execute with a client deadline through terminal-state mapping. + /// Zero and Duration::MAX disable it; result materialisation is excluded. pub async fn execute_with_timeout( &mut self, timeout: std::time::Duration, diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index a9ac20c0..37a3632c 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -708,32 +708,21 @@ 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`. This entry point has no - * client query deadline; use kernel_statement_execute_with_timeout_ms to apply - * one. + * Wait-for-result execution without a client query 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 query deadline. `timeout_ms` is - * an unsigned millisecond duration; 0 disables the deadline. Positive values - * must be <= DATABRICKS_KERNEL_MAX_CLIENT_QUERY_TIMEOUT_MS or InvalidArgument is - * returned before any RPC. The value is snapshotted per call and never sent as - * SEA wait_timeout or a server-side statement timeout. - * - * The deadline is captured on function entry and covers C-ABI runtime queueing, - * the initial ExecuteStatement request, execution/status retries and backoff, - * poll sleeps, GetStatementStatus requests, and terminal-state mapping. It ends - * before DML-count, reader/schema/result materialisation, result fetching, - * CloudFetch downloads, or post-terminal close work. - * - * On expiry this returns KernelStatusCode_Timeout and the last error carries - * SQLSTATE HYT00, retryable=false, and the query id when one was observed. - * `*out` is initialized to NULL and remains NULL on every failure. Server cancel - * and close are bounded best-effort background work and never delay this call. - * The statement remains reusable. + * Wait-for-result execution with a client-side deadline in milliseconds. + * Zero disables it; values above DATABRICKS_KERNEL_MAX_CLIENT_QUERY_TIMEOUT_MS + * return InvalidArgument. The deadline starts on entry, covers execution + * through terminal-state mapping, and excludes result materialisation and + * fetching. It 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. diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index f9e7768e..ccee8550 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -455,18 +455,11 @@ pub unsafe extern "C" fn kernel_statement_execute( execute_with_deadline(stmt, None, out) } -/// Wait-for-result execution with an execution-scoped client deadline. +/// Wait-for-result execution with a client deadline in milliseconds. /// -/// `timeout_ms == 0` disables the client deadline. A positive timeout covers -/// C-ABI runtime admission, the initial ExecuteStatement request, retries and -/// backoff, poll sleeps, status requests, and terminal-state mapping. Reader / -/// schema materialisation and result fetching are outside it. The absolute -/// deadline is captured on this native entry thread before work is queued onto -/// the kernel runtime. -/// -/// On expiry this returns [`KernelStatusCode::Timeout`], stores a non-retryable -/// `HYT00` error (including the query id when already known), leaves `*out` -/// null, and admits best-effort cancel/close work without waiting for it. +/// Zero disables the deadline. It starts at native entry, ends after terminal +/// mapping, and excludes result materialisation. Timeout returns +/// [`KernelStatusCode::Timeout`] with `HYT00` and leaves `*out` null. /// /// # Safety /// `stmt` must be a live statement handle; `out` must be writable. @@ -476,9 +469,7 @@ pub unsafe extern "C" fn kernel_statement_execute_with_timeout_ms( timeout_ms: u64, out: *mut *mut kernel_executed_statement_t, ) -> KernelStatusCode { - // Capture the monotonic origin at native entry, before validation, runtime - // initialisation, or queueing. Validation remains synchronous and RPC-free, - // but any time it consumes is still part of a positive caller budget. + // 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() { @@ -490,8 +481,6 @@ pub unsafe extern "C" fn kernel_statement_execute_with_timeout_ms( "kernel_statement_execute_with_timeout_ms: stmt must not be null", ); }; - // Validate against the same finite range as the Rust surface, then derive - // from the instant captured above. No runtime work or RPC precedes this. let deadline = match crate::statement::timeout::deadline_from_timeout_at( std::time::Duration::from_millis(timeout_ms), entered_at, @@ -503,10 +492,9 @@ pub unsafe extern "C" fn kernel_statement_execute_with_timeout_ms( execute_with_deadline(stmt, deadline, out) } -/// Shared sync-execute bridge after pointer/range validation and optional -/// deadline capture. The timeout entry point initializes `out` to null before -/// calling this helper; the legacy entry point deliberately preserves its -/// existing failure-path out-parameter behavior. +/// Run synchronous execution after entry-point validation. +/// +/// The timeout entry point clears `out`; the legacy entry point does not. unsafe fn execute_with_deadline( stmt: &mut Statement, deadline: Option, diff --git a/src/client/sea.rs b/src/client/sea.rs index fba0755e..518f302f 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -95,11 +95,7 @@ enum TerminalExecutionOutcome { Failed(Error), } -/// Failure while reaching a terminal response, plus the statement id when the -/// initial execute response had already published one. Keeping the id beside -/// the error lets the caller run orphan cleanup after the timed execution phase -/// has ended, so cleanup latency can neither consume the client deadline nor -/// replace the originating error with a client timeout. +/// Execution failure and any statement id available for cleanup. #[derive(Debug)] struct TerminalExecutionFailure { statement_id: Option, @@ -479,21 +475,22 @@ 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. Its caller applies the one - /// per-execution client deadline around the whole execute-and-poll future. + /// Poll until the server reports a raw terminal state. async fn wait_for_terminal( &self, response: ExecuteResponse, + poll_timeout: Option, ) -> Result<(ExecuteResponse, bool)> { + 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 poll_timeout.is_some_and(|timeout| started.elapsed() > timeout) { + return Err(Error::timeout().message("Statement execution timed out")); + } tokio::time::sleep(self.config.poll_interval).await; debug!( statement_id = %current_response.statement_id, @@ -695,13 +692,15 @@ impl SeaRestTransport { } } - let (response, response_from_poll) = - self.wait_for_terminal(response) - .await - .map_err(|error| TerminalExecutionFailure { - statement_id: Some(statement_id.clone()), - error, - })?; + let poll_timeout = + (request_type == RequestType::ExecuteMetadataQuery).then_some(self.config.poll_timeout); + let (response, response_from_poll) = self + .wait_for_terminal(response, poll_timeout) + .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), @@ -1933,6 +1932,62 @@ mod tests { 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, + None, + ) + .await + { + Ok(_) => panic!("metadata execution must retain its poll timeout"), + Err(error) => error, + }; + + assert_eq!(error.code, crate::kernel_error::ErrorCode::Timeout); + assert_eq!(error.message, "Statement execution timed out"); + server.verify().await; + } + #[test] fn test_base_url() { let client = create_test_client(); diff --git a/src/client/transport.rs b/src/client/transport.rs index 1b5c2719..06cca941 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -43,9 +43,7 @@ use std::time::{Duration, Instant}; /// never reads it. #[derive(Debug, Clone)] pub(crate) struct TransportConfig { - /// Maximum time an async handle's `await_result` waits for statement - /// completion (default: 600s). Synchronous `Statement::execute()` has no - /// hidden ceiling; its optional client deadline is supplied per execution. + /// Maximum wait for async-handle and metadata completion (default: 600s). pub poll_timeout: Duration, /// Interval between status polls (default: 500ms). pub poll_interval: Duration, diff --git a/src/session.rs b/src/session.rs index e4e1cbe5..74214243 100644 --- a/src/session.rs +++ b/src/session.rs @@ -101,8 +101,7 @@ pub(crate) struct SessionInner { /// (e.g. the [`Drop`] impl below). runtime_handle: tokio::runtime::Handle, - /// Bounded, non-blocking admission for best-effort cancel/close work after - /// a client query deadline expires. + /// Admission control for timeout cleanup. timeout_cleanup: TimeoutCleanupManager, /// Tracing span tagged with `session_id`. Every public method diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 34bc00e9..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. This async-handle - /// ceiling is separate from the optional per-call client deadline on - /// synchronous `Statement::execute_with_timeout()`. + /// 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 @@ -459,8 +457,6 @@ impl ExecutedAsyncStatement { let result = async { self.valid.check()?; - // Poll cadence + ceiling come from the transport's config. The sync - // execute path instead takes an optional execution-scoped deadline. let cfg = self.session.transport().poll_config(); let start = std::time::Instant::now(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index f3fb08bd..0aba3c45 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -306,8 +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. This entry point has no client query deadline; - /// use [`Statement::execute_with_timeout`] to apply one. + /// longer than 10s. Use [`Statement::execute_with_timeout`] to add a client + /// deadline. /// /// If a prior executed handle is still tracked by this `Statement`, /// the kernel spawns a fire-and-forget `CloseStatement` against it @@ -320,20 +320,16 @@ impl Statement { self.execute_with_deadline(None).await } - /// Wait-for-result execution bounded by one client-side deadline. + /// Execute with a client deadline through terminal-state mapping. /// - /// The timeout starts at method entry and covers the initial execute RPC, - /// retry/backoff, polling sleeps and status RPCs through terminal-state - /// mapping. Result/schema materialisation and fetching happen after that - /// boundary and are not timed. `Duration::ZERO` and `Duration::MAX` disable - /// the client deadline; network and server-side timeouts remain independent. + /// Result materialisation is excluded. `Duration::ZERO` and `Duration::MAX` + /// disable 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_deadline(deadline).await } - /// Absolute-deadline form used by the C ABI, which captures the deadline - /// before enqueueing work on its runtime. + /// Absolute-deadline form used by the C ABI. pub(crate) async fn execute_with_deadline( &mut self, client_deadline: Option, @@ -385,11 +381,7 @@ impl Statement { { Ok(result) => result, Err(error) if crate::statement::timeout::is_client_query_timeout(&error) => { - // The transport future has been abandoned at its deadline. - // It cannot safely keep borrowing this reusable Statement; - // hand only its immutable, attempt-local id to bounded - // background cleanup and prevent the generic drop guard from - // dispatching a duplicate cancel. + // Cleanup owns only the attempt id; defuse the duplicate guard. guard.defuse(); self.session .dispatch_timeout_cleanup(error.query_id.clone()); diff --git a/src/statement/timeout.rs b/src/statement/timeout.rs index f2cf17b2..35fa6eaf 100644 --- a/src/statement/timeout.rs +++ b/src/statement/timeout.rs @@ -20,12 +20,7 @@ use crate::klog::warn; use std::sync::Arc; use std::time::{Duration, Instant}; -/// Largest finite client query timeout accepted by the kernel, in milliseconds. -/// -/// This is the largest whole-millisecond duration representable by a signed -/// 64-bit nanosecond budget. Keeping the public C-ABI range within this bound -/// gives every binding one portable limit and leaves deadline construction free -/// of integer wraparound. +/// 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`]. @@ -33,32 +28,20 @@ pub const MAX_CLIENT_QUERY_TIMEOUT: Duration = Duration::from_millis(MAX_CLIENT_ pub(crate) const CLIENT_QUERY_TIMEOUT_SQL_STATE: &str = "HYT00"; -/// Bound background work created by client query timeouts per session. -/// -/// Timeout cleanup is best effort. Admission must never queue behind other -/// cleanup because doing so would put that wait back on the foreground timeout -/// path. Sixty-four concurrent attempts is deliberately generous for a single -/// session while still placing a hard ceiling on abandoned work. +/// Maximum detached cleanup tasks per session. const MAX_CONCURRENT_TIMEOUT_CLEANUPS: usize = 64; -/// Fresh budget for the detached cancel-then-close sequence. -/// -/// This is independent of the expired query deadline. It bounds resources held -/// by a failed or stalled cleanup without delaying the caller-visible timeout. +/// 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. /// -/// `Duration::ZERO` and `Duration::MAX` are explicit unlimited sentinels on the -/// Rust surface. Other values above [`MAX_CLIENT_QUERY_TIMEOUT`] are rejected so -/// Rust and C callers share the same finite range. +/// Zero and [`Duration::MAX`] mean unlimited. pub(crate) fn deadline_from_timeout(timeout: Duration) -> Result> { deadline_from_timeout_at(timeout, Instant::now()) } -/// Convert a relative timeout using a caller-supplied monotonic entry instant. -/// The C ABI uses this form so runtime initialization and queueing consume the -/// same budget captured at its native boundary. +/// Convert a timeout using a caller-supplied entry instant. pub(crate) fn deadline_from_timeout_at( timeout: Duration, entered_at: Instant, @@ -77,7 +60,6 @@ pub(crate) fn deadline_from_timeout_at( .ok_or_else(|| Error::invalid_argument().message("client query timeout is out of range")) } -/// Build the caller-visible error for an expired client execution deadline. pub(crate) fn client_query_timeout_error(query_id: Option<&str>) -> Error { let mut error = Error::timeout() .message("Client query timeout expired") @@ -89,14 +71,13 @@ pub(crate) fn client_query_timeout_error(query_id: Option<&str>) -> Error { error } -/// Distinguish the local execution deadline from network/server timeout errors. 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, non-blocking admission control for timeout cleanup tasks. +/// Per-session admission control for detached cleanup. pub(crate) struct TimeoutCleanupManager { permits: Arc, } @@ -114,8 +95,7 @@ impl TimeoutCleanupManager { } } - /// Admit and spawn best-effort cancel/close work without ever waiting for - /// queue capacity. Saturation intentionally drops the cleanup request. + /// Spawn best-effort cleanup without waiting for capacity. pub(crate) fn dispatch( &self, runtime: &tokio::runtime::Handle, diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index d043ca7a..e27b8e66 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -12,12 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Wiremock tests for the C ABI's statement execution controls: the detached -//! statement canceller (`kernel_statement_canceller_new` / `_cancel` / `_free`) -//! and the execution-scoped client query timeout. 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 @@ -35,8 +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 status/error fields, -//! null output, finite-range validation, unlimited values, cleanup, and reuse. +//! - `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 @@ -1670,8 +1665,6 @@ fn client_timeout_c_abi_contract_and_reuse() { KernelStatusCode::Success ); - // The initial response publishes an id and enters the 500ms poll sleep. - // A 75ms client deadline must return promptly and null a non-null sentinel. let mut out = std::ptr::dangling_mut::(); let started = Instant::now(); assert_eq!( @@ -1702,7 +1695,6 @@ fn client_timeout_c_abi_contract_and_reuse() { "stmt-c-timeout" ); - // Out-of-range values fail before any RPC and still clear the output. out = std::ptr::dangling_mut::(); assert_eq!( kernel_statement_execute_with_timeout_ms( @@ -1714,8 +1706,6 @@ fn client_timeout_c_abi_contract_and_reuse() { ); assert!(out.is_null()); - // The maximum finite value and zero (unlimited) are both accepted, and - // the same statement is reusable immediately after its timed execution. for timeout_ms in [MAX_CLIENT_QUERY_TIMEOUT_MS, 0] { let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); assert_eq!( diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 2d47ff57..4959ce43 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -213,9 +213,7 @@ fn running_body(statement_id: &str) -> String { .to_string() } -/// Return a delayed response on the first execute and an immediate response on -/// later calls. This lets timeout tests prove the same mutable Statement can be -/// reused after its initial POST future is abandoned. +/// Delay only the first execute response. struct DelayedFirstExecute { first: String, later: String, @@ -1425,8 +1423,6 @@ async fn client_timeout_covers_initial_post_and_statement_is_immediately_reusabl "the 500ms POST must be abandoned near the 75ms deadline" ); - // Both public unlimited sentinels and the largest finite value remain usable - // after the timed future was dropped before a statement id was observed. for timeout in [Duration::ZERO, Duration::MAX, MAX_CLIENT_QUERY_TIMEOUT] { let exec = stmt .execute_with_timeout(timeout) @@ -1512,7 +1508,6 @@ async fn client_timeout_covers_poll_sleep_and_cleanup_does_not_delay_return() { drop(no_status_poll); drop(running); - // Reuse while cleanup for the timed-out id is still in flight. let batch = int64_batch("n", vec![2]); mount_execute(&server, closed_inline_body("stmt-after-timeout", &batch)).await; let exec = stmt From 9d09f88a4a015ba2ffea5a6754181d9aec5228a4 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Tue, 15 Sep 2026 00:13:05 +0000 Subject: [PATCH 3/8] fix(statement): preserve default execute timeout Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/spec-v0.md | 5 +- include/databricks_kernel.h | 10 ++- src/c_abi/statement.rs | 21 ++--- src/client/mod.rs | 3 +- src/client/sea.rs | 125 +++++++++++++++++++------- src/client/transport.rs | 21 ++++- src/reader/cloudfetch/link_fetcher.rs | 22 ++--- src/reader/mod.rs | 5 +- src/statement/mutable.rs | 29 +++--- src/statement/timeout.rs | 11 ++- 10 files changed, 169 insertions(+), 83 deletions(-) diff --git a/docs/spec-v0.md b/docs/spec-v0.md index 3a0dafa0..5609398f 100644 --- a/docs/spec-v0.md +++ b/docs/spec-v0.md @@ -644,11 +644,12 @@ impl Statement { /// Read-only access (for logging or assertion). pub fn spec_ref(&self) -> &StatementSpec; - /// Wait-for-result execution without a client deadline. + /// 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 disable it; result materialisation is excluded. + /// Zero and Duration::MAX select unlimited execution; result materialisation + /// is excluded. pub async fn execute_with_timeout( &mut self, timeout: std::time::Duration, diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 37a3632c..8100a249 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -708,16 +708,18 @@ KernelStatusCode kernel_statement_set_query_tags(kernel_statement_t* stmt, const char* query_tags); /* - * Wait-for-result execution without a client query deadline. On success, - * release `*out` 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 disables it; values above DATABRICKS_KERNEL_MAX_CLIENT_QUERY_TIMEOUT_MS - * return InvalidArgument. The deadline starts on entry, covers execution + * 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. It is never sent to the server. * diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index ccee8550..b63e2fb2 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; @@ -452,13 +453,13 @@ pub unsafe extern "C" fn kernel_statement_execute( return store_invalid_arg("kernel_statement_execute: out must not be null"); } - execute_with_deadline(stmt, None, out) + execute_with_timeout_mode(stmt, ExecutionTimeout::Default, out) } /// Wait-for-result execution with a client deadline in milliseconds. /// -/// Zero disables the deadline. It starts at native entry, ends after terminal -/// mapping, and excludes result materialisation. Timeout returns +/// Zero selects unlimited execution. A finite deadline starts at native entry, +/// ends after terminal mapping, and excludes result materialisation. Timeout returns /// [`KernelStatusCode::Timeout`] with `HYT00` and leaves `*out` null. /// /// # Safety @@ -481,23 +482,23 @@ pub unsafe extern "C" fn kernel_statement_execute_with_timeout_ms( "kernel_statement_execute_with_timeout_ms: stmt must not be null", ); }; - let deadline = match crate::statement::timeout::deadline_from_timeout_at( + let timeout = match crate::statement::timeout::deadline_from_timeout_at( std::time::Duration::from_millis(timeout_ms), entered_at, ) { - Ok(deadline) => deadline, + Ok(deadline) => ExecutionTimeout::from_explicit_deadline(deadline), Err(error) => return store_and_code(error), }; - execute_with_deadline(stmt, deadline, out) + execute_with_timeout_mode(stmt, timeout, out) } /// Run synchronous execution after entry-point validation. /// -/// The timeout entry point clears `out`; the legacy entry point does not. -unsafe fn execute_with_deadline( +/// The timeout entry point clears `out`; the existing entry point does not. +unsafe fn execute_with_timeout_mode( stmt: &mut Statement, - deadline: Option, + timeout: ExecutionTimeout, out: *mut *mut kernel_executed_statement_t, ) -> KernelStatusCode { // `Statement::execute` borrows `&mut self`; we need that borrow to @@ -508,7 +509,7 @@ unsafe fn execute_with_deadline( 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_with_deadline(deadline).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 518f302f..9457952b 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}; @@ -674,6 +674,7 @@ impl SeaRestTransport { sql: &str, params: &ExecuteParams, request_type: RequestType, + poll_timeout: Option, ) -> std::result::Result { let response = self .call_execute_api(session_id, sql, params, request_type) @@ -692,8 +693,6 @@ impl SeaRestTransport { } } - let poll_timeout = - (request_type == RequestType::ExecuteMetadataQuery).then_some(self.config.poll_timeout); let (response, response_from_poll) = self .wait_for_terminal(response, poll_timeout) .await @@ -763,7 +762,7 @@ impl SeaRestTransport { sql: &str, params: &ExecuteParams, request_type: RequestType, - client_deadline: Option, + timeout: ExecutionTimeout, ) -> Result { // After call_execute_api succeeds, the SEA statement is open // on the server. Any subsequent failure before we hand back @@ -784,9 +783,12 @@ impl SeaRestTransport { // downloading chunk 0 to extract the result schema; a // non-retriable 4xx / 5xx on that GET propagates up. // - let execution = self.execute_to_terminal(session_id, sql, params, request_type); - let execution_result = match client_deadline { - Some(deadline) => { + let poll_timeout = + matches!(timeout, ExecutionTimeout::Default).then_some(self.config.poll_timeout); + let execution = + self.execute_to_terminal(session_id, sql, params, request_type, poll_timeout); + let execution_result = match timeout { + ExecutionTimeout::Deadline(deadline) => { match tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), execution) .await { @@ -802,7 +804,7 @@ impl SeaRestTransport { } } } - None => execution.await, + ExecutionTimeout::Default | ExecutionTimeout::Unlimited => execution.await, }; let terminal = match execution_result { Ok(terminal) => terminal, @@ -1067,14 +1069,14 @@ impl Transport for SeaRestTransport { session_id: &str, sql: &str, params: &ExecuteParams, - client_deadline: Option, + timeout: ExecutionTimeout, ) -> Result { self.execute_and_read( session_id, sql, params, RequestType::ExecuteStatement, - client_deadline, + timeout, ) .await } @@ -1444,7 +1446,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1465,7 +1467,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1490,7 +1492,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1514,7 +1516,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1534,7 +1536,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1553,7 +1555,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1578,7 +1580,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1597,7 +1599,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1634,7 +1636,7 @@ impl Transport for SeaRestTransport { &sql, &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await } @@ -1800,7 +1802,7 @@ mod tests { "UPDATE t SET x = x + 1", &ExecuteParams::default(), RequestType::ExecuteStatement, - None, + ExecutionTimeout::Default, ) .await .expect("polled DML execution must succeed"); @@ -1863,6 +1865,7 @@ mod tests { "SELEKT 1", &ExecuteParams::default(), RequestType::ExecuteStatement, + None, ) .await .expect("terminal server failure is a mapped execution outcome"); @@ -1882,13 +1885,13 @@ mod tests { } #[tokio::test] - async fn synchronous_execute_has_no_hidden_poll_timeout() { + 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")) @@ -1898,10 +1901,69 @@ mod tests { .mount(&server) .await; Mock::given(method("GET")) - .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_json(json!({}))) + .expect(0) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-default-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", + "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-timeout", 1)), + .set_body_string(succeeded_inline_dml_body("stmt-explicit-unlimited", 1)), ) .expect(1) .mount(&server) @@ -1915,20 +1977,17 @@ mod tests { ..TransportConfig::default() }, ); - let terminal = transport - .execute_to_terminal( + transport + .execute_and_read( "sess-test", "SELECT 1", &ExecuteParams::default(), RequestType::ExecuteStatement, + ExecutionTimeout::Unlimited, ) .await - .expect("sync execution must not inherit the async handle's poll timeout"); + .expect("an explicit unlimited timeout must bypass the default ceiling"); - assert!(matches!( - terminal.outcome, - TerminalExecutionOutcome::Succeeded(_) - )); server.verify().await; } @@ -1975,7 +2034,7 @@ mod tests { "SHOW CATALOGS", &ExecuteParams::default(), RequestType::ExecuteMetadataQuery, - None, + ExecutionTimeout::Default, ) .await { diff --git a/src/client/transport.rs b/src/client/transport.rs index 06cca941..96ed383a 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -35,6 +35,23 @@ 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, Instant}; /// never reads it. #[derive(Debug, Clone)] pub(crate) struct TransportConfig { - /// Maximum wait for async-handle and metadata 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,7 +312,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { session_id: &str, sql: &str, params: &ExecuteParams, - client_deadline: Option, + timeout: ExecutionTimeout, ) -> Result; /// Execute a SQL statement relying on the server's default inline wait diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 2d0511eb..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,7 +1136,7 @@ mod tests { _session_id: &str, _sql: &str, _params: &ExecuteParams, - _client_deadline: Option, + _timeout: ExecutionTimeout, ) -> Result { Ok(ExecuteResult { statement_id: "mock-statement".to_string(), @@ -1239,7 +1239,7 @@ mod tests { } async fn list_catalogs(&self, _session_id: &str) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1249,7 +1249,7 @@ mod tests { _catalog: Option<&str>, _schema_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1261,7 +1261,7 @@ mod tests { _table_pattern: Option<&str>, _table_types: Option<&[&str]>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1273,7 +1273,7 @@ mod tests { _table_pattern: Option<&str>, _column_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1284,7 +1284,7 @@ mod tests { _schema_pattern: Option<&str>, _procedure_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1295,7 +1295,7 @@ mod tests { _schema_pattern: Option<&str>, _function_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1307,7 +1307,7 @@ mod tests { _procedure_pattern: Option<&str>, _column_pattern: Option<&str>, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1318,7 +1318,7 @@ mod tests { _schema: &str, _table: &str, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } @@ -1332,7 +1332,7 @@ mod tests { _foreign_schema: &str, _foreign_table: &str, ) -> Result { - self.execute_statement("", "", &ExecuteParams::default(), None) + self.execute_statement("", "", &ExecuteParams::default(), ExecutionTimeout::Default) .await } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 378cb560..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,7 +1481,7 @@ mod tests { _: &str, _: &str, _: &ExecuteParams, - _: Option, + _: ExecutionTimeout, ) -> Result { unreachable!() } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 0aba3c45..d3d785ac 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,7 +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, Instant}; +use std::time::Duration; use tracing::Instrument; /// Outcome of [`Statement::execute_direct`] — the Thrift/JDBC directResults @@ -306,8 +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. Use [`Statement::execute_with_timeout`] to add a client - /// deadline. + /// 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 @@ -317,22 +317,24 @@ impl Statement { /// calls on it short-circuit to `InvalidStatementHandle` without /// hitting the wire. pub async fn execute(&mut self) -> Result { - self.execute_with_deadline(None).await + 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` - /// disable the deadline. + /// explicitly select unlimited execution. pub async fn execute_with_timeout(&mut self, timeout: Duration) -> Result { let deadline = crate::statement::timeout::deadline_from_timeout(timeout)?; - self.execute_with_deadline(deadline).await + self.execute_with_timeout_mode(ExecutionTimeout::from_explicit_deadline(deadline)) + .await } - /// Absolute-deadline form used by the C ABI. - pub(crate) async fn execute_with_deadline( + /// Internal form used by the Rust and C ABI entry points. + pub(crate) async fn execute_with_timeout_mode( &mut self, - client_deadline: Option, + timeout: ExecutionTimeout, ) -> Result { // `instrument` (rather than `.entered()`) so the resulting // future stays `Send` — napi-rs's `execute_tokio_future` and @@ -371,12 +373,7 @@ impl Statement { let result = match self .session .transport() - .execute_statement( - self.session.session_id(), - &sql, - &exec_params, - client_deadline, - ) + .execute_statement(self.session.session_id(), &sql, &exec_params, timeout) .await { Ok(result) => result, diff --git a/src/statement/timeout.rs b/src/statement/timeout.rs index 35fa6eaf..faca40ca 100644 --- a/src/statement/timeout.rs +++ b/src/statement/timeout.rs @@ -152,11 +152,18 @@ impl TimeoutCleanupManager { #[cfg(test)] mod tests { use super::*; + use crate::client::ExecutionTimeout; #[test] fn zero_and_duration_max_are_unlimited() { - assert_eq!(deadline_from_timeout(Duration::ZERO).unwrap(), None); - assert_eq!(deadline_from_timeout(Duration::MAX).unwrap(), None); + 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] From 8ee5d702878cd3980d21fc8a9e7a7cafa36d211c Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:28:21 +0000 Subject: [PATCH 4/8] Allow in-flight status RPC grace at query deadline Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- NEXT_CHANGELOG.md | 4 ++ docs/spec-v0.md | 3 +- include/databricks_kernel.h | 8 +-- src/c_abi/statement.rs | 6 ++- src/client/sea.rs | 91 ++++++++++++++++++++++++------- src/statement/mutable.rs | 4 +- src/statement/timeout.rs | 4 ++ tests/v0_execute_wiremock.rs | 102 ++++++++++++++++++++++++++++++++--- 8 files changed, 191 insertions(+), 31 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 4c7c1a14..d698a1af 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -22,6 +22,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 5609398f..4cbb0530 100644 --- a/docs/spec-v0.md +++ b/docs/spec-v0.md @@ -649,7 +649,8 @@ impl Statement { /// Execute with a client deadline through terminal-state mapping. /// Zero and Duration::MAX select unlimited execution; result materialisation - /// is excluded. + /// 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, diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8100a249..4cb46c60 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -719,9 +719,11 @@ KernelStatusCode kernel_statement_execute(kernel_statement_t* stmt, * 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. It is never sent to the server. + * 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. diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index b63e2fb2..471426b0 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -459,8 +459,10 @@ pub unsafe extern "C" fn kernel_statement_execute( /// 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. Timeout returns -/// [`KernelStatusCode::Timeout`] with `HYT00` and leaves `*out` null. +/// 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. diff --git a/src/client/sea.rs b/src/client/sea.rs index 9457952b..0be6b7b7 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -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; @@ -479,7 +479,8 @@ impl SeaRestTransport { async fn wait_for_terminal( &self, response: ExecuteResponse, - poll_timeout: Option, + timeout: ExecutionTimeout, + status_request_in_flight: &AtomicBool, ) -> Result<(ExecuteResponse, bool)> { let started = std::time::Instant::now(); let mut current_response = response; @@ -488,21 +489,46 @@ impl SeaRestTransport { loop { match current_response.status.state { StatementState::Pending | StatementState::Running => { - if poll_timeout.is_some_and(|timeout| started.elapsed() > 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 @@ -674,7 +700,8 @@ impl SeaRestTransport { sql: &str, params: &ExecuteParams, request_type: RequestType, - poll_timeout: Option, + timeout: ExecutionTimeout, + status_request_in_flight: &AtomicBool, ) -> std::result::Result { let response = self .call_execute_api(session_id, sql, params, request_type) @@ -694,12 +721,12 @@ impl SeaRestTransport { } let (response, response_from_poll) = self - .wait_for_terminal(response, poll_timeout) + .wait_for_terminal(response, timeout, status_request_in_flight) .await .map_err(|error| TerminalExecutionFailure { - statement_id: Some(statement_id.clone()), - error, - })?; + statement_id: Some(statement_id.clone()), + error, + })?; let outcome = match Self::terminal_outcome(response) { StatementOutcome::Done(response) => TerminalExecutionOutcome::Succeeded(response), @@ -783,16 +810,43 @@ impl SeaRestTransport { // downloading chunk 0 to extract the result schema; a // non-retriable 4xx / 5xx on that GET propagates up. // - let poll_timeout = - matches!(timeout, ExecutionTimeout::Default).then_some(self.config.poll_timeout); - let execution = - self.execute_to_terminal(session_id, sql, params, request_type, poll_timeout); + 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) => { - match tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), execution) - .await - { + 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 = + params.inflight_id_observer.as_ref().and_then(|slot| { + slot.try_lock().ok().and_then(|id| id.clone()) + }); + return Err(crate::statement::timeout::client_query_timeout_error( + query_id.as_deref(), + )); + } + } + } Err(_) => { let query_id = params .inflight_id_observer @@ -1865,7 +1919,8 @@ mod tests { "SELEKT 1", &ExecuteParams::default(), RequestType::ExecuteStatement, - None, + ExecutionTimeout::Unlimited, + &AtomicBool::new(false), ) .await .expect("terminal server failure is a mapped execution outcome"); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index d3d785ac..1e678fc4 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -324,7 +324,9 @@ impl Statement { /// Execute with a client deadline through terminal-state mapping. /// /// Result materialisation is excluded. `Duration::ZERO` and `Duration::MAX` - /// explicitly select unlimited execution. + /// 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)) diff --git a/src/statement/timeout.rs b/src/statement/timeout.rs index faca40ca..5e5f2033 100644 --- a/src/statement/timeout.rs +++ b/src/statement/timeout.rs @@ -28,6 +28,10 @@ pub const MAX_CLIENT_QUERY_TIMEOUT: Duration = Duration::from_millis(MAX_CLIENT_ 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; diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 4959ce43..7e64c03b 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -1532,7 +1532,7 @@ async fn client_timeout_covers_poll_sleep_and_cleanup_does_not_delay_return() { } #[tokio::test] -async fn client_timeout_covers_delayed_terminal_status_and_mapping() { +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; @@ -1553,25 +1553,115 @@ async fn client_timeout_covers_delayed_terminal_status_and_mapping() { .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-delayed-terminal/cancel")) + .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 broken"); + stmt.spec().sql("SELECT still_running"); let error = stmt .execute_with_timeout(Duration::from_millis(700)) .await .err() - .expect("deadline must expire while the terminal status RPC is in flight"); - assert_client_query_timeout(&error, Some("stmt-delayed-terminal")); + .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-delayed-terminal", 1, Duration::from_secs(1)).await; + wait_for_close_delete(&server, "stmt-stalled-status", 1, Duration::from_secs(1)).await; assert_eq!(closes, 1); + server.verify().await; } #[tokio::test] From 98f07df0155dc5b987c7a7eb4a25607755f9e24f Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 16 Sep 2026 21:00:08 +0000 Subject: [PATCH 5/8] docs: record client query deadline APIs Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- NEXT_CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index d698a1af..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. From 726e3d933c27b369219d8db92b2536ebf8269d8e Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 16 Sep 2026 21:19:01 +0000 Subject: [PATCH 6/8] fix(statement): retain timeout cleanup query id Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/sea.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 0be6b7b7..455e174d 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -837,10 +837,10 @@ impl SeaRestTransport { // client timeout during grace. Ok(Ok(terminal)) => Ok(terminal), Ok(Err(_)) | Err(_) => { - let query_id = - params.inflight_id_observer.as_ref().and_then(|slot| { - slot.try_lock().ok().and_then(|id| id.clone()) - }); + let query_id = params + .inflight_id_observer + .as_ref() + .and_then(|slot| slot.lock().ok().and_then(|id| id.clone())); return Err(crate::statement::timeout::client_query_timeout_error( query_id.as_deref(), )); @@ -851,7 +851,7 @@ impl SeaRestTransport { let query_id = params .inflight_id_observer .as_ref() - .and_then(|slot| slot.try_lock().ok().and_then(|id| id.clone())); + .and_then(|slot| slot.lock().ok().and_then(|id| id.clone())); return Err(crate::statement::timeout::client_query_timeout_error( query_id.as_deref(), )); From 6ca3f809148979d3857ac9c307cbd36feca04d17 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 16 Sep 2026 21:35:05 +0000 Subject: [PATCH 7/8] fix(statement): keep deadline cleanup asynchronous Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/sea.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/client/sea.rs b/src/client/sea.rs index 455e174d..4600feea 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -866,6 +866,13 @@ impl SeaRestTransport { 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; From 5c1bfcb9d588b471d8430b0b705571c6b352ea6c Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 17 Sep 2026 22:20:31 +0000 Subject: [PATCH 8/8] fix(statement): recover timeout cleanup query id Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/sea.rs | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 4600feea..114e4457 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -102,6 +102,19 @@ struct TerminalExecutionFailure { 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. @@ -837,10 +850,7 @@ impl SeaRestTransport { // client timeout during grace. Ok(Ok(terminal)) => Ok(terminal), Ok(Err(_)) | Err(_) => { - let query_id = params - .inflight_id_observer - .as_ref() - .and_then(|slot| slot.lock().ok().and_then(|id| id.clone())); + let query_id = timeout_query_id(params); return Err(crate::statement::timeout::client_query_timeout_error( query_id.as_deref(), )); @@ -848,10 +858,7 @@ impl SeaRestTransport { } } Err(_) => { - let query_id = params - .inflight_id_observer - .as_ref() - .and_then(|slot| slot.lock().ok().and_then(|id| id.clone())); + let query_id = timeout_query_id(params); return Err(crate::statement::timeout::client_query_timeout_error( query_id.as_deref(), ));