From 43cf931527ddbd87db5be6c739c5762683625370 Mon Sep 17 00:00:00 2001 From: Jay Xiao Date: Wed, 30 Sep 2026 22:54:31 +0000 Subject: [PATCH 01/10] feat(statement): enforce timeout across async polling Signed-off-by: Jay Xiao --- include/databricks_kernel.h | 11 +++ src/c_abi/statement.rs | 40 +++++++++- src/statement/executed_async.rs | 105 +++++++++++++++++++++++++-- src/statement/mutable.rs | 52 +++++++++++-- tests/v0_c_abi_canceller_wiremock.rs | 82 ++++++++++++++++++++- 5 files changed, 273 insertions(+), 17 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 684639c5..bb2d92dd 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -740,6 +740,17 @@ KernelStatusCode kernel_statement_execute_with_timeout_ms( KernelStatusCode kernel_statement_submit(kernel_statement_t* stmt, kernel_executed_async_statement_t** out); +/* Submit-and-return with a client-side execution deadline in milliseconds. + * Zero selects unlimited execution; values above + * DATABRICKS_KERNEL_MAX_CLIENT_QUERY_TIMEOUT_MS return InvalidArgument. The + * deadline starts on entry and is retained by the returned async handle across + * status polls. If it expires before a terminal status is observed, status + * returns Timeout with SQLSTATE HYT00 and the kernel schedules best-effort + * cancel/close cleanup. Result fetching is outside this deadline. */ +KernelStatusCode kernel_statement_submit_with_timeout_ms( + kernel_statement_t* stmt, uint64_t timeout_ms, + kernel_executed_async_statement_t** out); + /* * Free the statement lifecycle owner. Does NOT free executed-handle * boxes — each executed handle is a separate allocation that you must diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index aa6bb465..eaa2caec 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -877,6 +877,33 @@ pub unsafe extern "C" fn kernel_executed_statement_close( pub unsafe extern "C" fn kernel_statement_submit( stmt: *mut kernel_statement_t, out: *mut *mut kernel_executed_async_statement_t, +) -> KernelStatusCode { + submit_with_timeout(stmt, None, out) +} + +/// Submit-and-return with a client-side deadline retained across status polls. +/// Zero means unlimited. Result materialisation/fetching is outside the +/// deadline, matching synchronous execution. +/// +/// # Safety +/// `stmt` / `out` must be valid pointers. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_submit_with_timeout_ms( + stmt: *mut kernel_statement_t, + timeout_ms: u64, + out: *mut *mut kernel_executed_async_statement_t, +) -> KernelStatusCode { + submit_with_timeout( + stmt, + Some(std::time::Duration::from_millis(timeout_ms)), + out, + ) +} + +unsafe fn submit_with_timeout( + stmt: *mut kernel_statement_t, + timeout: Option, + out: *mut *mut kernel_executed_async_statement_t, ) -> KernelStatusCode { // Wrap the whole body in catch_ffi: block_on_ffi only catches a panic // in the awaited future, so the surrounding sync prologue/epilogue @@ -885,16 +912,21 @@ pub unsafe extern "C" fn kernel_statement_submit( // thread-local error on entry. catch_ffi(|| { if out.is_null() { - return store_invalid_arg("kernel_statement_submit: out must not be null"); + return store_invalid_arg("statement submit: 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_submit: stmt must not be null"); + return store_invalid_arg("statement submit: stmt must not be null"); }; let stmt_ptr: *mut Statement = stmt; match block_on_ffi(move || { let stmt = unsafe { &mut *stmt_ptr }; - Box::pin(async move { stmt.submit().await }) + Box::pin(async move { + match timeout { + Some(timeout) => stmt.submit_with_timeout(timeout).await, + None => stmt.submit().await, + } + }) }) { Ok(exec) => { let statement_id_c = crate::c_abi::error::to_cstring_lossy(exec.statement_id()); @@ -924,7 +956,7 @@ pub unsafe extern "C" fn kernel_executed_async_statement_status( // that run on the caller thread outside block_on_ffi's future guard // (a panic there would be UB); it also clears the thread-local error. catch_ffi(|| { - let Some(handle) = (exec as *mut ExecutedAsyncHandle).as_ref() else { + let Some(handle) = (exec as *mut ExecutedAsyncHandle).as_mut() else { return store_invalid_arg( "kernel_executed_async_statement_status: exec must not be null", ); diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 186507c2..631a7ac8 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -222,9 +222,25 @@ pub struct ExecutedAsyncStatement { /// Set once result materialisation hands success finalization to /// the returned `ResultStream`. result_stream_owns_success_telemetry: AtomicBool, + /// Absolute execution deadline retained across caller-driven polls. + client_deadline: Option, + client_timeout_expired: AtomicBool, } impl ExecutedAsyncStatement { + /// Produce the stable client query-timeout error and schedule bounded, + /// best-effort server cleanup when a deadline retained across + /// caller-driven status polls expires. + pub(crate) fn expire_client_query_timeout(&self) -> Error { + if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { + self.session + .dispatch_timeout_cleanup(Some(self.statement_id.clone())); + } + let error = crate::statement::timeout::client_query_timeout_error(Some(&self.statement_id)); + self.statement_telemetry.finalize(Some(&error)); + error + } + fn session_attribution(&self) -> SessionAttribution { if self.owning { SessionAttribution::Current @@ -255,6 +271,7 @@ impl ExecutedAsyncStatement { closed: Arc, initial_status: crate::types::sea::StatementStatus, statement_telemetry: StatementTelemetry, + client_deadline: Option, ) -> Self { Self { session, @@ -266,6 +283,8 @@ impl ExecutedAsyncStatement { latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), + client_deadline, + client_timeout_expired: AtomicBool::new(false), } } @@ -300,6 +319,8 @@ impl ExecutedAsyncStatement { latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), + client_deadline: None, + client_timeout_expired: AtomicBool::new(false), } } @@ -423,12 +444,35 @@ impl ExecutedAsyncStatement { let span = self.session.log_span().clone(); let result = async { self.valid.check()?; + if self.client_timeout_expired.load(Ordering::Acquire) + || self + .client_deadline + .is_some_and(|deadline| std::time::Instant::now() >= deadline) + { + return Err(self.expire_client_query_timeout()); + } let status_started = std::time::Instant::now(); - let response = self + let poll = self .session .transport() - .statement_status(&self.statement_id, self.session_attribution()) - .await?; + .statement_status(&self.statement_id, self.session_attribution()); + let response = match self.client_deadline { + Some(deadline) => { + let poll_deadline = deadline + .checked_add(crate::statement::timeout::CLIENT_QUERY_TIMEOUT_STATUS_GRACE) + .unwrap_or(deadline); + match tokio::time::timeout_at( + tokio::time::Instant::from_std(poll_deadline), + poll, + ) + .await + { + Ok(result) => result?, + Err(_) => return Err(self.expire_client_query_timeout()), + } + } + None => poll.await?, + }; self.statement_telemetry .record_poll(status_started.elapsed()); // Cache the wire status so the extended-field accessors @@ -436,6 +480,13 @@ impl ExecutedAsyncStatement { // stale initial-submit snapshot). self.record_latest_status(response.status.clone()); let status = StatementStatus::from_sea_response(&response); + if matches!(status, StatementStatus::Pending | StatementStatus::Running) + && self + .client_deadline + .is_some_and(|deadline| std::time::Instant::now() >= deadline) + { + return Err(self.expire_client_query_timeout()); + } match &status { StatementStatus::Failed(error) => { self.statement_telemetry.finalize(Some(error)); @@ -507,12 +558,45 @@ impl ExecutedAsyncStatement { loop { self.valid.check()?; + if self.client_timeout_expired.load(Ordering::Acquire) + || self + .client_deadline + .is_some_and(|deadline| std::time::Instant::now() >= deadline) + { + if let Some(g) = cancel_guard.take() { + g.defuse(); + } + return Err(self.expire_client_query_timeout()); + } let status_started = std::time::Instant::now(); - let response = self + let poll = self .session .transport() - .statement_status(&self.statement_id, self.session_attribution()) - .await?; + .statement_status(&self.statement_id, self.session_attribution()); + let response = match self.client_deadline { + Some(deadline) => { + let poll_deadline = deadline + .checked_add( + crate::statement::timeout::CLIENT_QUERY_TIMEOUT_STATUS_GRACE, + ) + .unwrap_or(deadline); + match tokio::time::timeout_at( + tokio::time::Instant::from_std(poll_deadline), + poll, + ) + .await + { + Ok(result) => result?, + Err(_) => { + if let Some(g) = cancel_guard.take() { + g.defuse(); + } + return Err(self.expire_client_query_timeout()); + } + } + } + None => poll.await?, + }; self.statement_telemetry .record_poll(status_started.elapsed()); // Cache the wire status so the extended-field @@ -550,6 +634,15 @@ impl ExecutedAsyncStatement { return Err(error); } StatementStatus::Pending | StatementStatus::Running => { + if self + .client_deadline + .is_some_and(|deadline| std::time::Instant::now() >= deadline) + { + if let Some(g) = cancel_guard.take() { + g.defuse(); + } + return Err(self.expire_client_query_timeout()); + } if start.elapsed() > cfg.poll_timeout { // Internal poll-timeout: we asked to wait, // we gave up. Leave the cancel guard armed diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 1e678fc4..604cad84 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -450,6 +450,28 @@ impl Statement { /// `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 { + self.submit_with_timeout_mode(ExecutionTimeout::Default) + .await + } + + /// Submit-and-return with one client-side execution deadline retained by + /// the returned handle across caller-driven status polls. + /// + /// `Duration::ZERO` and `Duration::MAX` explicitly select unlimited + /// execution. Result materialisation and fetching are outside the deadline. + pub async fn submit_with_timeout( + &mut self, + timeout: Duration, + ) -> Result { + let deadline = crate::statement::timeout::deadline_from_timeout(timeout)?; + self.submit_with_timeout_mode(ExecutionTimeout::from_explicit_deadline(deadline)) + .await + } + + async fn submit_with_timeout_mode( + &mut self, + timeout: ExecutionTimeout, + ) -> Result { let span = self.session.log_span().clone(); // Clear the shared in-flight-id slot before the first `.await` // (see `reset_inflight_slot`). @@ -466,11 +488,26 @@ impl Statement { ); let guard = cancel_state.guard(); - let response = self - .session - .transport() - .submit_statement(self.session.session_id(), &sql, &exec_params) - .await?; + let submit = self.session.transport().submit_statement( + self.session.session_id(), + &sql, + &exec_params, + ); + let response = match timeout { + ExecutionTimeout::Deadline(deadline) => { + match tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), submit) + .await + { + Ok(result) => result?, + Err(_) => { + return Err(crate::statement::timeout::client_query_timeout_error( + None, + )); + } + } + } + ExecutionTimeout::Default | ExecutionTimeout::Unlimited => submit.await?, + }; telemetry_for_body.on_statement_submitted(&response.statement_id); cancel_state.observe(&response.statement_id); @@ -498,6 +535,10 @@ impl Statement { // the first poll. response.status, telemetry_for_body, + match timeout { + ExecutionTimeout::Deadline(deadline) => Some(deadline), + ExecutionTimeout::Default | ExecutionTimeout::Unlimited => None, + }, )) } .instrument(span) @@ -623,6 +664,7 @@ impl Statement { closed, resp.status, telemetry_for_body, + None, ))) } } diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 210ec9c5..21b26ed4 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -68,8 +68,8 @@ use databricks_sql_kernel::c_abi::statement::{ kernel_statement_canceller_cancel, kernel_statement_canceller_free, kernel_statement_canceller_new, kernel_statement_canceller_t, kernel_statement_close, kernel_statement_execute, kernel_statement_execute_with_timeout_ms, kernel_statement_set_sql, - kernel_statement_submit, kernel_statement_t, KernelStatementStatusKind, - MAX_CLIENT_QUERY_TIMEOUT_MS, + kernel_statement_submit, kernel_statement_submit_with_timeout_ms, kernel_statement_t, + KernelStatementStatusKind, MAX_CLIENT_QUERY_TIMEOUT_MS, }; use databricks_sql_kernel::c_abi::KernelStatusCode; use serde_json::json; @@ -167,6 +167,84 @@ fn async_c_abi_submit_poll_and_materialise() { } } +#[test] +fn async_c_abi_query_timeout_expires_across_status_polls() { + let rt = tokio::runtime::Runtime::new().unwrap(); + 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(ResponseTemplate::new(200).set_body_string(running_body("stmt-timeout"))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-timeout")) + .respond_with(ResponseTemplate::new(200).set_body_string(running_body("stmt-timeout"))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-timeout/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + server + }); + + unsafe { + let session = open_session_c_abi(&server.uri()); + let mut stmt = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT 1").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + + let mut exec: *mut kernel_executed_async_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_submit_with_timeout_ms(stmt, 25, &mut exec), + KernelStatusCode::Success + ); + std::thread::sleep(Duration::from_millis(40)); + + let mut status = KernelStatementStatusKind::Running; + assert_eq!( + kernel_executed_async_statement_status(exec, &mut status), + KernelStatusCode::Timeout + ); + assert_eq!(status, KernelStatementStatusKind::Pending); + + 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_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-timeout" + ); + + assert_eq!( + kernel_executed_async_statement_close(exec), + KernelStatusCode::Success + ); + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + /// A submitted statement that the server reports as `FAILED` on the first /// status poll must surface `KernelStatementStatusKind::Failed` with a /// `SqlError` status code, and the last-error channel must carry the mapped From 509bdc1e68687af3ba68441c232970dfb63c71cd Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 00:54:27 +0000 Subject: [PATCH 02/10] ai: apply changes for #374 (2 review threads) Addresses: - #4150147368 at src/c_abi/statement.rs:941 - #4150250700 at tests/v0_c_abi_canceller_wiremock.rs:210 Signed-off-by: peco-engineer-bot[bot] --- include/databricks_kernel.h | 6 +- src/statement/mutable.rs | 15 +++++ tests/v0_c_abi_canceller_wiremock.rs | 95 ++++++++++++++++++++++++++++ 3 files changed, 115 insertions(+), 1 deletion(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index bb2d92dd..285f35b5 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -746,7 +746,11 @@ KernelStatusCode kernel_statement_submit(kernel_statement_t* stmt, * deadline starts on entry and is retained by the returned async handle across * status polls. If it expires before a terminal status is observed, status * returns Timeout with SQLSTATE HYT00 and the kernel schedules best-effort - * cancel/close cleanup. Result fetching is outside this deadline. */ + * cancel/close cleanup. One exception: if the deadline fires DURING the initial + * submit round-trip (before the server returns a statement id), no id is known + * yet, so no cancel/close can be scheduled; a statement the server may have + * created is left for session-close to reclaim. This window is small because + * submit uses wait_timeout=0s. Result fetching is outside this deadline. */ KernelStatusCode kernel_statement_submit_with_timeout_ms( kernel_statement_t* stmt, uint64_t timeout_ms, kernel_executed_async_statement_t** out); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 604cad84..43cff101 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -500,6 +500,21 @@ impl Statement { { Ok(result) => result?, Err(_) => { + // Mid-submit deadline expiry. The server statement + // id is unknown here: `cancel_state.observe` runs + // only once `submit` resolves, so a timeout before + // that leaves `observed_id` as `None`. Dropping the + // `submit` future therefore cannot schedule any + // server-side cancel/close — if the POST already + // reached the server and created a statement, that + // statement is leaked until session close reclaims + // it. This is inherent (no id to target) and the + // window is small because submit uses + // `wait_timeout=0s`; the "best-effort cancel/close + // cleanup on expiry" contract in the header is only + // fully honored on the status path, where an id has + // already been observed. We pass `None` as the + // query id for the same reason. return Err(crate::statement::timeout::client_query_timeout_error( None, )); diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 21b26ed4..aa3b45b7 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -245,6 +245,101 @@ fn async_c_abi_query_timeout_expires_across_status_polls() { } } +/// Boundary contract for `kernel_statement_submit_with_timeout_ms`, mirroring +/// the sibling `kernel_statement_execute_with_timeout_ms` boundary test: a +/// timeout above `MAX_CLIENT_QUERY_TIMEOUT_MS` is rejected with +/// `InvalidArgument` without a submit RPC, while `MAX_CLIENT_QUERY_TIMEOUT_MS` +/// and `0` are accepted. Locks the documented contract on the submit surface. +#[test] +fn async_c_abi_submit_timeout_rejects_oversized_and_accepts_boundaries() { + let rt = tokio::runtime::Runtime::new().unwrap(); + 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( + ResponseTemplate::new(200).set_body_string(succeeded_empty_body("stmt-submit-bnd")), + ) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-submit-bnd")) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_empty_body("stmt-submit-bnd")), + ) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-submit-bnd/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + server + }); + + unsafe { + let session = open_session_c_abi(&server.uri()); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT 1").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + + let mut exec = std::ptr::dangling_mut::(); + assert_eq!( + kernel_statement_submit_with_timeout_ms( + stmt, + MAX_CLIENT_QUERY_TIMEOUT_MS + 1, + &mut exec + ), + KernelStatusCode::InvalidArgument + ); + assert!( + exec.is_null(), + "the C output must be null on InvalidArgument" + ); + + for timeout_ms in [MAX_CLIENT_QUERY_TIMEOUT_MS, 0] { + let mut exec: *mut kernel_executed_async_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_submit_with_timeout_ms(stmt, timeout_ms, &mut exec), + KernelStatusCode::Success + ); + assert!(!exec.is_null()); + assert_eq!( + kernel_executed_async_statement_close(exec), + KernelStatusCode::Success + ); + } + + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } + + let submit_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!( + submit_posts, 2, + "the oversized timeout must be rejected without a submit RPC" + ); +} + /// A submitted statement that the server reports as `FAILED` on the first /// status poll must surface `KernelStatementStatusKind::Failed` with a /// `SqlError` status code, and the last-error channel must carry the mapped From fc2b729479ffe9e308ba379fb0fe0c00accd8c2c Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 22:04:20 +0000 Subject: [PATCH 03/10] ai: apply changes for #374 (1 review thread) Addresses: - #4160807790 at src/statement/mutable.rs:555 Signed-off-by: peco-engineer-bot[bot] --- src/statement/executed_async.rs | 68 +++++++++++++++++++++++++++++++-- src/statement/mutable.rs | 7 +--- 2 files changed, 67 insertions(+), 8 deletions(-) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 631a7ac8..de68d93f 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -44,7 +44,7 @@ //! class) can route through whichever handle their language idiom //! prefers; field availability is identical. -use crate::client::{ExecuteResponse, SessionAttribution}; +use crate::client::{ExecuteResponse, ExecutionTimeout, SessionAttribution}; use crate::kernel_error::{Error, Result}; use crate::klog::warn; use crate::result_stream::ResultStream; @@ -224,9 +224,35 @@ pub struct ExecutedAsyncStatement { result_stream_owns_success_telemetry: AtomicBool, /// Absolute execution deadline retained across caller-driven polls. client_deadline: Option, + /// When `true`, the caller explicitly disabled the client timeout + /// (`ExecutionTimeout::Unlimited`), so the poll loop must NOT fall + /// back to the transport's default `poll_timeout` ceiling. Mirrors + /// the sync `wait_for_terminal` gating, which only applies that + /// ceiling under `ExecutionTimeout::Default`. Without this, an + /// "unlimited" submit still dies at the 600s default poll_timeout. + poll_timeout_disabled: bool, client_timeout_expired: AtomicBool, } +/// Map an [`ExecutionTimeout`] onto the async handle's two deadline +/// knobs: `(client_deadline, poll_timeout_disabled)`. +/// +/// Mirrors the sync `wait_for_terminal` gating so the two consumption +/// modes agree on what "unlimited" means: +/// - `Deadline` → retain an absolute client deadline; the transport's +/// `poll_timeout` ceiling is irrelevant (the deadline fires first). +/// - `Unlimited` → no client deadline AND bypass the `poll_timeout` +/// ceiling, so an explicitly-unlimited submit does not silently die +/// at the 600s default. +/// - `Default` → no client deadline, keep the `poll_timeout` ceiling. +fn deadline_policy(timeout: ExecutionTimeout) -> (Option, bool) { + match timeout { + ExecutionTimeout::Deadline(deadline) => (Some(deadline), false), + ExecutionTimeout::Unlimited => (None, true), + ExecutionTimeout::Default => (None, false), + } +} + impl ExecutedAsyncStatement { /// Produce the stable client query-timeout error and schedule bounded, /// best-effort server cleanup when a deadline retained across @@ -264,6 +290,13 @@ impl ExecutedAsyncStatement { /// return useful values even before the caller drives a single /// `status()` / `await_result()` poll (e.g. when the server /// already finished by the time `submit` returned). + /// + /// `timeout` selects the handle's deadline policy, mirroring the + /// sync `wait_for_terminal` gating: `Deadline` retains an absolute + /// client deadline across polls; `Unlimited` disables BOTH that + /// deadline and the transport's default `poll_timeout` ceiling; + /// `Default` keeps the `poll_timeout` ceiling with no client + /// deadline. pub(crate) fn new( session: Arc, statement_id: String, @@ -271,8 +304,9 @@ impl ExecutedAsyncStatement { closed: Arc, initial_status: crate::types::sea::StatementStatus, statement_telemetry: StatementTelemetry, - client_deadline: Option, + timeout: ExecutionTimeout, ) -> Self { + let (client_deadline, poll_timeout_disabled) = deadline_policy(timeout); Self { session, statement_id, @@ -284,6 +318,7 @@ impl ExecutedAsyncStatement { statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline, + poll_timeout_disabled, client_timeout_expired: AtomicBool::new(false), } } @@ -320,6 +355,7 @@ impl ExecutedAsyncStatement { statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline: None, + poll_timeout_disabled: false, client_timeout_expired: AtomicBool::new(false), } } @@ -643,7 +679,7 @@ impl ExecutedAsyncStatement { } return Err(self.expire_client_query_timeout()); } - if start.elapsed() > cfg.poll_timeout { + if !self.poll_timeout_disabled && start.elapsed() > cfg.poll_timeout { // Internal poll-timeout: we asked to wait, // we gave up. Leave the cancel guard armed // so the server stops charging DBUs on the @@ -1044,4 +1080,30 @@ mod tests { let failed = StatementStatus::Failed(Error::sql_error().message("boom")); assert_eq!(failed.as_str(), "Failed"); } + + #[test] + fn deadline_policy_mirrors_sync_timeout_gating() { + // Default: no client deadline, poll_timeout ceiling stays on. + assert_eq!( + deadline_policy(ExecutionTimeout::Default), + (None, false), + "Default must keep the transport poll_timeout ceiling" + ); + // Unlimited: no client deadline AND the poll_timeout ceiling is + // bypassed — regression guard for an explicitly-unlimited submit + // silently dying at the 600s default poll_timeout. + assert_eq!( + deadline_policy(ExecutionTimeout::Unlimited), + (None, true), + "Unlimited must disable the poll_timeout ceiling" + ); + // Deadline: retains the absolute client deadline; the ceiling is + // left on but is moot because the deadline fires first. + let deadline = std::time::Instant::now(); + assert_eq!( + deadline_policy(ExecutionTimeout::Deadline(deadline)), + (Some(deadline), false), + "Deadline must retain the client deadline" + ); + } } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 43cff101..98b42676 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -550,10 +550,7 @@ impl Statement { // the first poll. response.status, telemetry_for_body, - match timeout { - ExecutionTimeout::Deadline(deadline) => Some(deadline), - ExecutionTimeout::Default | ExecutionTimeout::Unlimited => None, - }, + timeout, )) } .instrument(span) @@ -679,7 +676,7 @@ impl Statement { closed, resp.status, telemetry_for_body, - None, + ExecutionTimeout::Default, ))) } } From e010e06214572b3be321c15d5beb9f94c0fb9f76 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 22:16:03 +0000 Subject: [PATCH 04/10] ai: apply changes for #374 (1 review thread) Addresses: - #4161027160 at src/statement/executed_async.rs:250 Signed-off-by: peco-engineer-bot[bot] --- src/statement/executed_async.rs | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index de68d93f..81995d38 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -239,15 +239,22 @@ pub struct ExecutedAsyncStatement { /// /// Mirrors the sync `wait_for_terminal` gating so the two consumption /// modes agree on what "unlimited" means: -/// - `Deadline` → retain an absolute client deadline; the transport's -/// `poll_timeout` ceiling is irrelevant (the deadline fires first). +/// - `Deadline` → retain an absolute client deadline AND bypass the +/// `poll_timeout` ceiling: the client deadline *is* the ceiling. The +/// sync path only applies `poll_timeout` under `Default`, so a +/// `Deadline` runs to the full client deadline even when it exceeds +/// the 600s default `poll_timeout` (`MAX_CLIENT_QUERY_TIMEOUT_MS` +/// permits deadlines far beyond 600s). Leaving the ceiling armed here +/// would abort such a query at 600s with the generic internal +/// poll-timeout error instead of the caller's deadline firing with +/// the `Timeout`/`HYT00` client-query-timeout error. /// - `Unlimited` → no client deadline AND bypass the `poll_timeout` /// ceiling, so an explicitly-unlimited submit does not silently die /// at the 600s default. /// - `Default` → no client deadline, keep the `poll_timeout` ceiling. fn deadline_policy(timeout: ExecutionTimeout) -> (Option, bool) { match timeout { - ExecutionTimeout::Deadline(deadline) => (Some(deadline), false), + ExecutionTimeout::Deadline(deadline) => (Some(deadline), true), ExecutionTimeout::Unlimited => (None, true), ExecutionTimeout::Default => (None, false), } @@ -1097,13 +1104,18 @@ mod tests { (None, true), "Unlimited must disable the poll_timeout ceiling" ); - // Deadline: retains the absolute client deadline; the ceiling is - // left on but is moot because the deadline fires first. + // Deadline: retains the absolute client deadline AND bypasses the + // poll_timeout ceiling — the client deadline *is* the ceiling. + // Regression guard: MAX_CLIENT_QUERY_TIMEOUT_MS permits deadlines + // far beyond the 600s default poll_timeout, so leaving the ceiling + // armed would abort such a query at 600s with the generic internal + // poll-timeout error instead of the caller's deadline firing. The + // sync wait_for_terminal only applies poll_timeout under Default. let deadline = std::time::Instant::now(); assert_eq!( deadline_policy(ExecutionTimeout::Deadline(deadline)), - (Some(deadline), false), - "Deadline must retain the client deadline" + (Some(deadline), true), + "Deadline must retain the client deadline AND disable the poll_timeout ceiling" ); } } From 96e9203d09cd66149dfb13ccfb958de096673343 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 22:30:09 +0000 Subject: [PATCH 05/10] ai: apply changes for #374 (1 review thread) Addresses: - #4161140038 at src/c_abi/statement.rs:959 Signed-off-by: peco-engineer-bot[bot] --- src/c_abi/statement.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index eaa2caec..29092e34 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -956,7 +956,7 @@ pub unsafe extern "C" fn kernel_executed_async_statement_status( // that run on the caller thread outside block_on_ffi's future guard // (a panic there would be UB); it also clears the thread-local error. catch_ffi(|| { - let Some(handle) = (exec as *mut ExecutedAsyncHandle).as_mut() else { + let Some(handle) = (exec as *mut ExecutedAsyncHandle).as_ref() else { return store_invalid_arg( "kernel_executed_async_statement_status: exec must not be null", ); From 5fcd4521f528aebad491dd6277e3d1ac65b03309 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 23:01:17 +0000 Subject: [PATCH 06/10] ai: apply changes for #374 (2 review threads) Addresses: - #4161264557 at src/statement/executed_async.rs:490 - #4161264563 at src/statement/executed_async.rs:604 Signed-off-by: peco-engineer-bot[bot] --- src/statement/executed_async.rs | 50 +++++++++++++++++--- src/types/sea.rs | 16 +++++++ tests/v0_async_execute_wiremock.rs | 74 ++++++++++++++++++++++++++++++ tests/v0_execute_wiremock.rs | 70 ++++++++++++++++++++++++++++ 4 files changed, 203 insertions(+), 7 deletions(-) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 81995d38..1a2ef1be 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -232,6 +232,16 @@ pub struct ExecutedAsyncStatement { /// "unlimited" submit still dies at the 600s default poll_timeout. poll_timeout_disabled: bool, client_timeout_expired: AtomicBool, + /// Latched once this handle observes a terminal server state + /// (`Succeeded` / `Failed` / `Cancelled` / `Closed`), including + /// the initial-submit snapshot. The client deadline governs only + /// the pre-terminal window ("initial submit through observed + /// terminal status"): once a terminal state has been seen, a + /// subsequent `status()` must return that state regardless of the + /// deadline, instead of masking it with a `Timeout`/`HYT00` and + /// firing a wasted cancel+close against an already-finished + /// statement. + terminal_observed: AtomicBool, } /// Map an [`ExecutionTimeout`] onto the async handle's two deadline @@ -314,6 +324,7 @@ impl ExecutedAsyncStatement { timeout: ExecutionTimeout, ) -> Self { let (client_deadline, poll_timeout_disabled) = deadline_policy(timeout); + let initial_terminal = initial_status.state.is_terminal(); Self { session, statement_id, @@ -327,6 +338,7 @@ impl ExecutedAsyncStatement { client_deadline, poll_timeout_disabled, client_timeout_expired: AtomicBool::new(false), + terminal_observed: AtomicBool::new(initial_terminal), } } @@ -352,6 +364,7 @@ impl ExecutedAsyncStatement { statement_id: String, initial_status: crate::types::sea::StatementStatus, ) -> Self { + let initial_terminal = initial_status.state.is_terminal(); Self { session, statement_id, @@ -364,6 +377,7 @@ impl ExecutedAsyncStatement { client_deadline: None, poll_timeout_disabled: false, client_timeout_expired: AtomicBool::new(false), + terminal_observed: AtomicBool::new(initial_terminal), } } @@ -487,10 +501,19 @@ impl ExecutedAsyncStatement { let span = self.session.log_span().clone(); let result = async { self.valid.check()?; - if self.client_timeout_expired.load(Ordering::Acquire) - || self - .client_deadline - .is_some_and(|deadline| std::time::Instant::now() >= deadline) + // The client deadline governs only the pre-terminal window + // ("initial submit through observed terminal status"). Once + // this handle has observed a terminal state, `status()` + // re-polls and returns it regardless of the deadline, rather + // than masking the terminal outcome with a `Timeout`/`HYT00` + // and firing a wasted cancel+close against an already- + // finished statement. + let enforce_deadline = !self.terminal_observed.load(Ordering::Acquire); + if enforce_deadline + && (self.client_timeout_expired.load(Ordering::Acquire) + || self + .client_deadline + .is_some_and(|deadline| std::time::Instant::now() >= deadline)) { return Err(self.expire_client_query_timeout()); } @@ -500,7 +523,7 @@ impl ExecutedAsyncStatement { .transport() .statement_status(&self.statement_id, self.session_attribution()); let response = match self.client_deadline { - Some(deadline) => { + Some(deadline) if enforce_deadline => { let poll_deadline = deadline .checked_add(crate::statement::timeout::CLIENT_QUERY_TIMEOUT_STATUS_GRACE) .unwrap_or(deadline); @@ -514,7 +537,7 @@ impl ExecutedAsyncStatement { Err(_) => return Err(self.expire_client_query_timeout()), } } - None => poll.await?, + _ => poll.await?, }; self.statement_telemetry .record_poll(status_started.elapsed()); @@ -522,8 +545,15 @@ impl ExecutedAsyncStatement { // reflect what THIS handle has observed (instead of the // stale initial-submit snapshot). self.record_latest_status(response.status.clone()); + // Latch the terminal observation so subsequent `status()` + // calls stop enforcing the client deadline against this + // already-finished statement. + if response.status.state.is_terminal() { + self.terminal_observed.store(true, Ordering::Release); + } let status = StatementStatus::from_sea_response(&response); - if matches!(status, StatementStatus::Pending | StatementStatus::Running) + if enforce_deadline + && matches!(status, StatementStatus::Pending | StatementStatus::Running) && self .client_deadline .is_some_and(|deadline| std::time::Instant::now() >= deadline) @@ -646,6 +676,12 @@ impl ExecutedAsyncStatement { // accessors reflect THIS poll's observation — not the // initial-submit snapshot that's now stale by minutes. self.record_latest_status(response.status.clone()); + // Latch the terminal observation so a later `status()` + // call stops enforcing the client deadline against this + // already-finished statement. + if response.status.state.is_terminal() { + self.terminal_observed.store(true, Ordering::Release); + } match StatementStatus::from_sea_response(&response) { StatementStatus::Succeeded | StatementStatus::Closed => { if let Some(g) = cancel_guard.take() { diff --git a/src/types/sea.rs b/src/types/sea.rs index 8d877c0c..57e00f22 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -151,6 +151,22 @@ pub enum StatementState { Closed, } +impl StatementState { + /// Whether this is a terminal state — the server has reached a + /// final outcome and will not transition further. Used to latch + /// the "terminal observed" flag so a retained client deadline + /// stops governing a handle once its statement has finished. + pub(crate) fn is_terminal(self) -> bool { + matches!( + self, + StatementState::Succeeded + | StatementState::Failed + | StatementState::Canceled + | StatementState::Closed + ) + } +} + /// Error information from the service. #[derive(Debug, Clone, Deserialize)] pub struct ServiceError { diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 8fec1da0..2a40649f 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -772,6 +772,80 @@ async fn await_result_drop_fires_cancel_statement() { ); } +/// `await_result()` must enforce the client query timeout on its own +/// poll loop (not just the `status()` path). Submitting with a short +/// deadline against an always-RUNNING server drives one of the loop's +/// deadline exits (pre-poll check / mid-poll `timeout_at` / terminal +/// `Pending|Running` arm), each of which defuses the cancel guard and +/// returns `expire_client_query_timeout()`. We assert the owning path +/// surfaces `ErrorCode::Timeout` / `HYT00` carrying the query id, and +/// that the guard still fired a best-effort server-side cancel on exit. +#[tokio::test] +async fn await_result_enforces_client_query_timeout_against_running_server() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + // Server never leaves RUNNING, so the only way out of the + // `await_result` loop is the client deadline expiring. + mount_submit(&server, pending_body("stmt-await-timeout")).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-await-timeout")) + .respond_with( + ResponseTemplate::new(200).set_body_string(running_body("stmt-await-timeout")), + ) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-await-timeout/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 1"); + let async_exec = stmt + .submit_with_timeout(std::time::Duration::from_millis(25)) + .await + .expect("submit"); + + let err = match async_exec.await_result().await { + Ok(_) => panic!("await_result against an always-RUNNING server must time out"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::Timeout); + assert_eq!(err.sql_state.as_deref(), Some("HYT00")); + assert_eq!( + err.query_id.as_deref(), + Some("stmt-await-timeout"), + "client query timeout must carry the observed statement id" + ); + + // The owning handle defuses the drop-cancel guard on timeout and + // fires a best-effort server-side cancel so the warehouse stops + // charging DBUs on the now-abandoned query. + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let cancel_calls = server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .filter(|req| { + req.method == wiremock::http::Method::POST + && req + .url + .path() + .ends_with("/statements/stmt-await-timeout/cancel") + }) + .count(); + assert!( + cancel_calls >= 1, + "await_result timeout should fire a best-effort cancel_statement; got {cancel_calls}" + ); +} + // ─── Extended SEA status fields on the async handle (PR #23) ──────── // // The accessors `num_modified_rows()` / `display_message()` / diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index cc0807d3..218577bc 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -2371,6 +2371,76 @@ async fn client_timeout_is_cumulative_across_retry_backoff() { assert_eq!(execute_posts, 1, "no retry may start after the deadline"); } +#[tokio::test] +async fn status_after_observed_terminal_ignores_client_deadline() { + // Regression: once `status()` has observed a terminal state, the + // retained client deadline must stop governing the handle. A later + // `status()` past the deadline must return the terminal state + // (not Timeout/HYT00) and must NOT fire a cancel/close against the + // already-finished statement. The deadline covers only "initial + // submit through observed terminal status". + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + // Submit returns RUNNING (wait_timeout=0s), so the handle starts + // pre-terminal with the client deadline armed. + mount_execute(&server, running_body("stmt-latch-terminal")).await; + // Every status poll reports SUCCEEDED. + mount_status( + &server, + "stmt-latch-terminal", + json!({ + "statement_id": "stmt-latch-terminal", + "status": { "state": "SUCCEEDED" }, + }) + .to_string(), + ) + .await; + // A cancel must never fire; mount it so an erroneous POST would be + // observable (and would otherwise 404). + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-latch-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 1"); + let async_exec = stmt + .submit_with_timeout(Duration::from_millis(100)) + .await + .expect("submit returns a handle"); + + // First poll observes the terminal SUCCEEDED (within the deadline). + let first = async_exec.status().await.expect("first status"); + assert_eq!(first.as_str(), "Succeeded"); + + // Let the client deadline elapse, then poll again. The latch must + // make this return SUCCEEDED rather than the client-query-timeout. + tokio::time::sleep(Duration::from_millis(200)).await; + let second = async_exec + .status() + .await + .expect("terminal status must survive the elapsed deadline"); + assert_eq!(second.as_str(), "Succeeded"); + + // No cancel RPC may have been dispatched against the finished query. + let cancels = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| { + r.method == wiremock::http::Method::POST + && r.url.path() == "/api/2.0/sql/statements/stmt-latch-terminal/cancel" + }) + .count(); + assert_eq!(cancels, 0, "a finished statement must not be cancelled"); +} + #[tokio::test] async fn terminal_error_mapping_is_inside_the_client_timeout_phase() { let server = MockServer::start().await; From 062e8a1ec3dab6f0d755f5b31d194dc41a54694d Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 23:13:19 +0000 Subject: [PATCH 07/10] ai: apply changes for #374 (1 review thread) Addresses: - #4161264563 at src/statement/executed_async.rs:634 Signed-off-by: peco-engineer-bot[bot] --- tests/v0_async_execute_wiremock.rs | 84 ++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 2a40649f..adaeb327 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -846,6 +846,90 @@ async fn await_result_enforces_client_query_timeout_against_running_server() { ); } +/// Companion to `await_result_enforces_client_query_timeout_against_running_server`, +/// which (with an instant-responding mock) only drives the loop-level deadline +/// checks — the pre-poll check and the terminal-arm `Pending|Running` check. +/// This test pins the THIRD, distinct exit: the mid-poll `tokio::time::timeout_at` +/// RPC-expiry branch, which fires only when the status RPC itself hangs past +/// `deadline + CLIENT_QUERY_TIMEOUT_STATUS_GRACE` (5s). We give the client a +/// deadline comfortably longer than the first pre-poll evaluation (so the loop +/// enters the RPC rather than bailing early) and make the `GetStatementStatus` +/// GET hang past the grace window, so `timeout_at` wins. As on the other exits, +/// the owning handle must defuse the cancel guard and surface +/// `ErrorCode::Timeout` / `HYT00` carrying the statement id. +#[tokio::test] +async fn await_result_client_query_timeout_fires_on_hung_status_poll() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + // Submit returns PENDING instantly, but the status GET hangs for + // 8s — longer than `deadline + CLIENT_QUERY_TIMEOUT_STATUS_GRACE` + // (~0.5s + 5s) — so the only way out of the loop is the mid-poll + // `timeout_at` RPC-expiry branch, NOT the pre-poll / terminal-arm + // checks. + mount_submit(&server, pending_body("stmt-hung-poll")).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-hung-poll")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(running_body("stmt-hung-poll")) + .set_delay(std::time::Duration::from_secs(8)), + ) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-hung-poll/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 1"); + // 500ms deadline: long enough that the first pre-poll check passes + // and we enter the (hung) status RPC, short enough that the test's + // bound is `deadline + grace` ≈ 5.5s, not the full 8s GET delay. + let async_exec = stmt + .submit_with_timeout(std::time::Duration::from_millis(500)) + .await + .expect("submit"); + + let err = match async_exec.await_result().await { + Ok(_) => panic!("await_result must time out when the status poll hangs past the deadline"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::Timeout); + assert_eq!(err.sql_state.as_deref(), Some("HYT00")); + assert_eq!( + err.query_id.as_deref(), + Some("stmt-hung-poll"), + "client query timeout must carry the observed statement id" + ); + + // The mid-poll exit defuses the drop-cancel guard and fires a + // best-effort server-side cancel, same as the other two exits. + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let cancel_calls = server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .filter(|req| { + req.method == wiremock::http::Method::POST + && req + .url + .path() + .ends_with("/statements/stmt-hung-poll/cancel") + }) + .count(); + assert!( + cancel_calls >= 1, + "mid-poll timeout_at exit should fire a best-effort cancel_statement; got {cancel_calls}" + ); +} + // ─── Extended SEA status fields on the async handle (PR #23) ──────── // // The accessors `num_modified_rows()` / `display_message()` / From 0d2a931a535961130c9fa495a104f45ee03ab279 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 23:16:14 +0000 Subject: [PATCH 08/10] ai: apply changes for #374 (1 review thread) Addresses: - #4161406588 at src/statement/executed_async.rs:634 Signed-off-by: peco-engineer-bot[bot] --- src/statement/executed_async.rs | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 1a2ef1be..78afc2b1 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -631,10 +631,20 @@ impl ExecutedAsyncStatement { loop { self.valid.check()?; - if self.client_timeout_expired.load(Ordering::Acquire) - || self - .client_deadline - .is_some_and(|deadline| std::time::Instant::now() >= deadline) + // The client deadline governs only the pre-terminal + // window. Once this handle has observed a terminal state + // (here or via a prior `status()` / initial-submit + // snapshot), stop enforcing the deadline so we proceed to + // materialise the finished result instead of masking it + // with a `Timeout`/`HYT00` and firing a wasted + // cancel+close against an already-finished statement — + // mirrors the `enforce_deadline` gating in `status()`. + let enforce_deadline = !self.terminal_observed.load(Ordering::Acquire); + if enforce_deadline + && (self.client_timeout_expired.load(Ordering::Acquire) + || self + .client_deadline + .is_some_and(|deadline| std::time::Instant::now() >= deadline)) { if let Some(g) = cancel_guard.take() { g.defuse(); @@ -647,7 +657,7 @@ impl ExecutedAsyncStatement { .transport() .statement_status(&self.statement_id, self.session_attribution()); let response = match self.client_deadline { - Some(deadline) => { + Some(deadline) if enforce_deadline => { let poll_deadline = deadline .checked_add( crate::statement::timeout::CLIENT_QUERY_TIMEOUT_STATUS_GRACE, @@ -668,7 +678,7 @@ impl ExecutedAsyncStatement { } } } - None => poll.await?, + _ => poll.await?, }; self.statement_telemetry .record_poll(status_started.elapsed()); @@ -713,9 +723,10 @@ impl ExecutedAsyncStatement { return Err(error); } StatementStatus::Pending | StatementStatus::Running => { - if self - .client_deadline - .is_some_and(|deadline| std::time::Instant::now() >= deadline) + if enforce_deadline + && self + .client_deadline + .is_some_and(|deadline| std::time::Instant::now() >= deadline) { if let Some(g) = cancel_guard.take() { g.defuse(); From 4bb72ad0655cb54e06909ec69e267b8eb0703ea0 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 23:33:45 +0000 Subject: [PATCH 09/10] ai: apply changes for #374 (1 review thread) Addresses: - #4161511147 at src/statement/mutable.rs:497 Signed-off-by: peco-engineer-bot[bot] --- tests/v0_async_execute_wiremock.rs | 74 ++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index adaeb327..82675e24 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -930,6 +930,80 @@ async fn await_result_client_query_timeout_fires_on_hung_status_poll() { ); } +/// Companion to `await_result_client_query_timeout_fires_on_hung_status_poll`, +/// pinning the OTHER `tokio::time::timeout_at` exit on the submit path: the +/// mid-*submit* deadline-expiry branch, where the `POST /statements` RPC itself +/// hangs past the deadline. This branch has distinct observable behavior from +/// the status-poll exit: because `cancel_state.observe` runs only after `submit` +/// resolves, a timeout before that leaves the statement id unknown, so the +/// surfaced `Timeout`/`HYT00` error carries a `None` query id and NO server-side +/// cancel/close is scheduled (there is no id to target). The same `set_delay` +/// technique as the status-poll test covers it — delay the `POST /statements` +/// past the deadline so `timeout_at` wins. +#[tokio::test] +async fn submit_with_timeout_client_query_timeout_fires_on_hung_submit() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + // The submit POST hangs for 8s — far longer than the 300ms deadline — + // so the only way out is the mid-submit `timeout_at` RPC-expiry branch. + // The response body never matters because the deadline fires first. + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(pending_body("stmt-hung-submit")) + .set_delay(std::time::Duration::from_secs(8)), + ) + .mount(&server) + .await; + // Mount a cancel endpoint so that, if the kernel erroneously tried to + // cancel, the request would be recorded (and the negative assertion + // below would catch it). + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-hung-submit/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 1"); + let err = match stmt + .submit_with_timeout(std::time::Duration::from_millis(300)) + .await + { + Ok(_) => panic!("submit_with_timeout must time out when the submit POST hangs"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::Timeout); + assert_eq!(err.sql_state.as_deref(), Some("HYT00")); + // No statement id was observed before the deadline fired, so the error + // carries no query id — distinct from the status-poll exit. + assert_eq!( + err.query_id, None, + "mid-submit timeout cannot know the server statement id, so query_id must be None" + ); + + // Because the id is unknown, no best-effort cancel/close can be scheduled. + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let cancel_calls = server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .filter(|req| { + req.method == wiremock::http::Method::POST && req.url.path().ends_with("/cancel") + }) + .count(); + assert_eq!( + cancel_calls, 0, + "mid-submit timeout has no id to target, so no cancel_statement should fire; got {cancel_calls}" + ); +} + // ─── Extended SEA status fields on the async handle (PR #23) ──────── // // The accessors `num_modified_rows()` / `display_message()` / From 5653e36b7adfd91a4f683c64702e001b618de049 Mon Sep 17 00:00:00 2001 From: Jay Xiao Date: Fri, 2 Oct 2026 02:57:45 +0000 Subject: [PATCH 10/10] fix(ci): allow async-trait double must-use lint Signed-off-by: Jay Xiao --- src/lib.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 43938e3d..7661bc0b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,6 +14,12 @@ //! Databricks SQL Kernel //! +// `async_trait` marks its generated boxed futures as `must_use`. Rust 1.99's +// `double_must_use` lint also sees the `Future` trait's own annotation, so all +// async trait methods otherwise fail Clippy despite having the intended +// must-use behavior. +#![allow(clippy::double_must_use)] +//! //! Rust client core for Databricks SQL — the shared engine that powers //! the Databricks ODBC, Python, Go, and Node.js drivers. //!