diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index 3ce773d73..b93580bfa 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -72,6 +72,48 @@ and rollouts instead of dipping right after each one. [Contact us](https://www.lancedb.com/contact) to learn more about how prewarming is configured for your deployment. +## On-demand data prewarm + +On compatible Enterprise deployments, the SDK submits data prewarm through +SQL. Flight SQL connectivity is required; the existing generic HTTP job API is +used to inspect or wait for the durable warming job. Under Standard +authorization, submission requires table Select plus Usage on the database +and namespace hierarchy. Job events require System Usage and cancellation +requires System Operate. + +```python +from datetime import timedelta + +# The table handle determines the database, namespace, and branch. +job = table.prewarm_data_async( + ["video"], filter="quality > 0.7", concurrency=4 +) +print(job.id) +job.wait(timeout=timedelta(minutes=10)) + +# Reattach in a later process using the same database connection settings. +db.open_job(job.id).wait() +``` + +The method returns when the job is accepted. Waiting finishes when warming +reaches a terminal state; a timeout does not cancel the job. Use +`job.refresh()` and `job.spec["table_version"]` to inspect the captured source +version. In Python's asynchronous API, await submission and `job.wait()`. +Node exposes `table.prewarmDataAsync({ columns, filter, concurrency })` with +the same lifecycle. + +The filter is a single SQL predicate used for conservative metadata pruning. +Unknown or unavailable metadata keeps data eligible for warming. Omitted +columns warm all fields; concurrency must be a positive integer. Historical +version checkouts are unsupported: use the latest version of the selected +branch. The server never needs to scan rows merely to evaluate the predicate. + +`prewarm_data(columns)` / `prewarmData(columns)` still return after acceptance +without a job handle, but now also require SQL PREWARM support and Flight SQL +connectivity. Unsupported servers fail without a REST fallback or silently +dropping options. Repeated submissions may create distinct jobs; warming +already-cached data is safe. Index prewarm keeps its existing behavior. + ## What to read next {#next} diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 59d6929b4..5e9df4665 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4711,6 +4711,36 @@ describe.each(arrowVersions)( ); }); + test("prewarmDataAsync validates options and rejects local tables", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_job", [{ id: 1 }]); + await expect(table.prewarmDataAsync()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.prewarmDataAsync({ + columns: ["id"], + filter: "id > 0", + concurrency: 2, + }), + ).rejects.toThrow("only supported on remote tables"); + await expect( + table.prewarmDataAsync({ unsupported: 1 } as never), + ).rejects.toThrow("Unsupported data prewarm option: unsupported"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 4294967296, + ]) { + await expect(table.prewarmDataAsync({ concurrency })).rejects.toThrow( + "concurrency must be an integer", + ); + } + }); + test("full text index on list", async () => { const db = await connect(tmpDir.name); const data = [ diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 08a254bdb..cde32e536 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -172,6 +172,7 @@ export { UpdateOptions, OptimizeOptions, CompactionOptions, + PrewarmDataOptions, Version, WriteProgress, FtsToken, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 136eb1d6c..9eed3a280 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -165,6 +165,16 @@ export interface UpdateOptions { where: string; } +/** Settings for submitting a durable remote data-cache prewarm job. */ +export interface PrewarmDataOptions { + /** Lance field paths to warm; omitted or empty means every column. */ + columns?: string[]; + /** A single SQL predicate for conservative metadata pruning. */ + filter?: string; + /** Positive per-executor concurrency, at most 4294967295. */ + concurrency?: number; +} + /** Per-invocation compaction settings. Values must be safe integers. */ export interface CompactionOptions { /** Positive target rows per output fragment; also affects candidate selection. */ @@ -567,8 +577,8 @@ export abstract class Table { * This will load the column data into the page cache so that future queries that * read those columns avoid the initial cold-start latency. This call initiates * prewarming and returns once the request is accepted; the warming itself may - * continue in the background. Calling it on already-prewarmed columns is a - * no-op on the server. + * continue in the background. Submission uses SQL PREWARM and needs Flight + * SQL connectivity. Use {@link prewarmDataAsync} to retain the job handle. * * Prewarming is generally useful for columns used in filters or projections. * Large columns (e.g. high-dimensional vectors or binary data) may not be @@ -578,6 +588,28 @@ export abstract class Table { */ abstract prewarmData(columns?: string[]): Promise; + /** + * Submit data prewarm through SQL and return its durable warming-job handle. + * + * The table handle supplies the branch and namespace. Requires a compatible + * SQL PREWARM server and Flight SQL connectivity. Standard authorization + * requires table Select and database/namespace Usage. Status/wait use generic + * HTTP job APIs; events and cancellation retain their own privileges. + * No REST fallback or option-dropping retry is performed. Historical-version + * handles are unsupported; call `checkoutLatest()` first. + * + * Submission returns after acceptance. Use `job.wait()` for completion, or + * save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel + * the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. + * + * @example + * const job = await table.prewarmDataAsync({ + * columns: ["video"], filter: "quality > 0.7", concurrency: 4, + * }); + * await job.wait(); + */ + abstract prewarmDataAsync(options?: PrewarmDataOptions): Promise; + /** * Waits for asynchronous indexing to complete on the table. * @@ -1503,6 +1535,15 @@ export class LocalTable extends Table { await this.inner.prewarmData(columns); } + async prewarmDataAsync(options?: PrewarmDataOptions): Promise { + for (const key of Object.keys(options ?? {})) { + if (!["columns", "filter", "concurrency"].includes(key)) { + throw new Error(`Unsupported data prewarm option: ${key}`); + } + } + return new Job(await this.inner.prewarmDataAsync(options)); + } + async waitForIndex( indexNames: string[], timeoutSeconds: number, diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index f6abeb553..de51312c1 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -25,6 +25,32 @@ use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; use crate::util::schema_to_buffer; +/// Settings for durable data-cache prewarm submission. +#[napi(object)] +pub struct PrewarmDataOptions { + pub columns: Option>, + pub filter: Option, + pub concurrency: Option, +} + +impl PrewarmDataOptions { + fn into_options(self) -> napi::Result { + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(self.columns.unwrap_or_default()); + options.filter = self.filter; + if let Some(value) = self.concurrency { + if !value.is_finite() || value.fract() != 0.0 || value < 1.0 || value > u32::MAX as f64 + { + return Err(napi::Error::from_reason( + "concurrency must be an integer between 1 and 4294967295", + )); + } + options.concurrency = Some(value as u32); + } + Ok(options) + } +} + /// Per-invocation file-compaction settings. All numbers must be safe integers. #[napi(object)] pub struct CompactionOptions { @@ -296,6 +322,23 @@ impl Table { .default_error() } + #[napi(catch_unwind)] + pub async fn prewarm_data_async( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(PrewarmDataOptions::into_options) + .transpose()? + .unwrap_or_default(); + let job = self + .inner_ref()? + .prewarm_data_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new(job)) + } + #[napi(catch_unwind)] pub async fn wait_for_index(&self, index_names: Vec, timeout_s: i64) -> Result<()> { let timeout = std::time::Duration::from_secs(timeout_s.try_into().unwrap()); diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5897ddd0c..fd964e3d4 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -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, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 6730e6694..38a735087 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -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) ): diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 5f0af7a66..0858a60c4 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -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: diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ca2516fda..836850a5c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -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 diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e3b69ced1..09425fdb6 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -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) diff --git a/python/src/table.rs b/python/src/table.rs index 31cf8d25c..2fc421986 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -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>, + filter: Option, + concurrency: Option<&Bound<'py, PyAny>>, + ) -> PyResult> { + 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> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 92523ec34..d4c5ee118 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -410,14 +410,6 @@ impl RemoteDatabase { read_consistency_interval: Option, parsed: super::client::ParsedDbUrl, ) -> Result { - let sql_client = SqlClient::new( - parsed.db_name.clone(), - parsed.db_prefix.clone(), - api_key.to_string(), - host_overrides.rest.clone(), - host_overrides.sql, - client_config.clone(), - ); let header_map = RestfulLanceDbClient::::default_headers( api_key, region, @@ -428,6 +420,27 @@ impl RemoteDatabase { &client_config, )?; + // Preserve the resolved source-account hint when table operations use SQL. + let mut sql_config = client_config.clone(); + if let Some(account) = header_map.get("x-azure-storage-account-name") { + sql_config.extra_headers.insert( + "x-azure-storage-account-name".into(), + account + .to_str() + .map_err(|error| Error::InvalidInput { + message: error.to_string(), + })? + .into(), + ); + } + let sql_client = SqlClient::new( + parsed.db_name.clone(), + parsed.db_prefix.clone(), + api_key.to_string(), + host_overrides.rest.clone(), + host_overrides.sql, + sql_config, + ); let namespace_headers: HashMap = header_map .iter() .filter_map(|(k, v)| { diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 9c34f8f90..f5e053f9f 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -12,7 +12,6 @@ use arrow_array::RecordBatch; use arrow_flight::decode::FlightRecordBatchStream; use arrow_flight::error::FlightError; use arrow_flight::flight_service_client::FlightServiceClient; -#[cfg(test)] use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt}; use arrow_flight::{ Action, CancelFlightInfoRequest, CancelFlightInfoResult, CancelStatus, FlightClient, @@ -44,6 +43,8 @@ pub(super) use secret::SecretWriteOperation; mod stream; mod view; +const PREWARM_AZURE_HINT_CAPABILITY: &str = "lancedb.prewarm.azure_storage_account_name"; + use stream::{StreamingQuery, StreamingQueryHandle, Submission}; const DEFAULT_SQL_PORT: u16 = 10025; @@ -217,6 +218,55 @@ impl SqlClient { } } + /// Unknown headers are otherwise silently ignored by older SQL servers. + /// Probe only when a source-account hint is present, before submitting work. + pub(super) async fn execute_prewarm(&self, request: ExecuteQueryRequest) -> Result { + with_overall_timeout( + self.inner.overall_timeout()?, + "prewarm submission", + async { + validate_namespace_path(&request.default_namespace_path)?; + let request_id = Uuid::new_v4().to_string(); + let headers = self + .inner + .headers(&request.default_namespace_path, &request_id) + .await?; + if headers.contains_key("x-azure-storage-account-name") { + let connection = self.inner.connection(&request_id).await?; + let mut client = client_with_headers(connection.client.clone(), &headers)?; + let command = CommandStatementQuery { + query: request.query.clone(), + transaction_id: None, + }; + let descriptor = FlightDescriptor::new_cmd(command.as_any().encode_to_vec()); + let read_timeout = resolve_timeout( + self.inner.client_config.timeout_config.read_timeout, + "LANCE_CLIENT_READ_TIMEOUT", Some(DEFAULT_READ_TIMEOUT), + )?.unwrap(); + let info = tokio::time::timeout(read_timeout, client.get_flight_info(descriptor)) + .await.map_err(|_| Error::Runtime { message: format!("SQL PREWARM capability check timed out (request_id={request_id})") })? + .map_err(|error| sql_flight_error(&request_id, &error))?; + let supported = info.try_decode_schema().ok().is_some_and(|schema| { + schema + .metadata() + .get(PREWARM_AZURE_HINT_CAPABILITY) + .map(String::as_str) + == Some("true") + }); + if !supported { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM server cannot acknowledge the Azure storage-account hint (request_id={request_id}); upgrade the server. No execution request was sent." + ), + }); + } + } + self.execute(request).await + }, + ) + .await + } + pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result { Ok(self .execute_with_materialized_view_job_handle(request, false) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d25c72830..0e057f3db 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -143,6 +143,8 @@ struct TestSqlService { result_overrides: Arc>>, materialized_view_job_handle_supported: bool, optimize_error: Option, + prewarm_error: Option, + prewarm_azure_supported: bool, /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, @@ -318,6 +320,8 @@ impl Default for TestSqlService { result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())), materialized_view_job_handle_supported: false, optimize_error: None, + prewarm_error: None, + prewarm_azure_supported: false, exchange_drops: Arc::new(AtomicUsize::new(0)), result, large_result, @@ -352,9 +356,30 @@ impl FlightService for TestSqlService { async fn get_flight_info( &self, - _request: Request, + request: Request, ) -> std::result::Result, Status> { - Err(Status::unimplemented("get_flight_info")) + self.capture_headers(request.metadata()); + assert!( + request + .metadata() + .get("x-azure-storage-account-name") + .is_some() + ); + let schema = if self.prewarm_azure_supported { + self.result + .schema() + .as_ref() + .clone() + .with_metadata(HashMap::from([( + "lancedb.prewarm.azure_storage_account_name".into(), + "true".into(), + )])) + } else { + self.result.schema().as_ref().clone() + }; + Ok(Response::new( + FlightInfo::new().try_with_schema(&schema).unwrap(), + )) } async fn poll_flight_info( @@ -493,6 +518,11 @@ impl FlightService for TestSqlService { { return Err(error.clone()); } + if command.query.starts_with("PREWARM") + && let Some(error) = &self.prewarm_error + { + return Err(error.clone()); + } if command.query == "SELECT rejected" { return Err(Status::invalid_argument("invalid statement")); } @@ -4216,3 +4246,309 @@ async fn remote_optimize_branch_options_are_not_dropped() { ); shutdown.send(()).unwrap(); } + +fn prewarm_result() -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "job_id", + Arc::new(StringArray::from(vec!["warming-job"])) as ArrayRef, + ), + ( + "table_version", + Arc::new(arrow_array::UInt64Array::from(vec![42])) as ArrayRef, + ), + ]) + .unwrap() +} + +#[tokio::test] +async fn remote_prewarm_data_returns_the_durable_job_without_polling() { + use crate::table::PrewarmDataOptions; + for branch in [None, Some("experiment"), Some("o'brien")] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| -> http::Response { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let value: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(value["job_id"], "warming-job"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"warming-job", "job_type":"prewarm_page_cache", "job_state":"DONE", + "creation_ms":1,"spec":{"table_version":42}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clip\"name".into(), + vec!["team".into(), "inner".into()], + "team$inner$clip\"name".into(), + Default::default(), + Some(sql), + ) + .with_branch(branch.map(str::to_string)); + let job = table + .prewarm_data_async( + PrewarmDataOptions::new() + .columns(["attrs.score", "`caption.text`", "attrs.score"]) + .filter("quality > 0.7") + .concurrency(4), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("warming-job")); + assert_eq!( + polls.load(Ordering::SeqCst), + 0, + "acceptance must not eagerly poll HTTP" + ); + let branch_sql = branch + .map(|b| format!("branch = '{}', ", b.replace('\'', "''"))) + .unwrap_or_default(); + assert_eq!( + *statements.lock().unwrap(), + [format!( + "PREWARM WITH ({branch_sql}concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7" + )] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team$inner" && h.database == "analytics") + ); + job.wait().await.unwrap(); + assert_eq!(polls.load(Ordering::SeqCst), 1); + job.refresh().await.unwrap(); + assert_eq!(job.spec().unwrap()["table_version"], 42); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_legacy_prewarm_data_submits_sql_and_returns_on_acceptance() { + for columns in [None, Some(vec![]), Some(vec!["payload".into()])] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!( + "legacy prewarm must neither submit nor poll REST: {}", + r.url() + ); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + table.prewarm_data(columns.clone()).await.unwrap(); + let projection = if columns.as_ref().is_some_and(|c| !c.is_empty()) { + "\"payload\"" + } else { + "*" + }; + assert_eq!( + *statements.lock().unwrap(), + [format!("PREWARM AS SELECT {projection} FROM \"clips\"")] + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_data_rejects_bad_receipts_without_resubmission() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not retry malformed receipt through REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(error.to_string().contains("inspect jobs before retrying")); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_prewarm_errors_preserve_diagnostics_and_never_fall_back() { + for (status, unsupported) in [ + ( + Status::invalid_argument("Unknown PREWARM option 'branch'"), + true, + ), + (Status::permission_denied("source Select denied"), false), + ( + Status::invalid_argument("ParserError: expected expression, found invalid_filter"), + false, + ), + ] { + let service = TestSqlService { + adaptive: true, + prewarm_error: Some(status), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not retry through REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let error = table.prewarm_data(None).await.unwrap_err(); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error}" + ); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_requires_azure_ack_before_execution() { + for supported in [false, true] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + prewarm_azure_supported: supported, + ..Default::default() + }; + let statements = service.statements.clone(); + let mut config = ClientConfig::default(); + config.extra_headers.insert( + "x-azure-storage-account-name".into(), + "sourceaccount".into(), + ); + let (sql, shutdown) = start_sql_service(service, config).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not use REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let result = table.prewarm_data(None).await; + assert_eq!(result.is_ok(), supported, "{result:?}"); + assert_eq!(statements.lock().unwrap().len(), usize::from(supported)); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_wait_surfaces_warming_job_failure_or_cancellation() { + for state in ["FAILED", "CANCELLED"] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(move |r| -> http::Response { + assert_eq!(r.url().path(), "/v1/jobs/describe"); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"warming-job","job_type":"prewarm_page_cache","job_state":state, + "creation_ms":1,"spec":{"table_version":42}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let job = table.prewarm_data_async(Default::default()).await.unwrap(); + assert_eq!(job.id(), Some("warming-job")); + let error = job.wait().await.unwrap_err(); + if state == "FAILED" { + assert!(matches!(error, Error::JobFailed { .. }), "{error}"); + } else { + assert!(matches!(error, Error::JobCancelled { .. }), "{error}"); + } + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_rejects_historical_checkout_without_submitting() { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + assert_eq!(r.url().path(), "/v1/table/clips/describe/"); + http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + table.checkout(7).await.unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("historical version 7")); + assert!(statements.lock().unwrap().is_empty()); + shutdown.send(()).unwrap(); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 9b64ab56d..895b89026 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5,6 +5,7 @@ pub mod blobs; pub mod insert; mod ipc_stream; mod optimize; +mod prewarm; #[cfg(test)] mod write_tests; @@ -4563,20 +4564,50 @@ impl BaseTable for RemoteTable { } async fn prewarm_data(&self, columns: Option>) -> Result<()> { - let mut request = self.client.post(&format!( - "/v1/table/{}/page_cache/prewarm/", - self.identifier - )); - let mut body = serde_json::json!({ - "columns": columns.unwrap_or_default(), - }); - self.apply_branch_body(&mut body); - request = request.json(&body); - let (request_id, response) = self.send(request, true).await?; - self.check_table_response(&request_id, response).await?; + self.prewarm_data_async( + crate::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()), + ) + .await?; Ok(()) } + async fn prewarm_data_async(&self, options: crate::table::PrewarmDataOptions) -> Result { + if let Some(version) = *self.version.read().await { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM does not support historical version {version}; use checkout_latest() to prewarm the current branch" + ), + }); + } + let statement = prewarm::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "data prewarm requires a Flight SQL endpoint and SQL PREWARM support" + .into(), + })?; + let query = client + .execute_prewarm(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(prewarm::map_error)?; + let mut reader = query.reader().await.map_err(prewarm::map_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader.try_next().await.map_err(prewarm::map_error)? { + batches.push(batch); + } + let (job_id, _table_version) = prewarm::receipt(&batches)?; + // Construct lazily: submission must not require an HTTP status round trip. + Ok(Job::new(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + async fn table_definition(&self) -> Result { let schema = self.schema().await?; TableDefinition::try_from_rich_schema(schema) @@ -12988,67 +13019,16 @@ mod tests { } #[tokio::test] - async fn test_prewarm_data() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/table/my_table/page_cache/prewarm/" + async fn test_prewarm_data_requires_sql_without_rest_fallback() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!( + "data prewarm must not submit through REST: {}", + request.url() ); - http::Response::builder().status(200).body("{}").unwrap() }); - table.prewarm_data(None).await.unwrap(); - } - - #[tokio::test] - async fn test_prewarm_data_with_columns() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/table/my_table/page_cache/prewarm/" - ); - let body = request.body().unwrap().as_bytes().unwrap(); - let body: serde_json::Value = serde_json::from_slice(body).unwrap(); - assert_eq!(body["columns"], serde_json::json!(["col_a", "col_b"])); - http::Response::builder().status(200).body("{}").unwrap() - }); - table - .prewarm_data(Some(vec!["col_a".into(), "col_b".into()])) - .await - .unwrap(); - } - - #[tokio::test] - async fn test_prewarm_data_sends_the_checked_out_branch() { - use lance::dataset::refs::Ref; - - let table = - Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { - match request.url().path() { - "/v1/table/my_table/branches/create/" => { - http::Response::builder().status(200).body("{}").unwrap() - } - "/v1/table/my_table/page_cache/prewarm/" => { - let body = request_body_json(&request); - assert_eq!(body["branch"], "dev"); - assert_eq!(body["columns"], json!(["payload"])); - http::Response::builder() - .status(202) - .body(r#"{"job_id":"prewarm-job"}"#) - .unwrap() - } - path => panic!("unexpected request path: {path}"), - } - }); - let branch = table - .create_branch("dev", Ref::Version(None, None)) - .await - .unwrap(); - branch - .prewarm_data(Some(vec!["payload".into()])) - .await - .unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("SQL")); } #[tokio::test] diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs new file mode 100644 index 000000000..8388b6350 --- /dev/null +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! SQL submission and receipt validation for data-cache prewarm jobs. + +use arrow_array::{Array, RecordBatch, StringArray, UInt64Array}; +use datafusion_sql::sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Token}; + +use super::{quote_sql_identifier, quote_sql_string}; +use crate::{Error, Result, table::PrewarmDataOptions}; + +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &PrewarmDataOptions, +) -> Result { + let invalid = |message: &str| Error::InvalidInput { + message: message.into(), + }; + if options.concurrency == Some(0) { + return Err(invalid("prewarm concurrency must be greater than 0")); + } + if let Some(filter) = &options.filter { + if filter.trim().is_empty() { + return Err(invalid("prewarm filter must not be empty")); + } + let dialect = GenericDialect {}; + let mut parser = Parser::new(&dialect) + .try_with_sql(filter) + .map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?; + parser + .parse_expr() + .map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?; + if parser.peek_token().token != Token::EOF { + return Err(invalid("prewarm filter must be a single SQL expression")); + } + } + let mut settings = Vec::new(); + if let Some(branch) = branch { + if branch.trim().is_empty() { + return Err(invalid("prewarm branch must not be empty")); + } + settings.push(format!("branch = {}", quote_sql_string(branch))); + } + if let Some(concurrency) = options.concurrency { + settings.push(format!("concurrency = {concurrency}")); + } + let mut sql = "PREWARM".to_string(); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + let mut columns = Vec::new(); + for column in &options.columns { + let parts = lance::datatypes::parse_field_path(column)?; + let column = parts + .iter() + .map(|part| quote_sql_identifier(part)) + .collect::>() + .join("."); + if !columns.contains(&column) { + columns.push(column); + } + } + let projection = if columns.is_empty() { + "*".into() + } else { + columns.join(", ") + }; + sql.push_str(&format!( + " AS SELECT {projection} FROM {}", + quote_sql_identifier(table) + )); + if let Some(filter) = &options.filter { + sql.push_str(&format!(" WHERE {filter}")); + } + Ok(sql) +} + +pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> { + let invalid = || { + Error::Runtime { + message: "PREWARM did not return a single (job_id, table_version) receipt; inspect jobs before retrying because work may already have been submitted".into(), + } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let id = batch + .column_by_name("job_id") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + let version = batch + .column_by_name("table_version") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if id.is_null(0) || id.value(0).is_empty() || version.is_null(0) { + return Err(invalid()); + } + Ok((id.value(0).into(), version.value(0))) +} + +pub(super) fn map_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<&Error> { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let diagnostic = message.to_ascii_lowercase(); + (*grpc_code == tonic::Code::Unimplemented as i32 + || (*grpc_code == tonic::Code::InvalidArgument as i32 + && (diagnostic.contains("found: prewarm") + || diagnostic.contains("supported syntax: prewarm") + || diagnostic.contains("unknown prewarm option")))) + .then_some(error) + } + Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported), + _ => None, + } + } + if let Some(source) = unsupported(&error) { + let diagnostic = if matches!(error, Error::Sql { .. }) { + error.to_string() + } else { + format!("{error}; {source}") + }; + Error::NotSupported { + message: format!( + "Data prewarm requires a compatible SQL PREWARM server; upgrade the server. Requested options will not be removed and submission will not fall back to REST. Server diagnostic: {diagnostic}" + ), + } + } else { + error + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + #[test] + fn quotes_paths_branch_and_filter_without_changing_options() { + let options = PrewarmDataOptions::new() + .columns(["attrs.score", "`caption.text`", "attrs.score"]) + .filter("quality > 0.7 AND caption = 'it''s ready'") + .concurrency(4); + assert_eq!( + statement("clip\"name", Some("o'brien"), &options).unwrap(), + "PREWARM WITH (branch = 'o''brien', concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7 AND caption = 'it''s ready'" + ); + assert_eq!( + statement("clips", None, &Default::default()).unwrap(), + "PREWARM AS SELECT * FROM \"clips\"" + ); + assert!(statement("clips", None, &PrewarmDataOptions::new().filter("-1 < id")).is_ok()); + } + + #[test] + fn rejects_invalid_inputs_before_submission() { + for options in [ + PrewarmDataOptions::new().filter(""), + PrewarmDataOptions::new().filter("id > 0; DROP TABLE clips"), + PrewarmDataOptions::new().filter("id > 0 LIMIT 1"), + PrewarmDataOptions::new().filter("id >"), + PrewarmDataOptions::new().columns(["attrs..score"]), + PrewarmDataOptions::new().concurrency(0), + ] { + assert!(statement("clips", None, &options).is_err(), "{options:?}"); + } + } + + fn batch(ids: Vec>, versions: Vec>) -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "job_id", + Arc::new(StringArray::from(ids)) as arrow_array::ArrayRef, + ), + ( + "table_version", + Arc::new(UInt64Array::from(versions)) as arrow_array::ArrayRef, + ), + ]) + .unwrap() + } + + #[test] + fn receipt_requires_one_non_null_job_and_version() { + assert_eq!( + receipt(&[batch(vec![Some("job-1")], vec![Some(42)])]).unwrap(), + ("job-1".into(), 42) + ); + for batches in [ + vec![], + vec![batch(vec![], vec![])], + vec![batch(vec![None], vec![Some(42)])], + vec![batch(vec![Some("")], vec![Some(42)])], + vec![batch(vec![Some("job")], vec![None])], + vec![batch(vec![Some("a"), Some("b")], vec![Some(1), Some(2)])], + vec![ + batch(vec![Some("a")], vec![Some(1)]), + batch(vec![Some("b")], vec![Some(2)]), + ], + vec![RecordBatch::new_empty(Arc::new(Schema::new(vec![ + Field::new("wrong", DataType::Utf8, false), + ])))], + ] { + let error = receipt(&batches).unwrap_err().to_string(); + assert!(error.contains("inspect jobs before retrying"), "{error}"); + } + } + + #[test] + fn compatibility_errors_preserve_permission_and_predicate_diagnostics() { + for (code, message, unsupported) in [ + ( + tonic::Code::InvalidArgument, + "ParserError: found: PREWARM", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown PREWARM option 'branch'", + true, + ), + (tonic::Code::PermissionDenied, "permission denied", false), + ( + tonic::Code::InvalidArgument, + "ParserError: expected expression, found unsupported_filter", + false, + ), + ] { + let error = map_error(Error::Sql { + message: message.into(), + request_id: "prewarm-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }); + assert_eq!(matches!(error, Error::NotSupported { .. }), unsupported); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("prewarm-request")); + } + } +} diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4959b2842..e8ce17b7b 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -86,6 +86,8 @@ pub mod freshness; pub mod function_column_status; pub mod merge; pub mod optimize; +mod prewarm; +pub use prewarm::PrewarmDataOptions; pub(crate) mod primary_key; pub mod query; pub mod refresh; @@ -685,6 +687,13 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Currently only supported in LanceDB Enterprise. /// If `columns` is `None`, all columns are prewarmed. async fn prewarm_data(&self, columns: Option>) -> Result<()>; + + /// Submit a data-cache prewarm and return its durable job handle. + async fn prewarm_data_async(&self, _options: PrewarmDataOptions) -> Result { + Err(Error::NotSupported { + message: "data prewarm jobs are only supported on remote tables".into(), + }) + } /// Get statistics about the index. async fn index_stats(&self, index_name: &str) -> Result>; /// Merge insert new records into the table. @@ -2969,8 +2978,9 @@ impl Table { /// 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 — - /// calling it on already-prewarmed columns is a no-op on the server. + /// Remote tables use SQL PREWARM and require Flight SQL connectivity. + /// Use [`Self::prewarm_data_async`] to retain the durable job handle. + /// Repeated submissions can create distinct jobs; warming cached data is safe. /// /// 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 @@ -2982,6 +2992,38 @@ impl Table { self.inner.prewarm_data(columns).await } + /// Submit a durable data-cache prewarm job through SQL and return when accepted. + /// + /// The handle tracks the warming job, rather than the SQL submission. Use + /// [`Job::wait`] to wait for warming to finish, or save [`Job::id`] and + /// reopen it through [`crate::Connection::open_job`]. A wait timeout or + /// dropping the handle does not cancel the job. No terminal payload is + /// defined: waiting succeeds with `()`. + /// + /// Requires a compatible remote server with SQL PREWARM support and Flight + /// SQL connectivity. Under Standard authorization, submission requires + /// Select on the table and Usage on its database and namespace hierarchy. + /// Status and waiting use the generic HTTP job APIs; events and cancellation + /// retain their separate privileges. Unsupported servers are not retried + /// through REST or with requested settings removed. Local tables are unsupported. + /// Historical-version checkouts are unsupported; use `checkout_latest()` first. + /// After [`Job::refresh`], the pinned source version is in [`Job::spec`]. + /// + /// ```no_run + /// # async fn warm(table: &lancedb::Table) -> lancedb::Result<()> { + /// use lancedb::table::PrewarmDataOptions; + /// let job = table.prewarm_data_async(PrewarmDataOptions::new() + /// .columns(["video"]) + /// .filter("quality > 0.7") + /// .concurrency(4)).await?; + /// job.wait().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn prewarm_data_async(&self, options: PrewarmDataOptions) -> Result { + self.inner.prewarm_data_async(options).await + } + /// Poll until the columns are fully indexed. Will return Error::Timeout if the columns /// are not fully indexed within the timeout. pub async fn wait_for_index( diff --git a/rust/lancedb/src/table/prewarm.rs b/rust/lancedb/src/table/prewarm.rs new file mode 100644 index 000000000..142f7b864 --- /dev/null +++ b/rust/lancedb/src/table/prewarm.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Options for submitting a durable data-cache prewarm job. + +/// Data prewarm settings for [`super::Table::prewarm_data_async`]. +/// +/// The table handle supplies the database, namespace, and branch. Omitted +/// columns warm all fields. The filter selects conservative metadata ranges; +/// it does not execute a row-filter scan or change the source data. +#[derive(Debug, Clone, Default)] +#[non_exhaustive] +pub struct PrewarmDataOptions { + /// Lance field paths, including nested paths such as `attrs.score`. + pub columns: Vec, + /// An optional SQL predicate for metadata pruning. + pub filter: Option, + /// Positive per-executor warming concurrency. Omit for the server default. + pub concurrency: Option, +} + +impl PrewarmDataOptions { + /// Use server defaults and warm every column. + pub fn new() -> Self { + Self::default() + } + + /// Select fields to warm. An empty collection selects all columns. + pub fn columns(mut self, columns: impl IntoIterator>) -> Self { + self.columns = columns.into_iter().map(Into::into).collect(); + self + } + + /// Restrict warming using a single SQL predicate for metadata pruning. + pub fn filter(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } + + /// Set positive per-executor warming concurrency. + pub fn concurrency(mut self, concurrency: u32) -> Self { + self.concurrency = Some(concurrency); + self + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + #[tokio::test] + async fn local_table_rejects_durable_data_prewarm() { + let db = crate::connect(&format!("memory://prewarm-{}", uuid::Uuid::new_v4())) + .execute() + .await + .unwrap(); + let table = db + .create_empty_table( + "items", + Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])), + ) + .execute() + .await + .unwrap(); + let error = table + .prewarm_data_async(PrewarmDataOptions::new().filter("id > 0")) + .await + .unwrap_err(); + assert!(matches!(error, crate::Error::NotSupported { .. })); + assert!( + error + .to_string() + .contains("only supported on remote tables") + ); + } +}