diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 32afe3d77..47a20aa57 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -306,7 +306,8 @@ call or return a polling continuation that the SDK follows automatically. This behavior is the same with and without parameters. Open the reader directly; a directly streamed query needs its reader to make progress. Dropping an unread handle or its reader stops direct streaming. Deferred execution continues until -explicitly cancelled. +explicitly cancelled by default; use `cancel_on_drop=True` to attempt cancellation +when its unread handle or reader is dropped. For example: @@ -360,6 +361,26 @@ reader = db.execute_query( # await query.cancel() ``` +Set `timeout` to bound submission and result consumption together, including +any time before opening a reader. Set `read_timeout` to limit each server read. +Both accept `datetime.timedelta` and apply to one execution. An expired timeout +or failed result read stops reading and attempts to cancel Flight execution. +Cancellation on drop requires the submitting runtime to remain alive. Durable +server-side jobs require explicit `db.cancel_job(query.job_id)`. + +```python +from datetime import timedelta + +query = db.execute_query_async( + "SELECT * FROM events", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, +) +# To stop this execution explicitly: +query.cancel() +``` + ## Namespaces (Synchronous) A namespace-backed connection resolves tables through a diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 89f465e65..42615191f 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -247,6 +247,53 @@ cancellation. Background operations such as index builds return a [job](/basics/jobs) handle instead. Use the API for the returned handle to check status and retrieve results. +### Timeouts and cancellation {#query-timeouts} + +Rust and Python SQL executions support per-query limits. Python's synchronous +and asynchronous connections accept the same keyword arguments: + +```python +from datetime import timedelta + +query = db.execute_query_async( + "SELECT frame_id, caption FROM frames", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, +) +# Cancel explicitly if these results are no longer needed. +query.cancel() +``` + +`timeout` starts at submission and covers result consumption, including time +before opening a reader. `read_timeout` overrides the connection's limit for each +server read. Expiry stops reads and attempts to cancel Flight execution. The +execution deadline is also sent to the server on result-streaming RPCs. + +By default, deferred queries can be detached. `cancel_on_drop=True` attempts +cancellation when an unread handle or its reader is dropped; it requires the +submitting runtime to remain alive. Directly streamed queries always stop on +drop. With an asynchronous Python connection, await submission and +`query.cancel()`. + +Rust exposes the same controls on the submission builder: + +```rust +use std::time::Duration; + +let query = db.execute_query_async("SELECT frame_id, caption FROM frames") + .timeout(Duration::from_secs(30)) + .read_timeout(Duration::from_secs(5)) + .cancel_on_drop(true) + .execute() + .await?; +query.cancel().await?; +``` + +These options cancel Flight execution. A durable server-side job can outlive its +Flight waiter; cancel it explicitly with `db.cancel_job(query.job_id)` in Python, +or `Connection::cancel_job` in Rust. + ## Query plans {#query-plans} Use query plans to understand how LanceDB reads data, applies filters and uses diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 6632b2acf..01e7a3369 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -324,6 +324,9 @@ class Connection(object): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[pa.RecordBatch] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> SqlQuery: ... async def describe_query(self, query_id: UUID) -> QueryDescription: ... async def create_table( diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 6de3e050c..4d5840527 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1717,6 +1717,9 @@ class DBConnection(EnforceOverrides): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> pa.RecordBatchReader: """Execute SQL and return a blocking Arrow reader. @@ -1731,6 +1734,9 @@ class DBConnection(EnforceOverrides): query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ).reader() def execute_query_async( @@ -1739,6 +1745,9 @@ class DBConnection(EnforceOverrides): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> SqlQuery: """Start executing SQL and return its query handle. @@ -1764,13 +1773,24 @@ class DBConnection(EnforceOverrides): With or without parameters, the server chooses whether to stream rows on the initial call or return a polling continuation. The reader follows either path transparently. Dropping an unread handle or its reader - stops a directly streamed query; deferred execution requires explicit - cancellation. Open ``reader()`` directly: a streamed query needs its - reader to make progress and reports ``running`` until the stream ends. + stops a directly streamed query. Set ``cancel_on_drop=True`` to also + attempt cancellation of deferred Flight execution when its unread handle + or reader is dropped. By default, deferred queries can be detached. + Open ``reader()`` directly: a streamed query needs its reader to make + progress and reports ``running`` until the stream ends. Once a server-side SQL job exists, ``describe().job_id`` exposes its durable Job Registry id while the query is still running. This is separate from the connection-scoped query ``id``. + ``timeout`` limits submission and result consumption together, starting + when the query is submitted. It also applies before a reader is opened. + ``read_timeout`` overrides the connection's limit for each server read. + Both accept ``datetime.timedelta``. On expiry or a failed result read, + the SDK stops reading and attempts to cancel Flight execution. + Cancellation on drop is best effort and requires the connection's runtime + to remain alive. Durable server-side jobs require explicit + ``cancel_job(query.job_id)`` regardless of these options. + LanceDB Embedded connections do not support SQL. """ raise NotImplementedError( @@ -4630,6 +4650,9 @@ class AsyncConnection(object): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> AsyncRecordBatchReader: """Execute SQL and return an asynchronous Arrow reader. @@ -4644,6 +4667,9 @@ class AsyncConnection(object): query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) return await submitted.reader() @@ -4653,6 +4679,9 @@ class AsyncConnection(object): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> AsyncSqlQuery: """Start executing SQL and return its query handle. @@ -4660,6 +4689,11 @@ class AsyncConnection(object): references. The namespace defaults to ``["public"]``. ``parameters`` binds values to ``$1`` / ``$name`` placeholders; see [DBConnection.execute_query_async][lancedb.db.DBConnection.execute_query_async]. + ``timeout`` covers submission through result consumption, including + time before opening a reader. ``read_timeout`` limits each server read. + ``cancel_on_drop=True`` also attempts to cancel deferred Flight execution + when its unread handle or reader is dropped. See the synchronous method + above for cancellation and durable-job behavior. LanceDB Embedded connections raise ``NotImplementedError``. """ return AsyncSqlQuery( @@ -4667,6 +4701,9 @@ class AsyncConnection(object): query, default_namespace_path=default_namespace_path, parameters=to_parameter_batch(parameters), + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) ) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 4c8ec1a62..ff75c22f1 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -1732,12 +1732,18 @@ class AsyncLanceNamespaceDBConnection: *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> AsyncRecordBatchReader: """Execute SQL when supported by the underlying connection.""" return await self._inner.execute_query( query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) async def execute_query_async( @@ -1746,6 +1752,9 @@ class AsyncLanceNamespaceDBConnection: *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> AsyncSqlQuery: """Start executing SQL when supported by the underlying connection. @@ -1755,6 +1764,9 @@ class AsyncLanceNamespaceDBConnection: query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 4061db3e1..1e550b003 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1421,6 +1421,9 @@ class RemoteDBConnection(DBConnection): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> SqlQuery: """Start executing SQL through this LanceDB Enterprise connection. @@ -1436,6 +1439,9 @@ class RemoteDBConnection(DBConnection): query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) ) ) diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index a479fa5d1..fc6f94ad0 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import threading +from datetime import timedelta from uuid import UUID import numpy as np @@ -13,6 +14,7 @@ from lancedb import _lancedb from lancedb.arrow import AsyncRecordBatchReader from lancedb.db import AsyncConnection from lancedb.remote.db import RemoteDBConnection +from lancedb.namespace import AsyncLanceNamespaceDBConnection from lancedb.sql import AsyncQuery, Query, to_parameter_batch NIL_QUERY_ID = UUID(int=0) @@ -22,24 +24,46 @@ class FakeNativeQuery: id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef") job_id = None + def __init__(self): + self.cancelled = False + async def reader(self): return pa.table({"value": [1, 2]}) + async def cancel(self): + self.cancelled = True + class FakeNativeConnection: def __init__(self): self.parameters = [] + self.options = [] async def execute_query_async( - self, query, *, default_namespace_path=None, parameters=None + self, + query, + *, + default_namespace_path=None, + parameters=None, + timeout=None, + read_timeout=None, + cancel_on_drop=False, ): self.parameters.append(parameters) + self.options.append((timeout, read_timeout, cancel_on_drop)) return FakeNativeQuery() class FakeAsyncConnection: async def execute_query_async( - self, query, *, default_namespace_path=None, parameters=None + self, + query, + *, + default_namespace_path=None, + parameters=None, + timeout=None, + read_timeout=None, + cancel_on_drop=False, ): return AsyncQuery(FakeNativeQuery()) @@ -401,3 +425,61 @@ def test_sql_input_error_metadata_crosses_native_boundary(job_id): assert error.grpc_code == 3 assert str(error).startswith("No column 'missing' in table events") assert not str(error).startswith("SQL error") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"]) +async def test_async_sql_execution_controls_are_forwarded(method): + native = FakeNativeConnection() + connection = AsyncConnection(native) + await getattr(connection, method)( + "SELECT 1", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, + ) + assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)] + + +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"]) +def test_sync_sql_execution_controls_are_forwarded(method): + native = FakeNativeConnection() + connection = RemoteDBConnection.__new__(RemoteDBConnection) + connection._conn = AsyncConnection(native) + getattr(connection, method)( + "SELECT 1", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, + ) + assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)] + + +@pytest.mark.asyncio +async def test_async_query_cancellation_reaches_the_native_handle(): + native = FakeNativeQuery() + await AsyncQuery(native).cancel() + assert native.cancelled + + +def test_sync_query_cancellation_reaches_the_native_handle(): + native = FakeNativeQuery() + Query(AsyncQuery(native)).cancel() + assert native.cancelled + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"]) +async def test_namespace_sql_execution_controls_are_forwarded(method): + native = FakeNativeConnection() + connection = AsyncLanceNamespaceDBConnection.__new__( + AsyncLanceNamespaceDBConnection + ) + connection._inner = AsyncConnection(native) + await getattr(connection, method)( + "SELECT 1", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, + ) + assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)] diff --git a/python/src/connection.rs b/python/src/connection.rs index 40e3c7b42..3d1ad6d30 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -375,19 +375,29 @@ impl Connection { self.get_inner().map(|inner| inner.uri().to_string()) } - #[pyo3(signature = (query, *, default_namespace_path=None, parameters=None))] + #[pyo3(signature = (query, *, default_namespace_path=None, parameters=None, timeout=None, read_timeout=None, cancel_on_drop=false))] pub fn execute_query_async<'a>( self_: PyRef<'a, Self>, query: String, default_namespace_path: Option>, parameters: Option>, + timeout: Option, + read_timeout: Option, + cancel_on_drop: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let default_namespace_path = parse_default_namespace_path(default_namespace_path)?; future_into_py(self_.py(), async move { let mut operation = inner .execute_query_async(query) - .default_namespace_path(default_namespace_path); + .default_namespace_path(default_namespace_path) + .cancel_on_drop(cancel_on_drop); + if let Some(timeout) = timeout { + operation = operation.timeout(timeout); + } + if let Some(timeout) = read_timeout { + operation = operation.read_timeout(timeout); + } if let Some(PyArrowType(parameters)) = parameters { operation = operation.parameters(parameters); } diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index d413b2b78..ac742eec7 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -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 diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index b89c9f95e..b021bf0ee 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -212,6 +212,8 @@ pub struct ExecuteQueryRequest { /// also binds `$`. See /// [`ExecuteQueryAsyncBuilder::parameters`](crate::connection::ExecuteQueryAsyncBuilder::parameters). pub parameters: Option, + /// 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(), } } } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 2e91fc15d..f17bcc2b0 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1008,6 +1008,7 @@ impl Database for RemoteDatabase { query: sql, default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) @@ -1024,6 +1025,7 @@ impl Database for RemoteDatabase { 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::>().await?) @@ -1046,6 +1048,7 @@ impl Database for RemoteDatabase { query: format!("DROP STORAGE INTEGRATION {name}"), default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; result.reader().await?.try_collect::>().await?; diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index f5e053f9f..b2ca5651f 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -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, @@ -77,6 +80,8 @@ struct SqlClientInner { sql_host_override: Option, client_config: ClientConfig, client: Arc>, + deadline: Option, + 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 { - 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> { + match self.deadline { + Some(deadline) => Ok(Some( + deadline.saturating_duration_since(tokio::time::Instant::now()), + )), + None => self.overall_timeout(), + } + } + + fn set_execution_timeout(&self, request: &mut Request) { + if let Some(deadline) = self.deadline { + request.set_timeout(deadline.saturating_duration_since(tokio::time::Instant::now())); + } + } + fn overall_timeout(&self) -> Result> { 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, lifecycle: StdMutex, cancel_request_uncertain: Arc, + failure: StdMutex>, + cleanup_started: AtomicBool, + runtime: tokio::runtime::Handle, + deadline_task: StdMutex>, } #[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) { + 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, 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) { + 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 { 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); + +impl Drop for CancelQueryOnDrop { + fn drop(&mut self) { + self.0.cancel_in_background(); + } +} + struct RemoteQueryHandle { query: Arc, 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 { - 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( + receiver: mpsc::Receiver>, + schema: SchemaRef, + deadline: Option, + 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, diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index f0ebf1894..f2a12a024 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -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")?; diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index c8e1aa5c3..eb29e62af 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -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?; diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index 2ffb08936..482fa46de 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -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?; diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index 93c2a6c6e..14c08e94b 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -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(()), ) diff --git a/rust/lancedb/src/remote/sql/stream.rs b/rust/lancedb/src/remote/sql/stream.rs index 16155bf7c..b5315353f 100644 --- a/rust/lancedb/src/remote/sql/stream.rs +++ b/rust/lancedb/src/remote/sql/stream.rs @@ -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, last_accessed: StdMutex, job_id: StdMutex>, + deadline_task: StdMutex>, } 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) { + 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 { @@ -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 { 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 { - 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, diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index b058269a0..ca09c4b5d 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -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), ) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index eb70e87ac..7f1767ff1 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -116,6 +116,7 @@ struct CapturedHeaders { api_key: String, database_prefix: String, materialized_view_job_handle: Option, + grpc_timeout: Option, } /// Every exchange's statement and the parameter row it arrived with. @@ -138,6 +139,7 @@ struct TestSqlService { first_continuation_count: Arc, transient_poll_failures: Arc, headers: Arc>>, + result_deadlines: Arc>>>, gate_refresh_release: Arc, exchanges: ReceivedExchanges, result_overrides: Arc>>, @@ -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 { .. }) + )); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 8dbf75aea..6b46c45fc 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4237,6 +4237,7 @@ impl BaseTable for RemoteTable { query: statement, default_namespace_path: self.namespace.clone(), parameters: None, + options: Default::default(), }) .await .map_err(cleanup::map_error)?; @@ -4266,6 +4267,7 @@ impl BaseTable for RemoteTable { query: statement, default_namespace_path: self.namespace.clone(), parameters: None, + options: Default::default(), }) .await .map_err(cleanup::map_error)?; @@ -4298,6 +4300,7 @@ impl BaseTable for RemoteTable { 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 BaseTable for RemoteTable { 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 BaseTable for RemoteTable { query: statement, default_namespace_path: self.namespace.clone(), parameters: options.parameters, + options: Default::default(), }) .await .map_err(prewarm::map_explain_error)?; diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index bda5df085..88195aff2 100644 --- a/rust/lancedb/src/sql.rs +++ b/rust/lancedb/src/sql.rs @@ -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, + /// Limit each wait for a server response or the next result batch. + /// Defaults to the connection's read timeout. + pub read_timeout: Option, + /// 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`.