mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(sdk)!: submit data prewarm through SQL with durable jobs
This commit is contained in:
@@ -610,6 +610,13 @@ class Table:
|
||||
async def restore(self, version: Optional[Union[int, str]] = None): ...
|
||||
async def prewarm_index(self, index_name: str) -> None: ...
|
||||
async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ...
|
||||
async def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> Job: ...
|
||||
async def list_indices(self) -> list[IndexConfig]: ...
|
||||
async def tokenize(
|
||||
self,
|
||||
|
||||
@@ -1356,7 +1356,8 @@ class RemoteTable(Table):
|
||||
Currently only supported in LanceDB Enterprise.
|
||||
|
||||
This call initiates prewarming and returns once the request is accepted.
|
||||
It is idempotent and safe to call from multiple clients concurrently.
|
||||
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
|
||||
durable warming job, use ``prewarm_data_async()``.
|
||||
|
||||
This operation has a large upfront cost but can speed up future queries
|
||||
that need to fetch the given columns. Large columns such as embeddings
|
||||
@@ -1370,6 +1371,21 @@ class RemoteTable(Table):
|
||||
"""
|
||||
return LOOP.run(self._table.prewarm_data(columns))
|
||||
|
||||
def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> Job[None]:
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._table.prewarm_data_async(
|
||||
columns, filter=filter, concurrency=concurrency
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def wait_for_index(
|
||||
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
|
||||
):
|
||||
|
||||
@@ -1960,6 +1960,42 @@ class Table(ABC):
|
||||
"""
|
||||
raise NotImplementedError("create_index is not supported for this table type")
|
||||
|
||||
def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> Job[None]:
|
||||
"""Submit a remote data-cache prewarm and return its durable job.
|
||||
|
||||
Requires a compatible SQL PREWARM server and Flight SQL connectivity.
|
||||
The table handle supplies the branch and namespace. ``columns`` uses
|
||||
Lance field paths; an omitted/empty list warms all columns. ``filter``
|
||||
is one SQL predicate for conservative metadata pruning, not a row scan.
|
||||
``concurrency`` is a positive per-executor integer. Historical-version
|
||||
handles are unsupported; call ``checkout_latest()`` first.
|
||||
|
||||
Submission requires table Select and database/namespace Usage under
|
||||
Standard authorization. Status/wait use the generic HTTP job API;
|
||||
events and cancellation have their own privileges. Unsupported servers
|
||||
are not retried through REST or with settings removed.
|
||||
|
||||
Returns once accepted. ``job.wait()`` waits for warming to finish and
|
||||
returns None. Save ``job.id`` to resume with ``db.open_job(id)``. A wait
|
||||
timeout does not cancel the operation. After ``job.refresh()``,
|
||||
``job.spec["table_version"]`` identifies the pinned source version.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> job = table.prewarm_data_async( # doctest: +SKIP
|
||||
... ["video"], filter="quality > 0.7", concurrency=4)
|
||||
>>> job.wait() # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"data prewarm jobs are only supported on remote tables"
|
||||
)
|
||||
|
||||
def create_index_async(
|
||||
self,
|
||||
column: str,
|
||||
@@ -4614,7 +4650,8 @@ class LanceTable(Table):
|
||||
Currently only supported in LanceDB Enterprise.
|
||||
|
||||
This call initiates prewarming and returns once the request is accepted.
|
||||
It is idempotent and safe to call from multiple clients concurrently.
|
||||
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
|
||||
durable warming job, use ``prewarm_data_async()``.
|
||||
|
||||
This operation has a large upfront cost but can speed up future queries
|
||||
that need to fetch the given columns. Large columns such as embeddings
|
||||
@@ -4628,6 +4665,21 @@ class LanceTable(Table):
|
||||
"""
|
||||
return LOOP.run(self._table.prewarm_data(columns))
|
||||
|
||||
def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> Job[None]:
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._table.prewarm_data_async(
|
||||
columns, filter=filter, concurrency=concurrency
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def wait_for_index(
|
||||
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
|
||||
) -> None:
|
||||
@@ -7003,7 +7055,8 @@ class AsyncTable:
|
||||
Currently only supported in LanceDB Enterprise.
|
||||
|
||||
This call initiates prewarming and returns once the request is accepted.
|
||||
It is idempotent and safe to call from multiple clients concurrently.
|
||||
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
|
||||
durable warming job, use ``prewarm_data_async()``.
|
||||
|
||||
This operation has a large upfront cost but can speed up future queries
|
||||
that need to fetch the given columns. Large columns such as embeddings
|
||||
@@ -7017,6 +7070,31 @@ class AsyncTable:
|
||||
"""
|
||||
await self._inner.prewarm_data(columns)
|
||||
|
||||
async def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> AsyncJob[None]:
|
||||
"""Submit data prewarm and return a durable handle after acceptance.
|
||||
|
||||
See [Table.prewarm_data_async][lancedb.table.Table.prewarm_data_async]
|
||||
for options, permissions, and compatibility. Awaiting this method does
|
||||
not wait for warming; use ``await job.wait()`` for completion.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> job = await table.prewarm_data_async( # doctest: +SKIP
|
||||
... ["video"], filter="quality > 0.7", concurrency=4)
|
||||
>>> await job.wait() # doctest: +SKIP
|
||||
"""
|
||||
return AsyncJob(
|
||||
await self._inner.prewarm_data_async(
|
||||
columns, filter=filter, concurrency=concurrency
|
||||
)
|
||||
)
|
||||
|
||||
async def wait_for_index(
|
||||
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
|
||||
) -> None:
|
||||
|
||||
@@ -7076,10 +7076,10 @@ def _create_table_handler(request):
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _mock_remote_sql_connection(flight_server):
|
||||
def _mock_remote_sql_connection(flight_server, handler=_create_table_handler):
|
||||
"""Connection arguments for mock REST and Flight SQL servers."""
|
||||
with http.server.ThreadingHTTPServer(
|
||||
("127.0.0.1", 0), make_mock_http_handler(_create_table_handler)
|
||||
("127.0.0.1", 0), make_mock_http_handler(handler)
|
||||
) as rest_server:
|
||||
rest_port = rest_server.server_address[1]
|
||||
handle = start_server_thread(rest_server)
|
||||
@@ -7420,3 +7420,146 @@ async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnati
|
||||
if use_async:
|
||||
await result
|
||||
assert not any(path == "fetch_blobs" for path, _ in requests)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("legacy", [False, True])
|
||||
async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, legacy):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
polls = []
|
||||
|
||||
class PrewarmServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table(
|
||||
{
|
||||
"job_id": ["warming-job"],
|
||||
"table_version": pa.array([42], pa.uint64()),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
def handler(request):
|
||||
if request.path == "/v1/jobs/describe":
|
||||
body = json.loads(
|
||||
request.rfile.read(int(request.headers["Content-Length"]))
|
||||
)
|
||||
assert body == {"job_id": "warming-job"}
|
||||
polls.append(body)
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(
|
||||
json.dumps(
|
||||
{
|
||||
"job_id": "warming-job",
|
||||
"job_type": "prewarm_page_cache",
|
||||
"job_state": "DONE",
|
||||
"creation_ms": 1,
|
||||
"spec": {"table_version": 42},
|
||||
}
|
||||
).encode()
|
||||
)
|
||||
else:
|
||||
# No operation-specific REST prewarm endpoint is accepted.
|
||||
_create_table_handler(request)
|
||||
|
||||
server = PrewarmServer()
|
||||
with _mock_remote_sql_connection(server, handler) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
if legacy:
|
||||
assert await table.prewarm_data(["payload"]) is None
|
||||
else:
|
||||
job = await table.prewarm_data_async(
|
||||
["attrs.score"], filter="id >= 8", concurrency=4
|
||||
)
|
||||
assert job.id == "warming-job"
|
||||
assert not polls
|
||||
assert await job.wait() is None
|
||||
await job.refresh()
|
||||
assert job.spec["table_version"] == 42
|
||||
reopened = await db.open_job(job.id)
|
||||
assert await reopened.wait() is None
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
if legacy:
|
||||
assert table.prewarm_data(["payload"]) is None
|
||||
else:
|
||||
job = table.prewarm_data_async(
|
||||
["attrs.score"], filter="id >= 8", concurrency=4
|
||||
)
|
||||
assert job.id == "warming-job"
|
||||
assert not polls
|
||||
assert job.wait() is None
|
||||
job.refresh()
|
||||
assert job.spec["table_version"] == 42
|
||||
assert db.open_job(job.id).wait() is None
|
||||
assert len(server.tickets) == 1
|
||||
assert b"PREWARM" in server.tickets[0]
|
||||
if legacy:
|
||||
assert not polls
|
||||
assert b'"payload"' in server.tickets[0]
|
||||
else:
|
||||
assert b'"attrs"."score"' in server.tickets[0]
|
||||
assert b"concurrency = 4" in server.tickets[0]
|
||||
assert b"id >= 8" in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"filter": ""},
|
||||
{"filter": "id > 0; DROP TABLE test"},
|
||||
{"filter": "id > 0 LIMIT 1"},
|
||||
{"concurrency": 0},
|
||||
{"concurrency": -1},
|
||||
{"concurrency": 2**32},
|
||||
{"concurrency": True},
|
||||
{"concurrency": 1.5},
|
||||
],
|
||||
)
|
||||
def test_remote_data_prewarm_validates_before_submission(options):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class UnusedServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
raise AssertionError("invalid options must not submit SQL")
|
||||
|
||||
server = UnusedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(ValueError):
|
||||
table.prewarm_data_async(**options)
|
||||
assert not server.tickets
|
||||
|
||||
|
||||
def test_remote_data_prewarm_malformed_receipt_is_not_retried():
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class MalformedServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(pa.table({"job_id": ["warming-job"]}))
|
||||
|
||||
server = MalformedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(Exception, match="inspect jobs before retrying"):
|
||||
table.prewarm_data_async()
|
||||
assert len(server.tickets) == 1
|
||||
|
||||
@@ -6292,3 +6292,21 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
|
||||
metadata = (await table.schema()).field("doubled").metadata
|
||||
assert metadata[b"computed_column.auto_refresh_enabled"] == b"true"
|
||||
assert b"computed_column.auto_refresh_interval_seconds" not in metadata
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous):
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("prewarm", [{"id": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
await table.prewarm_data_async(filter="id > 0", concurrency=2)
|
||||
else:
|
||||
table = lancedb.connect(tmp_path).create_table("prewarm", [{"id": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
table.prewarm_data_async(filter="id > 0", concurrency=2)
|
||||
|
||||
@@ -1741,6 +1741,24 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (columns=None, *, filter=None, concurrency=None))]
|
||||
pub fn prewarm_data_async<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
columns: Option<Vec<String>>,
|
||||
filter: Option<String>,
|
||||
concurrency: Option<&Bound<'py, PyAny>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let mut options =
|
||||
lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default());
|
||||
options.filter = filter;
|
||||
options.concurrency = positive_u32_integer(concurrency, "concurrency")?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let job = inner.prewarm_data_async(options).await.infer_error()?;
|
||||
Ok(crate::job::Job::new(job))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn list_indices(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
|
||||
Reference in New Issue
Block a user