fix: add SQL query timeout and cancellation controls

Add per-query SQL deadlines, read timeouts, and drop cancellation controls for Rust and Python.
This commit is contained in:
Jack Ye
2026-11-21 14:35:04 -08:00
committed by GitHub
parent 7970d3075c
commit e3e55844bc
21 changed files with 834 additions and 52 deletions
+28
View File
@@ -5,6 +5,7 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use arrow_array::RecordBatch;
use arrow_schema::SchemaRef;
@@ -427,6 +428,33 @@ impl ExecuteQueryAsyncBuilder {
}
}
/// Limit this execution from submission through result consumption.
///
/// Expiry stops result reads and attempts to cancel Flight execution, even
/// if no reader was opened. It does not cancel durable server-side jobs.
/// Without this option, the connection's existing timeout settings apply.
pub fn timeout(mut self, timeout: Duration) -> Self {
self.request.options.timeout = Some(timeout);
self
}
/// Override the connection's timeout for each server read on this query.
pub fn read_timeout(mut self, timeout: Duration) -> Self {
self.request.options.read_timeout = Some(timeout);
self
}
/// Cancel deferred Flight execution when its unread handle or reader is dropped.
///
/// This is best effort and requires the submitting Tokio runtime to remain
/// alive. Defaults to false, allowing deferred queries to be detached.
/// Directly streamed queries already stop on drop. Durable jobs require
/// explicit job cancellation regardless of this setting.
pub fn cancel_on_drop(mut self, cancel: bool) -> Self {
self.request.options.cancel_on_drop = cancel;
self
}
/// Set the namespace used for unqualified table names.
///
/// An empty path is treated as `public`, which is the SQL name for the
+3
View File
@@ -212,6 +212,8 @@ pub struct ExecuteQueryRequest {
/// also binds `$<name>`. See
/// [`ExecuteQueryAsyncBuilder::parameters`](crate::connection::ExecuteQueryAsyncBuilder::parameters).
pub parameters: Option<RecordBatch>,
/// Execution limits and cancellation behavior for this statement.
pub options: crate::sql::QueryOptions,
}
impl ExecuteQueryRequest {
@@ -220,6 +222,7 @@ impl ExecuteQueryRequest {
query: query.into(),
default_namespace_path: vec!["public".to_string()],
parameters: None,
options: Default::default(),
}
}
}
+3
View File
@@ -1008,6 +1008,7 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
query: sql,
default_namespace_path: namespace_path.to_vec(),
parameters: None,
options: Default::default(),
})
.await?;
integration_sql::decode_info(&result.reader().await?.try_collect::<Vec<_>>().await?)
@@ -1024,6 +1025,7 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
query: format!("DESCRIBE STORAGE INTEGRATION {name}"),
default_namespace_path: namespace_path.to_vec(),
parameters: None,
options: Default::default(),
})
.await?;
integration_sql::decode_info(&result.reader().await?.try_collect::<Vec<_>>().await?)
@@ -1046,6 +1048,7 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
query: format!("DROP STORAGE INTEGRATION {name}"),
default_namespace_path: namespace_path.to_vec(),
parameters: None,
options: Default::default(),
})
.await?;
result.reader().await?.try_collect::<Vec<_>>().await?;
+210 -20
View File
@@ -51,8 +51,10 @@ const DEFAULT_SQL_PORT: u16 = 10025;
const DEFAULT_SQL_TLS_PORT: u16 = 10026;
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(120);
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(300);
const AUTOMATIC_CANCELLATION_TIMEOUT: Duration = Duration::from_secs(5);
const STATUS_POLL_TIMEOUT: Duration = Duration::from_secs(1);
const MIN_POLL_INTERVAL: Duration = Duration::from_millis(50);
const MAX_SQL_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 60 * 60);
const MAX_SQL_MESSAGE_SIZE: usize = 1024 * 1024 * 1024;
const SQL_JOB_ID_METADATA_KEY: &str = "x-lancedb-sql-job-id";
const TERMINAL_QUERY_RETENTION: Duration = Duration::from_secs(300);
@@ -69,6 +71,7 @@ pub(super) struct SubmittedQuery {
pub(super) materialized_view_job_handle_supported: bool,
}
#[derive(Clone)]
struct SqlClientInner {
database: String,
database_prefix: Option<String>,
@@ -77,6 +80,8 @@ struct SqlClientInner {
sql_host_override: Option<String>,
client_config: ClientConfig,
client: Arc<OnceCell<SqlConnection>>,
deadline: Option<tokio::time::Instant>,
cancel_on_drop: bool,
}
struct SqlConnection {
@@ -213,6 +218,8 @@ impl SqlClient {
sql_host_override,
client_config,
client: Arc::new(OnceCell::new()),
deadline: None,
cancel_on_drop: false,
}),
queries: Arc::new(QueryRegistry::new()),
}
@@ -279,12 +286,34 @@ impl SqlClient {
request: ExecuteQueryRequest,
materialized_view_job_handle: bool,
) -> Result<SubmittedQuery> {
let timeout = self.inner.overall_timeout()?;
let mut client = self.inner.as_ref().clone();
client.deadline = request
.options
.timeout
.map(|timeout| {
if timeout > MAX_SQL_TIMEOUT {
return Err(Error::InvalidInput {
message: "SQL query timeout exceeds the gRPC limit".to_string(),
});
}
tokio::time::Instant::now()
.checked_add(timeout)
.ok_or_else(|| Error::InvalidInput {
message: "SQL query timeout is too large".to_string(),
})
})
.transpose()?;
client.cancel_on_drop = request.options.cancel_on_drop;
if let Some(read_timeout) = request.options.read_timeout {
client.client_config.timeout_config.read_timeout = Some(read_timeout);
}
let client = Arc::new(client);
let timeout = client.execution_timeout()?;
with_overall_timeout(timeout, "SQL query submission", async {
validate_namespace_path(&request.default_namespace_path)?;
let query_id = Uuid::now_v7();
let opened = StreamingQuery::open(
self.inner.clone(),
client.clone(),
&request.query,
request.parameters,
&request.default_namespace_path,
@@ -300,24 +329,26 @@ impl SqlClient {
Submission::Stream(response) => {
let query = Arc::new(StreamingQuery::new(
query_id,
self.inner.clone(),
client.clone(),
response,
job_id.clone(),
));
self.queries
.insert(query_id, RegisteredQuery::Streamed(query.clone()));
query.start_deadline();
Query::new(Arc::new(StreamingQueryHandle::new(query)))
}
Submission::Deferred(poll_info) => {
let query = Arc::new(RemoteQuery::new(
query_id,
self.inner.clone(),
client.clone(),
request.default_namespace_path,
poll_info,
job_id,
)?);
self.queries
.insert(query_id, RegisteredQuery::Polled(query.clone()));
query.start_deadline();
Query::new(Arc::new(RemoteQueryHandle::new(query)))
}
};
@@ -375,6 +406,7 @@ impl SqlClient {
query: statement,
default_namespace_path: namespace,
parameters: None,
options: Default::default(),
})
.await?,
);
@@ -417,6 +449,21 @@ impl SqlClient {
}
impl SqlClientInner {
fn execution_timeout(&self) -> Result<Option<Duration>> {
match self.deadline {
Some(deadline) => Ok(Some(
deadline.saturating_duration_since(tokio::time::Instant::now()),
)),
None => self.overall_timeout(),
}
}
fn set_execution_timeout<T>(&self, request: &mut Request<T>) {
if let Some(deadline) = self.deadline {
request.set_timeout(deadline.saturating_duration_since(tokio::time::Instant::now()));
}
}
fn overall_timeout(&self) -> Result<Option<Duration>> {
resolve_timeout(
self.client_config.timeout_config.timeout,
@@ -561,6 +608,7 @@ impl SqlClientInner {
.clone();
let mut request = Request::new(ticket);
*request.metadata_mut() = metadata;
self.set_execution_timeout(&mut request);
let response =
tokio::time::timeout(read_timeout, connection.client.clone().do_get(request))
.await
@@ -801,6 +849,10 @@ struct RemoteQuery {
last_accessed: StdMutex<Instant>,
lifecycle: StdMutex<QueryLifecycle>,
cancel_request_uncertain: Arc<AtomicBool>,
failure: StdMutex<Option<String>>,
cleanup_started: AtomicBool,
runtime: tokio::runtime::Handle,
deadline_task: StdMutex<Option<tokio::task::AbortHandle>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -843,9 +895,75 @@ impl RemoteQuery {
last_accessed: StdMutex::new(Instant::now()),
lifecycle: StdMutex::new(lifecycle),
cancel_request_uncertain: Arc::new(AtomicBool::new(false)),
failure: StdMutex::new(None),
cleanup_started: AtomicBool::new(false),
runtime: tokio::runtime::Handle::current(),
deadline_task: StdMutex::new(None),
})
}
fn start_deadline(self: &Arc<Self>) {
let Some(deadline) = self.client.deadline else {
return;
};
let query = Arc::downgrade(self);
let task = self.runtime.spawn(async move {
tokio::time::sleep_until(deadline).await;
if let Some(query) = query.upgrade()
&& !matches!(
query.lifecycle(),
QueryLifecycle::Completed | QueryLifecycle::Cancelled
)
{
query.fail(&sql_result_timeout());
}
});
*self.deadline_task.lock().unwrap() = Some(task.abort_handle());
}
fn stop_deadline(&self) {
if let Some(task) = self.deadline_task.lock().unwrap().take() {
task.abort();
}
}
fn fail(self: &Arc<Self>, error: &Error) {
let lifecycle = self.lifecycle.lock().unwrap();
if matches!(
*lifecycle,
QueryLifecycle::Completed | QueryLifecycle::Cancelled | QueryLifecycle::Cancelling
) {
return;
}
self.failure
.lock()
.unwrap()
.get_or_insert_with(|| match error {
Error::Runtime { message } => message.clone(),
other => other.to_string(),
});
drop(lifecycle);
self.stop_deadline();
self.mark_terminal();
self.cancelled.notify_waiters();
self.cancel_in_background();
}
fn cancel_in_background(self: &Arc<Self>) {
if matches!(
self.lifecycle(),
QueryLifecycle::Completed | QueryLifecycle::Cancelled
) || self.cleanup_started.swap(true, Ordering::SeqCst)
{
return;
}
let query = self.clone();
self.runtime.spawn(async move {
let _ =
tokio::time::timeout(AUTOMATIC_CANCELLATION_TIMEOUT, query.cancel_inner()).await;
});
}
fn registry_expired(&self, abandoned: bool) -> bool {
if let Some(finished) = self.terminal_at.get() {
return finished.elapsed() >= TERMINAL_QUERY_RETENTION;
@@ -882,6 +1000,7 @@ impl RemoteQuery {
}
*lifecycle = QueryLifecycle::Cancelled;
drop(lifecycle);
self.stop_deadline();
self.mark_terminal();
self.cancelled.notify_waiters();
self.state_changed.notify_waiters();
@@ -916,13 +1035,17 @@ impl RemoteQuery {
fn mark_result_completed(&self) -> Result<()> {
let mut lifecycle = self.lifecycle.lock().unwrap();
if matches!(
*lifecycle,
QueryLifecycle::Cancelling | QueryLifecycle::Cancelled
) {
if self.failure.lock().unwrap().is_some()
|| matches!(
*lifecycle,
QueryLifecycle::Cancelling | QueryLifecycle::Cancelled
)
{
return Err(self.cancelled_error());
}
*lifecycle = QueryLifecycle::Completed;
drop(lifecycle);
self.stop_deadline();
Ok(())
}
@@ -931,13 +1054,20 @@ impl RemoteQuery {
}
fn is_cancellation_requested(&self) -> bool {
matches!(
self.lifecycle(),
QueryLifecycle::Cancelling | QueryLifecycle::Cancelled
)
let failed = self.failure.lock().unwrap().is_some();
failed
|| matches!(
self.lifecycle(),
QueryLifecycle::Cancelling | QueryLifecycle::Cancelled
)
}
fn cancelled_error(&self) -> Error {
if let Some(message) = self.failure.lock().unwrap().as_ref() {
return Error::Runtime {
message: message.clone(),
};
}
Error::JobCancelled {
job_id: Some(self.id.to_string()),
}
@@ -1214,6 +1344,9 @@ impl RemoteQuery {
async fn describe_inner(&self) -> Result<QueryDescription> {
self.touch();
if self.failure.lock().unwrap().is_some() {
return Err(self.cancelled_error());
}
if self.is_cancellation_requested() {
let state = self.state.lock().await.clone();
return query_description(self.id, self.job_id(), &state, self.lifecycle());
@@ -1380,6 +1513,14 @@ impl RemoteQuery {
}
}
struct CancelQueryOnDrop(Arc<RemoteQuery>);
impl Drop for CancelQueryOnDrop {
fn drop(&mut self) {
self.0.cancel_in_background();
}
}
struct RemoteQueryHandle {
query: Arc<RemoteQuery>,
result_started: AtomicBool,
@@ -1394,6 +1535,14 @@ impl RemoteQueryHandle {
}
}
impl Drop for RemoteQueryHandle {
fn drop(&mut self) {
if self.query.client.cancel_on_drop && !self.result_started.load(Ordering::SeqCst) {
self.query.cancel_in_background();
}
}
}
#[async_trait::async_trait]
impl QueryHandle for RemoteQueryHandle {
fn id(&self) -> Uuid {
@@ -1410,7 +1559,10 @@ impl QueryHandle for RemoteQueryHandle {
}
async fn reader(&self) -> Result<SendableRecordBatchStream> {
let timeout = self.query.client.overall_timeout()?;
let timeout = self.query.client.execution_timeout()?;
if self.query.failure.lock().unwrap().is_some() {
return Err(self.query.cancelled_error());
}
if self
.result_started
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
@@ -1421,9 +1573,22 @@ impl QueryHandle for RemoteQueryHandle {
});
}
let result_start = ResultStartGuard::new(&self.result_started);
let cancel_on_drop = self
.query
.client
.cancel_on_drop
.then(|| CancelQueryOnDrop(self.query.clone()));
let started = Instant::now();
let prepared =
with_overall_timeout(timeout, "SQL query result", self.query.prepare_result()).await?;
match with_overall_timeout(timeout, "SQL query result", self.query.prepare_result())
.await
{
Ok(prepared) => prepared,
Err(error) => {
self.query.fail(&error);
return Err(error);
}
};
let remaining_timeout = timeout.map(|timeout| timeout.saturating_sub(started.elapsed()));
let schema = prepared.schema.clone();
let (sender, receiver) = mpsc::channel(2);
@@ -1433,19 +1598,17 @@ impl QueryHandle for RemoteQueryHandle {
let result = with_overall_timeout(
remaining_timeout,
"SQL query result",
query.run_result_stream(prepared, sender),
query.clone().run_result_stream(prepared, sender),
)
.await;
if let Err(error) = result {
query.fail(&error);
let _ = error_sender.send(Err(error)).await;
}
});
let stream = futures::stream::unfold(receiver, |mut receiver| async move {
receiver.recv().await.map(|item| (item, receiver))
});
result_start.commit();
let stream: SendableRecordBatchStream =
Box::pin(SimpleRecordBatchStream::new(stream, schema));
let stream =
sql_result_stream(receiver, schema, self.query.client.deadline, cancel_on_drop);
Ok(match self.job_id() {
Some(job_id) => attach_sql_job_id(stream, &job_id),
None => stream,
@@ -1457,6 +1620,33 @@ impl QueryHandle for RemoteQueryHandle {
}
}
fn sql_result_timeout() -> Error {
Error::Runtime {
message: "SQL query result timed out".to_string(),
}
}
fn sql_result_stream<G: Send + 'static>(
receiver: mpsc::Receiver<Result<RecordBatch>>,
schema: SchemaRef,
deadline: Option<tokio::time::Instant>,
guard: G,
) -> SendableRecordBatchStream {
let stream = futures::stream::unfold(Some((receiver, guard)), move |state| async move {
let (mut receiver, guard) = state?;
let item = match deadline {
Some(deadline) => tokio::select! {
biased;
_ = tokio::time::sleep_until(deadline) => return Some((Err(sql_result_timeout()), None)),
item = receiver.recv() => item,
},
None => receiver.recv().await,
};
item.map(|item| (item, Some((receiver, guard))))
});
Box::pin(SimpleRecordBatchStream::new(stream, schema))
}
fn query_description(
id: Uuid,
job_id: Option<String>,
+3
View File
@@ -51,6 +51,7 @@ impl SqlClient {
),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
},
definition,
)
@@ -76,6 +77,7 @@ impl SqlClient {
),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
},
definition,
)
@@ -119,6 +121,7 @@ impl SqlClient {
),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
},
|batches| {
let rows = strings(&batches, "status")?;
@@ -55,6 +55,7 @@ impl SqlClient {
query: statement,
default_namespace_path: namespace,
parameters: None,
options: Default::default(),
},
true,
)
@@ -133,6 +134,7 @@ impl SqlClient {
query: format!("DESCRIBE MATERIALIZED VIEW {}", quote_identifier(name)),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
})
.await?;
let mut reader = query.reader().await?;
+1
View File
@@ -54,6 +54,7 @@ impl SqlClient {
query: statement,
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
})
.await?;
let reader = query.reader().await?;
+3
View File
@@ -83,6 +83,7 @@ impl SqlClient {
),
default_namespace_path: namespace.to_vec(),
parameters: Some(parameters),
options: Default::default(),
},
|_| Ok(()),
)
@@ -102,6 +103,7 @@ impl SqlClient {
query: format!("DESCRIBE SECRET {}", quote_identifier(name)),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
},
secret_info,
)
@@ -121,6 +123,7 @@ impl SqlClient {
query: format!("DROP SECRET IF EXISTS {}", quote_identifier(name)),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
},
|_| Ok(()),
)
+42 -16
View File
@@ -21,9 +21,9 @@ use uuid::Uuid;
use super::{
ABANDONED_QUERY_RETENTION, DEFAULT_READ_TIMEOUT, ResultEndpointStream, ResultStartGuard,
SqlClientInner, TERMINAL_QUERY_RETENTION, resolve_timeout, sql_error, sql_flight_error,
sql_status_error, with_overall_timeout,
sql_result_stream, sql_status_error, with_overall_timeout,
};
use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream};
use crate::arrow::SendableRecordBatchStream;
use crate::error::{Error, Result};
use crate::sql::{QueryDescription, QueryHandle, QueryStatus};
@@ -56,6 +56,7 @@ pub(super) struct StreamingQuery {
terminal_at: OnceLock<Instant>,
last_accessed: StdMutex<Instant>,
job_id: StdMutex<Option<String>>,
deadline_task: StdMutex<Option<tokio::task::AbortHandle>>,
}
struct PreparedStream {
@@ -183,11 +184,13 @@ impl StreamingQuery {
.map_err(|error| sql_flight_error(&request_id, &error))?;
let mut request = tonic::Request::new(futures::stream::iter(messages));
*request.metadata_mut() = metadata;
client.set_execution_timeout(&mut request);
tokio::time::timeout(read_timeout, flight.do_exchange(request)).await
} else {
let mut request =
tonic::Request::new(Ticket::new(CommandTicket { command }.encode_to_vec()));
*request.metadata_mut() = metadata;
client.set_execution_timeout(&mut request);
tokio::time::timeout(read_timeout, flight.do_get(request)).await
}
.map_err(|_| sql_error(&request_id, "SQL query submission timed out"))?
@@ -271,9 +274,30 @@ impl StreamingQuery {
terminal_at: OnceLock::new(),
last_accessed: StdMutex::new(Instant::now()),
job_id: StdMutex::new(job_id.filter(|job_id| !job_id.is_empty())),
deadline_task: StdMutex::new(None),
}
}
pub(super) fn start_deadline(self: &Arc<Self>) {
let Some(deadline) = self.client.deadline else {
return;
};
let query = Arc::downgrade(self);
let task = tokio::spawn(async move {
tokio::time::sleep_until(deadline).await;
if let Some(query) = query.upgrade() {
query.settle(Lifecycle::Failed("SQL query result timed out".to_string()));
query.response.lock().unwrap().take();
}
});
*self.deadline_task.lock().unwrap() = Some(task.abort_handle());
}
#[cfg(test)]
pub(super) fn deadline_stopped(&self) -> bool {
self.deadline_task.lock().unwrap().is_none()
}
pub(super) fn touch(&self) {
*self.last_accessed.lock().unwrap() = Instant::now();
}
@@ -328,11 +352,18 @@ impl StreamingQuery {
*lifecycle = state;
drop(lifecycle);
let _ = self.terminal_at.set(Instant::now());
if let Some(task) = self.deadline_task.lock().unwrap().take() {
task.abort();
}
self.cancelled.notify_waiters();
true
}
fn is_cancelled(&self) -> bool {
*self.lifecycle.lock().unwrap() == Lifecycle::Cancelled
matches!(
*self.lifecycle.lock().unwrap(),
Lifecycle::Cancelled | Lifecycle::Failed(_)
)
}
fn job_id(&self) -> Option<String> {
@@ -359,6 +390,11 @@ impl StreamingQuery {
}
fn cancelled_error(&self) -> Error {
if let Lifecycle::Failed(message) = &*self.lifecycle.lock().unwrap() {
return Error::Runtime {
message: message.clone(),
};
}
Error::JobCancelled {
job_id: Some(self.id.to_string()),
}
@@ -377,13 +413,7 @@ impl StreamingQuery {
/// Take the rows and wait for the first batch, which carries the schema.
async fn prepare(&self) -> Result<PreparedStream> {
let Some(rows) = self.response.lock().unwrap().take() else {
// Taken by an earlier attempt that failed, or dropped by a cancel.
return Err(match &*self.lifecycle.lock().unwrap() {
Lifecycle::Failed(message) => Error::Runtime {
message: message.clone(),
},
_ => self.cancelled_error(),
});
return Err(self.cancelled_error());
};
let mut rows = Borrowed {
query: self,
@@ -518,7 +548,7 @@ impl QueryHandle for StreamingQueryHandle {
}
async fn reader(&self) -> Result<SendableRecordBatchStream> {
let timeout = self.query.client.overall_timeout()?;
let timeout = self.query.client.execution_timeout()?;
if self
.result_started
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
@@ -559,12 +589,8 @@ impl QueryHandle for StreamingQueryHandle {
let _ = error_sender.send(Err(error)).await;
}
});
let stream = futures::stream::unfold(receiver, |mut receiver| async move {
receiver.recv().await.map(|item| (item, receiver))
});
result_start.commit();
let stream: SendableRecordBatchStream =
Box::pin(SimpleRecordBatchStream::new(stream, schema));
let stream = sql_result_stream(receiver, schema, self.query.client.deadline, ());
Ok(match self.job_id() {
Some(job_id) => super::attach_sql_job_id(stream, &job_id),
None => stream,
+2
View File
@@ -111,6 +111,7 @@ impl SqlClient {
),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
},
move |batches| view_description(batches, namespace_path),
)
@@ -132,6 +133,7 @@ impl SqlClient {
query: format!("DESCRIBE VIEW {}", quote_identifier(name)),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
},
move |batches| view_description(batches, namespace_path),
)
+285 -5
View File
@@ -116,6 +116,7 @@ struct CapturedHeaders {
api_key: String,
database_prefix: String,
materialized_view_job_handle: Option<String>,
grpc_timeout: Option<String>,
}
/// Every exchange's statement and the parameter row it arrived with.
@@ -138,6 +139,7 @@ struct TestSqlService {
first_continuation_count: Arc<AtomicUsize>,
transient_poll_failures: Arc<AtomicUsize>,
headers: Arc<std::sync::Mutex<Vec<CapturedHeaders>>>,
result_deadlines: Arc<std::sync::Mutex<Vec<Option<String>>>>,
gate_refresh_release: Arc<Notify>,
exchanges: ReceivedExchanges,
result_overrides: Arc<std::sync::Mutex<HashMap<String, RecordBatch>>>,
@@ -172,6 +174,9 @@ impl TestSqlService {
.to_string()
};
self.headers.lock().unwrap().push(CapturedHeaders {
grpc_timeout: metadata
.get("grpc-timeout")
.map(|value| value.to_str().unwrap().to_owned()),
database: header("database"),
namespace_path: header("namespace-path"),
request_id: header("x-request-id"),
@@ -315,6 +320,7 @@ impl Default for TestSqlService {
first_continuation_count: Arc::new(AtomicUsize::new(0)),
transient_poll_failures: Arc::new(AtomicUsize::new(0)),
headers: Arc::new(std::sync::Mutex::new(Vec::new())),
result_deadlines: Arc::new(std::sync::Mutex::new(Vec::new())),
gate_refresh_release: Arc::new(Notify::new()),
exchanges: Arc::new(std::sync::Mutex::new(Vec::new())),
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())),
@@ -533,6 +539,14 @@ impl FlightService for TestSqlService {
PROTOCOL_VERSION
);
}
if initial.is_none() {
self.result_deadlines.lock().unwrap().push(
request
.metadata()
.get("grpc-timeout")
.map(|value| value.to_str().unwrap().to_owned()),
);
}
let query = initial
.as_ref()
.map(|command| command.query.as_bytes())
@@ -1584,6 +1598,7 @@ async fn fast_durable_job_failure_exposes_the_same_job_id_on_the_query_handle()
query: "SELECT durable job failure".into(),
default_namespace_path: vec![],
parameters: None,
options: Default::default(),
})
.await
.unwrap();
@@ -1937,10 +1952,12 @@ async fn submits_polls_fetches_cancels_and_reuses_client() {
.delay_next
.store(true, Ordering::SeqCst);
assert_overall_timeout(collect_result(&timeout_query).await, "result");
timeout_header_provider
.delay_next
.store(true, Ordering::SeqCst);
assert_overall_timeout(timeout_query.cancel().await, "cancellation");
wait_for(
&cancel_count,
1,
"the overall timeout must cancel execution",
)
.await;
timeout_query.cancel().await.unwrap();
let pre_dispatch_timeout = timeout_client
@@ -2346,7 +2363,14 @@ async fn submits_polls_fetches_cancels_and_reuses_client() {
.submit("SELECT fail", &["public".to_string()])
.await
.unwrap();
let before_failure = cancel_count.load(Ordering::SeqCst);
assert!(collect_result(&failed).await.is_err());
wait_for(
&cancel_count,
before_failure + 1,
"failed result reads must cancel execution",
)
.await;
let registry = QueryRegistry::new();
for descriptor in ["active-one", "active-two"] {
@@ -2411,7 +2435,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() {
assert_eq!(client.initialized_client_count().await, 1);
assert_eq!(query_count.load(Ordering::SeqCst), 21);
assert_eq!(do_get_count.load(Ordering::SeqCst), 17);
assert_eq!(cancel_count.load(Ordering::SeqCst), 15);
assert_eq!(cancel_count.load(Ordering::SeqCst), 16);
assert_eq!(first_result, vec![expected.clone()]);
assert!(empty_result.is_empty());
assert!(client.describe(Uuid::nil()).await.is_err());
@@ -5066,3 +5090,259 @@ async fn remote_cleanup_preview_uses_sql_without_job_calls() {
);
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn sql_deadline_expires_unread_streamed_and_deferred_queries() {
for deferred in [false, true] {
for parameters in [None, Some(parameter_row())] {
let service = TestSqlService {
adaptive: true,
defer: deferred,
..TestSqlService::default()
};
let cancellations = service.cancel_count.clone();
let headers = service.headers.clone();
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let mut request = ExecuteQueryRequest::new("SELECT slow get");
request.parameters = parameters;
request.options.timeout = Some(Duration::from_secs(3));
let query = client.execute(request).await.unwrap();
assert!(headers.lock().unwrap()[0].grpc_timeout.is_some());
tokio::time::pause();
tokio::time::advance(Duration::from_secs(4)).await;
tokio::task::yield_now().await;
tokio::time::resume();
assert_overall_timeout(query.describe().await, "result");
assert_overall_timeout(client.describe(query.id()).await, "result");
assert_overall_timeout(query.reader().await, "result");
if deferred {
wait_for(
&cancellations,
1,
"expiry must cancel deferred execution without a reader",
)
.await;
}
let ordinary = client
.execute(ExecuteQueryRequest::new("SELECT 1"))
.await
.unwrap();
assert!(
!collect_result(&ordinary).await.unwrap().is_empty(),
"query options must not change the connection defaults"
);
}
}
}
#[tokio::test]
async fn a_deferred_result_timeout_sends_cancellation() {
let service = TestSqlService {
adaptive: true,
defer: true,
..TestSqlService::default()
};
let cancellations = service.cancel_count.clone();
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let mut request = ExecuteQueryRequest::new("SELECT slow get");
request.options.timeout = Some(Duration::from_secs(3));
let query = client.execute(request).await.unwrap();
tokio::time::pause();
tokio::time::advance(Duration::from_millis(2_900)).await;
let result = query.reader().await;
tokio::time::resume();
assert_overall_timeout(result, "result");
wait_for(
&cancellations,
1,
"a deferred reader timeout must cancel execution",
)
.await;
}
#[tokio::test]
async fn sql_read_timeout_is_per_query_and_cancels_deferred_execution() {
let service = TestSqlService {
adaptive: true,
defer: true,
..TestSqlService::default()
};
let cancellations = service.cancel_count.clone();
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let mut request = ExecuteQueryRequest::new("SELECT slow get");
request.options.read_timeout = Some(Duration::from_millis(100));
let query = client.execute(request).await.unwrap();
let error = collect_result(&query).await.unwrap_err();
assert!(
error.to_string().contains("SQL result read timed out"),
"{error}"
);
wait_for(
&cancellations,
1,
"a read timeout must cancel deferred execution",
)
.await;
let next = client
.execute(ExecuteQueryRequest::new("SELECT slow get"))
.await
.unwrap();
assert!(!collect_result(&next).await.unwrap().is_empty());
}
#[tokio::test]
async fn deferred_cancellation_on_drop_is_opt_in() {
let service = TestSqlService {
adaptive: true,
defer: true,
..TestSqlService::default()
};
let cancellations = service.cancel_count.clone();
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let detached = client
.execute(ExecuteQueryRequest::new("SELECT 1"))
.await
.unwrap();
let id = detached.id();
drop(detached);
assert_eq!(
client.describe(id).await.unwrap().status,
QueryStatus::Finished
);
assert_eq!(cancellations.load(Ordering::SeqCst), 0);
let mut request = ExecuteQueryRequest::new("SELECT 1");
request.options.cancel_on_drop = true;
let query = client.execute(request).await.unwrap();
let id = query.id();
// Drop outside the async runtime, as Python garbage collection may do.
std::thread::spawn(move || drop(query)).join().unwrap();
wait_for(&cancellations, 1, "dropping an opted-in handle must cancel").await;
assert_eq!(
client.describe(id).await.unwrap().status,
QueryStatus::Cancelled
);
}
#[tokio::test]
async fn deferred_reader_owns_cancellation_after_the_handle_is_dropped() {
let service = TestSqlService {
adaptive: true,
defer: true,
..TestSqlService::default()
};
let cancellations = service.cancel_count.clone();
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let mut request = ExecuteQueryRequest::new("SELECT slow");
request.options.cancel_on_drop = true;
let query = client.execute(request).await.unwrap();
let rows = query.reader().await.unwrap();
drop(query);
assert_eq!(
cancellations.load(Ordering::SeqCst),
0,
"an active reader must survive dropping its query handle"
);
drop(rows);
wait_for(
&cancellations,
1,
"dropping the reader must cancel deferred execution",
)
.await;
}
#[tokio::test]
async fn a_completed_query_is_not_cancelled_on_drop_or_deadline() {
let service = TestSqlService {
adaptive: true,
defer: true,
..TestSqlService::default()
};
let cancellations = service.cancel_count.clone();
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let mut request = ExecuteQueryRequest::new("SELECT 1");
request.options.timeout = Some(Duration::from_secs(3));
request.options.cancel_on_drop = true;
let query = client.execute(request).await.unwrap();
assert!(!collect_result(&query).await.unwrap().is_empty());
tokio::time::pause();
tokio::time::advance(Duration::from_secs(4)).await;
tokio::task::yield_now().await;
tokio::time::resume();
assert_eq!(
query.describe().await.unwrap().status,
QueryStatus::Finished
);
drop(query);
assert_eq!(cancellations.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn sql_deadline_applies_to_buffered_results_and_stops_its_timer_on_completion() {
for deferred in [false, true] {
let service = TestSqlService {
adaptive: true,
defer: deferred,
..TestSqlService::default()
};
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let mut request = ExecuteQueryRequest::new("SELECT 1");
request.options.timeout = Some(Duration::from_secs(3));
let query = client.execute(request).await.unwrap();
let mut rows = query.reader().await.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(
query.describe().await.unwrap().status,
QueryStatus::Finished
);
match client.queries.get(query.id()).unwrap() {
RegisteredQuery::Polled(query) => {
assert!(query.deadline_task.lock().unwrap().is_none())
}
RegisteredQuery::Streamed(query) => assert!(query.deadline_stopped()),
}
tokio::time::pause();
tokio::time::advance(Duration::from_secs(4)).await;
tokio::time::resume();
assert_overall_timeout(rows.try_next().await, "result");
assert!(rows.try_next().await.unwrap().is_none());
}
}
#[tokio::test]
async fn sql_deadline_is_forwarded_to_deferred_result_requests() {
let service = TestSqlService {
adaptive: true,
defer: true,
..TestSqlService::default()
};
let deadlines = service.result_deadlines.clone();
let headers = service.headers.clone();
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let mut request = ExecuteQueryRequest::new("SELECT 1");
request.options.timeout = Some(Duration::from_secs(3));
let query = client.execute(request).await.unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(!collect_result(&query).await.unwrap().is_empty());
let deadlines = deadlines.lock().unwrap();
let result_deadline = deadlines[0]
.as_deref()
.expect("the result request must carry an execution deadline");
assert_ne!(
Some(result_deadline),
headers.lock().unwrap()[0].grpc_timeout.as_deref(),
"the timeout budget must not restart for the result request"
);
}
#[tokio::test]
async fn sql_rejects_timeouts_that_cannot_be_encoded_by_grpc() {
let (client, _shutdown) =
start_sql_service(TestSqlService::default(), ClientConfig::default()).await;
let mut request = ExecuteQueryRequest::new("SELECT 1");
request.options.timeout = Some(Duration::from_secs(u64::MAX));
assert!(matches!(
client.execute(request).await,
Err(Error::InvalidInput { .. })
));
}
+5
View File
@@ -4237,6 +4237,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
options: Default::default(),
})
.await
.map_err(cleanup::map_error)?;
@@ -4266,6 +4267,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
options: Default::default(),
})
.await
.map_err(cleanup::map_error)?;
@@ -4298,6 +4300,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
options: Default::default(),
})
.await
.map_err(optimize::map_optimize_error)?;
@@ -4958,6 +4961,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: options.parameters,
options: Default::default(),
})
.await
.map_err(prewarm::map_error)?;
@@ -4997,6 +5001,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: options.parameters,
options: Default::default(),
})
.await
.map_err(prewarm::map_explain_error)?;
+21 -3
View File
@@ -3,7 +3,7 @@
//! Handles to SQL queries running on a LanceDB Enterprise database.
use std::{fmt, sync::Arc};
use std::{fmt, sync::Arc, time::Duration};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
@@ -11,6 +11,23 @@ use uuid::Uuid;
use crate::{Result, arrow::SendableRecordBatchStream};
/// Controls for one SQL execution.
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct QueryOptions {
/// Limit submission and result consumption together, starting at submission.
/// On expiry, the SDK stops reading and attempts to cancel Flight execution.
/// Durable server-side jobs still require explicit job cancellation.
pub timeout: Option<Duration>,
/// Limit each wait for a server response or the next result batch.
/// Defaults to the connection's read timeout.
pub read_timeout: Option<Duration>,
/// Attempt to cancel deferred Flight execution when its unread handle or
/// reader is dropped. Defaults to false so deferred queries can be detached.
/// Directly streamed queries always stop when their reader is dropped.
pub cancel_on_drop: bool,
}
/// The externally visible lifecycle state of a submitted SQL query.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryStatus {
@@ -73,8 +90,9 @@ pub(crate) trait QueryHandle: Send + Sync {
/// The handle can be inspected, opened as an Arrow reader, or cancelled.
/// The server may stream results on the initial call or defer execution and
/// return result tickets. Dropping an unread handle or its reader stops a
/// directly streamed query; deferred execution continues until explicitly
/// cancelled. This applies equally with and without parameters.
/// directly streamed query. Deferred execution continues until cancelled,
/// unless a timeout or `cancel_on_drop` was set on its execution builder.
/// This applies equally with and without parameters.
/// [`Self::id`] is scoped to the connection that submitted the query. When the
/// server runs the statement as a SQL job, [`Self::job_id`] exposes the durable
/// Job Registry identifier accepted by `open_job`.