mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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:
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -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)]
|
||||
|
||||
Reference in New Issue
Block a user