From 7b2dfb9e361bddfbf4b3e16f2d950f377d5b5e33 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 01:19:05 -0800 Subject: [PATCH 01/36] fix(python): align catalog and database connection inputs (#4983) Align Python catalog connection inputs with database connections, warn when region is ignored, and preserve remote storage settings in opened databases. --- docs/web/basics/catalog.mdx | 18 +++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/catalog.py | 154 ++++++++++++++++++++++-- python/python/lancedb/remote/db.py | 3 +- python/python/tests/test_catalog.py | 176 +++++++++++++++++++++++++++- python/python/type_tests/connect.py | 20 +++- python/src/catalog.rs | 8 +- rust/lancedb/src/catalog.rs | 12 ++ rust/lancedb/src/remote/catalog.rs | 10 ++ rust/lancedb/src/remote/db.rs | 2 +- 10 files changed, 389 insertions(+), 15 deletions(-) diff --git a/docs/web/basics/catalog.mdx b/docs/web/basics/catalog.mdx index 1e95aeca4..519d86067 100644 --- a/docs/web/basics/catalog.mdx +++ b/docs/web/basics/catalog.mdx @@ -158,6 +158,24 @@ list, create and drop databases across the whole deployment. Its `connect_database(name)` and `create_database(name)` then return the same kind of database connection `lancedb.connect()` does. +In Python, `connect_catalog` and `connect_catalog_async` accept the same +connection settings as their database counterparts. Use `host_override` to +share settings that include a `db://` URI; the catalog connection targets +the root of that deployment and ignores the database name. An explicitly +supplied `region` is ignored with a warning, since the HTTP(S) endpoint +selects the deployment. Embedded-only session and namespace settings are +unsupported. + +```python +settings = { + "uri": "db://analytics", + "api_key": "secret", + "host_override": "https://my-server.example", +} +db = lancedb.connect(**settings) +catalog = lancedb.connect_catalog(**settings) +``` + This connection is for database administration, not table or query work: list, create and drop databases through it, then switch to a **database** connection for everything else -- tables, queries, and SQL all run within a diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 521cc46bb..11798a520 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1227,6 +1227,7 @@ async def connect_catalog( sql_host_override: Optional[str] = None, read_consistency_interval: Optional[float] = None, oauth_config: Optional[Any] = None, + storage_options: Optional[dict[str, str]] = None, ) -> Catalog: ... class NameListing: diff --git a/python/python/lancedb/catalog.py b/python/python/lancedb/catalog.py index 338be98b8..5b3b0509c 100644 --- a/python/python/lancedb/catalog.py +++ b/python/python/lancedb/catalog.py @@ -3,13 +3,17 @@ """Remote catalogs manage databases.""" -from functools import cached_property +import os +import warnings +from concurrent.futures import ThreadPoolExecutor from datetime import timedelta +from functools import cached_property from typing import Any, AsyncIterator, Iterator, Optional, Union from . import _lancedb from .background_loop import LOOP from .authz import AsyncAuthorization, Authorization +from .common import URI, sanitize_uri from .db import AsyncConnection, DBConnection from .remote import ClientConfig, OAuthConfig from .remote.db import RemoteDBConnection @@ -163,12 +167,14 @@ class Catalog: client_config=None, sql_host_override: Optional[str] = None, oauth_config: Optional[OAuthConfig] = None, + storage_options: Optional[dict[str, str]] = None, ): self._inner = inner self._api_key = api_key self._client_config = client_config self._sql_host_override = sql_host_override self._oauth_config = oauth_config + self._storage_options = storage_options @cached_property def authz(self) -> Authorization: @@ -198,6 +204,7 @@ class Catalog: self._client_config, self._oauth_config, self._sql_host_override, + self._storage_options, ) def list_databases( @@ -227,28 +234,71 @@ class Catalog: async def connect_catalog_async( - endpoint: str, + uri: Optional[URI] = None, *, api_key: Optional[str] = None, - client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + region: Optional[str] = None, + host_override: Optional[str] = None, sql_host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, + client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + storage_options: Optional[dict[str, str]] = None, + session: Optional[_lancedb.Session] = None, + manifest_enabled: bool = False, + namespace_client_properties: Optional[dict[str, str]] = None, oauth_config: Optional[OAuthConfig] = None, ) -> AsyncCatalog: - """Connect to an HTTP(S) server's root catalog. + """Connect to a server's root catalog using database connection settings. + + ``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise + ``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with + [connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's + database is ignored and requests target the root catalog. + + ``region`` is ignored with a warning when supplied. Catalog connections use + the explicit endpoint rather than a region-derived Cloud (legacy) endpoint. + ``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable. + Embedded-only ``session``, ``manifest_enabled`` and + ``namespace_client_properties`` are not supported. Root requests omit database-selection headers. API key, client configuration, - OAuth, and table read consistency settings are inherited by opened databases. + OAuth, storage options, and table read consistency settings are inherited by + opened databases. Database names containing slashes remain single logical names. Set ``sql_host_override`` to the SQL service endpoint to execute SQL through returned connections when the catalog endpoint uses HTTPS. """ + if region is not None: + warnings.warn( + "region is ignored by connect_catalog_async; the catalog endpoint " + "is selected by host_override or uri.", + UserWarning, + stacklevel=2, + ) + for name, value in ( + ("session", session), + ("manifest_enabled", manifest_enabled or None), + ("namespace_client_properties", namespace_client_properties), + ): + if value is not None: + raise NotImplementedError( + f"{name} is not supported for catalog connections" + ) + endpoint = host_override if host_override is not None else uri + if endpoint is None: + raise ValueError("uri or host_override is required for catalog connections") if isinstance(client_config, dict): client_config = ClientConfig(**client_config) if client_config is None: client_config = ClientConfig() + if ( + api_key is None + and oauth_config is None + and client_config.header_provider is None + ): + api_key = os.environ.get("LANCEDB_API_KEY") inner = await _lancedb.connect_catalog( - endpoint, + sanitize_uri(endpoint), api_key=api_key, client_config=client_config, sql_host_override=sql_host_override, @@ -258,32 +308,115 @@ async def connect_catalog_async( else None ), oauth_config=oauth_config, + storage_options=storage_options, ) return AsyncCatalog(inner) def connect_catalog( - endpoint: str, + uri: Optional[URI] = None, *, api_key: Optional[str] = None, - client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + region: Optional[str] = None, + host_override: Optional[str] = None, sql_host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, + request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None, + client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + storage_options: Optional[dict[str, str]] = None, + session: Optional[_lancedb.Session] = None, + manifest_enabled: bool = False, + namespace_client_impl: Optional[str] = None, + namespace_client_properties: Optional[dict[str, str]] = None, + namespace_client_pushdown_operations: Optional[list[str]] = None, oauth_config: Optional[OAuthConfig] = None, + **kwargs: Any, ) -> Catalog: - """Connect synchronously to an HTTP(S) server's root catalog. + """Connect synchronously to a root catalog using database connection settings. See [connect_catalog_async][lancedb.connect_catalog_async] for options. + The inputs match [connect][lancedb.connect]; ``region`` is ignored with a + warning when supplied. Namespace client options and embedded session settings + are not supported. ``request_thread_pool`` is deprecated and unused, as in + ``connect``. Local filesystem and object-store catalogs are not supported. + + Examples + -------- + ```python + settings = {"api_key": "secret", "host_override": "https://my-server.example"} + catalog = lancedb.connect_catalog("db://analytics", **settings) + db = lancedb.connect("db://analytics", **settings) + ``` """ + unknown_kwargs = { + key: value + for key, value in kwargs.items() + if key not in ("connection_timeout", "read_timeout") + } + if unknown_kwargs: + raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}") + for name, value in ( + ("namespace_client_impl", namespace_client_impl), + ("namespace_client_pushdown_operations", namespace_client_pushdown_operations), + ): + if value is not None: + raise NotImplementedError( + f"{name} is not supported for catalog connections" + ) + if region is not None: + warnings.warn( + "region is ignored by connect_catalog; the catalog endpoint " + "is selected by host_override or uri.", + UserWarning, + stacklevel=2, + ) + if request_thread_pool is not None: + warnings.warn( + "request_thread_pool is no longer used and will be removed in " + "a future release.", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(client_config, dict): + client_config = ClientConfig(**client_config) + if client_config is None: + client_config = ClientConfig() + for name, field in ( + ("connection_timeout", "connect_timeout"), + ("read_timeout", "read_timeout"), + ): + if kwargs.get(name) is not None: + warnings.warn( + f"{name} is deprecated and will be removed in a future release. " + f"Please use client_config.timeout_config.{field} instead.", + DeprecationWarning, + stacklevel=2, + ) + setattr( + client_config.timeout_config, + field, + timedelta(seconds=kwargs[name]), + ) + if ( + api_key is None + and oauth_config is None + and client_config.header_provider is None + ): + api_key = os.environ.get("LANCEDB_API_KEY") return Catalog( LOOP.run( connect_catalog_async( - endpoint, + uri, api_key=api_key, + host_override=host_override, client_config=client_config, sql_host_override=sql_host_override, read_consistency_interval=read_consistency_interval, + storage_options=storage_options, + session=session, + manifest_enabled=manifest_enabled, + namespace_client_properties=namespace_client_properties, oauth_config=oauth_config, ) ), @@ -291,4 +424,5 @@ def connect_catalog( client_config=client_config, sql_host_override=sql_host_override, oauth_config=oauth_config, + storage_options=storage_options, ) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 21ad37b36..4219ca40b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -214,6 +214,7 @@ class RemoteDBConnection(DBConnection): client_config, oauth_config, sql_host_override, + storage_options, ): config = ( ClientConfig(**client_config) @@ -233,7 +234,7 @@ class RemoteDBConnection(DBConnection): result.region = "us-east-1" result.host_override = endpoint result.sql_host_override = sql_host_override - result.storage_options = None + result.storage_options = storage_options result.client_config = replace(config, extra_headers=headers) result._catalog_oauth = oauth_config is not None result._conn = inner diff --git a/python/python/tests/test_catalog.py b/python/python/tests/test_catalog.py index 95b03c6e7..edac21bc1 100644 --- a/python/python/tests/test_catalog.py +++ b/python/python/tests/test_catalog.py @@ -2,7 +2,9 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from datetime import timedelta import json +import warnings import pytest @@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): endpoint, api_key="secret", sql_host_override="invalid://localhost", + storage_options={"azure_storage_account_name": "catalog-account"}, client_config={ "extra_headers": { "X-LanceDB-Database": "wrong", @@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): assert db.table_names() == [] restored = lancedb.deserialize_conn(db.serialize()) assert restored.sql_host_override == "invalid://localhost" + assert restored.storage_options == {"azure_storage_account_name": "catalog-account"} for connection in (db, restored): with pytest.raises(ValueError, match="sql_host_override must use"): connection.execute_query_async("SELECT 1") @@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): ) assert "x-lancedb-database-prefix" not in headers assert headers["x-api-key"] == "secret" + assert headers["x-azure-storage-account-name"] == "catalog-account" @pytest.mark.asyncio @@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server): ] ) catalog = await lancedb.connect_catalog_async( - endpoint, sql_host_override="invalid://localhost" + endpoint, + sql_host_override="invalid://localhost", + storage_options={"account_name": "async-account"}, ) assert isinstance(catalog, lancedb.AsyncCatalog) db = await catalog.connect_database("analytics") @@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server): await catalog.drop_database("full") await catalog.drop_database("missing", ignore_missing=True) assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"} + for _, headers, _ in requests: + headers = {key.lower(): value for key, value in headers.items()} + assert headers["x-azure-storage-account-name"] == "async-account" @pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"]) @@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint): lancedb.connect_catalog(endpoint) +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"]) +@pytest.mark.asyncio +async def test_catalog_accepts_database_connection_settings( + catalog_server, asynchronous, region +): + endpoint, requests, responses = catalog_server + responses.extend([(200, {"namespaces": []}), (200, {"tables": []})]) + settings = { + "uri": "db://analytics", + "api_key": "shared-secret", + "region": region, + "host_override": endpoint, + "sql_host_override": "invalid://localhost", + "read_consistency_interval": timedelta(seconds=5), + "client_config": {"extra_headers": {"x-shared-setting": "shared"}}, + "storage_options": {"azure_storage_account_name": "shared-account"}, + "session": None, + "manifest_enabled": False, + "namespace_client_properties": None, + } + if not asynchronous: + settings.update( + request_thread_pool=None, + namespace_client_impl=None, + namespace_client_pushdown_operations=None, + ) + with pytest.warns( + UserWarning, match="region is ignored by connect_catalog" + ) as caught: + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert len(caught) == 1 + assert catalog.uri == endpoint + assert ( + [name async for name in catalog.list_databases()] + if asynchronous + else list(catalog.list_databases()) + ) == [] + db = ( + await lancedb.connect_async(**settings) + if asynchronous + else lancedb.connect(**settings) + ) + assert (await db.table_names() if asynchronous else db.table_names()) == [] + root_headers = {key.lower(): value for key, value in requests[0][1].items()} + db_headers = {key.lower(): value for key, value in requests[1][1].items()} + for headers in (root_headers, db_headers): + assert headers["x-api-key"] == "shared-secret" + assert headers["x-shared-setting"] == "shared" + assert headers["x-azure-storage-account-name"] == "shared-account" + assert "x-lancedb-database" not in root_headers + assert db_headers["x-lancedb-database"] == "analytics" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("host_only", [False, True]) +@pytest.mark.asyncio +async def test_catalog_default_region_is_silent_and_api_key_uses_environment( + catalog_server, monkeypatch, asynchronous, host_only +): + endpoint, requests, responses = catalog_server + monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret") + responses.extend([(200, {}), (200, {"tables": []})]) + settings = {"host_override": endpoint} if host_only else {"uri": endpoint} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert caught == [] + assert catalog.uri == endpoint + db = ( + await catalog.connect_database("analytics") + if asynchronous + else catalog.connect_database("analytics") + ) + if not asynchronous: + db = lancedb.deserialize_conn(db.serialize()) + assert (await db.table_names() if asynchronous else db.table_names()) == [] + for _, headers, _ in requests: + headers = {key.lower(): value for key, value in headers.items()} + assert headers["x-api-key"] == "environment-secret" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.asyncio +async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous): + endpoint, _, _ = catalog_server + settings = {"uri": "https://unused.example", "host_override": endpoint} + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert catalog.uri == endpoint + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "options, message", + [ + ({}, "uri or host_override is required"), + ({"session": object()}, "session"), + ({"manifest_enabled": True}, "manifest_enabled"), + ({"namespace_client_properties": {}}, "namespace_client_properties"), + ], +) +@pytest.mark.asyncio +async def test_catalog_rejects_unsupported_connection_settings( + catalog_server, asynchronous, options, message +): + _, requests, _ = catalog_server + error = NotImplementedError if options else ValueError + with pytest.raises(error, match=message): + if asynchronous: + await lancedb.connect_catalog_async(**options) + else: + lancedb.connect_catalog(**options) + assert requests == [] + + +@pytest.mark.parametrize( + "options, error, message", + [ + ( + {"namespace_client_impl": "dir"}, + NotImplementedError, + "namespace_client_impl", + ), + ( + {"namespace_client_pushdown_operations": []}, + NotImplementedError, + "namespace_client_pushdown_operations", + ), + ({"unknown_option": True}, ValueError, "Unknown keyword arguments"), + ], +) +def test_catalog_rejects_unsupported_sync_settings(options, error, message): + with pytest.raises(error, match=message): + lancedb.connect_catalog(**options) + + +def test_catalog_accepts_deprecated_sync_settings(catalog_server): + endpoint, _, responses = catalog_server + responses.append((200, {})) + with pytest.warns(DeprecationWarning) as caught: + catalog = lancedb.connect_catalog( + endpoint, + request_thread_pool=2, + connection_timeout=5, + read_timeout=10, + ) + assert len(caught) == 3 + db = catalog.connect_database("analytics") + assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5) + assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10) + + @pytest.mark.parametrize("asynchronous", [False, True]) @pytest.mark.asyncio @pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)]) diff --git a/python/python/type_tests/connect.py b/python/python/type_tests/connect.py index eb2cba37c..6da32d2ec 100644 --- a/python/python/type_tests/connect.py +++ b/python/python/type_tests/connect.py @@ -4,12 +4,30 @@ from typing import assert_type import lancedb -from lancedb import AsyncConnection, DBConnection +from lancedb import AsyncCatalog, AsyncConnection, Catalog, DBConnection def check_connect_type() -> None: assert_type(lancedb.connect("memory://"), DBConnection) + assert_type( + lancedb.connect_catalog( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + Catalog, + ) async def check_connect_async_type() -> None: assert_type(await lancedb.connect_async("memory://"), AsyncConnection) + assert_type( + await lancedb.connect_catalog_async( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + AsyncCatalog, + ) diff --git a/python/src/catalog.rs b/python/src/catalog.rs index fb2e7e8a0..456d62a3c 100644 --- a/python/src/catalog.rs +++ b/python/src/catalog.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -127,7 +128,8 @@ impl DatabaseNames { } #[pyfunction] -#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None))] +#[allow(clippy::too_many_arguments)] +#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None, storage_options=None))] pub fn connect_catalog( py: Python<'_>, endpoint: String, @@ -136,6 +138,7 @@ pub fn connect_catalog( sql_host_override: Option, read_consistency_interval: Option, oauth_config: Option, + storage_options: Option>, ) -> PyResult> { let interval = read_consistency_interval .map(Duration::try_from_secs_f64) @@ -151,6 +154,9 @@ pub fn connect_catalog( if let Some(config) = client_config { builder = builder.client_config(config.into()); } + if let Some(options) = storage_options { + builder = builder.storage_options(options); + } if let Some(endpoint) = sql_host_override { builder = builder.sql_host_override(endpoint); } diff --git a/rust/lancedb/src/catalog.rs b/rust/lancedb/src/catalog.rs index df80b6de6..dcea8fd90 100644 --- a/rust/lancedb/src/catalog.rs +++ b/rust/lancedb/src/catalog.rs @@ -349,6 +349,18 @@ impl ConnectCatalogBuilder { self.options.client_config = config; self } + /// Set storage options inherited by the catalog's remote database connections. + pub fn storage_options( + mut self, + options: impl IntoIterator, impl Into)>, + ) -> Self { + self.options.storage_options.extend( + options + .into_iter() + .map(|(key, value)| (key.into(), value.into())), + ); + self + } /// Set the SQL service endpoint inherited by database connections. /// /// Required to execute SQL when the catalog endpoint uses HTTPS. The SQL diff --git a/rust/lancedb/src/remote/catalog.rs b/rust/lancedb/src/remote/catalog.rs index 95facd04b..c620cf272 100644 --- a/rust/lancedb/src/remote/catalog.rs +++ b/rust/lancedb/src/remote/catalog.rs @@ -30,6 +30,8 @@ pub struct RemoteCatalogOptions { pub api_key: Option, /// Shared transport and authentication settings. pub client_config: ClientConfig, + /// Storage options supported by remote database connections. + pub storage_options: HashMap, /// SQL service endpoint used by returned database connections. /// Required for SQL when the catalog endpoint uses HTTPS. pub sql_host_override: Option, @@ -391,6 +393,10 @@ mod tests { .await; let mut options = RemoteCatalogOptions { api_key: Some("test-key".into()), + storage_options: HashMap::from([( + "azure_storage_account_name".into(), + "catalog-account".into(), + )]), ..Default::default() }; options.client_config.extra_headers = HashMap::from([ @@ -460,6 +466,10 @@ mod tests { ); assert!(!request.headers.contains_key("x-lancedb-database-prefix")); assert_eq!(request.headers["authorization"], "Bearer refreshed"); + assert_eq!( + request.headers["x-azure-storage-account-name"], + "catalog-account" + ); } assert_eq!( requests[0].line, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a9d55b511..549baf345 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -385,7 +385,7 @@ impl RemoteDatabase { sql: options.sql_host_override.clone(), }, config, - RemoteOptions::default(), + StorageOptions(options.storage_options.clone()).into(), options.read_consistency_interval, super::client::ParsedDbUrl { db_name: name.unwrap_or("").to_string(), From ced4799ad51f7ee4dd4bdff40c061ef59d8bb014 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 01:21:58 -0800 Subject: [PATCH 02/36] fix(python): preserve typed results for reopened refresh jobs (#4981) Restore typed results for reopened Function and SQL-expression refresh jobs while preserving their handles and cached descriptions. Fixes https://linear.app/lancedb/issue/ENT-3441. --- python/python/lancedb/db.py | 10 +- python/python/lancedb/job.py | 7 ++ python/python/tests/test_remote_db.py | 138 ++++++++++++++++++++++++++ python/src/connection.rs | 11 +- rust/lancedb/src/job.rs | 51 ++++++++++ rust/lancedb/src/remote/job.rs | 23 +++++ 6 files changed, 236 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 84ebb41a1..e2138520a 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -67,7 +67,7 @@ from .graph import ( PropertyGraph, _definition_json, ) -from .job import AsyncJob, Job, _typed_job +from .job import AsyncJob, Job, _opened_job, _typed_job from .storage_integration import SecretReference, StorageIntegrationInfo from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery @@ -1450,6 +1450,12 @@ class DBConnection(EnforceOverrides): specification, result, failure and event history, so there is no separate connection-level call for any of them. + For a column refresh, ``wait()`` returns a + [RefreshColumnResult][lancedb.functions.RefreshColumnResult], including + when the refresh was started through SQL. Other job types return + ``None`` from ``wait()``; their persisted result is available through + ``job.result`` after ``job.refresh()``. + Raises `JobNotFoundError` when the server has no such job, the way `open_table` does for a missing table. """ @@ -3626,7 +3632,7 @@ class AsyncConnection(object): """Open a server-side job by id. See [DBConnection.open_job][lancedb.db.DBConnection.open_job]. """ - return AsyncJob(await self._inner.open_job(job_id)) + return _opened_job(await self._inner.open_job(job_id)) async def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 094a7b8d5..bf9605567 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -17,6 +17,7 @@ from lancedb.background_loop import LOOP from . import _lancedb from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url +from .functions import RefreshColumnResult from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -692,3 +693,9 @@ def _typed_job( ) -> AsyncJob[T]: """Bind an internal JSON-producing job to its public result model.""" return AsyncJob(inner, result_decoder) + + +def _opened_job(inner: "_lancedb.Job") -> AsyncJob: + if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"): + return _typed_job(inner, RefreshColumnResult.from_json) + return AsyncJob(inner) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b0098aca3..8fde1209c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2557,6 +2557,144 @@ async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync): assert exc.value.__cause__.is_transport_error is True +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize( + "job_type", ["function_refresh", "computed_refresh", "refresh_column"] +) +@pytest.mark.parametrize("running", [False, True]) +@pytest.mark.parametrize("rows_failed", [0, 8]) +async def test_reopened_refresh_job_wait_returns_typed_result( + sync, job_type, running, rows_failed +): + terminal_result = { + "rows_assigned": 400 - rows_failed, + "rows_failed": rows_failed, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + "summary": {"future_field": True}, + } + polls = 0 + + def handler(request): + nonlocal polls + assert request.path == "/v1/jobs/describe" + payload = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert payload == {"job_id": "refresh-1"} + polls += 1 + in_progress = running and polls <= 2 + response = { + "job_id": "refresh-1", + "job_type": job_type, + "job_state": "IN_PROGRESS" if in_progress else "DONE", + "creation_ms": 1000, + "spec": {"column": "derived"}, + } + if not in_progress: + response["result"] = terminal_result + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + observed = [] + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + assert job.id == "refresh-1" + assert job.spec == {"column": "derived"} + result = job.wait(timeout=timedelta(seconds=5), progress=observed.append) + assert job.wait() == result + job.refresh() + assert job.result == terminal_result + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + assert job.id == "refresh-1" + assert job.spec == {"column": "derived"} + result = await job.wait( + timeout=timedelta(seconds=5), progress=observed.append + ) + assert await job.wait() == result + await job.refresh() + assert job.result == terminal_result + + assert isinstance(result, lancedb.RefreshColumnResult) + assert result == lancedb.RefreshColumnResult.model_validate(terminal_result) + assert result.rows_failed == rows_failed + assert observed[-1]["state"] == "finished" + if running: + assert observed[0]["state"] == "running" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("terminal_result", [None, {}]) +async def test_reopened_refresh_job_rejects_missing_or_invalid_result( + sync, terminal_result +): + def handler(request): + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + with pytest.raises(HttpError, match="typed job"): + job.wait() + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + with pytest.raises(HttpError, match="typed job"): + await job.wait() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_reopened_unit_job_ignores_additive_result_payload(sync): + terminal_result = {"future_field": True} + + def handler(request): + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "index-1", + "job_type": "create_index", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("index-1") + assert job.wait() is None + assert job.result == terminal_result + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("index-1") + assert await job.wait() is None + assert job.result == terminal_result + + @pytest.mark.parametrize("payload", [b"{", b"{}"]) def test_remote_job_wait_does_not_retry_malformed_description(payload): polls = 0 diff --git a/python/src/connection.rs b/python/src/connection.rs index 0be933cf2..69cf54c99 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -24,7 +24,7 @@ use lancedb::{ connection::NamespaceClientPushdownOperation, database::namespace::LanceNamespaceDatabase, database::{CreateTableMode, Database, ReadConsistency}, - function::GpuClass as LanceGpuClass, + function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, }; use pyo3::{ @@ -854,7 +854,14 @@ impl Connection { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let job = inner.open_job(&job_id).await.infer_error()?; - Ok(crate::job::Job::new(job)) + match job.job_type().as_deref() { + Some("function_refresh" | "computed_refresh" | "refresh_column") => { + Ok(crate::job::Job::new_typed( + job.into_typed::().infer_error()?, + )) + } + _ => Ok(crate::job::Job::new(job)), + } }) } diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index d178542b7..092ece8b5 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -277,6 +277,42 @@ impl Job<()> { } job } + + /// Decode this job's terminal payload as `T` when waiting. + /// + /// Use this after [`crate::Connection::open_job`] when the job's result + /// type is known. The job identity and cached description are preserved. + /// Missing or incompatible payloads are reported by [`Job::wait`]. + /// A job that completed before its handle was created has only a unit + /// result; converting it fails immediately if `T` cannot decode JSON null. + /// + /// ```no_run + /// # async fn reopen( + /// # db: &lancedb::Connection, id: &str, + /// # ) -> lancedb::Result { + /// let job = db.open_job(id).await? + /// .into_typed::()?; + /// job.wait().await + /// # } + /// ``` + pub fn into_typed(self) -> Result> + where + T: Clone + DeserializeOwned + Send + Sync + 'static, + { + let inner = match self.inner { + JobInner::Handle { handle, .. } => JobInner::Handle { + handle, + decode: Arc::new(TerminalResult::decode::), + }, + JobInner::Completed(()) => { + JobInner::Completed(TerminalResult::local(Value::Null).decode::()?) + } + }; + Ok(Job { + inner, + cache: self.cache, + }) + } } impl Job @@ -750,6 +786,21 @@ mod tests { )); } + #[tokio::test] + async fn completed_unit_job_can_be_retyped_as_unit() { + let job = Job::new_done().into_typed::<()>().unwrap(); + job.wait().await.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + } + + #[test] + fn completed_unit_job_rejects_an_incompatible_result_type() { + assert!(matches!( + Job::new_done().into_typed::(), + Err(Error::Runtime { .. }) + )); + } + #[tokio::test] async fn mapped_spawned_job_reuses_outcome() { let job = Job::spawned(tokio::spawn(async { Ok(41_u64) })).map(|value| value + 1); diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index d27c9c666..5a0afa7e8 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -403,6 +403,29 @@ mod tests { ); } + #[tokio::test] + async fn reopened_job_preserves_its_description_and_decodes_the_terminal_result() { + let description: DescribeJobResponse = serde_json::from_str(REFRESH_JOB).unwrap(); + let job = Job::opened( + Box::new(FixtureRemoteJob(REFRESH_JOB)), + description.into_description(), + ); + let raw_result = job.result(); + let job = job.into_typed::().unwrap(); + + assert_eq!(job.job_type().as_deref(), Some("refresh_function_columns")); + assert_eq!(job.state().as_deref(), Some("finished")); + assert_eq!(job.creation_ms(), Some(1787270400001)); + assert_eq!(job.result(), raw_result); + assert_eq!(job.wait().await.unwrap().rows_assigned, 999_998_800); + assert_eq!(job.wait().await.unwrap().published_version, Some(919)); + + let missing = Job::new(Box::new(FixtureRemoteJob(MISSING_RESULT_JOB))) + .into_typed::() + .unwrap(); + assert!(missing.wait().await.is_err()); + } + /// Five in-progress polls then done: 0.2 + 0.4 + 0.8 + 1 + 1 s of waiting. /// Under the old 5 s cap the same job would have waited 10 s. #[tokio::test(start_paused = true)] From 9e03bf97d400572e38d265f5c59acd990c4d818a Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 08:03:11 -0800 Subject: [PATCH 03/36] feat(python): support exist_ok when creating secrets (#4978) Add `exist_ok=False` to synchronous and asynchronous Python `create_secret`. Passing `True` uses `CREATE SECRET IF NOT EXISTS`, preserving an existing credential. The default continues to fail on an existing name; rotation stays explicit through `alter_secret`. ```python db.create_secret("api-key", value, exist_ok=True) await async_db.create_secret("api-key", value, exist_ok=True) ``` The Rust API gains an awaitable builder with `.exist_ok(true)` while existing `create_secret(...).await` calls keep working. Includes Python SQL round-trip coverage and Rust coverage for direct and deferred SQL responses. --- python/python/lancedb/_lancedb.pyi | 7 ++- python/python/lancedb/db.py | 48 ++++++++++++--- python/python/lancedb/remote/db.py | 13 ++++- python/python/tests/test_sql.py | 50 ++++++++++++++++ python/src/connection.rs | 4 +- rust/lancedb/src/connection.rs | 29 +++++++--- rust/lancedb/src/connection/create_secret.rs | 61 ++++++++++++++++++++ rust/lancedb/src/database.rs | 5 +- rust/lancedb/src/remote/db.rs | 12 +++- rust/lancedb/src/remote/sql.rs | 1 + rust/lancedb/src/remote/sql/secret.rs | 29 +++++++--- rust/lancedb/src/remote/sql_test.rs | 48 +++++++++++++-- 12 files changed, 269 insertions(+), 38 deletions(-) create mode 100644 rust/lancedb/src/connection/create_secret.rs diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 11798a520..a64014cb7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -228,7 +228,12 @@ class Connection(object): self, name: str, namespace_path: Optional[List[str]] = None ) -> None: ... async def create_secret( - self, name: str, value: str, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> None: ... async def alter_secret( self, name: str, value: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index e2138520a..59fa5b4c6 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1158,14 +1158,24 @@ class DBConnection(EnforceOverrides): ) def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: """Create a named Secret in this database. - Fails if the name is taken, so a create never silently becomes a - rotation. Nothing reads the value back: it is bound to a Function by + Fails if the name is taken unless ``exist_ok=True``, which leaves the + existing value unchanged. Use :meth:`alter_secret` to rotate a Secret. + Nothing reads the value back: it is bound to a Function by name and resolved by the service when that Function runs. Local connections raise ``NotImplementedError``. + + Examples + -------- + >>> db.create_secret("api-key", "credential", exist_ok=True) # doctest: +SKIP """ raise NotImplementedError( _append_doc_url( @@ -2492,9 +2502,18 @@ class LanceDBConnection(DBConnection): @override def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: - LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path)) + LOOP.run( + self._conn.create_secret( + name, value, exist_ok=exist_ok, namespace_path=namespace_path + ) + ) @override def alter_secret( @@ -3949,17 +3968,30 @@ class AsyncConnection(object): ) async def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: """Create a named Secret in this database. - Fails if the name is taken, so a create never silently becomes a - rotation. Nothing reads the value back. + Fails if the name is taken unless ``exist_ok=True``, which leaves the + existing value unchanged. Use :meth:`alter_secret` to rotate a Secret. + Nothing reads the value back. + + Examples + -------- + >>> await db.create_secret( # doctest: +SKIP + ... "api-key", "credential", exist_ok=True + ... ) """ await self._inner.create_secret( validate_secret_name(name), value, list(validate_namespace_path(namespace_path)), + exist_ok=exist_ok, ) async def alter_secret( diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 4219ca40b..a06af5d62 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1129,9 +1129,18 @@ class RemoteDBConnection(DBConnection): @override def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: - LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path)) + LOOP.run( + self._conn.create_secret( + name, value, exist_ok=exist_ok, namespace_path=namespace_path + ) + ) @override def alter_secret( diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index b4c555635..a479fa5d1 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -293,6 +293,56 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent(): assert echoed.column("k").to_pylist() == [10] +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "status"), + [ + (None, "created"), + (False, "created"), + (True, "created"), + (True, "already_exists"), + ], +) +async def test_create_secret_exist_ok_reaches_sql(asynchronous, exist_ok, status): + flight = pytest.importorskip("pyarrow.flight") + + class SecretServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.writes = [] + + def do_exchange(self, context, descriptor, reader, writer): + self.writes.append((descriptor.command, reader.read_all())) + result = pa.table({"status": [status]}) + writer.begin(result.schema) + writer.write_table(result) + writer.close() + + with SecretServer() as server: + options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {"namespace_path": ["team", "production"]} + if exist_ok is not None: + kwargs["exist_ok"] = exist_ok + if asynchronous: + db = await lancedb.connect_async("db://analytics", **options) + await db.create_secret("api-key", "credential's value", **kwargs) + else: + db = lancedb.connect("db://analytics", **options) + db.create_secret("api-key", "credential's value", **kwargs) + ((command, parameters),) = server.writes + + prefix = "CREATE SECRET IF NOT EXISTS" if exist_ok else "CREATE SECRET" + sql = f'{prefix} "api-key" TYPE = GENERIC_STRING SECRET_STRING = $1' + assert sql.encode() in command + assert b"credential's value" not in command + assert parameters.column(0).to_pylist() == ["credential's value"] + + @pytest.mark.parametrize("job_id", [None, "sql-job-1"]) def test_sql_input_error_metadata_crosses_native_boundary(job_id): flight = pytest.importorskip("pyarrow.flight") diff --git a/python/src/connection.rs b/python/src/connection.rs index 69cf54c99..1a99c1372 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1036,18 +1036,20 @@ impl Connection { }) } - #[pyo3(signature = (name, value, namespace_path=None))] + #[pyo3(signature = (name, value, namespace_path=None, *, exist_ok=false))] pub fn create_secret( self_: PyRef<'_, Self>, name: String, value: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner .create_secret(name, value, &namespace_path) + .exist_ok(exist_ok) .await .infer_error() }) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index a360818b5..fa35dc459 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -51,8 +51,11 @@ pub use lance_file::version::LanceFileVersion; use lance_io::object_store::StorageOptions; use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; +mod create_secret; mod create_table; +pub use create_secret::CreateSecretBuilder; + pub(crate) fn merge_storage_options( store_params: &mut ObjectStoreParams, pairs: impl IntoIterator, @@ -853,20 +856,30 @@ impl Connection { /// Create a named Secret in this database. /// - /// Fails if the name is taken, so a create can never silently become a - /// rotation. There is no API that reads a stored credential back; the only + /// Fails if the name is taken unless [`CreateSecretBuilder::exist_ok`] is true, + /// in which case the existing value is left unchanged. There is no API that + /// reads a stored credential back; the only /// consumer is a Function that binds the Secret by name. LanceDB Embedded databases /// return [`Error::NotSupported`]. - pub async fn create_secret( + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// connection.create_secret("api-key", "credential", &[]).exist_ok(true).await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_secret( &self, name: impl AsRef, value: impl AsRef, namespace_path: &[String], - ) -> Result<()> { - validate_secret_reference(name.as_ref(), namespace_path)?; - self.internal - .create_secret(name.as_ref(), value.as_ref(), namespace_path) - .await + ) -> CreateSecretBuilder { + CreateSecretBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + value.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// Replace the credential behind an existing Secret. diff --git a/rust/lancedb/src/connection/create_secret.rs b/rust/lancedb/src/connection/create_secret.rs new file mode 100644 index 000000000..265b97571 --- /dev/null +++ b/rust/lancedb/src/connection/create_secret.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_secret_reference; + +/// Configure creation of a named Secret with [`super::Connection::create_secret`]. +#[must_use] +pub struct CreateSecretBuilder { + database: Arc, + name: String, + value: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateSecretBuilder { + pub(super) fn new( + database: Arc, + name: String, + value: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + value, + namespace_path, + exist_ok: false, + } + } + + /// Succeed without changing the stored value when the Secret already exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the Secret, preserving any existing value when `exist_ok` is true. + pub async fn execute(self) -> Result<()> { + validate_secret_reference(&self.name, &self.namespace_path)?; + self.database + .create_secret(&self.name, &self.value, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateSecretBuilder { + type Output = Result<()>; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index bcdfd94b8..7b4859faa 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -635,13 +635,14 @@ pub trait Database: secret_catalog_not_supported() } - /// Create a named Secret in this database. Fails if the name is taken, so - /// a create can never silently become a rotation. + /// Create a named Secret in this database. If the name is taken, fail unless + /// `exist_ok` is true, in which case the stored value is left unchanged. async fn create_secret( &self, _name: &str, _value: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result<()> { secret_catalog_not_supported() } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 549baf345..31808f244 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -44,8 +44,8 @@ use super::client::{ ClientConfig, HeaderProvider, HttpSend, ID_DELIMITER, RequestResultExt, RestfulLanceDbClient, Sender, }; -use super::sql::SqlClient; use super::sql::materialized_view::quote_identifier; +use super::sql::{SecretWriteOperation, SqlClient}; use super::storage_integration as integration_sql; use super::table::RemoteTable; use super::util::parse_server_version; @@ -1044,11 +1044,17 @@ impl Database for RemoteDatabase { name: &str, value: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result<()> { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .write_secret(name, value, namespace_path, true) + .write_secret( + name, + value, + namespace_path, + SecretWriteOperation::Create { exist_ok }, + ) .await .map_err(direct_catalog_resource_error) } @@ -1056,7 +1062,7 @@ impl Database for RemoteDatabase { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .write_secret(name, value, namespace_path, false) + .write_secret(name, value, namespace_path, SecretWriteOperation::Alter) .await .map_err(direct_catalog_resource_error) } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 0b87ff5a5..949b078e3 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -40,6 +40,7 @@ mod function; pub(super) mod materialized_view; mod objects; mod secret; +pub(super) use secret::SecretWriteOperation; mod stream; mod view; diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index bdb70ef6f..6ddc78645 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -13,6 +13,12 @@ use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::TryStreamExt; use std::sync::Arc; + +pub(in crate::remote) enum SecretWriteOperation { + Create { exist_ok: bool }, + Alter, +} + fn secret_info(batches: Vec) -> Result { if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { return Err(Error::Runtime { @@ -47,10 +53,21 @@ impl SqlClient { name: &str, value: &str, namespace: &[String], - create: bool, + operation: SecretWriteOperation, ) -> Result<()> { validate_secret_name(name)?; validate_namespace(namespace)?; + let (prefix, assignment) = match operation { + SecretWriteOperation::Create { exist_ok } => ( + if exist_ok { + "CREATE SECRET IF NOT EXISTS" + } else { + "CREATE SECRET" + }, + "TYPE = GENERIC_STRING ", + ), + SecretWriteOperation::Alter => ("ALTER SECRET", "SET "), + }; let parameters = RecordBatch::try_from_iter(vec![( "", Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, @@ -61,14 +78,10 @@ impl SqlClient { self.object_job( ExecuteQueryRequest { query: format!( - "{} SECRET {} {}SECRET_STRING = $1", - if create { "CREATE" } else { "ALTER" }, + "{} {} {}SECRET_STRING = $1", + prefix, quote_identifier(name), - if create { - "TYPE = GENERIC_STRING " - } else { - "SET " - } + assignment ), default_namespace_path: namespace.to_vec(), parameters: Some(parameters), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index cfaf2a625..471966731 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3214,29 +3214,55 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { }; let exchanges = service.exchanges.clone(); let statements = service.statements.clone(); + let headers = service.headers.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|request| -> http::Response { panic!("unexpected REST request: {}", request.url().path()); }) .with_sql_client(client); - db.create_secret("api-key", "credential's value", &["team".into()]) + let connection = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + connection + .create_secret("api-key", "credential's value", &["team".into()]) .await .unwrap(); - db.alter_secret("api-key", "rotated-value", &["team".into()]) + connection + .create_secret("api-key", "ignored-value", &["team".into()]) + .exist_ok(true) + .await + .unwrap(); + connection + .alter_secret("api-key", "rotated-value", &["team".into()]) + .await + .unwrap(); + connection + .drop_secret("api-key", &["team".into()]) .await .unwrap(); - db.drop_secret("api-key", &["team".into()]).await.unwrap(); assert_eq!( statements.lock().unwrap().as_slice(), ["DROP SECRET IF EXISTS \"api-key\""] ); let seen = exchanges.lock().unwrap(); - assert_eq!(seen.len(), 2); + assert_eq!(seen.len(), 3); assert_eq!( seen[0].0, "CREATE SECRET \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" ); - assert_eq!(seen[1].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert_eq!( + seen[1].0, + "CREATE SECRET IF NOT EXISTS \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" + ); + assert_eq!(seen[2].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); assert_eq!( seen[0] .1 @@ -3259,6 +3285,18 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { .downcast_ref::() .unwrap() .value(0), + "ignored-value" + ); + assert_eq!( + seen[2] + .1 + .as_ref() + .unwrap() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), "rotated-value" ); shutdown.send(()).unwrap(); From a2a0d7f6322d64195243ff606de7924bcb08708b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:20:53 +0800 Subject: [PATCH 04/36] fix(ci): restore the unlocked Rust build cache once (#4997) `build-no-lock` restores Rust build outputs twice: toolchain setup enables its own cache by default before Cargo.lock removal, then the workflow restores an explicit cache afterward. Both restore into the same Cargo and target paths; the implicit action also allows PR cache saves. Disable only toolchain setup's implicit cache. The explicit restore remains after lock removal and retains its main-only save condition. This configuration is inherited unchanged by #4996. Its [failed job](https://github.com/lancedb/lancedb/actions/runs/43229196192/job/131220088196) reported runner ENOSPC while the second cache action was active, before dependency installation or Cargo. Earlier hosted logs confirm two restores into overlapping paths, but the failed job's full logs are unavailable, so the exact disk peak and ENOSPC cause remain unproven. A bounded probe using the resolved composite-action definitions verifies two restores before this change versus one afterward, preserves ordering and main-only saves, and confirms all other workflow configuration is unchanged. The [hosted run](https://github.com/lancedb/lancedb/actions/runs/43230840086/job/131225407007) confirms one successful 1.62 GB cache restore after lock removal and no PR cache save. It reached Cargo and linking without ENOSPC, but hit the inherited 30-minute deadline with the unchanged one-job driver. Free disk was 85 GiB before the build and 79 GiB at cancellation; these endpoint observations do not establish peak disk use or a general ENOSPC guarantee. The complementary two-job repair in #4996 now includes this prerequisite for combined hosted acceptance; this PR remains limited to cache ownership. --- .github/workflows/rust.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 9d28ac5e4..6d2bbf78d 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -154,6 +154,8 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: "stable" + # The explicit cache below runs after lock removal and only saves on main. + cache: false # Remove cargo.lock to force a fresh build - name: Remove Cargo.lock run: rm -f Cargo.lock From ec5e2cd621b605a5e362d81f7a13a449018b14e4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:21:31 +0800 Subject: [PATCH 05/36] ci: use two Cargo jobs for unlocked builds (#4996) Fresh unlocked workspace builds can exhaust the 30-minute CI job while Cargo is restricted to one compiler/linker task. Allow two concurrent tasks while retaining fresh dependency resolution, all workspace features and targets, the existing profile and timeout, and immediate cleanup of completed test executables. The single-cache prerequisite #4997 is included by a normal merge; merge it first under normal review gates. The final combined candidate passed hosted build-no-lock on head `8a3cda494f79a414101db392986cd18a64e5d80d` (tested merge `8d56029`, run [43236975778](https://github.com/lancedb/lancedb/actions/runs/43236975778/job/131247077833)). The build step took 18m42s and the full job 19m58s, within the unchanged 30-minute budget. Exactly one 1,624,797,998-byte cache restore completed; free disk samples before and after the build were 85 GiB and 79 GiB. These are endpoint samples, not peak RAM/disk measurements or a controlled speedup comparison. This job compiles and links targets but does not execute their tests. Temporary diagnostics are removed. The three existing driver tests pass, and the combined workflow and driver match their independently reviewed parents. --- ci/build_no_lock.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ci/build_no_lock.py b/ci/build_no_lock.py index 6ec156432..17d9ad333 100644 --- a/ci/build_no_lock.py +++ b/ci/build_no_lock.py @@ -54,6 +54,7 @@ def main() -> int: ["cargo", "metadata", "--format-version=1", "--no-deps", "--all-features"], stdout=subprocess.PIPE, text=True, + check=False, ) if metadata.returncode: return metadata.returncode @@ -68,7 +69,7 @@ def main() -> int: "--tests", # Bound simultaneous compiler/linker temporary outputs as well as retained files. "--jobs", - "1", + "2", "--message-format=json,json-diagnostic-rendered-ansi", ] cleanup_failed = False From b5623f88819120982731195b37f19b340eed1c02 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:22:21 +0800 Subject: [PATCH 06/36] ci: separate macOS Rust test phases (#4995) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit macOS doctests and library/integration tests currently share a 60-minute job budget. In #4967, compilation and doctests left only 3–4 minutes for an integration group that takes 6–7 minutes on the base revision, so the job was cancelled before it could finish. Run doctests and library/integration tests in separate matrix jobs on both macOS 15 and 26, each retaining the existing 60-minute limit. Preserve the library/integration check names, feature selection, locked dependencies and all existing coverage. This adds runner/build cost but removes the cumulative deadline coupling without reducing coverage. YAML parsing, shell syntax and matrix coverage checks pass. Hosted macOS execution and subsequent beta19 integration still need verification; this does not address the separate unlocked-build timeout. --- .github/workflows/rust.yml | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 6d2bbf78d..a5e5c9c30 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -297,10 +297,12 @@ jobs: run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests macos: + name: ${{ matrix.phase == 'tests' && format('macos ({0})', matrix.mac-runner) || format('macos-doc ({0})', matrix.mac-runner) }} timeout-minutes: 60 strategy: matrix: mac-runner: ["macos-15", "macos-26"] + phase: [tests, doc] runs-on: "${{ matrix.mac-runner }}" defaults: run: @@ -322,16 +324,17 @@ jobs: - name: Install dependencies run: brew install protobuf - name: Run tests + env: + CARGO_TEST_TARGETS: ${{ matrix.phase == 'doc' && '--doc' || '--lib --tests' }} run: | # Don't run the s3 integration tests since docker isn't available # on this image. ALL_FEATURES=`cargo metadata --format-version=1 --no-deps \ | jq -r '.packages[] | .features | keys | .[]' \ | grep -v s3-test | sort | uniq | paste -s -d "," -` - # Run doctests before test binaries fill the runner disk. Examples are - # already built by the Linux job, so avoid retaining them here. - cargo test --profile ci --features $ALL_FEATURES --locked --doc - cargo test --profile ci --features $ALL_FEATURES --locked --lib --tests + # Separate jobs give each phase its own time and disk budget. Examples + # are already built by the Linux job, so avoid retaining them here. + cargo test --profile ci --features $ALL_FEATURES --locked $CARGO_TEST_TARGETS windows: strategy: From b4d1c55f6228e9cf0a389fef07351aacfba09c01 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:22:35 +0800 Subject: [PATCH 07/36] test: isolate DynamoDB integration test databases (#4998) The concurrent-append and drop-all DynamoDB tests shared a database prefix. A timeout in the first could leave its table visible to the second. Give each test its own prefix while retaining five independent concurrent appends, the six-row assertion, and all drop/recreate checks. The final two-prefix diff passed both tests in hosted LocalStack across Node 22, 24, 26, and Node 24 experimental, without timing instrumentation ([run 43245851764](https://github.com/lancedb/lancedb/actions/runs/43245851764), head `5896c419`). Concurrency and the 5000 ms budget are unchanged. This fixes cascading fixture contamination; the original timeout remains unexplained, and these passing runs do not prove its root cause was fixed. --- nodejs/__test__/s3_integration.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nodejs/__test__/s3_integration.test.ts b/nodejs/__test__/s3_integration.test.ts index e4bc46806..35ce478a8 100644 --- a/nodejs/__test__/s3_integration.test.ts +++ b/nodejs/__test__/s3_integration.test.ts @@ -282,7 +282,7 @@ maybeDescribe("DynamoDB Lock", () => { }); it("can be used to configure a DynamoDB table for commit log", async () => { - const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`; + const uri = `s3+ddb://${bucket.name}/concurrent-appends?ddbTableName=${commitTable.name}`; const db = await connect(uri, { storageOptions: CONFIG, readConsistencyInterval: 0, @@ -307,7 +307,7 @@ maybeDescribe("DynamoDB Lock", () => { }); it("clears dynamodb state after dropping all tables", async () => { - const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`; + const uri = `s3+ddb://${bucket.name}/drop-all-tables?ddbTableName=${commitTable.name}`; const db = await connect(uri, { storageOptions: CONFIG, readConsistencyInterval: 0, From e61e21035c1f6f9b357510df5e88d0fa4c1be3f8 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 09:01:39 -0800 Subject: [PATCH 08/36] fix(python): explain Function namespace import restrictions (#4982) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plain `import ctypes.util` in a Function currently reports “dynamic namespace access” without explaining the module restriction or a way forward. Give blocked module imports a distinct error that names the modules, explains the reconstructed namespace constraint, and recommends an importable helper supplied through `code=`, `pip=`, or `conda=`. Dynamic namespace operations also get an actionable explanation. Document the full restrictions and the helper alternative in the decorator and Python Functions reference. Add regression coverage for direct imports, `from` imports, global module aliases, class Functions, the deprecated `@udf` alias, and helpers imported normally or shipped with `code=`. Existing import restrictions remain in place. For example, move `ctypes.util.find_library` into `native_diagnostics/__init__.py`, then use: ```python import native_diagnostics from lancedb import function @function(code=[native_diagnostics]) def probe_library(name: str) -> str: return native_diagnostics.find_library(name) ``` Fixes ENT-3408. --- docs/src/python/python.md | 45 +++++++ python/python/lancedb/functions.py | 63 ++++++--- .../tests/test_first_class_function_slice2.py | 7 +- .../python/tests/test_function_packaging.py | 120 ++++++++++++++++++ 4 files changed, 214 insertions(+), 21 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 8de5b5517..35f50c5a8 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -447,6 +447,51 @@ assert scaler(3.0) == 6.0 scaler.close() ``` +### Function packaging restrictions + +The decorator snapshots the Function's source and referenced globals into a new +module. It conservatively rejects imports of `sys`, `builtins`, `importlib`, +`inspect`, `gc`, `ctypes`, and `types`, including submodules such as `ctypes.util` +and `importlib.metadata`. This applies to imports inside function or class bodies +and references to module-level aliases. Even ordinary uses such as `sys.version` +and `ctypes.util.find_library` are blocked: these modules can reach names outside +the reconstructed Function namespace. References to `globals`, `locals`, `vars`, +`eval`, `exec`, `compile`, and `__import__` are rejected as dynamic namespace access. +These restrictions also apply to the deprecated `@udf` alias. + +For legitimate uses, move the code into an importable helper module and ship it +with `code=`, or install its package with `pip=` or `conda=`. Imported helpers keep +their own namespace; the packager does not scan their bodies. Helpers defined in +`__main__` are copied by source and have the same restrictions as the Function. + +For example, put this helper in `native_diagnostics/__init__.py`: + +```python +import ctypes.util + + +def find_library(name: str) -> str: + return ctypes.util.find_library(name) or "" +``` + +Then import the helper and include its source in the Function's artifact: + +```python +import native_diagnostics +from lancedb import function + + +@function(code=[native_diagnostics]) +def probe_library(name: str) -> str: + return native_diagnostics.find_library(name) +``` + +Captured literal globals support `None`, booleans, integers, strings, bytes, +finite floats, and tuples of these values. Construct other objects, including +PyArrow types and schemas, inside the Function or helper module instead. Values +used only in the decorator's `input_schema` or `output_schema` are not captured +globals and can be defined outside the Function. + Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or with `bytes` to materialize its contents before the Function runs. Reader inputs infer the Blob V2 type without an explicit input schema. Readers are diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index a5c741cd8..19d4171fb 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1570,10 +1570,23 @@ _NAMESPACE_MODULES = frozenset( ) -def _namespace_acquisition( - definition: ast.FunctionDef, references: set[str] -) -> list[str]: - found = set(references & _DYNAMIC_NAMESPACE_ACCESS) +_NAMESPACE_HELPER_HINT = ( + "Move this code into an importable helper module supplied with code=, pip=, " + "or conda=, then import and call the helper from the Function." +) + + +def _namespace_import_error(modules: Sequence[str]) -> ValueError: + return ValueError( + f"@function cannot package imports from namespace-access modules: {modules!r}. " + f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) " + "are blocked because they can access names outside the packaged " + "Function's reconstructed module namespace. " + _NAMESPACE_HELPER_HINT + ) + + +def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]: + found: set[str] = set() for node in ast.walk(definition): if isinstance(node, ast.Import): found.update( @@ -1883,11 +1896,17 @@ class _SourcePackager: ) source = ast.unparse(definition) references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n") - dynamic = _namespace_acquisition(definition, references) + dynamic = sorted(references & _DYNAMIC_NAMESPACE_ACCESS) if dynamic: raise ValueError( - f"@function cannot package dynamic namespace access: {dynamic!r}" + f"@function cannot package dynamic namespace access: {dynamic!r}. " + "These operations can access names outside the packaged " + "Function's reconstructed module namespace. Reference dependencies " + "explicitly. " + _NAMESPACE_HELPER_HINT ) + namespace_imports = _namespace_imports(definition) + if namespace_imports: + raise _namespace_import_error(namespace_imports) self._warn_unshipped_direct_imports(definition) self._packaged.add(id(target)) self._claim(target.__name__, ("definition", id(target))) @@ -1982,10 +2001,7 @@ class _SourcePackager: return f"from lance_blob import BlobReader as {name}" if isinstance(value, types.ModuleType): if value.__name__.split(".")[0] in _NAMESPACE_MODULES: - raise ValueError( - "@function cannot package dynamic namespace access: " - f"{value.__name__!r}" - ) + raise _namespace_import_error([value.__name__]) try: imported = importlib.import_module(value.__name__) except ImportError: @@ -2663,13 +2679,28 @@ def function( Other global values, including Arrow types and schemas, lists, dictionaries, sets, and NumPy arrays, cannot be captured as literals. Define them inside the function or class body instead. - Closures, lambdas, nested definitions, mutable module-level - objects, code that reaches the module namespace another way - (``globals()``/``eval``, ``sys.modules``, ``builtins``), and a + Closures, lambdas, nested definitions, mutable module-level objects, and a non-standard ``__builtins__`` are rejected where they can be seen and - otherwise unsupported. Changing any packaged source, including a module in - ``code``, produces a new Function version; the environment built from - ``pip`` or ``conda`` is reused. + otherwise unsupported. + + **Namespace restrictions.** The packaged source cannot import ``sys``, + ``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``, + including submodules such as ``ctypes.util`` and ``importlib.metadata``. + Referencing a module-level alias for one of these modules is also rejected. + References to ``globals``, ``locals``, ``vars``, ``eval``, ``exec``, + ``compile``, or ``__import__`` are rejected as dynamic namespace access. + These restrictions are conservative: even ordinary uses such as + ``ctypes.util.find_library`` or ``sys.version`` are blocked because these + modules can reach names outside the reconstructed Function namespace. + Move such code into an importable helper module supplied with ``code=``, + ``pip=``, or ``conda=``, then import and call the helper from the Function. + Helpers imported normally keep their own module namespace; these checks do + not scan their bodies. A helper defined in ``__main__`` is packaged by source + and is subject to the same checks. + + Changing any packaged source, including a module in ``code``, produces a + new Function version; the environment built from ``pip`` or ``conda`` is + reused. Parameters ---------- diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index d99a7aa21..97c0a5f3c 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -888,7 +888,7 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path): spec = importlib.util.spec_from_file_location("aliasing_udfs", module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) - with pytest.raises(ValueError, match="dynamic namespace access"): + with pytest.raises(ValueError, match="imports from namespace-access modules"): function(module.score) @@ -899,7 +899,6 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path): "eval('THRESHOLD')", "(lambda g: g()['THRESHOLD'])(globals)", "__import__('sys').modules[__name__].THRESHOLD", - "sys.modules[__name__].THRESHOLD", ], ) def test_function_rejects_dynamic_namespace_access(access): @@ -911,9 +910,7 @@ def test_function_rejects_dynamic_namespace_access(access): ) with pytest.raises(ValueError, match="dynamic namespace access"): _package_from_text( - "def score(value: int) -> int:\n" - " import sys\n" - f" return value + {access}\n" + f"def score(value: int) -> int:\n return value + {access}\n" ) diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 440adc4da..2e285aa33 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -466,6 +466,126 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): return value * factor +@pytest.mark.parametrize( + "module_name", + [ + "sys", + "builtins", + "importlib", + "inspect", + "gc", + "ctypes", + "types", + "ctypes.util", + "importlib.metadata", + ], +) +@pytest.mark.parametrize("import_style", ["import", "from", "global"]) +@pytest.mark.parametrize("class_function", [False, True]) +def test_namespace_module_errors_explain_the_rule_and_remedy( + helper_package, module_name, import_style, class_function +): + statement = f"import {module_name} as namespace_module" + body = f"{statement}\nreturn value\n" + preamble = "" + if import_style == "from": + body = f"from {module_name} import __name__\nreturn value\n" + elif import_style == "global": + preamble = statement + "\n" + body = "return str(namespace_module)\n" + if class_function: + definition = "class blocked:\n def __call__(self, value: str) -> str:\n" + source = preamble + definition + textwrap.indent(body, " ") + else: + definition = "def blocked(value: str) -> str:\n" + source = preamble + definition + textwrap.indent(body, " ") + module = helper_package("fx_namespace_import", {"__init__.py": source}) + + with pytest.raises(ValueError) as error: + function(module.blocked) + message = str(error.value) + assert "imports from namespace-access modules" in message + assert repr(module_name) in message + assert "builtins, ctypes, gc, importlib, inspect, sys, types" in message + assert "including submodules" in message + assert "reconstructed module namespace" in message + assert "importable helper module" in message + assert "code=, pip=, or conda=" in message + assert "dynamic namespace access" not in message + + +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +def test_udf_namespace_import_error_explains_the_helper_alternative(): + with pytest.raises(ValueError, match="ctypes.util.*importable helper module"): + + @udf + def probe(value: str) -> str: + import ctypes.util + + return str(ctypes.util.find_library(value)) + + +@pytest.mark.parametrize( + "operation", ["globals", "locals", "vars", "eval", "exec", "compile", "__import__"] +) +def test_dynamic_namespace_errors_name_the_operation_and_remedy( + helper_package, operation +): + module = helper_package( + "fx_namespace_operation", + { + "__init__.py": ( + f"def blocked(value: str) -> str:\n return str({operation})\n" + ) + }, + ) + with pytest.raises(ValueError) as error: + function(module.blocked) + message = str(error.value) + assert f"dynamic namespace access: ['{operation}']" in message + assert "Reference dependencies explicitly" in message + assert "importable helper module" in message + + +@pytest.mark.parametrize("ship_source", [False, True]) +def test_namespace_access_in_importable_helpers_keeps_its_module_namespace( + helper_package, ship_source +): + helpers = helper_package( + "fx_namespace_helper", + { + "__init__.py": """ + import ctypes.util + + def module_name(): + return ctypes.util.__name__ + """, + }, + ) + entry = helper_package( + "fx_namespace_entry", + { + "__init__.py": """ + from fx_namespace_helper import module_name + + def probe(value: str) -> str: + return module_name() + value + """, + }, + ) + options = {"code": [helpers]} if ship_source else {"pip": ["fx-namespace-helper"]} + definition = function(**options)(entry.probe) + if ship_source: + files = bundle_files(definition) + assert "import ctypes.util" in files["fx_namespace_helper/__init__.py"] + source = files["user_function.py"] + else: + source = artifact(definition).decode() + namespace = {} + exec(compile(source, "user_function.py", "exec"), namespace) + assert namespace["probe"]("!") == "ctypes.util!" + + def test_binding_passes_initialization_as_constants(): version = FunctionVersion.from_json( json.dumps( From 8939ef1f016b78e26dd41a77886edd6b83710e7a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:04:32 +0800 Subject: [PATCH 09/36] feat(python): warn on scalar GPU Functions (#4966) GPU Functions that use a scalar callable currently invoke the callable once per row. The SDK documents Arrow-vectorized callables, but silently accepts a scalar GPU callable, which makes it easy to assume that the runtime will batch model work automatically. Warn during Function construction when a GPU callable does not use the documented vectorized form. A callable is recognized as vectorized when every input is annotated as `pyarrow.Array`, or when a single input is annotated as `pyarrow.RecordBatch`. The warning explains the resulting per-row invocation and shows how to opt into batch execution. CPU Functions and the vectorized GPU forms do not emit it. The warning is advisory and does not change registration serialization, the artifact, the runtime adapter, or execution behavior. It is one part of the ENT-3522 documentation-and-warning alternative; it does not claim that a single A10G meets the original batch throughput requirement. Validation on the designated EC2 host reused the compatible existing native extension from `ent3563-sdk-freshness-9336cfb`; this does not claim a new native package or GPU performance run. The final head has a clean source tree and ran: ```bash PYTHONPATH="$sdk/python/python" /home/ec2-user/.venvs/ent3563-0a839fa/bin/python -m pytest -q python/python/tests/test_first_class_function_slice2.py -k 'gpu_marker_uses_gpu_runtime or gpu_scalar_warning_names_the_vectorized_alternative' /home/ec2-user/.venvs/ent3563-0a839fa/bin/ruff format --check python/python/lancedb/functions.py python/python/tests/test_first_class_function_slice2.py /home/ec2-user/.venvs/ent3563-0a839fa/bin/ruff check python/python/lancedb/functions.py python/python/tests/test_first_class_function_slice2.py ``` The actual result was `2 passed, 123 deselected`; both Ruff commands passed. The original 2,000-row single-A10G throughput requirement remains a separate ENT-3522 acceptance gate. --- python/python/lancedb/functions.py | 27 +++++++- .../tests/test_first_class_function_slice2.py | 63 ++++++++++++++++++- 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 19d4171fb..92be658a8 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1529,6 +1529,17 @@ def _infer_signature( return FunctionSignature(inputs=tuple(inputs), output=output) +def _is_vectorized_callable(function: Callable[..., Any], *, method: bool) -> bool: + parameters = _callable_parameters(function) + if method: + parameters = parameters[1:] + annotations = get_type_hints(function, include_extras=True) + annotated = tuple(annotations.get(parameter.name) for parameter in parameters) + return (len(annotated) == 1 and annotated[0] is pa.RecordBatch) or ( + bool(annotated) and all(annotation is pa.Array for annotation in annotated) + ) + + # Both spellings strip from packaged source; `udf` is the deprecated alias. _DECORATOR_NAMES = frozenset({"function", "udf"}) @@ -2302,7 +2313,9 @@ class FunctionDefinition: once per row. A callable whose parameters are all annotated as ``pyarrow.Array`` receives whole Arrow arrays and returns a ``pyarrow.Array`` instead. This authoring choice is independent of the - internal artifact adapter in the registration request. + internal artifact adapter in the registration request. GPU Functions should + use the Arrow form when the model supports batches: a scalar GPU callable is + invoked once per row and leaves the model's own batching unavailable. """ def __init__( @@ -2424,6 +2437,18 @@ class FunctionDefinition: signature = signature._copy(update={"initialization": initialization}) else: signature = _infer_signature(function, input_schema, output_schema) + if gpu_marker is not None: + call = _class_call(function) if is_class else function + if not _is_vectorized_callable(call, method=is_class): + warnings.warn( + f"GPU Function {function_name!r} uses a scalar callable, so each " + "row invokes it separately and its model batch is not inferred. " + "For GPU throughput, annotate every input as pyarrow.Array or " + "take one pyarrow.RecordBatch, provide input_schema and " + "output_schema, and batch inside that callable.", + UserWarning, + stacklevel=3, + ) code_files, code_modules = _code_files(code) entry_source = _SourcePackager( code_modules, frozenset(_requirement_name(package) for package in packages) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 97c0a5f3c..a3a9e3e20 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -18,6 +18,7 @@ import subprocess import sys import typing import urllib.parse +import warnings from typing import Optional import pyarrow as pa @@ -658,9 +659,11 @@ def test_function_image_requires_digest_reference(image): def test_function_gpu_marker_uses_gpu_runtime(): - @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") - def double_on_gpu(value: int) -> int: - return value * 2 + with pytest.warns(UserWarning, match="uses a scalar callable"): + + @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") + def double_on_gpu(value: int) -> int: + return value * 2 request = json.loads(double_on_gpu.registration_request.to_canonical_json()) assert request["runtime"]["kind"] == "python_v2" @@ -710,6 +713,60 @@ def test_function_gpu_marker_uses_gpu_runtime(): ) +class _GpuScalarFunction: + def __call__(self, value: str) -> int: + return len(value) + + +class _GpuArrayFunction: + def __call__(self, value: pa.Array) -> pa.Array: + return value + + +def test_gpu_scalar_warning_names_the_vectorized_alternative(): + with pytest.warns(UserWarning, match="model batch is not inferred"): + + @function(gpu=True) + def scalar_embedding(value: str) -> list[int]: + return [len(value)] + + input_schema = pa.schema([pa.field("value", pa.string(), nullable=False)]) + with pytest.warns(UserWarning, match="uses a scalar callable"): + class_scalar = function(_GpuScalarFunction, gpu=True) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + + @function( + gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64()) + ) + def array_embedding(value: pa.Array) -> pa.Array: + return value + + @function( + gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64()) + ) + def record_batch_embedding(value: pa.RecordBatch) -> pa.Array: + return value.column(0) + + @function + def cpu_scalar(value: str) -> int: + return len(value) + + class_embedding = function( + _GpuArrayFunction, + gpu=True, + input_schema=input_schema, + output_schema=pa.list_(pa.int64()), + ) + + assert not caught + assert array_embedding.registration_request.batch_size is None + assert record_batch_embedding.registration_request.batch_size is None + assert cpu_scalar.registration_request.batch_size is None + assert class_scalar.registration_request.batch_size is None + assert class_embedding.registration_request.batch_size is None + + def test_unknown_runtime_discards_payload_before_known_field_validation(): for payload in [ { From 10f89b3c32577bf054774b5c74346ba24ee79576 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:09 +0800 Subject: [PATCH 10/36] perf: reduce Blob read buffering and expose read window controls (#4979) Remote Blob reads retain and concatenate intermediate IPC buffers across batches and HTTP requests, increasing peak memory. Decode fragmented IPC bodies using their declared length, assemble Blob values once across batches/requests, and collect large-object Range responses into known-size buffers. Impossible IPC/Range allocations return errors instead of panicking. Closing a remote Blob file releases cached bytes immediately, including while a cross-window read is waiting for the network. Rust and Python expose configurable Blob read buffers. Python sync/async `fetch_blob_files` and `open_blob_file(s)` accept `buffer_size`; the default is 512 KiB and zero disables prefetch. Explicit ranges bypass prefetch. New PE batch-endpoint adoption is separate. Malformed-length and retained-cache regressions fail on the previous implementation and pass after the correction. Real HTTP tests cover buffer propagation, close during blocked input, batch/request aggregation, and large-object fallback. The final extension was rebuilt before Python validation. Non-Blob Arrow arrays may still require alignment copies; a contiguous multi-batch result still requires its final allocation. ## Benchmark Peak client RSS increment in KiB, using `python/benchmarks/bench_fetch_blobs_rss.py`, independent clients and real loopback HTTP. Both extensions were rebuilt from clean, unchanged source with the same toolchain/configuration; loaded artifact hashes were checked. Baseline `42f11d13a2755e44b63876b5a5edd93901291150`, after `0a8a76de5286949d80368f95a5c529adf422c187`. | Equivalent fetch workload | Payload | Before | After | | --- | ---: | ---: | ---: | | Single response, one batch | 48 MiB | 63,812 | 63,896 | | Multiple responses, one batch per response | 144 MiB | 423,104 | 195,628 | | Single response, 12 rows per batch | 48 MiB | 130,520 | 71,348 | | Multiple responses, 12 rows per batch | 144 MiB | 363,144 | 172,748 | | One oversized row, Range fallback | 70 MiB | 182,816 | 85,548 | These are one observation per workload and build, not a statistical distribution or memory upper bound. The single-batch workload shows no improvement. Cloud/Sophon deployment, credentialed S3 and long-running stress have not been exercised. --- docs/src/python/python.md | 9 + python/benchmarks/bench_fetch_blobs_rss.py | 183 ++++++++ python/python/lancedb/_blob.py | 19 + python/python/lancedb/_lancedb.pyi | 7 +- python/python/lancedb/remote/table.py | 13 +- python/python/lancedb/table.py | 56 ++- python/python/tests/test_blob_buffering.py | 236 ++++++++++ python/src/table.rs | 27 +- rust/lancedb/src/blob.rs | 24 + rust/lancedb/src/remote/table/blobs.rs | 424 +++++++++++++++--- .../src/remote/table/blobs/aggregate.rs | 121 +++++ rust/lancedb/src/remote/table/ipc_stream.rs | 123 ++++- .../src/remote/table/ipc_stream/framing.rs | 172 +++++++ 13 files changed, 1326 insertions(+), 88 deletions(-) create mode 100644 python/benchmarks/bench_fetch_blobs_rss.py create mode 100644 python/python/tests/test_blob_buffering.py create mode 100644 rust/lancedb/src/remote/table/blobs/aggregate.rs create mode 100644 rust/lancedb/src/remote/table/ipc_stream/framing.rs diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 35f50c5a8..0e7164c1a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -793,6 +793,15 @@ with `search().with_row_id(True).to_arrow()` and pass the result to the fetch AP One missing or deleted row ID rejects the entire blob-read batch; the APIs do not return partial results. +Local and remote `BlobFile` handles prefetch 512 KiB for sequential reads by +default. Pass `buffer_size=0` to `fetch_blob_files`, `open_blob_file`, or +`open_blob_files` for sparse reads, or choose another window size in bytes. +Call `file.set_buffer_size(size)` to change it without moving the cursor; +changing the size discards unused prefetched bytes. Explicit `read_range` and +`read_ranges` calls always read exactly the requested intervals and leave the +cursor unchanged. Remote prefetch consumes the HTTP response completely before +returning, so idle handles do not hold request concurrency slots or connections. + To construct inline Blob V2 arrays for ingestion in record batches, use [blob_array][lancedb.schema.blob_array]. It accepts bytes and `None`, preserving the distinction between an empty blob (`b""`) and a null blob: diff --git a/python/benchmarks/bench_fetch_blobs_rss.py b/python/benchmarks/bench_fetch_blobs_rss.py new file mode 100644 index 000000000..8281490f0 --- /dev/null +++ b/python/benchmarks/bench_fetch_blobs_rss.py @@ -0,0 +1,183 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Measure fetch_blobs RSS in a fresh client process against real HTTP. + +Run with the uv environment's Python. The server lives in a separate process so +payload generation and Arrow serialization are excluded from the client's RSS. +Each row contains 1 MiB; requests over the server's 64 MiB limit are split by the +SDK. Example: python benchmarks/bench_fetch_blobs_rss.py --rows 48 144 +""" + +import argparse +import json +import resource +import subprocess +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +def serve(batch_rows, row_mib): + import pyarrow as pa + + payload = b"x" * (row_mib << 20) + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def respond(self, status, data, content_type="application/json"): + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.send_header("phalanx-version", "0.5.0") + self.send_header("x-lancedb-version", "1") + self.end_headers() + for offset in range(0, len(data), 8192): + self.wfile.write(data[offset : offset + 8192]) + + def do_POST(self): + length = int(self.headers.get("Content-Length", 0)) + request_body = self.rfile.read(length) + if self.path.endswith("/describe/"): + self.do_GET() + return + body = json.loads(request_body) + count = len(body["row_ids"]) + if count * row_mib > 64: + self.respond( + 400, + b"fetch_blobs accepts at most 67108864 total blob bytes", + ) + return + schema = pa.schema([pa.field("image", pa.large_binary())]) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, schema) as writer: + for start in range(0, count, batch_rows): + array = pa.array( + [payload] * min(batch_rows, count - start), + type=pa.large_binary(), + ) + writer.write_batch(pa.record_batch([array], schema=schema)) + self.respond(200, sink.getvalue(), "application/vnd.apache.arrow.stream") + + def do_GET(self): + if "/blob/image/" in self.path: + start, end = map(int, self.headers["Range"][6:].split("-")) + body = memoryview(payload)[start : end + 1] + self.send_response(206) + self.send_header("Content-Length", str(len(body))) + self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}") + self.send_header("x-lancedb-version", "1") + self.end_headers() + for offset in range(0, len(body), 8192): + self.wfile.write(body[offset : offset + 8192]) + return + self.respond( + 200, + json.dumps( + { + "table": "test", + "version": 1, + "schema": {"fields": []}, + } + ).encode(), + ) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + print(server.server_port, flush=True) + server.serve_forever() + + +def client(port, rows, row_mib): + import lancedb + + db = lancedb.connect( + "db://rss-test", api_key="test", host_override=f"http://127.0.0.1:{port}" + ) + table = db.open_table("test") + # Reset the Linux high-water mark after imports and connection setup. + with open("/proc/self/clear_refs", "w") as reset: + reset.write("5") + + def memory_kib(field): + with open("/proc/self/status") as status: + return next( + int(line.split()[1]) for line in status if line.startswith(field + ":") + ) + + before = memory_kib("VmRSS") + values = table.fetch_blobs("image", list(range(rows))) + peak = memory_kib("VmHWM") + assert len(values) == rows + assert values.buffers()[2].size == rows * (row_mib << 20) + # Inspect slices without copying the result to Python bytes. + for i in (0, rows - 1): + assert values.slice(i, 1).buffers()[2][i * (row_mib << 20)] == ord("x") + print( + json.dumps( + { + "rows": rows, + "payload_mib": rows * row_mib, + "baseline_rss_kib": before, + "peak_rss_kib": peak, + "peak_delta_kib": peak - before, + "peak_delta_per_payload": (peak - before) / (rows * row_mib * 1024), + "rusage_maxrss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--rows", nargs="+", type=int, default=[48, 144]) + parser.add_argument("--batch-rows", type=int, default=48) + parser.add_argument("--row-mib", type=int, default=1) + parser.add_argument("--serve", action="store_true") + parser.add_argument("--client", type=int) + args = parser.parse_args() + if args.serve: + serve(args.batch_rows, args.row_mib) + elif args.client is not None: + client(args.client, args.rows[0], args.row_mib) + else: + server = subprocess.Popen( + [ + sys.executable, + __file__, + "--serve", + "--batch-rows", + str(args.batch_rows), + "--row-mib", + str(args.row_mib), + ], + stdout=subprocess.PIPE, + text=True, + ) + try: + port = server.stdout.readline().strip() + for rows in args.rows: + subprocess.run( + [ + sys.executable, + __file__, + "--client", + port, + "--rows", + str(rows), + "--row-mib", + str(args.row_mib), + ], + check=True, + ) + finally: + server.terminate() + server.wait() + + +if __name__ == "__main__": + main() diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 2c545a17e..fc1925ca6 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -35,6 +35,15 @@ FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray] FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]] +def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]: + if size is None: + return None + size = operator.index(size) + if size < 0: + raise ValueError("buffer_size must be non-negative") + return size + + def _normalize_blob_descriptor(value): if isinstance(value, pa.Scalar): value = value.as_py() @@ -58,6 +67,16 @@ class BlobFile(io.RawIOBase): def __init__(self, inner) -> None: self._inner = inner + def set_buffer_size(self, size: int) -> None: + """Set sequential read-ahead bytes (default 512 KiB); 0 disables it. + + Changing the size discards unused prefetched bytes without moving the + cursor. Explicit ``read_range`` and ``read_ranges`` bypass read-ahead. + """ + if self.closed: + raise ValueError("set_buffer_size of closed file") + self._inner.set_buffer_size(_validate_blob_buffer_size(size)) + async def aread(self) -> bytes: if self.closed: raise ValueError("read of closed file") diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a64014cb7..4f1da9ba7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -397,6 +397,7 @@ class BlobFile: def seek(self, position: int) -> None: ... def tell(self) -> int: ... def size(self) -> int: ... + def set_buffer_size(self, size: int) -> None: ... def read_range(self, offset: int, length: int) -> bytes: ... def read_ranges(self, ranges: list[tuple[int, int]]) -> list[bytes]: ... def read_up_to(self, length: int) -> bytes: ... @@ -755,9 +756,11 @@ class Table: requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: ... async def fetch_blob_files( - self, column: str, row_ids: list[int] + self, column: str, row_ids: list[int], buffer_size: Optional[int] = None ) -> list[Optional[BlobFile]]: ... - async def open_blob_file(self, descriptor: str) -> BlobFile: ... + async def open_blob_file( + self, descriptor: str, buffer_size: Optional[int] = None + ) -> BlobFile: ... def vector_search(self) -> VectorQuery: ... class Tags: diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 3f6bff45e..21749a0a7 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1420,13 +1420,20 @@ class RemoteTable(Table): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": - return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + return LOOP.run( + self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size) + ) def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: - return LOOP.run(self._table.open_blob_file(descriptor)) + return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size)) def head(self, n=5) -> pa.Table: """ diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 762f826c2..424b4b64c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -40,6 +40,7 @@ from ._blob import ( BlobFile, _normalize_blob_descriptor, _normalize_blob_row_ids, + _validate_blob_buffer_size, _wrap_blob_files, strip_auto_row_ids, validate_blob_mode, @@ -2664,6 +2665,8 @@ class Table(ABC): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": """Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles. @@ -2673,6 +2676,8 @@ class Table(ABC): ``pyarrow.Table`` carrying row identity via ``_rowid`` or a ``_lance_row_id`` field on the blob descriptor. Null blob values return ``None``. LanceDB Enterprise requires server version 0.5.0 or newer. + ``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB). + Set it to 0 for sparse reads. Explicit range reads bypass this buffer. ``_rowid`` values stay valid after compaction when the table has stable row ids. @@ -2682,7 +2687,10 @@ class Table(ABC): @abstractmethod def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: """Open a seekable file from a SQL ``blob_descriptor`` result. @@ -2691,6 +2699,7 @@ class Table(ABC): not change this table's checkout. Null descriptors return ``None``. Payload bytes load only when the returned handle is read. An external blob with an unspecified size may require a metadata request on opening. + ``buffer_size`` controls sequential read-ahead (default 512 KiB; 0 disables). ```python rows = db.execute_query( @@ -2701,7 +2710,9 @@ class Table(ABC): ``` """ - def open_blob_files(self, descriptors: Iterable) -> Iterator[Optional[BlobFile]]: + def open_blob_files( + self, descriptors: Iterable, *, buffer_size: Optional[int] = None + ) -> Iterator[Optional[BlobFile]]: """Iterate over lazy files from descriptor dictionaries or Arrow scalars. Accepts an Arrow array/chunked array or any iterable. Opens each handle @@ -2716,7 +2727,10 @@ class Table(ABC): ``` """ for descriptor in descriptors: - yield self.open_blob_file(descriptor) + if buffer_size is None: + yield self.open_blob_file(descriptor) + else: + yield self.open_blob_file(descriptor, buffer_size=buffer_size) @abstractmethod def _execute_query( @@ -3998,13 +4012,20 @@ class LanceTable(Table): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": - return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + return LOOP.run( + self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size) + ) def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: - return LOOP.run(self._table.open_blob_file(descriptor)) + return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size)) @property def tags(self) -> Tags: @@ -8620,26 +8641,39 @@ class AsyncTable: self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": + """Open handles with configurable read-ahead. + + See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files]. + """ + buffer_size = _validate_blob_buffer_size(buffer_size) handles = await self._inner.fetch_blob_files( - column, _normalize_blob_row_ids(row_ids, column) + column, _normalize_blob_row_ids(row_ids, column), buffer_size ) return _wrap_blob_files(handles) async def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: """Open a snapshot-bound descriptor as a seekable file. See [Table.open_blob_file][lancedb.table.Table.open_blob_file]. """ + buffer_size = _validate_blob_buffer_size(buffer_size) descriptor = _normalize_blob_descriptor(descriptor) if descriptor is None: return None - return BlobFile(await self._inner.open_blob_file(json.dumps(descriptor))) + return BlobFile( + await self._inner.open_blob_file(json.dumps(descriptor), buffer_size) + ) async def open_blob_files( - self, descriptors: Iterable + self, descriptors: Iterable, *, buffer_size: Optional[int] = None ) -> AsyncIterator[Optional[BlobFile]]: """Asynchronously iterate over files in descriptor order, preserving nulls. @@ -8654,7 +8688,7 @@ class AsyncTable: ``` """ for descriptor in descriptors: - yield await self.open_blob_file(descriptor) + yield await self.open_blob_file(descriptor, buffer_size=buffer_size) @property def tags(self) -> AsyncTags: diff --git a/python/python/tests/test_blob_buffering.py b/python/python/tests/test_blob_buffering.py new file mode 100644 index 000000000..09fbfb862 --- /dev/null +++ b/python/python/tests/test_blob_buffering.py @@ -0,0 +1,236 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +import threading +from contextlib import contextmanager +from urllib.parse import urlparse + +import pyarrow as pa +import pytest + +import lancedb +from test_remote_db import ( + BLOB_DESCRIBE_RESPONSE, + blob_descriptor_take_table, + mock_lancedb_connection, +) + + +@contextmanager +def remote_buffer_table(*, http_requests=None, truncate_first=False): + payload = bytes(range(256)) * 4096 + requests = [] + + def handler(request): + path = urlparse(request.path).path + if http_requests is not None: + http_requests.append(path) + if path.endswith("/describe/"): + body = json.dumps(BLOB_DESCRIBE_RESPONSE).encode() + content_type = "application/json" + elif path.endswith("/query/"): + data = json.loads( + request.rfile.read(int(request.headers["Content-Length"])) + ) + assert data["columns"] == ["image"] + table = blob_descriptor_take_table().slice(0, 1) + images = table["image"].combine_chunks() + images = pa.StructArray.from_arrays( + [ + images.field("kind"), + images.field("position"), + pa.array([len(payload)], pa.uint64()), + images.field("blob_id"), + images.field("blob_uri"), + ], + fields=list(images.type), + ) + table = table.set_column(0, table.schema.field(0), images) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, table.schema) as writer: + writer.write_table(table) + body = sink.getvalue().to_pybytes() + content_type = "application/vnd.apache.arrow.stream" + else: + assert path == "/v1/table/test/blob/image/10/bytes" + assert "version=1" in request.path + start, end = map(int, request.headers["Range"][6:].split("-")) + requests.append((start, end + 1)) + body = payload[start : end + 1] + if truncate_first and len(requests) == 1: + body = body[:5] + request.send_response(206) + request.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}") + request.send_header("Content-Length", str(len(body))) + request.end_headers() + request.wfile.write(body) + return + request.send_response(200) + request.send_header("Content-Type", content_type) + request.send_header("Content-Length", str(len(body))) + request.send_header("phalanx-version", "0.5.0") + request.send_header("x-lancedb-version", "1") + request.end_headers() + request.wfile.write(body) + + with mock_lancedb_connection(handler, blob_request_concurrency=1) as db: + yield db.open_table("test"), payload, requests + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("buffer_size", [None, 0, 8, 512 * 1024]) +async def test_remote_read_ahead_over_http(use_async, buffer_size): + with remote_buffer_table() as (table, payload, requests): + if use_async: + files = await table._table.fetch_blob_files( + "image", [10], buffer_size=buffer_size + ) + else: + files = table.fetch_blob_files("image", [10], buffer_size=buffer_size) + file = files[0] + assert requests == [] + assert file.read(2) == payload[:2] + window = 512 * 1024 if buffer_size is None else max(buffer_size, 2) + assert requests == [(0, window)] + assert file.read(2) == payload[2:4] + assert len(requests) == (2 if buffer_size == 0 else 1) + file.seek(1) + assert file.read(1) == payload[1:2] + assert len(requests) == (3 if buffer_size == 0 else 1) + before = len(requests) + assert file.read_range(0, 1) == payload[:1] + assert len(requests) == before + 1 + assert requests[-1] == (0, 1) + assert file.tell() == 2 + file.set_buffer_size(0) + assert file.read(1) == payload[2:3] + assert requests[-1] == (2, 3) + file.set_buffer_size(16) + assert file.read(1) == payload[3:4] + assert requests[-1] == (3, 19) + file.seek(len(payload) - 1) + assert file.read(4) == payload[-1:] + assert requests[-1] == (len(payload) - 1, len(payload)) + before = len(requests) + assert file.read(1) == b"" + assert len(requests) == before + file.close() + with pytest.raises(ValueError, match="closed"): + file.set_buffer_size(0) + + +def test_short_prefetch_over_http_preserves_cursor(): + with remote_buffer_table(truncate_first=True) as (table, payload, requests): + file = table.fetch_blob_files("image", [10], buffer_size=8)[0] + with pytest.raises(RuntimeError, match="returned 5 bytes, expected 8"): + file.read(6) + assert file.tell() == 0 + assert file.read(3) == payload[:3] + assert file.tell() == 3 + assert requests == [(0, 8), (0, 8)] + file.close() + + +def test_idle_prefetch_releases_http_concurrency_slot(): + with remote_buffer_table() as (table, payload, requests): + first, second = table.fetch_blob_files("image", [10, 10]) + assert first.read(1) == payload[:1] + results = [] + errors = [] + + def read_other(): + try: + results.append(second.read(1)) + except Exception as error: + errors.append(error) + + reader = threading.Thread(target=read_other, daemon=True) + reader.start() + reader.join(timeout=2) + completed_while_first_idle = not reader.is_alive() + first.close() + reader.join(timeout=2) + second.close() + assert completed_while_first_idle, ( + "idle prefetch retained the HTTP request slot" + ) + assert not errors + assert results == [payload[:1]] + assert requests == [(0, 512 * 1024), (0, 512 * 1024)] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_local_buffer_configuration_through_python(tmp_path, use_async): + db = lancedb.connect(tmp_path) + table = db.create_table( + "blobs", [{"image": b"0123456789"}], schema=pa.schema([lancedb.blob("image")]) + ) + row_ids = table.search().with_row_id(True).to_arrow()["_rowid"] + if use_async: + files = await table._table.fetch_blob_files("image", row_ids, buffer_size=0) + else: + files = table.fetch_blob_files("image", row_ids, buffer_size=0) + file = files[0] + assert file.read(2) == b"01" + file.set_buffer_size(4) + assert file.read(2) == b"23" + file.seek(1) + assert file.read(3) == b"123" + assert file.read_range(8, 2) == b"89" + with pytest.raises(ValueError, match="non-negative"): + file.set_buffer_size(-1) + with pytest.raises(TypeError): + file.set_buffer_size(1.5) + file.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_open_descriptor_files_forward_buffer_size(use_async): + with remote_buffer_table() as (table, payload, requests): + descriptor = { + "kind": 1, + "position": 0, + "size": len(payload), + "blob_id": 0, + "blob_uri": "", + "source": { + "uri": "s3://bucket/test.lance", + "version": 1, + "committed_at_micros": 1, + "column": "image", + "row_reference": 10, + "row_is_address": False, + }, + } + if use_async: + files = [ + file + async for file in table._table.open_blob_files( + [None, descriptor], buffer_size=8 + ) + ] + else: + files = list(table.open_blob_files([None, descriptor], buffer_size=8)) + assert files[0] is None + assert files[1].read(1) == payload[:1] + assert requests == [(0, 8)] + files[1].close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_invalid_buffer_size_rejects_before_http(use_async): + http_requests = [] + with remote_buffer_table(http_requests=http_requests) as (table, _, requests): + http_requests.clear() + with pytest.raises(ValueError, match="non-negative"): + if use_async: + await table._table.fetch_blob_files("image", [10], buffer_size=-1) + else: + table.fetch_blob_files("image", [10], buffer_size=-1) + assert requests == [] + assert http_requests == [] diff --git a/python/src/table.rs b/python/src/table.rs index c4211e44d..62c2ee765 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1243,6 +1243,15 @@ impl PyBlobFile { .map_err(|e| blob_file_error("tell", e)) } + fn set_buffer_size(self_: PyRef<'_, Self>, size: usize) -> PyResult<()> { + self_.ensure_open()?; + let inner = self_.inner.clone(); + self_ + .py() + .detach(move || block_on(async move { inner.set_buffer_size(size).await })) + .map_err(|e| blob_file_error("set_buffer_size", e)) + } + fn size(self_: PyRef<'_, Self>) -> u64 { self_.inner.size() } @@ -2019,11 +2028,12 @@ impl Table { } /// Open lazy blob handles for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids))] + #[pyo3(signature = (column, row_ids, buffer_size=None))] pub fn fetch_blob_files( self_: PyRef<'_, Self>, column: String, row_ids: Vec, + buffer_size: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2031,6 +2041,13 @@ impl Table { .fetch_blob_files(column.as_str(), &row_ids) .await .infer_error()?; + if let Some(size) = buffer_size { + for file in handles.iter().flatten() { + file.set_buffer_size(size) + .await + .map_err(|e| blob_file_error("set_buffer_size", e))?; + } + } Ok(handles .into_iter() .map(|handle| { @@ -2043,16 +2060,22 @@ impl Table { }) } - #[pyo3(signature = (descriptor))] + #[pyo3(signature = (descriptor, buffer_size=None))] pub fn open_blob_file<'py>( self_: PyRef<'py, Self>, descriptor: &str, + buffer_size: Option, ) -> PyResult> { let descriptor: BlobDescriptor = serde_json::from_str(descriptor) .map_err(|error| PyValueError::new_err(format!("invalid blob descriptor: {error}")))?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let file = inner.open_blob_file(&descriptor).await.infer_error()?; + if let Some(size) = buffer_size { + file.set_buffer_size(size) + .await + .map_err(|e| blob_file_error("set_buffer_size", e))?; + } Ok(PyBlobFile { inner: Arc::new(file), closed: AtomicBool::new(false), diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index a8a816fdd..ead1f2410 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -204,6 +204,30 @@ impl BlobFile { lance::dataset::BlobFile::new_external(object_store, path, uri, position, size).into() } + /// Default sequential read-ahead window, in bytes. + pub const DEFAULT_READ_BUFFER_SIZE: usize = 512 * 1024; + + /// Set sequential read-ahead bytes. `0` disables read-ahead. + /// + /// Changing the size discards unused prefetched bytes without moving the + /// cursor. [`Self::read_range`] and [`Self::read_ranges`] bypass read-ahead. + /// The default is [`Self::DEFAULT_READ_BUFFER_SIZE`]. + /// + /// ``` + /// # async fn sparse_read(file: &lancedb::blob::BlobFile) -> lance_core::Result<()> { + /// file.set_buffer_size(0).await?; + /// let header = file.read_up_to(16).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn set_buffer_size(&self, size: usize) -> lance_core::Result<()> { + match &self.inner { + BlobFileInner::Native(file) => file.set_buffer_size(size).await, + #[cfg(feature = "remote")] + BlobFileInner::Remote(file) => file.set_buffer_size(size).await, + } + } + /// Close the handle. pub async fn close(&self) -> lance_core::Result<()> { match &self.inner { diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 65ab13935..345b731c5 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -3,6 +3,11 @@ //! Cloud blob column listing, whole-byte fetch, and seekable HTTP byte-range handles. +mod aggregate; + +use aggregate::BlobAccumulator; +use arrow_buffer::{Buffer, OffsetBuffer}; + use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; @@ -159,9 +164,25 @@ impl BlobRangeRequester for TableBlobRangeRequester { } } -#[derive(Debug, Default)] +#[derive(Debug)] struct RemoteBlobState { cursor: u64, + buffer_size: usize, +} + +impl Default for RemoteBlobState { + fn default() -> Self { + Self { + cursor: 0, + buffer_size: BlobFile::DEFAULT_READ_BUFFER_SIZE, + } + } +} + +#[derive(Debug, Default)] +struct RemoteBlobBuffer { + start: u64, + bytes: Bytes, } /// Seekable Cloud blob handle over HTTP Range. @@ -171,6 +192,9 @@ struct RemoteBlobState { pub struct RemoteBlobFile { requester: Arc, state: Mutex, + // Never held across I/O: close can release cached bytes even while a read + // holds the cursor lock. A reader may retain its own prefix until it ends. + buffer: std::sync::Mutex, closed: AtomicBool, size: u64, version: Option, @@ -181,6 +205,7 @@ impl RemoteBlobFile { Self { requester, state: Mutex::new(RemoteBlobState::default()), + buffer: std::sync::Mutex::new(RemoteBlobBuffer::default()), closed: AtomicBool::new(false), size, version, @@ -190,6 +215,18 @@ impl RemoteBlobFile { /// Close the handle without waiting for an in-flight read. pub(crate) async fn close(&self) -> lance_core::Result<()> { self.closed.store(true, Ordering::Release); + self.buffer.lock().unwrap().bytes = Bytes::new(); + Ok(()) + } + + pub(crate) async fn set_buffer_size(&self, size: usize) -> lance_core::Result<()> { + self.ensure_open()?; + let mut state = self.state.lock().await; + self.ensure_open()?; + if state.buffer_size != size { + state.buffer_size = size; + self.buffer.lock().unwrap().bytes = Bytes::new(); + } Ok(()) } @@ -228,7 +265,7 @@ impl RemoteBlobFile { let BlobRangeResponse { request_id, response, - _permit, + _permit: permit, } = self .requester .request_range(&range_header, RangeRequestMode::DataRead, self.version) @@ -236,19 +273,9 @@ impl RemoteBlobFile { .map_err(remote_blob_error)?; self.ensure_open()?; validate_partial_response(&response, range.clone(), self.size)?; - let bytes = response - .bytes() - .await - .err_to_http(request_id) - .map_err(remote_blob_error)?; + let bytes = read_blob_body(response, range.end - range.start, request_id).await?; + drop(permit); self.ensure_open()?; - if bytes.len() as u64 != range.end - range.start { - return Err(remote_blob_error(format!( - "byte range returned {} bytes, expected {}", - bytes.len(), - range.end - range.start - ))); - } Ok(bytes) } @@ -275,7 +302,16 @@ impl RemoteBlobFile { let remaining = usize::try_from(remaining).map_err(|_| { lance_core::Error::invalid_input("remaining blob length exceeds addressable memory") })?; - self.read_up_to_locked(&mut state, remaining).await + // Joining a small cached prefix to a large tail would copy the entire + // blob while both allocations are live. Match the native reader's + // bounded reuse rule for whole-blob reads. + let held_len = cached_prefix(&self.buffer.lock().unwrap(), state.cursor, remaining).len(); + if remaining > held_len.saturating_mul(2) { + self.buffer.lock().unwrap().bytes = Bytes::new(); + } + let bytes = self.read_up_to_locked(&mut state, remaining).await?; + self.buffer.lock().unwrap().bytes = Bytes::new(); + Ok(bytes) } pub(crate) async fn read_up_to(&self, len: usize) -> lance_core::Result { @@ -296,14 +332,51 @@ impl RemoteBlobFile { return Ok(Bytes::new()); } - // A partial read must release its HTTP response before returning. Keeping - // it open across calls would hold a connection slot indefinitely and - // prevent other handles from making progress. - let end = state.cursor + target_len as u64; - let bytes = self.read_range(state.cursor..end).await?; + let prefix = cached_prefix(&self.buffer.lock().unwrap(), state.cursor, target_len); + if prefix.len() == target_len { + state.cursor += target_len as u64; + return Ok(prefix); + } + let fetch_start = state.cursor + prefix.len() as u64; + let still_need = target_len - prefix.len(); + let fetch_len = if state.buffer_size == 0 { + still_need as u64 + } else { + (state.buffer_size.max(still_need) as u64).min(self.size - fetch_start) + }; + // Fully consume the response before retaining only its Bytes. read_range + // releases both the connection and the concurrency permit before return. + let data = self + .read_range(fetch_start..fetch_start + fetch_len) + .await?; self.ensure_open()?; - state.cursor = end; - Ok(bytes) + let tail = data.slice(..still_need); + let result = if prefix.is_empty() { + tail + } else { + let mut joined = Vec::new(); + joined.try_reserve_exact(target_len).map_err(|error| { + remote_blob_error(format!( + "cannot allocate blob read of {target_len} bytes: {error}" + )) + })?; + joined.extend_from_slice(&prefix); + joined.extend_from_slice(&tail); + Bytes::from(joined) + }; + { + let mut buffer = self.buffer.lock().unwrap(); + // Serialize publishing a new window with close clearing the cache. + self.ensure_open()?; + if state.buffer_size != 0 { + buffer.start = fetch_start; + buffer.bytes = data; + } else { + buffer.bytes = Bytes::new(); + } + } + state.cursor += target_len as u64; + Ok(result) } pub(crate) async fn seek(&self, new_cursor: u64) -> lance_core::Result<()> { @@ -326,6 +399,83 @@ impl RemoteBlobFile { } } +/// Collect a range without retaining a second payload's worth of network chunks. +async fn read_blob_body( + response: Response, + expected: u64, + request_id: String, +) -> lance_core::Result { + let expected = usize::try_from(expected).map_err(|_| { + lance_core::Error::invalid_input("blob range length exceeds addressable memory") + })?; + let length_error = |received| { + remote_blob_error(format!( + "byte range returned {received} bytes, expected {expected}" + )) + }; + let mut chunks = response.bytes_stream(); + let first = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + .ok_or_else(|| length_error(0))?; + if first.len() > expected { + return Err(length_error(first.len())); + } + if first.len() == expected { + while let Some(chunk) = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + { + if !chunk.is_empty() { + return Err(length_error(expected.saturating_add(chunk.len()))); + } + } + return Ok(first); + } + let mut bytes = Vec::new(); + bytes.try_reserve_exact(expected).map_err(|error| { + remote_blob_error(format!( + "cannot allocate blob range of {expected} bytes: {error}" + )) + })?; + bytes.extend_from_slice(&first); + drop(first); + while let Some(chunk) = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + { + let received = bytes.len().saturating_add(chunk.len()); + if received > expected { + return Err(length_error(received)); + } + bytes.extend_from_slice(&chunk); + } + if bytes.len() != expected { + return Err(length_error(bytes.len())); + } + Ok(Bytes::from(bytes)) +} + +fn cached_prefix(buffer: &RemoteBlobBuffer, cursor: u64, length: usize) -> Bytes { + let Some(offset) = cursor.checked_sub(buffer.start) else { + return Bytes::new(); + }; + let Ok(offset) = usize::try_from(offset) else { + return Bytes::new(); + }; + if offset >= buffer.bytes.len() { + return Bytes::new(); + } + let end = offset.saturating_add(length).min(buffer.bytes.len()); + buffer.bytes.slice(offset..end) +} + fn remote_blob_error(error: impl std::fmt::Display) -> lance_core::Error { lance_core::Error::io(format!("remote blob read failed: {error}")) } @@ -434,10 +584,13 @@ impl RemoteTable { read_snapshot.version = Some(self.describe_read_snapshot(read_snapshot).await?.version); } let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); - let mut chunks = Vec::new(); + let mut blobs = BlobAccumulator::new(row_ids.len()); while let Some(ids) = pending.pop() { - match self.fetch_blobs_chunk(column, ids, read_snapshot).await { - Ok(blobs) => chunks.push(blobs), + match self + .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) + .await + { + Ok(()) => {} Err(error) if is_fetch_blobs_byte_limit_error(&error) => { // A single-request call may turn into several requests after a // byte-cap error. No bytes from the failed request were used. @@ -455,7 +608,15 @@ impl RemoteTable { Some(file) => Some(file.read().await?), None => None, }; - chunks.push(LargeBinaryArray::from(vec![blob.as_deref()])); + let blob = match blob { + Some(bytes) => LargeBinaryArray::new( + OffsetBuffer::new(vec![0, bytes.len() as i64].into()), + Buffer::from(bytes), + None, + ), + None => LargeBinaryArray::new_null(1), + }; + blobs.append(&blob)?; } else { let mid = ids.len() / 2; pending.push(&ids[mid..]); @@ -466,15 +627,7 @@ impl RemoteTable { } } - if chunks.len() == 1 { - return Ok(chunks.pop().unwrap()); - } - let chunk_refs: Vec<&dyn Array> = chunks.iter().map(|chunk| chunk as &dyn Array).collect(); - Ok(arrow::compute::concat(&chunk_refs)? - .as_any() - .downcast_ref::() - .expect("concatenating LargeBinary arrays returns LargeBinary") - .clone()) + Ok(blobs.finish()) } async fn fetch_blobs_chunk( @@ -482,7 +635,8 @@ impl RemoteTable { column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, - ) -> Result { + blobs: &mut BlobAccumulator, + ) -> Result<()> { let mut body = serde_json::json!({ "version": read_snapshot.version, "column": column, @@ -502,7 +656,7 @@ impl RemoteTable { Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), }; - let mut blob_chunks: Vec> = Vec::new(); + let mut rows = 0; while let Some(batch) = stream.try_next().await? { let blob_column = batch.column_by_name(column).ok_or_else(|| Error::Http { source: format!("fetch_blobs response is missing the '{column}' column").into(), @@ -525,28 +679,19 @@ impl RemoteTable { status_code: None, }); } - blob_chunks.push(arrow::compute::cast(blob_column, &DataType::LargeBinary)?); - } - let blobs = if blob_chunks.is_empty() { - LargeBinaryArray::from(Vec::>::new()) - } else { - let blob_chunk_refs: Vec<&dyn Array> = blob_chunks.iter().map(AsRef::as_ref).collect(); - arrow::compute::concat(&blob_chunk_refs)? + let array = arrow::compute::cast(blob_column, &DataType::LargeBinary)?; + let array = array .as_any() .downcast_ref::() - .ok_or_else(|| Error::Http { - source: "fetch_blobs could not read the concatenated response as LargeBinary" - .into(), - request_id: request_id.clone(), - status_code: None, - })? - .clone() - }; - if blobs.len() != row_ids.len() { + .expect("casting to LargeBinary returns LargeBinary"); + rows += array.len(); + blobs.append(array)?; + } + if rows != row_ids.len() { return Err(Error::Http { source: format!( "fetch_blobs returned {} rows for {} row ids", - blobs.len(), + rows, row_ids.len() ) .into(), @@ -554,7 +699,7 @@ impl RemoteTable { status_code: None, }); } - Ok(blobs) + Ok(()) } /// Materialize ranges through version-pinned handles, preserving nulls and order. @@ -1893,9 +2038,8 @@ mod tests { [ ("bytes=0-0".to_string(), None), ("bytes=5-8".to_string(), Some("5".to_string())), - ("bytes=0-3".to_string(), Some("5".to_string())), ( - format!("bytes=10-{}", PAYLOAD.len() - 1), + format!("bytes=0-{}", PAYLOAD.len() - 1), Some("5".to_string()) ), ] @@ -1943,7 +2087,7 @@ mod tests { } #[tokio::test] - async fn remote_blob_file_releases_response_after_each_partial_read() { + async fn remote_blob_file_reuses_prefetched_bytes_across_reads_and_seeks() { let requests = Arc::new(StdMutex::new(Vec::new())); let table = mock_remote_blob_table(requests.clone()); let file = table @@ -1961,7 +2105,41 @@ mod tests { assert_eq!(file.tell().await.unwrap(), 24); assert_eq!( requests.lock().unwrap().as_slice(), - ["bytes=0-0", "bytes=0-3", "bytes=4-6", "bytes=20-23"] + ["bytes=0-0", &format!("bytes=0-{}", PAYLOAD.len() - 1)] + ); + } + + #[tokio::test] + async fn remote_buffer_boundaries_and_disabled_read_ahead() { + let requests = Arc::new(StdMutex::new(Vec::new())); + let table = mock_remote_blob_table(requests.clone()); + let file = table + .probe_files("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + file.set_buffer_size(4).await.unwrap(); + assert_eq!(file.read_up_to(3).await.unwrap(), &PAYLOAD[..3]); + assert_eq!(file.read_up_to(3).await.unwrap(), &PAYLOAD[3..6]); + file.seek(5).await.unwrap(); + assert_eq!(file.read_up_to(2).await.unwrap(), &PAYLOAD[5..7]); + assert_eq!(file.read_range(5..6).await.unwrap(), &PAYLOAD[5..6]); + assert_eq!(file.tell().await.unwrap(), 7); + file.set_buffer_size(0).await.unwrap(); + assert_eq!(file.read_up_to(1).await.unwrap(), &PAYLOAD[7..8]); + assert_eq!(file.read_up_to(1).await.unwrap(), &PAYLOAD[8..9]); + assert_eq!( + requests.lock().unwrap().as_slice(), + [ + "bytes=0-0", + "bytes=0-3", + "bytes=4-7", + "bytes=5-5", + "bytes=7-7", + "bytes=8-8" + ] ); } @@ -2198,6 +2376,7 @@ mod tests { .flatten() .unwrap(); + file.set_buffer_size(0).await.unwrap(); let error = file.read_up_to(10).await.unwrap_err(); assert!( error.to_string().contains("returned 5 bytes, expected 10"), @@ -2324,6 +2503,7 @@ mod tests { file.read_up_to(1).await.unwrap_err(), file.seek(0).await.unwrap_err(), file.tell().await.unwrap_err(), + file.set_buffer_size(0).await.unwrap_err(), ] { assert!(error.to_string().contains("already closed"), "got: {error}"); } @@ -2530,10 +2710,114 @@ mod tests { assert!(error.to_string().contains("206"), "got: {error}"); } + #[tokio::test] + async fn impossible_range_capacity_returns_an_error() { + let size = isize::MAX as u64 + 1; + let table = RemoteTable::new_mock( + "videos".to_string(), + move |request| { + let range = request + .headers() + .get(header::RANGE) + .unwrap() + .to_str() + .unwrap(); + let end = if range == "bytes=0-0" { 0 } else { size - 1 }; + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, format!("bytes 0-{end}/{size}")) + .header(VERSION_HEADER, "5") + .body(vec![1]) + .unwrap() + }, + Some(Version::new(0, 5, 0)), + ); + let file = table + .probe_files("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + let error = file.read().await.unwrap_err(); + assert!( + error.to_string().contains("cannot allocate blob range"), + "{error}" + ); + assert_eq!(file.tell().await.unwrap(), 0); + } + + #[derive(Debug)] + struct TrackedRangeBody { + bytes: Vec, + dropped: Arc, + } + + impl AsRef<[u8]> for TrackedRangeBody { + fn as_ref(&self) -> &[u8] { + &self.bytes + } + } + + impl Drop for TrackedRangeBody { + fn drop(&mut self) { + self.dropped.store(true, Ordering::Release); + } + } + + #[tokio::test] + async fn close_releases_existing_cache_after_in_flight_read_ends() { + for cancel in [false, true] { + let release = Arc::new(tokio::sync::Barrier::new(2)); + let started = Arc::new(tokio::sync::Notify::new()); + let dropped = Arc::new(AtomicBool::new(false)); + let file = Arc::new(RemoteBlobFile::new( + Arc::new(BlockingRangeRequester { + release: release.clone(), + started: started.clone(), + block_start: 4, + tracked: Some(dropped.clone()), + }), + PAYLOAD.len() as u64, + Some(5), + )); + file.set_buffer_size(4).await.unwrap(); + assert_eq!(file.read_up_to(1).await.unwrap().as_ref(), &PAYLOAD[..1]); + file.seek(3).await.unwrap(); + assert!( + !dropped.load(Ordering::Acquire), + "warm cache was not retained" + ); + let reader = { + let file = file.clone(); + tokio::spawn(async move { file.read_up_to(2).await }) + }; + started.notified().await; + tokio::time::timeout(Duration::from_millis(50), file.close()) + .await + .expect("close waited for I/O") + .unwrap(); + if cancel { + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + } else { + release.wait().await; + let error = reader.await.unwrap().unwrap_err(); + assert!(error.to_string().contains("already closed"), "{error}"); + } + assert!( + dropped.load(Ordering::Acquire), + "closed handle retained its old window (cancel={cancel})" + ); + } + } + #[derive(Debug)] struct BlockingRangeRequester { release: Arc, started: Arc, + block_start: usize, + tracked: Option>, } #[async_trait::async_trait] @@ -2544,17 +2828,31 @@ mod tests { _mode: RangeRequestMode, _version: Option, ) -> Result { - if range_header == "bytes=0-3" { + let (start, end) = range_header + .strip_prefix("bytes=") + .unwrap() + .split_once('-') + .unwrap(); + let start: usize = start.parse().unwrap(); + let end: usize = end.parse().unwrap(); + if start == self.block_start { self.started.notify_one(); self.release.wait().await; } + let bytes = match &self.tracked { + Some(dropped) if start == 0 => Bytes::from_owner(TrackedRangeBody { + bytes: PAYLOAD[start..=end].to_vec(), + dropped: dropped.clone(), + }), + _ => Bytes::copy_from_slice(&PAYLOAD[start..=end]), + }; let response = http::Response::builder() .status(StatusCode::PARTIAL_CONTENT) .header( header::CONTENT_RANGE, - format!("bytes 0-{}/{}", PAYLOAD.len() - 1, PAYLOAD.len()), + format!("bytes {start}-{end}/{}", PAYLOAD.len()), ) - .body(PAYLOAD.to_vec()) + .body(bytes) .unwrap(); Ok(("hung".to_string(), Response::from(response)).into()) } @@ -2567,6 +2865,8 @@ mod tests { let requester: Arc = Arc::new(BlockingRangeRequester { release: release.clone(), started: started.clone(), + block_start: 0, + tracked: None, }); let file = Arc::new(RemoteBlobFile::new( requester, diff --git a/rust/lancedb/src/remote/table/blobs/aggregate.rs b/rust/lancedb/src/remote/table/blobs/aggregate.rs new file mode 100644 index 000000000..e8e794fa0 --- /dev/null +++ b/rust/lancedb/src/remote/table/blobs/aggregate.rs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Flatten response batches once, releasing each source buffer as it is copied. + +use std::collections::VecDeque; + +use arrow_array::{Array, LargeBinaryArray}; +use arrow_buffer::{Buffer, MutableBuffer, NullBufferBuilder, OffsetBuffer}; +use arrow_schema::ArrowError; + +pub(super) struct BlobAccumulator { + offsets: Vec, + nulls: NullBufferBuilder, + values: VecDeque, + bytes: i64, +} + +impl BlobAccumulator { + pub(super) fn new(rows: usize) -> Self { + let mut offsets = Vec::with_capacity(rows + 1); + offsets.push(0); + Self { + offsets, + nulls: NullBufferBuilder::new(rows), + values: VecDeque::new(), + bytes: 0, + } + } + + pub(super) fn append(&mut self, array: &LargeBinaryArray) -> Result<(), ArrowError> { + let offsets = array.value_offsets(); + let start = offsets[0]; + let length = offsets[array.len()] - start; + let total = self.bytes.checked_add(length).ok_or_else(|| { + ArrowError::ComputeError("fetch_blobs result exceeds i64 byte offsets".into()) + })?; + self.offsets.extend( + offsets[1..] + .iter() + .map(|offset| self.bytes + (*offset - start)), + ); + if let Some(nulls) = array.nulls() { + self.nulls.append_buffer(nulls); + } else { + self.nulls.append_n_non_nulls(array.len()); + } + if length != 0 { + self.values.push_back( + array + .values() + .slice_with_length(start as usize, length as usize), + ); + } + self.bytes = total; + Ok(()) + } + + pub(super) fn finish(mut self) -> LargeBinaryArray { + let values = match self.values.len() { + 0 => Buffer::default(), + 1 => self.values.pop_front().unwrap(), + _ => { + let mut values = MutableBuffer::new(self.bytes as usize); + // Do not retain all decoded batches alongside the final allocation. + // Drop each source allocation immediately after copying its bytes. + while let Some(chunk) = self.values.pop_front() { + values.extend_from_slice(&chunk); + } + values.into() + } + }; + LargeBinaryArray::new( + OffsetBuffer::new(self.offsets.into()), + values, + self.nulls.finish(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_buffer_is_not_copied() { + let array = LargeBinaryArray::from(vec![Some(b"alpha".as_slice()), None, Some(b"")]); + let mut result = BlobAccumulator::new(3); + result.append(&array).unwrap(); + let output = result.finish(); + assert_eq!(output.values().as_ptr(), array.values().as_ptr()); + assert_eq!(output, array); + } + + #[test] + fn slices_batches_nulls_and_empty_values_keep_order() { + let array = LargeBinaryArray::from(vec![ + Some(b"unused".as_slice()), + Some(b"alpha"), + None, + Some(b""), + Some(b"beta"), + ]); + let mut result = BlobAccumulator::new(6); + result.append(&array.slice(1, 3)).unwrap(); + result.append(&array.slice(4, 1)).unwrap(); + result.append(&array.slice(2, 2)).unwrap(); + assert_eq!( + result.finish(), + LargeBinaryArray::from(vec![ + Some(b"alpha".as_slice()), + None, + Some(b""), + Some(b"beta"), + None, + Some(b""), + ]) + ); + assert_eq!(BlobAccumulator::new(0).finish().len(), 0); + } +} diff --git a/rust/lancedb/src/remote/table/ipc_stream.rs b/rust/lancedb/src/remote/table/ipc_stream.rs index af31a9b28..08b3b1dea 100644 --- a/rust/lancedb/src/remote/table/ipc_stream.rs +++ b/rust/lancedb/src/remote/table/ipc_stream.rs @@ -3,6 +3,10 @@ //! Incremental decoding of response bodies that use Arrow IPC stream framing. +mod framing; + +use framing::{FramingError, IpcFraming}; + use arrow_array::RecordBatch; use arrow_buffer::Buffer; use arrow_ipc::reader::StreamDecoder; @@ -10,7 +14,6 @@ use bytes::Bytes; use datafusion_common::DataFusionError; use datafusion_physical_plan::SendableRecordBatchStream; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; -use futures::stream::BoxStream; use futures::{Stream, StreamExt, TryStreamExt}; use crate::error::{BoxError, Error, Result}; @@ -35,7 +38,7 @@ where E: Into + 'static, { let mut body = IpcStreamBody { - chunks: chunks.map_err(Into::into).boxed(), + framing: IpcFraming::new(chunks.map_err(Into::into).boxed()), chunk: Buffer::default(), decoder: StreamDecoder::new(), finished: false, @@ -62,7 +65,7 @@ where } struct IpcStreamBody { - chunks: BoxStream<'static, std::result::Result>, + framing: IpcFraming, /// The part of the current chunk that has not been decoded yet. chunk: Buffer, decoder: StreamDecoder, @@ -80,11 +83,12 @@ impl IpcStreamBody { async fn next_batch(&mut self) -> Result> { while !self.finished { if self.chunk.is_empty() { - match self.chunks.next().await { - Some(Ok(chunk)) => self.chunk = chunk.into(), - Some(Err(error)) => return Err(self.interrupted(error)), - None if read_end_of_stream(&mut self.decoder) => self.finished = true, - None => { + match self.framing.next_buffer().await { + Ok(Some(chunk)) => self.chunk = chunk, + Err(FramingError::Interrupted(error)) => return Err(self.interrupted(error)), + Err(FramingError::Arrow(error)) => return Err(error.into()), + Ok(None) if read_end_of_stream(&mut self.decoder) => self.finished = true, + Ok(None) => { return Err(self.interrupted( "the response ended before the Arrow end-of-stream marker".into(), )); @@ -208,6 +212,37 @@ mod tests { .collect() } + #[tokio::test] + async fn impossible_ipc_body_lengths_return_errors() { + let batches = batches(); + let messages = messages(&batches[0].schema(), &batches, IpcWriteOptions::default()); + for length in [-1, i64::MAX - 31, i64::MAX] { + let mut message = messages[1].clone(); + let metadata_len = u32::from_le_bytes(message[4..8].try_into().unwrap()) as usize; + let metadata = arrow_ipc::root_as_message(&message[8..8 + metadata_len]).unwrap(); + let field = metadata + ._tab + .vtable() + .get(arrow_ipc::Message::VT_BODYLENGTH); + assert_ne!(field, 0, "fixture must contain a body length field"); + let offset = 8 + metadata._tab.loc() + field as usize; + message[offset..offset + 8].copy_from_slice(&length.to_le_bytes()); + // A valid schema and message metadata followed by just one body byte. + message.truncate(8 + metadata_len + 1); + let (_, returned, error) = read(vec![ + Ok(Bytes::copy_from_slice(&messages[0])), + Ok(Bytes::from(message)), + ]) + .await; + assert!(returned.is_empty()); + let error = error.unwrap().to_string(); + assert!( + error.contains("body length") || error.contains("cannot allocate IPC message"), + "unexpected error for length {length}: {error}" + ); + } + } + /// The schema, the batches yielded, and the error that ended the stream. async fn read( chunks: Vec>, @@ -278,6 +313,78 @@ mod tests { assert_eq!(output, input); } + #[tokio::test] + async fn fragmented_body_keeps_only_its_declared_allocation() { + use arrow_array::LargeBinaryArray; + + let bytes = vec![42; 3 * 1024 * 1024 + 13]; + let array = LargeBinaryArray::from(vec![bytes.as_slice()]); + let batch = RecordBatch::try_from_iter([("blob", Arc::new(array) as ArrayRef)]).unwrap(); + let body = messages( + &batch.schema(), + std::slice::from_ref(&batch), + IpcWriteOptions::default(), + ) + .concat(); + let (_, output, error) = read(chunks(&body, 8191)).await; + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, [batch]); + let blobs = output[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!( + blobs.values().capacity() <= bytes.len() + 256, + "IPC body retained {} bytes for {} value bytes", + blobs.values().capacity(), + bytes.len() + ); + } + + #[rstest] + #[case(false)] + #[case(true)] + #[tokio::test] + async fn zero_body_batches_and_legacy_prefixes(#[case] legacy: bool) { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let input = [vec![], vec![1, 2], vec![]] + .into_iter() + .map(|values| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(values))]) + .unwrap() + }) + .collect::>(); + let options = IpcWriteOptions::try_new(8, legacy, arrow_ipc::MetadataVersion::V4).unwrap(); + let body = messages(&schema, &input, options).concat(); + let (_, output, error) = read(chunks(&body, 1)).await; + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, input); + } + + #[tokio::test] + async fn partial_next_prefix_still_delivers_a_zero_body_batch() { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let empty = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(Vec::::new()))], + ) + .unwrap(); + let nonempty = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1]))]) + .unwrap(); + let messages = messages( + &schema, + &[empty.clone(), nonempty], + IpcWriteOptions::default(), + ); + let cutoff = messages[..2].concat().len() + 1; + let body = messages.concat(); + let (_, output, error) = read(chunks(&body[..cutoff], 1)).await; + assert_eq!(output, [empty]); + assert_interrupted(error, 1, 0); + } + /// The server answers an empty result with the schema and the end-of-stream marker. #[tokio::test] async fn empty_result_keeps_its_schema() { diff --git a/rust/lancedb/src/remote/table/ipc_stream/framing.rs b/rust/lancedb/src/remote/table/ipc_stream/framing.rs new file mode 100644 index 000000000..da20c8e99 --- /dev/null +++ b/rust/lancedb/src/remote/table/ipc_stream/framing.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Frame IPC bodies before decoding, avoiding StreamDecoder's growing scratch buffer. + +use arrow_buffer::Buffer; +use arrow_schema::ArrowError; +use bytes::Bytes; +use futures::StreamExt; +use futures::stream::BoxStream; + +use crate::error::BoxError; + +pub(super) enum FramingError { + Interrupted(BoxError), + Arrow(ArrowError), +} + +#[derive(Clone, Copy)] +enum Frame { + Header { + bytes: [u8; 4], + read: usize, + continuation: bool, + }, + Metadata(usize), + Body(usize), + End, +} + +impl Default for Frame { + fn default() -> Self { + Self::Header { + bytes: [0; 4], + read: 0, + continuation: false, + } + } +} + +pub(super) struct IpcFraming { + chunks: BoxStream<'static, Result>, + chunk: Buffer, + frame: Frame, +} + +impl IpcFraming { + pub(super) fn new(chunks: BoxStream<'static, Result>) -> Self { + Self { + chunks, + chunk: Buffer::default(), + frame: Frame::default(), + } + } + + pub(super) async fn next_buffer(&mut self) -> Result, FramingError> { + let buffer = match self.frame { + Frame::Header { + mut bytes, + mut read, + continuation, + } => { + // Forward even a partial prefix immediately. StreamDecoder may + // need that byte to yield the preceding zero-body record batch. + self.fill_chunk().await?; + let take = self.chunk.len().min(4 - read); + let buffer = self.chunk.slice_with_length(0, take); + self.chunk.advance(take); + bytes[read..read + take].copy_from_slice(&buffer); + read += take; + self.frame = if read == 4 { + match u32::from_le_bytes(bytes) { + u32::MAX if !continuation => Frame::Header { + bytes: [0; 4], + read: 0, + continuation: true, + }, + 0 => Frame::End, + length => Frame::Metadata(length as usize), + } + } else { + Frame::Header { + bytes, + read, + continuation, + } + }; + buffer + } + Frame::Metadata(length) => { + let metadata = self.read_exact(length).await?; + let message = arrow_ipc::root_as_message(&metadata).map_err(|error| { + FramingError::Arrow(ArrowError::IpcError(format!( + "Invalid IPC message: {error}" + ))) + })?; + let length = usize::try_from(message.bodyLength()).map_err(|_| { + FramingError::Arrow(ArrowError::IpcError( + "IPC message body length is negative or exceeds addressable memory".into(), + )) + })?; + self.frame = if length == 0 { + Frame::default() + } else { + Frame::Body(length) + }; + metadata + } + Frame::Body(length) => { + let body = self.read_exact(length).await?; + self.frame = Frame::default(); + body + } + Frame::End => { + // Forward trailing bytes to the decoder so it rejects data after EOS. + if !self.chunk.is_empty() { + return Ok(Some(std::mem::take(&mut self.chunk))); + } + return self + .chunks + .next() + .await + .transpose() + .map(|chunk| chunk.map(Buffer::from)) + .map_err(FramingError::Interrupted); + } + }; + Ok(Some(buffer)) + } + + async fn read_exact(&mut self, length: usize) -> Result { + self.fill_chunk().await?; + if self.chunk.len() >= length { + let buffer = self.chunk.slice_with_length(0, length); + self.chunk.advance(length); + return Ok(buffer); + } + // The declared length is untrusted. Arrow's infallible aligned allocator + // can panic on its layout or abort on OOM; Vec exposes both as errors. + // StreamDecoder handles any array-specific alignment when decoding. + let mut buffer = Vec::new(); + buffer.try_reserve_exact(length).map_err(|error| { + FramingError::Arrow(ArrowError::IpcError(format!( + "cannot allocate IPC message of {length} bytes: {error}" + ))) + })?; + while buffer.len() < length { + self.fill_chunk().await?; + let take = self.chunk.len().min(length - buffer.len()); + buffer.extend_from_slice(&self.chunk[..take]); + self.chunk.advance(take); + } + Ok(Buffer::from_vec(buffer)) + } + + async fn fill_chunk(&mut self) -> Result<(), FramingError> { + while self.chunk.is_empty() { + self.chunk = self + .chunks + .next() + .await + .ok_or_else(|| { + FramingError::Interrupted( + "the response ended before the Arrow end-of-stream marker".into(), + ) + })? + .map_err(FramingError::Interrupted)? + .into(); + } + Ok(()) + } +} From 725eee8a47399ec634ad20b98e4968334d89b27d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:13 +0800 Subject: [PATCH 11/36] fix: prevent unsafe write retries and bound Blob uploads (#4977) Ambiguous gateway failures can occur after a write commits, so replaying the operation can append duplicate rows. Non-idempotent writes now retry only known precommit failures. Multipart retries reuse the same upload ID, part ID, and encoded bytes; ambiguous completion returns an unknown-outcome error without abort or replay. A definite 409/429 completion rejection triggers best-effort cleanup using the call's retry budget. Replayable parts and the shared byte-based partition target default to 64 MiB. Dictionary-bearing batches are compacted before size estimation and again when actual compressed IPC framing requires further splitting: keys are remapped without changing their types or schema, view backing buffers are collected, and ListView/LargeListView child ranges are compacted as an interval union so overlapping views retain sharing. Parts are prepared on demand; a single row and its schema can still exceed the target. Multipart progress starts at zero and counts each acknowledged IPC body once. Rust write builders and Python/TypeScript `add` expose per-call retry overrides. Atomic `create_table` pre-encodes to a temporary file and rejects compressed IPC over 256 MiB before sending any request; the schema-first import guidance now includes Python, TypeScript, and Rust examples. The shared partition target also affects local automatic partitioning. At `cb2a79473bd1b51b950c9fa3e9f247f929c8ac3b`, 70 targeted Rust cases pass on source verified against the committed four-file patch. With a 16 KiB target and 128 unique 1 KiB dictionary values, the original ordinary dictionary reproducer drops from 128 requests / 16,942,080 bytes to 16 / 143,488; ListView and LargeListView drop from 128 / 17,056,768 to 16 / 149,632. Encoded HTTP bodies are decoded to check values, nulls, slices, metadata, changing dictionaries, and overlapping views; additional cases cover framing-driven splitting, oversized rows, stable retry bytes/IDs, acknowledged progress, and atomic create. Real HTTP fault tests commit Blob payloads to a local Lance table and verify byte equality, no duplicate append, and zero abort/replay after ambiguous completion. The earlier 811 remote and 7 progress cases at `f36d217110a25f6b501c0255df9aaa60e3c8000a`, Linux Python remote database/options results (437 cases plus 8 fixture consumers), Node retry-binding evidence, and Rust/TypeScript documentation example checks remain historical validation. Python/Node extensions were not rebuilt for the dictionary follow-up; these results do not establish current binding integration or fresh cross-platform/minimum-dependency CI acceptance. A separate real Query Node lifecycle experiment used SDK `b8efe7d2d63647d4962789ca5fc042b59efe073d` and Sophon `58b7895c7c287810fff4e89f13226fc5fa60d9ef`. After the actual listener forced a connection closed, a surviving QN accepted a retry with identical upload ID, part ID, and IPC bytes. Ordinary insert and complete response-loss scenarios sent no replay or abort; fresh reads observed exactly one commit and exact Blob bytes in all three scenarios. This local experiment used a 1-second drain grace, two 32 KiB payloads, and one distinct staged part. It validates acknowledgement-loss recovery at those revisions, not concurrent overlapping attempts, large uploads, physical orphan cleanup, the later dictionary encoding change, or the original sixth-insert EOF. The part target is not a process memory limit: source/ancestor buffers and temporary compaction allocations may coexist. Struct/FixedSizeList parent nulls can retain hidden child keys; this is not complete logical-reachability GC for every Arrow combination, and retained hidden values may affect wire size. The current local Lance 15.0.0-beta.17 rejects ListView/LargeListView persistence; the tests establish remote client IPC encoding behavior, not native or Cloud persistence support. Live Cloud, full workspace/Clippy, the original ordinary-insert disconnect root cause, and Sophon's asynchronous transaction cleanup behavior are not established. Cancelling during staging retains the existing server-session cleanup limitation. Function reader delivery is separate. --- docs/src/js/interfaces/AddDataOptions.md | 12 + docs/web/ingestion/insert.mdx | 102 ++- nodejs/__test__/remote.test.ts | 59 ++ nodejs/lancedb/table.ts | 16 + nodejs/src/table.rs | 8 +- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/remote/table.py | 5 + python/python/lancedb/table.py | 17 + python/python/tests/test_remote_db.py | 302 ++++++- python/src/table.rs | 6 +- rust/lancedb/src/data/scannable.rs | 8 +- rust/lancedb/src/remote/client.rs | 65 +- rust/lancedb/src/remote/db.rs | 145 ++- rust/lancedb/src/remote/retry.rs | 35 +- rust/lancedb/src/remote/table.rs | 441 +++++++--- rust/lancedb/src/remote/table/insert.rs | 875 +++++++++++++++---- rust/lancedb/src/remote/table/write_tests.rs | 436 +++++++++ rust/lancedb/src/remote/util.rs | 283 +++++- rust/lancedb/src/table/add_data.rs | 12 + rust/lancedb/src/table/merge.rs | 10 + rust/lancedb/src/table/update.rs | 9 + rust/lancedb/src/table/write_progress.rs | 27 +- 22 files changed, 2484 insertions(+), 390 deletions(-) create mode 100644 rust/lancedb/src/remote/table/write_tests.rs diff --git a/docs/src/js/interfaces/AddDataOptions.md b/docs/src/js/interfaces/AddDataOptions.md index f1f57b98b..567269471 100644 --- a/docs/src/js/interfaces/AddDataOptions.md +++ b/docs/src/js/interfaces/AddDataOptions.md @@ -71,3 +71,15 @@ await table.add(data, { }, }); ``` + +*** + +### retries? + +```ts +optional retries: number; +``` + +Override the remote retry budget for this call (0 to 255). Zero disables +retries, including multipart parts. Ambiguous commits are never replayed. +Ignored by LanceDB Embedded. diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index befc1c37b..923a71b0e 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -150,6 +150,10 @@ Python and TypeScript report elapsed time in seconds; Rust returns a `Duration`. The expected row count may be unknown for streaming input. On the final update, it falls back to the number of rows written. +For remote multipart writes, rows count input scanning, while bytes count +acknowledged IPC parts. Bytes start at zero and a retried part is counted once, +after acknowledgement. Scanned rows and staged bytes do not imply a commit. + Keep callbacks short and use the write operation's result to determine success. The final `done` update means progress reporting has ended; it can also occur after a write fails or is cancelled. Input errors before writing starts may @@ -164,11 +168,29 @@ from a TypeScript callback are logged and do not abort the write. Wait for the write operation's result, then check the expected records. Progress callbacks describe activity; they do not establish that a write succeeded. If a request fails after the server may have committed it, blindly -repeating an append can duplicate rows. The client's automatic retries can do -the same: on an Enterprise table, the Python and TypeScript 0.40.0 clients resend an -append after a retryable status such as `504`, even when the server had already -committed it, and `add()` still returns success. Reconcile using your record -IDs, or choose an upsert policy designed for replay. +repeating an append can duplicate rows. Current clients do not automatically +replay non-idempotent writes after `500`, `502`, `503`, or `504`, or after a +response is lost. A plain `503` does not prove that a write was rejected before +commit. Connection failures before sending, `409` transaction conflicts, and +explicit `429` rate-limit rejections may be retried within `RetryConfig` limits. Idempotent multipart +parts have a separate retry policy described below. + +If multipart completion times out, loses its response, or receives a `5xx`, the +error reports **commit outcome unknown**. The client neither aborts the upload +nor resends completion or the input under +a new upload ID: aborting at this point could delete already committed data. +Check the table using your record IDs before retrying the operation. + +Configure connection-wide limits with `client_config.retry_config` in Python +(`lancedb.remote.RetryConfig`) or `clientConfig.retryConfig` in TypeScript. +Override the budget for one `add()` with Python `table.add(data, retries=0)` +or TypeScript `table.add(data, { retries: 0 })`. The value must be an integer +between 0 and 255. Rust write builders also provide a per-call override, for +example `table.add(data).retries(0).execute().await?`, +`table.update().retries(0)`, and `table.merge_insert(&["id"]).retries(0)`. +This disables transport retries for that operation, including multipart part +retries; it does not change local transaction conflict handling. Increasing a +retry budget never makes ambiguous commits safe to replay. ## Configure large uploads {#bulk-ingests-into-a-remote-table} @@ -176,26 +198,41 @@ IDs, or choose an upsert policy designed for replay. This section applies only to LanceDB Enterprise tables (`db://` connections). LanceDB Embedded writes are unaffected. -When you write to a LanceDB Enterprise table, the client sends the write as one HTTP `insert` request unless it splits the data into more than one partition, which it does for a large input it can measure or when you set [`write_parallelism`](#write-parallelism). A partitioned write goes up as a multipart write: the client cuts each partition into one or more `insert` parts and uploads them under a single upload id. Each part is streamed. Its size and duration still affect resource use and -timeouts: it has to finish within the client read timeout while the server writes it to object storage, so on very large ingests an oversized part can run past that timeout and surface as: +Large measured inputs, unknown-length streams, and explicit parallel uploads use +multipart writes when the server supports them. The client slices large batches +before IPC encoding and buffers each part for replay. A disconnected request, +read timeout, or configured retryable staging status retries exactly the same +upload ID, part ID, and IPC bytes. `RetryConfig.statuses` controls status retries; +an empty list disables them. The default includes `500`, `502`, `503`, and `504`. +The server replaces that part's staged transaction, so losing +its response does not append the rows twice. Exhausting the part retry budget +aborts the uncommitted session; it does not restart the entire upload. +A complete request rejected with a transaction conflict (`409`) or rate limit +(`429`) also triggers best-effort cleanup. Cleanup uses the call's retry budget; +its failure does not replace the original error. Ambiguous completion outcomes +never trigger cleanup or replay. -```text -lancedb.remote.errors.HttpError: operation timed out -``` +Part size still affects memory and HTTP timeouts. A single blob row cannot be +split across Arrow batches; a very large row may require a larger timeout and +more memory. No connection-pool or keepalive setting guarantees that a write +response will arrive. Two environment variables control how a multipart write's parts are cut. Both are picked up automatically by the Python and TypeScript clients, for clients that support these settings: | Variable | Default | What it controls | |----------|---------|------------------| -| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 8 GiB | Maximum size of a single insert part, in LZ4-compressed Arrow IPC bytes. Set to `0` to disable splitting and send one request per partition. | -| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Maximum wall-clock time, in whole seconds, that any one insert part may stay open. Set to `0` to disable the time-based cut. | +| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 64 MiB | Target LZ4-compressed IPC bytes per replayable part. A single indivisible row and its IPC schema may exceed the target. `0` disables byte-based cuts and can require buffering a whole partition. | +| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Time spent filling a replayable payload, in whole seconds. `0` disables time-based cuts. HTTP deadlines are configured separately in `timeout_config`. | -A part is cut after the input batch that reaches either limit, so cuts fall between batches. Lower the byte budget, with smaller input batches, when large ingests hit the read timeout; lower the duration when uploads are slow or throttled and the byte budget isn't the limiting factor. +A part is cut after an encoding slice reaches either limit. Input batches are +sliced to approximately 8 MiB before encoding, preserving row order. Peak +additional memory scales with active writers and the part budget. Lower +`write_parallelism` or the byte budget to reduce memory use. ```bash Bash icon="terminal" -export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=1073741824 # 1 GiB -export LANCE_CLIENT_MAX_REQUEST_DURATION=120 # 2 minutes +export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=33554432 # 32 MiB +export LANCE_CLIENT_MAX_REQUEST_DURATION=30 # payload preparation budget ``` @@ -203,6 +240,41 @@ Splitting into more parts does not change the final table. The server stages the the write. This upload protocol is separate from repeating an application-level `add()` after a timeout. +Remote `create_table(name, data)` remains one atomic request, including overwrite +and `exist_ok` modes. The client encodes into an automatically removed temporary +file before sending, rejects payloads larger than 256 MiB of compressed IPC, and +never silently creates an empty table as a fallback. Encoding and input failures +therefore issue no create request. Temporary disk usage is bounded by this budget; +individual oversized rows can still need substantial encoding memory. + +For larger imports, create the schema first and upload with progress reporting. +The empty table becomes visible immediately; `add()` commits its rows atomically. +The following examples use an existing connection `db`, an Arrow `schema`, and +input `data` matching that schema (an Arrow reader in Rust): + + +```python Python icon="python" +table = db.create_table("items", schema=schema) +table.add(data, progress=True) +``` + +```typescript TypeScript icon="square-js" +const table = await db.createEmptyTable("items", schema); +await table.add(data, { + progress: (p) => console.log(`Rows written: ${p.outputRows}`), +}); +``` + +```rust Rust icon="rust" +let table = db.create_empty_table("items", schema).execute().await?; +table + .add(data) + .progress(|p| println!("Rows written: {}", p.output_rows())) + .execute() + .await?; +``` + + ## Complete write workflow {#complete-example} diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 4ac08b4c4..a9989b84e 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -483,6 +483,65 @@ describe("remote connection", () => { expect(insertRequests).toBe(2); }); + it.each([ + { status: 429, retries: undefined, attempts: 2 }, + { status: 429, retries: 0, attempts: 1 }, + { status: 504, retries: undefined, attempts: 1 }, + { status: 504, retries: 0, attempts: 1 }, + ])("applies per-call add retries: %j", async (scenario) => { + let attempts = 0; + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + expect(req.url).toContain("/insert/"); + req.resume(); + req.on("end", () => { + attempts++; + res + .writeHead(attempts === 1 ? scenario.status : 200) + .end('{"version":2}'); + }); + }, + async (db) => { + const table = await db.openTable("items"); + const result = table.add([{ id: 1n }], { retries: scenario.retries }); + if (scenario.attempts === 2) { + await expect(result).resolves.toMatchObject({ version: 2 }); + } else { + await expect(result).rejects.toThrow(); + } + for (const retries of [-1, 256, 1.5]) { + await expect(table.add([{ id: 2n }], { retries })).rejects.toThrow( + "retries must be an integer between 0 and 255", + ); + } + }, + { + clientConfig: { + retryConfig: { + retries: 3, + statuses: [429, 504], + backoffFactor: 0, + backoffJitter: 0, + }, + }, + }, + ); + expect(attempts).toBe(scenario.attempts); + }); + it("should accept partial connection options", async () => { await connect("db://test", { apiKey: "fake", diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index b38c2381c..185088424 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -137,6 +137,13 @@ export interface AddDataOptions { * when the blob is read later. */ allowExternalBlobOutsideBases?: boolean; + + /** + * Override the remote retry budget for this call (0 to 255). Zero disables + * retries, including multipart parts. Ambiguous commits are never replayed. + * Ignored by LanceDB Embedded. + */ + retries?: number; } export interface UpdateOptions { @@ -1320,6 +1327,14 @@ export class LocalTable extends Table { } async add(data: Data, options?: Partial): Promise { + if ( + options?.retries !== undefined && + (!Number.isInteger(options.retries) || + options.retries < 0 || + options.retries > 255) + ) { + throw new Error("retries must be an integer between 0 and 255"); + } const mode = options?.mode ?? "append"; const schema = await this.schema(); @@ -1342,6 +1357,7 @@ export class LocalTable extends Table { mode, progress, options?.allowExternalBlobOutsideBases, + options?.retries, ); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index e3bd22c0b..7076bbec1 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -134,7 +134,7 @@ impl Table { #[napi( catch_unwind, - ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean" + ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean, retries?: number" )] pub async fn add( &self, @@ -142,6 +142,7 @@ impl Table { mode: String, progress_callback: Option, allow_external_blob_outside_bases: Option, + retries: Option, ) -> napi::Result { let batches = ipc_file_to_batches(buf.to_vec()) .map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?; @@ -157,6 +158,11 @@ impl Table { }) .collect::>>()?; let mut op = self.inner_ref()?.add(batches); + if let Some(retries) = retries { + let retries = u8::try_from(retries) + .map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?; + op = op.retries(retries); + } op = if mode == "append" { op.mode(AddDataMode::Append) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4f1da9ba7..15234532d 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -544,6 +544,7 @@ class Table: progress: Optional[Any] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: ... async def update( self, updates: Dict[str, str], where: Optional[str] diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 21749a0a7..6730e6694 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -719,6 +719,7 @@ class RemoteTable(Table): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. @@ -753,6 +754,9 @@ class RemoteTable(Table): using too much memory. allow_external_blob_outside_bases: bool, default False Not supported in LanceDB Enterprise. Setting this raises. + retries: int, optional + Override the retry budget for this call (0 to 255). Zero disables + retries, including multipart parts. Ambiguous commits are never replayed. Returns ------- @@ -770,6 +774,7 @@ class RemoteTable(Table): progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) ) finally: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 424b4b64c..3161eda30 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2256,6 +2256,7 @@ class Table(ABC): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. @@ -2316,6 +2317,10 @@ class Table(ABC): Store blob URIs that sit outside registered blob bases. The row keeps a reference, so the object has to stay readable. Local tables only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. Returns ------- @@ -4821,6 +4826,7 @@ class LanceTable(Table): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add data to the table. If vector columns are missing and the table @@ -4852,6 +4858,10 @@ class LanceTable(Table): allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. LanceDB Embedded only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. Returns ------- @@ -4869,6 +4879,7 @@ class LanceTable(Table): progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) ) finally: @@ -7080,6 +7091,7 @@ class AsyncTable: progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [AsyncTable][lancedb.table.AsyncTable]. @@ -7118,6 +7130,10 @@ class AsyncTable: allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. LanceDB Embedded only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. """ schema = await self.schema() @@ -7172,6 +7188,7 @@ class AsyncTable: progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) except RuntimeError as e: if "Cast error" in str(e): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 8fde1209c..448fd6c39 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -59,20 +59,124 @@ import pyarrow as pa from utils import start_server_thread -def make_mock_http_handler(handler): +def make_mock_http_handler(handler, *, buffer_body=True): class MockLanceDBHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): handler(self) def do_POST(self): - handler(self) + if not buffer_body: + handler(self) + return - def do_PUT(self): - handler(self) + # HTTP/1.0 closes after the response. Leaving a streamed upload unread + # can reset the connection while the client is still writing its body. + # Keep the original framing so handlers can inspect the actual request. + source = self.rfile + body = bytearray() + if self.headers.get("Transfer-Encoding") == "chunked": + while True: + line = source.readline() + assert line.endswith(b"\r\n") + body.extend(line) + size = int(line.split(b";")[0], 16) + if size == 0: + while True: + line = source.readline() + assert line.endswith(b"\r\n") + body.extend(line) + if line == b"\r\n": + break + break + chunk = source.read(size + 2) + assert len(chunk) == size + 2 and chunk[-2:] == b"\r\n" + body.extend(chunk) + else: + size = int(self.headers.get("Content-Length", 0)) + body.extend(source.read(size)) + assert len(body) == size + self.rfile = io.BytesIO(body) + try: + handler(self) + finally: + self.rfile.close() + self.rfile = source + + do_PUT = do_POST return MockLanceDBHandler +@pytest.mark.parametrize("chunked", [False, True]) +@pytest.mark.parametrize("read_body", [False, True]) +def test_mock_http_handler_waits_for_body(chunked, read_body): + body = ( + b"7;ext=value\r\npayload\r\n0\r\nX-Trailer: value\r\n\r\n" + if chunked + else b"payload" + ) + received = [] + + def handler(request): + if read_body: + assert (request.headers.get("Transfer-Encoding") == "chunked") == chunked + received.append(request.rfile.read(len(body))) + request.send_response(200) + request.end_headers() + + with http.server.HTTPServer( + ("127.0.0.1", 0), make_mock_http_handler(handler) + ) as server: + thread = start_server_thread(server) + try: + with socket.create_connection(server.server_address, timeout=2) as client: + framing = ( + "Transfer-Encoding: chunked" if chunked else "Content-Length: 7" + ) + client.sendall( + f"POST / HTTP/1.0\r\nHost: localhost\r\n{framing}\r\n\r\n".encode() + ) + client.settimeout(0.1) + with pytest.raises(TimeoutError): + client.recv(1024) + client.settimeout(2) + client.sendall(body) + assert client.recv(1024).startswith(b"HTTP/1.0 200") + finally: + server.shutdown() + thread.join() + assert received == ([body] if read_body else []) + + +@pytest.mark.parametrize("disconnect", [False, True]) +def test_mock_http_handler_allows_early_failure(disconnect): + def handler(request): + if disconnect: + request.connection.shutdown(socket.SHUT_RDWR) + request.close_connection = True + else: + request.send_response(413) + request.end_headers() + + with http.server.HTTPServer( + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=False) + ) as server: + thread = start_server_thread(server) + try: + with socket.create_connection(server.server_address, timeout=2) as client: + client.sendall( + b"POST / HTTP/1.0\r\nHost: localhost\r\nContent-Length: 7\r\n\r\n" + ) + response = client.recv(1024) + if disconnect: + assert response == b"" + else: + assert response.startswith(b"HTTP/1.0 413") + finally: + server.shutdown() + thread.join() + + @pytest.mark.parametrize("db_name", ["a" * 64, "invalid..database"]) def test_connect_rejects_invalid_cloud_dns_hostname(db_name): with pytest.raises(ValueError, match="DNS labels must contain 1 to 63 bytes"): @@ -80,9 +184,9 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name): @contextlib.contextmanager -def mock_lancedb_connection(handler, **client_config): +def mock_lancedb_connection(handler, *, buffer_body=True, **client_config): with http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body) ) as server: port = server.server_address[1] handle = start_server_thread(server) @@ -108,9 +212,9 @@ def mock_lancedb_connection(handler, **client_config): @contextlib.asynccontextmanager -async def mock_lancedb_connection_async(handler, **client_config): +async def mock_lancedb_connection_async(handler, *, buffer_body=True, **client_config): with http.server.HTTPServer( - ("127.0.0.1", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body) ) as server: port = server.server_address[1] handle = start_server_thread(server) @@ -135,6 +239,76 @@ async def mock_lancedb_connection_async(handler, **client_config): handle.join() +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.parametrize("retries", [None, 0]) +@pytest.mark.parametrize("status", [429, 504]) +@pytest.mark.asyncio +async def test_add_retry_override(sync_api, retries, status): + attempts = 0 + + def handler(request): + nonlocal attempts + if request.path.endswith("/describe/"): + payload = { + "version": 1, + "schema": { + "fields": [ + {"name": "id", "type": {"type": "int64"}, "nullable": True} + ] + }, + } + request.send_response(200) + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + return + assert request.path.endswith("/insert/") + body = bytearray() + if request.headers.get("Transfer-Encoding") == "chunked": + while True: + size = int(request.rfile.readline().strip(), 16) + if size == 0: + request.rfile.readline() + break + body.extend(request.rfile.read(size)) + request.rfile.read(2) + else: + body.extend( + request.rfile.read(int(request.headers.get("Content-Length", 0))) + ) + assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}] + attempts += 1 + request.send_response(status if attempts == 1 else 200) + request.end_headers() + request.wfile.write(b'{"version": 2}') + + config = { + "retry_config": { + "retries": 3, + "statuses": [429, 504], + "backoff_factor": 0, + "backoff_jitter": 0, + } + } + expected_success = status == 429 and retries is None + if sync_api: + with mock_lancedb_connection(handler, **config) as db: + table = db.open_table("test") + if expected_success: + assert table.add([{"id": 1}], retries=retries).version == 2 + else: + with pytest.raises((HttpError, RetryError)): + table.add([{"id": 1}], retries=retries) + else: + async with mock_lancedb_connection_async(handler, **config) as db: + table = await db.open_table("test") + if expected_success: + assert (await table.add([{"id": 1}], retries=retries)).version == 2 + else: + with pytest.raises((HttpError, RetryError)): + await table.add([{"id": 1}], retries=retries) + assert attempts == (2 if expected_success else 1) + + @pytest.fixture def missing_table_handler(cached, namespace_path): request_ids = [] @@ -1248,7 +1422,7 @@ async def test_create_table_timeout_is_actionable(timeout_config): request.close_connection = True async with mock_lancedb_connection_async( - handler, timeout_config=timeout_config + handler, buffer_body=False, timeout_config=timeout_config ) as db: batch = pa.record_batch({"id": [1, 2]}) reader = pa.RecordBatchReader.from_batches(batch.schema, [batch]) @@ -5076,10 +5250,14 @@ def test_remote_schema_restores_blob_extensions(use_async, with_pylance, nested) @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) -@pytest.mark.parametrize("mode", ["merge", "overwrite"]) +@pytest.mark.parametrize( + "mode,part_status", + [("merge", 200), ("overwrite", 200), ("overwrite", 503)], + ids=["merge", "overwrite", "overwrite-retry"], +) @pytest.mark.parametrize("target_with_ranges", [False, True]) async def test_remote_writes_normalize_blob_layouts( - use_async, mode, target_with_ranges + use_async, mode, part_status, target_with_ranges, mem_db ): description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE)) if target_with_ranges: @@ -5088,29 +5266,77 @@ async def test_remote_writes_normalize_blob_layouts( for name in ("position", "size") ) received = [] + paths = [] + staged = {} + part_attempts = [] + published = mem_db.create_table( + "published", + [{"id": 0, "image": b"before"}], + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), + ) def handler(request): - if request.path == "/v1/table/test/describe/": + path = urlparse(request.path).path + query = parse_qs(urlparse(request.path).query) + status = 200 + if path == "/v1/table/test/describe/": response = description else: - expected = "merge_insert" if mode == "merge" else "insert" - assert urlparse(request.path).path == f"/v1/table/test/{expected}/" - if request.headers.get("Transfer-Encoding") == "chunked": - body = bytearray() - while size := int(request.rfile.readline().split(b";")[0], 16): - body.extend(request.rfile.read(size)) - assert request.rfile.read(2) == b"\r\n" - assert request.rfile.read(2) == b"\r\n" + paths.append(path.removeprefix("/v1/table/test/")) + body = request.rfile.read() + if path == "/v1/table/test/multipart_write/create": + assert mode == "overwrite" + assert paths == ["multipart_write/create"] + assert not query and not body + response = {"upload_id": "blob-overwrite"} + elif path == "/v1/table/test/insert/": + assert mode == "overwrite" + assert query["mode"] == ["overwrite"] + assert query["upload_id"] == ["blob-overwrite"] + part_id = query["upload_part_id"][0] + assert str(uuid.UUID(part_id)) == part_id + part_attempts.append((part_id, body)) + assert published.version == 1 + assert published.search().select(["id"]).to_list() == [{"id": 0}] + if staged: + assert staged == {part_id: body} + else: + staged[part_id] = body + assert body[-8:] == b"\xff\xff\xff\xff\x00\x00\x00\x00" + received.append(pa.ipc.open_stream(body).read_all()) + status = part_status if len(part_attempts) == 1 else 200 + response = {} + elif path == "/v1/table/test/multipart_write/complete": + assert mode == "overwrite" + assert query == {"upload_id": ["blob-overwrite"]} and not body + expected_attempts = 2 if part_status == 503 else 1 + assert paths == ["multipart_write/create"] + [ + "insert/" + ] * expected_attempts + ["multipart_write/complete"] + assert len(staged) == len(received) == 1 + assert part_attempts == [part_attempts[0]] * expected_attempts + assert published.version == 1 + published.add(received[0], mode="overwrite") + response = {"version": published.version} else: - body = request.rfile.read(int(request.headers["Content-Length"])) - received.append(pa.ipc.open_stream(body).read_all()) - response = { - "version": 2, - "num_updated_rows": 0, - "num_inserted_rows": 2, - "num_deleted_rows": 0, - } - request.send_response(200) + assert mode == "merge" + assert path == "/v1/table/test/merge_insert/" + # merge_insert still streams a chunked body; preserve its framing. + if request.headers.get("Transfer-Encoding") == "chunked": + stream = io.BytesIO(body) + body = bytearray() + while size := int(stream.readline().split(b";")[0], 16): + body.extend(stream.read(size)) + assert stream.read(2) == b"\r\n" + assert stream.read(2) == b"\r\n" + received.append(pa.ipc.open_stream(body).read_all()) + response = { + "version": 2, + "num_updated_rows": 0, + "num_inserted_rows": 2, + "num_deleted_rows": 0, + } + request.send_response(status) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", "0.5.0") request.end_headers() @@ -5143,7 +5369,23 @@ async def test_remote_writes_normalize_blob_layouts( else: result = table.add(data, mode="overwrite") if use_async: - await result + result = await result + assert result.version == 2 + + if mode == "overwrite": + assert published.version == 2 + hits = published.search().select(["id"]).with_row_id(True).to_arrow() + by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + assert set(by_id) == {1, 2} + row_ids = [by_id[1], by_id[2]] + assert published.fetch_blobs("image", row_ids).to_pylist() == [b"payload", None] + payload, null = published.fetch_blob_files("image", row_ids) + assert null is None + with payload: + assert payload.read_range(1, 3) == b"ayl" + assert payload.read() == b"payload" + else: + assert paths == ["merge_insert/"] assert len(received) == 1 images = received[0]["image"].combine_chunks() diff --git a/python/src/table.rs b/python/src/table.rs index 62c2ee765..e76bae00a 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1471,7 +1471,7 @@ impl Table { }) } - #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false))] + #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))] pub fn add<'a>( self_: PyRef<'a, Self>, data: PyScannable, @@ -1479,6 +1479,7 @@ impl Table { progress: Option>, write_parallelism: Option, allow_external_blob_outside_bases: bool, + retries: Option, ) -> PyResult> { let mut op = self_ .inner_ref()? @@ -1491,6 +1492,9 @@ impl Table { } else { return Err(PyValueError::new_err(format!("Invalid mode: {}", mode))); } + if let Some(retries) = retries { + op = op.retries(retries); + } if let Some(write_parallelism) = write_parallelism { op = op.write_parallelism(write_parallelism); } diff --git a/rust/lancedb/src/data/scannable.rs b/rust/lancedb/src/data/scannable.rs index 0f810941a..cfad157b8 100644 --- a/rust/lancedb/src/data/scannable.rs +++ b/rust/lancedb/src/data/scannable.rs @@ -504,7 +504,7 @@ impl Scannable for PeekedScannable { /// when known; otherwise `sample_rows` row count is used as a lower bound /// estimate. /// -/// Targets roughly 1 million rows or 2 GB per partition, capped at +/// Targets roughly 1 million rows or 64 MiB per partition, capped at /// `max_partitions` (typically the number of available CPU cores). pub(crate) fn estimate_write_partitions( sample_bytes: usize, @@ -519,7 +519,7 @@ pub(crate) fn estimate_write_partitions( let total_rows = total_rows_hint.unwrap_or(sample_rows); let total_bytes = total_rows * bytes_per_row; let by_rows = total_rows.div_ceil(1_000_000); - let by_bytes = total_bytes.div_ceil(2 * 1024 * 1024 * 1024); + let by_bytes = total_bytes.div_ceil(64 * 1024 * 1024); by_rows.max(by_bytes).max(1).min(max_partitions) } @@ -813,8 +813,8 @@ mod tests { #[test] fn test_scales_by_byte_size() { - // 100k rows at 40KB/row = ~4GB total → ceil(4GB / 2GB) = 2 - let sample_bytes = 40_000 * 10; + // 100k rows at 1KB/row exceeds one 64 MiB partition. + let sample_bytes = 1_000 * 10; assert_eq!( estimate_write_partitions(sample_bytes, 10, Some(100_000), 8), 2 diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index e0722bfbc..b16d0091d 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -69,14 +69,9 @@ pub trait HeaderProvider: Send + Sync + std::fmt::Debug { async fn get_headers(&self) -> Result>; } -/// Default maximum bytes per insert request (8 GiB). -/// -/// Sized so a multipart part can hold at least one full Lance data file (the -/// default is 1M rows / 90 GB per file), which keeps fragments from being split -/// into undersized files across parts. The time-based cut -/// ([`DEFAULT_MAX_REQUEST_DURATION_DIVISOR`]) bounds request duration on slow -/// uploads, so a large byte budget does not risk the read timeout. -const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 8 * 1024 * 1024 * 1024; +/// Default target size for replayable multipart IPC payloads (64 MiB). +/// A single oversized row (including its schema) may exceed the target. +const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 64 * 1024 * 1024; /// The default max request duration is the read timeout divided by this, leaving /// headroom for the server to finalize and acknowledge a part before the read @@ -114,28 +109,22 @@ pub struct ClientConfig { /// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment /// variable that contains the user ID value. pub user_id: Option, - /// Maximum number of bytes to send in a single insert HTTP request. + /// Target compressed IPC bytes per multipart request. Defaults to 64 MiB. /// - /// During a multipart write, each partition's data is split into one or more - /// parts of at most this many (Arrow IPC, compressed) bytes, each uploaded as - /// a separate request under the shared upload id. This bounds how long any - /// one request stays open, so large bulk ingests do not exceed the client - /// read timeout while the server streams the part to object storage. - /// - /// The request body is still streamed (not buffered), so this does not - /// increase peak memory. Set to `Some(0)` to disable splitting (one request - /// per partition). You can also set the `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` - /// environment variable. Defaults to 8 GiB. + /// Parts are buffered for retries with the same upload and part IDs. Input + /// batches are sliced before encoding. A single row and its schema are + /// indivisible and may exceed the target. Peak additional memory is bounded + /// by the number of active writers times the part size (plus encoding buffers). + /// Set to `Some(0)` to disable byte-based cuts, or configure + /// `LANCE_CLIENT_MAX_BYTES_PER_REQUEST`. Disabling cuts can require buffering + /// an entire partition for replay. pub max_bytes_per_request: Option, - /// Maximum wall-clock time to spend uploading a single insert HTTP request. + /// Maximum time spent filling a replayable multipart payload. /// - /// Complements [`Self::max_bytes_per_request`]: during a multipart write a - /// part is cut when it reaches either the byte budget or this duration, - /// whichever comes first. The client read timeout also covers the - /// request-body upload, so a slow or throttled upload of a large part can - /// hit that timeout before the byte budget is reached; cutting by time keeps - /// each request short enough that it completes (and the server acknowledges - /// the part) within the read timeout. + /// A part is cut after encoding a batch slice when either its byte budget + /// or this duration is reached. This does not impose a network deadline; + /// `timeout_config` controls HTTP timeouts. Timed-out parts are retried using + /// their original payload and transaction ID. /// /// Set to `Some(Duration::ZERO)` to disable the time-based cut. You can also /// set the `LANCE_CLIENT_MAX_REQUEST_DURATION` environment variable (integer @@ -306,8 +295,9 @@ pub struct RetryConfig { /// You can also set the `LANCE_CLIENT_RETRY_STATUSES` environment variable /// to set this value. Use a comma-separated list of integer values. /// - /// Note that write operations will never be retried on 5xx errors as this may - /// result in duplicated writes. + /// Non-idempotent writes do not replay ambiguous 5xx responses. Multipart + /// parts can retry configured statuses because each replay replaces the same + /// staged transaction. Completion is never replayed. /// /// The default is 409, 429, 500, 502, 503, 504. pub statuses: Option>, @@ -888,6 +878,16 @@ impl RestfulLanceDbClient { Ok((request_id, response)) } + pub(crate) fn with_retries(&self, retries: Option) -> Self { + let mut client = self.clone(); + if let Some(retries) = retries { + client.retry_config.retries = retries; + client.retry_config.connect_retries = retries; + client.retry_config.read_retries = retries; + } + client + } + /// Send the request using retries configured in the RetryConfig. /// If retry_5xx is false, 5xx requests will not be retried regardless of the statuses configured /// in the RetryConfig. @@ -963,6 +963,13 @@ impl RestfulLanceDbClient { return Err(source); } retry_counter.increment_request_failures(source)?; + if status.is_server_error() { + log::warn!( + "Retrying request {} after gateway status {}", + request_id, + status + ); + } } Err(err) if err.is_connect() => { retry_counter.increment_connect_failures(err)?; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 31808f244..b562f41df 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -31,7 +31,7 @@ use crate::job::Job; use crate::listing::{ListingOptions, ListingPage}; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::job::{PauseJobResponse, RemoteJob, ResumeJobResponse, job_state_to_client}; -use crate::remote::util::stream_as_body; +use crate::remote::util::create_body; use crate::secrets::SecretInfo; use crate::table::BaseTable; use crate::utils::{ @@ -1497,7 +1497,7 @@ impl Database for RemoteDatabase { } } let data_schema = request.data.schema(); - let body = stream_as_body(request.data.scan_as_stream())?; + let body = create_body(request.data.scan_as_stream()).await?; let identifier = build_table_identifier(&request.name, &request.namespace_path)?; let req = self @@ -2623,6 +2623,147 @@ mod tests { assert_eq!(table.name(), "table1"); } + #[tokio::test] + async fn test_create_table_over_budget_never_reaches_server() { + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + let mut bytes = vec![0u8; 8 * 1024 * 1024]; + SmallRng::seed_from_u64(42).fill_bytes(&mut bytes); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(arrow_array::LargeBinaryArray::from(vec![Some( + bytes.as_slice(), + )]))], + ) + .unwrap(); + for overwrite in [false, true] { + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |_| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + http::Response::builder().status(200).body("").unwrap() + }); + let input: Box = + Box::new(arrow_array::RecordBatchIterator::new( + (0..34).map(|_| Ok(batch.clone())).collect::>(), + batch.schema(), + )); + let mut create = conn.create_table("table1", input); + if overwrite { + create = create.mode(CreateTableMode::Overwrite); + } + let error = create.execute().await.unwrap_err(); + let message = error.to_string(); + assert!(message.contains("single-request budget"), "{message}"); + assert!( + message.contains("schema=") && message.contains("progress=True"), + "{message}" + ); + // The same assertion covers a new half-table and damage to an + // existing table under overwrite: neither mode sends a request. + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 0); + } + } + + #[tokio::test] + async fn test_create_table_slices_large_batches_in_one_atomic_request() { + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |request| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let bytes = request.body().unwrap().as_bytes().unwrap(); + let batches = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None) + .unwrap() + .collect::, _>>() + .unwrap(); + assert!(batches.len() > 1); + assert_eq!( + batches.iter().map(|b| b.num_rows()).sum::(), + 4_000_000 + ); + http::Response::builder().status(200).body("").unwrap() + }); + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from_iter_values(0..4_000_000))], + ) + .unwrap(); + conn.create_table("table1", input).execute().await.unwrap(); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_create_table_compacts_dictionary_slices_in_one_atomic_request() { + use arrow_array::{Array, DictionaryArray, StringArray, cast::AsArray, types::Int32Type}; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + + let mut bytes = vec![0; 128 * 72 * 1024]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(72 * 1024) + .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let mut batches = Vec::new(); + for values in [strings.clone(), strings.iter().rev().cloned().collect()] { + let dict = DictionaryArray::::new( + Int32Array::from_iter_values(0..128), + Arc::new(StringArray::from(values)), + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "category", + dict.data_type().clone(), + false, + )])); + batches.push(RecordBatch::try_new(schema, vec![Arc::new(dict)]).unwrap()); + } + let schema = batches[0].schema(); + let expected = strings + .iter() + .chain(strings.iter().rev()) + .cloned() + .collect::>(); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let wire_schema = schema.clone(); + let conn = Connection::new_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/table/table1/create/"); + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let body = request.body().unwrap().as_bytes().unwrap(); + let reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), wire_schema); + let batches = reader.collect::, _>>().unwrap(); + assert!( + (2..=8).contains(&batches.len()), + "dictionary produced {} encoding slices", + batches.len() + ); + let actual = batches + .iter() + .flat_map(|batch| { + let values = arrow_cast::cast(batch.column(0), &DataType::Utf8).unwrap(); + values + .as_string::() + .iter() + .map(|s| s.unwrap().to_owned()) + .collect::>() + }) + .collect::>(); + assert_eq!(actual, expected); + assert!(body.len() < 2 * bytes.len() + 64 * 1024); + http::Response::builder().status(200).body("").unwrap() + }); + let input: Box = Box::new( + arrow_array::RecordBatchIterator::new(batches.into_iter().map(Ok), schema), + ); + conn.create_table("table1", input).execute().await.unwrap(); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + } + #[tokio::test] async fn test_create_table_already_exists() { let conn = Connection::new_with_handler(|_| { diff --git a/rust/lancedb/src/remote/retry.rs b/rust/lancedb/src/remote/retry.rs index 51c9b2126..c0ef2bd11 100644 --- a/rust/lancedb/src/remote/retry.rs +++ b/rust/lancedb/src/remote/retry.rs @@ -63,7 +63,7 @@ impl<'a> RetryCounter<'a> { /// Increment the appropriate failure counter based on the error type. /// /// For `Error::Http` whose source is a connect error, increments - /// `connect_failures`. For read errors (`is_body` or `is_decode`), + /// `connect_failures`. For read errors (`is_timeout`, `is_body` or `is_decode`), /// increments `read_failures`. For all other errors, increments /// `request_failures`. Calls `check_out_of_retries` to enforce global limits. pub fn increment_from_error(&mut self, source: crate::Error) -> crate::Result<()> { @@ -74,7 +74,7 @@ impl<'a> RetryCounter<'a> { if reqwest_err.is_some_and(|e| e.is_connect()) { self.connect_failures += 1; - } else if reqwest_err.is_some_and(|e| e.is_body() || e.is_decode()) { + } else if reqwest_err.is_some_and(|e| e.is_timeout() || e.is_body() || e.is_decode()) { self.read_failures += 1; } else { self.request_failures += 1; @@ -187,6 +187,37 @@ mod tests { )); } + #[tokio::test] + async fn test_increment_from_error_read_timeout() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let _ = tokio::io::copy(&mut socket, &mut tokio::io::sink()).await; + }); + let err = reqwest::Client::builder() + .read_timeout(Duration::from_millis(100)) + .build() + .unwrap() + .get(format!("http://{address}/")) + .send() + .await + .unwrap_err(); + assert!(err.is_timeout() && !err.is_connect()); + let config = test_config(); + let mut counter = RetryCounter::new(&config, "part-1".into()); + counter + .increment_from_error(Error::Http { + request_id: "part-1".into(), + status_code: None, + source: Box::new(err), + }) + .unwrap(); + assert_eq!(counter.read_failures, 1); + assert_eq!(counter.request_failures, 0); + server.abort(); + } + #[test] fn test_increment_from_error_request() { let config = test_config(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 48e5652ae..cc495a83f 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5,6 +5,8 @@ pub mod blobs; pub mod insert; mod ipc_stream; mod optimize; +#[cfg(test)] +mod write_tests; use self::insert::{RemoteWriteExec, WriteOp}; use super::client::RequestResultExt; @@ -1420,13 +1422,18 @@ impl RemoteTable { Ok(bodies) } - async fn create_multipart_write(&self) -> Result { + async fn create_multipart_write(&self, retries: Option) -> Result { let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/multipart_write/create", self.identifier ))); - let (request_id, response) = self.send(request, true).await?; + let client = self.client.with_retries(retries); + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = client + .send_with_retry(freshness_request.apply(request), None, true) + .await?; let response = self.check_table_response(&request_id, response).await?; + freshness_request.observe_headers(&self.freshness, response.headers()); let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse multipart create response: {}", e).into(), @@ -1452,7 +1459,7 @@ impl RemoteTable { )) .query(&[("upload_id", upload_id)]), ); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self.send(request, false).await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { @@ -1468,7 +1475,7 @@ impl RemoteTable { Ok(AddResult { version }) } - async fn abort_multipart_write(&self, upload_id: &str) -> Result<()> { + async fn abort_multipart_write(&self, upload_id: &str, retries: Option) -> Result<()> { let request = self.apply_branch_query( self.client .post(&format!( @@ -1477,7 +1484,14 @@ impl RemoteTable { )) .query(&[("upload_id", upload_id)]), ); - let (request_id, response) = self.send(request, true).await?; + let freshness = self.snapshot_freshness_headers(); + let client = self.client.with_retries(retries); + let (request_id, response) = client + .send_with_retry(freshness.apply(request), None, true) + .await?; + if response.status().is_success() { + freshness.observe_headers(&self.freshness, response.headers()); + } self.check_table_response(&request_id, response).await?; Ok(()) } @@ -1975,43 +1989,96 @@ mod test_utils { } } +#[derive(Debug)] +struct UnknownWriteOutcome { + upload_id: String, + source: Error, +} + +impl std::fmt::Display for UnknownWriteOutcome { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Multipart write {} commit outcome unknown; no abort or replay was attempted. Check the table before retrying: {}", + self.upload_id, self.source + ) + } +} + +impl std::error::Error for UnknownWriteOutcome { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.source) + } +} + impl RemoteTable { fn is_retryable_write_error(&self, err: &Error) -> bool { + // Transaction conflicts and explicit rate limits reject the write. + // A gateway 5xx says nothing about whether its manifest was committed. + let safe_status = |status| { + matches!(status, StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + && self.client.retry_config.statuses.contains(&status) + }; match err { Error::Http { source, status_code, .. } => { - // Don't retry read errors (is_body/is_decode): the - // server may have committed the write already, and - // without an idempotency key we'd duplicate data. source .downcast_ref::() .is_some_and(|e| e.is_connect()) - || status_code.is_some_and(|s| self.client.retry_config.statuses.contains(&s)) - } - // send_with_retry exhausted its internal retries on a retryable - // status. The outer loop can still retry the whole operation with - // a fresh session. - Error::Retry { status_code, .. } => { - status_code.is_some_and(|s| self.client.retry_config.statuses.contains(&s)) + || status_code.is_some_and(safe_status) } + Error::Retry { status_code, .. } => status_code.is_some_and(safe_status), _ => false, } } + async fn send_write_request( + &self, + request: RequestBuilder, + freshness: FreshnessHeaders, + retries: Option, + ) -> Result<(String, Response)> { + let client = self.client.with_retries(retries); + let mut counter = crate::remote::retry::RetryCounter::new( + &client.retry_config, + uuid::Uuid::new_v4().to_string(), + ); + loop { + let req = request.try_clone().ok_or_else(|| Error::Runtime { + message: "Write request cannot be replayed".into(), + })?; + let result = async { + let (id, response) = client.send(freshness.apply(req)).await?; + let response = self.check_table_response(&id, response).await?; + freshness.observe_headers(&self.freshness, response.headers()); + Ok((id, response)) + } + .await; + match result { + Err(err) if self.is_retryable_write_error(&err) => { + counter.increment_from_error(err)?; + tokio::time::sleep(counter.next_sleep_time()).await; + } + result => return result, + } + } + } + async fn add_single_partition(&self, output: PreprocessingOutput) -> Result { use crate::remote::retry::RetryCounter; let _guard = output.tracker.as_ref().map(|t| t.track_task()); + let client = self.client.with_retries(output.retries); let freshness_request = self.snapshot_freshness_headers(); let mut insert: Arc = Arc::new( RemoteWriteExec::new( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client.clone(), output.plan, WriteOp::Insert { overwrite: output.overwrite, @@ -2026,7 +2093,7 @@ impl RemoteTable { ); let mut retry_counter = - RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); + RetryCounter::new(&client.retry_config, uuid::Uuid::new_v4().to_string()); loop { let stream = execute_plan(insert.clone(), Default::default())?; @@ -2062,61 +2129,82 @@ impl RemoteTable { output: PreprocessingOutput, num_partitions: usize, ) -> Result { - use crate::remote::retry::RetryCounter; - - let mut retry_counter = - RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); - - loop { - let freshness_request = self.snapshot_freshness_headers(); - let upload_id = self.create_multipart_write().await?; - - let result = self - .execute_multipart_inserts(&upload_id, &output, num_partitions) - .await; - - match result { - Ok(()) => match self.complete_multipart_write(&upload_id).await { - Ok(result) => { - if output.overwrite { - self.invalidate_schema_cache(); - } - self.track_write_version(freshness_request, result.version); - return Ok(result); + if let Some(tracker) = &output.tracker { + tracker.use_wire_bytes(); + } + let freshness_request = self.snapshot_freshness_headers(); + let upload_id = self.create_multipart_write(output.retries).await?; + if let Err(err) = self + .execute_multipart_inserts(&upload_id, &output, num_partitions) + .await + { + if let Err(abort_err) = self.abort_multipart_write(&upload_id, output.retries).await { + log::warn!( + "Failed to abort multipart write {}: {}", + upload_id, + abort_err + ); + } + return Err(err); + } + // A lost complete response can mean a successful commit. Neither repeat + // complete nor start a new upload session without a server commit token. + let result = match self.complete_multipart_write(&upload_id).await { + Ok(result) => result, + Err(err) => { + let (request_id, status_code) = match &err { + Error::Http { + request_id, + status_code, + .. } - Err(e) => { - if let Err(abort_err) = self.abort_multipart_write(&upload_id).await { - log::warn!( - "Failed to abort multipart write {}: {}", - upload_id, - abort_err - ); - } - if output.rescannable && self.is_retryable_write_error(&e) { - retry_counter.increment_from_error(e)?; - tokio::time::sleep(retry_counter.next_sleep_time()).await; - continue; - } - return Err(e); - } - }, - Err(e) => { - if let Err(abort_err) = self.abort_multipart_write(&upload_id).await { + | Error::Retry { + request_id, + status_code, + .. + } => (request_id.clone(), *status_code), + _ => return Err(err), + }; + // These responses positively reject the commit. Cleanup remains + // best effort and must not replace the original write error. + if matches!( + status_code, + Some(StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + ) { + if let Err(abort_err) = + self.abort_multipart_write(&upload_id, output.retries).await + { log::warn!( - "Failed to abort multipart write {}: {}", + "Failed to abort rejected multipart write {}: {}", upload_id, abort_err ); } - if output.rescannable && self.is_retryable_write_error(&e) { - retry_counter.increment_from_error(e)?; - tokio::time::sleep(retry_counter.next_sleep_time()).await; - continue; - } - return Err(e); + return Err(err); } + if status_code.is_some_and(|status| !status.is_server_error()) { + return Err(err); + } + log::warn!( + "Multipart write {} completion failed; commit outcome may be unknown: {}. Check the table before retrying.", + upload_id, + err + ); + return Err(Error::Http { + request_id, + status_code, + source: Box::new(UnknownWriteOutcome { + upload_id, + source: err, + }), + }); } + }; + if output.overwrite { + self.invalidate_schema_cache(); } + self.track_write_version(freshness_request, result.version); + Ok(result) } async fn execute_multipart_inserts( @@ -2125,10 +2213,7 @@ impl RemoteTable { output: &PreprocessingOutput, num_partitions: usize, ) -> Result<()> { - debug_assert!( - output.rescannable, - "multipart inserts require rescannable input for retry support" - ); + let client = self.client.with_retries(output.retries); let plan = Arc::new( datafusion_physical_plan::repartition::RepartitionExec::try_new( @@ -2141,7 +2226,7 @@ impl RemoteTable { RemoteWriteExec::new_multipart( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client, plan, output.overwrite, upload_id.to_string(), @@ -3000,6 +3085,7 @@ impl BaseTable for RemoteTable { crate::table::computed_columns::ensure_supported_function_metadata(table_schema.as_ref())?; let table_def = TableDefinition::try_from_rich_schema(table_schema.clone())?; + let mut use_multipart = false; let num_partitions = if self.server_version.support_multipart_write() { // Peek at the first batch to estimate write partitions (same as // NativeTable) and, regardless of `write_parallelism`, to detect a @@ -3012,20 +3098,29 @@ impl BaseTable for RemoteTable { // sends one schema-only request. let mut peeked = PeekedScannable::new(add.data); let n = match peeked.peek().await { - Some(first_batch) => match add.write_parallelism { - Some(parallelism) if parallelism > 1 => parallelism, - Some(_) => 1, - None => { - let max_partitions = - lance_core::utils::tokio::get_num_compute_intensive_cpus(); - estimate_write_partitions( - first_batch.get_array_memory_size(), - first_batch.num_rows(), - peeked.num_rows(), - max_partitions, - ) + Some(first_batch) => { + let estimated_bytes = peeked.num_rows().map(|rows| { + first_batch.get_array_memory_size().saturating_mul(rows) + / first_batch.num_rows().max(1) + }); + // Unknown-length streams also need bounded requests, even + // when they cannot be rescanned or only use one writer. + use_multipart = estimated_bytes.is_none_or(|bytes| bytes > 64 * 1024 * 1024); + match add.write_parallelism { + Some(parallelism) if parallelism > 1 => parallelism, + Some(_) => 1, + None => { + let max_partitions = + lance_core::utils::tokio::get_num_compute_intensive_cpus(); + estimate_write_partitions( + first_batch.get_array_memory_size(), + first_batch.num_rows(), + peeked.num_rows(), + max_partitions, + ) + } } - }, + } None => 1, }; add.data = Box::new(peeked); @@ -3041,7 +3136,7 @@ impl BaseTable for RemoteTable { } let _finish = FinishOnDrop(output.tracker.clone()); - if num_partitions > 1 { + if use_multipart || num_partitions > 1 { self.add_multipart(output, num_partitions).await } else { self.add_single_partition(output).await @@ -3278,7 +3373,7 @@ impl BaseTable for RemoteTable { let freshness_request = self.snapshot_freshness_headers(); let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) + .send_write_request(request, freshness_request, update.retries) .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3316,7 +3411,7 @@ impl BaseTable for RemoteTable { .json(&body); let freshness_request = self.snapshot_freshness_headers(); let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) + .send_write_request(request, freshness_request, None) .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3363,6 +3458,7 @@ impl BaseTable for RemoteTable { self.check_mutable().await?; let timeout = params.timeout; + let client = self.client.with_retries(params.retries); let query = MergeInsertRequest::try_from(params)?; // Drive merge_insert through the same RemoteWriteExec streaming path as @@ -3407,7 +3503,7 @@ impl BaseTable for RemoteTable { RemoteWriteExec::new( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client.clone(), input, WriteOp::MergeInsert { query, timeout }, None, @@ -3420,7 +3516,7 @@ impl BaseTable for RemoteTable { ); let mut retry_counter = crate::remote::retry::RetryCounter::new( - &self.client.retry_config, + &client.retry_config, uuid::Uuid::new_v4().to_string(), ); @@ -14748,41 +14844,116 @@ mod tests { } #[tokio::test] - async fn test_add_retries_on_retryable_status() { - // Verify that rescannable data retries on retryable status codes (e.g. 502) - // and eventually succeeds. - let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); - let describe_body = describe_response(&batch.schema()); - - let attempt = Arc::new(AtomicUsize::new(0)); - let attempt_clone = attempt.clone(); - - let table = - Table::new_with_handler("my_table", move |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_body.clone()) - .unwrap(), - "/v1/table/my_table/insert/" => { - let n = attempt_clone.fetch_add(1, Ordering::SeqCst); - if n < 2 { - http::Response::builder() - .status(502) - .body("bad gateway".to_string()) - .unwrap() - } else { - http::Response::builder() + async fn test_add_write_retry_policy_and_override() { + for status in [429, 500, 502, 503, 504] { + for retries in [None, Some(0)] { + let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let describe = describe_response(&batch.schema()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let table = Table::new_with_handler("my_table", move |req| { + if req.url().path().ends_with("describe/") { + return http::Response::builder() .status(200) - .body(r#"{"version": 3}"#.to_string()) - .unwrap() + .body(describe.clone()) + .unwrap(); } + let n = observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(if n == 0 { status } else { 200 }) + .body(r#"{"version":3}"#.to_string()) + .unwrap() + }); + let mut add = table.add(batch); + if let Some(retries) = retries { + add = add.retries(retries); } - path => panic!("Unexpected request path: {}", path), - }); + let result = add.execute().await; + let safe_retry = status == 429 && retries.is_none(); + assert_eq!( + result.is_ok(), + safe_retry, + "{status}, {retries:?}: {result:?}" + ); + assert_eq!( + attempts.load(Ordering::SeqCst), + if safe_retry { 2 } else { 1 } + ); + } + } + } - let result = table.add(batch).execute().await.unwrap(); - assert_eq!(result.version, 3); - assert_eq!(attempt.load(Ordering::SeqCst), 3); + #[tokio::test] + async fn test_mutations_do_not_replay_gateway_failures() { + for status in [500, 502, 503, 504] { + for op in ["update", "delete", "merge_insert"] { + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let describe = describe_response(&batch.schema()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let table = Table::new_with_handler("my_table", move |req| { + if req.url().path().ends_with("describe/") { + return http::Response::builder() + .status(200) + .body(describe.clone()) + .unwrap(); + } + assert!(req.url().path().contains(op)); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(status) + .body("gateway fault".to_string()) + .unwrap() + }); + let result = match op { + "update" => table + .update() + .column("id", "id + 1") + .execute() + .await + .map(|_| ()), + "delete" => table.delete("true").await.map(|_| ()), + _ => { + let reader = + RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let mut merge = table.merge_insert(&["id"]); + merge.when_not_matched_insert_all(); + merge.execute(Box::new(reader)).await.map(|_| ()) + } + }; + assert!(result.is_err(), "{op}, {status}"); + assert_eq!(attempts.load(Ordering::SeqCst), 1, "{op}, {status}"); + } + } + } + + #[test] + fn test_write_retry_policy_for_both_error_variants() { + let table = RemoteTable::new_mock_with_config( + "my_table".into(), + |_| http::Response::builder().body("").unwrap(), + ClientConfig { + retry_config: RetryConfig { + retries: Some(1), + statuses: Some(vec![429, 500, 502, 503, 504]), + ..Default::default() + }, + ..Default::default() + }, + ); + for status in [429, 500, 502, 503, 504] { + let err = Error::Http { + request_id: "test".into(), + status_code: Some(StatusCode::from_u16(status).unwrap()), + source: "gateway response".into(), + }; + assert_eq!(table.is_retryable_write_error(&err), status == 429); + let mut counter = + crate::remote::retry::RetryCounter::new(&table.client.retry_config, "test".into()); + let exhausted = counter.increment_request_failures(err).unwrap_err(); + assert!(matches!(exhausted, Error::Retry { .. })); + assert_eq!(table.is_retryable_write_error(&exhausted), status == 429); + } } #[tokio::test] @@ -14931,7 +15102,7 @@ mod tests { let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap(); let result = table - .add(vec![batch]) + .add(vec![batch.clone(), batch]) .write_parallelism(2) .execute() .await @@ -15335,7 +15506,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_write_abort_on_complete_failure() { + async fn test_multipart_write_does_not_abort_on_complete_failure() { let abort_count = Arc::new(AtomicUsize::new(0)); let abort_count_c = abort_count.clone(); @@ -15386,7 +15557,7 @@ mod tests { let result = table.add(vec![batch]).write_parallelism(2).execute().await; assert!(result.is_err()); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); } fn retry_config_no_backoff() -> ClientConfig { @@ -15405,9 +15576,9 @@ mod tests { #[tokio::test] async fn test_multipart_write_retry_on_partition_failure() { - // All inserts for the first upload session return 503 (retryable). - // After exhausting internal retries, the outer loop retries with a - // new session and succeeds. + // A staging failure is retried in the same upload session. + let insert_count = Arc::new(AtomicUsize::new(0)); + let insert_count_c = insert_count.clone(); let create_count = Arc::new(AtomicUsize::new(0)); let complete_count = Arc::new(AtomicUsize::new(0)); let abort_count = Arc::new(AtomicUsize::new(0)); @@ -15435,7 +15606,9 @@ mod tests { if path == "/v1/table/my_table/insert/" { // Fail all inserts for the first session - if query.contains("upload_id=upload-1") { + assert!(query.contains("upload_id=upload-1")); + assert!(query.contains("upload_part_id=")); + if insert_count_c.fetch_add(1, Ordering::SeqCst) == 0 { return http::Response::builder() .status(503) .body("Service Unavailable".to_string()) @@ -15477,14 +15650,16 @@ mod tests { .unwrap(); assert_eq!(result.version, 7); - assert_eq!(create_count.load(Ordering::SeqCst), 2); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert_eq!(create_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); assert_eq!(complete_count.load(Ordering::SeqCst), 1); } #[tokio::test] - async fn test_multipart_write_retry_on_complete_failure() { - // Complete returns 503 for the first session, succeeds for the second. + async fn test_multipart_complete_unknown_outcome_never_aborts_or_replays() { + // A gateway failure may hide a committed write. No abort or replay is safe. + let complete_count = Arc::new(AtomicUsize::new(0)); + let complete_count_c = complete_count.clone(); let create_count = Arc::new(AtomicUsize::new(0)); let abort_count = Arc::new(AtomicUsize::new(0)); @@ -15516,6 +15691,7 @@ mod tests { } if path == "/v1/table/my_table/multipart_write/complete" { + complete_count_c.fetch_add(1, Ordering::SeqCst); // Fail complete for first session if query.contains("upload_id=upload-1") { return http::Response::builder() @@ -15548,11 +15724,12 @@ mod tests { .write_parallelism(2) .execute() .await - .unwrap(); + .unwrap_err(); - assert_eq!(result.version, 9); - assert_eq!(create_count.load(Ordering::SeqCst), 2); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert!(result.to_string().contains("commit outcome unknown")); + assert_eq!(complete_count.load(Ordering::SeqCst), 1); + assert_eq!(create_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); } // ---- Read freshness header tests ------------------------------------ diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index ebae823e1..0de1c21cc 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -17,7 +17,7 @@ use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, }; -use futures::{SinkExt, StreamExt}; +use futures::StreamExt; use http::header::CONTENT_TYPE; use lance::io::exec::utils::InstrumentedRecordBatchStreamAdapter; @@ -268,6 +268,17 @@ impl RemoteWriteExec { error_tx: tokio::sync::oneshot::Sender, tracker: Option>, ) -> DataFusionResult { + let data: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new( + data.schema(), + data.flat_map(|batch| match batch { + Ok(batch) => futures::stream::iter( + crate::remote::util::split_batch(batch, crate::remote::util::IPC_BATCH_BYTES) + .map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }), + )); let options = arrow_ipc::writer::IpcWriteOptions::default() .try_with_compression(Some(CompressionType::LZ4_FRAME))?; let writer = arrow_ipc::writer::StreamWriter::try_new_with_options( @@ -347,55 +358,55 @@ impl PartRequestCtx<'_, S> { /// whenever the current one reaches `max_bytes` (Arrow IPC, compressed) or /// has been uploading for `max_duration`, whichever comes first. /// - /// Each part is a separate `/insert?upload_id=...&upload_part_id=...` request - /// whose body is still streamed through a bounded channel, so peak memory - /// stays at a couple of batches regardless of `max_bytes`. The server stages - /// every part under the shared `upload_id` and merges them atomically when - /// the caller completes the multipart write. An empty partition stages - /// nothing: the multipart write always has at least one non-empty partition - /// to commit. + /// Each part has a fixed IPC body and transaction ID. A retry replaces the + /// same staged transaction instead of adding another part. Only the final + /// complete request makes staged rows visible. Parts are prepared on demand; + /// the target does not bound memory retained by input or ancestor buffers. /// - /// The byte budget targets a good on-disk fragment size; the duration budget - /// bounds request time so a slow or throttled upload does not keep a request - /// open past the client read timeout (which also covers the request body). + /// The duration budget limits payload preparation time; HTTP timeouts are + /// handled by retrying the prepared payload. async fn send_multipart_chunked( &self, max_bytes: u64, max_duration: Option, - mut input: SendableRecordBatchStream, + input: SendableRecordBatchStream, tracker: Option>, ) -> DataFusionResult<()> { let schema = input.schema(); + let max_batch_bytes = (max_bytes as usize).clamp(1, crate::remote::util::IPC_BATCH_BYTES); + let stream = input.flat_map(move |batch| match batch { + Ok(batch) => futures::stream::iter( + crate::remote::util::split_batch(batch, max_batch_bytes) + .map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }); + let mut input: SendableRecordBatchStream = + Box::pin(RecordBatchStreamAdapter::new(schema.clone(), stream)); - // A part always starts from a batch we already hold: the first batch of - // the partition, or the look-ahead batch from the previous part. This - // keeps empty partitions from staging a part and stops a size cut that - // lands exactly on the end of input from emitting a trailing empty part. - let mut first = match input.next().await { - Some(batch) => batch?, - None => return Ok(()), - }; - + let mut pending = std::collections::VecDeque::new(); loop { - let input_ended = self + let first = match pending.pop_front() { + Some(batch) => batch, + None => match input.next().await { + Some(batch) => batch?, + None => break, + }, + }; + if self .send_one_part( - &schema, max_bytes, max_duration, first, &mut input, + &mut pending, &tracker, ) - .await?; - - if input_ended { + .await? + { break; } - - first = match input.next().await { - Some(batch) => batch?, - None => break, - }; } Ok(()) @@ -431,143 +442,137 @@ impl PartRequestCtx<'_, S> { &self, request: reqwest::RequestBuilder, freshness_request: Option, - ) -> DataFusionResult<()> { - let (request_id, response) = self - .client - .send(request) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; + ) -> crate::Result<()> { + let (request_id, response) = self.client.send(request).await?; let response = RemoteTable::::handle_table_not_found(self.table_name, response, &request_id) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let response = self - .client - .check_response(&request_id, response) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; + .await?; + let response = self.client.check_response(&request_id, response).await?; self.freshness .observe(freshness_request, response.headers()); - response.bytes().await.map_err(|e| { - DataFusionError::External(Box::new(Error::Http { - source: Box::new(e), - request_id: request_id.clone(), - status_code: None, - })) + response.bytes().await.map_err(|e| Error::Http { + source: Box::new(e), + request_id: request_id.clone(), + status_code: None, })?; Ok(()) } - /// Stream one part, starting from `first` and pulling from `input` until the - /// part reaches `max_bytes`, has been uploading for `max_duration`, or the - /// input ends. The body is streamed through a bounded channel concurrently - /// with the request, so peak memory stays at a couple of batches. Wire bytes - /// are recorded on `tracker` as each chunk is produced, so progress advances - /// smoothly rather than jumping once per completed part. Returns whether the - /// input was exhausted while filling this part. + /// Encode each part before sending so a lost staging response can be retried + /// with exactly the same transaction ID and bytes. async fn send_one_part( &self, - schema: &arrow_schema::SchemaRef, max_bytes: u64, max_duration: Option, first: RecordBatch, input: &mut SendableRecordBatchStream, + queued: &mut std::collections::VecDeque, tracker: &Option>, ) -> DataFusionResult { - let (mut chunk_tx, chunk_rx) = - futures::channel::mpsc::channel::, std::io::Error>>(2); - let body = reqwest::Body::wrap_stream(chunk_rx); - - let part_id = uuid::Uuid::new_v4().to_string(); - let (request, freshness_request) = self.build_part_request(&part_id, body); - - // Measured from just before the request is sent, matching the window the - // client read timeout applies to the upload. + let schema = input.schema(); + let options = arrow_ipc::writer::IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME))?; + let mut writer = arrow_ipc::writer::StreamWriter::try_new_with_options( + Vec::new(), + &schema, + options.clone(), + )?; let started = Instant::now(); - let tracker = tracker.clone(); - // Unlike `stream_as_http_body`, this producer also cuts the part at the - // byte/time budget and reports back whether the input ended, so it drives - // its own bounded mpsc channel joined with the request instead of reusing - // that helper. - let producer = async move { - let options = arrow_ipc::writer::IpcWriteOptions::default() - .try_with_compression(Some(CompressionType::LZ4_FRAME)) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let mut writer = - arrow_ipc::writer::StreamWriter::try_new_with_options(Vec::new(), schema, options) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - - let mut part_bytes: u64 = 0; - let mut input_ended = false; - let mut pending = Some(first); - loop { - let batch = match pending.take() { - Some(batch) => batch, - None => match input.next().await { - Some(Ok(batch)) => batch, - Some(Err(e)) => { - // Abort the body so the server does not treat the - // truncated stream as a successful write; the - // original error is surfaced to the caller. - let _ = chunk_tx - .send(Err(std::io::Error::other("input stream error"))) - .await; - return Err(e); - } - None => { - input_ended = true; - break; - } - }, - }; - writer - .write(&batch) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let chunk = std::mem::take(writer.get_mut()); - let chunk_len = chunk.len(); - part_bytes += chunk_len as u64; - if chunk_tx.send(Ok(chunk)).await.is_err() { - // The request finished or failed; stop producing. + let mut pending = Some(first); + let mut has_batch = false; + let mut input_ended = false; + loop { + let batch = match pending.take().or_else(|| queued.pop_front()) { + Some(batch) => batch, + None => match input.next().await { + Some(batch) => batch?, + None => { + input_ended = true; + break; + } + }, + }; + let before = writer.get_ref().len(); + writer.write(&batch)?; + // Reserve the EOS marker. A rejected batch starts a fresh stream, + // so its dictionary messages are encoded again with fresh state. + if (writer.get_ref().len() as u64).saturating_add(8) > max_bytes { + if has_batch { + writer.get_mut().truncate(before); + queued.push_front(batch); break; } - if let Some(ref t) = tracker { - t.record_bytes(chunk_len); - } - if part_bytes >= max_bytes - || max_duration.is_some_and(|limit| started.elapsed() >= limit) - { - break; + if batch.num_rows() > 1 { + let middle = batch.num_rows() / 2; + queued.push_front(crate::remote::util::compact_batch_dictionaries( + batch.slice(middle, batch.num_rows() - middle), + )?); + pending = Some(crate::remote::util::compact_batch_dictionaries( + batch.slice(0, middle), + )?); + writer = arrow_ipc::writer::StreamWriter::try_new_with_options( + Vec::new(), + &schema, + options.clone(), + )?; + continue; } + // A single row and its schema cannot be split further. } - - writer - .finish() - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let tail = std::mem::take(writer.get_mut()); - if !tail.is_empty() { - let tail_len = tail.len(); - if chunk_tx.send(Ok(tail)).await.is_ok() - && let Some(ref t) = tracker - { - t.record_bytes(tail_len); - } + has_batch = true; + if writer.get_ref().len() as u64 >= max_bytes + || max_duration.is_some_and(|limit| started.elapsed() >= limit) + { + break; } - Ok::(input_ended) - }; + } + writer.finish()?; + let body = bytes::Bytes::from(writer.into_inner()?); + let part_id = uuid::Uuid::new_v4().to_string(); + let mut retries = + crate::remote::retry::RetryCounter::new(&self.client.retry_config, part_id.clone()); + loop { + let (request, freshness) = self.build_part_request(&part_id, body.clone().into()); + match self.send_part_request(request, freshness).await { + Ok(()) => { + if let Some(tracker) = tracker { + tracker.record_bytes(body.len()); + } + return Ok(input_ended); + } + Err(err) if retryable_part_error(&err, &self.client.retry_config.statuses) => { + let cause = err.to_string(); + retries + .increment_from_error(err) + .map_err(|err| DataFusionError::External(Box::new(err)))?; + log::warn!( + "Retrying multipart upload {} part {} after {}; reusing the same payload", + self.upload_id, + part_id, + cause + ); + tokio::time::sleep(retries.next_sleep_time()).await; + } + Err(err) => return Err(DataFusionError::External(Box::new(err))), + } + } + } +} - let send = self.send_part_request(request, freshness_request); - - // `join!` rather than `tokio::spawn`: the producer borrows `input` (and - // `schema`), so it cannot satisfy the `'static` bound a spawned task - // needs. Running both futures on this task lets them make progress - // concurrently without that constraint. - let (producer_result, send_result) = futures::join!(producer, send); - // Prefer the producer error (e.g. NaN rejection) over any HTTP error it - // induced. - let input_ended = producer_result?; - send_result?; - - Ok(input_ended) +fn retryable_part_error(err: &Error, statuses: &[reqwest::StatusCode]) -> bool { + match err { + Error::Http { + status_code: Some(status), + .. + } => statuses.contains(status), + Error::Http { source, .. } => source.downcast_ref::().is_some_and(|err| { + err.is_connect() + || err.is_timeout() + || err.is_body() + || err.is_decode() + || err.is_request() + }), + _ => false, } } @@ -697,13 +702,10 @@ impl ExecutionPlan for RemoteWriteExec { let max_request_duration = self.max_request_duration; let stream = futures::stream::once(async move { - // Multipart writes with a byte budget split the partition into - // several bounded, still-streamed requests so no single request - // stays open long enough to hit the client read timeout. This path - // is insert-only (guarded above). - if let (Some(upload_id), Some(max_bytes)) = - (upload_id.as_deref(), max_bytes_per_request) - { + // Multipart payloads remain replayable even when byte-based cuts + // are disabled. Single-request writes never replay ambiguous errors. + if let Some(upload_id) = upload_id.as_deref() { + let max_bytes = max_bytes_per_request.unwrap_or(u64::MAX); let overwrite = matches!(op, WriteOp::Insert { overwrite: true }); let ctx = PartRequestCtx { client: &client, @@ -1220,7 +1222,7 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - // A 1-byte budget forces every batch into its own part. + // A 1-byte budget forces every row into its own part. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1237,7 +1239,102 @@ mod tests { let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); while stream.next().await.transpose().unwrap().is_some() {} - assert_eq!(insert_count.load(Ordering::SeqCst), 3); + assert_eq!(insert_count.load(Ordering::SeqCst), 6); + } + + #[tokio::test] + async fn test_multipart_respects_disabled_status_retries() { + use futures::StreamExt; + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let mut client = crate::remote::client::test_utils::client_with_handler(move |_| { + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(503) + .body("unavailable") + .unwrap() + }); + client.retry_config.statuses.clear(); + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let input = input_plan_from_batches(batch.schema(), vec![batch]).await; + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(64 * 1024 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + assert!(stream.next().await.unwrap().is_err()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_multipart_splits_one_batch_within_encoded_byte_budget() { + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + let mut bytes = vec![0; 128 * 1024]; + SmallRng::seed_from_u64(7).fill_bytes(&mut bytes); + let values = arrow_array::LargeBinaryArray::from_iter_values(bytes.chunks_exact(1024)); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + false, + )])); + let input = input_plan_from_batches( + schema.clone(), + vec![arrow_array::RecordBatch::try_new(schema, vec![Arc::new(values)]).unwrap()], + ) + .await; + let decoded = Arc::new(Mutex::new(Vec::new())); + let observed = decoded.clone(); + let requests = Arc::new(AtomicUsize::new(0)); + let count = requests.clone(); + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + assert!( + body.len() <= 16 * 1024, + "encoded part exceeded its budget: {}", + body.len() + ); + let reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + let mut decoded = observed.lock().unwrap(); + for batch in reader { + let batch = batch.unwrap(); + let values = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + for value in values.iter() { + decoded.extend_from_slice(value.unwrap()); + } + } + count.fetch_add(1, Ordering::SeqCst); + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert!(requests.load(Ordering::SeqCst) > 1); + assert_eq!(*decoded.lock().unwrap(), bytes); } #[tokio::test] @@ -1376,7 +1473,7 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - // A 1-byte budget forces every batch into its own part. + // A 1-byte budget forces every row into its own part. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1394,13 +1491,13 @@ mod tests { while stream.next().await.transpose().unwrap().is_some() {} let ids = part_ids.lock().unwrap().clone(); - assert_eq!(ids.len(), 3, "expected one part id per part: {ids:?}"); + assert_eq!(ids.len(), 6, "expected one part id per part: {ids:?}"); assert!( ids.iter().all(|id| !id.is_empty()), "part ids must be non-empty: {ids:?}" ); let unique: HashSet<&String> = ids.iter().collect(); - assert_eq!(unique.len(), 3, "part ids must be distinct: {ids:?}"); + assert_eq!(unique.len(), 6, "part ids must be distinct: {ids:?}"); } #[tokio::test] @@ -1446,8 +1543,8 @@ mod tests { while stream.next().await.transpose().unwrap().is_some() {} } - // 2 parts from partition 0 + 1 part from partition 1. - assert_eq!(insert_count.load(Ordering::SeqCst), 3); + // 4 single-row parts from partition 0 + 2 from partition 1. + assert_eq!(insert_count.load(Ordering::SeqCst), 6); } #[tokio::test] @@ -1551,7 +1648,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_records_progress_within_a_part() { + async fn test_multipart_records_acknowledged_bytes() { use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; use futures::StreamExt; @@ -1577,9 +1674,7 @@ mod tests { })); let tracker = Arc::new(WriteProgressTracker::new(callback, None)); - // A large byte budget keeps all three batches in one part; smooth - // progress therefore requires bytes to be reported per chunk rather than - // once when the part completes. + // Count encoded bytes once when the part is acknowledged. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1603,8 +1698,8 @@ mod tests { ); let observed = observed.lock().unwrap(); assert!( - observed.len() > 1, - "expected multiple incremental progress updates within the part: {observed:?}" + observed.len() == 1, + "expected one progress update per acknowledged part: {observed:?}" ); assert!( observed.windows(2).all(|w| w[1] >= w[0]), @@ -1615,4 +1710,454 @@ mod tests { "final progress should report bytes: {observed:?}" ); } + #[tokio::test] + async fn test_multipart_nested_dictionary_values_and_retries() { + use arrow_array::{ + Array, ArrayRef, BinaryArray, DictionaryArray, ListArray, RecordBatch, StructArray, + UInt8Array, types::UInt8Type, + }; + use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; + use arrow_cast::cast; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + use std::collections::HashMap; + + let mut bytes = vec![0; 128 * 1024]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let mut batches = Vec::new(); + for shift in [0, 1] { + let values = BinaryArray::from_iter( + std::iter::once(None).chain(bytes.chunks_exact(1024).skip(shift).map(Some)), + ); + let keys = UInt8Array::from(vec![ + Some(120), + Some(1), + None, + Some(1), + Some(2), + Some(0), + Some(3), + Some(4), + ]); + let dict = Arc::new(DictionaryArray::::new(keys, Arc::new(values))); + let field = Arc::new( + Field::new("category", dict.data_type().clone(), true) + .with_metadata(HashMap::from([("field-meta".into(), "retained".into())])), + ); + let entries = StructArray::new(vec![field].into(), vec![dict], None); + let list = ListArray::new( + Arc::new(Field::new_list_field(entries.data_type().clone(), false)), + OffsetBuffer::new(ScalarBuffer::from(vec![0, 1, 3, 5, 6, 6, 8])), + Arc::new(entries), + Some(NullBuffer::from(vec![true, true, true, true, false, true])), + ); + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![Field::new("categories", list.data_type().clone(), true)], + HashMap::from([("schema-meta".into(), "retained".into())]), + )); + // The discarded first row references a large, otherwise unused value. + batches.push( + RecordBatch::try_new(schema, vec![Arc::new(list)]) + .unwrap() + .slice(1, 5), + ); + } + let schema = batches[0].schema(); + let plain_type = DataType::List(Arc::new(Field::new_list_field( + DataType::Struct( + vec![ + Field::new("category", DataType::Binary, true) + .with_metadata(HashMap::from([("field-meta".into(), "retained".into())])), + ] + .into(), + ), + false, + ))); + let expected: Vec = batches + .iter() + .map(|b| cast(b.column(0), &plain_type).unwrap()) + .collect(); + let expected = + arrow_select::concat::concat(&expected.iter().map(|a| a.as_ref()).collect::>()) + .unwrap(); + let input = input_plan_from_batches(schema.clone(), batches).await; + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = requests.clone(); + let mut client = crate::remote::client::test_utils::client_with_handler(move |request| { + let query: HashMap<_, _> = request.url().query_pairs().into_owned().collect(); + assert_eq!(query["upload_id"], "upload-1"); + let body = request.body().unwrap().as_bytes().unwrap().to_vec(); + let mut requests = observed.lock().unwrap(); + requests.push((query["upload_part_id"].clone(), body)); + http::Response::builder() + .status(if requests.len() == 1 { 503 } else { 200 }) + .body("{}") + .unwrap() + }); + client.retry_config.backoff_factor = 0.0; + client.retry_config.backoff_jitter = 0.0; + use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; + let acknowledged = Arc::new(AtomicUsize::new(0)); + let acknowledged_c = acknowledged.clone(); + let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { + acknowledged_c.store(p.output_bytes(), Ordering::SeqCst); + })); + let tracker = Arc::new(WriteProgressTracker::new(callback, None)); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + Some(tracker), + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + let requests = requests.lock().unwrap(); + assert!(requests.len() >= 2); + assert_eq!( + requests[0], requests[1], + "retry must reuse part id and encoded bytes" + ); + let mut decoded = Vec::new(); + for (_, body) in &requests[1..] { + assert!(body.len() <= 16 * 1024, "part size: {}", body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + for batch in reader { + decoded.push(cast(batch.unwrap().column(0), &plain_type).unwrap()); + } + } + let actual = + arrow_select::concat::concat(&decoded.iter().map(|a| a.as_ref()).collect::>()) + .unwrap(); + assert_eq!(actual.as_ref(), expected.as_ref()); + let total: usize = requests[1..].iter().map(|(_, b)| b.len()).sum(); + assert_eq!(acknowledged.load(Ordering::SeqCst), total); + assert!( + total < 16 * 1024, + "unused dictionary values leaked: {total}" + ); + } + + #[rstest::rstest] + #[case(false, "linear", 1024)] + #[case(true, "linear", 1024)] + #[case(false, "linear", 1000)] + #[case(true, "linear", 1000)] + #[case(false, "nested", 1024)] + #[case(true, "nested", 1024)] + #[case(false, "sharing", 1024)] + #[case(true, "sharing", 1024)] + #[case(false, "empty", 1024)] + #[case(true, "empty", 1024)] + #[tokio::test] + async fn test_multipart_list_view_dictionary_ranges( + #[case] large: bool, + #[case] layout: &str, + #[case] value_bytes: usize, + ) { + if large { + check_list_view_dictionary_ranges::(layout, value_bytes).await; + } else { + check_list_view_dictionary_ranges::(layout, value_bytes).await; + } + } + + async fn check_list_view_dictionary_ranges( + layout: &str, + value_bytes: usize, + ) { + use arrow_array::{ + Array, ArrayRef, DictionaryArray, GenericListViewArray, Int32Array, ListArray, + RecordBatch, StringArray, StructArray, cast::AsArray, types::Int32Type, + }; + use arrow_buffer::{NullBuffer, OffsetBuffer}; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + use std::collections::HashMap; + + let mut bytes = vec![0; 128 * value_bytes]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(value_bytes) + .map(|c| c.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let mut expected = Vec::new(); + let mut batches = Vec::new(); + let nested = layout != "linear"; + for reverse in [false, true] + .into_iter() + .take(if layout == "nested" { 2 } else { 1 }) + { + let values: Vec<_> = if reverse { + strings.iter().rev().cloned().collect() + } else { + strings.clone() + }; + let keys: Vec = (0..128) + .map(|i| if layout == "sharing" { i % 2 } else { i }) + .collect(); + // A sliced child has its own nonzero physical offset. + let dict = DictionaryArray::::new( + Int32Array::from_iter_values(std::iter::once(127).chain(keys.iter().copied())), + Arc::new(StringArray::from(values.clone())), + ) + .slice(1, 128); + let mut offsets = Vec::new(); + let mut sizes = Vec::new(); + let mut valid = Vec::new(); + let start = usize::from(layout == "nested"); + for row in 0..128 + start { + let (offset, size, is_valid) = match layout { + "empty" if row % 2 == 0 => (80, 48, false), + "empty" => (128, 0, true), + "nested" if row % 17 == 0 => (80, 48, false), + "nested" if row % 13 == 0 => (128, 0, true), + "nested" => (4 + (row * 7) % 64, 3, true), + "sharing" => (4 + (row % 2) * 4, 64, true), + _ => (row, 1, true), + }; + offsets.push(O::from_usize(offset).unwrap()); + sizes.push(O::from_usize(size).unwrap()); + valid.push(is_valid); + if row >= start { + expected.push(is_valid.then(|| { + (offset..offset + size) + .map(|i| values[keys[i] as usize].clone()) + .collect::>() + })); + } + } + let item = Arc::new( + Field::new("category", dict.data_type().clone(), false) + .with_metadata(HashMap::from([("item-meta".into(), "retained".into())])), + ); + let views = GenericListViewArray::::new( + item, + offsets.into(), + sizes.into(), + Arc::new(dict), + Some(NullBuffer::from(valid)), + ); + let view_count = views.len(); + let column: ArrayRef = if nested { + let field = Arc::new(Field::new("views", views.data_type().clone(), true)); + let entries = StructArray::new(vec![field].into(), vec![Arc::new(views)], None); + Arc::new(ListArray::new( + Arc::new(Field::new_list_field(entries.data_type().clone(), false)), + OffsetBuffer::from_lengths(std::iter::repeat_n(1, view_count)), + Arc::new(entries), + None, + )) + } else { + Arc::new(views) + }; + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![Field::new("categories", column.data_type().clone(), true)], + HashMap::from([("schema-meta".into(), "retained".into())]), + )); + batches.push( + RecordBatch::try_new(schema, vec![column]) + .unwrap() + .slice(start, 128), + ); + } + let schema = batches[0].schema(); + let logical_bytes: usize = expected.iter().flatten().flatten().map(String::len).sum(); + let input = input_plan_from_batches(schema.clone(), batches).await; + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let decoded = Arc::new(Mutex::new(Vec::new())); + let decoded_c = decoded.clone(); + let sharing = layout == "sharing"; + let empty = layout == "empty"; + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + observed.lock().unwrap().push(body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + for batch in reader { + let batch = batch.unwrap(); + for row in 0..batch.num_rows() { + let column = if nested { + batch + .column(0) + .as_list::() + .value(row) + .as_struct() + .column(0) + .slice(0, 1) + } else { + batch.column(0).slice(row, 1) + }; + let views = column + .as_any() + .downcast_ref::>() + .unwrap(); + if empty { + assert_eq!(views.values().len(), 0, "null/empty views retain no child"); + } + if sharing { + assert_eq!( + views.values().len(), + 68, + "overlapping ranges must share their child" + ); + } + decoded_c.lock().unwrap().push(if views.is_null(0) { + None + } else { + let value = arrow_cast::cast(&views.value(0), &DataType::Utf8).unwrap(); + Some( + value + .as_string::() + .iter() + .map(|v| v.unwrap().to_owned()) + .collect::>(), + ) + }); + } + } + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert_eq!(*decoded.lock().unwrap(), expected); + let lengths = lengths.lock().unwrap(); + let total: usize = lengths.iter().sum(); + eprintln!( + "ListView IPC: large={}, layout={layout}, value_bytes={value_bytes}, parts={}, first={}, total={total}", + O::IS_LARGE, + lengths.len(), + lengths[0] + ); + // Every selected row in these cases fits the target, including IPC framing. + assert!( + lengths.iter().all(|n| *n <= 16 * 1024), + "oversized parts: {lengths:?}" + ); + assert!( + total <= (2 * logical_bytes).max(16 * 1024), + "dictionary upload amplified: {total}" + ); + if sharing { + assert_eq!(lengths.len(), 1); + } + } + + #[rstest::rstest] + #[case(1024, false)] + // Dictionary data fits the target; IPC framing forces the sender to split again. + #[case(1000, false)] + #[case(1024, true)] + #[case(20 * 1024, false)] + #[tokio::test] + async fn test_multipart_dictionary_payload_is_not_repeated_per_row( + #[case] value_bytes: usize, + #[case] use_views: bool, + ) { + use arrow_array::{ + Array, ArrayRef, DictionaryArray, Int32Array, RecordBatch, StringArray, + StringViewArray, types::Int32Type, + }; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + + let mut bytes = vec![0; 128 * value_bytes]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(value_bytes) + .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let values: ArrayRef = if use_views { + Arc::new(StringViewArray::from_iter_values(&strings)) + } else { + Arc::new(StringArray::from(strings.clone())) + }; + let array = + DictionaryArray::::try_new(Int32Array::from_iter_values(0..128), values) + .unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "category", + array.data_type().clone(), + false, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap(); + let input = input_plan_from_batches(schema.clone(), vec![batch]).await; + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let decoded = Arc::new(Mutex::new(Vec::new())); + let decoded_c = decoded.clone(); + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + observed.lock().unwrap().push(body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + let mut rows = 0; + for batch in reader { + let batch = batch.unwrap(); + rows += batch.num_rows(); + let values = arrow_cast::cast(batch.column(0), &DataType::Utf8).unwrap(); + let values = values.as_any().downcast_ref::().unwrap(); + decoded_c + .lock() + .unwrap() + .extend(values.iter().map(|v| v.unwrap().to_owned())); + } + assert!( + body.len() <= 16 * 1024 || rows == 1, + "oversized divisible part: {} bytes, {rows} rows", + body.len() + ); + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert_eq!(*decoded.lock().unwrap(), strings); + let lengths = lengths.lock().unwrap(); + let total: usize = lengths.iter().sum(); + eprintln!( + "dictionary IPC: value_bytes={value_bytes}, views={use_views}, parts={}, first={}, total={total}", + lengths.len(), + lengths[0] + ); + assert!( + total <= 2 * bytes.len(), + "dictionary upload amplified: parts={}, first={}, total={total}", + lengths.len(), + lengths[0] + ); + } } diff --git a/rust/lancedb/src/remote/table/write_tests.rs b/rust/lancedb/src/remote/table/write_tests.rs new file mode 100644 index 000000000..c97619af1 --- /dev/null +++ b/rust/lancedb/src/remote/table/write_tests.rs @@ -0,0 +1,436 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Real HTTP faults with a local Lance table behind the staging fixture. This +//! exercises SDK behavior; it does not model Sophon's asynchronous txn cleanup. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{LargeBinaryArray, RecordBatch}; +use arrow_ipc::reader::StreamReader; +use arrow_schema::{DataType, Field, Schema}; +use lance::arrow::json::JsonSchema; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use super::RemoteTable; +use crate::remote::client::{ClientConfig, RestfulLanceDbClient, RetryConfig, TimeoutConfig}; +use crate::remote::db::ServerVersion; +use crate::table::AddDataBuilder; + +#[derive(Clone, Copy, Debug)] +enum Fault { + Close, + Timeout, + Status(u16), +} + +#[derive(Default)] +struct State { + creates: usize, + completes: usize, + aborts: usize, + attempts: Vec<(String, Vec)>, + parts: HashMap>, +} + +async fn read_request(socket: &mut tokio::net::TcpStream) -> (String, Vec) { + let mut header = Vec::new(); + while !header.ends_with(b"\r\n\r\n") { + header.push(socket.read_u8().await.unwrap()); + assert!(header.len() < 64 * 1024); + } + let header = String::from_utf8(header).unwrap(); + let path = header.split_whitespace().nth(1).unwrap().to_owned(); + let length = header + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().unwrap()) + }) + .unwrap_or(0); + assert!( + !header + .to_ascii_lowercase() + .contains("transfer-encoding: chunked") + ); + let mut body = vec![0; length]; + socket.read_exact(&mut body).await.unwrap(); + (path, body) +} + +async fn respond(socket: &mut tokio::net::TcpStream, status: u16, body: &str) { + let response = format!( + "HTTP/1.1 {status} Result\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; +} + +#[tokio::test] +async fn multipart_http_faults_preserve_committed_blob_payloads() { + for complete_fault in [false, true] { + for fault in [ + Fault::Close, + Fault::Timeout, + Fault::Status(500), + Fault::Status(502), + Fault::Status(503), + Fault::Status(504), + ] { + let dir = tempfile::tempdir().unwrap(); + let db = crate::connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![crate::blob::blob("payload", true)])); + let stored = db + .create_empty_table("stored", schema.clone()) + .execute() + .await + .unwrap(); + let state = Arc::new(Mutex::new(State::default())); + let server_state = state.clone(); + let server_table = stored.clone(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let mut tasks = tokio::task::JoinSet::new(); + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let state = server_state.clone(); + let table = server_table.clone(); + tasks.spawn(async move { + let (path, body) = read_request(&mut socket).await; + let mut apply_fault = false; + let response; + if path.contains("multipart_write/create") { + state.lock().unwrap().creates += 1; + response = r#"{"upload_id":"00000000-0000-0000-0000-000000000001"}"# + .to_string(); + } else if path.contains("/insert/") { + let url = url::Url::parse(&format!("http://localhost{path}")).unwrap(); + let params: HashMap<_, _> = url.query_pairs().into_owned().collect(); + assert_eq!(params["upload_id"], "00000000-0000-0000-0000-000000000001"); + let part = params["upload_part_id"].clone(); + let mut state = state.lock().unwrap(); + apply_fault = !complete_fault && state.attempts.is_empty(); + state.attempts.push((part.clone(), body.clone())); + // Match the verified server contract: replace the txn + // associated with this part ID before acknowledging it. + state.parts.insert(part, body); + response = "{}".into(); + } else if path.contains("multipart_write/complete") { + let parts = { + let mut state = state.lock().unwrap(); + state.completes += 1; + state.parts.values().cloned().collect::>() + }; + for body in parts { + let reader = + StreamReader::try_new(std::io::Cursor::new(body), None) + .unwrap(); + let batches = reader.collect::, _>>().unwrap(); + table.add(batches).execute().await.unwrap(); + } + apply_fault = complete_fault; + response = r#"{"version":2}"#.into(); + } else if path.contains("multipart_write/abort") { + state.lock().unwrap().aborts += 1; + panic!("abort must never follow a possibly committed complete"); + } else { + panic!("unexpected request {path}"); + } + if apply_fault { + match fault { + Fault::Close => return, + Fault::Timeout => { + tokio::time::sleep(Duration::from_secs(2)).await; + return; + } + Fault::Status(status) => { + respond( + &mut socket, + status, + "gateway fault after staging/commit", + ) + .await; + return; + } + } + } + respond(&mut socket, 200, &response).await; + }); + } + }); + let client = RestfulLanceDbClient::try_new( + &crate::remote::client::parse_db_url("db://test").unwrap(), + "us-east-1", + Some(format!("http://{address}")), + Default::default(), + ClientConfig { + timeout_config: TimeoutConfig { + read_timeout: Some(Duration::from_secs(1)), + ..Default::default() + }, + retry_config: RetryConfig { + retries: Some(3), + read_retries: Some(3), + connect_retries: Some(3), + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let remote = Arc::new(RemoteTable::new_with_sql_client( + client, + "test".into(), + "test".into(), + vec![], + "test".into(), + ServerVersion(semver::Version::new(0, 4, 0)), + None, + )); + remote.seed_schema(&serde_json::json!({"version": 1, "schema": JsonSchema::try_from(schema.as_ref()).unwrap()}).to_string()); + let payload_a = vec![17u8; 32 * 1024]; + let payload_b = vec![29u8; 32 * 1024]; + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(LargeBinaryArray::from(vec![ + Some(payload_a.as_slice()), + Some(payload_b.as_slice()), + ]))], + ) + .unwrap(); + let progress = Arc::new(Mutex::new(Vec::new())); + let seen = progress.clone(); + let result = AddDataBuilder::new(remote, Box::new(input), None) + .write_parallelism(2) + .progress(move |p| { + seen.lock() + .unwrap() + .push((p.output_rows(), p.output_bytes(), p.done())) + }) + .execute() + .await; + if complete_fault { + assert!( + result + .unwrap_err() + .to_string() + .contains("commit outcome unknown"), + "{fault:?}" + ); + } else { + result.unwrap(); + } + assert_eq!( + stored.count_rows(None).await.unwrap(), + 2, + "{fault:?}, complete={complete_fault}" + ); + let payloads = stored.fetch_blobs("payload", &[0, 1]).await.unwrap(); + assert_eq!(payloads.value(0), payload_a); + assert_eq!(payloads.value(1), payload_b); + let state = state.lock().unwrap(); + assert_eq!((state.creates, state.completes, state.aborts), (1, 1, 0)); + assert_eq!(state.parts.len(), 1); + assert_eq!(state.attempts.len(), if complete_fault { 1 } else { 2 }); + if !complete_fault { + assert_eq!(state.attempts[0], state.attempts[1]); + } + let progress = progress.lock().unwrap(); + let last = progress.last().unwrap(); + assert_eq!(last.0, 2); + assert!(last.1 > 0 && last.2); + assert_eq!( + progress.first().unwrap().1, + 0, + "scan is not an acknowledgement" + ); + assert!(progress.windows(2).all(|pair| pair[0].1 <= pair[1].1)); + assert_eq!(last.1, state.parts.values().map(Vec::len).sum::()); + server.abort(); + } + } +} + +#[tokio::test] +async fn multipart_retries_sixth_part_after_reused_connection_closes() { + use datafusion_execution::TaskContext; + use datafusion_physical_plan::ExecutionPlan; + use futures::TryStreamExt; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let mut attempts = Vec::new(); + let (mut socket, _) = listener.accept().await.unwrap(); + for n in 0..6 { + let (path, body) = read_request(&mut socket).await; + attempts.push((path, body)); + if n == 5 { + break; + } + // Keep one connection pooled for the first five acknowledged parts. + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") + .await + .unwrap(); + } + // The sixth part was staged, but the peer closes before response headers. + drop(socket); + let (mut socket, _) = listener.accept().await.unwrap(); + attempts.push(read_request(&mut socket).await); + respond(&mut socket, 200, "{}").await; + attempts + }); + let client = RestfulLanceDbClient::try_new( + &crate::remote::client::parse_db_url("db://test").unwrap(), + "test-region", + Some(format!("http://{address}")), + Default::default(), + ClientConfig { + retry_config: RetryConfig { + retries: Some(3), + read_retries: Some(3), + connect_retries: Some(3), + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let input = arrow_array::record_batch!(("id", Int32, [1, 2, 3, 4, 5, 6])).unwrap(); + let plan = Arc::new( + crate::table::datafusion::scannable_exec::ScannableExec::new(Box::new(input), None), + ); + let exec = super::insert::RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + plan, + false, + "upload-1".into(), + None, + None, + Some(1), + None, + ); + exec.execute(0, Arc::new(TaskContext::default())) + .unwrap() + .try_collect::>() + .await + .unwrap(); + let attempts = server.await.unwrap(); + assert_eq!(attempts.len(), 7); + assert_eq!( + attempts[5], attempts[6], + "retry must reuse both part ID and bytes" + ); + let unique: std::collections::HashSet<_> = attempts.iter().map(|(path, _)| path).collect(); + assert_eq!(unique.len(), 6, "the staged sixth txn must be replaced"); +} + +#[tokio::test] +async fn multipart_rejections_preserve_progress_and_cleanup_boundaries() { + // Stage rejection, definite complete rejection, and ambiguous successful responses. + for (stage_status, complete_status, complete_body, cleanup) in [ + (503, 200, "{}", true), + (200, 409, "transaction conflict", true), + (200, 429, "rate limited", true), + (200, 200, "{}", false), + (200, 200, "not json", false), + (200, 503, "gateway failure", false), + ] { + for abort_status in [200, 503] { + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = requests.clone(); + let progress = Arc::new(Mutex::new(Vec::new())); + let during_request = progress.clone(); + let remote = Arc::new(RemoteTable::new_mock( + "test".into(), + move |request| { + let path = request.url().path(); + observed.lock().unwrap().push(path.to_owned()); + let (status, body) = if path.ends_with("/create") { + (200, r#"{"upload_id":"rejected-upload"}"#) + } else if path.ends_with("/insert/") { + let progress = during_request.lock().unwrap(); + assert!(!progress.is_empty(), "must execute the scan tracker"); + assert!(progress.iter().all(|p: &(usize, usize, bool)| p.1 == 0)); + (stage_status, "{}") + } else if path.ends_with("/complete") { + (complete_status, complete_body) + } else if path.ends_with("/abort") { + (abort_status, "cleanup response") + } else { + panic!("unexpected request {path}") + }; + http::Response::builder() + .status(status) + .body(body.to_owned()) + .unwrap() + }, + Some(semver::Version::new(0, 4, 0)), + )); + let input = arrow_array::record_batch!(("id", Int32, [1, 2])).unwrap(); + remote.seed_schema(&serde_json::json!({"version": 1, "schema": JsonSchema::try_from(input.schema().as_ref()).unwrap()}).to_string()); + let seen = progress.clone(); + let error = AddDataBuilder::new(remote, Box::new(input), None) + .write_parallelism(2) + .retries(0) + .progress(move |p| { + seen.lock() + .unwrap() + .push((p.output_rows(), p.output_bytes(), p.done())) + }) + .execute() + .await + .unwrap_err(); + let requests = requests.lock().unwrap(); + let count = |suffix: &str| { + requests + .iter() + .filter(|path| path.ends_with(suffix)) + .count() + }; + assert_eq!(count("/create"), 1); + assert_eq!(count("/insert/"), 1); + assert_eq!(count("/complete"), usize::from(stage_status == 200)); + assert_eq!( + count("/abort"), + usize::from(cleanup), + "cleanup must honor retries=0: {error}" + ); + assert_eq!( + error.to_string().contains("commit outcome unknown"), + !cleanup, + "{error}" + ); + let progress = progress.lock().unwrap(); + let last = progress.last().unwrap(); + assert!(last.2); + assert_eq!(last.0, 2); + if stage_status != 200 { + assert!( + progress.iter().all(|p| p.1 == 0), + "unacknowledged bytes reported" + ); + } + } + } +} diff --git a/rust/lancedb/src/remote/util.rs b/rust/lancedb/src/remote/util.rs index 1c368e2f5..dcfaf9312 100644 --- a/rust/lancedb/src/remote/util.rs +++ b/rust/lancedb/src/remote/util.rs @@ -1,7 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use arrow_array::{ + Array, ArrayRef, GenericListViewArray, OffsetSizeTrait, RecordBatch, UInt64Array, + cast::AsArray, make_array, +}; +use arrow_buffer::ScalarBuffer; +use arrow_data::ArrayData; use arrow_ipc::CompressionType; +use arrow_schema::{ArrowError, DataType, Field}; +use arrow_select::{dictionary::garbage_collect_any_dictionary, take::take}; use futures::{Stream, StreamExt}; use reqwest::Response; @@ -9,6 +17,269 @@ use crate::{Result, arrow::SendableRecordBatchStream}; use super::db::ServerVersion; +fn has_dictionary(data: &ArrayData) -> bool { + matches!(data.data_type(), DataType::Dictionary(_, _)) + || data.child_data().iter().any(has_dictionary) +} + +fn has_list_view(data: &ArrayData) -> bool { + matches!( + data.data_type(), + DataType::ListView(_) | DataType::LargeListView(_) + ) || data.child_data().iter().any(has_list_view) +} + +// Arrow take on ordinary lists copies nested ListView ranges through +// MutableArrayData, losing sharing. Select child row IDs instead, then apply +// that selection recursively to the real children. +fn take_dictionary_rows( + array: &dyn Array, + indices: &UInt64Array, +) -> std::result::Result { + let data = array.to_data(); + if !has_list_view(&data) { + return take(array, indices, None); + } + let item = || std::sync::Arc::new(Field::new_list_field(DataType::UInt64, false)); + let proxy_type = match data.data_type() { + DataType::List(_) | DataType::Map(_, _) => DataType::List(item()), + DataType::LargeList(_) => DataType::LargeList(item()), + DataType::FixedSizeList(_, size) => DataType::FixedSizeList(item(), *size), + DataType::Struct(fields) => DataType::Struct( + fields + .iter() + .map(|f| f.as_ref().clone().with_data_type(DataType::UInt64)) + .collect(), + ), + // ListView take already preserves sharing; its actual child selection + // is performed by compact_list_view before dictionary collection. + _ => return take(array, indices, None), + }; + let children = data + .child_data() + .iter() + .map(|child| UInt64Array::from_iter_values(0..child.len() as u64).to_data()) + .collect(); + let proxy = make_array( + data.clone() + .into_builder() + .data_type(proxy_type) + .child_data(children) + .build()?, + ); + let selected = take(proxy.as_ref(), indices, None)?.to_data(); + let children = data + .child_data() + .iter() + .zip(selected.child_data()) + .map(|(child, ids)| { + let ids = UInt64Array::from(ids.clone()); + Ok(take_dictionary_rows(make_array(child.clone()).as_ref(), &ids)?.to_data()) + }) + .collect::, ArrowError>>()?; + Ok(make_array( + selected + .into_builder() + .data_type(data.data_type().clone()) + .child_data(children) + .build()?, + )) +} + +fn compact_list_view( + views: &GenericListViewArray, +) -> std::result::Result { + let mut ranges: Vec<_> = (0..views.len()) + .filter_map(|row| { + let start = views.value_offsets()[row].as_usize(); + let size = views.value_sizes()[row].as_usize(); + (views.is_valid(row) && size != 0).then(|| (start, start + size)) + }) + .collect(); + ranges.sort_unstable(); + let mut union: Vec<(usize, usize, usize)> = Vec::with_capacity(ranges.len()); + let mut len = 0; + for (start, end) in ranges { + if let Some(last) = union.last_mut().filter(|last| start <= last.1) { + let end = end.max(last.1); + len += end - last.1; + last.1 = end; + } else { + union.push((start, end, len)); + len += end - start; + } + } + let mut offsets = Vec::with_capacity(views.len()); + let mut sizes = Vec::with_capacity(views.len()); + for row in 0..views.len() { + let size = views.value_sizes()[row]; + if views.is_null(row) || size.as_usize() == 0 { + offsets.push(O::usize_as(0)); + sizes.push(O::usize_as(0)); + } else { + let start = views.value_offsets()[row].as_usize(); + let range = union[union.partition_point(|r| r.0 <= start) - 1]; + // Removing gaps cannot increase a valid original offset. + offsets.push(O::from_usize(range.2 + start - range.0).unwrap()); + sizes.push(size); + } + } + // Each child position is selected once, even for unsorted, overlapping views. + let indices = UInt64Array::from_iter_values( + union + .iter() + .flat_map(|&(start, end, _)| (start..end).map(|i| i as u64)), + ); + let child = take_dictionary_rows(views.values().as_ref(), &indices)?; + views + .to_data() + .into_builder() + .offset(0) + .buffers(vec![ + ScalarBuffer::from(offsets).into_inner(), + ScalarBuffer::from(sizes).into_inner(), + ]) + .child_data(vec![child.to_data()]) + .build() +} + +fn compact_dictionary_data(data: ArrayData) -> std::result::Result { + let data = match data.data_type() { + DataType::Dictionary(_, _) => { + let array = make_array(data); + garbage_collect_any_dictionary(array.as_any_dictionary())?.to_data() + } + DataType::ListView(_) => compact_list_view(make_array(data).as_list_view::())?, + DataType::LargeListView(_) => compact_list_view(make_array(data).as_list_view::())?, + // Selecting dictionary values retains view backing buffers, which IPC + // otherwise serializes in full even when most views are unreferenced. + DataType::Utf8View => make_array(data).as_string_view().gc().to_data(), + DataType::BinaryView => make_array(data).as_binary_view().gc().to_data(), + _ => data, + }; + let children = data + .child_data() + .iter() + .cloned() + .map(compact_dictionary_data) + .collect::, _>>()?; + data.into_builder().child_data(children).build() +} + +/// Compact dictionaries retained by row slices without changing the schema. +/// Row slices (and `take` alone) retain the original dictionary lookup tables. +/// Struct/fixed-size-list validity does not mask child slots, so values hidden +/// only by those ancestor nulls may remain referenced. +pub(super) fn compact_batch_dictionaries( + batch: RecordBatch, +) -> std::result::Result { + let columns = batch + .columns() + .iter() + .map(|array| { + let data = array.to_data(); + if !has_dictionary(&data) { + return Ok(array.clone()); + } + // Normalize container offsets and select their child rows before + // collecting dictionaries nested in lists/structs/maps. + let data = if matches!(data.data_type(), DataType::Dictionary(_, _)) { + data + } else { + let indices = UInt64Array::from_iter_values(0..array.len() as u64); + take_dictionary_rows(array.as_ref(), &indices)?.to_data() + }; + Ok(make_array(compact_dictionary_data(data)?)) + }) + .collect::, ArrowError>>()?; + RecordBatch::try_new_with_options( + batch.schema(), + columns, + &arrow_array::RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + ) +} + +/// Split batches before IPC encoding, preserving row order and allowing a single +/// oversized row. Compact each dictionary before measuring or splitting it so +/// descendants never repeatedly scan or encode the full source dictionary. +/// Yield slices on demand so compacted dictionary copies are not all retained. +pub(super) fn split_batch( + batch: RecordBatch, + max_bytes: usize, +) -> impl Iterator> { + let mut pending = vec![batch]; + std::iter::from_fn(move || { + while let Some(batch) = pending.pop() { + let batch = match compact_batch_dictionaries(batch) { + Ok(batch) => batch, + Err(err) => { + pending.clear(); + return Some(Err(err)); + } + }; + let size: usize = batch + .columns() + .iter() + .map(|array| { + array + .to_data() + .get_slice_memory_size() + .unwrap_or_else(|_| array.get_buffer_memory_size()) + }) + .sum(); + if size > max_bytes && batch.num_rows() > 1 { + let middle = batch.num_rows() / 2; + pending.push(batch.slice(middle, batch.num_rows() - middle)); + pending.push(batch.slice(0, middle)); + } else { + return Some(Ok(batch)); + } + } + None + }) +} + +pub(super) const IPC_BATCH_BYTES: usize = 8 * 1024 * 1024; +pub(super) const MAX_CREATE_BYTES: usize = 256 * 1024 * 1024; + +/// Validate the entire create payload before issuing its single atomic request. +/// A truncated IPC stream can be accepted as EOF by Arrow readers, so failing a +/// live request body after exceeding the budget cannot guarantee atomic failure. +/// Spooling bounds memory while ensuring an oversized input never reaches create. +pub(super) async fn create_body(data: SendableRecordBatchStream) -> Result { + use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; + let io_error = |err: std::io::Error| crate::Error::Other { + message: "Failed to prepare atomic remote create payload".into(), + source: Some(Box::new(err)), + }; + let file = tempfile::tempfile().map_err(io_error)?; + let mut file = tokio::fs::File::from_std(file); + let mut stream = Box::pin(stream_as_ipc(data)?); + let mut bytes = 0usize; + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + bytes = bytes.saturating_add(chunk.len()); + if bytes > MAX_CREATE_BYTES { + return Err(crate::Error::InvalidInput { + message: format!( + "Remote create_table exceeds the {MAX_CREATE_BYTES}-byte single-request budget. \ + Create the table with db.create_table(name, schema=...), then upload with \ + table.add(data, progress=True)." + ), + }); + } + file.write_all(&chunk).await.map_err(io_error)?; + } + file.rewind().await.map_err(io_error)?; + let stream = futures::stream::try_unfold(file, |mut file| async move { + let mut chunk = vec![0; 64 * 1024]; + let len = file.read(&mut chunk).await?; + chunk.truncate(len); + Ok::<_, std::io::Error>((len != 0).then_some((chunk, file))) + }); + Ok(reqwest::Body::wrap_stream(stream)) +} + pub fn stream_as_ipc( data: SendableRecordBatchStream, ) -> Result>> { @@ -18,6 +289,13 @@ pub fn stream_as_ipc( let buf = Vec::with_capacity(WRITE_BUF_SIZE); let writer = arrow_ipc::writer::StreamWriter::try_new_with_options(buf, &data.schema(), options)?; + let data = data.flat_map(|batch| match batch { + Ok(batch) => futures::stream::iter( + split_batch(batch, IPC_BATCH_BYTES).map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }); let stream = futures::stream::try_unfold( (data, writer, false), move |(mut data, mut writer, finished)| async move { @@ -42,11 +320,6 @@ pub fn stream_as_ipc( Ok(stream) } -pub fn stream_as_body(data: SendableRecordBatchStream) -> Result { - let stream = stream_as_ipc(data)?; - Ok(reqwest::Body::wrap_stream(stream)) -} - pub fn parse_server_version(req_id: &str, rsp: &Response) -> Result { let version = rsp .headers() diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index 8c5dc4b45..d6323449d 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -65,6 +65,7 @@ pub struct AddDataBuilder { pub(crate) progress_callback: Option, pub(crate) write_parallelism: Option, pub(crate) allow_external_blob_outside_bases: bool, + pub(crate) retries: Option, } impl std::fmt::Debug for AddDataBuilder { @@ -93,9 +94,18 @@ impl AddDataBuilder { progress_callback: None, write_parallelism: None, allow_external_blob_outside_bases: false, + retries: None, } } + /// Override the remote retry budget for this call. `0` disables retries, + /// including retries of idempotent multipart parts. Ambiguous commits are + /// never replayed, regardless of this setting. Ignored by embedded tables. + pub fn retries(mut self, retries: u8) -> Self { + self.retries = Some(retries); + self + } + pub fn mode(mut self, mode: AddDataMode) -> Self { self.mode = mode; self @@ -217,6 +227,7 @@ impl AddDataBuilder { mode: self.mode, tracker, allow_external_blob_outside_bases: self.allow_external_blob_outside_bases, + retries: self.retries, }) } } @@ -231,6 +242,7 @@ pub struct PreprocessingOutput { pub mode: AddDataMode, pub tracker: Option>, pub allow_external_blob_outside_bases: bool, + pub retries: Option, } /// Check that the input schema is valid for insert. diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 3f37c540d..fe131d907 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -75,6 +75,7 @@ pub struct MergeInsertBuilder { pub(crate) when_not_matched_by_source_delete: bool, pub(crate) when_not_matched_by_source_delete_filt: Option, pub(crate) timeout: Option, + pub(crate) retries: Option, pub(crate) use_index: bool, pub(crate) use_rte: Option, pub(crate) validate_single_shard: bool, @@ -91,12 +92,21 @@ impl MergeInsertBuilder { when_not_matched_by_source_delete: false, when_not_matched_by_source_delete_filt: None, timeout: None, + retries: None, use_index: true, use_rte: None, validate_single_shard: true, } } + /// Override the remote transport retry budget for this operation. `0` + /// disables retries. Ambiguous write results are never replayed. This is + /// independent of local transaction conflict retries. + pub fn retries(&mut self, retries: u8) -> &mut Self { + self.retries = Some(retries); + self + } + /// Rows that exist in both the source table (new data) and /// the target table (old data) will be updated, replacing /// the old row with the corresponding matching row. diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index d9828fff1..55980c5ff 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -26,6 +26,7 @@ pub struct UpdateBuilder { parent: Arc, pub(crate) filter: Option, pub(crate) columns: Vec<(String, String)>, + pub(crate) retries: Option, } impl UpdateBuilder { @@ -34,9 +35,17 @@ impl UpdateBuilder { parent, filter: None, columns: Vec::new(), + retries: None, } } + /// Override the remote retry budget for this call. `0` disables retries. + /// Ambiguous write results are never replayed. Ignored by embedded tables. + pub fn retries(mut self, retries: u8) -> Self { + self.retries = Some(retries); + self + } + /// Limits the update operation to rows matching the given filter /// /// If a row does not match the filter then it will be left unchanged. diff --git a/rust/lancedb/src/table/write_progress.rs b/rust/lancedb/src/table/write_progress.rs index 191c3284d..12e4dd62c 100644 --- a/rust/lancedb/src/table/write_progress.rs +++ b/rust/lancedb/src/table/write_progress.rs @@ -6,7 +6,7 @@ //! You can add a callback to process progress in [`crate::table::AddDataBuilder::progress`]. //! [`WriteProgress`] is the struct passed to the callback. -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -30,12 +30,19 @@ impl WriteProgress { self.elapsed } - /// Number of rows written so far. + /// Number of rows processed by the input scan. + /// + /// This does not indicate that the rows have been committed. pub fn output_rows(&self) -> usize { self.output_rows } - /// Number of bytes written so far. + /// Number of bytes processed by the writer. + /// + /// Remote multipart writes report acknowledged IPC part bytes, starting at + /// zero. Retransmitted parts are counted once. Other writers report their + /// encoded bytes when available, otherwise the scanned Arrow memory size. + /// This does not indicate that the write has been committed. pub fn output_bytes(&self) -> usize { self.output_bytes } @@ -94,6 +101,8 @@ pub(crate) struct WriteProgressTracker { /// Wire bytes tracked separately by the insert layer. When set (> 0), /// this takes precedence over the in-memory bytes from `rows_and_bytes`. wire_bytes: AtomicUsize, + /// Multipart writes select this before scanning, including zero acknowledgements. + wire_bytes_enabled: AtomicBool, active_tasks: Arc, total_tasks: AtomicUsize, start: Instant, @@ -107,6 +116,7 @@ impl WriteProgressTracker { Self { rows_and_bytes: std::sync::Mutex::new((0, 0)), wire_bytes: AtomicUsize::new(0), + wire_bytes_enabled: AtomicBool::new(false), active_tasks: Arc::new(AtomicUsize::new(0)), total_tasks: AtomicUsize::new(1), start: Instant::now(), @@ -115,6 +125,11 @@ impl WriteProgressTracker { } } + /// Select wire-byte progress, including zero, before polling the input plan. + pub fn use_wire_bytes(&self) { + self.wire_bytes_enabled.store(true, Ordering::Relaxed); + } + /// Set the total number of parallel write tasks (the write parallelism). pub fn set_total_tasks(&self, n: usize) { self.total_tasks.store(n, Ordering::Relaxed); @@ -179,7 +194,11 @@ impl WriteProgressTracker { let wire = self.wire_bytes.load(Ordering::Relaxed); // Prefer wire bytes (actual I/O size) when the insert layer is // tracking them; fall back to in-memory Arrow size otherwise. - let output_bytes = if wire > 0 { wire } else { in_memory_bytes }; + let output_bytes = if self.wire_bytes_enabled.load(Ordering::Relaxed) || wire > 0 { + wire + } else { + in_memory_bytes + }; WriteProgress { elapsed: self.start.elapsed(), output_rows: rows, From da40aa6c44b0eaf5f2003e5837e1a4f5e7c3799b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:23 +0800 Subject: [PATCH 12/36] test: isolate SQL reader timeout from submission latency (#5000) The reader timeout regression can fail on a busy runner while submitting its real loopback Flight exchange, before it ever calls `reader()`. Freeze Tokio time and inhibit automatic clock advancement during submission, then let the existing 200ms result timeout fire. Preserve the exact result-stage error through both describe APIs and a second reader, and verify that the timeout closes the server response stream. With a diagnostic-only 300ms wall-clock delay in request-header preparation, main fails with `SQL query submission timed out`; the repaired fixture passes the same scenario through the real Flight/reader path. The focused regression and all 54 adjacent SQL tests pass locally. Hosted Linux and macOS CLI tests and the complete PR CI pass on `fb96931be004166a479cc031aca4b1db05f4b78d`. --- rust/lancedb/src/remote/sql_test.rs | 33 +++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 471966731..d94defac4 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -607,7 +607,15 @@ impl FlightService for TestSqlService { )); } if query == "SELECT exchange stall" { - return Ok(Response::new(futures::stream::pending().boxed())); + let dropped = DropSignal(self.exchange_drops.clone()); + return Ok(Response::new( + futures::stream::pending() + .map(move |message| { + let _dropped = &dropped; + message + }) + .boxed(), + )); } let rows = parameters.ok_or_else(|| Status::invalid_argument("exchange without parameters"))?; @@ -990,13 +998,26 @@ async fn an_abandoned_reader_leaves_the_rows_for_the_next_one() { async fn a_reader_that_times_out_reports_the_failure() { let mut client_config = ClientConfig::default(); client_config.timeout_config.timeout = Some(Duration::from_millis(200)); - let (client, _shutdown) = start_sql_service(TestSqlService::default(), client_config).await; + let service = TestSqlService::default(); + let drops = service.exchange_drops.clone(); + let (client, _shutdown) = start_sql_service(service, client_config).await; - let stalled = client - .execute(parameterized("SELECT exchange stall", parameter_row())) - .await - .unwrap(); + // Real loopback I/O must finish before the clock can advance to the timeout. + // A blocking task inhibits Tokio's automatic clock advance during submission. + tokio::time::pause(); + let submission_client = client.clone(); + let stalled = tokio::task::spawn_blocking(move || { + tokio::runtime::Handle::current().block_on( + submission_client.execute(parameterized("SELECT exchange stall", parameter_row())), + ) + }) + .await + .unwrap() + .unwrap(); + assert_eq!(drops.load(Ordering::SeqCst), 0); assert_overall_timeout(stalled.reader().await, "result"); + tokio::time::resume(); + wait_for(&drops, 1, "a timed-out reader must end the call").await; let Err(retried) = stalled.reader().await else { panic!("the rows are gone, so a second reader cannot succeed"); }; From 9b13e8f72530c8b1950c09685f6920711154a539 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:39 +0800 Subject: [PATCH 13/36] feat(python): materialize remote blobs at the query snapshot (#4973) Python remote queries materialize Blob v2 payloads with `blob_mode="bytes"` through synchronous and asynchronous `to_arrow`, `to_list`, `to_pandas`, and `to_batches`. Deferred reads bind to the actual producing dataset without changing the caller's live table handle, including concurrent writes and same-name DROP/CREATE. Trust only the authoritative `x-lancedb-query-version` plus `x-lancedb-query-snapshot`. A numeric version alone cannot distinguish a recreated table; the ordinary live watermark and user-supplied Arrow metadata cannot establish provenance. An independent immutable handle carries the original identity through every batch, byte-limit split, and large-Blob Range fallback, and requires a verified response echo before accepting payloads. Aliases, NULL/empty results, rerankers, and hybrid legs retain consistent provenance. Missing capability, mixed identities, or a serving node ignoring the precondition fails explicitly; ordinary descriptor queries remain available on older servers. The source docs distinguish Enterprise SQL payload bytes from SDK descriptors. Server dependency: https://github.com/lancedb/sophon/pull/10211. Validation uses retained, independently audited local evidence: 724 Python cases passed (one optional PyAV skip), 67 focused SDK Rust cases passed, 36 server checks passed, and 15 actual REST/SDK scenarios passed across retained runs. These cover sync/async and Arrow file/stream recreation, concurrent overwrite, deletion of a selected version, legacy capabilities, forged IPC metadata, WAL exclusion, and actual mid-batch recreation. The original aggregate experiment exited 101 because its extra harness assumed a Python batch size would split the native result; its 36 server checks and 13 completed scenarios remain valid. The corrected native-batch experiment passed separately for sync and async. No aggregate all-green claim is made. The public batched-range operation has separate cross-partition identity integration in https://github.com/lancedb/sophon/pull/10219 and https://github.com/lancedb/lancedb/pull/4994. This change does not claim to fix that loop. Realtime/MemWAL remains outside Blob v2 GA, without disabling existing writes or compaction. No dependency pins changed. Merge/rollout hold remains: upgrade every serving node before enabling the new SDK capability, verify proxy forwarding of both authoritative headers and the verification echo, and preserve queried versions for later reads. Missing or inconsistent capability fails explicitly; identity does not retain versions or authenticate storage paths. Actual deployed proxy/Cloud/PE behavior and production retention remain unverified. Old SDKs do not gain incarnation protection from a server-only upgrade. Published documentation retains the Early access badge and released Enterprise instructions, including explicit fetches for copying. The new Enterprise `blob_mode="bytes"` guidance, snapshot-bound copy example, future streaming restrictions and GA wording remain source-only MDX drafts until release. The correction distinguishing released Enterprise SQL bytes from SDK descriptors remains visible. Documentation validation checked comment boundaries, visible instructions, Python example syntax and whitespace; the site was not built. This documentation-only revision reuses the implementation evidence above. --- docs/web/management/table.mdx | 102 +++++- docs/web/sql/dql/blob-descriptor.mdx | 8 +- python/python/lancedb/_lancedb.pyi | 7 +- python/python/lancedb/query.py | 138 ++++++-- python/python/tests/test_remote_db.py | 457 +++++++++++++++++++++++-- python/src/table.rs | 16 +- rust/lancedb/src/remote/table.rs | 171 ++++++++- rust/lancedb/src/remote/table/blobs.rs | 30 +- rust/lancedb/src/table.rs | 23 ++ 9 files changed, 876 insertions(+), 76 deletions(-) diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 23fdbdb4a..031342fbc 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -375,8 +375,16 @@ file, up to 64 KiB by default, and larger values are stored outside it. A `blob` column keeps metadata separate from the payload bytes, so queries can filter rows without loading the blobs. -Most queries return descriptors, which contain metadata about the blob instead -of its bytes. You can +{/* Draft for Blob v2 GA. Confirm release status before removing Early access. + +Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled +are outside the GA support scope. +*/} + +SDK queries return descriptors by default, which contain metadata about the +blob instead of its bytes. Enterprise SQL queries return payload bytes by +default; use `blob_descriptor(column)` to select metadata instead. With an SDK, +you can [read the bytes in the query results](#multimodal-blob-query-results) or [fetch them by row ID](#multimodal-read-blobs). @@ -500,14 +508,41 @@ the default `"lazy"` mode because it would open `BlobFile` handles. Query with `blob_mode="descriptions"`, then read bytes with `fetch_blobs` or `fetch_blob_files`. +{/* Draft for the Enterprise Python bytes release. Replace the released instructions above only after SDK and serving-node rollout. + +`blob_mode="bytes"` also supports Enterprise queries. The SDK locks all blob +fetches, including streaming batches, to both the version in +`x-lancedb-query-version` and the incarnation/revision identity in +`x-lancedb-query-snapshot`, captured from the same query response. Every payload +request verifies that identity against the actual opened dataset before reading +rows. Concurrent writes therefore preserve the selected payloads. Dropping and +recreating a table, even at the same location and version, cannot substitute the +replacement's bytes: the original snapshot is served or the read fails explicitly. + +Upgrade the SDK and every serving node to support snapshot identities. A server +that reports only a numeric query version, a legacy `x-lancedb-version` watermark, +or Arrow schema metadata does not enable deferred bytes. Missing or unsupported +identities raise `NotImplementedError`; use `"descriptions"` until the upgrade is +complete. Ordinary queries, descriptors, and independent `fetch_blobs` calls keep +working. Old SDKs keep their existing behavior and do not gain this protection +from a server-only upgrade. Realtime/MemWAL and historical manifests without a +native transaction identity do not support deferred bytes. Snapshot identities +do not retain old versions; deleting the selected version still fails explicitly. +In-memory tables and namespace `QueryTable` pushdown do not support bytes mode. +On an Enterprise table, sync `Table.to_pandas()` and `Table.to_arrow()` are not +supported; use `table.search()` instead. A query's `to_pandas()` also raises in +the default `"lazy"` mode because remote lazy handles are not supported. +*/} + ###### Copy a subset of blob rows {#multimodal-copy-subset} -Blob query results describe the stored payload; they are not the bytes to -insert into another table. These APIs return different values: +SDK descriptors identify stored payloads; materialize the bytes before inserting +them into another table. These APIs return different values: | Read path | Value | | --- | --- | -| SQL or an Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | +| Enterprise SQL | Raw payload bytes by default. | +| An SDK Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | | `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. | | A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. | @@ -545,6 +580,50 @@ Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches for larger subsets; `fetch_blobs` materializes all requested bytes in memory. For incremental decoding, use `fetch_blob_files` instead. +{/* Draft for the Enterprise Python bytes release. Replace the copy example above when snapshot-bound remote bytes are released. + +For Enterprise tables, prefer server-side `CREATE TABLE AS SELECT` or +`INSERT INTO ... SELECT` to copy blobs without a client round trip: + +```sql +CREATE TABLE image_subset AS SELECT id, image FROM images WHERE id < 100; +-- To append to an existing destination: +INSERT INTO image_subset SELECT id, image FROM images WHERE id >= 100 AND id < 200; +``` + +For SDK copies, query with `blob_mode="bytes"` to bind selection and payload +reads to one snapshot. The following example copies up to 100 rows from an +existing `images` table with an integer `id` and a blob `image` column. + +```python +import lancedb +import pyarrow as pa + +source = db.open_table("images") +hits = ( + source.search() + .where("id < 100") + .select(["id", "image"]) + .limit(100) + .to_arrow(blob_mode="bytes") +) +subset = db.create_table( + "image_subset", + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), +) +if hits.num_rows: + subset.add(hits) +``` + +Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches +for larger subsets; `fetch_blobs` materializes all requested bytes in memory. +For incremental decoding, use `fetch_blob_files` instead. + +Remote bytes mode requires a server that supports snapshot-bound Blob reads. +Older servers and Realtime/MemWAL tables can still return descriptors, but +bytes mode raises an explicit unsupported-operation error before fetching payloads. +*/} + `blob_mode="bytes"` materializes top-level and struct-nested blob columns. It raises `ValueError` when the selected columns include blobs inside a list. Select those columns with `blob_mode="descriptions"`, or leave @@ -579,6 +658,19 @@ overwrite the table, use a separate reader checked out to a fixed version before querying. Otherwise, an overwrite can invalidate the row IDs used to fetch bytes and raise `ValueError`. +{/* Draft for the Enterprise Python bytes release. Replace the streaming restrictions above after release. + +Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, +including no blobs inside lists, namespace `QueryTable` pushdown, or query +shapes that cannot preserve their row results. Enterprise queries require a +valid `x-lancedb-query-version` and `x-lancedb-query-snapshot` response headers. +Legacy v1 bytes are limited to +eligible local plain scans. For local queries, if concurrent writers can +overwrite the table, use a separate reader checked out to a fixed version +before querying. Otherwise, an overwrite can invalidate the row IDs used to +fetch bytes and raise `ValueError`. +*/} + ###### Optional pandas examples {#multimodal-blob-pandas} The lazy-handle calls below require pylance. The query example expects `tbl_async`, diff --git a/docs/web/sql/dql/blob-descriptor.mdx b/docs/web/sql/dql/blob-descriptor.mdx index 5021f2d20..7ba83311c 100644 --- a/docs/web/sql/dql/blob-descriptor.mdx +++ b/docs/web/sql/dql/blob-descriptor.mdx @@ -15,10 +15,10 @@ SELECT id, blob_descriptor(video) AS descriptor FROM videos ``` -A [BlobV2](/management/table#managed-blobs) column's bytes are not fetched by -a plain `SELECT`: that already returns `large_binary`, the same as any other -binary column. `blob_descriptor` instead returns a small struct describing -where the payload lives, without reading it. Pass one row's descriptor to +A plain `SELECT` of a [BlobV2](/management/table#managed-blobs) column returns +its payload as `large_binary`. `blob_descriptor` instead returns a small +struct describing where the payload lives, without reading the payload. +Pass one row's descriptor to the SDK's blob file reader to open that payload directly: diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 15234532d..956806cde 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -749,7 +749,12 @@ class Table: def take_row_ids(self, row_ids: list[int]) -> TakeQuery: ... async def blob_columns(self) -> list[str]: ... async def fetch_blobs( - self, column: str, row_ids: list[int] + self, + column: str, + row_ids: list[int], + *, + version: Optional[int] = None, + snapshot_identity: Optional[str] = None, ) -> pa.LargeBinaryArray: ... async def fetch_blob_ranges( self, diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index bab40be95..f99aaeb73 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -4,6 +4,7 @@ from __future__ import annotations import asyncio +import re from abc import ABC, abstractmethod from concurrent.futures import ThreadPoolExecutor from datetime import timedelta @@ -194,20 +195,57 @@ def _unsupported_blob_pandas_error(reason: str) -> RuntimeError: ) -def _supports_local_blob_fetch( +def _supports_blob_fetch( async_table: "AsyncTable", pushdown_operations: Iterable[str] ) -> bool: - # Remote tables and QueryTable pushdown answer queries on a server, so a - # fetch through this handle could read another version. - return async_table._inner._is_native() and "QueryTable" not in pushdown_operations + # Remote queries carry their producing snapshot in response metadata. + # Namespace QueryTable pushdown has no equivalent snapshot contract. + return ( + not async_table._inner._is_native() or "QueryTable" not in pushdown_operations + ) + + +def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]: + value = (schema.metadata or {}).get(b"lancedb:query_version", b"") + if not value.isdigit() or not 0 < int(value) < 2**64: + raise NotImplementedError( + "blob_mode='bytes' requires a stable table snapshot: the query response " + "has a missing, invalid, or inconsistent x-lancedb-query-version header. " + "Upgrade the server and use a table without Realtime/MemWAL, or use " + "blob_mode='descriptions'." + ) + identity = (schema.metadata or {}).get(b"lancedb:query_snapshot", b"") + if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity): + raise NotImplementedError( + "blob_mode='bytes' requires a trustworthy query snapshot identity: " + "missing or unsupported x-lancedb-query-snapshot. Upgrade the server " + "on every serving node, or use blob_mode='descriptions'." + ) + return int(value), identity.decode("ascii") + + +def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table: + """Preserve a snapshot only when every query leg used the same identity.""" + keys = (b"lancedb:query_version", b"lancedb:query_snapshot") + snapshots = { + tuple((source.schema.metadata or {}).get(key) for key in keys) + for source in sources + } + metadata = dict(result.schema.metadata or {}) + for key in keys: + metadata.pop(key, None) + snapshot = next(iter(snapshots)) if len(snapshots) == 1 else None + if snapshot is not None and all(value is not None for value in snapshot): + metadata.update(zip(keys, snapshot)) + return result.replace_schema_metadata(metadata) def _blob_bytes_without_snapshot_error() -> NotImplementedError: return NotImplementedError( "blob_mode='bytes' cannot safely materialize blob columns without a " - "stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown " - "run the query on a server, so the blob fetch could read another table " - "version. Use blob_mode='descriptions' to inspect descriptors. To read " + "stable table snapshot. Namespace QueryTable pushdown does not bind " + "the query and blob fetches to one table version. " + "Use blob_mode='descriptions' to inspect descriptors. To read " "payloads, select row IDs with with_row_id(True), then call " "table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, " "row_ids). Keep the source unchanged between selection and fetching." @@ -1297,9 +1335,9 @@ class LanceQueryBuilder(ABC): columns without pylance. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - LanceDB Enterprise blob queries support only ``"descriptions"`` until a - stable - table snapshot can bind the query and blob fetches. + Enterprise queries support ``"bytes"`` at the query response's + snapshot and ``"descriptions"`` without payload reads. Remote + ``"lazy"`` handles are not supported. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and optional flattening. @@ -1307,6 +1345,10 @@ class LanceQueryBuilder(ABC): validate_blob_mode(blob_mode) if _is_remote_query_table(self._table): blob_sources = self._validated_blob_sources(blob_mode) + if blob_mode == "bytes": + return flatten_columns( + self.to_arrow(timeout=timeout, blob_mode=blob_mode), flatten + ).to_pandas(**kwargs) return _finish_remote_pandas( self.to_arrow(timeout=timeout), blob_mode=blob_mode, @@ -1629,7 +1671,8 @@ class LanceQueryBuilder(ABC): _query_is_plain_blob_scan(query) and getattr(self, "_reranker", None) is None and not _query_needs_lance_scanner(self) - and _supports_local_blob_fetch( + and self._table._table._inner._is_native() + and _supports_blob_fetch( self._table._table, getattr(self._table, "_pushdown_operations", ()), ) @@ -1650,11 +1693,12 @@ class LanceQueryBuilder(ABC): if blob_mode != "bytes": return blob_sources reject_unfetchable_blob_columns(schema, self._columns, blob_sources) - if blob_sources and not _supports_local_blob_fetch( + if blob_sources and not _supports_blob_fetch( self._table._table, getattr(self._table, "_pushdown_operations", ()) ): raise _blob_bytes_without_snapshot_error() - reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources) + if not _is_remote_query_table(self._table): + reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources) return blob_sources def _blob_output_schema(self) -> pa.Schema: @@ -1667,9 +1711,20 @@ class LanceQueryBuilder(ABC): return tbl if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) - return replace_blob_columns_with_bytes_sync( - tbl, blob_sources, self._table.fetch_blobs - ) + reject_unmatched_blob_outputs(tbl.schema, blob_sources) + if _is_remote_query_table(self._table) and blob_sources: + version, identity = _remote_blob_snapshot(tbl.schema) + + async def fetch_at_version(column, row_ids): + return await self._table._table._inner.fetch_blobs( + column, row_ids, version=version, snapshot_identity=identity + ) + + def fetch_blobs(column, row_ids): + return LOOP.run(fetch_at_version(column, row_ids)) + else: + fetch_blobs = self._table.fetch_blobs + return replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs) def _finalize_blob_query_table( self, @@ -2386,6 +2441,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): rs_table = result_set.read_all() result_set = self._reranker.rerank_vector(self._str_query, rs_table) check_reranker_result(result_set) + result_set = _merge_query_snapshot(result_set, rs_table) # convert result_set back to RecordBatchReader result_set = pa.RecordBatchReader.from_batches( result_set.schema, result_set.to_batches() @@ -2599,8 +2655,10 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): query = self._query_for_scan(blob_sources) results = self._table._execute_query(query, timeout=timeout).read_all() if self._reranker is not None: + source = results results = self._reranker.rerank_fts(self._query, results) check_reranker_result(results) + results = _merge_query_snapshot(results, source) return self._finalize_blob_query_table( results, blob_mode=blob_mode, blob_sources=blob_sources ) @@ -2847,6 +2905,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): with_row_ids=True, offset=self._offset, ) + results = _merge_query_snapshot(results, fts_results, vector_results) return self._finish_hybrid_results( results, blob_mode=blob_mode, blob_sources=blob_sources ) @@ -3559,9 +3618,8 @@ class AsyncQueryBase(object): _query_is_plain_blob_scan(query) and getattr(self, "_reranker", None) is None and not _query_needs_lance_scanner(self) - and _supports_local_blob_fetch( - self._table, self._table._pushdown_operations - ) + and self._table._inner._is_native() + and _supports_blob_fetch(self._table, self._table._pushdown_operations) ) def select(self, columns: Union[List[str], dict[str, str]]) -> Self: @@ -3766,11 +3824,14 @@ class AsyncQueryBase(object): if blob_mode != "bytes": return blob_sources reject_unfetchable_blob_columns(schema, projection, blob_sources) - if blob_sources and not _supports_local_blob_fetch( + if blob_sources and not _supports_blob_fetch( self._table, self._table._pushdown_operations ): raise _blob_bytes_without_snapshot_error() - reject_unmatched_blob_outputs(await self._blob_output_schema(), blob_sources) + if self._table._inner._is_native(): + reject_unmatched_blob_outputs( + await self._blob_output_schema(), blob_sources + ) return blob_sources async def _blob_output_schema(self) -> pa.Schema: @@ -3783,9 +3844,21 @@ class AsyncQueryBase(object): return tbl if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) - return await replace_blob_columns_with_bytes( - tbl, blob_sources, self._table.fetch_blobs - ) + reject_unmatched_blob_outputs(tbl.schema, blob_sources) + if ( + self._table is not None + and not self._table._inner._is_native() + and blob_sources + ): + version, identity = _remote_blob_snapshot(tbl.schema) + + async def fetch_blobs(column, row_ids): + return await self._table._inner.fetch_blobs( + column, row_ids, version=version, snapshot_identity=identity + ) + else: + fetch_blobs = self._table.fetch_blobs + return await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs) async def to_arrow( self, @@ -3811,7 +3884,8 @@ class AsyncQueryBase(object): ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. ``"bytes"`` returns payload bytes for supported row-addressable blob columns and raises for blobs inside lists. - LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``. + Enterprise queries fetch bytes at the version reported by the query + response. Namespace query pushdown refuses ``"bytes"``. """ blob_sources = await self._validated_blob_sources(blob_mode) if blob_mode == "bytes" and blob_sources: @@ -3893,9 +3967,9 @@ class AsyncQueryBase(object): columns without pylance. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - LanceDB Enterprise blob queries support only ``"descriptions"`` until a - stable - table snapshot can bind the query and blob fetches. + Enterprise queries support ``"bytes"`` at the query response's + snapshot and ``"descriptions"`` without payload reads. Remote + ``"lazy"`` handles are not supported. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and optional flattening. @@ -3903,6 +3977,9 @@ class AsyncQueryBase(object): validate_blob_mode(blob_mode) if self._table is not None and not self._table._inner._is_native(): await self._validated_blob_sources(blob_mode) + if blob_mode == "bytes": + tbl = await self.to_arrow(timeout=timeout, blob_mode=blob_mode) + return flatten_columns(tbl, flatten).to_pandas(**kwargs) return await self._remote_to_pandas( flatten=flatten, timeout=timeout, blob_mode=blob_mode, **kwargs ) @@ -4508,7 +4585,9 @@ class AsyncFTSQuery(AsyncStandardQuery): ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: + source = results results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) return AsyncRecordBatchReader(results, max_batch_length=max_batch_length) @@ -4835,7 +4914,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: + source = results results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) return AsyncRecordBatchReader(results, max_batch_length=max_batch_length) @@ -5027,6 +5108,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): ): result = result.drop(["_rowid"]) + result = _merge_query_snapshot(result, fts_results, vector_results) return AsyncRecordBatchReader(result, max_batch_length=max_batch_length) async def explain_plan(self, verbose: Optional[bool] = False): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 448fd6c39..561a0f900 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5462,14 +5462,34 @@ def blob_descriptor_take_table(): @contextlib.contextmanager -def blob_remote_table(*, server_version=Version("0.5.0"), location=None): +def blob_remote_table( + *, + server_version=Version("0.5.0"), + location=None, + version_header="1", + framing="file", + requests=None, + state=None, + empty=False, + schema_version=None, + search_scores=False, + snapshot_supported=True, + identity_header="v1:" + "a" * 64, + verify_identity=True, +): + if state is None: + state = {"version": 1} + def handler(request): if request.path == "/v1/table/test/describe/": + content_len = int(request.headers.get("Content-Length", 0)) + body = json.loads(request.rfile.read(content_len)) if content_len else {} request.send_response(200) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", str(server_version)) request.end_headers() response = dict(BLOB_DESCRIBE_RESPONSE) + response["version"] = body.get("version") or state["version"] if location is not None: response["location"] = str(location) request.wfile.write(json.dumps(response).encode()) @@ -5502,9 +5522,22 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): elif request.path == "/v1/table/test/query/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) + if requests is not None: + requests.append(("query", body)) columns = body.get("columns") - assert columns in (None, ["id", "image"], ["id"], ["image"]) - if columns == ["id"]: + assert columns in ( + None, + ["id", "image"], + ["id"], + ["image"], + {"payload": "image"}, + ) + if isinstance(columns, dict): + response_table = blob_query_response_table().select(["image", "_rowid"]) + response_table = response_table.rename_columns(["payload", "_rowid"]) + if not body.get("with_row_id", False): + response_table = response_table.drop(["_rowid"]) + elif columns == ["id"]: response_table = blob_query_response_table().select(["id"]) else: if columns == ["image"]: @@ -5521,25 +5554,86 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): response_table = blob_query_response_table() if not body.get("with_row_id", False): response_table = response_table.drop(["_rowid"]) + if search_scores and not body.get("filter", "").startswith("_rowid IN"): + if body.get("vector"): + response_table = response_table.append_column( + "_distance", pa.array([0.1, 0.2, 0.3], type=pa.float32()) + ) + elif body.get("full_text_query"): + response_table = response_table.append_column( + "_score", pa.array([3.0, 2.0, 1.0], type=pa.float32()) + ) + if empty: + response_table = response_table.slice(0, 0) + if schema_version is not None: + response_table = response_table.replace_schema_metadata( + { + b"lancedb:query_version": schema_version.encode(), + b"lancedb:query_snapshot": ("v1:" + "f" * 64).encode(), + } + ) request.send_response(200) - request.send_header("Content-Type", "application/vnd.apache.arrow.file") - request.send_header("x-lancedb-version", "1") + request.send_header( + "Content-Type", f"application/vnd.apache.arrow.{framing}" + ) + header = ( + version_header(body) if callable(version_header) else version_header + ) + if header is not None: + request.send_header("x-lancedb-version", header) + if snapshot_supported: + request.send_header("x-lancedb-query-version", header) + identity = ( + identity_header(body) + if callable(identity_header) + else identity_header + ) + if identity is not None: + request.send_header("x-lancedb-query-snapshot", identity) request.end_headers() - with pa.ipc.new_file(request.wfile, response_table.schema) as writer: - writer.write_table(response_table) + writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream + with writer_factory(request.wfile, response_table.schema) as writer: + writer.write_table(response_table, max_chunksize=1) elif request.path == "/v1/table/test/fetch_blobs/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) assert body["column"] == "image" - assert body["row_ids"] == [10, 20, 30] + if requests is not None: + requests.append(("fetch_blobs", body)) + payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""} + if state["version"] > 1 and body.get("version") != 1: + payloads = {row: b"new-version" for row in payloads} response_table = pa.table( - {"image": pa.array([b"alpha", None, b"gamma"], type=pa.large_binary())} + { + "image": pa.array( + [payloads[row] for row in body["row_ids"]], + type=pa.large_binary(), + ) + } ) request.send_response(200) request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + if verify_identity and request.headers.get("x-lancedb-query-snapshot"): + request.send_header( + "x-lancedb-query-snapshot", + request.headers["x-lancedb-query-snapshot"], + ) request.end_headers() with pa.ipc.new_stream(request.wfile, response_table.schema) as writer: writer.write_table(response_table) + elif request.path == "/v1/table/test/insert/": + if request.headers.get("Transfer-Encoding") == "chunked": + while size := int(request.rfile.readline().split(b";")[0], 16): + request.rfile.read(size) + assert request.rfile.read(2) == b"\r\n" + assert request.rfile.read(2) == b"\r\n" + else: + request.rfile.read(int(request.headers.get("Content-Length", 0))) + state["version"] += 1 + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps({"version": state["version"]}).encode()) else: request.send_response(404) request.end_headers() @@ -5548,6 +5642,222 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): yield db.open_table("test") +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +@pytest.mark.parametrize("method", ["to_arrow", "to_list", "to_pandas", "to_batches"]) +async def test_remote_blob_bytes_conversion(use_async, framing, method): + if method == "to_pandas": + pytest.importorskip("pandas") + requests = [] + with blob_remote_table(framing=framing, requests=requests) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + query = query.select(["id", "image"]) + if method == "to_batches": + kwargs = {"max_batch_length" if use_async else "batch_size": 1} + reader = query.to_batches(blob_mode="bytes", **kwargs) + if use_async: + reader = await reader + batches = [batch async for batch in reader] + else: + batches = list(reader) + assert all(batch.num_rows == 1 for batch in batches) + result = pa.Table.from_batches(batches, schema=reader.schema).to_pylist() + else: + result = getattr(query, method)(blob_mode="bytes") + if use_async: + result = await result + if method == "to_arrow": + assert result.schema.field("image").type == pa.large_binary() + result = result.to_pylist() + elif method == "to_pandas": + result = result.to_dict("records") + assert result == [ + {"id": 1, "image": b"alpha"}, + {"id": 2, "image": None}, + {"id": 3, "image": b"gamma"}, + ] + fetches = [body for path, body in requests if path == "fetch_blobs"] + assert fetches + assert all(body["version"] == 1 for body in fetches) + assert [row for body in fetches for row in body["row_ids"]] == [10, 20, 30] + descriptor_queries = [ + body + for path, body in requests + if path == "query" and body.get("filter", "").startswith("_rowid IN") + ] + assert all(body["version"] == 1 for body in descriptor_queries) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_keeps_query_snapshot_during_writes(use_async, framing): + requests = [] + state = {"version": 1} + with blob_remote_table( + framing=framing, requests=requests, state=state + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + kwargs = {"max_batch_length" if use_async else "batch_size": 1} + reader = query.select(["id", "image"]).to_batches(blob_mode="bytes", **kwargs) + if use_async: + reader = await reader + # The query has selected v1; commit v2 before consuming any payloads. + write = table.add([{"id": 4, "image": b"new-version"}]) + if use_async: + await write + version = await table.version() if use_async else table.version + assert version == 2 + if use_async: + rows = [row async for batch in reader for row in batch.to_pylist()] + else: + rows = [row for batch in reader for row in batch.to_pylist()] + assert [row["image"] for row in rows] == [b"alpha", None, b"gamma"] + fetches = [body for path, body in requests if path == "fetch_blobs"] + assert all(body["version"] == 1 for body in fetches) + # Snapshot fetches must not check out the caller's live handle. + version = await table.version() if use_async else table.version + assert version == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("version_header", [None, "invalid", "0", "-1", str(2**64)]) +async def test_remote_blob_bytes_invalid_snapshot(use_async, version_header): + requests = [] + with blob_remote_table( + version_header=version_header, requests=requests, schema_version="1" + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_empty_results(use_async, framing): + requests = [] + with blob_remote_table( + empty=True, framing=framing, requests=requests + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + result = query.to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result.num_rows == 0 + assert result.schema.field("image").type == pa.large_binary() + assert result.column_names == ["id", "image"] + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("kind", ["vector", "fts", "hybrid"]) +@pytest.mark.parametrize("rerank", [False, True]) +async def test_remote_blob_bytes_search_queries(use_async, kind, rerank): + with blob_remote_table(search_scores=True) as remote_table: + if use_async: + query = remote_table._table.query() + if kind in ("vector", "hybrid"): + query = query.nearest_to([1.0, 2.0]) + if kind in ("fts", "hybrid"): + query = query.nearest_to_text("hello") + elif kind == "vector": + query = remote_table.search([1.0, 2.0], vector_column_name="vector") + elif kind == "fts": + query = remote_table.search("hello", query_type="fts") + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + if rerank: + from lancedb.rerankers import RRFReranker + + class StripMetadataReranker(RRFReranker): + def rerank_vector(self, query, vector_results): + return vector_results.append_column( + "_relevance_score", pa.array([3.0, 2.0, 1.0]) + ).replace_schema_metadata(None) + + def rerank_fts(self, query, fts_results): + return self.rerank_vector(query, fts_results) + + def rerank_hybrid(self, query, vector_results, fts_results): + return ( + super() + .rerank_hybrid(query, vector_results, fts_results) + .replace_schema_metadata(None) + ) + + kwargs = {"query_string": "hello"} if kind == "vector" else {} + query = query.rerank(StripMetadataReranker(), **kwargs) + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result["image"].to_pylist() == [b"alpha", None, b"gamma"] + assert "_rowid" not in result.column_names + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_hybrid_rejects_different_snapshots(use_async): + def header(body): + return "2" if body.get("full_text_query") else "1" + + requests = [] + with blob_remote_table( + search_scores=True, version_header=header, requests=requests + ) as remote_table: + if use_async: + query = ( + remote_table._table.query() + .nearest_to([1.0, 2.0]) + .nearest_to_text("hello") + ) + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + with pytest.raises( + NotImplementedError, match="inconsistent x-lancedb-query-version" + ): + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("with_row_id", [False, True]) +async def test_remote_blob_bytes_alias_and_explicit_row_ids(use_async, with_row_id): + with blob_remote_table() as remote_table: + query = remote_table._table.query() if use_async else remote_table.search() + query = query.select({"payload": "image"}) + if with_row_id: + query = query.with_row_id() if use_async else query.with_row_id(True) + result = query.to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result["payload"].to_pylist() == [b"alpha", None, b"gamma"] + assert ("_rowid" in result.column_names) == with_row_id + if with_row_id: + assert result["_rowid"].to_pylist() == [10, 20, 30] + + def test_remote_blob_columns_and_fetch(): with blob_remote_table() as table: assert table.blob_columns() == ["image"] @@ -5569,7 +5879,7 @@ def test_sync_remote_blob_pandas_avoids_storage_access( raise AssertionError("remote storage must not be opened") monkeypatch.setattr(lance, "dataset", fail_dataset) - with blob_remote_table(location=location) as table: + with blob_remote_table(location=location, version_header=None) as table: monkeypatch.setattr(table, "to_lance", fail_dataset) query = table.search().select(["id", "image"]) if blob_mode == "descriptions": @@ -5582,8 +5892,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access( NotImplementedError, match="stable table snapshot" ) as exc: query.to_pandas(blob_mode=blob_mode) - assert "fetch_blobs(column, row_ids)" in str(exc.value) - assert "with_row_id(True)" in str(exc.value) + if blob_mode == "bytes": + assert "x-lancedb-query-version" in str(exc.value) + else: + assert "fetch_blobs(column, row_ids)" in str(exc.value) + assert "with_row_id(True)" in str(exc.value) @pytest.mark.asyncio @@ -5667,7 +5980,7 @@ async def test_async_remote_blob_descriptions_to_pandas_uses_server(monkeypatch) @pytest.mark.asyncio @pytest.mark.parametrize("blob_mode", ["bytes", "lazy"]) async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode): - with blob_remote_table() as remote_table: + with blob_remote_table(version_header=None) as remote_table: table = remote_table._table async def fail_uri(): @@ -5692,8 +6005,8 @@ async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob @pytest.mark.parametrize("method", ["to_arrow", "to_list"]) -def test_remote_search_bytes_refused_before_query(monkeypatch, method): - with blob_remote_table() as table: +def test_remote_search_bytes_requires_response_version(method): + with blob_remote_table(version_header=None) as table: query = table.search().select(["id", "image"]) descriptions = getattr(query, method)(blob_mode="descriptions") images = ( @@ -5703,19 +6016,15 @@ def test_remote_search_bytes_refused_before_query(monkeypatch, method): ) assert "_lance_row_id" not in images[0] - def fail_query(*args, **kwargs): - raise AssertionError("bytes must be refused before the query runs") - - monkeypatch.setattr(table, "_execute_query", fail_query) - with pytest.raises(NotImplementedError, match="stable table snapshot"): + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): getattr(query, method)(blob_mode="bytes") with pytest.raises(ValueError, match="blob_mode must be one of"): table.to_pandas(blob_mode="handles") @pytest.mark.asyncio -async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch): - with blob_remote_table() as remote_table: +async def test_async_remote_to_arrow_bytes_requires_response_version(monkeypatch): + with blob_remote_table(version_header=None) as remote_table: table = remote_table._table async def fail_fetch(*args, **kwargs): @@ -5723,8 +6032,7 @@ async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch): monkeypatch.setattr(table, "fetch_blobs", fail_fetch) query = table.query().select(["id", "image"]) - monkeypatch.setattr(query, "to_batches", fail_fetch) - with pytest.raises(NotImplementedError, match="stable table snapshot"): + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): await query.to_arrow(blob_mode="bytes") with pytest.raises(NotImplementedError, match="stable table snapshot"): await table.to_arrow(blob_mode="bytes") @@ -5821,7 +6129,7 @@ def test_remote_blob_query_to_pandas(): @pytest.mark.parametrize("blob_mode", ["default", "lazy", "bytes"]) def test_remote_blob_query_to_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode): - with blob_remote_table() as table: + with blob_remote_table(version_header=None) as table: def fail_fetch(*args, **kwargs): raise AssertionError("blob fetch must not use an unpinned remote table") @@ -6884,3 +7192,102 @@ def test_remote_optimize_rejects_explicit_pruning_before_submitting(): table.optimize(delete_unverified=True) assert server.tickets == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_rejects_legacy_watermark(use_async, framing): + requests = [] + with blob_remote_table( + framing=framing, + snapshot_supported=False, + version_header="1", + schema_version="1", + requests=requests, + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + descriptors = query.to_arrow(blob_mode="descriptions") + if use_async: + descriptors = await descriptors + assert descriptors.num_rows == 3 + assert pa.types.is_struct(descriptors.schema.field("image").type) + query = table.query() if use_async else table.search() + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("identity_header", [None, "", "v2:" + "a" * 64, "v1:broken"]) +async def test_remote_blob_bytes_requires_trustworthy_identity( + use_async, identity_header +): + requests = [] + with blob_remote_table( + identity_header=identity_header, schema_version="1", requests=requests + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + # Ordinary descriptors still work, even with forged Arrow schema metadata. + result = query.to_arrow(blob_mode="descriptions") + if use_async: + result = await result + assert result.num_rows == 3 + with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_rejects_unverified_serving_node(use_async): + with blob_remote_table(verify_identity=False) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + with pytest.raises( + NotImplementedError, match="did not verify the query snapshot identity" + ): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnations( + use_async, +): + requests = [] + + def identity(body): + return "v1:" + ("b" if body.get("full_text_query") else "a") * 64 + + with blob_remote_table( + search_scores=True, identity_header=identity, requests=requests + ) as remote_table: + if use_async: + query = ( + remote_table._table.query() + .nearest_to([1.0, 2.0]) + .nearest_to_text("hello") + ) + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + with pytest.raises( + NotImplementedError, match="inconsistent x-lancedb-query-version" + ): + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) diff --git a/python/src/table.rs b/python/src/table.rs index e76bae00a..31cf8d25c 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1978,14 +1978,28 @@ impl Table { } /// Read blob bytes for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids))] + #[pyo3(signature = (column, row_ids, *, version=None, snapshot_identity=None))] pub fn fetch_blobs( self_: PyRef<'_, Self>, column: String, row_ids: Vec, + version: Option, + snapshot_identity: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { + let inner = match (version, snapshot_identity) { + (None, None) => inner, + (Some(version), Some(identity)) => inner + .query_snapshot_with_identity(version, &identity) + .await + .infer_error()?, + _ => { + return Err(PyValueError::new_err( + "deferred blob reads require both query version and snapshot identity", + )); + } + }; let blobs: LargeBinaryArray = inner .fetch_blobs(column.as_str(), &row_ids) .await diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index cc495a83f..d560a4802 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -95,6 +95,34 @@ const MIN_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-ve const MIN_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-timestamp"); const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-read-version"); const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version"); +const QUERY_SNAPSHOT_HEADER: &str = "x-lancedb-query-snapshot"; + +fn valid_query_snapshot_identity(value: &str) -> bool { + value.strip_prefix("v1:").is_some_and(|digest| { + digest.len() == 64 + && digest + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} + +fn check_query_snapshot_response( + expected: Option<&str>, + response: &reqwest::Response, +) -> Result<()> { + if let Some(expected) = expected + && response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + != Some(expected) + { + return Err(Error::NotSupported { message: "Blob response did not verify the query snapshot identity; upgrade every serving node".into() }); + } + Ok(()) +} + +const QUERY_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-query-version"); /// Asks for stream framing, which is decoded as it arrives. Servers that do not /// stream query results ignore this and answer with file framing. const QUERY_ACCEPT: &str = @@ -613,6 +641,7 @@ pub struct RemoteTable { /// Stamped onto every branch-accepting request so reads and writes resolve /// on the branch's own version chain rather than main's. branch: Option, + expected_query_snapshot: Option, } impl std::fmt::Debug for RemoteTable { @@ -855,6 +884,7 @@ impl RemoteTable { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -891,6 +921,7 @@ impl RemoteTable { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, + expected_query_snapshot: None, } } @@ -1170,20 +1201,37 @@ impl RemoteTable { .and_then(|value| value.to_str().ok()) .map(str::to_owned); let framing = resolve_arrow_ipc_framing(content_type.as_deref(), request_id)?; + let table_version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); - match framing { + // Legacy version headers are freshness watermarks, not proof that the + // query and a later Blob read use the same immutable dataset. + let query_version = response + .headers() + .get(&QUERY_VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); + + let query_identity = response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .map(str::to_owned); + + let stream = match framing { ArrowIpcFraming::Stream => { - let table_version = response - .headers() - .get(&VERSION_HEADER) - .and_then(|value| value.to_str().ok()) - .and_then(|value| value.parse().ok()); ipc_stream::read_ipc_stream( response.bytes_stream(), request_id.to_string(), table_version, ) - .await + .await? } ArrowIpcFraming::File => { // File framing keeps its footer at the end, so the whole body is @@ -1192,9 +1240,21 @@ impl RemoteTable { let reader = FileReader::try_new(Cursor::new(body), None)?; let schema = reader.schema(); let stream = futures::stream::iter(reader).map_err(DataFusionError::from); - Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + Box::pin(RecordBatchStreamAdapter::new(schema, stream)) as SendableRecordBatchStream } + }; + // Bind subsequent blob reads to the response's snapshot, never to a + // version sampled from the live table before or after the query. + let mut metadata = stream.schema().metadata().clone(); + metadata.remove("lancedb:query_version"); + metadata.remove("lancedb:query_snapshot"); + if let Some(identity) = query_identity { + metadata.insert("lancedb:query_snapshot".into(), identity); } + if let Some(version) = query_version { + metadata.insert("lancedb:query_version".into(), version.to_string()); + } + Ok(with_stream_metadata(stream, metadata)) } fn apply_query_params( @@ -1620,9 +1680,37 @@ impl RemoteTable { streams.await? }; + if let Some(first) = streams.first() { + let schema = first.schema(); + if streams.iter().skip(1).any(|stream| { + stream.schema().metadata().get("lancedb:query_version") + != schema.metadata().get("lancedb:query_version") + }) { + return Err(Error::Runtime { + message: "Remote query responses refer to different table snapshots; retry the query against a fixed version".into(), + }); + } + } + + let identities_agree = streams.first().is_none_or(|first| { + streams.iter().skip(1).all(|stream| { + stream.schema().metadata().get("lancedb:query_snapshot") + == first.schema().metadata().get("lancedb:query_snapshot") + }) + }); Ok(streams .into_iter() .map(|stream| { + // Ordinary descriptor queries remain usable during an upgrade. + // Deferred bytes require every leg's identity, so never preserve + // the first leg's capability when another leg lacks or differs. + let stream = if identities_agree { + stream + } else { + let mut metadata = stream.schema().metadata().clone(); + metadata.remove("lancedb:query_snapshot"); + with_stream_metadata(stream, metadata) + }; let stream = restore_projection_order(stream, &query.base().select); match deadline { Some((deadline, timeout)) => { @@ -1673,6 +1761,26 @@ impl RemoteTable { } } +fn with_stream_metadata( + stream: SendableRecordBatchStream, + metadata: HashMap, +) -> SendableRecordBatchStream { + let schema = Arc::new( + stream + .schema() + .as_ref() + .clone() + .with_metadata(metadata.clone()), + ); + let batches = stream.map(move |batch| { + batch.map(|mut batch| { + batch.schema_metadata_mut().clone_from(&metadata); + batch + }) + }); + Box::pin(RecordBatchStreamAdapter::new(schema, batches)) +} + fn restore_projection_order( stream: Pin>, select: &Select, @@ -1921,6 +2029,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -1948,6 +2057,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -1984,6 +2094,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } } @@ -2570,6 +2681,23 @@ impl BaseTable for RemoteTable { } } } + async fn query_snapshot_with_identity( + &self, + version: u64, + identity: &str, + ) -> Result> { + if version == 0 || !valid_query_snapshot_identity(identity) { + return Err(Error::InvalidInput { + message: "invalid or unsupported query snapshot identity".into(), + }); + } + let mut snapshot = self.with_branch(self.branch.clone()); + *snapshot.version.write().await = Some(version); + snapshot.reset_freshness(None, true); + snapshot.expected_query_snapshot = Some(identity.to_owned()); + Ok(Arc::new(snapshot)) + } + async fn query_snapshot(&self) -> Result> { let description = self.describe().await?; let TableDescription { @@ -6704,8 +6832,15 @@ mod tests { assert_eq!(request_sizes.lock().unwrap().as_slice(), &[1024, 1]); } + #[rstest::rstest] + #[case(false)] + #[case(true)] #[tokio::test] - async fn test_fetch_blobs_splits_byte_limited_requests_and_reads_large_blob_by_range() { + async fn test_fetch_blobs_splits_byte_limited_requests_and_reads_large_blob_by_range( + #[case] guarded: bool, + ) { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // Simulate a lower byte cap so this test exercises the same 400 response // without allocating 64 MiB of blob data. let requests = Arc::new(std::sync::Mutex::new(Vec::new())); @@ -6714,8 +6849,15 @@ mod tests { "my_table", semver::Version::new(0, 5, 0), move |request| { + if guarded { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + } let path = request.url().path(); if path == "/v1/table/my_table/describe/" { + assert!( + !guarded, + "a later describe cannot establish the producing identity" + ); return http::Response::builder() .status(200) .body(br#"{"version":42,"schema":{"fields":[]}}"#.to_vec()) @@ -6766,6 +6908,7 @@ mod tests { return http::Response::builder() .status(200) .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .body(write_ipc_stream_uncompressed(&batch)) .unwrap(); } @@ -6781,12 +6924,14 @@ mod tests { match range { "bytes=0-0" => http::Response::builder() .status(206) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .header(reqwest::header::CONTENT_RANGE, "bytes 0-0/10") .header(VERSION_HEADER, "42") .body(b"0".to_vec()) .unwrap(), "bytes=0-9" => http::Response::builder() .status(206) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .header(reqwest::header::CONTENT_RANGE, "bytes 0-9/10") .body(b"0123456789".to_vec()) .unwrap(), @@ -6795,6 +6940,14 @@ mod tests { }, ); + let table = if guarded { + table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap() + } else { + table + }; let blobs = table .fetch_blobs("image", &[10, 20, 30, 40, 20]) .await diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 345b731c5..a0051c955 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -33,8 +33,8 @@ use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; use crate::table::{AnyQuery, BaseTable}; use super::{ - FreshnessHeaders, FreshnessState, ReadSnapshot, RemoteTable, VERSION_HEADER, - freshness_headers_snapshot, + FreshnessHeaders, FreshnessState, QUERY_SNAPSHOT_HEADER, ReadSnapshot, RemoteTable, + VERSION_HEADER, check_query_snapshot_response, freshness_headers_snapshot, }; // The Cloud route rejects larger row-id lists. Its separate 64 MiB byte limit @@ -93,6 +93,7 @@ struct TableBlobRangeRequester { version: Option, branch: Option, source_uri: Option, + expected_query_snapshot: Option, source_commit_micros: Option, row_is_address: bool, freshness: Arc>, @@ -125,6 +126,9 @@ impl BlobRangeRequester for TableBlobRangeRequester { .apply(self.client.get(&self.path)) .header(header::RANGE, range_header) }; + if let Some(identity) = &self.expected_query_snapshot { + request = request.header(QUERY_SNAPSHOT_HEADER, identity); + } if let Some(version) = version.or(self.version) { request = request.query(&[("version", version)]); } @@ -140,6 +144,10 @@ impl BlobRangeRequester for TableBlobRangeRequester { request = request.query(&[("source_commit_micros", timestamp)]); } let (request_id, response) = self.client.send_with_retry(request, None, true).await?; + if response.status().is_success() || response.status() == StatusCode::RANGE_NOT_SATISFIABLE + { + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + } // Preserve 416 size-probe responses so the caller can detect empty blobs. if response.status() == StatusCode::RANGE_NOT_SATISFIABLE && matches!(mode, RangeRequestMode::SizeProbe) @@ -531,7 +539,11 @@ impl RemoteTable { // A dotted path needs client-side validation because the server may // report an internal type mismatch when the path crosses a list. Use // an already cached schema for top-level list fields as well. - if column.contains('.') || self.schema_cache.try_get().is_some() { + // Guarded readers must validate the producing identity on the server + // before consulting any schema resolved from a later logical binding. + if self.expected_query_snapshot.is_none() + && (column.contains('.') || self.schema_cache.try_get().is_some()) + { let schema = self.schema().await?; crate::blob::reject_list_blob_column(schema.as_ref(), column)?; } @@ -539,6 +551,9 @@ impl RemoteTable { } async fn explain_list_blob_bad_request(&self, column: &str, error: Error) -> Error { + if self.expected_query_snapshot.is_some() { + return error; + } let is_bad_request = match &error { Error::Http { status_code: Some(code), @@ -648,9 +663,17 @@ impl RemoteTable { .client .post(&format!("/v1/table/{}/fetch_blobs/", self.identifier)) .json(&body); + let request = if let Some(identity) = &self.expected_query_snapshot { + request.header(QUERY_SNAPSHOT_HEADER, identity) + } else { + request + }; let (request_id, response) = self .send_with_freshness(request, true, read_snapshot.freshness) .await?; + if response.status().is_success() { + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + } let mut stream = match self.read_arrow_response(&request_id, response).await { Ok(stream) => stream, Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), @@ -1023,6 +1046,7 @@ impl RemoteTable { version: read_snapshot.version, branch: source.map_or_else(|| self.branch.clone(), |source| source.branch.clone()), source_uri: source.map(|source| source.uri.clone()), + expected_query_snapshot: self.expected_query_snapshot.clone(), source_commit_micros: source.map(|source| source.committed_at_micros), row_is_address: source.is_some_and(|source| source.row_is_address), freshness: Arc::new(std::sync::Mutex::new(read_snapshot.freshness_state)), diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 18a5b7ddf..db68ab290 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -832,6 +832,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "blob_columns is not supported on this table type".into(), }) } + /// Bind a remote payload reader to an identity from its producing query. + async fn query_snapshot_with_identity( + &self, + _version: u64, + _identity: &str, + ) -> Result> { + Err(Error::NotSupported { + message: "query snapshot identities are not supported on this table type".into(), + }) + } /// Materialize blob bytes for the given row ids. See [`Table::fetch_blobs`]. async fn fetch_blobs(&self, _column: &str, _row_ids: &[u64]) -> Result { Err(Error::NotSupported { @@ -1352,6 +1362,19 @@ impl Table { }) } + /// Create an independent remote handle constrained by a query response. + #[doc(hidden)] + pub async fn query_snapshot_with_identity(&self, version: u64, identity: &str) -> Result { + Ok(Self { + inner: self + .inner + .query_snapshot_with_identity(version, identity) + .await?, + database: self.database.clone(), + embedding_registry: self.embedding_registry.clone(), + }) + } + /// Count the number of rows in this dataset. /// /// # Arguments From 9755c57d4111425b81f6fe4494ed58a3bf5cc416 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 03:20:20 +0800 Subject: [PATCH 14/36] fix: prune Function outcomes for replaced fragments (#5005) An input-preserving merge can fail freshness preservation after a successful data write: the replaced fragment loses its signature, but its known/failed-row records remain and fail sidecar validation. This affects tables with persisted Function outcome metadata. Prune both outcome maps with the same live-fragment set used for signatures and row state. Outcomes on untouched fragments remain intact, and inserted rows remain pending fill. The regression performs a real mixed update/insert and reopens the resulting snapshot to check both output columns. Native validation on Linux: the exact regression fails before the fix with `failure evidence names a fragment without a signature`. At `20b10d80408cb455d9e5827f5d7d36a117622dea`, all 24 discovered `table::freshness::tests::function_write_` cases pass, including the new real merge regression. Test lists, counts and logs were retained and SHA-256 verified. [Current-head CI passed both workspace Clippy configurations](https://github.com/lancedb/lancedb/actions/runs/43274052568/job/131377627811). A separate package-only, default-feature Clippy command reported dead-code errors in seven files unchanged from the base; that local failure is retained rather than represented as a pass. Other hosted gates are pending. This does not claim downstream Sophon integration or deployed acceptance. --- rust/lancedb/src/table/freshness.rs | 97 +++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 477020fc3..645653a46 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -1879,6 +1879,8 @@ pub async fn preserve_function_freshness( pending_fill.retain(|id, _| live.contains(id)); state.signatures.retain(|id, _| live.contains(id)); state.row_state.retain(|id, _| live.contains(id)); + state.failure_coverage.retain(|id, _| live.contains(id)); + state.failed_rows.retain(|id, _| live.contains(id)); state.basis.clear(); let reference = write_sidecar(dataset, &state.normalize()?).await?; let fill_reference = if pending_fill.is_empty() { @@ -3029,6 +3031,101 @@ mod tests { } } + #[tokio::test] + async fn function_write_prunes_outcomes_for_replaced_fragments() { + let table = fresh_function_table().await; + let mut dataset = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .as_ref() + .clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + let failures = FailureEvidence { + known_rows: BTreeMap::from([ + (0, RoaringBitmap::from_iter([0, 1])), + (1, RoaringBitmap::from_iter([0, 1])), + ]), + failed_rows: BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]), + }; + for column in ["search_text", "search_token_count"] { + record_freshness_with_failures( + &mut dataset, + None, + column, + "fb_01K3TEXT", + &inputs, + signatures.clone(), + &failures, + ) + .await + .unwrap(); + } + + // Replace all of fragment 0, insert one uncomputed row, and leave + // fragment 1 (including its retained failure evidence) untouched. + let source = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "e"]), + ("spare", Int32, [1, 1, 1]) + ) + .unwrap(); + let mut merge = + MergeInsertBuilder::try_new(Arc::new(dataset), vec!["title".into()]).unwrap(); + merge.when_matched(WhenMatched::UpdateAll); + merge.when_not_matched(WhenNotMatched::InsertAll); + let (merged, stats) = merge + .try_build() + .unwrap() + .execute_reader(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + let mut dataset = merged.as_ref().clone(); + assert!(!dataset.get_fragments().iter().any(|f| f.id() == 0)); + assert!(dataset.get_fragments().iter().any(|f| f.id() == 1)); + preserve_function_freshness( + &mut dataset, + FunctionWrite::Merge { + source_schema: &source.schema(), + on: &["title".into()], + num_inserted_rows: stats.num_inserted_rows, + }, + ) + .await + .unwrap(); + + let reopened = dataset + .checkout_version(dataset.version().version) + .await + .unwrap(); + for column in ["search_text", "search_token_count"] { + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&reopened, column, "fb_01K3TEXT", &inputs) + .await + .unwrap() + else { + panic!("the preserved sidecar should retain failure evidence"); + }; + assert_eq!( + failures.known_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([0, 1]))]) + ); + assert_eq!( + failures.failed_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]) + ); + assert_eq!(staleness.pending_fill.len(), 1); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] From 1806dc232395d2a446a2eef17886194b5dd27051 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 12 Nov 2026 11:34:14 -0800 Subject: [PATCH 15/36] ci(java): publish beta releases to Fury instead of Maven Central (#5011) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Java publishing has failed since `v0.42.0-beta.10` because the `lancedb` Sonatype org hit Maven Central's monthly release-count limit: ```text Publishing blocked: your organization has reached its monthly release count limit. Grace period ended 2026-11-08. Usage resets 2026-12-01. ``` This sends beta tags to `https://maven.fury.io/lancedb/` instead, matching how Python publishes betas to `pypi.fury.io/lancedb`. Stable releases still go to Maven Central. ```text tag contains "beta" -> setup-java server "fury" -> mvn deploy -P deploy-to-fury otherwise -> setup-java server "ossrh" -> mvn deploy -P deploy-to-ossrh ``` - `java/pom.xml`: new `deploy-to-fury` profile that points `distributionManagement` at Fury. - `java/README.md`: explains how to add the Fury and `maven.lance.org` repositories to use a beta. Requires a `FURY_TOKEN` secret with push access to the `lancedb` Fury account. The token is passed as the Maven username with a placeholder password. That follows Gemfury's convention but hasn't been tested against Fury yet. ## Evidence Running the beta path locally (`deploy -pl lancedb-core -am -P deploy-to-fury`) against a file repository deployed `lancedb-parent` (POM) and `lancedb-core` (JAR, POM, sources, javadoc). `help:effective-pom -P deploy-to-fury` resolves the release repository to `https://maven.fury.io/lancedb/`. ## Merge Risk **Door:** Two-way. This only changes where future betas are published; reverting the workflow restores Central publishing. **Blast Radius:** `release-ci`. Beta consumers need the extra repository; stable consumers are unaffected. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .github/workflows/java-publish.yml | 20 +++++++++++++----- java/README.md | 34 ++++++++++++++++++++++++++++++ java/pom.xml | 9 ++++++++ 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/.github/workflows/java-publish.yml b/.github/workflows/java-publish.yml index 094aa552a..35d052de9 100644 --- a/.github/workflows/java-publish.yml +++ b/.github/workflows/java-publish.yml @@ -39,9 +39,11 @@ jobs: distribution: temurin java-version: 8 cache: "maven" - server-id: ossrh - server-username: SONATYPE_USER - server-password: SONATYPE_TOKEN + # Betas go to Fury and stable releases to Maven Central, which limits + # how many releases an organization may publish each month. + server-id: ${{ contains(github.ref, 'beta') && 'fury' || 'ossrh' }} + server-username: ${{ contains(github.ref, 'beta') && 'FURY_TOKEN' || 'SONATYPE_USER' }} + server-password: ${{ contains(github.ref, 'beta') && 'FURY_PASSWORD' || 'SONATYPE_TOKEN' }} gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} gpg-passphrase: MAVEN_GPG_PASSPHRASE - name: Set git config @@ -52,8 +54,16 @@ jobs: if: github.event_name == 'pull_request' run: | ./mvnw --batch-mode -DskipTests package -pl lancedb-core -am - - name: Publish - if: startsWith(github.ref, 'refs/tags/v') + - name: Publish to Fury + if: startsWith(github.ref, 'refs/tags/v') && contains(github.ref, 'beta') + run: | + ./mvnw --batch-mode -DskipTests deploy -pl lancedb-core -am -P deploy-to-fury + env: + FURY_TOKEN: ${{ secrets.FURY_TOKEN }} + # Fury authenticates with the token as the username; the password is ignored. + FURY_PASSWORD: NOPASS + - name: Publish to Maven Central + if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, 'beta') run: | echo "use-agent" >> ~/.gnupg/gpg.conf echo "pinentry-mode loopback" >> ~/.gnupg/gpg.conf diff --git a/java/README.md b/java/README.md index fd163b9f1..85e7e85ba 100644 --- a/java/README.md +++ b/java/README.md @@ -1,5 +1,39 @@ # LanceDB Java Enterprise Client +## Installation + +Stable releases of `com.lancedb:lancedb-core` are published to Maven Central. + +Beta releases are published to `https://maven.fury.io/lancedb/` instead. They +depend on Lance beta releases, which are published to `https://maven.lance.org`. +To use a beta, add both repositories alongside Maven Central: + +```xml + + + lancedb + https://maven.fury.io/lancedb/ + + + lance + https://maven.lance.org + + +``` + +For Gradle: + +```kotlin +repositories { + mavenCentral() + maven { url = uri("https://maven.fury.io/lancedb/") } + maven { url = uri("https://maven.lance.org") } +} +``` + +Use an explicit version, including the full `-beta.N` suffix. Beta versions are +Maven releases, not `SNAPSHOT` versions. + ## Configuration and Initialization ### LanceDB Cloud (legacy) diff --git a/java/pom.xml b/java/pom.xml index df709fb4f..fc89ebe4c 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -318,6 +318,15 @@ + + deploy-to-fury + + + fury + https://maven.fury.io/lancedb/ + + + deploy-to-ossrh From 6d24446a3043fcb22a73c2c9aed21b62a5648938 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 04:03:04 +0800 Subject: [PATCH 16/36] feat: add negotiated batched blob range reads across SDKs (#4994) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Existing Rust and Python blob range calls must keep working when only the SDK is upgraded. Add negotiated batched range reads across Rust, Python sync/async and TypeScript, preserving ordered NULLs, duplicates and branch/version reads with splitting and reassembly at 1,024 ranges or 64 MiB per request. Only a successful describe response advertising `x-lancedb-blob-ranges: 1` selects the batched endpoint. Missing or unknown capability values select the existing descriptor-query plus BlobFile Range GET route before the operation. Endpoint failures never switch protocols. HTTP 400 preserves the server message and request ID as Rust `InvalidInput` / Python `ValueError`; other errors retain their existing semantics. The operation binds both numeric version and immutable snapshot identity from its producing query or first range response. Every later partition and oversized-range piece sends that original identity and requires an equal response identity before decoding. Same-name table recreation therefore fails explicitly instead of returning mixed old/new payloads; no partial array is returned on later failure. Targets `main`. The read-buffering prerequisite #4979, safe-write prerequisite #4977 and deferred-query identity prerequisite #4973 are merged into main; #5000 also supplies the merged SQL timeout-test prerequisite. Server support is [Sophon #10219](https://github.com/lancedb/sophon/pull/10219), including #10211. Exact SDK `1497b508324662180086a4d1e0a6eb9e0b3970db` and server `f39712c2c150b220eb831e00f6663c9eef32dce5` passed a real local SDK → REST → PE experiment: one Rust harness test, 14 assertion groups, 38 REST range requests and 34 PE RPCs. All four sync/async × warm/cold table-recreation cases failed explicitly before the second descriptor lookup or PE dispatch, with no mixed payload or partial result. The other groups retained 1,025-range success, 70 MiB reassembly, branch/version reads, overwrite snapshot consistency, error behavior and TypeScript buffer ownership. Bindings were rebuilt and their loaded hashes verified. This is local interoperability evidence, not Cloud, mixed-fleet or deployed header-forwarding acceptance. The server dependency upgrade, External/cache/URI-policy acceptance and validated rollout remain required. Enforcing PE support must precede QN and SDK enablement; identity does not retain versions or freeze External objects. This PR does not claim deployed support or complete ENT-3100/GA acceptance. Published documentation retains the Early access badge and released Enterprise instructions, including explicit fetches for copying. The new Enterprise `blob_mode="bytes"` guidance, snapshot-bound copy example, future streaming restrictions and GA wording remain source-only MDX drafts until release. The correction distinguishing released Enterprise SQL bytes from SDK descriptors remains visible. Documentation validation checked comment boundaries, visible instructions, Python example syntax and whitespace; the site was not built. The main integration keeps these release gates unchanged. Main integration at `0491d9bdcc65ce5d52ea93e1083c89e951ea4f9d` normally merges main `9b13e8f72530c8b1950c09685f6920711154a539`, including its Lance beta.18 dependency. Focused current-source validation passed: 493 remote-table/query/Blob/IPC/write-progress Rust tests, 23 shared create/write-body tests, 59 native Blob integration tests and 7 public HTTP range tests. Rebuilt Python passed 468 selected tests (one optional PyAV test skipped), and rebuilt TypeScript passed 194 selected tests across four suites; lint/format, TypeScript compilation and API documentation generation passed. Shared tests include actual HTTP multipart failures, acknowledgment boundaries, dictionary compaction and native Blob compaction. The 598 unrelated Jest cases excluded by the focused shared-suite selector were not run. The retained 14-group joint REST/PE experiment used the earlier exact candidates stated above. Operation-identity/range/IPC code is unchanged, but dependencies and shared write interfaces changed with main; the new local checks validate the SDK combination and do not constitute a fresh final-head SDK/server joint, Cloud or rollout run. Early access and every remaining server/External/cache/policy/dependency/rollout condition remain in force. CI snapshot on this head (2026-11-12 18:30 UTC): `build-no-lock` failed in the standalone `ci/tests/test_build_no_lock.py` fixture at the retained-rlib assertion, before the actual SDK no-lock build. The fixture, helper and Rust workflow are byte-identical to main; the fixture does not load SDK source. The underlying CI/environment cause is not diagnosed here. Other jobs remained pending/running at the snapshot, so CI is not reported as passing. Failure: https://github.com/lancedb/lancedb/actions/runs/43280277756/job/131399418284. --- docs/src/js/classes/Table.md | 42 ++ docs/src/js/globals.md | 1 + docs/src/js/type-aliases/BlobRangeRequest.md | 39 ++ docs/web/management/table.mdx | 27 + nodejs/__test__/blob_ranges.test.ts | 589 ++++++++++++++++ nodejs/__test__/table.test.ts | 37 + nodejs/lancedb/blob.ts | 10 + nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 49 +- nodejs/src/blob.rs | 50 +- nodejs/src/table.rs | 29 +- python/python/lancedb/table.py | 12 +- python/python/tests/test_blob_ranges.py | 380 +++++++++++ python/python/tests/test_remote_db.py | 46 +- rust/lancedb/src/blob.rs | 2 +- rust/lancedb/src/remote/db.rs | 10 +- rust/lancedb/src/remote/table.rs | 28 + rust/lancedb/src/remote/table/blobs.rs | 400 ++++++++++- .../src/remote/table/blobs/aggregate.rs | 136 +++- rust/lancedb/src/table.rs | 21 +- rust/lancedb/tests/remote_blob_ranges.rs | 634 ++++++++++++++++++ 21 files changed, 2473 insertions(+), 70 deletions(-) create mode 100644 docs/src/js/type-aliases/BlobRangeRequest.md create mode 100644 nodejs/__test__/blob_ranges.test.ts create mode 100644 python/python/tests/test_blob_ranges.py create mode 100644 rust/lancedb/tests/remote_blob_ranges.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 431796843..3150d94ec 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -650,6 +650,48 @@ tables; no partial handles are returned. *** +### fetchBlobRanges() + +```ts +abstract fetchBlobRanges( + column, + requests, + options?): Promise<(null | Buffer)[]> +``` + +Materializes row-specific byte ranges at the table's current checkout. +Preserves request order, duplicates, and nulls. Zero length returns an empty +buffer for a non-null blob. Invalid ranges or missing rows reject the entire +call. See [Table.fetchBlobs](Table.md#fetchblobs) for row-ID validity across versions. + +Remote tables use the batched endpoint when the server advertises support, +splitting at 1024 ranges and 64 MiB, including individual larger ranges. +Older servers use descriptor queries and BlobFile range reads. Both protocols +use one exact branch and version. Errors from an advertised endpoint propagate +without switching protocols. All output bytes occupy memory. + +#### Parameters + +* **column**: `string` + +* **requests**: readonly [`BlobRangeRequest`](../type-aliases/BlobRangeRequest.md)[] + +* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md) + +#### Returns + +`Promise`<(`null` \| `Buffer`)[]> + +#### Example + +```ts +const bytes = await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1024n }, +]); +``` + +*** + ### fetchBlobs() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 19d7ceb97..beed7c8af 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -169,6 +169,7 @@ - [BlobMode](type-aliases/BlobMode.md) - [BlobOptions](type-aliases/BlobOptions.md) - [BlobRange](type-aliases/BlobRange.md) +- [BlobRangeRequest](type-aliases/BlobRangeRequest.md) - [BlobReadOptions](type-aliases/BlobReadOptions.md) - [BlobUri](type-aliases/BlobUri.md) - [Data](type-aliases/Data.md) diff --git a/docs/src/js/type-aliases/BlobRangeRequest.md b/docs/src/js/type-aliases/BlobRangeRequest.md new file mode 100644 index 000000000..daa231260 --- /dev/null +++ b/docs/src/js/type-aliases/BlobRangeRequest.md @@ -0,0 +1,39 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobRangeRequest + +# Type Alias: BlobRangeRequest + +```ts +type BlobRangeRequest: object; +``` + +One row-specific range for [Table.fetchBlobRanges](../classes/Table.md#fetchblobranges). + +## Type declaration + +### length + +```ts +length: bigint; +``` + +Number of bytes to read, as a uint64. Zero returns an empty non-null value. + +### offset + +```ts +offset: bigint; +``` + +Byte offset from the beginning of the logical blob, as a uint64. + +### rowId + +```ts +rowId: bigint | number; +``` + +A row ID from a query with row IDs enabled. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 031342fbc..bf6bf3edd 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -736,6 +736,10 @@ The other fetch methods load bytes directly: | Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | | Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | +{/* Draft for the TypeScript cross-row Blob range release. Replace the row above: +| Byte slices across many rows in one call | `fetch_blob_ranges` | `fetchBlobRanges` | `fetch_blob_ranges` | +*/} + - `fetch_blobs` returns the full bytes for each row ID in order. Null blobs produce null entries, and empty blobs produce empty byte strings. - `fetch_blob_files` loads bytes when you call `read`, `read_range`, or @@ -759,6 +763,21 @@ The other fetch methods load bytes directly: +{/* Draft for the TypeScript cross-row Blob range release. + +Upcoming-release draft: TypeScript adds `fetchBlobRanges` for cross-row slices. +Until that SDK release is available, use `fetchBlobFiles` and `readRanges`. +Server-side batching requires a deployment with the validated range capability; +older servers continue using the descriptor and Range path selected before the +read. An error from the selected batched endpoint is returned without fallback. +A batched call keeps the native snapshot identity from its first range response +across every partition and requires each serving node to verify it. Missing identity +support or a replaced/deleted snapshot fails the whole call; upgrade all serving +nodes before selecting the batched endpoint with a new SDK. +Custom TypeScript `Table` subclasses must implement the new abstract method. + +*/} + Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, `read_ranges` reads more than one slice of one blob. Python takes `(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an @@ -770,6 +789,14 @@ exclusive `end`, and Rust takes `start..end` ranges: + {/* Draft for the TypeScript cross-row Blob range release. + {`// Upcoming-release draft: slices from more than one row. +const slices = await blobTable.fetchBlobRanges("image", [ + { rowId: rowIds[0]!, offset: 0n, length: 6n }, + { rowId: rowIds[1]!, offset: 7n, length: 5n }, +]); +`}{"\n"} + */} {TsBlobApiRanges} diff --git a/nodejs/__test__/blob_ranges.test.ts b/nodejs/__test__/blob_ranges.test.ts new file mode 100644 index 000000000..7d2fab566 --- /dev/null +++ b/nodejs/__test__/blob_ranges.test.ts @@ -0,0 +1,589 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { createHash } from "crypto"; +import { getEventListeners } from "events"; +import { createReadStream } from "fs"; +import * as http from "http"; +import { AddressInfo } from "net"; +import { + Table as ArrowTable, + Binary, + Field, + LargeBinary, + Struct, + Uint8, + Uint32, + Uint64, + Utf8, + tableToIPC, + vectorFromArray, +} from "apache-arrow"; +import { BlobRangeRequest, Connection, Table, connect } from "../lancedb"; + +jest.setTimeout(30000); + +const IDENTITY = `v1:${"a".repeat(64)}`; +const MIB = 1024 * 1024; +type Range = { + // biome-ignore lint/style/useNamingConvention: Matches the server JSON contract. + row_id: number; + offset: number; + length: number; +}; +type Request = { + column: string; + branch: string | null; + version: number | null; + ranges: Range[]; + identity?: string; +}; + +function payload(row: number, offset: number, length: number, version: number) { + const bytes = Buffer.alloc(length); + for (let i = 0; i < length; i++) { + bytes[i] = (row * 17 + ((offset + i) % 251) + version) % 251; + } + return bytes; +} + +async function withRangeServer( + run: (db: Connection, calls: Request[], paths: string[]) => Promise, + fault?: string | number, + capability: string | null = "1", + onStall?: () => void, +) { + let takes = 0; + const calls: Request[] = []; + const paths: string[] = []; + const server = http.createServer((req, res) => { + req.setTimeout(15000); + paths.push(req.url ?? ""); + if ( + req.url === "/v1/table/test/describe/" || + req.url === "/v1/table/test/branches/list/" + ) { + res.writeHead(200, { + "Content-Type": "application/json", + "phalanx-version": "1.13.0-beta.0", + ...(req.url.endsWith("/describe/") && capability !== null + ? { "x-lancedb-blob-ranges": capability } + : {}), + }); + const response = req.url.endsWith("branches/list/") + ? { + branches: { + experiment: { + parentBranch: null, + parentVersion: 1, + createAt: 1, + manifestSize: 1, + }, + }, + } + : { version: 8, schema: { fields: [] } }; + res.end(JSON.stringify(response)); + return; + } + if (capability !== "1" && req.method === "GET") { + const url = new URL(req.url!, "http://localhost"); + expect(url.searchParams.get("branch")).toBe("experiment"); + expect(url.searchParams.get("version")).toBe("3"); + const [start, end] = req.headers.range!.slice(6).split("-").map(Number); + const bytes = Buffer.from("alpha").subarray(start, end + 1); + res + .writeHead(206, { + "Content-Range": `bytes ${start}-${end}/5`, + "Content-Length": bytes.length, + "x-lancedb-version": "3", + }) + .end(bytes); + return; + } + expect(req.method).toBe("POST"); + expect(req.url).toBe( + capability === "1" + ? "/v1/table/test/fetch_blob_ranges/" + : "/v1/table/test/query/", + ); + const chunks: Buffer[] = []; + let size = 0; + req.on("data", (chunk: Buffer) => { + size += chunk.length; + expect(size).toBeLessThanOrEqual(256 * 1024); + chunks.push(chunk); + }); + req.on("end", () => { + if (capability !== "1") { + const body = JSON.parse(Buffer.concat(chunks).toString()) as { + branch: string; + version: number; + filter: string; + }; + expect(body.branch).toBe("experiment"); + expect(body.version).toBe(3); + takes++; + const ids = (body.filter.match(/\d+/g) ?? []) + .map(Number) + .filter((id) => [10, 20, 40].includes(id)) + .reverse(); + const descriptor = new Struct([ + new Field("kind", new Uint8(), false), + new Field("position", new Uint64(), false), + new Field("size", new Uint64(), false), + new Field("blob_id", new Uint32(), false), + new Field("blob_uri", new Utf8(), false), + ]); + const arrow = new ArrowTable({ + image: vectorFromArray( + ids.map((id) => + id === 20 + ? null + : { + kind: 0, + position: 0n, + size: id === 40 ? 0n : 5n, + // biome-ignore lint/style/useNamingConvention: Arrow descriptor field. + blob_id: 0, + // biome-ignore lint/style/useNamingConvention: Arrow descriptor field. + blob_uri: "", + }, + ), + descriptor, + ), + _rowid: vectorFromArray(ids.map(BigInt), new Uint64()), + }); + expect(takes).toBeGreaterThan(0); + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + "x-lancedb-version": "3", + }) + .end(tableToIPC(arrow, "stream")); + return; + } + const body = JSON.parse(Buffer.concat(chunks).toString()) as Request; + body.identity = req.headers["x-lancedb-query-snapshot"] as + | string + | undefined; + calls.push(body); + expect(body.column).toBe("image"); + expect(body.branch).toBe("experiment"); + expect(body.ranges.length).toBeLessThanOrEqual(1024); + expect( + body.ranges.reduce((sum, range) => sum + range.length, 0), + ).toBeLessThanOrEqual(64 * MIB); + const version = body.version ?? (calls.length === 1 ? 7 : 8); + const failure = + calls.length > 1 || String(fault).startsWith("first-") + ? fault + : undefined; + if (failure === "recreated" || failure === "gone") { + res + .writeHead(failure === "recreated" ? 400 : 404) + .end("query snapshot identity mismatch: source gone or replaced"); + return; + } + if (failure === "stall" && calls.length === 2) { + res.writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + "x-lancedb-version": "7", + "x-lancedb-query-snapshot": IDENTITY, + }); + res.flushHeaders(); + onStall?.(); + return; + } + if (typeof failure === "number") { + res.writeHead(failure).end("ordinary server failure"); + return; + } + if (failure === "disconnect") { + req.socket.destroy(); + return; + } + let values = body.ranges.map((range) => + range.row_id === 20 + ? null + : payload(range.row_id, range.offset, range.length, version), + ); + if (failure === "count") values = []; + if (failure === "length") values = [Buffer.alloc(0)]; + const arrow = new ArrowTable({ + [failure === "column" ? "wrong" : "value"]: vectorFromArray( + values, + failure === "type" ? new Binary() : new LargeBinary(), + ), + }); + let ipc = tableToIPC(arrow, "stream"); + if (failure === "eos") ipc = ipc.subarray(0, ipc.length - 8); + if (failure === "body") ipc = ipc.subarray(0, Math.floor(ipc.length / 2)); + res.writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + connection: "close", + "Content-Length": ipc.length + (failure === "transport" ? 10 : 0), + ...(failure === "version" ? {} : { "x-lancedb-version": version }), + ...(["missing-identity", "first-missing-identity"].includes( + String(failure), + ) + ? {} + : { + "x-lancedb-query-snapshot": + failure === "wrong-identity" + ? `v1:${"b".repeat(64)}` + : failure === "first-invalid-identity" + ? "broken" + : IDENTITY, + }), + }); + // Fragment the generated IPC payload across actual HTTP writes. + for (let i = 0; i < ipc.length; i += 8192) + res.write(ipc.subarray(i, i + 8192)); + res.end(); + }); + }); + server.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const port = (server.address() as AddressInfo).port; + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${port}`, + clientConfig: { + retryConfig: { retries: 2, connectRetries: 2, readRetries: 2 }, + blobRequestConcurrency: 1, + timeoutConfig: { timeout: 20 }, + }, + }); + try { + await run(db, calls, paths); + } finally { + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + } +} + +async function open(db: Connection, version?: number): Promise { + return db.openTable("test", [], { branch: "experiment", version }); +} + +describe("fetchBlobRanges", () => { + it.each([null, "0", "2"])( + "uses old routes before data requests for capability %s", + async (capability) => { + await withRangeServer( + async (db, calls, paths) => { + // Reopening exercises both the initial and cached database describe paths. + for (let i = 0; i < 2; i++) { + const table = await open(db, 3); + const requests = [ + { rowId: 10n, offset: 1n, length: 3n }, + { rowId: 20n, offset: 0n, length: 1n }, + { rowId: 40n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 5n, length: 0n }, + { rowId: 10n, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("lph"), + null, + Buffer.alloc(0), + Buffer.alloc(0), + Buffer.from("lph"), + ]); + for (const row of [ + { rowId: 10n, offset: 4n, length: 2n }, + { rowId: 99n, offset: 0n, length: 1n }, + ]) + await expect( + table.fetchBlobRanges("image", [row]), + ).rejects.toThrow(); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + expect(paths).toHaveLength(before); + } + expect(calls).toHaveLength(0); + expect(paths.some((path) => path.includes("fetch_blob_ranges"))).toBe( + false, + ); + }, + undefined, + capability, + ); + }, + ); + + it("renegotiates advertised support when reopening a cached table", async () => { + await withRangeServer(async (db, calls) => { + for (let i = 0; i < 2; i++) { + const table = await open(db); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, i === 0 ? 7 : 8)]); + } + expect(calls).toHaveLength(2); + }); + }); + + it("cancels while waiting for a later response body and releases the only permit", async () => { + let markStalled!: () => void; + const stalled = new Promise((resolve) => { + markStalled = resolve; + }); + await withRangeServer( + async (db, calls) => { + const table = await open(db); + const controller = new AbortController(); + const pending = table.fetchBlobRanges( + "image", + Array.from({ length: 2049 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + { signal: controller.signal }, + ); + const rejected = expect(pending).rejects.toMatchObject({ + name: "AbortError", + }); + await stalled; + controller.abort(); + await rejected; + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + expect(calls).toHaveLength(2); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, 8)]); + expect(calls).toHaveLength(3); + }, + "stall", + "1", + () => markStalled(), + ); + }); + it.each([undefined, 3])( + "preserves order, nulls, duplicates and snapshot (checkout %s)", + async (version) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db, version); + const requests: BlobRangeRequest[] = Array.from( + { length: 1025 }, + (_, i) => ({ + rowId: i % 9 === 0 ? 20 : 10 + (i % 7), + offset: BigInt(i), + length: BigInt(i % 4), + }), + ); + requests.push( + { rowId: 10n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 2n, length: 3n }, + { rowId: 10n, offset: 2n, length: 3n }, + ); + const result = await table.fetchBlobRanges("image", requests); + expect(result).toEqual( + requests.map((range) => + Number(range.rowId) === 20 + ? null + : payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + version ?? 7, + ), + ), + ); + expect(calls.map((body) => body.version)).toEqual([ + version ?? null, + version ?? 7, + ]); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, version ?? 8)]); + expect(calls[2].version).toBe(version ?? null); + expect( + paths.filter((path) => path.endsWith("fetch_blob_ranges/")), + ).toHaveLength(3); + }); + }, + ); + + it("partitions the byte budget and reassembles one range larger than 64 MiB", async () => { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = [ + { rowId: 10n, offset: 3n, length: BigInt(65 * MIB) }, + { rowId: 30n, offset: 7n, length: 2n }, + ]; + const result = await table.fetchBlobRanges("image", requests); + for (const [i, range] of requests.entries()) { + expect(result[i]?.length).toBe(Number(range.length)); + expect( + createHash("sha256") + .update(result[i] as Buffer) + .digest("hex"), + ).toBe( + createHash("sha256") + .update( + payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + 7, + ), + ) + .digest("hex"), + ); + } + expect(calls).toHaveLength(2); + expect(calls.map((body) => body.version)).toEqual([null, 7]); + }); + }); + + it.each([ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ])("rejects the whole call after a later %s failure", async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(); + expect(calls).toHaveLength(2); + expect( + paths.every( + (path) => + path.endsWith("describe/") || + path.endsWith("branches/list/") || + path.endsWith("fetch_blob_ranges/"), + ), + ).toBe(true); + }, fault); + }); + + it.each(["missing-identity", "wrong-identity", "recreated", "gone"])( + "retains original identity through row and byte partitions (%s)", + async (fault) => { + for (const huge of [false, true]) { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = huge + ? [{ rowId: 10n, offset: 0n, length: BigInt(64 * MIB + 1) }] + : Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })); + await expect( + table.fetchBlobRanges("image", requests), + ).rejects.toThrow(); + expect(calls.map((call) => call.identity)).toEqual([ + undefined, + IDENTITY, + ]); + expect(calls.map((call) => call.version)).toEqual([null, 7]); + }, fault); + } + }, + ); + + it.each(["first-missing-identity", "first-invalid-identity"])( + "requires a first authoritative bulk identity (%s)", + async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(/snapshot identity/); + expect(calls).toHaveLength(1); + expect(paths).toHaveLength(before + 1); + }, fault); + }, + ); + + it("validates integers, overflow and cancellation and leaves empty calls at zero I/O", async () => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + for (const request of [ + { rowId: -1, offset: 0n, length: 1n }, + { rowId: 1.5, offset: 0n, length: 1n }, + { rowId: Number.MAX_SAFE_INTEGER + 1, offset: 0n, length: 1n }, + { rowId: -1n, offset: 0n, length: 1n }, + { rowId: 1n << 64n, offset: 0n, length: 1n }, + { rowId: 10n, offset: -1n, length: 1n }, + { rowId: 10n, offset: 0n, length: -1n }, + { rowId: 10n, offset: 0n, length: 1n << 64n }, + { rowId: 20n, offset: (1n << 64n) - 1n, length: 1n }, + ]) { + await expect( + table.fetchBlobRanges("image", [request]), + ).rejects.toThrow(); + } + // Runtime type validation must also reject a number passed as an offset. + await expect( + table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0 as unknown as bigint, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + controller.abort(new Error("cancelled by caller")); + await expect( + table.fetchBlobRanges( + "image", + [{ rowId: 10n, offset: 0n, length: 1n }], + { signal: controller.signal }, + ), + ).rejects.toThrow("cancelled by caller"); + expect(paths).toHaveLength(before); + expect(calls).toHaveLength(0); + }); + }); + + it("records the loaded native artifact", async () => { + const artifacts = Object.keys(require.cache).filter( + (path) => path.endsWith(".node") && path.includes("lancedb"), + ); + expect(artifacts.length).toBeGreaterThan(0); + for (const path of artifacts) { + const hash = createHash("sha256"); + for await (const chunk of createReadStream(path)) hash.update(chunk); + console.log( + `loaded native artifact=${path} sha256=${hash.digest("hex")}`, + ); + } + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index b803e9043..59d6929b4 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3019,6 +3019,43 @@ describe("when dealing with blob columns", () => { expect(bytes.map((b) => b?.toString())).toEqual(["new", "hi"]); }); + it("fetchBlobRanges reads local ranges with order, duplicates, nulls and validation", async () => { + const { table, rowIds } = await openBlobTable(); + const [alphaId, betaId, nullId] = rowIds; + const requests = [ + { rowId: betaId, offset: 1n, length: 3n }, + { rowId: alphaId, offset: 0n, length: 2n }, + { rowId: nullId, offset: 0n, length: 1n }, + { rowId: alphaId, offset: 5n, length: 0n }, + { rowId: betaId, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("eta"), + Buffer.from("al"), + null, + Buffer.alloc(0), + Buffer.from("eta"), + ]); + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + await expect( + table.fetchBlobRanges("image", [ + { rowId: alphaId, offset: 4n, length: 2n }, + ]), + ).rejects.toThrow(); + await expect( + table.fetchBlobRanges("image", [ + { rowId: (1n << 63n) - 1n, offset: 0n, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + expect( + await table.fetchBlobRanges("image", requests, { + signal: controller.signal, + }), + ).toHaveLength(5); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + }); + it("discovers blob columns", async () => { const { table } = await openBlobTable(); expect(await table.blobColumns()).toEqual(["image"]); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 67e662175..a46484314 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -305,6 +305,16 @@ export async function runWithSignal( } } +/** One row-specific range for {@link Table.fetchBlobRanges}. */ +export type BlobRangeRequest = { + /** A row ID from a query with row IDs enabled. */ + rowId: bigint | number; + /** Byte offset from the beginning of the logical blob, as a uint64. */ + offset: bigint; + /** Number of bytes to read, as a uint64. Zero returns an empty non-null value. */ + length: bigint; +}; + /** A half-open byte range `[start, end)` for {@link BlobFile.readRanges}. */ export type BlobRange = { start: bigint; diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 35697dc8c..08a254bdb 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -91,6 +91,7 @@ export type { BlobInput, BlobOptions, BlobRange, + BlobRangeRequest, BlobReadOptions, BlobUri, } from "./blob"; diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 185088424..136eb1d6c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -17,7 +17,12 @@ import { tableFromIPC, } from "./arrow"; -import { BlobFile, BlobReadOptions, runWithSignal } from "./blob"; +import { + BlobFile, + BlobRangeRequest, + BlobReadOptions, + runWithSignal, +} from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; import { IndexOptions } from "./indices"; import { Job } from "./job"; @@ -683,6 +688,31 @@ export abstract class Table { options?: BlobReadOptions, ): Promise<(Buffer | null)[]>; + /** + * Materializes row-specific byte ranges at the table's current checkout. + * Preserves request order, duplicates, and nulls. Zero length returns an empty + * buffer for a non-null blob. Invalid ranges or missing rows reject the entire + * call. See {@link Table.fetchBlobs} for row-ID validity across versions. + * + * Remote tables use the batched endpoint when the server advertises support, + * splitting at 1024 ranges and 64 MiB, including individual larger ranges. + * Older servers use descriptor queries and BlobFile range reads. Both protocols + * use one exact branch and version. Errors from an advertised endpoint propagate + * without switching protocols. All output bytes occupy memory. + * + * @example + * ```ts + * const bytes = await table.fetchBlobRanges("image", [ + * { rowId: 10n, offset: 0n, length: 1024n }, + * ]); + * ``` + */ + abstract fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]>; + /** * Opens lazy blob handles for `column` at the given row IDs using the * table's current checkout. @@ -1510,6 +1540,23 @@ export class LocalTable extends Table { return values.map((value) => value ?? null); } + async fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]> { + const rowIds = rowIdsToBigInts(requests.map((request) => request.rowId)); + const ranges = requests.map((request, i) => ({ + rowId: rowIds[i], + offset: request.offset, + length: request.length, + })); + const values = await runWithSignal(options?.signal, (signal) => + this.inner.fetchBlobRanges(column, ranges, signal), + ); + return values.map((value) => value ?? null); + } + async fetchBlobFiles( column: string, rowIds: readonly (bigint | number)[], diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs index 59cf61af6..b55154019 100644 --- a/nodejs/src/blob.rs +++ b/nodejs/src/blob.rs @@ -21,6 +21,25 @@ pub struct BlobRange { pub end: BigInt, } +#[napi(object)] +pub struct BlobRangeRequest { + pub row_id: BigInt, + pub offset: BigInt, + pub length: BigInt, +} + +impl BlobRangeRequest { + pub(crate) fn parse(self) -> napi::Result { + let row_id = parse_u64(self.row_id, "row id")?; + let offset = parse_u64(self.offset, "offset")?; + let length = parse_u64(self.length, "length")?; + offset + .checked_add(length) + .ok_or_else(|| napi::Error::from_reason("blob range offset + length overflows u64"))?; + Ok(lancedb::blob::BlobRangeRequest::new(row_id, offset, length)) + } +} + #[napi] pub struct BlobFile { inner: Arc, @@ -205,14 +224,25 @@ pub fn parse_row_ids(row_ids: Vec) -> napi::Result> { .collect() } -pub fn copy_blob_buffers(array: LargeBinaryArray) -> Vec> { - (0..array.len()) - .map(|i| { - if array.is_null(i) { - None - } else { - Some(Buffer::from(array.value(i).to_vec())) - } - }) - .collect() +pub fn copy_blob_buffers(array: LargeBinaryArray) -> napi::Result>> { + let allocation_error = + |error| napi::Error::from_reason(format!("cannot allocate blob result: {error}")); + let mut result = Vec::new(); + result + .try_reserve_exact(array.len()) + .map_err(allocation_error)?; + for value in array.iter() { + let buffer = value + .map(|value| { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(value.len()) + .map_err(allocation_error)?; + bytes.extend_from_slice(value); + Ok::<_, napi::Error>(Buffer::from(bytes)) + }) + .transpose()?; + result.push(buffer); + } + Ok(result) } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 7076bbec1..f6abeb553 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -17,7 +17,7 @@ use napi::bindgen_prelude::*; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; -use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable}; +use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; use crate::error::NapiErrorExt; use crate::index::Index; use crate::job::JobFailureInfo; @@ -420,7 +420,32 @@ impl Table { .fetch_blobs(column.as_str(), &row_ids) .await .default_error()?; - Ok(copy_blob_buffers(array)) + copy_blob_buffers(array) + }) + } + + #[napi(catch_unwind)] + pub fn fetch_blob_ranges<'env>( + &self, + env: &'env Env, + column: String, + requests: Vec, + signal: Option, + ) -> napi::Result>>> { + let mut ranges = Vec::new(); + ranges.try_reserve_exact(requests.len()).map_err(|error| { + napi::Error::from_reason(format!("cannot allocate blob range requests: {error}")) + })?; + for request in requests { + ranges.push(request.parse()?); + } + let table = self.inner_ref()?.clone(); + spawn_abortable(env, signal, async move { + let array = table + .fetch_blob_ranges(column.as_str(), ranges) + .await + .default_error()?; + copy_blob_buffers(array) }) } diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 3161eda30..5f0af7a66 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2661,8 +2661,12 @@ class Table(ABC): results are returned. Row IDs can be obtained from a query with ``with_row_id(True)``. - LanceDB Enterprise reads the requested ranges through version-pinned blob - handles using HTTP byte-range requests. + LanceDB Enterprise uses the batched endpoint when the server advertises + support, partitioning at 1024 ranges and 64 MiB, including individual + larger ranges. Older servers use descriptor queries and BlobFile range + reads. Both protocols read one exact branch and version without changing + the table's checkout. Errors from an advertised endpoint propagate without + switching protocols. The final output occupies memory. """ @abstractmethod @@ -8652,6 +8656,10 @@ class AsyncTable: column: str, requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: + """Materialize row-specific byte ranges. + + See [Table.fetch_blob_ranges][lancedb.table.Table.fetch_blob_ranges]. + """ return await self._inner.fetch_blob_ranges(column, list(requests)) async def fetch_blob_files( diff --git a/python/python/tests/test_blob_ranges.py b/python/python/tests/test_blob_ranges.py new file mode 100644 index 000000000..c65dfb8ae --- /dev/null +++ b/python/python/tests/test_blob_ranges.py @@ -0,0 +1,380 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Exercise the public sync/async range APIs over bounded loopback HTTP.""" + +import asyncio +import hashlib +import json +from pathlib import Path +import socket +import threading + +import lancedb._lancedb as native +import pyarrow as pa +import pytest + +from lancedb.remote.errors import HttpError, TableNotFoundError +from test_remote_db import mock_lancedb_connection + +MIB = 1024 * 1024 +IDENTITY = "v1:" + "a" * 64 +ROUTE = "/v1/table/test/fetch_blob_ranges/" + + +def payload(row, offset, length, version): + pattern = bytes((row * 17 + i + version) % 251 for i in range(251)) + start = offset % 251 + return (pattern * ((start + length + 250) // 251))[start : start + length] + + +class RangeServer: + def __init__(self, fault=None): + self.fault = fault + self.calls = [] + self.fetches = [] + self.identities = [] + self.stalled = threading.Event() + self.release = threading.Event() + + def __call__(self, request): + request.connection.settimeout(15) + size = int(request.headers.get("Content-Length", 0)) + assert size <= 256 * 1024 + body = json.loads(request.rfile.read(size) or b"{}") + self.calls.append((request.command, request.path, body)) + if request.path in ( + "/v1/table/test/describe/", + "/v1/table/test/branches/list/", + ): + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.send_header("phalanx-version", "1.13.0-beta.0") + if request.path.endswith("/describe/"): + request.send_header("x-lancedb-blob-ranges", "1") + request.end_headers() + response = ( + { + "branches": { + "experiment": { + "parentBranch": None, + "parentVersion": 1, + "createAt": 1, + "manifestSize": 1, + } + } + } + if request.path.endswith("branches/list/") + else {"version": 8, "schema": {"fields": []}} + ) + request.wfile.write(json.dumps(response).encode()) + return + assert (request.command, request.path) == ("POST", ROUTE) + self.fetches.append(body) + self.identities.append(request.headers.get("x-lancedb-query-snapshot")) + assert body["column"] == "image" + assert body["branch"] == "experiment" + ranges = body["ranges"] + assert len(ranges) <= 1024 + assert sum(r["length"] for r in ranges) <= 64 * MIB + version = body["version"] or (7 if len(self.fetches) == 1 else 8) + values = [ + None + if r["row_id"] == 20 + else payload(r["row_id"], r["offset"], r["length"], version) + for r in ranges + ] + fault = ( + self.fault + if len(self.fetches) > 1 or str(self.fault).startswith("first-") + else None + ) + if fault in ("recreated", "gone"): + request.send_response(400 if fault == "recreated" else 404) + request.end_headers() + request.wfile.write( + b"query snapshot identity mismatch: source gone or replaced" + ) + return + if fault == "stall" and len(self.fetches) == 2: + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", str(version)) + request.send_header("x-lancedb-query-snapshot", IDENTITY) + request.end_headers() + request.wfile.flush() + self.stalled.set() + assert self.release.wait(15), "test did not release stalled response" + return + if fault == "structured400": + request.send_response(400) + request.send_header("x-lancedb-error-code", "invalid_input") + request.end_headers() + request.wfile.write(b'{"error":"range exceeds blob size"}') + return + if isinstance(fault, int): + request.send_response(fault) + request.end_headers() + request.wfile.write(b"ordinary server failure") + return + if fault == "disconnect": + request.connection.shutdown(socket.SHUT_RDWR) + return + column = "wrong" if fault == "column" else "value" + data_type = pa.binary() if fault == "type" else pa.large_binary() + if fault == "count": + values = [] + elif fault == "length": + values = [b""] + batch = pa.table({column: pa.array(values, type=data_type)}) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, batch.schema) as writer: + writer.write_table(batch, max_chunksize=257) + ipc = sink.getvalue().to_pybytes() + if fault == "eos": + ipc = ipc[:-8] + elif fault == "body": + ipc = ipc[: len(ipc) // 2] + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + if fault != "version": + request.send_header("x-lancedb-version", str(version)) + if fault not in ("missing-identity", "first-missing-identity"): + identity = ( + "broken" + if fault == "first-invalid-identity" + else "v1:" + "b" * 64 + if fault == "wrong-identity" + else IDENTITY + ) + request.send_header("x-lancedb-query-snapshot", identity) + request.send_header( + "Content-Length", str(len(ipc) + (10 if fault == "transport" else 0)) + ) + request.end_headers() + for i in range(0, len(ipc), 8192): + request.wfile.write(ipc[i : i + 8192]) + + +async def fetch(table, requests, use_async): + result = table.fetch_blob_ranges("image", requests) + return await result if use_async else result + + +def api(db, use_async, version=None): + table = db.open_table("test", branch="experiment", version=version) + return table._table if use_async else table + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("version", [None, 3]) +async def test_range_sdk_order_snapshot_and_overwrite(use_async, version): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async, version) + requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)] + requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)] + result = await fetch(table, requests, use_async) + assert isinstance(result, pa.LargeBinaryArray) + assert result.to_pylist() == [ + None if row == 20 else payload(row, offset, length, version or 7) + for row, offset, length in requests + ] + assert [b["version"] for b in handler.fetches] == [version, version or 7] + result = await fetch(table, [(10, 0, 1)], use_async) + assert result.to_pylist() == [payload(10, 0, 1, version or 8)] + assert handler.fetches[-1]["version"] == version + assert len(handler.fetches) == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_cached_reopen_negotiates_capability(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + for version in (7, 8): + table = api(db, use_async) + result = await fetch(table, [(10, 0, 1)], use_async) + assert result.to_pylist() == [payload(10, 0, 1, version)] + assert len(handler.fetches) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_large_single_and_aggregate_budget(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + requests = [ + (10, 3, 33 * MIB), + (30, 7, 33 * MIB), + (40, 11, 70 * MIB), + (20, 0, 2**64 - 1), + ] + # The loopback server advances latest after the first partition. + result = await fetch(table, requests, use_async) + assert len(result) == 4 + for i, (row, offset, length) in enumerate(requests[:3]): + expected = payload(row, offset, length, 7) + assert ( + hashlib.sha256(result[i].as_buffer()).digest() + == hashlib.sha256(expected).digest() + ) + assert len(result[i].as_buffer()) == length + assert result[3].as_py() is None + assert len(handler.fetches) == 3 + assert [b["version"] for b in handler.fetches] == [None, 7, 7] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "fault", + [ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ], +) +async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault): + handler = RangeServer(fault=fault) + with mock_lancedb_connection( + handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2} + ) as db: + table = api(db, use_async) + with pytest.raises(Exception) as exc: + await fetch(table, [(10, 0, 1)] * 1025, use_async) + if fault == 404: + assert isinstance(exc.value, TableNotFoundError) + assert isinstance(exc.value.__cause__, HttpError) + assert exc.value.__cause__.status_code == 404 + else: + assert not isinstance(exc.value, ValueError) + if isinstance(fault, int): + assert exc.value.status_code == fault + assert len(handler.fetches) == 2 + assert all( + path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE) + for _, path, _ in handler.calls + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_structured_400_preserves_value_error(use_async): + handler = RangeServer(fault="structured400") + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + with pytest.raises(ValueError, match="range exceeds blob size"): + await fetch(table, [(10, 0, 1)] * 1025, use_async) + assert len(handler.fetches) == 2 + + +@pytest.mark.asyncio +async def test_range_sdk_async_cancel_releases_only_request_permit(): + handler = RangeServer(fault="stall") + with mock_lancedb_connection(handler, blob_request_concurrency=1) as db: + table = api(db, True) + pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True)) + try: + assert await asyncio.to_thread(handler.stalled.wait, 10) + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert len(handler.fetches) == 2 + result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5) + assert result.to_pylist() == [payload(10, 0, 1, 8)] + assert len(handler.fetches) == 3 + finally: + pending.cancel() + handler.release.set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_integer_validation_and_empty_zero_io(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + before = len(handler.calls) + assert (await fetch(table, [], use_async)).to_pylist() == [] + for request in [ + (-1, 0, 1), + (2**64, 0, 1), + (10, -1, 1), + (10, 0, -1), + (10, 0, 2**64), + (10, 0.5, 1), + (20, 2**64 - 1, 1), + (10, 0), + ]: + with pytest.raises((ValueError, OverflowError, TypeError)): + await fetch(table, [request], use_async) + assert len(handler.calls) == before + + +def test_range_sdk_loaded_artifact_identity(): + artifact = Path(native.__file__).resolve() + digest = hashlib.sha256() + with artifact.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}") + assert artifact.is_file() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "fault", ["missing-identity", "wrong-identity", "recreated", "gone"] +) +@pytest.mark.parametrize("huge", [False, True]) +async def test_range_sdk_original_identity_survives_every_partition( + use_async, fault, huge +): + handler = RangeServer(fault=fault) + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025 + error = ( + ValueError + if fault == "recreated" + else TableNotFoundError + if fault == "gone" + else NotImplementedError + ) + with pytest.raises( + error, match="snapshot identity" if fault != "gone" else None + ): + await fetch(table, requests, use_async) + assert handler.identities == [None, IDENTITY] + assert len(handler.fetches) == 2 + assert [body["version"] for body in handler.fetches] == [None, 7] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"]) +async def test_range_sdk_bulk_requires_identity_before_payload_acceptance( + use_async, fault +): + handler = RangeServer(fault=fault) + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + before = len(handler.calls) + with pytest.raises(NotImplementedError, match="snapshot identity"): + await fetch(table, [(10, 0, 1)] * 1025, use_async) + assert len(handler.fetches) == 1 + assert len(handler.calls) == before + 1 diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 561a0f900..4f707f041 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5466,6 +5466,7 @@ def blob_remote_table( *, server_version=Version("0.5.0"), location=None, + range_capability=None, version_header="1", framing="file", requests=None, @@ -5487,6 +5488,8 @@ def blob_remote_table( request.send_response(200) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", str(server_version)) + if range_capability is not None: + request.send_header("x-lancedb-blob-ranges", range_capability) request.end_headers() response = dict(BLOB_DESCRIBE_RESPONSE) response["version"] = body.get("version") or state["version"] @@ -5594,6 +5597,42 @@ def blob_remote_table( writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream with writer_factory(request.wfile, response_table.schema) as writer: writer.write_table(response_table, max_chunksize=1) + elif ( + range_capability == "1" + and request.path == "/v1/table/test/fetch_blob_ranges/" + ): + size = int(request.headers["Content-Length"]) + body = json.loads(request.rfile.read(size)) + payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""} + values = [] + for item in body["ranges"]: + row, offset, length = ( + item[key] for key in ("row_id", "offset", "length") + ) + error = None + if row not in payloads: + error = "only 1 exist" + elif payloads[row] is not None and offset + length > len(payloads[row]): + error = "range exceeds blob size" + if error: + request.send_response(400) + request.end_headers() + request.wfile.write(error.encode()) + return + payload = payloads[row] + values.append( + None if payload is None else payload[offset : offset + length] + ) + response_table = pa.table( + {"value": pa.array(values, type=pa.large_binary())} + ) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", "1") + request.send_header("x-lancedb-query-snapshot", "v1:" + "a" * 64) + request.end_headers() + with pa.ipc.new_stream(request.wfile, response_table.schema) as writer: + writer.write_table(response_table) elif request.path == "/v1/table/test/fetch_blobs/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) @@ -5901,8 +5940,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access( @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) -async def test_remote_fetch_blob_ranges(use_async): - with blob_remote_table() as remote_table: +@pytest.mark.parametrize("range_capability", [None, "0", "2", "1"]) +async def test_remote_fetch_blob_ranges(use_async, range_capability): + with blob_remote_table( + server_version="1.13.0-beta.0", range_capability=range_capability + ) as remote_table: table = remote_table._table if use_async else remote_table requests = [ (30, 2, 3), diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index ead1f2410..82f502250 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -356,7 +356,7 @@ impl BlobFile { /// /// `row_id` is obtained from a query with row ids enabled. /// `offset` and `length` are relative to the beginning of the logical blob. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct BlobRangeRequest { /// Row id of the blob value to read. pub row_id: u64, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index b562f41df..578e3bbab 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1655,9 +1655,9 @@ impl Database for RemoteDatabase { let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; let rsp = RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; - self.client.check_response(&request_id, rsp).await?; + let rsp = self.client.check_response(&request_id, rsp).await?; - Ok(Arc::new(RemoteTable::new_with_sql_client( + let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), self.db_name.clone(), request.name, @@ -1665,7 +1665,9 @@ impl Database for RemoteDatabase { identifier, version, self.sql_client.clone(), - ))) + )); + table.seed_blob_ranges_capability(rsp.headers()); + Ok(table) } else { // Describe the table to confirm it exists before moving on. let req = self @@ -1676,6 +1678,7 @@ impl Database for RemoteDatabase { RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; let rsp = self.client.check_response(&request_id, rsp).await?; let version = parse_server_version(&request_id, &rsp)?; + let describe_headers = rsp.headers().clone(); let describe_body = rsp.text().await.ok(); let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), @@ -1686,6 +1689,7 @@ impl Database for RemoteDatabase { version.clone(), self.sql_client.clone(), )); + table.seed_blob_ranges_capability(&describe_headers); // This describe already carries the schema, so hand it to the table // instead of making the first schema read fetch it again. A version or // branch pin applied after this invalidates the cache. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index d560a4802..fdb547afa 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -86,6 +86,7 @@ use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::io::Cursor; use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime}; use tokio::sync::RwLock; @@ -634,6 +635,8 @@ pub struct RemoteTable { version: Arc>>, location: RwLock>, schema_cache: BackgroundCache, + // Only a successful describe can opt into the batched range protocol. + blob_ranges_supported: Arc, // WAL-PK-FUSION: delete, with its initializers below. wal_pk_fusion: PkFusionMemory, freshness: Arc>, @@ -881,6 +884,7 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -888,6 +892,15 @@ impl RemoteTable { } } + pub(super) fn seed_blob_ranges_capability(&self, headers: &http::HeaderMap) { + self.blob_ranges_supported.store( + headers + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + } + /// Seed the schema cache from a `describe` body the caller already fetched. /// /// Best effort. `open_table` succeeds today without reading this body, so a @@ -918,6 +931,7 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: self.blob_ranges_supported.clone(), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, @@ -1067,6 +1081,7 @@ impl RemoteTable { }; let response = self.check_table_response(&request_id, response).await?; + self.seed_blob_ranges_capability(response.headers()); match response.text().await { Ok(body) => { @@ -1943,6 +1958,7 @@ async fn fetch_schema( read_snapshot: ReadSnapshot, branch: Option, freshness: Arc>, + blob_ranges_supported: Arc, ) -> Result { let mut body = serde_json::json!({ "version": read_snapshot.version }); if let Some(branch) = &branch { @@ -1969,6 +1985,13 @@ async fn fetch_schema( let response = client.check_response(&request_id, response).await?; freshness_headers.observe_headers(&freshness, response.headers()); + blob_ranges_supported.store( + response + .headers() + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); let body = response.text().await.map_err(|e| { let status_code = e.status(); Error::Http { @@ -2026,6 +2049,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2054,6 +2078,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2091,6 +2116,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2885,6 +2911,7 @@ impl BaseTable for RemoteTable { let table_name = self.name.clone(); let branch = self.branch.clone(); let freshness = self.freshness.clone(); + let blob_ranges_supported = self.blob_ranges_supported.clone(); match self .schema_cache @@ -2896,6 +2923,7 @@ impl BaseTable for RemoteTable { read_snapshot, branch, freshness, + blob_ranges_supported, ) .await }) diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index a0051c955..3367d2218 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -35,11 +35,13 @@ use crate::table::{AnyQuery, BaseTable}; use super::{ FreshnessHeaders, FreshnessState, QUERY_SNAPSHOT_HEADER, ReadSnapshot, RemoteTable, VERSION_HEADER, check_query_snapshot_response, freshness_headers_snapshot, + valid_query_snapshot_identity, }; // The Cloud route rejects larger row-id lists. Its separate 64 MiB byte limit // is handled by splitting a rejected request below. const MAX_FETCH_BLOBS_ROW_IDS: usize = 1024; +const MAX_FETCH_BLOB_RANGE_BYTES: u64 = 64 * 1024 * 1024; fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { matches!(error, Error::Http { @@ -599,7 +601,7 @@ impl RemoteTable { read_snapshot.version = Some(self.describe_read_snapshot(read_snapshot).await?.version); } let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); - let mut blobs = BlobAccumulator::new(row_ids.len()); + let mut blobs = BlobAccumulator::new(row_ids.len())?; while let Some(ids) = pending.pop() { match self .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) @@ -642,7 +644,7 @@ impl RemoteTable { } } - Ok(blobs.finish()) + Ok(blobs.finish()?) } async fn fetch_blobs_chunk( @@ -725,11 +727,88 @@ impl RemoteTable { Ok(()) } - /// Materialize ranges through version-pinned handles, preserving nulls and order. + /// Materialize ranges using the protocol advertised by a successful describe. pub(super) async fn fetch_blob_ranges_impl( &self, column: &str, requests: &[BlobRangeRequest], + ) -> Result { + let mut blobs = BlobAccumulator::new(requests.len())?; + if requests.is_empty() { + return Ok(blobs.finish()?); + } + for request in requests { + request + .offset + .checked_add(request.length) + .ok_or_else(|| Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + })?; + } + self.reject_list_blob_path_if_known(column).await?; + if !self.blob_ranges_supported.load(Ordering::Relaxed) { + return self.fetch_blob_ranges_legacy(column, requests).await; + } + // Select the protocol before issuing data requests. An advertised endpoint + // failing in a mixed deployment must fail truthfully, without fallback. + let mut snapshot = self.snapshot_read_state().await; + let mut identity = self.expected_query_snapshot.clone(); + let mut index = 0; + let mut consumed = 0; + let mut ranges = Vec::new(); + ranges + .try_reserve_exact(MAX_FETCH_BLOBS_ROW_IDS) + .map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + while index < requests.len() { + ranges.clear(); + let continuation = consumed != 0; + let mut budget = MAX_FETCH_BLOB_RANGE_BYTES; + while index < requests.len() && ranges.len() < MAX_FETCH_BLOBS_ROW_IDS { + let request = requests[index]; + let remaining = request.length - consumed; + if budget == 0 && remaining != 0 { + break; + } + let length = remaining.min(budget); + // The full range was checked above; all subranges fit within it. + ranges.push(BlobRangeRequest::new( + request.row_id, + request.offset + consumed, + length, + )); + consumed += length; + budget -= length; + if consumed == request.length { + index += 1; + consumed = 0; + } else { + break; + } + } + let array = self + .fetch_blob_ranges_chunk(column, &ranges, &mut snapshot, &mut identity) + .await?; + // A null has no bytes to partition. Avoid sending arbitrarily many + // empty fragments for a null with a very large requested length. + if consumed != 0 && array.is_null(array.len() - 1) { + index += 1; + consumed = 0; + } + if continuation { + blobs.append_continuation(&array)?; + } else { + blobs.append(&array)?; + } + } + Ok(blobs.finish()?) + } + + async fn fetch_blob_ranges_legacy( + &self, + column: &str, + requests: &[BlobRangeRequest], ) -> Result { let row_ids = requests .iter() @@ -738,16 +817,12 @@ impl RemoteTable { let files = self.fetch_blob_files_impl(column, &row_ids).await?; let mut builder = LargeBinaryBuilder::with_capacity(requests.len(), 0); for (file, request) in files.into_iter().zip(requests) { - let end = - request - .offset - .checked_add(request.length) - .ok_or_else(|| Error::InvalidInput { - message: "blob range offset + length overflows u64".into(), - })?; match file { Some(file) => { - let bytes = file.read_range(request.offset..end).await?; + // Overflow was checked before selecting either protocol. + let bytes = file + .read_range(request.offset..request.offset + request.length) + .await?; builder.append_value(bytes); } None => builder.append_null(), @@ -756,6 +831,162 @@ impl RemoteTable { Ok(builder.finish()) } + async fn fetch_blob_ranges_chunk( + &self, + column: &str, + ranges: &[BlobRangeRequest], + snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result { + let _permit = self + .client + .blob_request_semaphore + .clone() + .acquire_owned() + .await + .expect("blob request semaphore is never closed"); + let body = serde_json::json!({ + "column": column, + "version": snapshot.version, + "branch": self.branch, + "ranges": ranges, + }); + let request = self + .client + .post(&format!("/v1/table/{}/fetch_blob_ranges/", self.identifier)) + .json(&body); + let request = if let Some(expected) = identity.as_deref() { + request.header(super::QUERY_SNAPSHOT_HEADER, expected) + } else { + request + }; + let (request_id, response) = self + .send_with_freshness(request, false, snapshot.freshness) + .await?; + // The range operation defines 400 as invalid input. Let the established + // checker decode structured/plain server errors before normalizing it. + let response = self + .check_table_response(&request_id, response) + .await + .map_err(|error| { + if let Error::Http { + source, + request_id, + status_code: Some(StatusCode::BAD_REQUEST), + } = error + { + Error::InvalidInput { + message: format!("fetch_blob_ranges (request {request_id}): {source}"), + } + } else { + error + } + })?; + let invalid = |message: String| Error::Http { + source: format!("fetch_blob_ranges: {message}").into(), + request_id: request_id.clone(), + status_code: None, + }; + let version = response.headers().get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version != 0) + .ok_or_else(|| invalid("missing or invalid x-lancedb-version; a server supporting the batched range endpoint is required".into()))?; + if snapshot.version.is_some_and(|expected| expected != version) { + return Err(invalid(format!( + "response version {version} differs from requested version {:?}", + snapshot.version + ))); + } + // Do not decode or accept any payload before establishing/verifying the + // identity. A later partition can never replace the original expectation. + check_query_snapshot_response(identity.as_deref(), &response)?; + if identity.is_none() { + let actual = response.headers().get(super::QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .ok_or_else(|| Error::NotSupported { + message: "Batched Blob ranges require a snapshot identity; upgrade every serving node".into(), + })?; + *identity = Some(actual.to_owned()); + } + snapshot.version = Some(version); + // This endpoint's contract is stream framing. Keep the bounded, fallible + // IPC path from #4979 instead of buffering an Arrow file response. + let content_type = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if !content_type + .split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case(crate::remote::ARROW_STREAM_CONTENT_TYPE) + { + return Err(invalid(format!( + "expected Arrow IPC stream, got '{content_type}'" + ))); + } + let mut stream = super::ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.clone(), + Some(version), + ) + .await?; + let schema = stream.schema(); + if !matches!( + schema + .field_with_name("value") + .map(|field| field.data_type()), + Ok(DataType::LargeBinary) + ) { + return Err(invalid( + "response requires a LargeBinary column named 'value'".into(), + )); + } + let mut blobs = BlobAccumulator::new(ranges.len())?; + let mut rows = 0usize; + let mut bytes = 0u64; + while let Some(batch) = stream.try_next().await? { + let array = batch + .column_by_name("value") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| { + invalid("response requires a LargeBinary column named 'value'".into()) + })?; + let end = rows + .checked_add(array.len()) + .filter(|end| *end <= ranges.len()) + .ok_or_else(|| invalid("response has more rows than requested".into()))?; + let offsets = array.value_offsets(); + bytes = bytes + .checked_add((offsets[array.len()] - offsets[0]) as u64) + .filter(|bytes| *bytes <= MAX_FETCH_BLOB_RANGE_BYTES) + .ok_or_else(|| invalid("response exceeds 64 MiB of range bytes".into()))?; + for (i, range) in ranges[rows..end].iter().enumerate() { + if array.is_valid(i) && array.value_length(i) as u64 != range.length { + return Err(invalid(format!( + "row {} returned {} bytes for requested length {}", + rows + i, + array.value_length(i), + range.length + ))); + } + } + blobs.append(array)?; + rows = end; + } + if rows != ranges.len() { + return Err(invalid(format!( + "returned {rows} rows for {} ranges", + ranges.len() + ))); + } + Ok(blobs.finish()?) + } + /// Open seekable handles for `row_ids`. /// /// Descriptors for the requested rows come from one `_rowid` take query per @@ -1666,10 +1897,155 @@ mod tests { let error = table.fetch_blob_ranges("image", &ranges).await.unwrap_err(); assert!(error.to_string().contains(message), "{error}"); // Missing rows and invalid ranges fail without reading any bytes. - assert_eq!(requests.lock().unwrap().len(), 1); + assert!(matches!(error, Error::InvalidInput { .. })); + assert_eq!( + requests.lock().unwrap().len(), + usize::from(!message.contains("overflows")) + ); } } + #[tokio::test] + async fn remote_blob_ranges_keep_producing_query_identity_from_first_request() { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let calls = Arc::new(StdMutex::new(Vec::new())); + let captured = calls.clone(); + let table = RemoteTable::new_mock( + "my_table".into(), + move |request| { + assert_eq!( + request.url().path(), + "/v1/table/my_table/fetch_blob_ranges/" + ); + assert_eq!( + request.headers()[super::super::QUERY_SNAPSHOT_HEADER], + IDENTITY + ); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["version"], 42); + let rows = body["ranges"].as_array().unwrap().len(); + captured.lock().unwrap().push(rows); + let batch = RecordBatch::try_from_iter([( + "value", + Arc::new(LargeBinaryArray::from(vec![Some(b"A".as_slice()); rows])) + as Arc, + )]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "42") + .header(super::super::QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(bytes) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let snapshot = table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap(); + let ranges = snapshot + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(b"A".as_slice()); 1025]) + ); + assert_eq!(*calls.lock().unwrap(), [1024, 1]); + assert!(table.snapshot_read_state().await.version.is_none()); + } + + #[tokio::test] + async fn remote_blob_ranges_cancel_releases_the_only_request_permit() { + use std::sync::atomic::AtomicUsize; + let entered = Arc::new(tokio::sync::Notify::new()); + let started = entered.clone(); + let calls = Arc::new(AtomicUsize::new(0)); + let captured = calls.clone(); + let table = Arc::new(RemoteTable::new_mock_with_version_and_config( + "my_table".into(), + move |request| { + assert!(request.url().path().ends_with("/fetch_blob_ranges/")); + if captured.fetch_add(1, Ordering::SeqCst) == 0 { + started.notify_one(); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header( + super::super::QUERY_SNAPSHOT_HEADER, + format!("v1:{}", "a".repeat(64)), + ) + .body(reqwest::Body::wrap_stream(futures::stream::pending::< + std::result::Result, + >())) + .unwrap() + } else { + http::Response::builder() + .status(400) + .header("x-lancedb-error-code", "invalid_input") + .body(reqwest::Body::from( + r#"{"error":"range exceeds blob size"}"#, + )) + .unwrap() + } + }, + Some(Version::new(1, 13, 0)), + crate::remote::ClientConfig { + blob_request_concurrency: Some(1), + ..Default::default() + }, + )); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let reader_table = table.clone(); + let reader = tokio::spawn(async move { + reader_table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + }); + tokio::time::timeout(Duration::from_secs(5), entered.notified()) + .await + .unwrap(); + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + let error = tokio::time::timeout( + Duration::from_secs(5), + table.fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1)]), + ) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds blob size")); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn remote_blob_ranges_reject_overflow_before_http() { + let (table, requests) = mock_take_blob_table(vec![], Some("7")); + let error = table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err(); + assert!(error.to_string().contains("overflows u64"), "{error}"); + assert!(requests.lock().unwrap().is_empty()); + } + #[tokio::test] async fn remote_blob_ranges_accept_empty_requests_without_http() { let (table, requests) = mock_take_blob_table(vec![], Some("7")); diff --git a/rust/lancedb/src/remote/table/blobs/aggregate.rs b/rust/lancedb/src/remote/table/blobs/aggregate.rs index e8e794fa0..68bc20c88 100644 --- a/rust/lancedb/src/remote/table/blobs/aggregate.rs +++ b/rust/lancedb/src/remote/table/blobs/aggregate.rs @@ -6,75 +6,143 @@ use std::collections::VecDeque; use arrow_array::{Array, LargeBinaryArray}; -use arrow_buffer::{Buffer, MutableBuffer, NullBufferBuilder, OffsetBuffer}; +use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer}; use arrow_schema::ArrowError; +fn allocation_error(error: impl std::fmt::Display) -> ArrowError { + ArrowError::ComputeError(format!("cannot allocate blob result: {error}")) +} + pub(super) struct BlobAccumulator { offsets: Vec, - nulls: NullBufferBuilder, + validity: Vec, values: VecDeque, bytes: i64, + has_nulls: bool, } impl BlobAccumulator { - pub(super) fn new(rows: usize) -> Self { - let mut offsets = Vec::with_capacity(rows + 1); + pub(super) fn new(rows: usize) -> Result { + let capacity = rows + .checked_add(1) + .ok_or_else(|| allocation_error("row count overflow"))?; + let mut offsets = Vec::new(); + offsets + .try_reserve_exact(capacity) + .map_err(allocation_error)?; offsets.push(0); - Self { + let mut validity = Vec::new(); + let validity_bytes = rows / 8 + usize::from(!rows.is_multiple_of(8)); + validity + .try_reserve_exact(validity_bytes) + .map_err(allocation_error)?; + Ok(Self { offsets, - nulls: NullBufferBuilder::new(rows), + validity, values: VecDeque::new(), bytes: 0, - } + has_nulls: false, + }) } pub(super) fn append(&mut self, array: &LargeBinaryArray) -> Result<(), ArrowError> { + self.append_inner(array, false) + } + + /// The first value continues the preceding response's final logical range. + pub(super) fn append_continuation( + &mut self, + array: &LargeBinaryArray, + ) -> Result<(), ArrowError> { + self.append_inner(array, true) + } + + fn append_inner( + &mut self, + array: &LargeBinaryArray, + continuation: bool, + ) -> Result<(), ArrowError> { + let rows = self.offsets.len() - 1; + if continuation + && (rows == 0 + || array.is_empty() + || (self.validity[(rows - 1) / 8] & (1 << ((rows - 1) % 8)) != 0) + != array.is_valid(0)) + { + return Err(ArrowError::ComputeError( + "inconsistent nulls in split blob range".into(), + )); + } let offsets = array.value_offsets(); let start = offsets[0]; let length = offsets[array.len()] - start; let total = self.bytes.checked_add(length).ok_or_else(|| { - ArrowError::ComputeError("fetch_blobs result exceeds i64 byte offsets".into()) + ArrowError::ComputeError("blob result exceeds i64 byte offsets".into()) })?; - self.offsets.extend( - offsets[1..] - .iter() - .map(|offset| self.bytes + (*offset - start)), - ); - if let Some(nulls) = array.nulls() { - self.nulls.append_buffer(nulls); - } else { - self.nulls.append_n_non_nulls(array.len()); - } + let skip = usize::from(continuation); + self.offsets + .try_reserve(array.len() - skip) + .map_err(allocation_error)?; + let new_rows = rows + .checked_add(array.len() - skip) + .ok_or_else(|| allocation_error("row count overflow"))?; + let validity_bytes = new_rows / 8 + usize::from(new_rows % 8 != 0); + self.validity + .try_reserve(validity_bytes - self.validity.len()) + .map_err(allocation_error)?; + self.validity.resize(validity_bytes, 0); if length != 0 { + self.values.try_reserve(1).map_err(allocation_error)?; self.values.push_back( array .values() .slice_with_length(start as usize, length as usize), ); } + if continuation { + *self.offsets.last_mut().unwrap() = self.bytes + (offsets[1] - start); + } + self.offsets.extend( + offsets[1 + skip..] + .iter() + .map(|offset| self.bytes + (*offset - start)), + ); + for i in skip..array.len() { + let row = rows + i - skip; + if array.is_valid(i) { + self.validity[row / 8] |= 1 << (row % 8); + } else { + self.has_nulls = true; + } + } self.bytes = total; Ok(()) } - pub(super) fn finish(mut self) -> LargeBinaryArray { + pub(super) fn finish(mut self) -> Result { let values = match self.values.len() { 0 => Buffer::default(), 1 => self.values.pop_front().unwrap(), _ => { - let mut values = MutableBuffer::new(self.bytes as usize); - // Do not retain all decoded batches alongside the final allocation. + let length = usize::try_from(self.bytes).map_err(allocation_error)?; + let mut values = Vec::new(); + values.try_reserve_exact(length).map_err(allocation_error)?; // Drop each source allocation immediately after copying its bytes. while let Some(chunk) = self.values.pop_front() { values.extend_from_slice(&chunk); } - values.into() + Buffer::from_vec(values) } }; - LargeBinaryArray::new( + let rows = self.offsets.len() - 1; + let nulls = self + .has_nulls + .then(|| NullBuffer::new(BooleanBuffer::new(Buffer::from_vec(self.validity), 0, rows))); + Ok(LargeBinaryArray::new( OffsetBuffer::new(self.offsets.into()), values, - self.nulls.finish(), - ) + nulls, + )) } } @@ -85,9 +153,9 @@ mod tests { #[test] fn single_buffer_is_not_copied() { let array = LargeBinaryArray::from(vec![Some(b"alpha".as_slice()), None, Some(b"")]); - let mut result = BlobAccumulator::new(3); + let mut result = BlobAccumulator::new(3).unwrap(); result.append(&array).unwrap(); - let output = result.finish(); + let output = result.finish().unwrap(); assert_eq!(output.values().as_ptr(), array.values().as_ptr()); assert_eq!(output, array); } @@ -101,21 +169,27 @@ mod tests { Some(b""), Some(b"beta"), ]); - let mut result = BlobAccumulator::new(6); + let mut result = BlobAccumulator::new(6).unwrap(); result.append(&array.slice(1, 3)).unwrap(); result.append(&array.slice(4, 1)).unwrap(); result.append(&array.slice(2, 2)).unwrap(); assert_eq!( - result.finish(), + result.finish().unwrap(), LargeBinaryArray::from(vec![ Some(b"alpha".as_slice()), None, Some(b""), Some(b"beta"), None, - Some(b""), + Some(b"") ]) ); - assert_eq!(BlobAccumulator::new(0).finish().len(), 0); + assert_eq!(BlobAccumulator::new(0).unwrap().finish().unwrap().len(), 0); + } + + #[test] + fn impossible_capacity_is_an_error() { + assert!(BlobAccumulator::new(usize::MAX).is_err()); + assert!(BlobAccumulator::new(usize::MAX / 2).is_err()); } } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index db68ab290..4959b2842 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1452,8 +1452,13 @@ impl Table { /// ranges for the same blob. The output has the same length and order as /// the requests. Null blobs produce null output slots; empty ranges on /// non-null blobs produce empty byte strings. - /// LanceDB Enterprise tables read through version-pinned [`BlobFile`] handles using - /// HTTP byte-range requests. + /// LanceDB Enterprise uses the batched endpoint when the server advertises + /// support, splitting calls at 1024 ranges and 64 MiB of requested bytes. + /// Individual larger ranges are partitioned and reassembled into one result. + /// Older servers use descriptor queries and [`Self::fetch_blob_files`] range + /// reads. Both protocols read one exact branch and version without changing + /// this handle's checkout. The final materialized output still occupies memory. + /// Errors from an advertised endpoint propagate without switching protocols. /// /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no @@ -1486,10 +1491,14 @@ impl Table { column: impl AsRef, requests: impl IntoIterator, ) -> Result { - let requests = requests.into_iter().collect::>(); - self.inner - .fetch_blob_ranges(column.as_ref(), &requests) - .await + let mut ranges = Vec::new(); + for request in requests { + ranges.try_reserve(1).map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + ranges.push(request); + } + self.inner.fetch_blob_ranges(column.as_ref(), &ranges).await } /// Open lazy [`BlobFile`] handles for the given row ids. diff --git a/rust/lancedb/tests/remote_blob_ranges.rs b/rust/lancedb/tests/remote_blob_ranges.rs new file mode 100644 index 000000000..51c49fe09 --- /dev/null +++ b/rust/lancedb/tests/remote_blob_ranges.rs @@ -0,0 +1,634 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +#![cfg(feature = "remote")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{Array, ArrayRef, LargeBinaryArray, RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use lancedb::Table; +use lancedb::blob::BlobRangeRequest; +use lancedb::remote::{ClientConfig, RetryConfig, TimeoutConfig}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; + +const MIB: u64 = 1024 * 1024; +const IDENTITY: &str = "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const ROUTE: &str = "/v1/table/test/fetch_blob_ranges/"; + +struct Reply { + status: u16, + version: Option, + body: Vec, + declared_extra: usize, + identity: Option<&'static str>, +} + +fn ipc(column: &str, values: ArrayRef) -> Vec { + let batch = RecordBatch::try_from_iter([(column, values)]).unwrap(); + let mut body = Vec::new(); + let mut writer = StreamWriter::try_new(&mut body, &batch.schema()).unwrap(); + // Multiple batches exercise response assembly as well as HTTP partitions. + let mid = batch.num_rows() / 2; + writer.write(&batch.slice(0, mid)).unwrap(); + writer + .write(&batch.slice(mid, batch.num_rows() - mid)) + .unwrap(); + writer.finish().unwrap(); + drop(writer); + body +} + +fn legacy_reply(path: &str, body: &Value, takes: usize) -> Reply { + use arrow_array::{StructArray, UInt8Array, UInt32Array, UInt64Array}; + let version = body["version"] + .as_u64() + .unwrap_or(if takes == 1 { 7 } else { 8 }); + if path.ends_with("/query/") { + assert_eq!(body["branch"], "experiment"); + assert_eq!(body["columns"], json!(["image"])); + let filter = body["filter"].as_str().unwrap(); + let ids = filter + .split_once('(') + .unwrap() + .1 + .trim_end_matches(')') + .split(',') + .map(|id| id.trim().parse::().unwrap()) + .filter(|id| [10, 20, 30, 40].contains(id)) + .rev() + .collect::>(); + let fields = lance_core::datatypes::BLOB_V2_DESC_FIELDS.clone(); + let descriptors = StructArray::new( + fields, + vec![ + Arc::new(UInt8Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from( + ids.iter() + .map(|id| if *id == 40 { 0 } else { 5 }) + .collect::>(), + )), + Arc::new(UInt32Array::from(vec![0; ids.len()])), + Arc::new(StringArray::from(vec![""; ids.len()])), + ], + Some(ids.iter().map(|id| *id != 20).collect()), + ); + let batch = RecordBatch::try_from_iter([ + ("image", Arc::new(descriptors) as ArrayRef), + ("_rowid", Arc::new(UInt64Array::from(ids)) as ArrayRef), + ]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + Reply { + status: 200, + version: Some(version), + body: bytes, + declared_extra: 0, + identity: Some(IDENTITY), + } + } else { + assert!(path.contains("branch=experiment"), "{path}"); + let version = path + .split("version=") + .nth(1) + .unwrap() + .split('&') + .next() + .unwrap() + .parse::() + .unwrap(); + let range = body["range"] + .as_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap(); + let (start, end) = range.split_once('-').unwrap(); + let start = start.parse::().unwrap(); + let end = end.parse::().unwrap(); + let payload = if version == 8 { b"ALPHA" } else { b"alpha" }; + Reply { + status: 206, + version: Some(version), + body: payload[start..=end].to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + } + } +} + +fn reply(values: Vec>>, version: u64) -> Reply { + Reply { + status: 200, + version: Some(version), + body: ipc( + "value", + Arc::new(LargeBinaryArray::from_iter( + values.iter().map(|v| v.as_deref()), + )), + ), + declared_extra: 0, + identity: Some(IDENTITY), + } +} + +fn byte(row: u64, offset: u64, version: u64) -> u8 { + ((row * 17 + offset % 251 + version) % 251) as u8 +} + +fn serve_ranges(body: &Value, version: u64) -> Reply { + assert_eq!(body["column"], "image"); + let ranges = body["ranges"].as_array().unwrap(); + assert!(ranges.len() <= 1024); + assert!( + ranges + .iter() + .map(|r| r["length"].as_u64().unwrap()) + .sum::() + <= 64 * MIB + ); + let values = ranges + .iter() + .map(|r| { + let row = r["row_id"].as_u64().unwrap(); + let offset = r["offset"].as_u64().unwrap(); + let length = r["length"].as_u64().unwrap(); + (row != 20).then(|| { + (offset..offset + length) + .map(|i| byte(row, i, version)) + .collect() + }) + }) + .collect(); + reply(values, version) +} + +struct Server { + url: String, + calls: Arc>>, + task: tokio::task::JoinHandle<()>, + identities: Arc>>>, +} + +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl Server { + async fn new(handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static) -> Self { + Self::with_capability(handler, Some("1")).await + } + + async fn with_capability( + handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static, + capability: Option<&'static str>, + ) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let calls = Arc::new(Mutex::new(Vec::new())); + let captured = calls.clone(); + let identities = Arc::new(Mutex::new(Vec::new())); + let captured_identities = identities.clone(); + let task = tokio::spawn(async move { + let mut fetches = 0; + let mut takes = 0; + loop { + let (socket, _) = listener.accept().await.unwrap(); + let captured = captured.clone(); + let result = tokio::time::timeout(Duration::from_secs(20), async { + let mut socket = BufReader::new(socket); + let mut line = String::new(); + socket.read_line(&mut line).await?; + let path = line.split_whitespace().nth(1).unwrap().to_string(); + let method = line.split_whitespace().next().unwrap().to_string(); + let mut range = String::new(); + let mut length = 0; + let mut identity = None; + loop { + line.clear(); + socket.read_line(&mut line).await?; + assert!(line.len() <= 16384); + if line == "\r\n" { break; } + if let Some((name, value)) = line.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse::().unwrap(); + } + if name.eq_ignore_ascii_case("x-lancedb-query-snapshot") { identity = Some(value.trim().to_owned()); } + if name.eq_ignore_ascii_case("range") { range = value.trim().to_string(); } + } + } + assert!(length <= 256 * 1024); + let mut bytes = vec![0; length]; + socket.read_exact(&mut bytes).await?; + let body = if method == "GET" { json!({"range": range}) } else if bytes.is_empty() { json!({}) } else { serde_json::from_slice(&bytes).unwrap() }; + captured.lock().unwrap().push((path.clone(), body.clone())); + let response = if path == "/v1/table/test/describe/" { + Reply { status: 200, version: None, body: serde_json::to_vec(&json!({"version": 8, "schema": {"fields": []}})).unwrap(), declared_extra: 0, identity: None } + } else if path == "/v1/table/test/branches/list/" { + Reply { status: 200, version: None, body: br#"{"branches":{"experiment":{"parentBranch":null,"parentVersion":1,"createAt":1,"manifestSize":1}}}"#.to_vec(), declared_extra: 0, identity: None } + } else if capability != Some("1") { + assert_ne!(path, ROUTE, "unknown capability must select old routes first"); + takes += usize::from(path.ends_with("/query/")); + legacy_reply(&path, &body, takes) + } else { + assert_eq!(path, ROUTE, "unexpected legacy or fallback request"); + fetches += 1; + captured_identities.lock().unwrap().push(identity); + handler(&body, fetches) + }; + if response.status == 0 { return Ok::<_, std::io::Error>(()); } + let version = response.version.map(|v| format!("x-lancedb-version: {v}\r\n")).unwrap_or_default(); + let capability = if path.ends_with("/describe/") { capability.map(|value| format!("x-lancedb-blob-ranges: {value}\r\n")).unwrap_or_default() } else { String::new() }; + let content_type = if path == ROUTE || path.ends_with("/query/") { "application/vnd.apache.arrow.stream" } else { "application/json" }; + let content_range = if method == "GET" { format!("Content-Range: {}/5\r\n", body["range"].as_str().unwrap().replace("bytes=", "bytes ")) } else { String::new() }; + let identity = if path == ROUTE { response.identity.map(|id| format!("x-lancedb-query-snapshot: {id}\r\n")).unwrap_or_default() } else { String::new() }; + let header = format!("HTTP/1.1 {} Response\r\nContent-Type: {content_type}\r\nphalanx-version: 1.13.0-beta.0\r\n{capability}{version}{identity}{content_range}Content-Length: {}\r\nConnection: close\r\n\r\n", response.status, response.body.len() + response.declared_extra); + socket.write_all(header.as_bytes()).await?; + for chunk in response.body.chunks(8192) { socket.write_all(chunk).await?; } + socket.shutdown().await?; + Ok(()) + }).await; + // A client rejecting a malformed schema may close the body early. + assert!(result.is_ok(), "loopback request timed out"); + } + }); + Self { + url, + calls, + task, + identities, + } + } + + async fn table(&self, version: Option) -> Table { + let db = lancedb::connect("db://dev") + .api_key("fake") + .region("us-east-1") + .host_override(&self.url) + .client_config(ClientConfig { + retry_config: RetryConfig { + retries: Some(2), + connect_retries: Some(2), + read_retries: Some(2), + ..Default::default() + }, + timeout_config: TimeoutConfig { + timeout: Some(Duration::from_secs(30)), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let mut open = db.open_table("test").branch("experiment"); + if let Some(version) = version { + open = open.version(version); + } + open.execute().await.unwrap() + } +} + +#[tokio::test] +async fn public_ranges_work_on_old_routes_only_servers() { + for capability in [None, Some("0"), Some("2")] { + for checkout in [None, Some(3)] { + let server = Server::with_capability( + |_, _| panic!("new endpoint must not be requested"), + capability, + ) + .await; + let table = server.table(checkout).await; + let cloned = table.clone(); + let ranges = [ + BlobRangeRequest::new(10, 1, 3), + BlobRangeRequest::new(20, 0, 1), + BlobRangeRequest::new(40, 0, 0), + BlobRangeRequest::new(10, 5, 0), + BlobRangeRequest::new(10, 1, 3), + ]; + let result = cloned.fetch_blob_ranges("image", ranges).await.unwrap(); + assert_eq!( + result, + LargeBinaryArray::from(vec![ + Some(b"lph".as_slice()), + None, + Some(b"".as_slice()), + Some(b"".as_slice()), + Some(b"lph".as_slice()) + ]) + ); + let result = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!( + result.value(0), + if checkout.is_none() { b"A" } else { b"a" } + ); + for ranges in [ + vec![BlobRangeRequest::new(10, 4, 2)], + vec![BlobRangeRequest::new(99, 0, 1)], + ] { + assert!(matches!( + table.fetch_blob_ranges("image", ranges).await.unwrap_err(), + lancedb::Error::InvalidInput { .. } + )); + } + assert!( + !server + .calls + .lock() + .unwrap() + .iter() + .any(|(path, _)| path == ROUTE) + ); + } + } +} + +#[tokio::test] +async fn public_ranges_keep_order_nulls_and_snapshot_without_pinning_live_handle() { + for checkout in [None, Some(3)] { + let server = Server::new(move |body, call| { + assert_eq!(body["branch"], "experiment"); + let expected = checkout.or((call > 1 && call < 3).then_some(7)); + assert_eq!(body["version"].as_u64(), expected); + serve_ranges( + body, + body["version"] + .as_u64() + .unwrap_or(if call == 1 { 7 } else { 8 }), + ) + }) + .await; + let table = server.table(checkout).await; + let mut requests = (0..1025) + .map(|i| BlobRangeRequest::new(if i % 9 == 0 { 20 } else { 10 + i % 7 }, i, i % 4)) + .collect::>(); + requests.extend([ + BlobRangeRequest::new(10, 0, 0), + BlobRangeRequest::new(10, 2, 3), + BlobRangeRequest::new(10, 2, 3), + ]); + let result = table + .fetch_blob_ranges("image", requests.clone()) + .await + .unwrap(); + assert_eq!(result.len(), requests.len()); + for (i, request) in requests.iter().enumerate() { + assert_eq!(result.is_null(i), request.row_id == 20); + if request.row_id != 20 { + let expected = (request.offset..request.offset + request.length) + .map(|j| byte(request.row_id, j, checkout.unwrap_or(7))) + .collect::>(); + assert_eq!(result.value(i), expected); + } + } + let next = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!(next.value(0), [byte(10, 0, checkout.unwrap_or(8))]); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); + } +} + +#[tokio::test] +async fn public_ranges_partition_bytes_and_reassemble_large_single_range() { + let server = Server::new(|body, call| { + assert_eq!(body["version"].as_u64(), (call > 1).then_some(7)); + serve_ranges(body, 7) + }) + .await; + let table = server.table(None).await; + let requests = [ + BlobRangeRequest::new(10, 3, 33 * MIB), + BlobRangeRequest::new(30, 7, 33 * MIB), + BlobRangeRequest::new(40, 11, 70 * MIB), + BlobRangeRequest::new(20, 0, u64::MAX), + ]; + let result = table.fetch_blob_ranges("image", requests).await.unwrap(); + assert_eq!(result.len(), 4); + for (i, request) in requests[..3].iter().enumerate() { + assert_eq!(result.value_length(i) as u64, request.length); + assert!( + result + .value(i) + .iter() + .enumerate() + .all(|(j, value)| *value == byte(request.row_id, request.offset + j as u64, 7)) + ); + } + assert!(result.is_null(3)); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); +} + +#[tokio::test] +async fn public_ranges_reject_malformed_responses_and_http_failures_without_fallback() { + for case in 0..16 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + // Fail after one successful partition to prove no partial success. + if call == 1 { + return response; + } + match case { + 0 => response.body = ipc("value", Arc::new(StringArray::from(vec!["bad"]))), + 1 => { + response.body = ipc( + "wrong", + Arc::new(LargeBinaryArray::from(vec![Some(b"a".as_slice())])), + ) + } + 2 => response = reply(vec![], 7), + 3 => response = reply(vec![Some(vec![1]), Some(vec![2])], 7), + 4 => response.body.truncate(response.body.len() - 8), + 5 => response.body.truncate(response.body.len() / 2), + 6 => response.declared_extra = 10, + 7 => response = reply(vec![Some(vec![])], 7), + 8 => response.version = None, + 9 => response.version = Some(8), + 10..=14 => { + response.status = [401, 403, 404, 429, 500][case - 10]; + response.body = b"ordinary failure".to_vec(); + } + 15 => response.status = 0, + _ => unreachable!(), + } + response + }) + .await; + let table = server.table(None).await; + let requests = vec![BlobRangeRequest::new(10, 0, 1); 1025]; + assert!( + table.fetch_blob_ranges("image", requests).await.is_err(), + "case {case}" + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2, + "case {case}" + ); + } +} + +#[tokio::test] +async fn public_ranges_validate_locally_and_propagate_server_range_errors() { + let server = Server::new(|_, _| Reply { + status: 400, + version: None, + body: b"range exceeds blob size or missing row".to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + assert_eq!(table.fetch_blob_ranges("image", []).await.unwrap().len(), 0); + assert!( + table + .fetch_blob_ranges("image", [BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err() + .to_string() + .contains("overflows u64") + ); + assert_eq!(server.calls.lock().unwrap().len(), before); + let error = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 9, 2)]) + .await + .unwrap_err(); + assert!(matches!(error, lancedb::Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds")); +} + +#[tokio::test] +async fn public_ranges_require_original_identity_on_every_partition() { + for huge in [false, true] { + for case in 0..5 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + if call == 2 { + response.identity = match case { + 0 => None, // Old serving node ignores the precondition. + 1 => Some("invalid"), + _ => Some( + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ), + }; + if case == 3 || case == 4 { + response.status = if case == 3 { 400 } else { 404 }; + response.body = + b"query snapshot identity mismatch: gone or replaced".to_vec(); + } else { + // Identity verification must win over malformed payload. + response.body = b"not Arrow".to_vec(); + } + } + response + }) + .await; + let table = server.table(None).await; + let requests = if huge { + vec![BlobRangeRequest::new(10, 0, 64 * MIB + 1)] + } else { + vec![BlobRangeRequest::new(10, 0, 1); 1025] + }; + let error = table + .fetch_blob_ranges("image", requests) + .await + .unwrap_err(); + if case < 3 { + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + } else if case == 3 { + assert!( + matches!(error, lancedb::Error::InvalidInput { .. }), + "{error}" + ); + } else { + assert!( + matches!(error, lancedb::Error::TableNotFound { .. }), + "{error}" + ); + } + assert_eq!( + *server.identities.lock().unwrap(), + [None, Some(IDENTITY.into())] + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2 + ); + } + } +} + +#[tokio::test] +async fn public_ranges_cannot_establish_identity_from_numeric_version_or_describe() { + for identity in [None, Some("invalid"), Some("v2:unsupported")] { + let server = Server::new(move |_, call| { + assert_eq!(call, 1, "no failure fallback, replay or second partition"); + let mut response = reply(vec![Some(b"A".to_vec()); 1024], 7); + response.identity = identity; + response.body = b"not Arrow".to_vec(); + response + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + let error = table + .fetch_blob_ranges("image", vec![BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap_err(); + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + assert_eq!(server.calls.lock().unwrap().len(), before + 1); + } +} From cababaecf08a12bdd97a157cac16751c13350274 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 06:22:35 +0800 Subject: [PATCH 17/36] feat(remote): discover server builds and retain error provenance (#4999) Remote callers can use `db.server_info()` in Rust and Python, including synchronous and asynchronous Python connections, to identify the responding server without submitting a query or Job. Typed results describe the query-node build, component versions, Function protocol and configured images. Older servers without the endpoint return an explicit unsupported error. REST and Flight errors retain the reported build in diagnostic text and Rust `RemoteErrorMetadata.server`. Typed table/job-not-found errors preserve their HTTP source and classification, including the schema-cache path; masked REST errors can obtain provenance from the response header. Unknown build information stays absent. The matching native Python SDK was exercised against a real localhost server (`8829b074` client / `43920fa` server): sync/async discovery, both SQL version forms and actual REST/Flight error provenance passed. The product files match this branch; private validation drivers are excluded. Focused coverage includes typed 404 errors, masked errors, and the public schema-cache regression. Deployment and published-package acceptance remain separate. Server counterpart: https://github.com/lancedb/sophon/pull/10234. Related: ENT-3565. --- docs/src/python/python.md | 12 +++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/db.py | 23 +++++ python/python/lancedb/remote/db.py | 9 ++ python/python/lancedb/server_info.py | 33 +++++++ python/python/tests/test_remote_db.py | 87 +++++++++++++++++ python/src/connection.rs | 8 ++ rust/lancedb/src/connection.rs | 18 ++++ rust/lancedb/src/database.rs | 7 ++ rust/lancedb/src/error.rs | 77 ++++++++++++--- rust/lancedb/src/lib.rs | 1 + rust/lancedb/src/remote/db.rs | 133 +++++++++++++++++++++++++- rust/lancedb/src/remote/sql.rs | 13 ++- rust/lancedb/src/remote/sql_test.rs | 47 +++++++++ rust/lancedb/src/remote/table.rs | 60 +++++++++--- rust/lancedb/src/server_info.rs | 56 +++++++++++ 16 files changed, 553 insertions(+), 32 deletions(-) create mode 100644 python/python/lancedb/server_info.py create mode 100644 rust/lancedb/src/server_info.rs diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 0e7164c1a..058f2529a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -37,6 +37,18 @@ embedding_functions`. Prefer keyword arguments for optional parameters. ::: lancedb.db.DBConnection +Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection) +to include the responding server's release, Git revision, build date and Function +runtime information in a bug report. It returns a JSON-compatible dictionary and +does not submit a query or job. Configured images are distinct from the version +of an already running job. During a rolling upgrade, successive requests can +reach different query-node builds. Embedded connections and older servers without +the endpoint raise `NotImplementedError`. + +::: lancedb.server_info.ServerBuildInfo + +::: lancedb.server_info.ServerInfo + Resource listings return iterators. Use `list(db.list_tables())` to collect all table names. `db.list_tables().tables` is a list of the first page; `limit` controls its page size and `page_token` resumes at a saved token. The same diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 956806cde..ffdd68e5f 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -185,6 +185,7 @@ class Connection(object): limit: Optional[int], ) -> list[str]: ... # Deprecated: Use list_tables instead async def open_job(self, job_id: str) -> Job: ... + async def server_info(self) -> str: ... async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( self, request_json: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 59fa5b4c6..b4e5c6182 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -58,6 +58,7 @@ from lance_namespace import ( from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from . import __version__ +from .server_info import ServerInfo from ._lancedb import _append_doc_url, connect as lancedb_connect # type: ignore from .functions import FunctionVersion, FunctionDefinition from .graph import ( @@ -1476,6 +1477,22 @@ class DBConnection(EnforceOverrides): ) ) + def server_info(self) -> ServerInfo: + """Return the responding server's build and Function runtime information. + + This call submits no query, Function, or job. The response is a + JSON-compatible dictionary, convenient to include in a bug report:: + + info = db.server_info() + print(info["query_node"]) # release, git_sha, build_date + + Requires System Usage permission. Embedded connections and older + servers without this endpoint raise ``NotImplementedError``. + Different calls can reach different builds during a rolling upgrade. + Configured images do not identify the version of a running job. + """ + raise NotImplementedError("Server build discovery requires a remote connection") + def list_gpu_classes(self) -> List[GpuClass]: """List the operator-configured Function GPU classes. @@ -3653,6 +3670,12 @@ class AsyncConnection(object): """ return _opened_job(await self._inner.open_job(job_id)) + async def server_info(self) -> ServerInfo: + """Read the responding server's build information. See + [DBConnection.server_info][lancedb.db.DBConnection.server_info]. + """ + return json.loads(await self._inner.server_info()) + async def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See [DBConnection.list_gpu_classes][lancedb.db.DBConnection.list_gpu_classes]. diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index a06af5d62..911766674 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -4,6 +4,8 @@ from __future__ import annotations +from lancedb.server_info import ServerInfo + from dataclasses import replace from datetime import timedelta import json @@ -966,6 +968,13 @@ class RemoteDBConnection(DBConnection): """ return Job(LOOP.run(self._conn.open_job(job_id))) + @override + def server_info(self) -> ServerInfo: + """Read the responding server's build information. See + [DBConnection.server_info][lancedb.db.DBConnection.server_info]. + """ + return LOOP.run(self._conn.server_info()) + @override def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See diff --git a/python/python/lancedb/server_info.py b/python/python/lancedb/server_info.py new file mode 100644 index 000000000..d53c6c380 --- /dev/null +++ b/python/python/lancedb/server_info.py @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Remote server build information returned as JSON-compatible dictionaries.""" + +from typing import Optional, TypedDict + + +class ServerBuildInfo(TypedDict): + """Immutable identity compiled into a server executable.""" + + release: str + git_sha: str + build_date: Optional[str] + + +class ServerInfo(TypedDict): + """The responding query node and its configured Function runtime. + + ``query_node`` can be ``None`` when the executable has no build metadata. + ``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling + upgrade, separate requests can reach different query-node builds. + Configured images do not establish the version of a running job. + """ + + query_node: Optional[ServerBuildInfo] + lance_version: str + lancedb_version: str + function_worker_protocol_version: int + configured_query_node_image: Optional[str] + configured_job_worker_image: Optional[str] + configured_sql_job_image: Optional[str] + configured_gpu_worker_image: Optional[str] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 4f707f041..ca2516fda 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -6539,6 +6539,93 @@ def test_remote_job_handle_reports_its_own_detail(): } +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("known_build", [False, True]) +@pytest.mark.asyncio +async def test_remote_server_info(is_async, known_build): + requests = [] + expected = { + "query_node": { + "release": "1.2.3", + "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + } + if known_build + else None, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_query_node_image": "example.invalid/query:configured", + "configured_job_worker_image": "example.invalid/cpu:configured", + "configured_sql_job_image": "example.invalid/cli:configured", + "configured_gpu_worker_image": "example.invalid/worker:configured", + } + + def handler(request): + requests.append((request.command, request.path)) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(expected).encode()) + + if is_async: + async with mock_lancedb_connection_async(handler) as db: + actual = await db.server_info() + else: + with mock_lancedb_connection(handler) as db: + actual = db.server_info() + + assert actual == expected + assert json.loads(json.dumps(actual)) == expected + assert requests == [("GET", "/v1/server/info")] + + +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("status", [404, 403]) +@pytest.mark.asyncio +async def test_remote_server_info_errors(is_async, status): + requests = [] + + def handler(request): + requests.append((request.command, request.path)) + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "error": "discovery unavailable", + "server": { + "release": "1.2.3", + "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }, + } + ).encode() + ) + + expected_error = NotImplementedError if status == 404 else HttpError + with pytest.raises(expected_error) as caught: + if is_async: + async with mock_lancedb_connection_async(handler) as db: + await db.server_info() + else: + with mock_lancedb_connection(handler) as db: + db.server_info() + + if status == 404: + assert "/v1/server/info" in str(caught.value) + else: + # Permission responses do not carry the input-error classifier header. + # The native HTTP error and Python conversion must retain provenance. + assert "discovery unavailable" in str(caught.value) + assert "1.2.3" in str(caught.value) + assert "0123456789ab" in str(caught.value) + assert "2024-01-01T00:00:00Z" in str(caught.value) + assert caught.value.status_code == 403 + assert requests == [("GET", "/v1/server/info")] + + @pytest.mark.parametrize("is_async", [False, True]) @pytest.mark.asyncio async def test_remote_list_gpu_classes(is_async): diff --git a/python/src/connection.rs b/python/src/connection.rs index 1a99c1372..2bf01a6f7 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1285,6 +1285,14 @@ impl Connection { )) } + pub fn server_info(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let info = inner.server_info().await.infer_error()?; + serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string())) + }) + } + pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index fa35dc459..cc398e32b 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -1303,6 +1303,24 @@ impl Connection { self.database().list_gpu_classes().await } + /// Read the responding server's build and Function runtime information. + /// + /// This request does not submit a query, Function, or job. It requires + /// System Usage permission. Embedded databases and older servers without + /// `GET /v1/server/info` return [`Error::NotSupported`]. During a rolling + /// upgrade, separate requests can report different query-node builds. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let info = db.server_info().await?; + /// println!("{:?}", info.query_node); + /// # Ok(()) + /// # } + /// ``` + pub async fn server_info(&self) -> Result { + self.database().server_info().await + } + /// List server-side jobs across the database's tables. /// /// Results are fetched lazily, one page at a time. See [`Listing`] diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 7b4859faa..23ed9fc3d 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -479,6 +479,13 @@ pub trait Database: async fn list_gpu_classes(&self) -> Result> { gpu_class_catalog_not_supported() } + + /// Read the responding remote server's build identity. + async fn server_info(&self) -> Result { + Err(crate::Error::NotSupported { + message: "Server build discovery requires a remote LanceDB connection".into(), + }) + } /// Create a materialized view through a remote catalog and return its /// initial-population job. Local connections use the native declaration /// path directly. diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 89ad7a229..6aed94d71 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -64,6 +64,8 @@ impl RemoteResourceIdentity { #[derive(Debug, Clone, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RemoteErrorMetadata { + /// Build of the executable that produced the error, when reported. + pub server: Option, /// Machine-readable input error code, when available. pub error_code: Option, /// SQL job that failed, when the request ran in an isolated job. @@ -84,6 +86,8 @@ impl RemoteErrorMetadata { .map(str::to_owned) }; Self { + server: header("x-lancedb-server-build") + .and_then(|value| serde_json::from_str(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header("x-lancedb-sql-job-id"), job_request_id: header("x-job-request-id"), @@ -119,7 +123,7 @@ pub(crate) fn parse_flight_resource_identity(value: &str) -> Option, @@ -131,17 +135,28 @@ impl HttpErrorSource { pub(crate) fn new( message: String, response_body: Option<&str>, - metadata: RemoteErrorMetadata, + mut metadata: RemoteErrorMetadata, ) -> Self { let details = response_body.and_then(parse_http_error_details); + let body = + response_body.and_then(|body| serde_json::from_str::(body).ok()); + if metadata.server.is_none() { + metadata.server = body + .as_ref() + .and_then(|body| body.get("server").cloned()) + .and_then(|server| serde_json::from_value(server).ok()); + } let message = if metadata.error_code.is_some() { - response_body - .and_then(|body| serde_json::from_str::(body).ok()) + body.as_ref() .and_then(|body| body.get("error")?.as_str().map(str::to_owned)) .unwrap_or(message) } else { message }; + let message = match &metadata.server { + Some(server) => format!("{message} [server: {server}]"), + None => message, + }; Self { message, details, @@ -317,6 +332,18 @@ impl Display for JobFailure { } } +fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static)) -> String { + #[cfg(feature = "remote")] + if let Some(server) = _source + .downcast_ref::() + .and_then(Error::remote_error_metadata) + .and_then(|metadata| metadata.server.as_ref()) + { + return format!(" [server: {server}]"); + } + String::new() +} + #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { @@ -324,7 +351,7 @@ pub enum Error { InvalidTableName { name: String, reason: String }, #[snafu(display("Invalid input, {message}"))] InvalidInput { message: String }, - #[snafu(display("Table '{name}' was not found"))] + #[snafu(display("Table '{name}' was not found{}", server_build_suffix(source.as_ref())))] TableNotFound { name: String, source: BoxError }, #[snafu(display( "Table '{name}' exists but could not be loaded (it may be corrupt or incomplete): {source}" @@ -385,8 +412,8 @@ pub enum Error { }, #[snafu(display("Job{} was cancelled", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobCancelled { job_id: Option }, - #[snafu(display("Job '{job_id}' was not found"))] - JobNotFound { job_id: String }, + #[snafu(display("Job '{job_id}' was not found{}", server_build_suffix(source.as_ref())))] + JobNotFound { job_id: String, source: BoxError }, // 3rd party / external errors #[snafu(display("object_store error: {source}"))] @@ -576,7 +603,7 @@ impl Error { match self { Self::Http { status_code, .. } => *status_code, Self::Retry { status_code, .. } => *status_code, - Self::TableNotFound { source, .. } => { + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => { source.downcast_ref::().and_then(Self::status_code) } Self::JobFailed { failure, .. } => { @@ -623,7 +650,7 @@ impl Error { Self::Retry { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), - Self::TableNotFound { source, .. } => source + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), Self::JobFailed { failure, .. } => failure @@ -635,9 +662,35 @@ impl Error { } } - /// A copy of an error that other partitions of a DataFusion plan still hold. - /// Only an interrupted response can be copied, because it shares its source. - fn clone_shared(&self) -> Option { + /// Copy supported errors without flattening sources retained by a shared plan + /// or schema cache. + pub(crate) fn clone_shared(&self) -> Option { + #[cfg(feature = "remote")] + match self { + Self::Http { + source, + request_id, + status_code, + } => { + return source + .downcast_ref::() + .map(|source| Self::Http { + source: Box::new(source.clone()), + request_id: request_id.clone(), + status_code: *status_code, + }); + } + Self::TableNotFound { name, source } => { + return source + .downcast_ref::() + .and_then(Self::clone_shared) + .map(|source| Self::TableNotFound { + name: name.clone(), + source: Box::new(source), + }); + } + _ => {} + } #[cfg(feature = "remote")] if let Self::ResponseInterrupted { request_id, diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 0f02d90cf..9f800d593 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -216,6 +216,7 @@ pub mod query; pub mod remote; pub mod rerankers; pub mod secrets; +pub mod server_info; pub mod sql; pub mod storage_integration; pub mod table; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 578e3bbab..92523ec34 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1242,16 +1242,39 @@ impl Database for RemoteDatabase { let handle = super::job::RemoteJob::new(self.client.clone(), job_id.to_string()); match crate::job::JobHandle::describe(&handle).await { Ok(description) => Ok(Job::opened(Box::new(handle), description)), - Err(Error::Http { - status_code: Some(StatusCode::NOT_FOUND), - .. - }) => Err(Error::JobNotFound { + Err( + error @ Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }, + ) => Err(Error::JobNotFound { job_id: job_id.to_string(), + source: Box::new(error), }), Err(err) => Err(err), } } + async fn server_info(&self) -> Result { + let req = self.client.get("/v1/server/info"); + let (request_id, response) = self.client.send(req).await?; + let response = match self.client.check_response(&request_id, response).await { + Ok(response) => response, + Err(Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }) => { + return Err(Error::NotSupported { + message: "Server build discovery requires a newer LanceDB server; \ + GET /v1/server/info returned 404 Not Found" + .into(), + }); + } + Err(error) => return Err(error), + }; + response.json().await.err_to_http(request_id) + } + async fn list_gpu_classes(&self) -> Result> { #[derive(serde::Deserialize)] struct Response { @@ -4155,6 +4178,106 @@ mod tests { } } + #[tokio::test] + async fn test_server_info_preserves_remote_provenance() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/server/info"); + http::Response::builder().status(200).body(serde_json::json!({ + "query_node": { "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" }, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_gpu_worker_image": "example.invalid/worker:configured", + "future_component": "ignored" + }).to_string()).unwrap() + }); + let info = conn.server_info().await.unwrap(); + let build = info.query_node.unwrap(); + assert_eq!(build.release, "1.2.3"); + assert_eq!(build.git_sha, "0123456789ab"); + assert_eq!(build.build_date.as_deref(), Some("2024-01-01T00:00:00Z")); + assert_eq!(info.function_worker_protocol_version, 25); + assert_eq!( + info.configured_gpu_worker_image.as_deref(), + Some("example.invalid/worker:configured") + ); + } + + #[tokio::test] + async fn test_server_info_error_provenance_survives_classification() { + for target in ["table", "job", "masked"] { + let conn = Connection::new_with_handler(move |_| { + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + if target == "masked" { + http::Response::builder() + .status(500) + .header("x-lancedb-server-build", server.to_string()) + .body("Internal server error".to_string()) + .unwrap() + } else { + http::Response::builder() + .status(404) + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let error = match target { + "table" => conn.open_table("missing").execute().await.unwrap_err(), + "job" => conn.open_job("missing").await.unwrap_err(), + _ => conn.server_info().await.unwrap_err(), + }; + match target { + "table" => assert!(matches!(&error, Error::TableNotFound { .. })), + "job" => assert!(matches!(&error, Error::JobNotFound { .. })), + _ => assert_eq!( + error.status_code(), + Some(http::StatusCode::INTERNAL_SERVER_ERROR) + ), + } + let server = error + .remote_error_metadata() + .unwrap() + .server + .as_ref() + .unwrap(); + assert_eq!(server.git_sha, "0123456789ab"); + assert_eq!(server.release, "1.2.3"); + let message = error.to_string(); + assert!(message.contains("0123456789ab"), "{message}"); + assert!(message.contains("2024-01-01T00:00:00Z"), "{message}"); + } + } + + #[tokio::test] + async fn test_server_info_distinguishes_unsupported_from_denied() { + for status in [404, 403] { + let conn = Connection::new_with_handler(move |_| { + http::Response::builder() + .status(status) + .body("unavailable") + .unwrap() + }); + let error = conn.server_info().await.unwrap_err(); + if status == 404 { + assert!( + matches!(error, Error::NotSupported { message } if message.contains("/v1/server/info")) + ); + } else { + assert!(matches!( + error, + Error::Http { + status_code: Some(http::StatusCode::FORBIDDEN), + .. + } + )); + } + } + } + #[tokio::test] async fn test_list_gpu_classes_reports_configured_hardware() { let conn = Connection::new_with_handler(|request| { @@ -4368,7 +4491,7 @@ mod tests { }); let err = conn.open_job("nope").await.unwrap_err(); assert!( - matches!(&err, Error::JobNotFound { job_id } if job_id == "nope"), + matches!(&err, Error::JobNotFound { job_id, .. } if job_id == "nope"), "{err:?}" ); } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 949b078e3..9c34f8f90 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -1797,6 +1797,11 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .map(str::to_owned) }; let metadata = crate::error::RemoteErrorMetadata { + server: status + .metadata() + .get_bin("x-lancedb-server-build-bin") + .and_then(|value| value.to_bytes().ok()) + .and_then(|value| serde_json::from_slice(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header(SQL_JOB_ID_METADATA_KEY), job_request_id: header("x-job-request-id"), @@ -1805,8 +1810,12 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .and_then(crate::error::parse_flight_resource_identity), }; let sql_job_id = metadata.job_id.clone(); + let mut message = status.message().to_owned(); + if let Some(server) = &metadata.server { + message.push_str(&format!(" [server: {server}]")); + } let error = Error::Sql { - message: status.message().into(), + message: message.clone(), request_id: request_id.into(), grpc_code: status.code() as i32, metadata: Box::new(metadata), @@ -1816,7 +1825,7 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro job_id: Some(sql_job_id.clone()), failure: Box::new(JobFailure { phase: None, - message: Some(status.message().into()), + message: Some(message), traceback: None, retryable: None, sql_job_id: Some(sql_job_id), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d94defac4..eb994f7dd 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -33,6 +33,53 @@ use crate::remote::table::RemoteTable; use crate::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; use crate::table::BaseTable; +#[test] +fn server_info_survives_flight_error_and_job_wrapping() { + for with_job in [false, true] { + let mut status = tonic::Status::invalid_argument("invalid query"); + status + .metadata_mut() + .insert("x-lancedb-error-code", "invalid_query".parse().unwrap()); + let build = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" + }) + .to_string(); + status.metadata_mut().insert_bin( + "x-lancedb-server-build-bin", + tonic::metadata::MetadataValue::from_bytes(build.as_bytes()), + ); + if with_job { + status + .metadata_mut() + .insert(SQL_JOB_ID_METADATA_KEY, "job-original".parse().unwrap()); + } + let error = sql_status_error("request-original", &status); + let text = error.to_string(); + assert!(text.contains("invalid query"), "{text}"); + assert!(text.contains("1.2.3"), "{text}"); + assert!(text.contains("0123456789ab"), "{text}"); + assert!(text.contains("2024-01-01T00:00:00Z"), "{text}"); + assert_eq!( + error.remote_error_metadata().unwrap().error_code.as_deref(), + Some("invalid_query") + ); + match error { + Error::JobFailed { job_id, .. } if with_job => { + assert_eq!(job_id.as_deref(), Some("job-original")) + } + Error::Sql { + grpc_code, + request_id, + .. + } if !with_job => { + assert_eq!(grpc_code, tonic::Code::InvalidArgument as i32); + assert_eq!(request_id, "request-original"); + } + other => panic!("unexpected error classification: {other}"), + } + } +} + #[derive(Debug, Default)] struct DelayedHeaderProvider { delay_next: AtomicBool, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index fdb547afa..dcceb4260 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1939,7 +1939,7 @@ fn base_media_type(content_type: &str) -> &str { fn unwrap_shared_error(arc: Arc) -> Error { match Arc::try_unwrap(arc) { Ok(err) => err, - Err(arc) => match &*arc { + Err(arc) => arc.clone_shared().unwrap_or_else(|| match &*arc { Error::TableNotFound { name, source } => Error::TableNotFound { name: name.clone(), source: source.to_string().into(), @@ -1947,7 +1947,7 @@ fn unwrap_shared_error(arc: Arc) -> Error { _ => Error::Runtime { message: arc.to_string(), }, - }, + }), } } @@ -1971,17 +1971,8 @@ async fn fetch_schema( let (request_id, response) = client.send_with_retry(request, None, true).await?; - if response.status() == StatusCode::NOT_FOUND { - let body = response.text().await.ok().unwrap_or_default(); - return Err(Error::TableNotFound { - name: table_name.to_string(), - source: Box::new(Error::Http { - source: body.into(), - request_id, - status_code: Some(StatusCode::NOT_FOUND), - }), - }); - } + let response = + RemoteTable::::handle_table_not_found(table_name, response, &request_id).await?; let response = client.check_response(&request_id, response).await?; freshness_headers.observe_headers(&freshness, response.headers()); @@ -4922,6 +4913,49 @@ mod tests { assert_eq!(schema, expected); } + #[tokio::test] + async fn test_server_info_survives_schema_cache_errors() { + let expected = crate::server_info::ServerBuildInfo { + release: "1.2.3".into(), + git_sha: "0123456789ab".into(), + build_date: Some("2024-01-01T00:00:00Z".into()), + }; + for header_only in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + let response = http::Response::builder().status(404); + if header_only { + response + .header("x-lancedb-server-build", server.to_string()) + .body("missing".to_string()) + .unwrap() + } else { + response + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let original = Arc::new(table.schema().await.unwrap_err()); + // Keep another reader's reference alive to exercise the shared result. + let shared = unwrap_shared_error(original.clone()); + for error in [original.as_ref(), &shared] { + assert!(matches!(error, Error::TableNotFound { name, .. } if name == "my_table")); + assert_eq!(error.status_code(), Some(StatusCode::NOT_FOUND)); + assert_eq!( + error + .remote_error_metadata() + .and_then(|metadata| metadata.server.as_ref()), + Some(&expected), + ); + assert!(error.to_string().contains("0123456789ab")); + } + } + } + #[tokio::test] async fn test_count_rows() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/server_info.rs b/rust/lancedb/src/server_info.rs new file mode 100644 index 000000000..48daf508b --- /dev/null +++ b/rust/lancedb/src/server_info.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Remote server provenance for diagnostics without submitting a query or job. + +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Immutable identity compiled into a server executable. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerBuildInfo { + /// Release of this executable. + pub release: String, + /// Git revision used to build the executable. + pub git_sha: String, + /// UTC RFC 3339 build timestamp, when known. + pub build_date: Option, +} + +impl fmt::Display for ServerBuildInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} (git {}, built {})", + self.release, + self.git_sha, + self.build_date.as_deref().unwrap_or("unknown") + ) + } +} + +/// Identity of the query node that answered a discovery request. +/// +/// Different requests can reach different versions during a rolling upgrade. +/// Configured images do not establish which version a running job uses. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerInfo { + /// The responding executable; absent if its identity was not initialized. + pub query_node: Option, + /// Lance library linked into the responding server. + pub lance_version: String, + /// LanceDB library linked into the responding server. + pub lancedb_version: String, + /// Function worker protocol supported by this server build. + pub function_worker_protocol_version: u16, + /// Configured query-node image, not an independently observed digest. + pub configured_query_node_image: Option, + /// Default CPU/job worker image; existing jobs can retain earlier pins. + pub configured_job_worker_image: Option, + /// CLI image configured for newly launched SQL jobs. + pub configured_sql_job_image: Option, + /// Configured GPU worker image, not an observation of a running worker. + pub configured_gpu_worker_image: Option, +} From f863ea5e0858f7a081206488ee7e33ec4e34d88d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 06:34:38 +0800 Subject: [PATCH 18/36] feat(rust): support cross-table blob copies in DataFusion (#4976) `INSERT INTO target SELECT ... FROM source` currently cannot copy Blob v2 descriptors into an independent table. This enables copies from a single native source snapshot through projections, filters, sorting, and limits, while preserving descriptor queries such as `SELECT payload.size`. Source-owned payloads become target-owned data, so subsequent source mutation, compaction, or deletion does not invalidate the copy; nested fields retain their named identity across metadata differences, child reordering, scalar casts, and nullable parents. External blobs remain URI/range references under the destination's existing authorization policy: a destination that independently registers the matching external base accepts the copy, while an unregistered destination rejects it without committing. Source base registrations are not transferred, and `allow_external_blob_outside_bases` is not relaxed. JOIN, UNION, aggregation, and computed descriptors are rejected during planning. This addresses the DataFusion cross-table copy portion of OSS-696; remote/cloud execution and Realtime/MemWAL remain outside this support boundary. Local acceptance covers 15 passing DataFusion Blob integration cases, including byte reads after physical source-directory deletion, authorized and unauthorized External ranges, and a source-read failure after an earlier partition has written an uncommitted data file, with both the live destination and an independently reopened manifest unchanged. Existing regression evidence also includes 195 DataFusion unit tests and 59 Blob integration tests. Rust formatting and whitespace checks passed. Remote-feature builds, cloud/S3 execution, clippy, and the full workspace suite were not run. --- rust/lancedb/src/table/datafusion.rs | 99 ++- .../src/table/datafusion/blob_materialize.rs | 615 +++++++++++++++ rust/lancedb/src/table/datafusion/insert.rs | 4 + rust/lancedb/tests/datafusion_blob_schema.rs | 707 +++++++++++++++++- 4 files changed, 1380 insertions(+), 45 deletions(-) create mode 100644 rust/lancedb/src/table/datafusion/blob_materialize.rs diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 81df7d300..22ec5caeb 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -4,6 +4,7 @@ //! This module contains adapters to allow LanceDB tables to be used as DataFusion table providers. mod blob_coerce; +mod blob_materialize; mod blob_nulls; pub mod cast; pub mod insert; @@ -31,7 +32,7 @@ use lance_core::{ datatypes::{Projection, Schema as LanceSchema}, }; -use super::{AnyQuery, BaseTable}; +use super::{AnyQuery, BaseTable, NativeTableExt}; use crate::{ Error, Result, query::{QueryExecutionOptions, QueryFilter, QueryRequest, Select}, @@ -199,7 +200,8 @@ impl ExecutionPlan for MetadataEraserExec { pub enum BlobSchema { /// Expose Blob v2 descriptors (`kind`, `position`, `size`, `blob_id`, `blob_uri`) /// and legacy v1 descriptors (`position`, `size`). Scans support all blob fields; - /// SQL INSERT into Blob v2 tables is unsupported. + /// SQL INSERT SELECT materializes descriptors from a single native-table + /// snapshot; remote and Realtime/MemWAL sources are not supported. #[default] Read, /// Expose Blob v2 write inputs (`data`, `uri`, `position`, `size`) and legacy @@ -213,9 +215,33 @@ pub enum BlobSchema { /// /// Defaults to [`BlobSchema::Read`], matching the descriptor schema produced by /// scans without fetching blob bytes. Use [`Self::with_blob_schema`] to enable -/// SQL INSERT into blob columns. Legacy v1 blobs expose descriptors in read mode -/// and `LargeBinary` inputs in write mode; write-mode descriptor scans fail with -/// a schema mismatch. Tables without blob columns behave the same in both modes. +/// SQL INSERT with logical blob inputs. In read mode, INSERT SELECT can copy +/// Blob v2 descriptors from a single native-table snapshot into target-owned +/// payloads, including projections, filters, sorting, and limits. JOIN, UNION, +/// aggregation, and computed descriptors fail during planning because their +/// source row addresses cannot be established safely. Legacy v1 blobs expose +/// descriptors in read mode and `LargeBinary` inputs in write mode; write-mode +/// descriptor scans fail with a schema mismatch. Tables without blob columns +/// behave the same in both modes. +/// Descriptor copying requires a native source table; remote and Realtime/MemWAL +/// sources are not supported by this materialization path. +/// +/// With read adapters registered as `source` and `target`, copying blobs needs +/// no payload UDF or explicit system columns: +/// +/// ```sql +/// INSERT INTO target SELECT * FROM source WHERE id > 10; +/// ``` +/// +/// The target owns the copied payloads independently of subsequent source +/// compaction or deletion. External URI references retain their external +/// storage semantics and remain subject to the target's registered external +/// bases; copying a descriptor does not authorize a new external location. +/// +/// Materialization allocates payload bytes for each input batch outside the +/// DataFusion memory pool. For large blobs, configure a conservative +/// `SessionConfig::with_batch_size`; the pool limit alone does not bound these +/// allocations, and a single blob can still exceed that limit. #[derive(Debug)] pub struct BaseTableAdapter { table: Arc, @@ -440,13 +466,55 @@ impl TableProvider for BaseTableAdapter { ..Default::default() }; - let plan = self - .table - .create_plan(&AnyQuery::Query(query), options) + // The scan and any later INSERT rewrite must use the same snapshot, + // even if the live table advances between planning and execution. + let projects_descriptors = match projection { + Some(indices) => indices + .iter() + .any(|index| blob_nulls::has_descriptor(provider_schema.field(*index))), + None => provider_schema + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)), + }; + let snapshot = if self.blob_schema == BlobSchema::Read + && self.table.as_native().is_some() + && projects_descriptors + { + Some( + self.table + .query_snapshot() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?, + ) + } else { + None + }; + let source = snapshot.as_ref().unwrap_or(&self.table); + let plan = source + .create_plan(&AnyQuery::Query(query.clone()), options.clone()) .map_err(|err| DataFusionError::External(err.into())) .await?; let plan = blob_nulls::mask_plan(plan)?; - let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let mut plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + if let Some(snapshot) = snapshot + && plan + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + let dataset = snapshot + .as_native() + .unwrap() + .dataset + .get() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + plan = Arc::new(blob_materialize::BlobScanExec::new( + plan, snapshot, dataset, query, options, + )); + } if self.blob_schema == BlobSchema::Write { let schema = match projection { Some(projection) => Arc::new(provider_schema.project(projection)?), @@ -509,17 +577,30 @@ impl TableProvider for BaseTableAdapter { input: Arc, insert_op: InsertOp, ) -> DataFusionResult> { + let has_descriptors = input + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + || (blob_materialize::has_source_scan(&input) + && input + .schema() + .fields() + .iter() + .any(|field| blob_materialize::has_descriptor(field))); if self.blob_schema == BlobSchema::Read && self .schema .fields() .iter() .any(|field| blob_nulls::has_descriptor(field)) + && !has_descriptors { return Err(DataFusionError::NotImplemented( "SQL INSERT into Blob v2 tables requires BlobSchema::Write".into(), )); } + let input = blob_materialize::materialize(input, self.write_schema.as_ref()).await?; let mode = match insert_op { InsertOp::Append => WriteMode::Append, InsertOp::Overwrite => WriteMode::Overwrite, diff --git a/rust/lancedb/src/table/datafusion/blob_materialize.rs b/rust/lancedb/src/table/datafusion/blob_materialize.rs new file mode 100644 index 000000000..22d0a023d --- /dev/null +++ b/rust/lancedb/src/table/datafusion/blob_materialize.rs @@ -0,0 +1,615 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Preserve scan provenance until INSERT can materialize source-owned blobs. +//! +//! External descriptors remain references and must satisfy the destination's +//! existing external-base policy; source authorization grants no target trust. + +use std::fmt; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use datafusion_common::{DataFusionError, Result, tree_node::TreeNodeRecursion}; +use datafusion_execution::{SendableRecordBatchStream, TaskContext}; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::{ + PhysicalExpr, ScalarFunctionExpr, + expressions::{CastExpr, Column, Literal}, +}; +use datafusion_physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, + coalesce_partitions::CoalescePartitionsExec, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + filter::FilterExec, + limit::{GlobalLimitExec, LocalLimitExec}, + projection::ProjectionExec, + repartition::RepartitionExec, + sorts::{sort::SortExec, sort_preserving_merge::SortPreservingMergeExec}, + stream::RecordBatchStreamAdapter, +}; +use futures::{FutureExt, TryStreamExt, future::BoxFuture}; +use lance::{Dataset, dataset::BlobV2BatchRewritePlan}; +use lance_core::{ + ROW_ADDR, + datatypes::{BlobV2Layout, Schema as LanceSchema}, +}; + +use super::{BaseTable, MetadataEraserExec, blob_nulls}; +use crate::{ + query::{QueryExecutionOptions, QueryRequest, Select}, + table::AnyQuery, +}; + +const HIDDEN_ROW_ADDR: &str = "__lancedb_blob_rowaddr"; + +// Expressions such as CASE can retain the descriptor layout while dropping +// extension metadata. They still require proven provenance before writing. +pub(super) fn has_descriptor(field: &Field) -> bool { + contains_layout(field.data_type(), BlobV2Layout::Descriptor) +} + +fn descriptor_for_target(input: &Field, target: &Field) -> bool { + if crate::blob::is_blob(target) { + return matches!(input.data_type(), DataType::Struct(fields) + if BlobV2Layout::classify(fields) == Some(BlobV2Layout::Descriptor)); + } + match (input.data_type(), target.data_type()) { + (DataType::Struct(input), DataType::Struct(target)) => target.iter().any(|target| { + input + .find(target.name()) + .is_some_and(|(_, input)| descriptor_for_target(input, target)) + }), + ( + DataType::List(input) | DataType::LargeList(input) | DataType::FixedSizeList(input, _), + DataType::List(target) + | DataType::LargeList(target) + | DataType::FixedSizeList(target, _), + ) => descriptor_for_target(input, target), + _ => false, + } +} + +fn contains_layout(data_type: &DataType, layout: BlobV2Layout) -> bool { + match data_type { + DataType::Struct(fields) => { + BlobV2Layout::classify(fields) == Some(layout) + || fields + .iter() + .any(|field| contains_layout(field.data_type(), layout)) + } + DataType::List(item) | DataType::LargeList(item) | DataType::FixedSizeList(item, _) => { + contains_layout(item.data_type(), layout) + } + _ => false, + } +} + +pub(super) fn has_source_scan(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.children().iter().any(|child| has_source_scan(child)) +} + +#[expect( + deprecated, + reason = "DataFusion 55 still accepts CoalesceBatchesExec plans" +)] +fn preserves_row_identity(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input + .downcast_ref::() + .is_some() + || input.downcast_ref::().is_some() +} + +fn provenance_error(detail: impl fmt::Display) -> DataFusionError { + DataFusionError::Plan(format!( + "Blob INSERT SELECT requires descriptors from one source table snapshot with an \ + unambiguous row address; {detail}. JOIN, UNION, aggregation, and computed blob \ + descriptors are not supported" + )) +} + +/// A transparent scan boundary. It retains the snapshot and scan request, rather +/// than exposing a system column to SELECT * or fetching any payloads on reads. +#[derive(Debug)] +pub(super) struct BlobScanExec { + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, +} + +impl BlobScanExec { + pub(super) fn new( + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, + ) -> Self { + Self { + input, + source, + dataset, + query, + options, + } + } + + async fn with_row_address(&self) -> Result { + let mut query = self.query.clone(); + let Select::Columns(columns) = &mut query.select else { + return Err(provenance_error( + "source scan has no explicit column projection", + )); + }; + if !columns.iter().any(|name| name == ROW_ADDR) { + columns.push(ROW_ADDR.to_owned()); + } + let plan = self + .source + .create_plan(&AnyQuery::Query(query), self.options.clone()) + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + let plan = blob_nulls::mask_plan(plan)?; + let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let schema = plan.schema(); + let mut projection: Vec<(Arc, String)> = self + .input + .schema() + .fields() + .iter() + .map(|field| { + Ok(( + Arc::new(Column::new(field.name(), schema.index_of(field.name())?)) as _, + field.name().clone(), + )) + }) + .collect::>()?; + projection.push(( + Arc::new(Column::new(ROW_ADDR, schema.index_of(ROW_ADDR)?)), + HIDDEN_ROW_ADDR.into(), + )); + Ok(Provenance { + plan: Arc::new(ProjectionExec::try_new(projection, plan)?), + dataset: self.dataset.clone(), + fields: self + .input + .schema() + .fields() + .iter() + .map(|field| Some(field.name().clone())) + .collect(), + }) + } +} + +impl DisplayAs for BlobScanExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "BlobScanExec: version={}", + self.dataset.version().version + ) + } +} + +impl ExecutionPlan for BlobScanExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "BlobScanExec" + } + fn properties(&self) -> &Arc { + self.input.properties() + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid scan children"))?; + Ok(Arc::new(Self::new( + input, + self.source.clone(), + self.dataset.clone(), + self.query.clone(), + self.options.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + self.input.execute(partition, context) + } +} + +struct Provenance { + plan: Arc, + dataset: Arc, + // Source field path for each output column, before the hidden address. + fields: Vec>, +} + +fn source_field(expr: &Arc, fields: &[Option]) -> Option { + if let Some(column) = expr.downcast_ref::() { + return fields.get(column.index()).cloned().flatten(); + } + let call = expr.downcast_ref::()?; + call.fun().inner().downcast_ref::()?; + let (root, path) = call.args().split_first()?; + let mut source = source_field(root, fields)?; + for component in path { + let name = component + .downcast_ref::()? + .value() + .try_as_str() + .flatten()?; + source.push('.'); + source.push_str(name); + } + Some(source) +} + +fn with_provenance(input: Arc) -> BoxFuture<'static, Result> { + async move { + if let Some(scan) = input.downcast_ref::() { + return scan.with_row_address().await; + } + let children = input.children(); + // An explicit allowlist keeps row identity from silently propagating + // through a future operator that changes cardinality or column meaning. + if children.len() != 1 || !preserves_row_identity(&input) { + return Err(provenance_error(format!( + "cannot establish provenance through {}", + input.name() + ))); + } + let mut provenance = with_provenance(children[0].clone()).await?; + if let Some(projection) = input.downcast_ref::() { + let fields = projection + .expr() + .iter() + .map(|expr| source_field(&expr.expr, &provenance.fields)) + .collect(); + let mut expressions: Vec<(Arc, String)> = projection + .expr() + .iter() + .map(|expr| (expr.expr.clone(), expr.alias.clone())) + .collect(); + expressions.push(( + Arc::new(Column::new( + HIDDEN_ROW_ADDR, + provenance.plan.schema().fields().len() - 1, + )), + HIDDEN_ROW_ADDR.into(), + )); + provenance.plan = Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + provenance.fields = fields; + } else { + if input.schema() != children[0].schema() { + return Err(provenance_error(format!( + "{} changes the source schema", + input.name() + ))); + } + provenance.plan = input.replace_children( + vec![provenance.plan], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + } + Ok(provenance) + } + .boxed() +} + +/// Defer only a container coercion whose Blob leaves retain their named paths. +/// Descriptor leaves are atomic: casting their members is never provenance. +fn can_defer_blob_cast(source: &Field, cast_type: &DataType, target: &Field) -> bool { + if crate::blob::is_blob(target) { + let (DataType::Struct(source), DataType::Struct(cast)) = (source.data_type(), cast_type) + else { + return false; + }; + return BlobV2Layout::classify(source) == Some(BlobV2Layout::Descriptor) + && (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Logical) + || (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Descriptor) + && source.len() == cast.len() + && source.iter().zip(cast).all(|(source, cast)| { + source.name() == cast.name() && source.data_type() == cast.data_type() + }))); + } + match (source.data_type(), cast_type, target.data_type()) { + (DataType::Struct(source), DataType::Struct(cast), DataType::Struct(target)) => { + source.len() == cast.len() + && source.len() == target.len() + && target.iter().all(|target| { + source + .find(target.name()) + .zip(cast.find(target.name())) + .is_some_and(|((_, source), (_, cast))| { + can_defer_blob_cast(source, cast.data_type(), target) + }) + }) + } + (DataType::List(source), DataType::List(cast), DataType::List(target)) + | (DataType::LargeList(source), DataType::LargeList(cast), DataType::LargeList(target)) => { + can_defer_blob_cast(source, cast.data_type(), target) + } + ( + DataType::FixedSizeList(source, source_len), + DataType::FixedSizeList(cast, cast_len), + DataType::FixedSizeList(target, target_len), + ) => { + source_len == cast_len + && source_len == target_len + && can_defer_blob_cast(source, cast.data_type(), target) + } + _ => !has_descriptor(source) && cast_type == target.data_type(), + } +} + +pub(super) async fn materialize( + input: Arc, + target_schema: &Schema, +) -> Result> { + if !target_schema + .fields() + .iter() + .any(|field| crate::blob::field_tree_has_blob_v2(field)) + { + return Ok(input); + } + // INSERT may cast containers for metadata, field order, scalar siblings, + // or a Write adapter's logical layout. Bind the original Blob leaves and + // materialize before applying the target coercion. Other expressions still + // have to pass the Column/GetField provenance checks below. + let input = if let Some(projection) = input.downcast_ref::() { + let mut changed = false; + let expressions = projection + .expr() + .iter() + .map(|projected| { + let mut expr = projected.expr.clone(); + if let Some(cast) = expr.downcast_ref::() + && let Ok(target) = target_schema.field_with_name(&projected.alias) + && crate::blob::field_tree_has_blob_v2(target) + && let source = cast + .expr() + .return_field(projection.input().schema().as_ref())? + && has_descriptor(&source) + { + if !can_defer_blob_cast( + &source, + &cast.data_type(projection.input().schema().as_ref())?, + target, + ) { + return Err(provenance_error(format!( + "cast of column '{}' does not preserve Blob leaf identity", + projected.alias + ))); + } + expr = cast.expr().clone(); + changed = true; + } + Ok((expr, projected.alias.clone())) + }) + .collect::>>()?; + if changed { + Arc::new(ProjectionExec::try_new( + expressions, + projection.input().clone(), + )?) as Arc + } else { + input + } + } else { + input + }; + let rewrite_columns: Vec = input + .schema() + .fields() + .iter() + .map(|field| { + target_schema + .field_with_name(field.name()) + .is_ok_and(|target| descriptor_for_target(field, target)) + }) + .collect(); + if !rewrite_columns.iter().any(|rewrite| *rewrite) { + return Ok(input); + } + let provenance = with_provenance(input.clone()).await?; + let mut source_schema = LanceSchema::default(); + let mut expressions: Vec<(Arc, String)> = Vec::new(); + for (index, (field, source)) in input + .schema() + .fields() + .iter() + .zip(&provenance.fields) + .enumerate() + { + let name = format!("__lancedb_blob_column_{index}"); + if rewrite_columns[index] { + let source = source.as_ref().ok_or_else(|| { + provenance_error(format!("column '{}' has no source", field.name())) + })?; + let mut source_field = provenance + .dataset + .schema() + .field(source) + .ok_or_else(|| provenance_error(format!("source field '{source}' is missing")))? + .clone(); + if !crate::blob::field_tree_has_blob_v2(&Field::from(&source_field)) { + return Err(provenance_error(format!( + "source field '{source}' is not a Blob v2 column" + ))); + } + source_field.name = name.clone(); + source_schema.fields.push(source_field); + } + expressions.push((Arc::new(Column::new(field.name(), index)), name)); + } + expressions.push(( + Arc::new(Column::new(HIDDEN_ROW_ADDR, provenance.fields.len())), + ROW_ADDR.into(), + )); + let plan: Arc = + Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + // preserve_managed=false forces even managed source payloads to become + // target-owned bytes instead of retaining source storage references. + let rewrite = Arc::new(BlobV2BatchRewritePlan::try_new( + &source_schema, + plan.schema().as_ref(), + false, + false, + )?); + let schema = Arc::new(Schema::new( + rewrite + .output_schema() + .fields() + .iter() + .zip(input.schema().fields()) + .map(|(rewritten, original)| rewritten.as_ref().clone().with_name(original.name())) + .collect::>(), + )); + let plan = Arc::new(MaterializeBlobsExec::new( + plan, + provenance.dataset, + rewrite, + schema, + )); + super::cast::cast_to_table_schema(plan, target_schema) + .map_err(|error| DataFusionError::External(Box::new(error))) +} + +struct MaterializeBlobsExec { + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + properties: Arc, +} + +impl fmt::Debug for MaterializeBlobsExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MaterializeBlobsExec") + .field("input", &self.input) + .finish_non_exhaustive() + } +} + +impl MaterializeBlobsExec { + fn new( + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + ) -> Self { + // Rewriting changes column types; descriptor equivalences/orderings do + // not describe the resulting payload structs. + let properties = Arc::new(PlanProperties::new( + datafusion_physical_expr::EquivalenceProperties::new(schema.clone()), + datafusion_physical_expr::Partitioning::UnknownPartitioning( + input.output_partitioning().partition_count(), + ), + input.properties().emission_type, + input.properties().boundedness, + )); + Self { + input, + dataset, + rewrite, + schema, + properties, + } + } +} + +impl DisplayAs for MaterializeBlobsExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "MaterializeBlobsExec") + } +} + +impl ExecutionPlan for MaterializeBlobsExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "MaterializeBlobsExec" + } + fn properties(&self) -> &Arc { + &self.properties + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid rewrite children"))?; + Ok(Arc::new(Self::new( + input, + self.dataset.clone(), + self.rewrite.clone(), + self.schema.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + let dataset = self.dataset.clone(); + let rewrite = self.rewrite.clone(); + let schema = self.schema.clone(); + let stream = self + .input + .execute(partition, context)? + .and_then(move |batch| { + let dataset = dataset.clone(); + let rewrite = rewrite.clone(); + let schema = schema.clone(); + async move { + let batch = rewrite.transform_batch(&dataset, batch).await?; + Ok(RecordBatch::try_new(schema, batch.columns().to_vec())?) + } + }); + Ok(Box::pin(RecordBatchStreamAdapter::new( + self.schema.clone(), + stream, + ))) + } +} diff --git a/rust/lancedb/src/table/datafusion/insert.rs b/rust/lancedb/src/table/datafusion/insert.rs index ec1e603d2..a2d5f34c9 100644 --- a/rust/lancedb/src/table/datafusion/insert.rs +++ b/rust/lancedb/src/table/datafusion/insert.rs @@ -195,6 +195,7 @@ impl ExecutionPlan for InsertExec { context: Arc, ) -> DataFusionResult { let input_stream = self.input.execute(partition, context)?; + let input_plan = self.input.clone(); let dataset = self.dataset.clone(); let mut write_params = self.write_params.clone(); let partial_transactions = self.partial_transactions.clone(); @@ -227,6 +228,9 @@ impl ExecutionPlan for InsertExec { )); let stream = futures::stream::once(async move { + // Source blob snapshots must outlive the final target commit, not + // only the consumption of the input stream. + let _input_plan = input_plan; if let Some(tracker) = tracker && write_params.write_progress.is_none() { diff --git a/rust/lancedb/tests/datafusion_blob_schema.rs b/rust/lancedb/tests/datafusion_blob_schema.rs index d51c182f6..5af3122ab 100644 --- a/rust/lancedb/tests/datafusion_blob_schema.rs +++ b/rust/lancedb/tests/datafusion_blob_schema.rs @@ -571,66 +571,701 @@ async fn legacy_blob_write_mode_rejects_descriptor_scans_and_keeps_scalar_scans( } #[tokio::test] -async fn copying_non_null_descriptors_between_tables_commits_no_rows() { +async fn copying_descriptors_materializes_payloads_and_preserves_snapshot() { + use std::collections::HashMap; + use std::num::NonZeroUsize; + + use lancedb::blob::{BlobOptions, blob_with_options}; + use lancedb::table::OptimizeAction; + + for managed in [false, true] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let payload = blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(8), + dedicated_size_threshold: NonZeroUsize::new(32), + }, + ); + let values: Vec> = vec![ + Some(b"hi"), + Some(&[2; 16]), + Some(&[3; 64]), + None, + Some(b""), + Some(b"skip"), + ]; + let schema = Arc::new(Schema::new_with_metadata( + vec![Field::new("id", DataType::Int64, false), payload], + HashMap::from([("lance.blob.managed".into(), managed.to_string())]), + )); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2, 3, 4, 5, 6])), + blob_inputs(values.clone()), + ], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_batch_size(2) + .with_target_partitions(2), + ); + register(&ctx, &source, BlobSchema::Read).await; + // Descriptor queries and SELECT * retain their original read schema. + let sizes = sql(&ctx, "SELECT payload.size FROM docs ORDER BY id").await; + assert_eq!( + sizes + .column(0) + .as_primitive::() + .value(2), + 64 + ); + assert_eq!(sql(&ctx, "SELECT * FROM docs").await.num_columns(), 2); + let kinds = sql(&ctx, "SELECT payload.kind FROM docs ORDER BY id").await; + let kinds = kinds + .column(0) + .as_primitive::(); + if !managed { + assert_eq!( + kinds.value(0), + lance_core::datatypes::BlobKind::Inline as u8 + ); + assert_eq!( + kinds.value(1), + lance_core::datatypes::BlobKind::Packed as u8 + ); + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Dedicated as u8 + ); + } else { + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Managed as u8 + ); + } + let (_destination_tmp, destination) = empty_table(vec![ + blob("copied", true), + Field::new("id", DataType::Int64, false), + ]) + .await; + let writer = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode); + ctx.register_table("destination", Arc::new(writer)).unwrap(); + let plan = ctx.sql("INSERT INTO destination (id, copied) SELECT id + 10, payload AS copied FROM docs WHERE id > 0 AND (payload.size IS NULL OR payload.size < 100) ORDER BY id DESC LIMIT 5 OFFSET 1") + .await.unwrap().create_physical_plan().await.unwrap(); + // A live-table change after planning must not change the source + // version used to decode the descriptors in this insert. + source.delete("id = 1").await.unwrap(); + datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(destination.count_rows(None).await.unwrap(), 5); + source.optimize(OptimizeAction::All).await.unwrap(); + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let reader = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID]) + .unwrap(); + ctx.register_table("copied_rows", Arc::new(reader)).unwrap(); + let ids = sql(&ctx, "SELECT _rowid FROM copied_rows ORDER BY id").await; + let ids = ids + .column(0) + .as_primitive::() + .values(); + assert_eq!( + destination.fetch_blobs("copied", ids).await.unwrap(), + LargeBinaryArray::from(values[..5].to_vec()) + ); + } + } +} + +#[tokio::test] +async fn copying_nested_descriptors_preserves_parent_nulls_and_field_identity() { + use arrow_array::Int32Array; + use lancedb::blob::{BlobOptions, blob_with_options}; + + for difference in ["metadata", "order", "scalar"] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let children = vec![ + Arc::new(Field::new("note", DataType::Utf8, true)), + Arc::new(Field::new("rank", DataType::Int32, true)), + Arc::new(blob_with_options( + "clip", + true, + BlobOptions { + inline_size_threshold: Some(8), + ..Default::default() + }, + )), + ]; + let extra_field = Field::new("extra", DataType::Struct(children.clone().into()), true); + let extra = StructArray::new( + children.into(), + vec![ + Arc::new(StringArray::from(vec![ + Some("a"), + Some("hidden"), + Some("c"), + ])), + Arc::new(Int32Array::from(vec![1, 2, 3])), + blob_inputs(vec![Some(b"hi"), Some(b"hidden"), Some(b"")]), + ], + Some(NullBuffer::from(vec![true, false, true])), + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + extra_field, + ])), + vec![Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let mut target_children = vec![ + Field::new("note", DataType::Utf8, true), + Field::new( + "rank", + if difference == "scalar" { + DataType::Int64 + } else { + DataType::Int32 + }, + true, + ), + blob("clip", true), + ]; + if difference == "order" { + target_children.swap(0, 2); + } + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + Field::new("extra", DataType::Struct(target_children.into()), true), + blob("flattened", true), + ]) + .await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + for expression in [ + "CASE WHEN id = 1 THEN extra ELSE NULL END", + "named_struct('note', extra.note, 'rank', extra.rank, 'clip', extra.clip)", + ] { + let query = format!( + "INSERT INTO destination SELECT id, {expression} AS extra, extra.clip AS flattened FROM docs" + ); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{difference}, {mode:?}: {error}" + ); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } + sql(&ctx, "INSERT INTO destination SELECT id, extra, extra.clip AS flattened FROM docs ORDER BY id DESC").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let ids = row_ids(&ctx, &destination).await; + let expected = + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, Some(b"".as_slice())]); + assert_eq!( + destination.fetch_blobs("extra.clip", &ids).await.unwrap(), + expected, + "{difference}, {mode:?}" + ); + assert_eq!( + destination.fetch_blobs("flattened", &ids).await.unwrap(), + expected + ); + let nested = sql(&ctx, "SELECT extra FROM read_docs ORDER BY id").await; + let extra = nested.column(0).as_struct(); + assert!(extra.is_null(1)); + assert_eq!( + extra + .column_by_name("note") + .unwrap() + .as_string::() + .value(2), + "c" + ); + let rank = extra.column_by_name("rank").unwrap(); + if difference == "scalar" { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } else { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } + } + } +} + +#[tokio::test] +async fn ordinary_descriptor_shaped_structs_remain_plain_data() { + let fields = vec![ + Field::new("id", DataType::Int64, false), + Field::new( + "raw", + DataType::Struct( + vec![ + Field::new("kind", DataType::UInt8, true), + Field::new("position", DataType::UInt64, true), + Field::new("size", DataType::UInt64, true), + Field::new("blob_id", DataType::UInt32, true), + Field::new("blob_uri", DataType::Utf8, true), + ] + .into(), + ), + true, + ), + ]; + let (source_tmp, source) = empty_table(fields.clone()).await; + let (_destination_tmp, destination) = empty_table(fields).await; + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + sql(&ctx, "INSERT INTO docs VALUES (1, named_struct('kind', 1, 'position', 2, 'size', 3, 'blob_id', 4, 'blob_uri', 'plain data'))").await; + let expected = sql(&ctx, "SELECT * FROM docs").await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + sql(&ctx, "INSERT INTO destination SELECT * FROM docs").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let actual = sql(&ctx, "SELECT * FROM destination").await; + assert_eq!(actual.columns(), expected.columns()); +} + +#[tokio::test] +async fn ambiguous_descriptor_sources_fail_during_planning_without_writing() { let (_tmp, source) = empty_table(vec![ Field::new("id", DataType::Int64, false), blob("payload", true), ]) .await; - let ctx = SessionContext::new_with_config( - SessionConfig::new() - .with_batch_size(1) - .with_target_partitions(1), - ); + let ctx = SessionContext::new(); register(&ctx, &source, BlobSchema::Write).await; sql( &ctx, "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", ) .await; - sql(&ctx, "INSERT INTO docs VALUES (2, NULL)").await; register(&ctx, &source, BlobSchema::Read).await; - let (_dest_tmp, destination) = empty_table( - source - .schema() - .await - .unwrap() - .fields() - .iter() - .map(|f| f.as_ref().clone()) - .collect(), - ) + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) .await; let writer = BaseTableAdapter::try_new(destination.base_table().clone()) .await - .unwrap() - .with_blob_schema(BlobSchema::Write); + .unwrap(); ctx.register_table("destination", Arc::new(writer)).unwrap(); let version = destination.version().await.unwrap(); - // The null row is valid and reaches the writer before the non-null - // descriptor. Even if it is written to a fragment, it must not be committed. - let plan = ctx - .sql("INSERT INTO destination SELECT id, payload FROM docs ORDER BY id DESC") + for select in [ + "SELECT a.id, a.payload FROM docs a JOIN docs b ON a.id = b.id", + "SELECT id, payload FROM docs UNION ALL SELECT id, payload FROM docs", + "SELECT id, payload FROM docs GROUP BY id, payload", + "SELECT id, CASE WHEN id = 1 THEN payload ELSE NULL END AS payload FROM docs", + ] { + let query = format!("INSERT INTO destination {select}"); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{query}: {error}" + ); + } + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + assert_eq!(destination.version().await.unwrap(), version); +} + +#[tokio::test] +async fn external_descriptor_copy_obeys_destination_bases_and_preserves_ranges() { + use lance::dataset::WriteParams; + use lance_core::datatypes::BlobKind; + use lance_table::format::BasePath; + use lancedb::table::WriteOptions; + + let external_tmp = tempdir().unwrap(); + let payload = b"0123456789abcdef"; + let path = external_tmp.path().join("payload.bin"); + std::fs::write(&path, payload).unwrap(); + let uri = url::Url::from_file_path(&path).unwrap().to_string(); + let base_uri = url::Url::from_directory_path(external_tmp.path()) + .unwrap() + .to_string(); + let base = |id| BasePath { + id, + name: Some("external".into()), + path: base_uri.clone(), + is_dataset_root: false, + }; + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ])); + let DataType::Struct(children) = schema.field(1).data_type().clone() else { + unreachable!() + }; + let input = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + Arc::new(StructArray::new( + children, + vec![ + Arc::new(LargeBinaryArray::from(vec![ + None, + Some(b"inline".as_slice()), + ])), + Arc::new(StringArray::from(vec![Some(uri.as_str()), None])), + Arc::new(UInt64Array::from(vec![Some(4), None])), + Arc::new(UInt64Array::from(vec![Some(6), None])), + ], + None, + )), + ], + ) + .unwrap(); + for source_registered in [false, true] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let source = db + .create_empty_table("source", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: source_registered.then(|| vec![base(7)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + source + .add(input.clone()) + .allow_external_blob_outside_bases(!source_registered) + .execute() + .await + .unwrap(); + for mode in [BlobSchema::Read, BlobSchema::Write] { + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let descriptor = sql(&ctx, "SELECT payload.blob_id FROM docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + if source_registered { 7 } else { 0 } + ); + for authorized in [false, true] { + let destination_tmp = tempdir().unwrap(); + let destination_db = connect(destination_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let destination = destination_db + .create_empty_table("destination", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: authorized.then(|| vec![base(11)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + ctx.deregister_table("destination").unwrap(); + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let result = ctx + .sql("INSERT INTO destination SELECT * FROM docs ORDER BY id") + .await + .unwrap() + .collect() + .await; + if !authorized { + let error = result.unwrap_err().to_string(); + assert!( + error.contains("outside registered external bases"), + "{error}" + ); + let reopened = destination_db + .open_table("destination") + .execute() + .await + .unwrap(); + assert_eq!(reopened.version().await.unwrap(), version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); + // A logical URI input has the same destination authorization boundary. + ctx.register_table( + "logical_target", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write), + ), + ) + .unwrap(); + let error = ctx.sql(&format!("INSERT INTO logical_target SELECT 3, named_struct('data', NULL, 'uri', '{uri}')")).await.unwrap().collect().await.unwrap_err().to_string(); + assert!( + error.contains("allow_external_blob_outside_bases"), + "{error}" + ); + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } else { + result.unwrap(); + let ids = row_ids(&ctx, &destination).await; + let descriptor = sql(&ctx, "SELECT payload.kind, payload.blob_id, payload.blob_uri, payload.position, payload.size FROM read_docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + BlobKind::External as u8 + ); + assert_eq!( + descriptor + .column(1) + .as_primitive::() + .value(0), + 11 + ); + assert_eq!( + descriptor.column(2).as_string::().value(0), + "payload.bin" + ); + assert_eq!( + descriptor + .column(3) + .as_primitive::() + .value(0), + 4 + ); + assert_eq!( + descriptor + .column(4) + .as_primitive::() + .value(0), + 6 + ); + assert_eq!( + destination.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![ + Some(&payload[4..10]), + Some(b"inline".as_slice()) + ]) + ); + let files = destination.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[0].as_ref().unwrap(); + assert_eq!(file.uri(), Some("payload.bin")); + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let registered = &dataset.manifest().base_paths[&11]; + let resolved = + url::Url::parse(&format!("{}/", registered.path.trim_end_matches('/'))) + .unwrap() + .join(file.uri().unwrap()) + .unwrap(); + assert_eq!(resolved.as_str(), uri); + assert_eq!(file.position(), Some(4)); + assert_eq!(file.size(), 6); + } + } + } + } +} + +#[tokio::test] +async fn source_payload_failure_after_written_partition_does_not_commit() { + use datafusion_physical_plan::{ + ExecutionPlanProperties, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + union::UnionExec, + }; + use futures::TryStreamExt; + use lancedb::blob::{BlobOptions, blob_with_options}; + use std::num::NonZeroUsize; + + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(0), + dedicated_size_threshold: NonZeroUsize::new(1), + }, + ), + ])); + let source = db + .create_table( + "docs", + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + blob_inputs(vec![Some(&[1; 64]), Some(&[2; 64])]), + ], + ) + .unwrap(), + ) + .execute() + .await + .unwrap(); + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_target_partitions(1) + .with_batch_size(1), + ); + register(&ctx, &source, BlobSchema::Read).await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + let first = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 1") .await .unwrap() .create_physical_plan() .await .unwrap(); - let error = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + let second = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 2") .await - .unwrap_err(); - assert!(error.to_string().contains("blob"), "{error}"); + .unwrap() + .create_physical_plan() + .await + .unwrap(); + assert_eq!(first.name(), "InsertExec"); + assert_eq!(second.name(), "InsertExec"); + // Combine already validated SQL inputs only to control partition scheduling: + // finish one real uncommitted write before faulting the next payload read. + let input = UnionExec::try_new(vec![ + first.children()[0].clone(), + second.children()[0].clone(), + ]) + .unwrap(); + assert_eq!(input.output_partitioning().partition_count(), 2); + let insert = first + .replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let batches: Vec = insert + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 1 + ); assert_eq!(destination.count_rows(None).await.unwrap(), 0); assert_eq!(destination.version().await.unwrap(), version); - sql( - &ctx, - "INSERT INTO destination SELECT id, payload FROM docs WHERE payload IS NULL", - ) - .await; - let ids = row_ids(&ctx, &destination).await; - assert_eq!(ids.len(), 1); - assert_eq!( - destination.fetch_blobs("payload", &ids).await.unwrap(), - LargeBinaryArray::from(vec![None::<&[u8]>]) + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let data_dir = _destination_tmp.path().join("docs.lance").join("data"); + assert!( + std::fs::read_dir(data_dir).unwrap().next().is_some(), + "first partition must have written a data file" ); + let ids = row_ids(&ctx, &source).await; + let files = source.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[1].as_ref().unwrap(); + assert_eq!( + file.kind(), + Some(lance_core::datatypes::BlobKind::Dedicated) + ); + let missing_path = std::path::Path::new("/").join(file.data_path().unwrap().as_ref()); + drop(files); + std::fs::remove_file(&missing_path).unwrap(); + let error = insert + .execute(1, ctx.task_ctx()) + .unwrap() + .try_collect::>() + .await + .unwrap_err() + .to_string(); + assert!( + error.contains(missing_path.file_name().unwrap().to_str().unwrap()), + "{error}" + ); + // Check both the live handle and an independently reopened manifest. + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + let reopened = lance::Dataset::open(dataset.uri()).await.unwrap(); + assert_eq!(reopened.version().version, version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); } From 9302287bed205bc017979681fa31b9b8e6ae450f Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 14:57:00 -0800 Subject: [PATCH 19/36] fix: accept defining queries in Python materialized views (#4980) Python materialized-view creation now accepts a complete defining SQL query across sync, async, remote, and namespace connections, including creation jobs: ```python view = db.create_materialized_view( "events_by_kind", query="SELECT kind, count(*) AS n FROM events GROUP BY kind", ) ``` `query` is mutually exclusive with `source`, `select`, `where`, and `limit`. Existing source-based calls remain supported. Adds Rust `Connection::create_materialized_view_from_query`: embedded connections plan through `MaterializedViewDefinition::from_sql`, while remote connections submit the full query for server-side parsing. Includes regression coverage for grouping, UNNEST, query forwarding, creation jobs, and argument validation. --- docs/src/python/python.md | 14 ++ .../materialized-views.mdx | 28 +-- python/python/lancedb/_lancedb.pyi | 8 +- python/python/lancedb/db.py | 60 ++++-- python/python/lancedb/materialized_view.py | 10 + python/python/lancedb/namespace.py | 16 +- python/python/lancedb/remote/db.py | 8 +- .../python/tests/test_materialized_views.py | 175 +++++++++++++-- python/src/connection.rs | 50 ++++- rust/lancedb/src/materialized_view.rs | 199 +++++++++++++++--- rust/lancedb/src/remote/sql_test.rs | 55 +++++ 11 files changed, 536 insertions(+), 87 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 058f2529a..4ce325b2f 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -627,6 +627,20 @@ remain available, as do LanceDB Enterprise operations. The same feature requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary eager `add_columns` transforms remain available. +Pass a complete defining SQL query with `query=` to use grouping, Functions +in `FROM`, or `UNNEST`: + +```python +view = db.create_materialized_view( + "events_by_kind", + query="SELECT kind, count(*) AS n FROM events GROUP BY kind", +) +``` + +`query` is mutually exclusive with `source`, `select`, `where`, and `limit`. +It is also accepted by asynchronous connections and `create_materialized_view_async`. +The backend SQL parser determines which query shapes are supported. + In LanceDB Enterprise, creation accepts `auto_refresh_enabled` and `auto_refresh_interval_seconds`: diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 0f9494c9f..617eb7525 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -20,19 +20,19 @@ In SQL this is [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view#create). ## Create a view {#create} A materialized view is defined by a SQL query, so it is created with one. -From Python, run the statement on an [Enterprise connection](/basics/catalog#enterprise) -with [`execute_query`](/basics/sql#sql-from-python); the SQL is the same -either way: +From Python, pass the defining query to `create_materialized_view` on an +[Enterprise connection](/basics/catalog#enterprise): ```python Python icon="python" -db.execute_query(""" - CREATE MATERIALIZED VIEW frames_captioned AS - SELECT frame_id, video_id, ts, caption - FROM frames - WHERE selected = true -""").read_all() -view = db.open_materialized_view("frames_captioned") +view = db.create_materialized_view( + "frames_captioned", + query=""" + SELECT frame_id, video_id, ts, caption + FROM frames + WHERE selected = true + """, +) ``` ```sql SQL icon="database" @@ -43,9 +43,11 @@ WHERE selected = true ``` -`execute_query` returns once the result stream is readable, not once the -statement has finished, so `.read_all()` waits out the full creation before -the next line opens it. +`create_materialized_view` waits for creation and initial population, then +returns the view handle. Use `create_materialized_view_async` to submit a job +and wait for it separately. Both methods accept `query=` on synchronous and +asynchronous connections. `query` cannot be combined with `source`, `select`, +`where`, or `limit`; put those clauses in the query itself. The query defines the view: here, the `frames` table's `frame_id`, `video_id`, `ts` and `caption` columns, filtered to the frames selected for diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index ffdd68e5f..5897ddd0c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -349,24 +349,28 @@ class Connection(object): async def create_materialized_view( self, name: str, - source: str, + source: Optional[str] = None, projections: Optional[List[Tuple[str, str]]] = None, filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + *, + query: Optional[str] = None, ) -> Table: ... async def create_materialized_view_async( self, name: str, - source: str, + source: Optional[str] = None, projections: Optional[List[Tuple[str, str]]] = None, filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + *, + query: Optional[str] = None, ) -> Job: ... def list_materialized_views( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b4e5c6182..7d690abe3 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -79,6 +79,7 @@ from .materialized_view import ( MaterializedViewSource, SelectArg, normalize_select, + _validate_create_materialized_view, ) from .secrets import ( EnvVarSecret, @@ -698,8 +699,9 @@ class DBConnection(EnforceOverrides): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -722,8 +724,12 @@ class DBConnection(EnforceOverrides): ---------- name: str The name of the view. - source: str - The name of the source table. + source: str, optional + The name of the source table. Required when ``query`` is omitted. + query: str, optional + The complete defining SQL query, including any GROUP BY or FROM + Function. Mutually exclusive with ``source``, ``select``, ``where`` + and ``limit``. Supported query shapes depend on the backend. select: list or dict, optional The view's columns: column names, ``(alias, SQL expression)`` pairs, or a dict of the same. Omitting it selects every source @@ -745,6 +751,13 @@ class DBConnection(EnforceOverrides): Returns ------- MaterializedView + + Examples + -------- + >>> view = db.create_materialized_view( # doctest: +SKIP + ... "events_by_kind", + ... query="SELECT kind, count(*) AS n FROM events GROUP BY kind", + ... ) """ raise NotImplementedError( _append_doc_url( @@ -756,8 +769,9 @@ class DBConnection(EnforceOverrides): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2108,8 +2122,9 @@ class LanceDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2144,6 +2159,7 @@ class LanceDBConnection(DBConnection): self._conn.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -2158,8 +2174,9 @@ class LanceDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2171,6 +2188,7 @@ class LanceDBConnection(DBConnection): self._conn.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -3390,8 +3408,9 @@ class AsyncConnection(object): async def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -3407,9 +3426,15 @@ class AsyncConnection(object): See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ - source, native_options = await self._materialized_view_source( - source, select, where, limit - ) + _validate_create_materialized_view(source, query, select, where, limit) + if source is not None: + source, native_options = await self._materialized_view_source( + source, select, where, limit + ) + else: + native_options = {} + if query is not None: + native_options["query"] = query inner = await self._inner.create_materialized_view( name, source, @@ -3426,8 +3451,9 @@ class AsyncConnection(object): async def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -3441,9 +3467,15 @@ class AsyncConnection(object): Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. """ - source, native_options = await self._materialized_view_source( - source, select, where, limit - ) + _validate_create_materialized_view(source, query, select, where, limit) + if source is not None: + source, native_options = await self._materialized_view_source( + source, select, where, limit + ) + else: + native_options = {} + if query is not None: + native_options["query"] = query inner = await self._inner.create_materialized_view_async( name, source, diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 7b8c8c6a4..dc04f89f8 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -134,6 +134,16 @@ def _quote_identifier(name: str) -> str: return f"`{escaped}`" +def _validate_create_materialized_view(source, query, select, where, limit): + if query is not None: + if any(value is not None for value in (source, select, where, limit)): + raise ValueError( + "query cannot be combined with source, select, where or limit" + ) + elif source is None: + raise ValueError("either source or query must be provided") + + def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]: """``select`` items may be a column name, an ``(alias, expression)`` pair, or a dict of the same. A bare name projects itself and is quoted, so any diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index aa9025641..72dc78c8b 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -696,8 +696,9 @@ class LanceNamespaceDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -715,6 +716,7 @@ class LanceNamespaceDBConnection(DBConnection): self._inner.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -730,8 +732,9 @@ class LanceNamespaceDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -743,6 +746,7 @@ class LanceNamespaceDBConnection(DBConnection): self._inner.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -1339,8 +1343,9 @@ class AsyncLanceNamespaceDBConnection: async def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1352,6 +1357,7 @@ class AsyncLanceNamespaceDBConnection: view = await self._inner.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -1366,8 +1372,9 @@ class AsyncLanceNamespaceDBConnection: async def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1379,6 +1386,7 @@ class AsyncLanceNamespaceDBConnection: return await self._inner.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 911766674..db3ab554c 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -792,8 +792,9 @@ class RemoteDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -807,6 +808,7 @@ class RemoteDBConnection(DBConnection): self._conn.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -828,8 +830,9 @@ class RemoteDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -841,6 +844,7 @@ class RemoteDBConnection(DBConnection): self._conn.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index bf964102b..1ea0c1cb9 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -10,6 +10,7 @@ import lancedb import pytest import pyarrow as pa from lancedb.db import AsyncConnection +from lancedb.exceptions import JobFailedError from lancedb.materialized_view import MaterializedViewDefinition from lancedb.remote.db import RemoteDBConnection from utils import start_server_thread @@ -175,7 +176,8 @@ async def test_remote_refresh_reports_unknown_metrics( assert not any("count_rows" in path for path in requests) -def test_sync_remote_create_uses_public_async_connection(): +@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"]) +def test_sync_remote_create_uses_public_async_connection(query): calls = [] class StubAsyncTable: @@ -190,6 +192,7 @@ def test_sync_remote_create_uses_public_async_connection(): name, source, *, + query=None, select=None, where=None, limit=None, @@ -201,6 +204,7 @@ def test_sync_remote_create_uses_public_async_connection(): ( name, source, + query, select, where, limit, @@ -219,18 +223,24 @@ def test_sync_remote_create_uses_public_async_connection(): db.db_name = "example" db.serialize = lambda: "{}" - view = db.create_materialized_view( - "adults", - "people", - select=["name"], - where="age >= 18", - limit=10, - with_no_data=True, - auto_refresh_enabled=True, - auto_refresh_interval_seconds=0.5, - ) + if query is None: + view = db.create_materialized_view( + "adults", + "people", + select=["name"], + where="age >= 18", + limit=10, + with_no_data=True, + auto_refresh_enabled=True, + auto_refresh_interval_seconds=0.5, + ) + assert calls == [ + ("adults", "people", None, ["name"], "age >= 18", 10, True, True, 0.5) + ] + else: + view = db.create_materialized_view("adults", query=query) + assert calls == [("adults", None, query, None, None, None, False, None, None)] assert view.name == "adults" - assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)] db.drop_materialized_view("adults", namespace_path=["analytics"]) assert calls[-1] == ("drop", "adults", ["analytics"]) @@ -790,3 +800,144 @@ def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False) assert view.table.count_rows() == 3 + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("namespace", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "query, expected", + [ + ( + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + [{"kind": "a", "n": 2}, {"kind": "b", "n": 1}], + ), + ( + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + [{"id": 1, "tag": "x"}, {"id": 1, "tag": "y"}, {"id": 3, "tag": "z"}], + ), + ], +) +async def test_query_defined_materialized_view( + tmp_path, sync, namespace, background, query, expected +): + if namespace: + connect = lancedb.connect_namespace if sync else lancedb.connect_namespace_async + db = connect("dir", {"root": str(tmp_path)}, storage_options=STABLE_ROW_IDS) + elif sync: + db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS) + else: + db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) + rows = [ + {"id": 1, "kind": "a", "tags": ["x", "y"]}, + {"id": 2, "kind": "a", "tags": []}, + {"id": 3, "kind": "b", "tags": ["z"]}, + ] + if sync: + db.create_table("events", rows, storage_options=STABLE_ROW_IDS) + if background: + db.create_materialized_view_async("result", query=query).wait() + view = db.open_materialized_view("result") + else: + view = db.create_materialized_view("result", query=query) + actual = view.table.to_arrow().to_pylist() + assert view.definition.query == query + view.refresh() + refreshed = view.table.to_arrow().to_pylist() + else: + await db.create_table("events", rows, storage_options=STABLE_ROW_IDS) + if background: + job = await db.create_materialized_view_async("result", query=query) + await job.wait() + view = await db.open_materialized_view("result") + else: + view = await db.create_materialized_view("result", query=query) + actual = (await view.table.to_arrow()).to_pylist() + assert (await view.definition()).query == query + await view.refresh() + refreshed = (await view.table.to_arrow()).to_pylist() + assert sorted(actual, key=str) == sorted(expected, key=str) + assert sorted(refreshed, key=str) == sorted(expected, key=str) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "clauses", + [{"source": "people"}, {"select": []}, {"select": {}}, {"where": ""}, {"limit": 0}], +) +async def test_query_rejects_source_clauses_before_submission( + sync, background, clauses +): + connect = lancedb.connect if sync else lancedb.connect_async + db = connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1") + if not sync: + db = await db + create = ( + db.create_materialized_view_async if background else db.create_materialized_view + ) + with pytest.raises(ValueError, match="query cannot be combined"): + if sync: + create("invalid", query="SELECT * FROM people", **clauses) + else: + await create("invalid", query="SELECT * FROM people", **clauses) + with pytest.raises(ValueError, match="either source or query"): + if sync: + create("missing") + else: + await create("missing") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize( + "query", + [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ], +) +async def test_remote_create_forwards_defining_query(sync, query): + native = CapturingCreateConnection() + db = AsyncConnection(native) + if sync: + remote = RemoteDBConnection.__new__(RemoteDBConnection) + remote._conn = db + job = remote.create_materialized_view_async("result", query=query) + job.wait() + else: + job = await db.create_materialized_view_async("result", query=query) + await job.wait() + assert native.calls[0][0:2] == ("result", None) + assert native.calls[0][2]["query"] == query + + +@pytest.mark.experimental_functions +@pytest.mark.parametrize("background", [False, True]) +def test_query_with_no_data_and_invalid_query(tmp_path, background): + db = make_db(tmp_path) + query = "SELECT name FROM people WHERE age >= 18" + if background: + db.create_materialized_view_async( + "adults", query=query, with_no_data=True + ).wait() + view = db.open_materialized_view("adults") + else: + view = db.create_materialized_view("adults", query=query, with_no_data=True) + assert view.table.count_rows() == 0 + view.refresh() + assert view.table.count_rows() == 2 + create = ( + db.create_materialized_view_async if background else db.create_materialized_view + ) + error = JobFailedError if background else ValueError + with pytest.raises(error, match="unsupported clause"): + result = create("invalid", query="SELECT * FROM people ORDER BY age") + if background: + result.wait() + assert "invalid" not in db.table_names() diff --git a/python/src/connection.rs b/python/src/connection.rs index 2bf01a6f7..a32c00be1 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -26,6 +26,7 @@ use lancedb::{ database::{CreateTableMode, Database, ReadConsistency}, function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, + materialized_view::CreateMaterializedViewBuilder, }; use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, @@ -34,6 +35,27 @@ use pyo3::{ types::{PyAnyMethods, PyDict, PyDictMethods, PyList}, }; +fn materialized_view_builder( + connection: &LanceConnection, + name: String, + source: Option, + query: Option, + has_clauses: bool, +) -> PyResult { + match (source, query) { + (None, Some(query)) if !has_clauses => { + Ok(connection.create_materialized_view_from_query(name, query)) + } + (Some(source), None) => Ok(connection.create_materialized_view(name, source)), + (None, None) => Err(PyValueError::new_err( + "either source or query must be provided", + )), + _ => Err(PyValueError::new_err( + "query cannot be combined with source, select, where or limit", + )), + } +} + #[pyclass] pub struct Connection { inner: Option, @@ -483,21 +505,29 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + query: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder; if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -520,21 +550,29 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + query: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder; if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index bd7fbb942..9920cd893 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1574,14 +1574,15 @@ async fn prepare_with( } /// Builds a materialized view. Created by -/// [`Connection::create_materialized_view`]. +/// [`Connection::create_materialized_view`] or +/// [`Connection::create_materialized_view_from_query`]. pub struct CreateMaterializedViewBuilder { connection: Connection, name: String, namespace: Vec, - source: String, + input: MaterializedViewInput, source_namespace: Vec, - projections: Vec<(String, String)>, + projections: Option>, filter: Option, limit: Option, with_no_data: bool, @@ -1589,6 +1590,11 @@ pub struct CreateMaterializedViewBuilder { auto_refresh_interval_seconds: Option, } +enum MaterializedViewInput { + Source(String), + Query(String), +} + fn source_sql_identifier( namespace_path: &[String], source: &str, @@ -1609,14 +1615,14 @@ fn source_sql_identifier( } impl CreateMaterializedViewBuilder { - pub(crate) fn new(connection: Connection, name: String, source: String) -> Self { + fn new(connection: Connection, name: String, input: MaterializedViewInput) -> Self { Self { connection, name, namespace: Vec::new(), - source, + input, source_namespace: Vec::new(), - projections: Vec::new(), + projections: None, filter: None, limit: None, with_no_data: false, @@ -1644,10 +1650,12 @@ impl CreateMaterializedViewBuilder { mut self, columns: impl IntoIterator, impl Into)>, ) -> Self { - self.projections = columns - .into_iter() - .map(|(output, expression)| (output.into(), expression.into())) - .collect(); + self.projections = Some( + columns + .into_iter() + .map(|(output, expression)| (output.into(), expression.into())) + .collect(), + ); self } @@ -1697,22 +1705,38 @@ impl CreateMaterializedViewBuilder { } fn query(&self) -> Result { + if let MaterializedViewInput::Query(query) = &self.input { + if !self.source_namespace.is_empty() + || self.projections.is_some() + || self.filter.is_some() + || self.limit.is_some() + { + return Err(Error::InvalidInput { + message: "a defining query cannot be combined with source_namespace, select, only_if or limit".into(), + }); + } + return Ok(query.clone()); + } + let MaterializedViewInput::Source(source) = &self.input else { + unreachable!() + }; fn quote(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) } - let projection = if self.projections.is_empty() { - "*".to_string() - } else { - self.projections - .iter() - .map(|(output, expression)| format!("{expression} AS {}", quote(output))) - .collect::>() - .join(", ") - }; + let projection = + if let Some(projections) = self.projections.as_ref().filter(|p| !p.is_empty()) { + projections + .iter() + .map(|(output, expression)| format!("{expression} AS {}", quote(output))) + .collect::>() + .join(", ") + } else { + "*".to_string() + }; let source = source_sql_identifier( &self.source_namespace, - &self.source, + source, self.connection.uri().starts_with("db://"), ); let mut query = format!("SELECT {projection} FROM {source}"); @@ -1775,19 +1799,33 @@ impl CreateMaterializedViewBuilder { .to_string(), }); } - let source = self - .connection - .open_table(&self.source) - .namespace(self.source_namespace.clone()) - .execute() - .await?; - let prepared = prepare_declaration( - &source, - (!self.projections.is_empty()).then_some(self.projections.as_slice()), - self.filter.as_deref(), - self.limit, - ) - .await?; + let prepared = match &self.input { + MaterializedViewInput::Source(name) => { + let source = self + .connection + .open_table(name) + .namespace(self.source_namespace.clone()) + .execute() + .await?; + prepare_declaration( + &source, + self.projections.as_deref().filter(|p| !p.is_empty()), + self.filter.as_deref(), + self.limit, + ) + .await? + } + MaterializedViewInput::Query(_) => { + let definition = MaterializedViewDefinition::from_sql(&self.query()?)?; + let source = self + .connection + .open_table(&definition.source_table) + .namespace(definition.source_namespace.clone()) + .execute() + .await?; + prepare_definition(&source, definition).await? + } + }; let view = prepared.create_in(&self.namespace, &self.name).await?; if !self.with_no_data { view.refresh().execute().await?; @@ -2067,7 +2105,41 @@ impl Connection { name: impl Into, source: impl Into, ) -> CreateMaterializedViewBuilder { - CreateMaterializedViewBuilder::new(self.clone(), name.into(), source.into()) + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Source(source.into()), + ) + } + + /// Define a materialized view using a complete SQL query. + /// + /// Embedded connections parse the query with + /// [`MaterializedViewDefinition::from_sql`]. Remote connections send the + /// query to the server, which determines the supported SQL syntax. + /// Put projections, predicates and limits in the query rather than using + /// the builder's source-specific methods. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn create(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let view = db.create_materialized_view_from_query( + /// "events_by_kind", + /// "SELECT kind, count(*) AS n FROM events GROUP BY kind", + /// ).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_materialized_view_from_query( + &self, + name: impl Into, + query: impl Into, + ) -> CreateMaterializedViewBuilder { + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Query(query.into()), + ) } /// Open the materialized view named `name`. @@ -2229,6 +2301,65 @@ mod tests { ); } + #[tokio::test] + async fn query_builder_rejects_source_clauses() { + let conn = connect("memory://").execute().await.unwrap(); + let builder = || conn.create_materialized_view_from_query("mv", "SELECT * FROM src"); + for invalid in [ + builder().select([("x", "x")]), + builder().select(Vec::<(String, String)>::new()), + builder().only_if("x > 0"), + builder().limit(0), + builder().source_namespace(vec!["ns".into()]), + ] { + assert!(matches!(invalid.query(), Err(Error::InvalidInput { .. }))); + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn create_from_query_supports_grouping_and_background_population() { + let conn = connect("memory://").execute().await.unwrap(); + conn.create_table( + "src", + record_batch!(("kind", Utf8, ["a", "a", "b"])).unwrap(), + ) + .execute() + .await + .unwrap(); + let query = "SELECT kind, count(*) AS n FROM src GROUP BY kind"; + let view = conn + .create_materialized_view_from_query("groups", query) + .with_no_data(true) + .execute() + .await + .unwrap(); + assert_eq!(view.definition_sql(), query); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + view.refresh().execute().await.unwrap(); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); + conn.create_materialized_view_from_query("background", query) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + conn.open_materialized_view("background") + .await + .unwrap() + .table() + .count_rows(None) + .await + .unwrap(), + 2 + ); + } + #[test] fn sql_definition_defaults_share_one_metadata_value() { let metadata = HashMap::from([( diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index eb994f7dd..d25c72830 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1137,6 +1137,61 @@ async fn catalog_connections_use_explicit_sql_endpoint_and_database_scope() { server.await.unwrap().unwrap(); } +#[tokio::test] +async fn remote_query_builder_sends_the_complete_query() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let incoming = futures::stream::try_unfold(listener, |listener| async { + let (socket, _) = listener.accept().await?; + Ok::<_, std::io::Error>(Some((socket, listener))) + }); + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(FlightServiceServer::new(service)) + .serve_with_incoming_shutdown(incoming, async { + let _ = shutdown_rx.await; + }), + ); + let connection = crate::connect("db://analytics") + .region("us-east-1") + .api_key("test-key") + .host_override("http://127.0.0.1:1") + .sql_host_override(&format!("grpc://{address}")) + .execute() + .await + .unwrap(); + for query in [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ] { + connection + .create_materialized_view_from_query("result", query) + .auto_refresh_enabled(false) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + statements.lock().unwrap().last().unwrap(), + &format!( + "CREATE MATERIALIZED VIEW \"result\" WITH (auto_refresh_enabled = false) AS {query}" + ) + ); + } + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + #[tokio::test] async fn remote_create_uses_sql_and_preserves_options_and_namespace() { for defer in [false, true] { From db098ba812ff9cf47e7c8ba5c1a2d58485b6d510 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 12:34:31 +0800 Subject: [PATCH 20/36] fix(ci): support Cargo 1.100 artifact layout in cleanup fixture (#5010) Cargo 1.100 moves intermediate compiler artifacts into per-unit build directories and emits `build_script_build` instead of `build-script-build`. The unlocked-build fixture currently fails on its old rlib path before the SDK build starts, even though the library survives cleanup. Discover compiler inputs recursively and accept both build-script names while preserving the library, generated-input, ordinary-executable, discarded-test, linker-failure and outside-target assertions. The standalone fixture reproduces the failure before this change and passes afterward on Rust/Cargo 1.100.0; it also passes on 1.97.0. Fault injection confirms missing libraries and other retained inputs still fail their assertions. Production cleanup and normal workflow coverage are unchanged. --- ci/tests/test_build_no_lock.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ci/tests/test_build_no_lock.py b/ci/tests/test_build_no_lock.py index 634e8d333..f760d2bfc 100644 --- a/ci/tests/test_build_no_lock.py +++ b/ci/tests/test_build_no_lock.py @@ -88,9 +88,11 @@ class BuildNoLockTest(unittest.TestCase): self.assertTrue((target / "fixture_cli").is_file()) # Cargo guarantees this binary for test execution, not compile-time reads. subprocess.run([str(target / "fixture_cli")], check=True) - self.assertTrue(list((target / "deps").glob("libartifact_fixture*.rlib"))) - self.assertTrue(list((target / "build").glob("*/build-script-build"))) - self.assertTrue(list((target / "build").glob("*/out/generated.rs"))) + # Cargo 1.100 nests compiler inputs in per-unit build directories and + # names the build-script executable build_script_build. + self.assertTrue(list(target.rglob("libartifact_fixture*.rlib"))) + self.assertTrue(list((target / "build").rglob("build[-_]script[-_]build"))) + self.assertTrue(list((target / "build").rglob("out/generated.rs"))) def test_link_failure_preserves_cargo_status_and_diagnostic(self): with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp: From bab22a3fbd0f120b6d9e23cd4f3ee37621bb9bb5 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 00:21:58 -0800 Subject: [PATCH 21/36] feat(python): bundle Function package resources (#4987) A package shipped through `code=` currently loses its non-Python files. This breaks vendored packages that read JSON configuration, manifests, prompts, or binary resources after deployment. Include regular package resources in a separate base64-encoded `python_bundle.resources` map, preserving exact bytes and relative paths. Both source and resources contribute to the artifact digest. UTF-8 Python source bytes retain their original line endings as well, so manifests that hash vendor code continue to match. For example, `@function(code=[my_package])` can use `importlib.resources.files("my_package").joinpath("models.json").read_text()` on the worker. Hidden files and caches are excluded; symlinks and unsafe paths warn instead of following files outside the package. Source-only bundles retain their existing wire form. Resource bundles require matching server support. Adds an isolated-import regression with a vendored subpackage, JSON metadata, binary data, SHA256 verification, preserved CRLF bytes, and resource-only version changes. Local builds and tests are disabled by request. Ruff formatting and linting run locally; CI runs the tests. --- docs/src/python/python.md | 12 ++ docs/web/management/function.mdx | 21 ++- python/python/lancedb/functions.py | 92 ++++++++------ .../python/tests/test_function_packaging.py | 120 ++++++++++++++++-- 4 files changed, 187 insertions(+), 58 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 4ce325b2f..36f47c8f0 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1420,3 +1420,15 @@ name; omitting it allows matching reads of any revision. Prefixes must be concre paths without wildcards or traversal. This integration does not make Hugging Face a writable database location for `ATTACH DATABASE`. Dataset SQL sources select a matching integration automatically, with no integration argument in the query. + + +### Function package resources + +`@function(code=[my_package])` includes the package’s Python modules and data +files, including vendored subpackages. Resource paths and bytes are preserved, +so `importlib.resources` and package integrity checks work after deployment. +Changing a resource changes the Function artifact digest. This requires a server +that accepts `python_bundle.resources`. + +Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or +`conda=` for platform-specific dependencies and `models=` for large model snapshots. diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index bebbe1169..04c146bb1 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -499,13 +499,20 @@ def caption(jpeg: bytes) -> str: Each module in `code` is captured and shipped the same way the function -itself is: as source, snapshotted at registration. Only `.py` source files are -included; package data such as JSON, YAML, prompt, or tokenizer files is not -copied. `@function` warns before registration when it skips such files from a -package in `code`, naming the affected paths. To use a package that includes -the required resources, install it with `pip=` or `conda=` and remove that -package from `code`; otherwise the Python-only copied package shadows the -installed distribution. +itself is: as source, snapshotted at registration. Packages also include regular +data files such as JSON, YAML, prompts, and tokenizer files, including resources +inside vendored subpackages. Resource paths and bytes are preserved for +`importlib.resources` and package integrity checks. Changing a resource changes +the Function artifact's identity. Caches, hidden paths, symlinks, and unsafe +paths are excluded. + +Package resources require matching SDK and server support. Upgrade query nodes +and Function image-building workers before registering resource bundles; older +servers reject them. Older SDKs ship only Python source and warn when excluding +package data. On deployments without resource-bundle support, install the +package with `pip=` or `conda=` and omit it from `code` so the copied package does +not shadow the installed distribution. Use environment dependencies for +platform-specific packages and `models=` for large model snapshots. ## Drop it {#drop} diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 92be658a8..f04d3d481 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -22,6 +22,7 @@ import symtable import json import linecache import math +import os import re import sys import textwrap @@ -29,6 +30,7 @@ import types import warnings from collections.abc import Mapping, Sequence from datetime import date, datetime +from pathlib import Path from typing import ( Annotated, Any, @@ -2104,18 +2106,12 @@ class _SourcePackager: self._require_importable(node.module) -def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]: - """The Python source files of the modules and packages in ``code=``, - keyed by their path on the Function's import path. - - Package resources are not part of the source artifact. Warn about files - and excluded directories that the walk leaves behind instead of silently - producing a Function that will fail later on the worker. - """ - import os - from pathlib import Path - +def _code_files( + modules: Sequence[Any], +) -> tuple[dict[str, str], dict[str, str], frozenset[str]]: + """Source and byte-preserving package resources on the Function import path.""" files: dict[str, str] = {} + resources: dict[str, str] = {} names: set[str] = set() for module in modules: if not isinstance(module, types.ModuleType): @@ -2149,35 +2145,50 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]] sources = [] skipped = set() for directory, subdirectories, filenames in os.walk(root): - # Only importable modules travel: data files, caches, and - # directories that are not identifiers cannot be imported. kept = [] for child in sorted(subdirectories): - if child == "__pycache__": + path = Path(directory) / child + if child == "__pycache__" or child.startswith("."): continue - if _SOURCE_PATH_COMPONENT.fullmatch(child): + if not path.is_symlink() and re.fullmatch( + r"[A-Za-z0-9_][A-Za-z0-9_.-]*", child + ): kept.append(child) else: - relative = (Path(directory) / child).relative_to(root) + relative = path.relative_to(root) skipped.add(f"{name}/{relative.as_posix()}/") subdirectories[:] = kept for filename in sorted(filenames): + path = Path(directory) / filename stem, suffix = os.path.splitext(filename) - if suffix in {".pyc", ".pyo"}: + if suffix in {".pyc", ".pyo"} or filename.startswith("."): continue - if suffix == ".py" and _SOURCE_PATH_COMPONENT.fullmatch(stem): - sources.append(Path(directory) / filename) + relative = path.relative_to(root) + key = f"{name}/{relative.as_posix()}" + if ( + path.is_symlink() + or not path.is_file() + or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", filename) + ): + skipped.add(key) + elif suffix == ".py": + if all( + _SOURCE_PATH_COMPONENT.fullmatch(part) + for part in relative.with_suffix("").parts + ): + sources.append(path) + else: + skipped.add(key) else: - relative = (Path(directory) / filename).relative_to(root) - skipped.add(f"{name}/{relative.as_posix()}") + resources[key] = base64.b64encode(path.read_bytes()).decode( + "ascii" + ) if skipped: - skipped_paths = ", ".join(sorted(skipped)) warnings.warn( - f"code= ships Python .py modules only; package {name!r} " - f"will not include: {skipped_paths}. Install a package that " - "includes the required resources with pip= or conda=, and " - f"remove {name!r} from code= so the copied package cannot " - "shadow the installed distribution.", + "code= cannot ship these package paths: " + f"{', '.join(sorted(skipped))}. " + "Use regular files with safe relative names and importable " + "Python module names.", UserWarning, ) for path in sources: @@ -2188,12 +2199,12 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]] if not file or not file.endswith(".py"): raise ValueError(f"code= ships Python source; module {name!r} has none") files[f"{name}.py"] = _source_text(Path(file)) - return files, frozenset(names) + return files, resources, frozenset(names) def _source_text(path) -> str: try: - return path.read_text(encoding="utf-8") + return path.read_bytes().decode("utf-8") except UnicodeDecodeError as error: raise ValueError(f"code= ships UTF-8 source; {path} is not UTF-8") from error @@ -2449,14 +2460,17 @@ class FunctionDefinition: UserWarning, stacklevel=3, ) - code_files, code_modules = _code_files(code) + code_files, code_resources, code_modules = _code_files(code) entry_source = _SourcePackager( code_modules, frozenset(_requirement_name(package) for package in packages) ).package(function, signature) if code_files: kind = _PYTHON_BUNDLE_ARTIFACT + bundle = {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}} + if code_resources: + bundle["resources"] = code_resources source = json.dumps( - {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}}, + bundle, ensure_ascii=False, sort_keys=True, separators=(",", ":"), @@ -2802,13 +2816,15 @@ def function( immutable Function version; per-refresh aggregate GPU budgets are selected through ``refresh_column`` instead of registration. code : sequence of module, optional - Top-level modules or packages whose importable ``.py`` files ship - with the Function and are importable by their own names. Package data - files are not copied. To use a package that includes required data - resources, install it with ``pip=`` or ``conda=`` and remove that - package from ``code=`` so the copied Python package cannot shadow the - installed distribution. ``@function`` warns when it skips files from a - package in ``code=``. + Top-level modules or packages shipped with the Function and importable + by their own names. Package resources, including binary data and + vendored subpackages, retain their relative paths and exact bytes. + Source and resource changes both create a new Function version. + Caches and hidden paths are excluded. Symlinks and unsafe paths are + skipped with a warning. Compiled dependencies must match the remote + runtime; use ``pip=`` or ``conda=`` for platform-specific distributions + and ``models=`` for large model snapshots. Resource bundles require + server support for the ``python_bundle.resources`` field. models : sequence of HuggingFaceModel, optional Immutable Hugging Face repository snapshots prepared in the worker node cache before user code starts. A Function may declare a diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 2e285aa33..fcefc9110 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -7,6 +7,7 @@ from __future__ import annotations import base64 import importlib +import hashlib import json import subprocess import sys @@ -628,6 +629,102 @@ def test_binding_passes_initialization_as_constants(): version(text=col("body"), model=object()) +def test_vendored_package_resources_survive_an_isolated_import( + tmp_path, helper_package +): + package = helper_package( + "fx_vendor", + { + "__init__.py": "from .vendor.model import predict", + "vendor/__init__.py": "", + "vendor/model.py": """ + import hashlib + import json + from importlib.resources import files + + def predict(value): + root = files("fx_vendor") + payload = root.joinpath("label-maps/payload.bin").read_bytes() + metadata = json.loads(root.joinpath("models.json").read_text()) + source = root.joinpath("vendor/model.py").read_bytes() + source_digest = hashlib.sha256(source).hexdigest() + assert source_digest == metadata["source_sha256"] + assert hashlib.sha256(payload).hexdigest() == metadata["sha256"] + return value + metadata["offset"] + """, + "models.json": "{}", + }, + ) + payload = b"\x00\xff\r\nvendored model data" + package_root = Path(package.__file__).parent + (package_root / "label-maps").mkdir() + (package_root / "label-maps/payload.bin").write_bytes(payload) + module_path = package_root / "vendor/model.py" + module_bytes = ( + module_path.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n") + ) + module_path.write_bytes(module_bytes) + (package_root / "models.json").write_bytes( + json.dumps( + { + "sha256": hashlib.sha256(payload).hexdigest(), + "source_sha256": hashlib.sha256(module_bytes).hexdigest(), + "offset": 7, + } + ).encode() + + b"\r\n" + ) + + entry = helper_package( + "fx_vendor_entry", + { + "__init__.py": """ + import fx_vendor + from lancedb import function + + @function(code=[fx_vendor]) + def vendored(value: int) -> int: + return fx_vendor.predict(value) + """ + }, + ) + vendored = entry.vendored + + first_digest = vendored.registration_request.artifact.digest + bundle = json.loads(artifact(vendored)) + isolated = tmp_path / "isolated" + isolated.mkdir() + for name, content in bundle["files"].items(): + target = isolated / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content.encode("utf-8")) + for name, content in bundle["resources"].items(): + target = isolated / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(base64.b64decode(content)) + assert (isolated / "fx_vendor/models.json").read_bytes().endswith(b"\r\n") + result = subprocess.run( + [ + sys.executable, + "-I", + "-c", + "import sys; sys.path.insert(0, sys.argv[1]); " + "from user_function import vendored; assert vendored(3) == 10", + str(isolated), + ], + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr + (package_root / "models.json").write_text('{"offset": 8}') + assert ( + function(code=[package])( + vendored._function + ).registration_request.artifact.digest + != first_digest + ) + + def test_code_packages_ship_as_a_bundle_and_version_with_their_source( tmp_path, helper_package ): @@ -672,14 +769,13 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source( first = define() assert len(caught) == 1 warning = str(caught[0].message) - assert "fx_helpers/fixtures/data.json" in warning + assert "fx_helpers/fixtures/data.json" not in warning assert "fx_helpers/not-a-module.py" in warning - assert warning.index("fx_helpers/fixtures/data.json") < warning.index( - "fx_helpers/not-a-module.py" - ) - assert "remove 'fx_helpers' from code=" in warning - assert "pip=" in warning - assert "conda=" in warning + + assert "safe relative names" in warning + assert "importable Python module names" in warning + resources = json.loads(artifact(first))["resources"] + assert base64.b64decode(resources["fx_helpers/fixtures/data.json"]) == b"{}" assert "__pycache__" not in warning assert ".pyc" not in warning shipped = bundle_files(first) @@ -732,7 +828,7 @@ def test_code_package_cache_artifacts_do_not_warn(helper_package): ] -def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_package): +def test_code_package_resources_keep_nonidentifier_directories(helper_package): resources = helper_package( "fx_resources", { @@ -748,11 +844,9 @@ def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_packag def resource_boundary(value: int) -> int: return value - assert len(caught) == 1 - warning = str(caught[0].message) - assert "fx_resources/label-maps/" in warning - assert "remove 'fx_resources' from code=" in warning - assert "labels.json" not in warning + assert not caught + resources = json.loads(artifact(resource_boundary))["resources"] + assert base64.b64decode(resources["fx_resources/label-maps/labels.json"]) == b"{}" assert sorted(bundle_files(resource_boundary)) == [ "fx_resources/__init__.py", "user_function.py", From 927b24394866c835b7f7c3e27a3ee10845a9bf46 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Fri, 13 Nov 2026 09:38:50 -0800 Subject: [PATCH 22/36] fix(remote): preserve branches in cache prewarm requests (#5012) Calling `prewarm_data` or `prewarm_index` on a checked-out remote branch currently targets main. Both methods omit the branch context, which can warm the wrong snapshot, miss a branch-only index, or fail when the branch's minimum read version is ahead of main. This PR carries the table handle's branch through the existing request helpers. Main requests retain their existing format, with no public API changes. --- rust/lancedb/src/remote/table.rs | 71 ++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index dcceb4260..9b64ab56d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4548,10 +4548,10 @@ impl BaseTable for RemoteTable { async fn prewarm_index(&self, index_name: &str) -> Result<()> { let encoded_name = urlencoding::encode(index_name); - let request = self.client.post(&format!( + let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/index/{encoded_name}/prewarm/", self.identifier - )); + ))); let (request_id, response) = self.send(request, true).await?; if response.status() == StatusCode::NOT_FOUND { return Err(Error::IndexNotFound { @@ -4567,9 +4567,10 @@ impl BaseTable for RemoteTable { "/v1/table/{}/page_cache/prewarm/", self.identifier )); - let body = serde_json::json!({ + 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?; @@ -13018,6 +13019,70 @@ mod tests { .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(); + } + + #[tokio::test] + async fn test_prewarm_index_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/index/my_index/prewarm/" => { + let branch = request + .url() + .query_pairs() + .find(|(key, _)| key == "branch") + .map(|(_, value)| value.into_owned()); + assert_eq!(branch.as_deref(), Some("feature/dev")); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"prewarm-job"}"#) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let branch = table + .create_branch("feature/dev", Ref::Version(None, None)) + .await + .unwrap(); + branch.prewarm_index("my_index").await.unwrap(); + } + #[tokio::test] async fn test_drop_index() { let table = Table::new_with_handler("my_table", |request| { From 1765747f916d6eb7f3fbbcc105591e5835ea3684 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 11:02:07 -0800 Subject: [PATCH 23/36] fix: allow updates to Function input columns (#4985) Updating an input column on a table with a Function binding currently fails before the write, although the write path already preserves freshness for bindings whose inputs are unchanged. Allow input updates through the normal update builder while retaining supported binding-metadata validation and the guard against writing computed or internal assignment outputs directly. Lance rewrites only the matched rows. Their affected Function outputs keep their previous values and their changed input signatures make them eligible for refresh; unchanged fragments retain their freshness. Rewrites affecting only unrelated inputs keep the existing freshness-preservation path. For a table whose Function reads `title`, this update now succeeds while retaining the previous computed values until refresh: ```python table.update(where="id = 7", values={"title": "revised"}) ``` Server consumers need this crate update before remote input updates gain the behavior. Adds regressions for a one-row input update, retained output values, freshness scope, independent binding preservation, and atomic rejection of mixed input/output writes. Local builds and tests are disabled by request; CI runs the regressions. --- rust/lancedb/src/table/computed_columns.rs | 54 ++++++++- rust/lancedb/src/table/freshness.rs | 122 +++++++++++++++++++++ rust/lancedb/src/table/update.rs | 33 +++--- 3 files changed, 192 insertions(+), 17 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index d09a790a3..64e90b246 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -1757,10 +1757,20 @@ pub(crate) fn ensure_not_written<'a>( schema: &ArrowSchema, written: impl IntoIterator, ) -> Result<()> { - let declared: Vec = computed_columns(schema) + ensure_supported_function_metadata(schema)?; + let mut declared: Vec = computed_columns(schema) .into_iter() .map(|declaration| declaration.name) .collect(); + declared.extend( + function_bindings(schema)? + .into_iter() + .filter_map(|binding| { + binding + .assignment() + .map(|assignment| assignment.output_name.clone()) + }), + ); for name in written { if declared.iter().any(|declared| *declared == root(name)) { return Err(Error::InvalidInput { @@ -2532,10 +2542,15 @@ pub(crate) mod test_support { )]) .await .unwrap(); - let inputs = ["title".to_string(), "body".to_string()]; + let schema = dataset.schema(); let outputs = bindings .iter() .flat_map(|binding| { + let inputs = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); let assignment = binding.assignment().map(|assignment| { ( assignment.output_name.clone(), @@ -2547,9 +2562,9 @@ pub(crate) mod test_support { .iter() .map(|output| (output.output_name.clone(), output.output_ordinal)) .chain(assignment) - .map(|(name, ordinal)| { + .map(move |(name, ordinal)| { ( - dataset.schema().field(&name).unwrap().id as u32, + schema.field(&name).unwrap().id as u32, function_computed_column_metadata( binding.binding_id(), ordinal, @@ -4144,6 +4159,37 @@ mod tests { ArrowSchema::new(fields) } + #[test] + fn input_writes_preserve_the_assignment_column_guard() { + let mut raw: Value = serde_json::to_value(test_support::text_features_binding("")).unwrap(); + raw["assignment"] = serde_json::json!({ + "output_name": "__function_assignment_fb_01K3TEXT", "output_field_id": -1, + }); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["outputs"][1]["nullable"] = Value::Bool(true); + raw["output_schema"]["fields"].as_array_mut().unwrap().push(serde_json::json!({ + "name": "__function_assignment_fb_01K3TEXT", "nullable": true, "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let schema = ArrowSchema::new_with_metadata( + valid_function_binding_schema(true, true, &binding) + .fields() + .to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.into(), + function_bindings_metadata(&[binding]).unwrap(), + )]), + ); + ensure_not_written(&schema, ["title", "body"]).unwrap(); + for output in [ + "search_text", + "search_token_count", + "__function_assignment_fb_01K3TEXT", + ] { + assert!(ensure_not_written(&schema, [output]).is_err(), "{output}"); + } + } + #[test] fn test_non_nullable_function_inputs_can_bind_to_nullable_parameters() { let binding = FunctionBinding::from_json(include_str!( diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 645653a46..563a2a4e5 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -2646,6 +2646,8 @@ mod tests { use lance_file::version::ConcreteFileVersion; use lance_table::format::overlay::{DataOverlayFile, OverlayCoverage}; + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + const COLUMN: &str = "doubled"; const EXPRESSION: &str = "value * 2"; @@ -3126,6 +3128,126 @@ mod tests { } } + #[tokio::test] + async fn input_update_dirties_only_the_updated_rows_and_retains_outputs() { + let table = fresh_function_table().await; + let result = table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + assert_eq!(result.rows_updated, 1); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for output in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, output).await; + let mut dirty_rows = 0; + for fragment in dataset.get_fragments() { + if stale.needs_recompute(fragment.id() as u32) { + let batch = fragment + .scan() + .project(&["title"]) + .unwrap() + .try_into_batch() + .await + .unwrap(); + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}"); + dirty_rows += batch.num_rows(); + } + } + assert_eq!(dirty_rows, 1, "{stale:?}"); + } + assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1); + } + + #[tokio::test] + async fn input_update_keeps_an_independent_function_binding_fresh() { + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, ["x", "y", "z", "w"]), + ("search_text", Utf8, ["a x", "b y", "c z", "d w"]), + ("search_token_count", Int64, [2, 2, 2, 2]), + ("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]), + ("search_token_count_other", Int64, [2, 2, 2, 2]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("independent_functions", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut other = serde_json::to_value(text_features_binding("_other")).unwrap(); + other["inputs"][1]["field_path"] = serde_json::json!("title"); + other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone(); + let bindings = [ + text_features_binding(""), + serde_json::from_value(other).unwrap(), + ]; + stamp_bindings(&table, &bindings).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + for binding in &bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let inputs = fields_for_paths(dataset.schema(), &paths).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + } + native.dataset.update(dataset); + table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .needs_recompute(2) + ); + let other = &bindings[1]; + let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap(); + for output in other.outputs() { + let stale = + staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs) + .await + .unwrap(); + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 55980c5ff..93e8a08ea 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -103,11 +103,6 @@ pub(crate) async fn execute_update( // 1. Snapshot the current dataset let dataset = table.dataset.get().await?; crate::materialized_view::ensure_not_a_view(&table.name, &dataset.schema().metadata, "update")?; - super::computed_columns::ensure_not_function_bound( - &arrow_schema::Schema::from(dataset.schema()), - "update", - update.columns.iter().map(|(name, _)| name.as_str()), - )?; super::computed_columns::ensure_not_written( &arrow_schema::Schema::from(dataset.schema()), update.columns.iter().map(|(name, _)| name.as_str()), @@ -473,26 +468,38 @@ mod tests { assert_eq!(0, tbl.count_rows(Some("i == 0".to_string())).await.unwrap()); } - /// A Function binding protects only the columns it reads or writes; any - /// other column updates as on a plain table. #[tokio::test] - async fn update_on_a_function_table_refuses_only_bound_columns() { + async fn update_allows_function_inputs_but_protects_outputs() { let table = crate::table::computed_columns::test_support::bound_table().await; - let result = table.update().column("spare", "7").execute().await.unwrap(); + let result = table + .update() + .column("title", "'changed'") + .execute() + .await + .unwrap(); assert_eq!(result.rows_updated, 1); - for column in ["title", "search_text"] { + assert_eq!( + table + .count_rows(Some("title = 'changed' AND search_text = 'a b'".into())) + .await + .unwrap(), + 1 + ); + for column in ["search_text", "search_token_count"] { + let version = table.version().await.unwrap(); let err = table .update() - .column(column, "'x'") + .column("title", "'must not commit'") + .column(column, "NULL") .execute() .await .unwrap_err(); assert!( matches!(&err, crate::Error::InvalidInput { message } - if message.contains(&format!("update of '{column}'")) - && message.contains("a Function binding reads or writes it")), + if message.contains("is computed") && message.contains("cannot be written directly")), "{column}: {err:?}" ); + assert_eq!(table.version().await.unwrap(), version); } } } From 3a980054a19dc51f53979a04142468f57478d156 Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:24:55 -0800 Subject: [PATCH 24/36] docs: standardize Realtime Engine naming (#4969) The Enterprise feature name was inconsistently written as "Real Time Engine" and "real time engine". Standardize it to **Realtime Engine** in eight website guides, including page and sidebar titles, descriptions, prose, link labels, cards, and search keywords. The remaining MemWAL references describe Lance's open source format or literal API/job identifiers, including `memwal_compaction` and `memwal_catchup_`, and are preserved. Only `docs/web/*.mdx` pages change; SDK source, generated API reference, code examples, URL destinations, and section anchors are unchanged. Validation: - `git diff --check` passes. - Reviewed all MemWAL and Realtime Engine references under `docs/`. - Verified each changed file differs only by the intended naming substitutions and preserves code blocks, inline code, links, anchors, and MemWAL identifiers. - Confirmed no split or hyphenated "real time engine" names remain in website guides. - No snippets needed regeneration because code examples are unchanged. Vale and Mintlify are not installed locally, so their checks were not run locally. --- docs/web/basics/sdk.mdx | 2 +- docs/web/enterprise/distributed-real-time-read.mdx | 2 +- docs/web/enterprise/distributed-real-time-write.mdx | 4 ++-- docs/web/enterprise/realtime-engine-compaction.mdx | 12 ++++++------ docs/web/ingestion/realtime-write.mdx | 8 ++++---- docs/web/search/realtime-read.mdx | 8 ++++---- docs/web/sql/ddl/table.mdx | 2 +- docs/web/tables/realtime-engine.mdx | 10 +++++----- 8 files changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index 2ff1a4ba7..0274c039a 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -53,7 +53,7 @@ without a LanceDB SDK. For SQL queries, connect through LanceDB's Java client builds on this Lance Namespace Java core: table creation, listing and most other catalog operations go through the generated `LanceNamespace` interface talking to Enterprise's Namespace endpoint. -The [real time engine](/tables/realtime-engine) is the one area with its own, +The [Realtime Engine](/tables/realtime-engine) is the one area with its own, LanceDB-specific Java client on top, since RTE's LSM write path is not part of the Lance Namespace Client SDK Specification. diff --git a/docs/web/enterprise/distributed-real-time-read.mdx b/docs/web/enterprise/distributed-real-time-read.mdx index 1b6a582c4..7442474ec 100644 --- a/docs/web/enterprise/distributed-real-time-read.mdx +++ b/docs/web/enterprise/distributed-real-time-read.mdx @@ -1,7 +1,7 @@ --- title: "Distributed RTE Read" sidebarTitle: "Distributed RTE Read" -description: "How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine." +description: "How a query combines the Realtime Engine's fresh tier with the ordinary distributed query-serving path, machine to machine." icon: "network-wired" availability: embedded: unavailable diff --git a/docs/web/enterprise/distributed-real-time-write.mdx b/docs/web/enterprise/distributed-real-time-write.mdx index ac91e2d0d..e75497360 100644 --- a/docs/web/enterprise/distributed-real-time-write.mdx +++ b/docs/web/enterprise/distributed-real-time-write.mdx @@ -3,7 +3,7 @@ title: "Distributed RTE Write" sidebarTitle: "Distributed RTE Write" description: "How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it." icon: "bolt" -keywords: ["rte", "real time engine", "shard", "sharding", "horizontal scaling", "write throughput"] +keywords: ["rte", "realtime engine", "shard", "sharding", "horizontal scaling", "write throughput"] availability: embedded: unavailable enterprise: available @@ -128,7 +128,7 @@ throughput than this provides. Enable RTE and write to a table; the same call on Embedded or Enterprise. - + MemWAL, shards, memtables and SSTables -- the shared architecture. diff --git a/docs/web/enterprise/realtime-engine-compaction.mdx b/docs/web/enterprise/realtime-engine-compaction.mdx index e04429ab8..fb1a68481 100644 --- a/docs/web/enterprise/realtime-engine-compaction.mdx +++ b/docs/web/enterprise/realtime-engine-compaction.mdx @@ -1,7 +1,7 @@ --- -title: "Real Time Engine compaction" +title: "Realtime Engine compaction" sidebarTitle: "RTE Compaction" -description: "How Enterprise automatically folds a Real Time Engine shard's SSTables into the base table and catches its indexes up." +description: "How Enterprise automatically folds a Realtime Engine shard's SSTables into the base table and catches its indexes up." icon: "compress" availability: embedded: unavailable @@ -11,7 +11,7 @@ availability: [Distributed Compaction](/enterprise/distributed-compaction) merges small base-table fragments and reclaims deleted rows -- the same operation [Compaction](/maintenance/compaction) describes for LanceDB Embedded. A -table with the [real time engine](/tables/realtime-engine) enabled has a +table with the [Realtime Engine](/tables/realtime-engine) enabled has a second, unrelated compaction: folding a shard's accumulated SSTables into the base table and catching the base table's indexes up over the rows that just landed. This produces two job types, `memwal_compaction` and @@ -176,9 +176,9 @@ manifest update in step 6 is the single point where a row's SSTable copy stops being listed, and it only commits after `merge_insert` has already written that row into the base table. -A table queried *without* the real time engine's live path only sees data +A table queried *without* the Realtime Engine's live path only sees data once it has been folded into the base table, so its staleness bound tracks -whichever trigger fires -- wider either way than the real time engine's +whichever trigger fires -- wider either way than the Realtime Engine's own millisecond-scale freshness. A shard under steady write pressure compacts on the count or bytes trigger, within `WAL_COMPACTION_INTERVAL_SECS` plus the compaction job's own runtime. A shard that never gathers enough @@ -197,7 +197,7 @@ for what a live RTE read sees instead. ## What to read next {#next} - + The MemWAL format, shards, and WAL nodes this page assumes. diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx index 5b61e67bc..21b6eb2fa 100644 --- a/docs/web/ingestion/realtime-write.mdx +++ b/docs/web/ingestion/realtime-write.mdx @@ -1,15 +1,15 @@ --- title: "RTE Write (Upsert)" sidebarTitle: "RTE Write (Upsert)" -description: "Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." +description: "Enable the Realtime Engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] +keywords: ["rte", "realtime engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] availability: embedded: available enterprise: available --- -The [real time engine](/tables/realtime-engine) puts an LSM-style write tier in +The [Realtime Engine](/tables/realtime-engine) puts an LSM-style write tier in front of a table, turning many small writes into a few large commits. This page covers enabling it and writing to a table; for querying an RTE table, see [RTE reads](/search/realtime-read). @@ -239,6 +239,6 @@ for the numbers. - [RTE reads](/search/realtime-read) — query an RTE table - [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales this -- [How the real time engine works](/tables/realtime-engine#memwal-format) +- [How the Realtime Engine works](/tables/realtime-engine#memwal-format) - [Merge insert](/ingestion/merge-insert) - [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx index 19c5bc2ab..d87d98c81 100644 --- a/docs/web/search/realtime-read.mdx +++ b/docs/web/search/realtime-read.mdx @@ -1,15 +1,15 @@ --- title: "RTE reads" sidebarTitle: "RTE Read" -description: "Query a table with the real time engine enabled and get writes back within milliseconds of being written, merged transparently with the base table." +description: "Query a table with the Realtime Engine enabled and get writes back within milliseconds of being written, merged transparently with the base table." icon: "magnifying-glass" -keywords: ["rte", "real time engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] +keywords: ["rte", "realtime engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] availability: embedded: available enterprise: available --- -A table with the [real time engine](/tables/realtime-engine) enabled queries +A table with the [Realtime Engine](/tables/realtime-engine) enabled queries the same way as any other table — nothing about `search`, filtering, or SQL changes. This page covers what you get back; for enabling RTE and writing to a table, see [RTE writes](/ingestion/realtime-write). For how Enterprise @@ -79,6 +79,6 @@ available. - [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table - [Distributed RTE Read](/enterprise/distributed-real-time-read) — combining results across machines in Enterprise -- [How the real time engine works](/tables/realtime-engine#memwal-format) +- [How the Realtime Engine works](/tables/realtime-engine#memwal-format) - [Hybrid search](/search/hybrid-search) - [Vector search](/search/vector-search) diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index 6e751667e..ab0ff64bf 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -176,7 +176,7 @@ ALTER TABLE t UNSET RTE ``` -The [real time engine](/tables/realtime-engine) puts a write-ahead log in front +The [Realtime Engine](/tables/realtime-engine) puts a write-ahead log in front of the table, making small frequent writes cheap by batching them out of the commit path. `sharding` and `buckets` spread the log so concurrent writers do not contend on one place; `bucket` sharding names its `column`, which must be diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx index 5c6983cc5..09e933894 100644 --- a/docs/web/tables/realtime-engine.mdx +++ b/docs/web/tables/realtime-engine.mdx @@ -1,21 +1,21 @@ --- -title: "Real Time engine (RTE)" -sidebarTitle: "Real Time Engine (RTE)" +title: "Realtime Engine (RTE)" +sidebarTitle: "Realtime Engine (RTE)" description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] +keywords: ["rte", "realtime engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] availability: embedded: available enterprise: available --- -## What is the real time engine? {#what-is-rte} +## What is the Realtime Engine? {#what-is-rte} Every write to a LanceDB table is normally a commit to the underlying Lance dataset. That is ideal for bulk loads, but a stream of small upserts becomes a stream of small commits, and each write is only visible once its commit lands. -The real time engine (RTE) puts an LSM-style write tier in front of the table. +The Realtime Engine (RTE) puts an LSM-style write tier in front of the table. It turns many small writes into a few large commits, and makes each write **searchable within milliseconds** of being acknowledged. It is enabled per table, and nothing about how you query that table changes. From 7d50d2d28f84559672d15f8d91e06bf55cc2fa3d Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 13 Nov 2026 11:44:40 -0800 Subject: [PATCH 25/36] chore(deps): bump Rust deps flagged by security scans (#5035) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Bumps the Rust dependencies flagged by Aikido that have a semver-compatible fix available. Supersedes #5009 (rustls in the docs lockfile is included here). Root `Cargo.lock`: | Crate | From | To | | --- | --- | --- | | mio | 1.2.0 | 1.2.5 | | smallvec | 1.15.1 | 1.16.5 | | thread_local | 1.1.9 | 1.1.10 | | tinyvec | 1.11.0 | 1.13.3 | | zerocopy / zerocopy-derive | 0.8.48 | 0.8.63 | | event-listener | 5.4.1 | 5.4.2 | | arrayvec | 0.7.6 | 0.7.8 | | wasm-bindgen (+ js-sys, web-sys) | 0.2.121 | 0.2.130 | | getrandom 0.4 | 0.4.2 | 0.4.3 (drops wasip3 → wasmparser 0.244) | | brotli | 3.5.0 | 9.1.1 (via `random_word` dev-dep 0.4.3 → 1.0.0) | `docs/web-tests/rs/Cargo.lock` gets the same crates plus rustls, hyper, h2, moka, bytes, crossbeam-epoch and anyhow. That crate is not a workspace member, so cargo refused to resolve it; it now has an empty `[workspace]` table. Still open, blocked upstream: quick-xml 0.41 (lance-io), rand 0.9 (datafusion/lance/candle), heapless 0.8 (rstar via geo), paste, unsafe-libyaml (rattler_conda_types, lindera), fast-float/smartstring (polars 0.39), number_prefix (needs hf-hub 1.0 migration), zstd 0.13 (arrow-ipc). ## Merge Risk **Door:** two-way. Lockfile patch/minor bumps and a dev-only dependency. **Blast Radius:** none expected; no source changes. The docs crate is not built in CI. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 282 +++++++------------------------- docs/web-tests/rs/Cargo.lock | 301 ++++++++--------------------------- docs/web-tests/rs/Cargo.toml | 4 + rust/lancedb/Cargo.toml | 2 +- 4 files changed, 127 insertions(+), 462 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index efe0338cd..22b0f1e6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,15 +63,15 @@ dependencies = [ [[package]] name = "alloc-no-stdlib" -version = "2.0.4" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" [[package]] name = "alloc-stdlib" -version = "0.2.2" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ "alloc-no-stdlib", ] @@ -221,9 +221,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" @@ -1474,9 +1474,9 @@ dependencies = [ [[package]] name = "brotli" -version = "3.5.0" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1485,9 +1485,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "2.5.1" +version = "6.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -2261,7 +2261,7 @@ checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" dependencies = [ "cpubits", "ctutils", - "getrandom 0.4.2", + "getrandom 0.4.3", "hybrid-array", "num-traits", "rand_core 0.10.1", @@ -2285,7 +2285,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "hybrid-array", "rand_core 0.10.1", ] @@ -3504,11 +3504,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -4248,17 +4247,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if 1.0.4", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -4939,12 +4936,6 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -5275,13 +5266,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if 1.0.4", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -6243,12 +6233,6 @@ dependencies = [ "spin 0.9.9", ] -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "lexical-core" version = "1.0.6" @@ -6704,9 +6688,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.0" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -8550,16 +8534,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.117", -] - [[package]] name = "primefield" version = "0.14.0" @@ -8870,7 +8844,7 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.1", "rand_pcg", @@ -8973,7 +8947,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -9061,15 +9035,13 @@ dependencies = [ [[package]] name = "random_word" -version = "0.4.3" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07eed67a16dde2cc3c7f65c072acd8d5b2e53d4aab95067c320db851c7651f29" +checksum = "5d9299243acac3cb4f35c9f78d5ad29c87e70cd916a70f293d8526e54049c340" dependencies = [ "ahash", "brotli", - "once_cell", - "paste", - "rand 0.8.6", + "rand 0.10.1", "unicase", ] @@ -10528,9 +10500,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] @@ -11014,7 +10986,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.2", + "getrandom 0.4.3", "once_cell", "rustix 1.1.4", "windows-sys 0.61.2", @@ -11113,9 +11085,9 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if 1.0.4", ] @@ -11183,18 +11155,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.11.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokenizers" @@ -11744,12 +11707,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "unicode_categories" version = "0.1.1" @@ -11836,7 +11793,7 @@ version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -11919,16 +11876,7 @@ version = "1.0.3+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] @@ -11942,12 +11890,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if 1.0.4", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -11955,19 +11902,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -11975,48 +11923,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -12043,23 +11969,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.11.1", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -12579,100 +12493,12 @@ version = "0.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.11.1", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "wkb" version = "0.9.2" @@ -12775,7 +12601,7 @@ dependencies = [ "countio", "futures", "futures-util", - "getrandom 0.4.2", + "getrandom 0.4.3", "heapify", "itertools 0.14.0", "lz4_flex 0.13.1", @@ -12912,18 +12738,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -12999,7 +12825,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e408c6cc4699dd017d53dc080cd51c2cea2b5354af57a1479bd265ed42911487" dependencies = [ "crc32fast", - "getrandom 0.4.2", + "getrandom 0.4.3", "indexmap 2.14.0", "libc", "memchr", diff --git a/docs/web-tests/rs/Cargo.lock b/docs/web-tests/rs/Cargo.lock index 6e288950e..85384c8af 100644 --- a/docs/web-tests/rs/Cargo.lock +++ b/docs/web-tests/rs/Cargo.lock @@ -87,9 +87,9 @@ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "ar_archive_writer" @@ -129,9 +129,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" @@ -683,9 +683,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cast" @@ -1019,9 +1019,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] @@ -1904,7 +1904,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1993,7 +1993,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2004,11 +2004,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -2289,17 +2288,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -2317,9 +2314,9 @@ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" [[package]] name = "h2" -version = "0.4.12" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2475,9 +2472,9 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" [[package]] name = "hyper" -version = "1.8.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -2490,7 +2487,6 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -2699,12 +2695,6 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -2808,7 +2798,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2876,7 +2866,7 @@ dependencies = [ "portable-atomic", "portable-atomic-util", "serde_core", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2917,11 +2907,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.83" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] @@ -3607,12 +3598,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "lexical-core" version = "1.0.6" @@ -3925,9 +3910,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", @@ -3936,9 +3921,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.12.11" +version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8261cd88c312e0004c1d51baad2980c66528dfdb2bee62003e643a4d8f86b077" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" dependencies = [ "async-lock", "crossbeam-channel", @@ -3949,7 +3934,6 @@ dependencies = [ "futures-util", "parking_lot", "portable-atomic", - "rustc_version", "smallvec", "tagptr", "uuid", @@ -4062,7 +4046,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4919,7 +4903,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "itertools 0.14.0", "log", "multimap", @@ -5020,7 +5004,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.3", "rand_pcg", @@ -5046,7 +5030,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.59.0", ] [[package]] @@ -5113,7 +5097,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -5520,14 +5504,14 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.11.0", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -5861,9 +5845,9 @@ checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "smartstring" @@ -5900,7 +5884,7 @@ version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.117", @@ -5912,7 +5896,7 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f103c50866b8743da9429b8a581d81a27c2d3a9c4ac7df8f8571c1dd7896eda" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.117", @@ -6247,7 +6231,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.2", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6301,9 +6285,9 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if", ] @@ -6371,18 +6355,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" @@ -6646,12 +6621,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -6700,7 +6669,7 @@ version = "1.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -6731,9 +6700,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -6750,26 +6719,16 @@ version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ - "wit-bindgen 0.46.0", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -6777,22 +6736,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.56" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836d9622d604feee9e5de25ac10e3ea5f2d65b41eac0d9ce72eb5deae707ce7c" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ - "cfg-if", "js-sys", - "once_cell", + "tokio", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6800,48 +6757,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.6", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -6855,23 +6790,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.10.0", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.83" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b32828d774c412041098d182a8b38b16ea816958e07cf40eec2bc080ae137ac" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -6909,7 +6832,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7254,94 +7177,6 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.10.0", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "writeable" version = "0.6.2" @@ -7388,18 +7223,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.31" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.31" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", diff --git a/docs/web-tests/rs/Cargo.toml b/docs/web-tests/rs/Cargo.toml index 8bc594c3c..1e1de2e45 100644 --- a/docs/web-tests/rs/Cargo.toml +++ b/docs/web-tests/rs/Cargo.toml @@ -1,3 +1,7 @@ +# Standalone crate pinned to a published lancedb release, not part of the root +# workspace. Without this, cargo commands here fail to resolve the workspace. +[workspace] + [package] name = "rs" version = "0.1.0" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 737c385c1..ef5da44c5 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -118,7 +118,7 @@ lance-testing = { workspace = true } # production remote feature so Python wheels do not resolve its Axum 0.7 stack. lance-namespace-impls = { workspace = true, features = ["rest-adapter"] } tempfile = { workspace = true } -random_word = { version = "0.4.3", features = ["en"] } +random_word = { version = "1.0.0", features = ["en"] } tokio = { workspace = true, features = ["io-util", "macros", "net", "test-util"] } uuid = { workspace = true } walkdir = "2" From b061c3627c46ec3d310cddb0aa45f022f8c4aad2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:35:52 -0800 Subject: [PATCH 26/36] feat(python): support exist_ok when creating views (#4984) Add `exist_ok=False` to synchronous and asynchronous Python view creation. Passing `True` sends `CREATE VIEW IF NOT EXISTS` and returns the existing view's stored query and schema unchanged; the default continues to fail on an existing name. ```python view = db.create_view("recent_orders", query, exist_ok=True) view = await async_db.create_view("recent_orders", query, exist_ok=True) ``` Requires a SQL server supporting `CREATE VIEW IF NOT EXISTS`. Rust gains an awaitable builder with `.exist_ok(true)`. Existing `.create_view(...).await` calls continue to work; callers requiring `Future` must convert the builder, and custom `Database` implementations must accept the new `exist_ok` argument. Includes Python round-trip coverage and Rust coverage for direct/deferred results and metadata preservation. --- docs/web/sql/ddl/view.mdx | 10 +++ python/python/lancedb/_lancedb.pyi | 7 ++- python/python/lancedb/db.py | 36 ++++++++--- python/python/lancedb/remote/db.py | 11 +++- python/python/tests/test_view_creation.py | 71 ++++++++++++++++++++++ python/src/connection.rs | 4 +- rust/lancedb/src/connection.rs | 24 +++++--- rust/lancedb/src/connection/create_view.rs | 62 +++++++++++++++++++ rust/lancedb/src/database.rs | 1 + rust/lancedb/src/remote/db.rs | 3 +- rust/lancedb/src/remote/sql/view.rs | 7 ++- rust/lancedb/src/remote/sql_test.rs | 28 ++++++++- 12 files changed, 239 insertions(+), 25 deletions(-) create mode 100644 python/python/tests/test_view_creation.py create mode 100644 rust/lancedb/src/connection/create_view.rs diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index e039fc43a..3d94292ab 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -23,6 +23,16 @@ catalog removal; physical cleanup can continue afterward. ## CREATE VIEW {#create} +{/* Draft for the view exist_ok release. + +`CREATE VIEW IF NOT EXISTS` creates a missing view and returns an existing +view's stored query and schema unchanged. Without `IF NOT EXISTS`, an existing +name is an error. In Python, use `db.create_view(name, query, exist_ok=True)`; +in Rust, use `db.create_view(name, query, &namespace).exist_ok(true).await?`. +Returning an existing view requires `SELECT` on that view. + +*/} + ```sql SQL icon="database" CREATE VIEW "recent_matches" AS diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5897ddd0c..56b644abb 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -253,7 +253,12 @@ class Connection(object): self, name: str, namespace_path: Optional[List[str]] = None ) -> Tuple[str, int, int]: ... async def create_view( - self, name: str, query: str, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ... async def describe_view( self, name: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 7d690abe3..020c79be0 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1273,7 +1273,12 @@ class DBConnection(EnforceOverrides): ) def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: """Create a view: a named query the database plans on every read. @@ -1281,9 +1286,10 @@ class DBConnection(EnforceOverrides): is refused now rather than at the first read. A view holds no rows, and its readers see its sources as they are at read time. - There is no replace: a name already taken is an error, and changing a - view is a drop followed by a create. LanceDB Embedded connections raise - ``NotImplementedError``. + A name already taken is an error unless ``exist_ok=True``, which returns + the existing view's stored query and schema without changing them. + Changing a view is a drop followed by a create. LanceDB Embedded + connections raise ``NotImplementedError``. >>> import lancedb >>> db = lancedb.connect("db://my_database") # doctest: +SKIP @@ -2592,10 +2598,17 @@ class LanceDBConnection(DBConnection): @override def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: return LOOP.run( - self._conn.create_view(name, query, namespace_path=namespace_path) + self._conn.create_view( + name, query, exist_ok=exist_ok, namespace_path=namespace_path + ) ) @override @@ -4107,7 +4120,12 @@ class AsyncConnection(object): ) async def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: """Create a view: a named query the database plans on every read. @@ -4115,7 +4133,9 @@ class AsyncConnection(object): [DBConnection.create_view][lancedb.DBConnection.create_view]. """ return _view_description( - await self._inner.create_view(name, query, list(namespace_path or [])) + await self._inner.create_view( + name, query, list(namespace_path or []), exist_ok=exist_ok + ) ) async def describe_view( diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index db3ab554c..ea9468331 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1197,10 +1197,17 @@ class RemoteDBConnection(DBConnection): @override def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: return LOOP.run( - self._conn.create_view(name, query, namespace_path=namespace_path) + self._conn.create_view( + name, query, exist_ok=exist_ok, namespace_path=namespace_path + ) ) @override diff --git a/python/python/tests/test_view_creation.py b/python/python/tests/test_view_creation.py new file mode 100644 index 000000000..410356da0 --- /dev/null +++ b/python/python/tests/test_view_creation.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "existing"), + [(None, False), (False, False), (True, False), (True, True)], +) +async def test_create_view_exist_ok_preserves_server_metadata( + asynchronous, exist_ok, existing +): + flight = pytest.importorskip("pyarrow.flight") + original_query = "SELECT 'original' AS original" + submitted_query = ( + "SELECT 'replacement' AS replacement" if existing else original_query + ) + schema = { + "fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}], + "metadata": { + "lancedb::view::default_db": "analytics", + "lancedb::view::default_namespace": "team", + }, + } + result = pa.table( + {"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]} + ) + + class ViewServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with ViewServer() as server: + connection_options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + if asynchronous: + db = await lancedb.connect_async("db://analytics", **connection_options) + view = await db.create_view( + "saved", submitted_query, namespace_path=["team"], **kwargs + ) + else: + db = lancedb.connect("db://analytics", **connection_options) + view = db.create_view( + "saved", submitted_query, namespace_path=["team"], **kwargs + ) + (request,) = server.requests + + prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW" + assert f'{prefix} "saved" AS {submitted_query}'.encode() in request + assert view.name == "saved" + assert view.namespace_path == ["team"] + assert view.default_namespace_path == ["team"] + assert view.query == original_query + assert view.schema.names == ["original"] diff --git a/python/src/connection.rs b/python/src/connection.rs index a32c00be1..ffa59fd02 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1158,18 +1158,20 @@ impl Connection { }) } - #[pyo3(signature = (name, query, namespace_path=None))] + #[pyo3(signature = (name, query, namespace_path=None, *, exist_ok=false))] pub fn create_view( self_: PyRef<'_, Self>, name: String, query: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { let view = inner .create_view(name, query, &namespace_path) + .exist_ok(exist_ok) .await .infer_error()?; view_description_to_py(view) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index cc398e32b..c7a058502 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -53,6 +53,9 @@ use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; mod create_secret; mod create_table; +mod create_view; + +pub use create_view::CreateViewBuilder; pub use create_secret::CreateSecretBuilder; @@ -976,9 +979,10 @@ impl Connection { /// refused now rather than at the first read. A view holds no rows, and /// its readers see its sources as they are at read time. /// - /// There is no replace: a name already taken is an error, and changing a - /// view is a drop followed by a create, each authorized against what it - /// actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. + /// A name already taken is an error unless [`CreateViewBuilder::exist_ok`] is + /// true, which returns the stored definition and schema without changing them. + /// Changing a view is a drop followed by a create, each authorized against what + /// it actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// # Example /// @@ -1011,16 +1015,18 @@ impl Connection { /// # Ok(()) /// # } /// ``` - pub async fn create_view( + pub fn create_view( &self, name: impl AsRef, query: impl AsRef, namespace_path: &[String], - ) -> Result { - validate_view_reference(name.as_ref(), namespace_path)?; - self.internal - .create_view(name.as_ref(), query.as_ref(), namespace_path) - .await + ) -> CreateViewBuilder { + CreateViewBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + query.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// What this database records about one view: its defining query and the diff --git a/rust/lancedb/src/connection/create_view.rs b/rust/lancedb/src/connection/create_view.rs new file mode 100644 index 000000000..bd80ca6e7 --- /dev/null +++ b/rust/lancedb/src/connection/create_view.rs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_view_reference; +use crate::view::ViewDescription; + +/// Configure creation of a view with [`super::Connection::create_view`]. +#[must_use] +pub struct CreateViewBuilder { + database: Arc, + name: String, + query: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateViewBuilder { + pub(super) fn new( + database: Arc, + name: String, + query: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + query, + namespace_path, + exist_ok: false, + } + } + + /// Return the existing view without changing its definition if it exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the view or return the existing view when `exist_ok` is true. + pub async fn execute(self) -> Result { + validate_view_reference(&self.name, &self.namespace_path)?; + self.database + .create_view(&self.name, &self.query, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateViewBuilder { + type Output = Result; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 23ed9fc3d..39e361a39 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -693,6 +693,7 @@ pub trait Database: _name: &str, _query: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result { view_ops_not_supported() } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 92523ec34..a05bb07b7 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1099,11 +1099,12 @@ impl Database for RemoteDatabase { name: &str, query: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .create_view(name, query, namespace_path) + .create_view(name, query, namespace_path, exist_ok) .await } async fn describe_view( diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index 0c2229684..513113187 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -99,13 +99,18 @@ impl SqlClient { name: &str, query: &str, namespace: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace)?; let namespace_path = namespace.to_vec(); + let if_not_exists = if exist_ok { " IF NOT EXISTS" } else { "" }; self.object_job( ExecuteQueryRequest { - query: format!("CREATE VIEW {} AS {query}", quote_identifier(name)), + query: format!( + "CREATE VIEW{if_not_exists} {} AS {query}", + quote_identifier(name) + ), default_namespace_path: namespace.to_vec(), parameters: None, }, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d25c72830..6a3f30390 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -24,6 +24,7 @@ use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; use crate::Connection; use crate::database::Database; +use crate::embeddings::MemoryRegistry; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::RemoteCatalogOptions; use crate::remote::client::HeaderProvider; @@ -3710,26 +3711,49 @@ async fn view_create_and_describe_return_metadata_through_sql() { ..Default::default() }; let statements = service.statements.clone(); + let headers = service.headers.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { panic!("unexpected REST request"); }) .with_sql_client(client); - let created = db + let connection = Connection::new(Arc::new(db), Arc::new(MemoryRegistry::new())); + let created = connection .create_view("adults", "SELECT name FROM people", &["team".into()]) .await .unwrap(); - let described = db.describe_view("adults", &["team".into()]).await.unwrap(); + let existing = connection + .create_view( + "adults", + "SELECT replacement FROM other_people", + &["team".into()], + ) + .exist_ok(true) + .await + .unwrap(); + let described = connection + .describe_view("adults", &["team".into()]) + .await + .unwrap(); assert_eq!(created, described); + assert_eq!(existing, described); assert_eq!(created.schema.fields()[0].name(), "name"); assert_eq!(created.default_namespace_path, ["team"]); assert_eq!( statements.lock().unwrap().as_slice(), [ "CREATE VIEW \"adults\" AS SELECT name FROM people", + "CREATE VIEW IF NOT EXISTS \"adults\" AS SELECT replacement FROM other_people", "DESCRIBE VIEW \"adults\"" ] ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); shutdown.send(()).unwrap(); } } From 2c3c30dbdf02a4dc9f725b00701b995954e228b1 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:35:54 -0800 Subject: [PATCH 27/36] feat(python): support exist_ok for Function creation (#4992) Adds `exist_ok=False` to Python Function creation and job submission. `exist_ok=True` sends `CREATE FUNCTION IF NOT EXISTS` and returns the stored immutable version, preserving its code, credentials and execution settings. The default retains the current version-creation behavior. ```python version = db.create_function(analyze_caption, exist_ok=True) ``` The option also exists on the Rust registration request and is kept out of the canonical Function definition payload. Includes sync/async/background protocol and stored-version coverage. Requires matching SQL server support. BREAKING CHANGE: Rust `FunctionRegistrationRequest` struct literals must initialize `exist_ok`; legacy serialized requests default to false. No local builds or tests were run, as requested. --- docs/web/management/function.mdx | 13 ++++ docs/web/sql/ddl/function.mdx | 9 +++ python/python/lancedb/_lancedb.pyi | 6 +- python/python/lancedb/db.py | 25 +++++++- python/python/lancedb/remote/db.py | 6 +- python/python/tests/test_function_creation.py | 63 +++++++++++++++++++ python/src/connection.rs | 6 +- rust/lancedb/src/function.rs | 7 +++ rust/lancedb/src/remote/sql/function.rs | 11 +++- rust/lancedb/src/remote/sql_test.rs | 20 +++++- 10 files changed, 155 insertions(+), 11 deletions(-) create mode 100644 python/python/tests/test_function_creation.py diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 04c146bb1..aae67ceb9 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -111,6 +111,19 @@ with `db.get_function(name, version=...)`. The version may be an integer or its string form. Omit `version` to resolve and return the latest currently visible revision. +{/* Draft for the function exist_ok release. + +Use `exist_ok=True` on `create_function` or `create_function_async` to return +the existing named version without changing its code, credentials or settings. +This requires a deployment that supports the option. The default retains the +current behavior of registering a new version. + +```python +version = db.create_function(embed, exist_ok=True) +``` + +*/} + The SQL command submits an internal `create_function` image-build job and waits for publication. The SDK returns the SQL query handle. Query handles diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 95c2d4d6e..55e2d6fe7 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -16,6 +16,15 @@ availability: ## CREATE FUNCTION {#create} +{/* Draft for the function exist_ok release. + +`CREATE FUNCTION IF NOT EXISTS` preserves an existing named Function version, +including its code, credentials and execution settings. In Python, pass +`exist_ok=True` to `create_function` or `create_function_async`. The default +retains the existing version-creation behavior. + +*/} + ```sql SQL icon="database" CREATE FUNCTION f(x int64) RETURNS int64 diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 56b644abb..44523fd42 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -188,7 +188,11 @@ class Connection(object): async def server_info(self) -> str: ... async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( - self, request_json: str, namespace_path: Optional[List[str]] = None + self, + request_json: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> Job: ... async def get_function( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 020c79be0..050b20727 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1004,10 +1004,14 @@ class DBConnection(EnforceOverrides): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. + ``exist_ok=True`` returns the existing named Function version unchanged. + By default, registration retains its existing version-creation behavior. + The server builds the OCI image and registers the completed artifact. This is the blocking counterpart of :meth:`create_function_async`. LanceDB Embedded connections raise ``NotImplementedError``. @@ -1040,7 +1044,10 @@ class DBConnection(EnforceOverrides): ``` """ return self.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ).wait() def create_function_async( @@ -1048,10 +1055,14 @@ class DBConnection(EnforceOverrides): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: """Submit a scalar Python function for building and registration. + ``exist_ok=True`` preserves an existing named version and its metadata. + The default retains the existing version-creation behavior. + The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. @@ -2396,11 +2407,15 @@ class LanceDBConnection(DBConnection): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ) ) return Job(job) @@ -3732,10 +3747,14 @@ class AsyncConnection(object): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[FunctionVersion]: """Submit a scalar Python function for building and registration. + ``exist_ok=True`` preserves an existing named version and its metadata. + The default retains the existing version-creation behavior. + The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. @@ -3749,7 +3768,7 @@ class AsyncConnection(object): raise TypeError("create_function_async requires a @function definition") request = definition.bind_secrets(secrets) inner = await self._inner.create_function_async( - request.to_canonical_json(), namespace_path + request.to_canonical_json(), namespace_path, exist_ok=exist_ok ) return _typed_job(inner, FunctionVersion.from_json) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ea9468331..870b85b1e 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -992,11 +992,15 @@ class RemoteDBConnection(DBConnection): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ) ) return Job(job) diff --git a/python/python/tests/test_function_creation.py b/python/python/tests/test_function_creation.py new file mode 100644 index 000000000..823dba7b9 --- /dev/null +++ b/python/python/tests/test_function_creation.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +import lancedb +from lancedb.functions import function + + +@pytest.mark.asyncio +@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"]) +@pytest.mark.parametrize("exist_ok", [None, False, True]) +async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/first_class_functions/v1" + / "remote_function_version.canonical.json" + ) + stored = json.loads(fixture.read_text()) + result = pa.table({"definition": [json.dumps(stored)]}) + + @function(name=stored["name"]) + def replacement(value: float) -> float: + return value * 2 + + class FunctionServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with FunctionServer() as server: + options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + kwargs["namespace_path"] = ["team"] + if entry == "async_job": + db = await lancedb.connect_async("db://analytics", **options) + job = await db.create_function_async(replacement, **kwargs) + version = await job.wait() + else: + db = lancedb.connect("db://analytics", **options) + if entry == "sync_job": + version = db.create_function_async(replacement, **kwargs).wait() + else: + version = db.create_function(replacement, **kwargs) + (request,) = server.requests + + prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION" + assert f'{prefix} "{stored["name"]}" FROM '.encode() in request + assert b'"exist_ok"' not in request + assert json.loads(version.to_canonical_json()) == stored diff --git a/python/src/connection.rs b/python/src/connection.rs index ffa59fd02..dabecc048 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -903,15 +903,17 @@ impl Connection { }) } - #[pyo3(signature = (request_json, namespace_path=None))] + #[pyo3(signature = (request_json, namespace_path=None, *, exist_ok=false))] pub fn create_function_async( self_: PyRef<'_, Self>, request_json: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); - let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) + let mut request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) .infer_error()?; + request.exist_ok = exist_ok; let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index e3d47948e..d1b63f2ad 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -834,6 +834,9 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s /// database already holds, which Sophon resolves inside the remote runtime. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FunctionRegistrationRequest { + /// Preserve an existing named Function version instead of registering a new one. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, /// Default retries of failed user-code calls. Enterprise only. #[serde(default, skip_serializing_if = "Option::is_none")] pub retry_policy: Option, @@ -876,6 +879,10 @@ pub struct FunctionRegistrationRequest { pub models: Vec, } +fn is_false(value: &bool) -> bool { + !*value +} + impl FunctionRegistrationRequest { /// Decode a registration request supplied by an SDK language binding. pub fn from_json(json: &str) -> Result { diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index c2b5aba06..19a1a6cbc 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -34,13 +34,22 @@ impl SqlClient { validate_function_name(&request.name)?; validate_namespace(namespace)?; let name = quote_identifier(&request.name); + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let mut body = serde_json::to_value(request).map_err(|error| Error::Runtime { message: error.to_string(), })?; body.as_object_mut().unwrap().remove("name"); + body.as_object_mut().unwrap().remove("exist_ok"); self.object_job( ExecuteQueryRequest { - query: format!("CREATE FUNCTION {name} FROM {}", literal(&body.to_string())), + query: format!( + "CREATE FUNCTION{if_not_exists} {name} FROM {}", + literal(&body.to_string()) + ), default_namespace_path: namespace.to_vec(), parameters: None, }, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 6a3f30390..e1780f118 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3087,7 +3087,16 @@ async fn function_creation_and_description_use_sql_query_handles() { const REQUEST: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" ); - for (defer, with_models) in [(false, false), (false, true), (true, false), (true, true)] { + for (defer, with_models, exist_ok) in [ + (false, false, false), + (false, true, false), + (true, false, false), + (true, true, false), + (false, false, true), + (false, true, true), + (true, false, true), + (true, true, true), + ] { let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); request_json["batch_size"] = serde_json::json!(2); request_json["max_concurrency"] = serde_json::json!(4); @@ -3113,9 +3122,11 @@ async fn function_creation_and_description_use_sql_query_handles() { let expected_models = version_json["image"].get("models"); let mut expected_request = request_json.clone(); expected_request.as_object_mut().unwrap().remove("name"); - let request = + let mut request = crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) .unwrap(); + assert!(!request.exist_ok); + request.exist_ok = exist_ok; let result = RecordBatch::try_from_iter(vec![( "definition", Arc::new(StringArray::from(vec![version_json.to_string()])) as ArrayRef, @@ -3151,7 +3162,10 @@ async fn function_creation_and_description_use_sql_query_handles() { { let seen = statements.lock().unwrap(); let encoded = seen[0] - .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .strip_prefix(&format!( + "CREATE FUNCTION{} \"normalize_score\" FROM '", + if exist_ok { " IF NOT EXISTS" } else { "" } + )) .unwrap() .strip_suffix('\'') .unwrap(); From a0eb6b4b71d7b59a5047387a32563b098e349418 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:37:08 -0800 Subject: [PATCH 28/36] feat(python): support exist_ok for storage integrations (#4986) Adds `exist_ok=False` to sync and async Python storage integration creation. `exist_ok=True` sends `CREATE STORAGE INTEGRATION IF NOT EXISTS` and returns the server's stored configuration, preserving the prefix, credentials and external ID. ```python integration = db.create_storage_integration( "raw", storage_provider="S3", storage_prefix="s3://customer-bucket/raw/", aws_role_arn="arn:aws:iam::123456789012:role/access", exist_ok=True, ) ``` The non-exhaustive Rust request also supports `.exist_ok(true)` for every provider. Requires a SQL server supporting this syntax. Includes protocol and provider SQL coverage. No local builds or tests were run, as requested. --- docs/web/sql/ddl/storage-integration.mdx | 10 +++ python/python/lancedb/db.py | 13 +++ python/python/lancedb/remote/db.py | 2 + .../test_storage_integration_creation.py | 85 +++++++++++++++++++ .../lancedb/src/remote/storage_integration.rs | 53 +++++++++++- rust/lancedb/src/storage_integration.rs | 26 ++++++ 6 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 python/python/tests/test_storage_integration_creation.py diff --git a/docs/web/sql/ddl/storage-integration.mdx b/docs/web/sql/ddl/storage-integration.mdx index 37351f971..9444824ac 100644 --- a/docs/web/sql/ddl/storage-integration.mdx +++ b/docs/web/sql/ddl/storage-integration.mdx @@ -28,6 +28,16 @@ CREATE STORAGE INTEGRATION ``` +{/* Draft for the storage-integration exist_ok release. + +`IF NOT EXISTS` returns an existing integration unchanged, including its provider, +storage prefix, credential references and external ID. In the Python SDK, pass +`exist_ok=True` to `create_storage_integration`. The default reports an error when +the name already exists. +Returning an existing integration requires `USAGE` on that integration. + +*/} + `STORAGE_PROVIDER` and `STORAGE_PREFIX` are required for every provider. `STORAGE_PREFIX` is the URI prefix the integration covers -- a query only matches an integration whose prefix is a prefix of the URI it reads. diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 050b20727..39c9eb1d5 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -432,8 +432,12 @@ class DBConnection(EnforceOverrides): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: + """Register storage access, preserving existing configuration with + ``exist_ok=True``. Existing names are errors by default. + """ raise NotImplementedError def describe_storage_integration( @@ -2503,6 +2507,7 @@ class LanceDBConnection(DBConnection): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: return LOOP.run( @@ -2520,6 +2525,7 @@ class LanceDBConnection(DBConnection): azure_client_secret_secret=azure_client_secret_secret, gcp_credentials_json_secret=gcp_credentials_json_secret, huggingface_token_secret=huggingface_token_secret, + exist_ok=exist_ok, namespace_path=namespace_path, ) ) @@ -3888,6 +3894,7 @@ class AsyncConnection(object): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: """Register cloud storage access using database-owned credential Secrets. @@ -3902,6 +3909,10 @@ class AsyncConnection(object): optionally set ``huggingface_token_secret`` to a Secret containing the token; omitting it selects anonymous access at the default rate limits. Registration returns setup instructions without verifying storage access. + + ``exist_ok=True`` returns the stored configuration unchanged when the + integration exists, preserving its provider, prefix and credential + bindings. Existing names are errors by default. """ azure_options = ( azure_tenant_id_secret, @@ -4010,6 +4021,8 @@ class AsyncConnection(object): "aws_access_key_id_secret": reference(aws_access_key_id_secret), "aws_secret_access_key_secret": reference(aws_secret_access_key_secret), } + if exist_ok: + request["exist_ok"] = True info = await self._inner.create_storage_integration( validate_secret_name(name), json.dumps(request), diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 870b85b1e..9221c7ceb 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1091,6 +1091,7 @@ class RemoteDBConnection(DBConnection): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: return LOOP.run( @@ -1108,6 +1109,7 @@ class RemoteDBConnection(DBConnection): azure_client_secret_secret=azure_client_secret_secret, gcp_credentials_json_secret=gcp_credentials_json_secret, huggingface_token_secret=huggingface_token_secret, + exist_ok=exist_ok, namespace_path=namespace_path, ) ) diff --git a/python/python/tests/test_storage_integration_creation.py b/python/python/tests/test_storage_integration_creation.py new file mode 100644 index 000000000..13b94d741 --- /dev/null +++ b/python/python/tests/test_storage_integration_creation.py @@ -0,0 +1,85 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "existing"), + [(None, False), (False, False), (True, False), (True, True)], +) +async def test_storage_integration_exist_ok_preserves_server_metadata( + asynchronous, exist_ok, existing +): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/storage_integration.json" + ) + stored = json.loads(fixture.read_text()) + stored["namespace_path"] = ["team"] + columns = {} + for key, value in stored.items(): + if isinstance(value, (dict, list)): + value = json.dumps(value) + columns[key] = pa.array([None], type=pa.string()) if value is None else [value] + result = pa.table(columns) + prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"] + role = ( + "arn:aws:iam::999999999999:role/replacement" + if existing + else stored["aws_role_arn"] + ) + + class IntegrationServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with IntegrationServer() as server: + connection_options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + kwargs.update( + storage_provider="S3", + storage_prefix=prefix, + aws_role_arn=role, + namespace_path=["team"], + ) + uri = f"db://{stored['database']}" + if asynchronous: + db = await lancedb.connect_async(uri, **connection_options) + info = await db.create_storage_integration(stored["name"], **kwargs) + else: + db = lancedb.connect(uri, **connection_options) + info = db.create_storage_integration(stored["name"], **kwargs) + (request,) = server.requests + + command = ( + "CREATE STORAGE INTEGRATION IF NOT EXISTS" + if exist_ok + else "CREATE STORAGE INTEGRATION" + ) + assert f'{command} "raw"'.encode() in request + assert prefix.encode() in request + assert role.encode() in request + assert info.storage_prefix == stored["storage_prefix"] + assert info.aws_role_arn == stored["aws_role_arn"] + assert info.aws_external_id == stored["aws_external_id"] + assert info.created_at_millis == stored["created_at_millis"] + assert info.namespace_path == ["team"] diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs index bdba4f1df..48dab4c6a 100644 --- a/rust/lancedb/src/remote/storage_integration.rs +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -54,6 +54,11 @@ pub(super) fn create_sql( namespace: &[String], request: &CreateStorageIntegrationRequest, ) -> Result { + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; if request.storage_provider != StorageProvider::HuggingFace && request.huggingface_token_secret.is_some() { @@ -77,7 +82,7 @@ pub(super) fn create_sql( )); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -115,7 +120,7 @@ pub(super) fn create_sql( .as_ref() .ok_or_else(|| invalid("GCP integrations require gcp_credentials_json_secret"))?; return Ok(format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", object_name(name, namespace)?, literal(&request.storage_prefix), secret_name(reference)? @@ -135,7 +140,7 @@ pub(super) fn create_sql( .filter(|account| !account.is_empty()) .ok_or_else(|| invalid("Azure integrations require azure_storage_account"))?; let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", object_name(name, namespace)?, literal(&request.storage_prefix), literal(account) @@ -169,7 +174,7 @@ pub(super) fn create_sql( return Err(invalid("S3 integrations cannot contain Azure options")); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -283,6 +288,46 @@ mod tests { use super::*; + #[test] + fn create_if_not_exists_preserves_provider_options() { + let secret = SecretReference::new("credential"); + let requests = [ + CreateStorageIntegrationRequest::s3("s3://bucket/", "role"), + CreateStorageIntegrationRequest::s3_with_secrets( + "s3://bucket/", + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::azure( + "az://container/", + "account", + secret.clone(), + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::gcp("gs://bucket/", secret), + CreateStorageIntegrationRequest::huggingface("hf://datasets/acme/data/"), + ]; + for request in requests { + let legacy_json = serde_json::to_value(&request).unwrap(); + assert!(legacy_json.get("exist_ok").is_none()); + let decoded: CreateStorageIntegrationRequest = + serde_json::from_value(legacy_json).unwrap(); + assert!(!decoded.exist_ok); + let strict = create_sql("raw", &[], &request).unwrap(); + let guarded = request.exist_ok(true); + assert_eq!(serde_json::to_value(&guarded).unwrap()["exist_ok"], true); + assert_eq!( + create_sql("raw", &[], &guarded).unwrap(), + strict.replacen( + "CREATE STORAGE INTEGRATION ", + "CREATE STORAGE INTEGRATION IF NOT EXISTS ", + 1, + ) + ); + } + } + #[test] fn sql_quotes_values_and_keeps_secret_root_namespace_explicit() { let role = CreateStorageIntegrationRequest::s3("s3://bucket/it's/", "role'value"); diff --git a/rust/lancedb/src/storage_integration.rs b/rust/lancedb/src/storage_integration.rs index 50bfc0aca..587528037 100644 --- a/rust/lancedb/src/storage_integration.rs +++ b/rust/lancedb/src/storage_integration.rs @@ -40,6 +40,9 @@ impl SecretReference { #[derive(Debug, Clone, Serialize, Deserialize)] #[non_exhaustive] pub struct CreateStorageIntegrationRequest { + /// Return the stored configuration unchanged when the integration already exists. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, pub storage_provider: StorageProvider, pub storage_prefix: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -77,12 +80,31 @@ pub enum StorageProvider { HuggingFace, } +fn is_false(value: &bool) -> bool { + !*value +} + impl CreateStorageIntegrationRequest { + /// Return an existing integration without changing its configuration. + /// Defaults to false, which reports an error for an existing name. + /// + /// ``` + /// use lancedb::storage_integration::CreateStorageIntegrationRequest; + /// let config = CreateStorageIntegrationRequest::huggingface( + /// "hf://datasets/acme/data/", + /// ).exist_ok(true); + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Register a prefix and the customer-owned IAM role authorized to access it. pub fn s3(storage_prefix: impl Into, aws_role_arn: impl Into) -> Self { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: Some(aws_role_arn.into()), aws_access_key_id_secret: None, aws_secret_access_key_secret: None, @@ -105,6 +127,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: None, aws_access_key_id_secret: Some(access_key), aws_secret_access_key_secret: Some(secret_key), @@ -138,6 +161,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Azure, storage_prefix: storage_prefix.into(), + exist_ok: false, azure_storage_account: Some(storage_account.into()), azure_tenant_id_secret: Some(tenant_id), azure_client_id_secret: Some(client_id), @@ -163,6 +187,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Gcp, storage_prefix: storage_prefix.into(), + exist_ok: false, gcp_credentials_json_secret: Some(credentials_json), huggingface_token_secret: None, aws_role_arn: None, @@ -189,6 +214,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::HuggingFace, storage_prefix: storage_prefix.into(), + exist_ok: false, huggingface_token_secret: None, gcp_credentials_json_secret: None, aws_role_arn: None, From 4db0d5c7f50a61d1c01a9ef409c11e3ba09d04eb Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:48:26 -0800 Subject: [PATCH 29/36] feat(python): support exist_ok when cloning tables (#4990) Adds `exist_ok=False` to Python table cloning and `.exist_ok(true)` to the Rust clone builder. An existing target is returned with its data and version history unchanged; strict duplicate errors remain the default. ```python snapshot = db.clone_table("snapshot", source_uri, exist_ok=True) ``` Embedded cloning skips source reads for an existing target and handles typed creation conflicts. Remote cloning forwards the option to the server. Includes sync/async preservation and remote request coverage, plus SQL syntax documentation for `CREATE TABLE IF NOT EXISTS target CLONE source`. Requires a server supporting the option for remote clones. BREAKING CHANGE: Rust `CloneTableRequest` struct literals must initialize the new `exist_ok` field; `CloneTableRequest::new` remains compatible. No local builds or tests were run, as requested. --- docs/web/management/table.mdx | 12 ++++ docs/web/sql/ddl/table.mdx | 10 ++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 8 +++ python/python/lancedb/remote/db.py | 4 ++ python/python/tests/test_clone_creation.py | 36 ++++++++++++ python/src/connection.rs | 6 +- rust/lancedb/src/connection.rs | 30 +++++++++- rust/lancedb/src/database.rs | 3 + rust/lancedb/src/database/listing.rs | 65 ++++++++++++++-------- rust/lancedb/src/remote/db.rs | 16 +++++- 11 files changed, 162 insertions(+), 30 deletions(-) create mode 100644 python/python/tests/test_clone_creation.py diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index bf6bf3edd..8031a4c49 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -270,6 +270,18 @@ Renaming is not supported on a local directory connection. In LanceDB Enterprise whether a table can be renamed or cloned at all depends on how the deployment stores its catalog. +{/* Draft for the table-clone exist_ok release. + +Pass `exist_ok=True` to keep an existing target table, including its data and +version history, instead of reporting a duplicate. The source is used only when +the target is missing. Remote use requires a deployment that supports this option. + +```python +db.clone_table("docs_snapshot", source_uri="s3://bucket/db/documents.lance", exist_ok=True) +``` + +*/} + A **shallow** clone (the default) references the source's data files rather than copying them, so it is fast and cheap regardless of table size. It is the practical way to branch an experiment off a known version, or to pin a training diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index ab0ff64bf..c8c42d4e0 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -205,6 +205,16 @@ Dropping, renaming, or retyping a column is an SDK operation ## CLONE {#clone} +{/* Draft for the table-clone exist_ok release. + +Use `CREATE TABLE IF NOT EXISTS target CLONE source` to preserve an existing +target unchanged. The Python equivalent is +`db.clone_table("target", source_uri, exist_ok=True)`. Omitting the option reports +an error for an existing target. A skipped clone does not copy rows or change +the target's version history. + +*/} + ```sql SQL icon="database" CREATE TABLE docs_snapshot CLONE documents diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 44523fd42..d5c024959 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -347,6 +347,8 @@ class Connection(object): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + *, + exist_ok: bool = False, ) -> Table: ... async def rename_table( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 39c9eb1d5..18ca9cf6f 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -2271,6 +2271,7 @@ class LanceDBConnection(DBConnection): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> LanceTable: """Clone a table from a source table. @@ -2295,6 +2296,8 @@ class LanceDBConnection(DBConnection): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -2310,6 +2313,7 @@ class LanceDBConnection(DBConnection): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) ) return LanceTable.open( @@ -3595,6 +3599,7 @@ class AsyncConnection(object): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> AsyncTable: """Clone a table from a source table. @@ -3619,6 +3624,8 @@ class AsyncConnection(object): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -3633,6 +3640,7 @@ class AsyncConnection(object): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) return AsyncTable(table) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 9221c7ceb..69b691004 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -576,6 +576,7 @@ class RemoteDBConnection(DBConnection): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> Table: """Clone a table from a source table. @@ -595,6 +596,8 @@ class RemoteDBConnection(DBConnection): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -612,6 +615,7 @@ class RemoteDBConnection(DBConnection): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) ) return RemoteTable( diff --git a/python/python/tests/test_clone_creation.py b/python/python/tests/test_clone_creation.py new file mode 100644 index 000000000..6c12420c5 --- /dev/null +++ b/python/python/tests/test_clone_creation.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous): + source_uri = str(tmp_path / "source.lance") + if asynchronous: + db = await lancedb.connect_async(tmp_path) + await db.create_table("source", [{"id": 1}]) + table = await db.clone_table("target", source_uri, exist_ok=True) + assert (await table.to_arrow()).to_pylist() == [{"id": 1}] + await table.add([{"id": 2}]) + version = await table.version() + with pytest.raises(ValueError, match="already exists"): + await db.clone_table("target", source_uri) + kept = await db.clone_table("target", "missing.lance", exist_ok=True) + assert await kept.version() == version + assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}] + else: + db = lancedb.connect(tmp_path) + db.create_table("source", [{"id": 1}]) + table = db.clone_table("target", source_uri, exist_ok=True) + assert table.to_arrow().to_pylist() == [{"id": 1}] + table.add([{"id": 2}]) + version = table.version + with pytest.raises(ValueError, match="already exists"): + db.clone_table("target", source_uri) + kept = db.clone_table("target", "missing.lance", exist_ok=True) + assert kept.version == version + assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}] diff --git a/python/src/connection.rs b/python/src/connection.rs index dabecc048..8763822cc 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -457,7 +457,8 @@ impl Connection { }) } - #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true, *, exist_ok=false))] pub fn clone_table( self_: PyRef<'_, Self>, target_table_name: String, @@ -466,6 +467,7 @@ impl Connection { source_version: Option, source_tag: Option, is_shallow: bool, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); @@ -477,7 +479,7 @@ impl Connection { if let Some(tag) = source_tag { builder = builder.source_tag(tag); } - builder = builder.is_shallow(is_shallow); + builder = builder.is_shallow(is_shallow).exist_ok(exist_ok); future_into_py(self_.py(), async move { let table = builder.execute().await.infer_error()?; diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index c7a058502..6dacbbbea 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -433,6 +433,21 @@ impl CloneTableBuilder { } } + /// Preserve an existing target without reading or cloning the source. + /// Defaults to false, which reports a duplicate-name error. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let table = db.clone_table("snapshot", "s3://bucket/source.lance") + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.request.exist_ok = exist_ok; + self + } + /// Set the source version to clone from pub fn source_version(mut self, version: u64) -> Self { self.request.source_version = Some(version); @@ -633,7 +648,8 @@ impl Connection { /// Creates a new table by cloning from an existing source table. /// By default, this performs a shallow clone where the new table shares /// the underlying data files with the source table. - /// The target table name must be unused. An existing table is left unchanged. + /// The target table name must be unused by default. Use + /// [`CloneTableBuilder::exist_ok`] to open an existing target unchanged. /// /// # Parameters /// - `target_table_name`: The name of the new table to create @@ -2787,6 +2803,14 @@ mod tests { "unexpected clone error: {err:?}" ); + let preserved = db + .clone_table(target, "missing-source.lance") + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(preserved.name(), target); + // Reopen both tables to verify that the failed clone left their data and versions intact. for (name, expected_data) in [("source", source_data), ("target", target_data)] { let table = db.open_table(name).execute().await.unwrap(); @@ -2804,8 +2828,9 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { let tmp_dir = tempdir().unwrap(); let uri = tmp_dir.path().to_str().unwrap(); let db = connect(uri).execute().await.unwrap(); @@ -2830,6 +2855,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table("cloned_table", source_uri) + .exist_ok(exist_ok) .execute() .await .unwrap(); diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 39e361a39..638ae0dd5 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -163,6 +163,8 @@ impl CreateTableRequest { /// sharing the same data, deletion, and index files. #[derive(Clone, Debug)] pub struct CloneTableRequest { + /// Preserve an existing target rather than returning a duplicate-name error. + pub exist_ok: bool, /// The name of the target table to create pub target_table_name: String, /// The namespace path for the target table. Empty list represents root namespace. @@ -184,6 +186,7 @@ pub struct CloneTableRequest { impl CloneTableRequest { pub fn new(target_table_name: String, source_uri: String) -> Self { Self { + exist_ok: false, target_table_name, target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index d5749f974..765c8af3d 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1119,40 +1119,47 @@ impl Database for ListingDatabase { }; let target_uri = self.table_uri(&request.target_table_name)?; - match DatasetBuilder::from_uri(&target_uri) + let exists = match DatasetBuilder::from_uri(&target_uri) .with_read_params(read_params.clone()) .load() .await { - Ok(_) => { + Ok(_) if !request.exist_ok => { return Err(Error::TableAlreadyExists { name: request.target_table_name, }); } - Err(lance::Error::DatasetNotFound { .. }) => {} + Ok(_) => true, + Err(lance::Error::DatasetNotFound { .. }) => false, Err(err) => return Err(err.into()), + }; + + if !exists { + let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) + .with_read_params(read_params.clone()) + .load() + .await + .map_err(|e| -> Error { e.into() })?; + + let version_ref = match (request.source_version, request.source_tag) { + (Some(v), None) => Ok(Ref::Version(None, Some(v))), + (None, Some(tag)) => Ok(Ref::Tag(tag)), + (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), + _ => Err(Error::InvalidInput { + message: "Cannot specify both source_version and source_tag".to_string(), + }), + }?; + + match source_dataset + .shallow_clone(&target_uri, version_ref, Some(storage_params)) + .await + { + Ok(_) => {} + Err(lance::Error::DatasetAlreadyExists { .. }) if request.exist_ok => {} + Err(error) => return Err(error.into()), + } } - let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) - .with_read_params(read_params.clone()) - .load() - .await - .map_err(|e| -> Error { e.into() })?; - - let version_ref = match (request.source_version, request.source_tag) { - (Some(v), None) => Ok(Ref::Version(None, Some(v))), - (None, Some(tag)) => Ok(Ref::Tag(tag)), - (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), - _ => Err(Error::InvalidInput { - message: "Cannot specify both source_version and source_tag".to_string(), - }), - }?; - - source_dataset - .shallow_clone(&target_uri, version_ref, Some(storage_params)) - .await - .map_err(|e| -> Error { e.into() })?; - let cloned_table = NativeTable::open_with_params( &target_uri, &request.target_table_name, @@ -2252,6 +2259,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_table".to_string(), target_namespace_path: vec![], source_uri: source_uri.clone(), @@ -2313,6 +2321,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_with_data".to_string(), target_namespace_path: vec![], source_uri, @@ -2375,6 +2384,7 @@ mod tests { // Clone should work with storage options let cloned = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2412,6 +2422,7 @@ mod tests { // Try deep clone (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2453,6 +2464,7 @@ mod tests { // Try clone with namespace (should fail for listing database) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec!["namespace".to_string()], // Non-empty namespace source_uri, @@ -2494,6 +2506,7 @@ mod tests { // Try clone with invalid target name let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "invalid/name".to_string(), // Invalid name with slash target_namespace_path: vec![], source_uri, @@ -2514,6 +2527,7 @@ mod tests { // Try to clone from non-existent source let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri: "/nonexistent/table.lance".to_string(), @@ -2551,6 +2565,7 @@ mod tests { // Try clone with both version and tag (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2625,6 +2640,7 @@ mod tests { // Clone from the initial version (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_version".to_string(), target_namespace_path: vec![], source_uri, @@ -2704,6 +2720,7 @@ mod tests { // Clone from the tag (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_tag".to_string(), target_namespace_path: vec![], source_uri, @@ -2756,6 +2773,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "independent_clone".to_string(), target_namespace_path: vec![], source_uri, @@ -2849,6 +2867,7 @@ mod tests { // Clone without specifying version or tag (should get latest) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_latest".to_string(), target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a05bb07b7..300cd6b09 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1612,10 +1612,13 @@ impl Database for RemoteDatabase { is_shallow: Some(request.is_shallow), }; - let req = self + let mut req = self .client .post(&format!("/v1/table/{}/clone", table_identifier.clone())) .json(&remote_request); + if request.exist_ok { + req = req.query(&[("exist_ok", true)]); + } let (request_id, rsp) = self.client.send(req).await?; @@ -3651,9 +3654,10 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { - let conn = Connection::new_with_handler(|request| { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { + let conn = Connection::new_with_handler(move |request| { assert_eq!(request.method(), &reqwest::Method::POST); assert_eq!(request.url().path(), "/v1/table/cloned_table/clone"); assert_eq!( @@ -3665,12 +3669,18 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(body).unwrap(); assert_eq!(body["source_location"], "s3://bucket/source_table"); assert_eq!(body["is_shallow"], true); + if exist_ok { + assert_eq!(request.url().query(), Some("exist_ok=true")); + } else { + assert!(request.url().query().is_none()); + } http::Response::builder().status(200).body("").unwrap() }); let table = conn .clone_table("cloned_table", "s3://bucket/source_table") + .exist_ok(exist_ok) .execute() .await .unwrap(); From 81d04b8c361b596b29f4f7988aab7df0eb9f84ca Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 19:21:29 -0800 Subject: [PATCH 30/36] feat(python): support exist_ok for materialized views (#4991) --- docs/web/sql/ddl/materialized-view.mdx | 10 +++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 25 ++++++ python/python/lancedb/namespace.py | 8 ++ python/python/lancedb/remote/db.py | 4 + .../tests/test_materialized_view_creation.py | 84 +++++++++++++++++++ .../python/tests/test_materialized_views.py | 2 + python/src/connection.rs | 10 ++- rust/lancedb/src/materialized_view.rs | 49 ++++++++++- rust/lancedb/src/remote/db.rs | 11 ++- .../src/remote/sql/materialized_view.rs | 15 ++++ rust/lancedb/src/remote/sql_test.rs | 60 +++++++++++++ rust/lancedb/src/remote/table.rs | 7 ++ 13 files changed, 281 insertions(+), 6 deletions(-) create mode 100644 python/python/tests/test_materialized_view_creation.py diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index 2f9173ecd..a2453ba01 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -27,6 +27,16 @@ CREATE MATERIALIZED VIEW AS SELECT ... ``` +{/* Draft for the materialized-view exist_ok release. + +`IF NOT EXISTS` preserves an existing materialized view's definition, data and +refresh settings without refreshing it. The Python equivalent is +`db.create_materialized_view("saved", "source", exist_ok=True)`. A skipped +asynchronous creation returns a completed job without submitting a refresh job. +Existing names are errors by default. + +*/} + Once created, a materialized view can be queried like a table. Use the statements below to list, refresh and drop it. For SDK methods, see [Materialized views](/management/materialized-view#create). diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index d5c024959..e3f00557c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -369,6 +369,7 @@ class Connection(object): auto_refresh_interval_seconds: Optional[float] = None, *, query: Optional[str] = None, + exist_ok: bool = False, ) -> Table: ... async def create_materialized_view_async( self, @@ -382,6 +383,7 @@ class Connection(object): auto_refresh_interval_seconds: Optional[float] = None, *, query: Optional[str] = None, + exist_ok: bool = False, ) -> Job: ... def list_materialized_views( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 18ca9cf6f..b84e4d581 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -710,11 +710,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -780,11 +784,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: """Submit materialized-view creation and return its job. + ``exist_ok=True`` preserves an existing view without refreshing it. + A skipped creation returns a completed job without a registry job ID. + The job may already be complete in LanceDB Embedded. In LanceDB Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL server and the returned ``id`` is the registry job ID. That ID can be @@ -2150,11 +2158,15 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -2185,6 +2197,7 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -2202,6 +2215,7 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: @@ -2214,6 +2228,7 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -3453,11 +3468,15 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncMaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -3480,6 +3499,7 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, @@ -3496,11 +3516,15 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job. + ``exist_ok=True`` preserves an existing view without refreshing it. + A skipped creation returns a completed job without a registry job ID. + Wait for the returned job before opening or querying the view. In LanceDB Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. @@ -3521,6 +3545,7 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 72dc78c8b..67fcc61f7 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -705,6 +705,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> "MaterializedView": """Define a materialized view over a table in the root namespace. See @@ -723,6 +724,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) ).name ) @@ -741,6 +743,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> Job[None]: job = LOOP.run( self._inner.create_materialized_view_async( @@ -753,6 +756,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) ) return Job(job) @@ -1352,6 +1356,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> "AsyncMaterializedView": """Define a materialized view over a table in the root namespace.""" view = await self._inner.create_materialized_view( @@ -1364,6 +1369,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) # Reopen through the namespace so the view's table carries the # namespace client and pushdown configuration a bare inner table lacks. @@ -1381,6 +1387,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job.""" return await self._inner.create_materialized_view_async( @@ -1393,6 +1400,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) async def open_materialized_view(self, name: str) -> "AsyncMaterializedView": diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 69b691004..b9928d278 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -803,6 +803,7 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: @@ -817,6 +818,7 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -841,6 +843,7 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: @@ -853,6 +856,7 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) diff --git a/python/python/tests/test_materialized_view_creation.py b/python/python/tests/test_materialized_view_creation.py new file mode 100644 index 000000000..0d9a4c2b4 --- /dev/null +++ b/python/python/tests/test_materialized_view_creation.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +import lancedb + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("namespace", [False, True]) +@pytest.mark.parametrize("defining_query", [False, True]) +async def test_exist_ok_preserves_materialized_data( + tmp_path, asynchronous, background, namespace, defining_query +): + source_args = ( + {"query": "SELECT * FROM source"} if defining_query else {"source": "source"} + ) + replacement_args = { + **( + {"query": "SELECT * FROM missing"} + if defining_query + else {"source": "missing"} + ), + "auto_refresh_enabled": True, + "auto_refresh_interval_seconds": 1, + } + options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}} + if asynchronous: + db = ( + lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options) + if namespace + else await lancedb.connect_async(tmp_path, **options) + ) + source = await db.create_table("source", [{"id": 1}]) + original = await db.create_materialized_view( + "saved", **source_args, exist_ok=True + ) + definition = await original.definition() + version = await original.table.version() + await source.add([{"id": 2}]) + if background: + job = await db.create_materialized_view_async( + "saved", **replacement_args, exist_ok=True + ) + await job.wait() + kept = await db.open_materialized_view("saved") + else: + kept = await db.create_materialized_view( + "saved", **replacement_args, exist_ok=True + ) + assert (await kept.definition()).query == definition.query + assert await kept.table.version() == version + assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}] + with pytest.raises(ValueError, match="already exists"): + await db.create_materialized_view("saved", **source_args) + else: + db = ( + lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options) + if namespace + else lancedb.connect(tmp_path, **options) + ) + source = db.create_table("source", [{"id": 1}]) + original = db.create_materialized_view("saved", **source_args, exist_ok=True) + definition = original.definition + version = original.table.version + source.add([{"id": 2}]) + if background: + job = db.create_materialized_view_async( + "saved", **replacement_args, exist_ok=True + ) + job.wait() + kept = db.open_materialized_view("saved") + else: + kept = db.create_materialized_view( + "saved", **replacement_args, exist_ok=True + ) + assert kept.definition.query == definition.query + assert kept.table.version == version + assert kept.table.to_arrow().to_pylist() == [{"id": 1}] + with pytest.raises(ValueError, match="already exists"): + db.create_materialized_view("saved", **source_args) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 1ea0c1cb9..13950a39c 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -197,6 +197,7 @@ def test_sync_remote_create_uses_public_async_connection(query): where=None, limit=None, with_no_data=False, + exist_ok=False, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, ): @@ -729,6 +730,7 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options "filter": None, "limit": None, "with_no_data": False, + "exist_ok": False, "auto_refresh_enabled": options.get("auto_refresh_enabled"), "auto_refresh_interval_seconds": options.get( "auto_refresh_interval_seconds" diff --git a/python/src/connection.rs b/python/src/connection.rs index 8763822cc..1a171032c 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -507,7 +507,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, @@ -519,6 +519,7 @@ impl Connection { auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let builder = materialized_view_builder( @@ -529,7 +530,7 @@ impl Connection { projections.is_some() || filter.is_some() || limit.is_some(), )?; future_into_py(self_.py(), async move { - let mut builder = builder; + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -552,7 +553,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, @@ -564,6 +565,7 @@ impl Connection { auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let builder = materialized_view_builder( @@ -574,7 +576,7 @@ impl Connection { projections.is_some() || filter.is_some() || limit.is_some(), )?; future_into_py(self_.py(), async move { - let mut builder = builder; + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 9920cd893..4b2a61f2c 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -287,6 +287,8 @@ pub struct MaterializedViewInfo { #[doc(hidden)] #[derive(Debug, Clone, PartialEq)] pub struct CreateMaterializedViewRequest { + /// Preserve an existing materialized view without refreshing it. + pub exist_ok: bool, /// Name of the new view. pub name: String, /// Namespace in which to create the view. @@ -1586,6 +1588,7 @@ pub struct CreateMaterializedViewBuilder { filter: Option, limit: Option, with_no_data: bool, + exist_ok: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, } @@ -1626,6 +1629,7 @@ impl CreateMaterializedViewBuilder { filter: None, limit: None, with_no_data: false, + exist_ok: false, auto_refresh_enabled: None, auto_refresh_interval_seconds: None, } @@ -1678,6 +1682,35 @@ impl CreateMaterializedViewBuilder { self } + /// Preserve an existing view's definition, data and refresh settings. + /// Defaults to false. A skipped creation does not refresh the view. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// db.create_materialized_view("saved", "source").exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + async fn existing_view(&self) -> Result> { + match self + .connection + .open_table(&self.name) + .namespace(self.namespace.clone()) + .execute() + .await + { + Ok(table) => MaterializedView::from_table(table).await.map(Some), + Err(Error::TableNotFound { .. }) => Ok(None), + Err(error) => Err(error), + } + } + /// Enable or disable automatic refresh in LanceDB Enterprise. /// When omitted, the server determines whether automatic refresh is enabled. /// LanceDB Embedded does not support automatic refresh. @@ -1759,6 +1792,7 @@ impl CreateMaterializedViewBuilder { .connection .database() .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: self.exist_ok, name: self.name.clone(), namespace_path: self.namespace.clone(), query: self.query()?, @@ -1793,6 +1827,11 @@ impl CreateMaterializedViewBuilder { async fn execute_native(self) -> Result { crate::require_experimental_functions()?; + if self.exist_ok + && let Some(view) = self.existing_view().await? + { + return Ok(view); + } if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { return Err(Error::NotSupported { message: "automatic materialized-view refresh requires LanceDB Enterprise" @@ -1826,7 +1865,15 @@ impl CreateMaterializedViewBuilder { prepare_definition(&source, definition).await? } }; - let view = prepared.create_in(&self.namespace, &self.name).await?; + let view = match prepared.create_in(&self.namespace, &self.name).await { + Ok(view) => view, + Err(Error::TableAlreadyExists { .. }) if self.exist_ok => { + return self.existing_view().await?.ok_or_else(|| Error::Runtime { + message: "materialized view disappeared after concurrent creation".into(), + }); + } + Err(error) => return Err(error), + }; if !self.with_no_data { view.refresh().execute().await?; } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 300cd6b09..7100e1b04 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -803,16 +803,24 @@ impl Database for RemoteDatabase { } else { format!(" WITH ({})", options.join(", ")) }; + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let submission = client .submit_materialized_view_job( format!( - "CREATE MATERIALIZED VIEW \"{name}\"{options} AS {}", + "CREATE MATERIALIZED VIEW{if_not_exists} \"{name}\"{options} AS {}", request.query ), request.namespace_path, ) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Ok(Job::new_done()) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new(Box::new(RemoteJob::new( @@ -4865,6 +4873,7 @@ mod tests { for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { let result = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec![], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index 4eaad5156..e982afac7 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -39,6 +39,7 @@ fn strings(batch: &RecordBatch, name: &str) -> Result> { } pub(in crate::remote) enum MaterializedViewJobSubmission { + AlreadyExists, Registry { job_id: String }, Query(Arc), } @@ -66,6 +67,7 @@ impl SqlClient { let mut reader: SendableRecordBatchStream = query.reader().await?; let mut rows = 0; let mut registry_job_id = None; + let mut already_exists = false; while let Some(batch) = reader.try_next().await? { rows += batch.num_rows(); if rows > 1 { @@ -74,6 +76,16 @@ impl SqlClient { .into(), }); } + if let Some(column) = batch.column_by_name("status") { + let values = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "materialized-view submission status is not UTF-8".into(), + })?; + already_exists = + values.len() == 1 && !values.is_null(0) && values.value(0) == "already_exists"; + } if let Some(column) = batch.column_by_name("job_id") { let values = column .as_any() @@ -100,6 +112,9 @@ impl SqlClient { message: "materialized-view submission must return exactly one status row".into(), }); } + if already_exists && registry_job_id.is_none() { + return Ok(MaterializedViewJobSubmission::AlreadyExists); + } let job_id = registry_job_id.ok_or_else(|| Error::Runtime { message: "server acknowledged an early materialized-view handle but returned no job_id" .into(), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index e1780f118..1c39eda19 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1220,6 +1220,7 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { ] { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1302,6 +1303,7 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1329,6 +1331,63 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry_job() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + materialized_view_job_handle_supported: true, + ..Default::default() + }; + let statement = "CREATE MATERIALIZED VIEW IF NOT EXISTS \"adults\" AS SELECT * FROM people"; + service.result_overrides.lock().unwrap().insert( + statement.into(), + RecordBatch::try_from_iter([ + ( + "status", + Arc::new(StringArray::from(vec!["already_exists"])) as arrow_array::ArrayRef, + ), + ( + "job_id", + Arc::new(StringArray::from(vec![""])) as arrow_array::ArrayRef, + ), + ]) + .unwrap(), + ); + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!( + "a skipped creation must not poll a registry job: {}", + request.url() + ); + }) + .with_sql_client(client); + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: true, + name: "adults".into(), + namespace_path: vec!["team".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + }) + .await + .unwrap(); + if defer { + assert!(job.id().is_none()); + } else { + assert_eq!(job.job_type().as_deref(), Some("query")); + } + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert_eq!(*statements.lock().unwrap(), [statement]); + shutdown.send(()).unwrap(); + } +} + #[tokio::test] async fn remote_create_registry_handle_reopens_describes_and_cancels() { let service = TestSqlService { @@ -1394,6 +1453,7 @@ async fn remote_create_registry_handle_reopens_describes_and_cancels() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 9b64ab56d..f4e5c1e4a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2658,6 +2658,13 @@ impl BaseTable for RemoteTable { .submit_materialized_view_job(statement, self.namespace.clone()) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Err(Error::Runtime { + message: + "REFRESH MATERIALIZED VIEW returned a create-only already_exists status" + .into(), + }) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new_typed(Box::new(MaterializedViewRefreshJob { From f6311ae7e9c34ab8fc5067282fec864bd9f3a558 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 19:21:50 -0800 Subject: [PATCH 31/36] feat: support exist_ok for index creation (#4993) --- docs/web/sql/ddl/index.mdx | 40 +++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/remote/table.py | 10 ++ python/python/lancedb/table.py | 71 ++++++++- python/python/tests/test_index.py | 42 ++++++ python/python/tests/test_remote_db.py | 52 +++++++ python/python/tests/test_table.py | 96 ++++++++++++ python/python/tests/test_table_signatures.py | 6 +- python/src/table.rs | 10 +- rust/lancedb/src/index.rs | 17 +++ rust/lancedb/src/remote/table.rs | 42 +++++- rust/lancedb/src/table.rs | 8 +- rust/lancedb/src/table/create_index.rs | 146 ++++++++++++++++++- 13 files changed, 525 insertions(+), 17 deletions(-) diff --git a/docs/web/sql/ddl/index.mdx b/docs/web/sql/ddl/index.mdx index 425af7376..035424b5f 100644 --- a/docs/web/sql/ddl/index.mdx +++ b/docs/web/sql/ddl/index.mdx @@ -38,6 +38,46 @@ runs as `create_` followed by the algorithm instead. See [Incremental Indexing](/indexing/incremental-indexing). +{/* Draft for the index exist_ok release. + +```sql +CREATE INDEX IF NOT EXISTS text_search ON documents USING fts (text) +``` + +Use `IF NOT EXISTS` to preserve the existing index with the same name. Without an +explicit name, the name is derived from the column (`title_idx`, or +`title_list_element_idx` for list-element FTS). Existing definitions and builds +are kept, even when the new request specifies different settings. + +The Python SDK exposes the same behavior through `exist_ok=True` on +`create_index` and `create_index_async`, including scalar and FTS wrappers. +This option takes precedence over `replace`, whose default behavior is unchanged. + +```python +from lancedb.index import BTree + +table.create_index("title", config=BTree(), name="title_idx", exist_ok=True) +``` + +```rust +use lancedb::index::Index; + +table.create_index(&["title"], Index::BTree(Default::default())) + .name("title_idx".to_string()) + .exist_ok(true) + .execute() + .await?; +``` + +The SDK option is available in Python and Rust. TypeScript support is a separate +follow-up. Remote use requires a server that supports the option. + +An existing background build continues running. A completed submission handle +for a skipped creation does not wait for that build; use `wait_for_index` when +its completion is required. + +*/} + ## DROP INDEX {#drop} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index e3f00557c..cbc62f772 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -591,6 +591,7 @@ class Table: *, name: Optional[str], train: Optional[bool], + exist_ok: bool = False, ): ... async def create_index_async( self, @@ -615,6 +616,7 @@ class Table: *, name: Optional[str], train: Optional[bool], + exist_ok: bool = False, ) -> Job: ... async def list_versions(self) -> List[Dict[str, Any]]: ... async def version(self) -> int: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 6730e6694..dbfd127ee 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -369,6 +369,7 @@ class RemoteTable(Table): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -395,6 +396,7 @@ class RemoteTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -433,6 +435,7 @@ class RemoteTable(Table): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on a column. @@ -492,6 +495,7 @@ class RemoteTable(Table): self._table.create_index( field_names, replace=replace, + exist_ok=exist_ok, config=config, name=name, wait_timeout=wait_timeout, @@ -516,6 +520,7 @@ class RemoteTable(Table): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -541,6 +546,7 @@ class RemoteTable(Table): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -572,6 +578,7 @@ class RemoteTable(Table): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -675,6 +682,7 @@ class RemoteTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -690,6 +698,7 @@ class RemoteTable(Table): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -702,6 +711,7 @@ class RemoteTable(Table): self._table.create_index_async( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 5f0af7a66..e0b96e476 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -168,6 +168,36 @@ def _validate_index_accelerator(accelerator: Any) -> None: raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err +def _create_accelerated_index(dataset, *, exist_ok=False, name=None, **options): + if exist_ok: + parts = _parse_field_path(options["column"]) + default_name = ".".join(parts) + if any("." in part for part in parts): + default_name = ".".join( + "`" + part.replace("`", "``") + "`" + if any( + not character.isalnum() and character != "_" for character in part + ) + else part + for part in parts + ) + name = name or f"{default_name}_idx" + dataset.checkout_latest() + if any(index["name"] == name for index in dataset.list_indices()): + return + options["replace"] = False + options["name"] = name + _validate_index_accelerator(options.get("accelerator")) + try: + dataset.create_index(**options) + except Exception: + if exist_ok: + dataset.checkout_latest() + if any(index["name"] == name for index in dataset.list_indices()): + return + raise + + def _polars_predicate_pushdown_barrier(frame: Any) -> Any: """Return a Polars frame unchanged while blocking predicate pushdown.""" return frame @@ -1834,6 +1864,7 @@ class Table(ABC): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -1859,6 +1890,7 @@ class Table(ABC): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -1890,6 +1922,7 @@ class Table(ABC): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -1913,6 +1946,9 @@ class Table(ABC): BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. + exist_ok : bool, default False + Preserve the existing index with the requested or derived name. + Takes precedence over replace and keeps its definition and build. wait_timeout : timedelta, optional LanceDB Enterprise only: how long to wait for the index build to finish. If not set, the call returns once the build is scheduled. @@ -1968,6 +2004,7 @@ class Table(ABC): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -2060,6 +2097,7 @@ class Table(ABC): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -2144,6 +2182,7 @@ class Table(ABC): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on the table. @@ -4318,6 +4357,7 @@ class LanceTable(Table): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -4343,6 +4383,7 @@ class LanceTable(Table): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -4374,6 +4415,7 @@ class LanceTable(Table): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -4397,6 +4439,9 @@ class LanceTable(Table): BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. + exist_ok : bool, default False + Preserve the existing index with the requested or derived name. + Takes precedence over replace and keeps its definition and build. wait_timeout : timedelta, optional Timeout to wait for async indexing to complete. name : str, optional @@ -4465,8 +4510,10 @@ class LanceTable(Table): # Handle accelerator through pylance if accelerator is not None: dataset = self.to_lance() - _validate_index_accelerator(accelerator) - dataset.create_index( + _create_accelerated_index( + dataset, + exist_ok=exist_ok, + name=name, column=column, index_type=index_type, metric=metric, @@ -4492,7 +4539,6 @@ class LanceTable(Table): if acc is not None: # Dispatch to pylance for GPU acceleration dataset = self.to_lance() - _validate_index_accelerator(acc) index_type_map = { "IvfFlat": "IVF_FLAT", "IvfSq": "IVF_SQ", @@ -4509,7 +4555,10 @@ class LanceTable(Table): if num_bits is not None: quantization_kwargs["num_bits"] = num_bits - dataset.create_index( + _create_accelerated_index( + dataset, + exist_ok=exist_ok, + name=name, column=column, index_type=lance_index_type, metric=getattr(config, "distance_type", "l2"), @@ -4531,6 +4580,7 @@ class LanceTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4546,6 +4596,7 @@ class LanceTable(Table): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -4564,6 +4615,7 @@ class LanceTable(Table): self._table.create_index_async( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4684,6 +4736,7 @@ class LanceTable(Table): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -4710,6 +4763,7 @@ class LanceTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4747,6 +4801,7 @@ class LanceTable(Table): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on a column. @@ -4808,6 +4863,7 @@ class LanceTable(Table): self._table.create_index( field_names, replace=replace, + exist_ok=exist_ok, config=config, name=name, wait_timeout=wait_timeout, @@ -6806,6 +6862,7 @@ class AsyncTable: ] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ): """Create an index to speed up queries @@ -6836,6 +6893,9 @@ class AsyncTable: If not set, the call returns once the build is scheduled. name: str, optional The name of the index. If not provided, a default name will be generated. + exist_ok: bool, default False + Preserve an existing index with the requested or derived name. This + takes precedence over replace and keeps its definition and build. train: bool, default True Whether to train the index with existing data. Vector indices always train with existing data. @@ -6891,6 +6951,7 @@ class AsyncTable: column, index=config, replace=replace, + exist_ok=exist_ok, wait_timeout=wait_timeout, name=name, train=train, @@ -6928,6 +6989,7 @@ class AsyncTable: ] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> AsyncJob: """Create an index, returning a handle to the indexing job. @@ -6946,6 +7008,7 @@ class AsyncTable: column, index=config, replace=replace, + exist_ok=exist_ok, wait_timeout=wait_timeout, name=name, train=train, diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 738a791ad..e658d18e1 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -621,3 +621,45 @@ def test_index_statistics_index_type_lists_all_supported_values(): set(get_args(get_type_hints(IndexStatistics)["index_type"])) == expected_index_types ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))] +) +async def test_index_exist_ok_preserves_existing_index( + some_table, background, column, config +): + await some_table.create_index(column, config=config, exist_ok=True) + version = await some_table.version() + original = await some_table.list_indices() + if background: + job = await some_table.create_index_async( + column, config=config, replace=True, exist_ok=True + ) + await job.wait() + else: + await some_table.create_index( + column, config=config, replace=True, exist_ok=True + ) + assert await some_table.version() == version + assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [ + (i.name, i.index_type) for i in original + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("background", [False, True]) +async def test_named_index_exist_ok_checks_before_column_validation( + some_table, background +): + await some_table.create_index("id", config=BTree(), name="kept") + version = await some_table.version() + method = some_table.create_index_async if background else some_table.create_index + result = await method("missing", config=BTree(), name="kept", exist_ok=True) + if background: + assert result.id is None + await result.wait() + assert await some_table.version() == version + assert [index.name for index in await some_table.list_indices()] == ["kept"] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ca2516fda..ea7f73c71 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -45,6 +45,7 @@ from lancedb.query import ( LanceVectorQueryBuilder, MatchQuery, ) +from lancedb.index import BTree from lancedb.remote import ClientConfig from lancedb.remote.errors import ( AlreadyExistsError, @@ -7420,3 +7421,54 @@ 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("is_async", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("kwargs", [{}, {"exist_ok": False}, {"exist_ok": True}]) +async def test_remote_index_exist_ok_wire(is_async, background, kwargs): + received = [] + + def handler(request): + parsed = urlparse(request.path) + body = request.rfile.read(int(request.headers.get("Content-Length", 0))) + if parsed.path.endswith("/create_index/"): + received.append((parse_qs(parsed.query), json.loads(body))) + payload = {} + elif parsed.path.endswith("/describe/"): + payload = dict( + version=1, + schema=dict( + fields=[dict(name="id", type={"type": "int64"}, nullable=False)] + ), + ) + elif parsed.path.endswith("/create/"): + payload = {} + else: + raise AssertionError(request.path) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + + method = "create_index_async" if background else "create_index" + if is_async: + async with mock_lancedb_connection_async(handler) as db: + table = await db.create_table("test", [{"id": 1}]) + result = await getattr(table, method)("id", config=BTree(), **kwargs) + if background: + await result.wait() + else: + with mock_lancedb_connection(handler) as db: + table = db.create_table("test", [{"id": 1}]) + result = getattr(table, method)("id", config=BTree(), **kwargs) + if background: + result.wait() + query, body = received[0] + assert query == ({"exist_ok": ["true"]} if kwargs.get("exist_ok") else {}) + assert "exist_ok" not in body + if kwargs.get("exist_ok"): + assert body["replace"] is False + else: + assert "replace" not in body diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e3b69ced1..604d6afb3 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1837,6 +1837,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # Test with target_partition_size @@ -1862,6 +1863,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # target_partition_size has a default value, @@ -1886,6 +1888,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1902,6 +1905,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1922,6 +1926,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1942,6 +1947,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) @@ -2073,6 +2079,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name="my_custom_index", train=True, + exist_ok=False, ) # Test with train=False @@ -2084,6 +2091,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name=None, train=False, + exist_ok=False, ) # Test with both name and train @@ -2095,6 +2103,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name="my_index_name", train=True, + exist_ok=False, ) @@ -2132,6 +2141,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # Scalar index via new API @@ -2143,6 +2153,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # FTS index via new API @@ -2154,6 +2165,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) @@ -6292,3 +6304,87 @@ 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.parametrize( + "method", + ["create_index", "create_index_async", "create_scalar_index", "create_fts_index"], +) +@pytest.mark.parametrize("name", [None, "kept_index"]) +def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name): + table = mem_db.create_table( + "keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)] + ) + column = "text" if method == "create_fts_index" else "id" + config = FTS() if column == "text" else BTree() + table.create_index(column, config=config, name=name, exist_ok=True) + before = table.version + original = table.list_indices() + kwargs = dict(name=name, exist_ok=True) + if method in ("create_index", "create_index_async"): + kwargs["config"] = config + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + result = getattr(table, method)(column, **kwargs) + if method == "create_index_async": + result.wait() + assert table.version == before + assert [(index.name, index.index_type) for index in table.list_indices()] == [ + (index.name, index.index_type) for index in original + ] + with pytest.raises((ValueError, RuntimeError), match="already exists"): + table.create_index(column, config=config, name=name, replace=False) + table.create_index(column, config=config, name=name) + assert table.version > before + + +@pytest.mark.parametrize( + "column,name,existing", + [ + ("vector", "kept", "kept"), + ("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"), + ], +) +def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing): + dataset = MagicMock() + dataset.list_indices.return_value = [{"name": existing}] + with patch("lancedb.table._validate_index_accelerator") as validate: + table_module._create_accelerated_index( + dataset, column=column, accelerator="cuda", name=name, exist_ok=True + ) + validate.assert_not_called() + dataset.create_index.assert_not_called() + + +def test_accelerated_index_exist_ok_preserves_concurrent_winner(): + dataset = MagicMock() + dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]] + dataset.create_index.side_effect = RuntimeError("concurrent create") + with patch("lancedb.table._validate_index_accelerator"): + table_module._create_accelerated_index( + dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True + ) + assert dataset.create_index.call_args.kwargs["replace"] is False + assert dataset.create_index.call_args.kwargs["name"] == "vector_idx" + + +@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"]) +def test_index_exist_ok_matches_lance_default_name(mem_db, column): + table = mem_db.create_table( + "quoted_index", + [{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}], + ) + table.create_index(column, config=BTree()) + before = table.version + table.create_index(column, config=BTree(), exist_ok=True) + assert table.version == before + assert len(table.list_indices()) == 1 + + +def test_fts_exist_ok_matches_quoted_default_name(mem_db): + table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}]) + table.create_index("`body-text`", config=FTS()) + before = table.version + table.create_index("`body-text`", config=FTS(), exist_ok=True) + assert table.version == before + assert len(table.list_indices()) == 1 diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py index 387a89f31..41a688068 100644 --- a/python/python/tests/test_table_signatures.py +++ b/python/python/tests/test_table_signatures.py @@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table): }.items(): assert getattr(config, name) == value assert kwargs == dict( - wait_timeout=timeout, name="custom_idx", replace=False, train=False + wait_timeout=timeout, + name="custom_idx", + replace=False, + train=False, + exist_ok=False, ) diff --git a/python/src/table.rs b/python/src/table.rs index 31cf8d25c..f77ff5a7f 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1628,7 +1628,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index<'a>( self_: PyRef<'a, Self>, column: String, @@ -1637,6 +1638,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1645,6 +1647,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } @@ -1661,7 +1664,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index_async<'a>( self_: PyRef<'a, Self>, column: String, @@ -1670,6 +1674,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1678,6 +1683,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 87eff864d..91c941154 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -220,6 +220,7 @@ pub struct IndexBuilder { pub(crate) index: Index, pub(crate) columns: Vec, pub(crate) replace: bool, + pub(crate) exist_ok: bool, pub(crate) wait_timeout: Option, pub(crate) train: bool, pub(crate) name: Option, @@ -232,6 +233,7 @@ impl IndexBuilder { index, columns, replace: true, + exist_ok: false, train: true, wait_timeout: None, name: None, @@ -324,6 +326,21 @@ impl IndexBuilder { self } + /// Preserve an existing index with the requested name. Defaults to false. + /// This takes precedence over `replace`; a skipped creation does not rebuild. + /// + /// ```no_run + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// table.create_index(&["id"], lancedb::index::Index::Auto) + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Duration of time to wait for asynchronous indexing to complete. If not set, /// `create_index()` will not wait. /// diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f4e5c1e4a..a7cf3f80d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -701,9 +701,13 @@ impl RemoteTable { async fn submit_create_index(&self, mut index: IndexBuilder) -> Result> { self.check_mutable().await?; - let request = self + let mut request = self .client .post(&format!("/v1/table/{}/create_index/", self.identifier)); + if index.exist_ok { + request = request.query(&[("exist_ok", true)]); + index.replace = false; + } let column = match index.columns.len() { 0 => { @@ -18101,6 +18105,42 @@ mod tests { branch.restore().await.unwrap(); } + #[tokio::test] + async fn test_index_exist_ok_query_and_replacement_policy() { + for exist_ok in [false, true] { + for background in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/create_index/" => { + assert_eq!(request.url().query(), exist_ok.then_some("exist_ok=true")); + let body = request_body_json(&request); + assert_eq!( + body.get("replace"), + exist_ok.then_some(&serde_json::Value::Bool(false)) + ); + assert!(body.get("exist_ok").is_none()); + http::Response::builder() + .status(200) + .body("{}".into()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let builder = table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(exist_ok); + if background { + builder.execute_async().await.unwrap().wait().await.unwrap(); + } else { + builder.execute().await.unwrap(); + } + } + } + } + #[tokio::test] async fn test_branch_create_index_carries_branch_in_body() { use lance::dataset::refs::Ref; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4959b2842..ff0ab8b94 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4145,14 +4145,18 @@ impl BaseTable for NativeTable { } async fn create_index(&self, opts: IndexBuilder) -> Result<()> { - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(()); + }; self.build_index(opts, prepared).await } async fn create_index_async(&self, opts: IndexBuilder) -> Result { // Prepare before spawning so bad input is reported by this call rather // than only by the job. - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(Job::new_done()); + }; let table = self.clone(); Ok(Job::spawned(tokio::spawn(async move { table.build_index(opts, prepared).await diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 5f9ae13b4..e0da64029 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -115,14 +115,24 @@ impl NativeTable { pub(super) async fn prepare_index( &self, opts: &crate::index::IndexBuilder, - ) -> Result { + ) -> Result> { + self.dataset.ensure_mutable()?; + let dataset = self.dataset.get().await?; + if opts.exist_ok + && let Some(name) = &opts.name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(None); + } if opts.columns.len() != 1 { return Err(Error::Schema { message: "Multi-column (composite) indices are not yet supported".to_string(), }); } - self.dataset.ensure_mutable()?; - let dataset = self.dataset.get().await?; let (column, field) = if let Index::FTS(params) = &opts.index { let resolved = resolve_lance_fts_field_path(dataset.schema(), &opts.columns[0])?; if params.get_document_granularity().is_list_element() && resolved.list_depth == 0 { @@ -137,9 +147,48 @@ impl NativeTable { } else { Self::resolve_index_field(dataset.schema(), &opts.columns[0])? }; + if let Some(name) = Self::guarded_index_name(opts, &column)? + && dataset + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(None); + } let params = self.make_index_params(&field, opts.index.clone()).await?; let index_type = self.get_index_type_for_field(&field, &opts.index); - Ok((column, params, index_type)) + Ok(Some((column, params, index_type))) + } + + fn guarded_index_name( + opts: &crate::index::IndexBuilder, + column: &str, + ) -> Result> { + let name = if opts.exist_ok { + Some(if let Some(name) = &opts.name { + name.clone() + } else { + let names = lance_core::datatypes::parse_field_path(column)?; + let default_name = if matches!(&opts.index, Index::FTS(_)) + || names.iter().any(|name| name.contains('.')) + { + column.to_string() + } else { + names.join(".") + }; + let suffix = if matches!(&opts.index, Index::FTS(params) if params.get_document_granularity().is_list_element()) + { + "_list_element_idx" + } else { + "_idx" + }; + format!("{default_name}{suffix}") + }) + } else { + None + }; + Ok(name) } /// Builds a prepared index and publishes the new dataset version. @@ -150,16 +199,42 @@ impl NativeTable { ) -> Result<()> { let (column, lance_idx_params, index_type) = prepared; let mut dataset = (*self.dataset.get().await?).clone(); + let guarded_name = Self::guarded_index_name(&opts, &column)?; + if let Some(name) = &guarded_name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(()); + } let columns = [column.as_str()]; let mut builder = dataset .create_index_builder(&columns, index_type, lance_idx_params.as_ref()) .train(opts.train) - .replace(opts.replace); + .replace(opts.replace && !opts.exist_ok); - if let Some(name) = opts.name { + if let Some(name) = guarded_name.clone().or(opts.name) { builder = builder.name(name); } - builder.await?; + if let Err(error) = builder.await { + if let Some(name) = guarded_name { + self.dataset.reload().await?; + if self + .dataset + .get() + .await? + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(()); + } + } + return Err(error.into()); + } // A writer already open was built before this index existed, so it has // to pick it up here or a read needing it is refused until it reopens. self.dataset @@ -568,6 +643,63 @@ mod tests { Ok(FixedSizeListArray::from(data)) } + #[tokio::test] + async fn test_concurrent_index_exist_ok_preserves_single_identity() { + let dir = tempdir().unwrap(); + let db = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("id", Int32, (0..512).collect::>())).unwrap(); + let table = db.create_table("t", batch).execute().await.unwrap(); + let second = db.open_table("t").execute().await.unwrap(); + let (left, right) = tokio::join!( + table + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute(), + second + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute() + ); + left.unwrap(); + right.unwrap(); + table.checkout_latest().await.unwrap(); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices.len(), 1); + let original_uuid = indices[0].uuid; + let version = table.version().await.unwrap(); + table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), version); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices[0].uuid, original_uuid); + } + #[tokio::test] async fn test_create_index() { use std::iter::repeat_with; From d67ec47921ba0b761405b898703725864adb15a2 Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:23:41 -0800 Subject: [PATCH 32/36] docs: make the landing page concise (#4898) Shortens the docs landing page and organizes its overview around database features, with the multimodal data model, ML workflow, SDKs, and PyTorch loader explained in prose. Keeps versioning visible, branching in draft, and the existing `{#architecture}` anchor. Validation: added documentation links and anchors verified; `git diff --check` passes. `mint validate` reports the same four pre-existing missing snippet-export warnings in the reranking and vector-search pages, also reproduced on the unchanged revision. Closes https://linear.app/lancedb/issue/DOC-80/strengthen-what-is-lancedb --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brendan Clement --- docs/web/basics/lance.mdx | 2 +- docs/web/docs.json | 2 +- docs/web/enterprise/deployment/kubernetes.mdx | 2 +- docs/web/enterprise/security.mdx | 2 +- docs/web/index.mdx | 157 +++++------------- docs/web/quickstart.mdx | 6 +- 6 files changed, 51 insertions(+), 120 deletions(-) diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index 84996ffe9..341d36cde 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -76,4 +76,4 @@ boundaries). - [Multimodal data and blobs](/management/table#multimodal): declare `lancedb.blob()` columns and read blobs on demand. - [Table versioning](/management/table#versioning): read and manage table versions. - [Computed columns](/feature-engineering/add-computed-column): add derived features to your data. -- [Architecture](/index#architecture): how LanceDB Embedded and Enterprise build on Lance. +- [Embedded vs Enterprise](/basics/embedded-vs-enterprise): how LanceDB Embedded and Enterprise build on Lance. diff --git a/docs/web/docs.json b/docs/web/docs.json index c20341793..3414fd121 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -81,7 +81,7 @@ }, { "source": "/basics/offerings", - "destination": "/#architecture" + "destination": "/basics/embedded-vs-enterprise" }, { "source": "/enterprise/deployment", diff --git a/docs/web/enterprise/deployment/kubernetes.mdx b/docs/web/enterprise/deployment/kubernetes.mdx index 0133cf065..0c09d7f90 100644 --- a/docs/web/enterprise/deployment/kubernetes.mdx +++ b/docs/web/enterprise/deployment/kubernetes.mdx @@ -10,7 +10,7 @@ keywords: ["kubernetes", "k8s", "aks", "deployment", "helm"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/index#architecture) for what differs between the two. +[Embedded vs Enterprise](/basics/embedded-vs-enterprise) for what differs between the two. The Kubernetes deployment procedure is published with LanceDB Enterprise. See [LanceDB Enterprise](/enterprise#deployment) for the general shape, and diff --git a/docs/web/enterprise/security.mdx b/docs/web/enterprise/security.mdx index 367e71b51..25af04656 100644 --- a/docs/web/enterprise/security.mdx +++ b/docs/web/enterprise/security.mdx @@ -10,7 +10,7 @@ keywords: ["compliance", "security", "soc2", "encryption", "audit"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/index#architecture) for what differs between the two. +[Embedded vs Enterprise](/basics/embedded-vs-enterprise) for what differs between the two. Compliance posture (certifications, data residency, encryption at rest and in transit, audit logging) is a property of a deployment, so it is documented diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 7b6bc6eed..1d451c246 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -6,130 +6,59 @@ icon: "/static/assets/logo/lancedb-icon-gray.svg" keywords: ["multimodal lakehouse", "training", "feature engineering", "search", "open source", "oss"] --- -**LanceDB** is a [multimodal lakehouse](https://lancedb.com/blog/multimodal-lakehouse/) for AI teams that need -one data layer for curation, feature engineering, search and retrieval, and model training. -It is built on top of [Lance](/basics/lance), an open-source lakehouse format designed for multimodal AI data. +LanceDB Enterprise is a distributed multimodal lakehouse for AI. It gives you one data layer for search and +retrieval, curation, feature engineering, and model training. It is built on [Lance](/basics/lance), an open-source +columnar format for multimodal AI data. For the open-source retrieval library that runs inside your application, +see [LanceDB Embedded](/basics/lancedb-embedded). -Move from data exploration to model training on one unified platform without needing to manage a -fragmented stack of storage, feature, retrieval, and training systems. +LanceDB Enterprise depends only on object storage for its primary state, and NVMe/memory for caching in the serving +layer, giving it the latency profile of an in-memory database with the petabyte scalability and cost profile of S3. +It brings these workloads into one system, giving your team one system to become expert in and removing the need +for multiple database systems and synchronization pipelines between them. -## Train on the right data faster {#train-on-the-right-data-faster} +Core features include: -Search, curate, and train at petabyte scale, with all your multimodal data in one table. +- [**SQL**](/basics/sql) powered by Apache DataFusion +- [**Secondary indexes**](/indexing) for vector search, full-text search, and scalar filters +- [**Computed columns**](/feature-engineering/add-computed-column) with on-demand or scheduled refresh +- [**Materialized views**](/feature-engineering/materialized-views) with on-demand or scheduled refresh +- [**Time travel and versioning**](/management/table#versioning) to pin and revisit datasets +- **Search**: [vector](/search/vector-search), [full-text](/search/full-text-search), and + [hybrid](/search/hybrid-search), with [filters](/search/filtering) and [reranking](/reranking) +- [**Functions**](/curation/create-function) for custom transformations and model inference (early access) +- [**Row-level random access**](/basics/lance#capabilities) for retrieval and training +- [**Column additions**](/management/table#schema-add-new-columns) without rewriting existing columns -Preparing training data and running experiments slow down when raw data, metadata, embeddings, features, and governance -artifacts live in separate systems. LanceDB keeps them together in one versioned multimodal table, so AI teams spend less -time stitching infrastructure together and more time improving datasets, testing features, and keeping GPUs fed. +{/* +Draft until branching reaches early access. Add this item to the list above, after Time travel and versioning: +- [**Copy-on-write branching**](/tables/branching) that gives each experiment or agent a writable fork of a table to review before it reaches `main` +*/} -## Accelerate the data flywheel for model research {#accelerate-the-data-flywheel-for-model-research} +LanceDB Enterprise stores images, video, audio, text, embeddings, and metadata in +[schema-enforced tables](/management/table#multimodal). These features let you build +declarative ML data pipelines: ingest raw data and metadata, enrich it incrementally with computed columns and +Functions, and organize it into [curated datasets](/curation) with materialized views. Add features without +rewriting existing columns, then train from those datasets using row-level random access and sampling. -Keep your AI data in one table.{/* Draft until branching reaches early access: restore ", and give each agent-driven experiment its own isolated branch" before the period. */} -Find the failure, fix the data, and retrain. +Connect through [SDKs](/basics/sdk) for Python, TypeScript, and Rust, and use the +[PyTorch data loader](/training/data-loading) for reproducible shuffling and streaming batches. - - - Start from one failed grasp or evaluation example. [Search](/search/) multimodal data, metadata, and embeddings - together, retrieve similar examples, and [curate](/curation) them into a targeted training subset. - - {/* - Draft until branching reaches early access. +## Architecture {#architecture} - - Don't let an agent silently corrupt your data and ruin a training run. Give each agent its own - [branch](/tables/branching), a writable fork of the table, to experiment on, and review the changes before - they reach `main`. See [Run experiments on branches](/agent-branch-experiments). - - */} - - Keep episodes, frames, metadata, features, and embeddings together in one schema-enforced table, without - pipelines to keep them in sync. Table [versions](/management/table#versioning) let you trace each training - run back to the exact data it used. - - - Define the [computed columns](/feature-engineering/add-computed-column) and - [materialized views](/feature-engineering/materialized-views) your experiment needs, such as extracted features - or embeddings, and refresh them as your data changes. On LanceDB Enterprise, column refreshes run as background - jobs on the cluster instead of in your code. - - - Keep GPUs fed. [`StreamingDataset`](/training/data-loading) streams multimodal training data into PyTorch with - globally shuffled, deterministic batches, combining fast random access with high-throughput scans. - - +Queries and feature engineering run across a cluster, with background indexing and maintenance. Deploy +LanceDB Enterprise in your cloud or use a LanceDB-managed deployment. -Use the same table to curate training data, add derived features, retrieve examples, and feed training jobs that rely on expensive GPUs. -Training workloads can sample, shuffle, and scan projected columns from local storage or object storage, then assemble -GPU-ready batches from a tagged dataset version. Training pipelines need curation, derived features, reproducible -splits, fast random access, and a clean path into frameworks such as PyTorch -- LanceDB keeps all of it connected -through the same table model, whether a workflow uses one table or several related ones. - -## Architecture: Embedded and Enterprise {#architecture} - -LanceDB ships as two offerings on the same [Lance](/basics/lance) format and table model, which stores table data, -versions, and indexes in open, columnar files. What changes between them is how storage and compute are organized -around that format: start locally with Embedded, then move to Enterprise when your team needs distributed scale, -managed infrastructure, private deployment, or higher-throughput curation, feature engineering, search and -retrieval, and training workflows. - - - - An open-source, embedded retrieval library that runs inside your application process, with no separate - database server to deploy. - - - A distributed multimodal lakehouse service for production workloads that need managed infrastructure and - higher-throughput workflows. - - - -See [Embedded vs Enterprise](/basics/embedded-vs-enterprise) for a feature-by-feature comparison, including -architecture, latency, throughput, and day-to-day usage differences. +Your application connects to the service through an SDK or [SQL client](/basics/sql). The cluster executes queries, +refreshes derived data, and maintains tables and indexes outside your application. ## Projects using LanceDB {#projects-using-lancedb} -### Training {#training} - -- [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) -- a platform for reproducible world-model - research built on a LanceDB data layer, reporting 3-4x faster data loading on Push-T versus HDF5 / MP4 at a - fraction of the disk footprint. -- [le-wm](https://github.com/lucas-maes/le-wm) -- a joint-embedding predictive world model from pixels, trained on - the stable-worldmodel platform and its LanceDB data layer. -- [lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb) -- a drop-in LanceDB backend for HuggingFace - LeRobot datasets with faster loading across robotics datasets. - -### Agentic applications {#agentic-applications} - -- [OpenClaw LanceDB Plugin](https://docs.openclaw.ai/plugins/memory-lancedb) -- stores an agent's long-term memory - in LanceDB, automatically recalling relevant memories before a model turn and capturing new facts afterward. -- [Cognee](https://github.com/topoteretes/cognee) -- an open-source AI memory platform that gives agents persistent - memory across sessions, using LanceDB as one of its vector store backends. -- [CrewAI](https://github.com/crewAIInc/crewAI) -- a multi-agent framework that - [rebuilt its agent memory on LanceDB](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb). - -Across these projects, LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations, -features, and training or memory access patterns in one format instead of scattering them across task-specific -stores. - -## Start with your workload {#start-with-your-workload} - - - - Create tables, append records, and update or delete rows as your data changes. - - - Use vector search, full-text search, hybrid search, reranking, filtering, and SQL. - - - Profile, sample, chunk, join, and deduplicate records before training on them. - - - Derive computed columns and materialized views without moving data elsewhere. - - - Use LanceDB tables and permutations for projected, shuffled, random-access training reads. - - - Create, list, and drop tables, namespaces, and views from Python, TypeScript, or SQL. - - +Teams use LanceDB for world-model and robotics training, as in +[stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) and +[lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb), and for agent memory, as in +[CrewAI](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb), +[Cognee](https://github.com/topoteretes/cognee), and +[OpenClaw](https://docs.openclaw.ai/plugins/memory-lancedb). +Try out LanceDB using our [quickstart](/quickstart). For help planning an Enterprise deployment +that meets your scale and performance needs, [contact the LanceDB team](https://www.lancedb.com/contact). diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index ef462cbf7..12c9f87ca 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -7,8 +7,10 @@ icon: rocket import { PyConnect, TsConnect, RsConnect, PyConnectObjectStorage, TsConnectObjectStorage, RsConnectObjectStorage, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartCurateSample, PyQuickstartCurateDedupeSetup, PyQuickstartCurateDedupe, PyQuickstartCurateDedupeQuery, PyQuickstartFlattenStats, PyQuickstartAddFeature, PyQuickstartAddFeatureEnterprise, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, RsQuickstartMultimodalBytes } from '/snippets/quickstart.mdx'; -This quickstart uses LanceDB Embedded with a local database and works without an account or API key. -LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. +This quickstart walks you through creating a table, searching your data, and preparing it for training. +By default, it uses LanceDB Embedded with a local database, so no account or API key is required. +To follow along with an existing LanceDB Enterprise deployment, use the +[Enterprise connection instructions](#connect-to-lancedb-enterprise). ## 1\. Install LanceDB {#1-install-lancedb} From 97e62dc11b561db29df24260d158ec9dba1f9a0d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 15:41:33 +0800 Subject: [PATCH 33/36] feat(remote): expose canonical job statistics reports (#5016) Expose `Job::stats()` in Rust and synchronous/asynchronous Python jobs. It reads `POST /v1/jobs/stats` and returns the canonical server-rendered report verbatim, or `None` for a running job or one without a readable durable profile. It does not wait for completion or recompute measurements. On `cc25005525671756b5cf5ebd96492b792e9aa1cb`, all three Rust transport tests and six Python tests passed against the matching rebuilt native extension; strict SDK Clippy also passed. These tests cover optional reports, exact text preservation, fresh reads, errors, and the HTTP boundary with a controlled server. Against the actual Phalanx HTTP route from [Sophon #10247](https://github.com/lancedb/sophon/pull/10247) (`5be3236`), the same native extension also completed two sync and two async reads after durable registry archival, preserving the exact canonical report. This is an HTTP/registry integration fixture, not a Function workload or shared-cluster acceptance. The private runner's JSON field-order collector failed after the successful probe; all raw evidence was retained and hash-verified, and the original receipt was recovered with the corrected parser without rerunning the probe. The follow-up `ad36f66` only corrects the synchronous Python API-reference link to the asynchronous method. Ruff checks and formatting passed; runtime evidence above remains applicable. The actual Phalanx/native-SDK probe covers archived reports; running-job null availability is covered by separate backend and SDK transport tests, not that end-to-end probe. Part of ENT-3501. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/job.py | 41 +++++++++++ python/python/tests/test_job.py | 40 +++++++++++ python/python/tests/test_remote_db.py | 44 ++++++++++++ python/src/job.rs | 5 ++ rust/lancedb/src/job.rs | 28 ++++++++ rust/lancedb/src/remote/job.rs | 97 +++++++++++++++++++++++++++ 7 files changed, 256 insertions(+) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index cbc62f772..1e811d865 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -437,6 +437,7 @@ class Job: async def cancel(self) -> None: ... async def refresh(self) -> None: ... async def timeline(self) -> str: ... + async def stats(self) -> Optional[str]: ... async def events( self, *, diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index bf9605567..9195e01ae 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -425,6 +425,32 @@ class AsyncJob(Generic[T]): description = self._inner._description if self._inner is not None else None return getattr(description, name) if description is not None else None + async def stats(self) -> Optional[str]: + """Return a printable run report for this Function job. + + The report includes recorded phase timings, finishing-supervisor slot + occupancy, all-attempt split execution and batch latency, and accepted-row + throughput. Each call reads the current server report. + Returns ``None`` while the job is running or if no recorded profile is + available, without waiting for completion. Missing measurements remain + unavailable rather than becoming zero. The server formats the report; + the SDK returns it verbatim. + + Requires a server-side Function job and a server supporting run reports. + Local operations and SQL query handles do not support this operation. + Unsupported operations raise ``NotImplementedError`` or a server error. + This method returns text; use ``print`` to display it. + + Examples + -------- + >>> print(await job.stats()) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job statistics require a server-side Function job" + ) + return await self._inner.stats() + async def export_timeline(self, path: str | PathLike[str]) -> None: """Write a fresh recorded Function job timeline as Chrome trace JSON. @@ -649,6 +675,21 @@ class Job(Generic[T]): def _field(self, name: str) -> Optional[Any]: return getattr(self._inner, name) if self._inner is not None else None + def stats(self) -> Optional[str]: + """Return a printable Function job run report. + + See [AsyncJob.stats][lancedb.job.AsyncJob.stats] for metrics and availability. + + Examples + -------- + >>> print(job.stats()) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job statistics require a server-side Function job" + ) + return LOOP.run(self._inner.stats()) + def export_timeline(self, path: str | PathLike[str]) -> None: """Write Chrome trace JSON for this Function job. diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 690f6414b..9897d97b5 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -754,6 +754,46 @@ async def test_query_wait_timeout_requires_keeping_original_handle(): assert "db.open_job" not in message +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stats_returns_fresh_report_without_waiting_or_printing(sync, capsys): + reports = [ + None, + "Function job: finished\nWorker utilization: unavailable\n", + "Function job: finished\nWorker utilization: 25.0%\n", + ] + inner = SimpleNamespace( + stats=AsyncMock(side_effect=reports), + wait=AsyncMock(), + cancel=AsyncMock(), + ) + job = AsyncJob(inner) + for expected in reports: + actual = await asyncio.to_thread(Job(job).stats) if sync else await job.stats() + assert actual == expected + inner.wait.assert_not_awaited() + inner.cancel.assert_not_awaited() + assert capsys.readouterr().out == "" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stats_preserves_errors_and_rejects_untracked_jobs(sync): + error = RuntimeError("run reports are unavailable on this server") + job = AsyncJob(SimpleNamespace(stats=AsyncMock(side_effect=error))) + with pytest.raises(RuntimeError) as exc: + if sync: + await asyncio.to_thread(Job(job).stats) + else: + await job.stats() + assert exc.value is error + with pytest.raises(NotImplementedError, match="server-side Function job"): + if sync: + Job(None).stats() + else: + await AsyncJob(None).stats() + + @pytest.mark.asyncio @pytest.mark.parametrize("sync", [False, True]) async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ea7f73c71..b38ae4a5b 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2732,6 +2732,50 @@ async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync): assert exc.value.__cause__.is_transport_error is True +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_remote_job_stats_returns_native_optional_report(sync): + report = "Function job: finished\nWorker utilization: unavailable\n" + paths = [] + + def handler(request): + payload = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert payload == {"job_id": "refresh-1"} + paths.append(request.path) + if request.path == "/v1/jobs/describe": + response = { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "IN_PROGRESS", + "creation_ms": 1000, + } + elif request.path == "/v1/jobs/stats": + available = paths.count("/v1/jobs/stats") > 1 + response = { + "job_id": "refresh-1", + "profile": {"future_field": True} if available else None, + "report": report if available else None, + } + else: + raise AssertionError(f"unexpected request: {request.path}") + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + assert job.stats() is None + assert job.stats() == report + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + assert await job.stats() is None + assert await job.stats() == report + assert paths == ["/v1/jobs/describe", "/v1/jobs/stats", "/v1/jobs/stats"] + + @pytest.mark.asyncio @pytest.mark.parametrize("sync", [False, True]) @pytest.mark.parametrize( diff --git a/python/src/job.rs b/python/src/job.rs index 0d411072f..08f6440ab 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -159,6 +159,11 @@ impl Job { }) } + pub fn stats(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { inner.stats().await.infer_error() }) + } + #[pyo3(signature = (*, limit=None, filter=None))] pub fn events( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 092ece8b5..b1e3c1bbf 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -90,6 +90,11 @@ pub(crate) trait JobHandle: Send + Sync { job_detail_not_supported("job timeline export") } + /// A printable report of recorded Function job metrics. + async fn stats(&self) -> Result> { + job_detail_not_supported("job statistics") + } + /// The job's recorded lifecycle events. async fn events(&self, _request: JobEventsRequest) -> Result> { job_detail_not_supported("job event history") @@ -531,6 +536,29 @@ where } } + /// Fetch a printable run report for a server-side Function job. + /// + /// The server report includes recorded phase timings, finishing-supervisor + /// slot occupancy, all-attempt split execution and batch latency, and + /// accepted-row throughput. Returns `None` for running jobs or when no recorded + /// profile is available, without waiting for completion. Requires server + /// support; local operations and SQL query handles do not support reports. + /// + /// ```no_run + /// # async fn report(job: &lancedb::job::Job) -> Result<(), Box> { + /// if let Some(report) = job.stats().await? { + /// println!("{report}"); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn stats(&self) -> Result> { + match &self.inner { + JobInner::Handle { handle, .. } => handle.stats().await, + JobInner::Completed(_) => job_detail_not_supported("job statistics"), + } + } + /// Waits until the operation reaches a terminal state. /// /// Returns the endpoint's typed result. Unit-result jobs return `()`. diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 5a0afa7e8..c546ce4d1 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -261,6 +261,35 @@ impl JobHandle for RemoteJob { Ok(trace) } + async fn stats(&self) -> Result> { + let request = self + .client + .post("/v1/jobs/stats") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let response: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse job statistics: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if response.get("job_id").and_then(serde_json::Value::as_str) == Some(self.job_id.as_str()) + { + match response.get("report") { + Some(serde_json::Value::Null) => return Ok(None), + Some(serde_json::Value::String(report)) => return Ok(Some(report.clone())), + _ => {} + } + } + Err(Error::Http { + source: "server response is not a Function job run report; job statistics require server support".into(), + request_id, + status_code: None, + }) + } + async fn events(&self, request: JobEventsRequest) -> Result> { let mut body = serde_json::json!({ "job_id": self.job_id }); if let Some(limit) = request.limit { @@ -354,6 +383,74 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + #[tokio::test] + async fn stats_reads_report_verbatim_and_preserves_unavailable_without_waiting() { + let requests = Arc::new(AtomicUsize::new(0)); + let seen = requests.clone(); + let report = "Function job: finished\nWorker utilization: unavailable\n"; + let client = client_with_handler(move |request| { + assert_eq!(request.method(), reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/jobs/stats"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body, serde_json::json!({"job_id":"job-1"})); + let response = if seen.fetch_add(1, Ordering::SeqCst) == 0 { + serde_json::json!({"job_id":"job-1","profile":null,"report":null}) + } else { + serde_json::json!({"job_id":"job-1","profile":{"future_field":17},"report":report}) + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".to_string()))); + assert_eq!(job.stats().await.unwrap(), None); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert_eq!(job.stats().await.unwrap().as_deref(), Some(report)); + assert_eq!(requests.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn stats_rejects_malformed_or_unrelated_responses() { + for body in [ + "{", + r#"{"job_id":"job-1"}"#, + r#"{"job_id":"job-1","report":7}"#, + r#"{"job_id":"another-job","report":"a report"}"#, + ] { + let client = client_with_handler(move |_| { + http::Response::builder().status(200).body(body).unwrap() + }); + let error = RemoteJob::new(client, "job-1".to_string()) + .stats() + .await + .unwrap_err(); + assert!(matches!(error, crate::Error::Http { .. })); + assert!(error.to_string().contains("job statistics")); + } + } + + #[tokio::test] + async fn stats_preserves_not_found_errors() { + let client = client_with_handler(|_| { + http::Response::builder() + .status(404) + .body("job not found") + .unwrap() + }); + let error = RemoteJob::new(client, "missing".to_string()) + .stats() + .await + .unwrap_err(); + match error { + crate::Error::Http { status_code, .. } => { + assert_eq!(status_code, Some(reqwest::StatusCode::NOT_FOUND)); + } + other => panic!("expected HTTP 404, got {other:?}"), + } + } + struct FixtureRemoteJob(&'static str); #[async_trait] From dd449978d9c43a286ae7bf739301be34827125c4 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 14 Nov 2026 01:09:40 -0800 Subject: [PATCH 34/36] docs: clarify Function workflows and search contracts Clarify Function signatures, refresh and recovery workflows, job snapshots, FTS operators, and IVF deduplication limits. --- .agents/skills/lancedb-vector-dedup/SKILL.md | 63 ++++++++ docs/web/basics/jobs.mdx | 73 +++++++++ docs/web/curation/create-function.mdx | 61 ++++++- docs/web/curation/dedupe.mdx | 58 ++++++- docs/web/docs.json | 1 + .../add-computed-column.mdx | 7 + .../materialized-views.mdx | 24 +++ .../feature-engineering/refresh-column.mdx | 119 ++++++++++++++ docs/web/management/function-failures.mdx | 151 ++++++++++++++++++ docs/web/management/function.mdx | 44 +++++ docs/web/search/full-text-search.mdx | 57 +++++++ docs/web/sql/dql/dedupe.mdx | 9 ++ docs/web/sql/dql/duplicate-pairs.mdx | 6 + docs/web/sql/dql/fts.mdx | 63 +++++++- 14 files changed, 725 insertions(+), 11 deletions(-) create mode 100644 .agents/skills/lancedb-vector-dedup/SKILL.md create mode 100644 docs/web/management/function-failures.mdx diff --git a/.agents/skills/lancedb-vector-dedup/SKILL.md b/.agents/skills/lancedb-vector-dedup/SKILL.md new file mode 100644 index 000000000..1221e4061 --- /dev/null +++ b/.agents/skills/lancedb-vector-dedup/SKILL.md @@ -0,0 +1,63 @@ +--- +name: lancedb-vector-dedup +description: Plan and run Enterprise IVF vector deduplication with dedupe and duplicate_pairs, including sampling, index coverage, recall and resource limits. Use for near-duplicate embedding or perceptual-hash records; use MinHash guidance for text shingles. +--- + +# Vector deduplication + +Read the maintained [workflow](../../../docs/web/curation/dedupe.mdx), +[DEDUPE reference](../../../docs/web/sql/dql/dedupe.mdx) and +[DUPLICATE_PAIRS reference](../../../docs/web/sql/dql/duplicate-pairs.mdx) +before constructing SQL. In a source checkout these paths are relative to this +skill directory. When using an installed copy without the docs, read +`https://docs.lancedb.com/curation/dedupe` and the linked SQL references. + +## Establish the comparison contract + +- Confirm an Enterprise deployment that supports these table functions. Use + `dedupe` and `duplicate_pairs`; legacy `vector_dedup` names are rejected. +- Inspect the vector type, metric, compatible index, indexed fragments and + source version. Wait for index coverage after writes. Do not run a full + scan over unindexed fragments or silently change the index to make it run. +- Explain that candidates are compared only within physical IVF partitions + and segments. Encoded/quantized distances are not an exact raw-vector + comparison. L2 thresholds are squared distances; Hamming counts bits. +- Use `id_column` on pair queries for business IDs. Retain `dataset_version`, + segment and partition identities. Do not decode internal row IDs or assume + that representatives stay the same after later data/index changes. + +## Bound the first experiment + +Use a reproducible partition sample before a full scan: + +```sql +SELECT id_a, id_b, distance, dataset_version, segment_id, partition_id +FROM duplicate_pairs( + 'frames', 'embedding', + distance_threshold => 0.02, + id_column => 'frame_id', + selection => 'random', count => 10, seed => 42 +) +``` + +Adapt the threshold and sample size to the metric and actual partition count. +Sampling partitions is not uniform sampling of rows. Inspect known duplicate +and distinct examples, pair density, partition skew, memory, spill space and +elapsed time. Do not infer global recall or ten-billion-row qualification +from a small or unversioned benchmark. Pair work and output can be quadratic +within a partition; an outer SQL `LIMIT` is not an upstream work budget. + +## Choose the result + +`dedupe` returns original representative rows and always scans all partitions. +Use its default `connected_components` for transitive groups; choose +`direct_representative` when chains should not merge transitively. It does not +accept `id_column`, `selection`, `count` or `seed`; `duplicate_pairs` does not +accept `resolution`. + +Keep pair data on the server when possible; avoid collecting an unbounded +edge set in client memory. Persist a new table/view only within the user's +authorized scope, preserving source rows unless deletion was requested. +Do not register a Python Function or fetch/rewrite Blob payloads to invoke +these built-in table functions. For MinHash/text deduplication, follow the +separate `https://docs.lancedb.com/enterprise/sql-minhash` workflow. diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 47285f5d0..264acd728 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -33,6 +33,46 @@ print(job.status()) ``` +## Cached properties and live calls {#snapshots} + +Python job properties describe the last observation; reading them does not +contact the server. Submission need not fetch the full registry record, so +some properties can initially be `None`. + +| Surface | Contract | +| --- | --- | +| `state` | Last observed lifecycle state. It does not update on its own. | +| `job_type`, `creation_ms` | Cached job kind and creation time in epoch milliseconds. | +| `spec` | Complete, job-specific submitted specification. Read this separately from the bounded `repr(job)` display. | +| `result` | Cached, job-specific reported data; it is not necessarily the typed object returned by `wait()`. | +| `failure` | Cached `JobFailureInfo`, when the server reports a terminal failure. | +| `status()` | Live lifecycle request. For registry jobs it also caches the full record. A failed state is returned without raising a job-failure exception; request errors can still raise. | +| `refresh()` | Fetch and cache the current record without waiting for completion. | +| `events(...)` | Separate live request returning a `pyarrow.Table` of recorded events; it does not refresh the properties. | +| `wait(...)` | Poll until completion and return the operation's typed result, or raise on failure/cancellation. Refresh afterward when you need the complete final registry record. | + +For example, poll a registry handle and then retrieve its final details: + +```python +import time + +state = job.status() +while state == "running": + print(job.state) + time.sleep(2) + state = job.status() + +result = job.wait() +job.refresh() +print(result) +print(job.spec) +``` + +The four lifecycle strings below are the usual SDK contract; newer server +states may pass through an older client. Do not infer execution progress from +`state` alone. Structured progress methods and queue fields require matching +SDK/server support; see [refresh admission](/feature-engineering/refresh-column#admission). + ## Submit and wait for a job {#waiting} 1. **Submit the operation.** Keep the returned job handle. For an Enterprise @@ -133,6 +173,39 @@ for info in db.list_jobs(page_limit=50): ``` +`list_jobs` yields `JobInfo` summaries, newest creation time first, rather than +live `Job` handles. Open an ID to inspect its full record. `page_limit` bounds +each server request, not the total yielded items, and `page_token` resumes a +listing. It is a lazy iterator: iteration performs requests and can raise +request errors. To materialize it, use `list(db.list_jobs(...))`; it does not +support list indexing, `len()`, or a `.to_list()` method. + +`Listing.num_page_results()` reports cached items remaining in the current +page and `Listing.page_token()` reports the next request's token. Drain the +cached items before saving that token, or resuming can skip them. A `None` +token after the final page can coexist with unread cached items. A resumed +listing is not a transactionally frozen view of jobs submitted in the meantime. + +`events.schema` describes the Arrow response. Use `events.to_pylist()` for +Python row dictionaries. Common event columns are `event_seq` (int64), `state` +(string), `updated_at_millis` (int64), `updated_by` (string), and nullable +`emitted_from`, `emitted_by` and `claim_entity` strings. Optional uint64 work +counters such as `rows_processed` and diagnostic details depend on job type +and server version. If a `payload` column is returned, its value is a nullable +JSON string, not an already decoded Python dictionary. +Empty results retain their schema. Events are newest first and belong to the +requested job; child events are separate. An event count is not a completed-row +count, and a running job can have no terminal `result` while producing events. + +For a Function refresh, `wait()` returns a `RefreshColumnResult` such as +`rows_assigned`, `rows_failed`, `rows_remaining`, `source_version` and optional +`published_version`. Other job types have different results. Do not parse the +printed representation to recover a spec, result or progress measurement. +For object-shaped registry data, `job.spec` and `job.result` are decoded Python +dictionaries: access fields with keys, such as `job.result.get("summary")` +after refreshing a successful Function job. The separate typed object from +`wait()` uses attributes, such as `result.rows_assigned`. + Event responses have [row limits](/basics/limits#jobs). An explicit limit can request more than the default, but it does not guarantee a complete event history. diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 111eaf13f..9ee7d572a 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -44,6 +44,58 @@ table.add_columns({"doubled": version(value=col("value"))}) immutable version, so changing one produces a new version rather than altering rows a previous version already filled. +## Supported Function signatures {#signature-types} + +A table's [Arrow schema](/sql/data-types#supported) can contain types that a +Function cannot accept or return. The matrix below describes the Python SDK +`0.42.0-beta.12` source contract. Nested schemas and list-Blob outputs require +a matching Enterprise server; an SDK upgrade alone does not enable them. + +| Arrow type | Function input/output support | +| --- | --- | +| Boolean; signed/unsigned 8, 16, 32, 64-bit integers; float16/32/64 | Supported. Ordinary `int` and `float` annotations infer int64 and float64. | +| utf8 / large_utf8; binary / large_binary | Supported. `str` and `bytes` infer utf8 and binary. Plain binary does not carry Blob semantics. | +| date32 / date64 | Supported; Python `date` infers date32. | +| timestamp, with or without timezone; time32/64; duration; interval | Unsupported by the Function signature grammar. A Python `datetime` annotation can resolve to an Arrow timestamp but registration still rejects it. | +| decimal; map; dictionary; union; fixed-size binary | Unsupported. Decode dictionary values and use supported scalar/list/struct representations. | +| struct; list / large_list; positive-length fixed-size list | Supported with supported children. Explicit schemas preserve child nullability; annotation-only `list[T]` uses non-nullable elements. Struct fields must be nonempty and uniquely named. | +| Blob v2 at top level or in a struct | Supported in inputs and outputs; use `lancedb.blob(...)` in the schema. | +| Blob v2 under list / large_list | Output only on supporting SDK/server versions. Inputs are rejected. | +| Blob v2 under fixed-size list or map | Unsupported in both directions. | + +For times, pass an int64 epoch value with an explicit unit such as microseconds, +or a UTF-8 ISO 8601 string with its timezone. Convert inside the Function and +cast the result in SQL if needed. Use scaled integers with a declared scale +when exact decimal values matter; converting to float can lose precision. +Represent a map as a list of key/value structs when that fits the calculation. + +A scalar output is non-nullable because physical NULL represents an unfilled +computed output. For an optional value, return a named struct with a nullable +field, for example: + +```python +import pyarrow as pa +from lancedb import function + +@function( + input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]), + output_schema=pa.schema([pa.field("score", pa.float64(), nullable=True)]), +) +def optional_score(text: str): + return {"score": float(len(text)) if text else None} +``` + +Return a dictionary by field name. A successfully computed nullable field can +be NULL; `score IS NULL` alone cannot distinguish it from pending work or a +skipped failure. Use the job result and error diagnostics. Do not assume an +explicit assignment-state flag is available on every deployment. + +List-nested Blob outputs are queryable as descriptors, but row-ID blob fetch +APIs and `blob_mode="bytes"` do not fetch payloads inside lists. Prefer a +separate row per media item when you need independent reads, retries or +re-scoring. A plain struct shaped like a Blob without its extension metadata +is not a substitute for `lancedb.blob`. + ## Batch: once per call, many rows at a time {#batch} A function is called once per batch instead of once per row when its @@ -170,9 +222,12 @@ in the function's source. A Secret is a database-scoped named credential: puts it in the environment variable the function reads, without ever returning it from any API or recording it in the function's own definition. Combine it with the stateful form so the HTTP client -- and any rate limiter -around it -- is built once, not reopened on every row. There is no built-in -retry or per-row error-skip policy -- a function that calls a flaky service -should handle timeouts and retries itself, inside `__call__`. +around it -- is built once, not reopened on every row. Configure HTTP timeouts +inside `__call__`. Refresh-level `error_policy='skip'` can record row failures; +see [handling failures](/management/function#failures). Native retry policies +need matching SDK, server and Function-image support; on other deployments, +handle bounded retries inside the Function only when repeating the request is +safe. See [Vend a Secret to a Function](/curation/vend-secret#specify) for the full worked example, how the bound value actually reaches a running diff --git a/docs/web/curation/dedupe.mdx b/docs/web/curation/dedupe.mdx index 470e170c2..2e90bc231 100644 --- a/docs/web/curation/dedupe.mdx +++ b/docs/web/curation/dedupe.mdx @@ -136,12 +136,60 @@ SELECT * FROM dedupe( See [Refresh a materialized view](/feature-engineering/refresh-materialized-view) for manual and automatic refresh options to keep it current as new records land. -## At production scale {#production} +## Index, snapshot and recall limits {#limits} -[LeRobotDataset](/integrations/lerobotdataset) runs the same `dedupe` -call over 27.6 million real embedding rows to remove near-static frames from a -robotics training set in under 30 seconds -- the mechanism does not change -with scale, only the table it runs against. +These are Enterprise SQL table functions, not standard SQL or a registered +Python Function. They require one compatible current vector index covering +the scanned snapshot. Wait for indexing to finish after ingestion and inspect +index coverage before running a full scan. Unindexed fragments are rejected; +deleted rows are excluded at the pinned dataset version. + +The scan compares candidates **within each physical IVF partition and index +segment**. It does not compare across partitions or segments. Scanning every +partition therefore does not establish global all-pairs recall. Quantized +indexes compare their encoded vector representations; `IVF_FLAT` compares the +stored vectors. Thresholds must match the index's metric: L2 is squared L2, +cosine is `1 - cosine`, dot distance is `1 - dot`, and Hamming counts differing +bits. Inspect close examples and known duplicates before choosing a threshold. + +`duplicate_pairs` reports `dataset_version`, `segment_id` and `partition_id`. +Retain those with the index configuration and source version when comparing +runs. Pass `id_column` for application IDs, rather than treating physical row +addresses as durable identifiers. A new append, index change or bridge between +components can change groups and representatives. + +## Efficient use and scale qualification {#production} + +Start with [`duplicate_pairs` partition sampling](/sql/dql/duplicate-pairs#sampling), +using a recorded seed and a bounded partition count. Inspect pair density and +threshold quality before running `dedupe`, which always scans every partition. +Sampling partitions is not uniform row sampling and can miss rare groups. +`resolution='connected_components'` merges transitive chains; +`direct_representative` uses direct representative relationships instead. + +Pair work grows quadratically within dense partitions, and a loose threshold +can emit a quadratic number of edges. An outer `LIMIT` is not a resource +budget for upstream pair finding or group resolution. Avoid repeatedly +materializing all pairs in a Python list; select needed columns, aggregate on +the server, and persist a reviewed result when repeated reads justify it. +Measure peak memory, spill storage, elapsed time and pair count on +representative partitions before increasing scope. + +The [LeRobotDataset integration](/integrations/lerobotdataset) illustrates a +27.6-million-row data workflow. Its timings are not a versioned qualification +of this deduplication path on arbitrary indexes or hardware. A 10-billion-row +run is not qualified by that example. Qualify source/index versions, partition +sizes, metric, threshold, worker resources, spill limits and correctness on your +deployment before extrapolating. There is no universal row-count or latency +guarantee in this guide. + +For text shingles and MinHash signatures, use the distinct +[MinHash workflow](/enterprise/sql-minhash). Vector distance deduplication and +MinHash/Jaccard text deduplication have different indexes and thresholds. + +Agents can follow the repository's +[vector deduplication skill](https://github.com/lancedb/lancedb/blob/main/.agents/skills/lancedb-vector-dedup/SKILL.md) +to apply these checks without inventing Function options or scale guarantees. ## Continue with the curated data {#next} diff --git a/docs/web/docs.json b/docs/web/docs.json index 3414fd121..c586d4f62 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -496,6 +496,7 @@ "management/materialized-view", "management/secret", "management/function", + "management/function-failures", "management/storage-integration" ] }, diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 851b37d9b..7cc9f6988 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -13,6 +13,13 @@ import { PySchemaAddSetup, } from '/snippets/tables.mdx'; + +Declare computed columns on ordinary tables. A materialized view derives its +schema from its query; include the calculation in the view's `SELECT` instead +of attaching a Function with `add_columns`. See +[materialized-view schema changes](/feature-engineering/materialized-views#schema-changes). + + Lance can write a new column without rewriting the columns already in the table. That matters most on a table that also holds large images, video or embeddings, where rewriting everything just to add one small derived field diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 617eb7525..ccfd8429d 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -176,6 +176,30 @@ definition is read with `await view.definition()`. Creation, refresh and drop also have async, job-returning SDK methods; see [Materialized view](/management/materialized-view#manage). +## Add derived values to a view {#schema-changes} + +A materialized view's output schema belongs to its defining `SELECT`. Do not +use `view.table.add_columns(...)` to attach another computed or Function column +to that output. In particular, adding a Function binding is rejected: the +column would not be produced by the next view refresh. + +Choose where the calculation belongs: + +- Include the expression or Function call in the view's `SELECT`, as in the + [caption example](#functions). To change an existing definition, create a + replacement view under a new name, check its results, indexes and grants, + and move readers to it before dropping the old view. +- Add a Function column to the ordinary source table, refresh it, then select + that stored column in a view. This lets you manage column refresh separately + from view refresh. +- Create an ordinary table from a query when you need independently editable + outputs. That table is a snapshot; it does not inherit the view's refresh + relationship to the source. + +Opening the underlying table gives access to reads and indexes; it does not +make independent schema changes part of the materialized-view definition. +Changing automatic-refresh settings also does not change that definition. + ## Related guides {#next} diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 1b809b91d..d82fb1eef 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -77,6 +77,11 @@ catch-up works when it's re-enabled after being off. ## Refreshing part of a table {#partial} +Python `where=` requires a supporting SDK, such as `0.42.0b9`, and an +Enterprise server with filtered refresh support. Stable `0.41.0` does not +accept this argument. The SQL form is available independently of that Python +argument on supporting servers. + Enterprise A refresh can be scoped to a predicate, with `where=` in Python or `WHERE` in SQL, which is useful for filling a slice first and checking it before committing to the whole table: @@ -123,6 +128,89 @@ to let LanceDB track which outputs need updating. `function_refresh` for one filled by a registered [function](/management/function). +### Re-score selected list elements {#list-elements} + +`WHERE` selects **rows**, not elements within a list. Refreshing a row that +contains ten answers passes the whole list to the Function. A mask can control +which elements your code computes, but the Function still returns one complete +list for that row. There is no element-level refresh or partial-list write API. + +This example keeps `sample_id` as the link to an existing `samples` table with +a Blob column named `media`. It creates only answer metadata and scores; it +neither reads nor copies Blob payloads. Run it on a deployment supporting +`@function`, list signatures and Python `where=`, with `samples` already +containing sample IDs `s1` and `s2`. + +```python +from lancedb import col, function + +media_before = db.execute_query( + "SELECT sample_id, media FROM samples " + "WHERE sample_id IN ('s1', 's2') ORDER BY sample_id" +).read_all().to_pylist() + +answers = db.create_table("answer_rescore_demo", [ + {"group_id": "g1", "sample_id": "s1", + "answers": ["yes", "maybe", "no"], + "selected": [False, True, False], "previous": [0.1, 0.2, 0.3]}, + {"group_id": "g1", "sample_id": "s2", + "answers": ["other"], "selected": [False], "previous": [0.4]}, +]) + +@function +def rescore_masked( + answers: list[str], selected: list[bool], previous: list[float] +) -> list[float]: + if not (len(answers) == len(selected) == len(previous)): + raise ValueError("answers, selected and previous must have equal lengths") + return [ + float(len(answer)) if choose else old + for answer, choose, old in zip(answers, selected, previous) + ] + +version = db.create_function(rescore_masked) +answers.add_columns( + {"rescored": version( + answers=col("answers"), selected=col("selected"), previous=col("previous") + )}, + auto_refresh_enabled=False, +) +job = answers.refresh_column_async("rescored", where="sample_id = 's1'") +job.wait() + +rows = answers.search().select( + ["group_id", "sample_id", "previous", "rescored"] +).to_list() +by_sample = {row["sample_id"]: row for row in rows} +assert by_sample["s1"]["group_id"] == "g1" +assert by_sample["s1"]["rescored"] == [0.1, 5.0, 0.3] +assert by_sample["s1"]["previous"] == [0.1, 0.2, 0.3] +assert by_sample["s2"]["rescored"] is None +assert by_sample["s2"]["previous"] == [0.4] + +media_after = db.execute_query( + "SELECT sample_id, media FROM samples " + "WHERE sample_id IN ('s1', 's2') ORDER BY sample_id" +).read_all().to_pylist() +assert media_after == media_before +``` + +Here length is a deterministic stand-in for a scorer. Only `"maybe"` is scored; +the other scores are copied from `previous`. The final equality checks Blob +descriptors on an otherwise unchanged source table, without fetching payloads. +Keep the source table unchanged during this comparison. Use the same model, +normalization and score type as the original computation in a real re-scoring +pass. For another pass, explicitly supply the intended prior scores and mask; +refresh does not merge the previous output into your Function's inputs. + +If answers need independent retries or versions, prefer one ordinary table row +per answer, with `group_id`, `sample_id`, a stable application `answer_id`, +answer text and score. Keep media in `samples` and join by `sample_id` when +needed. A row predicate can then select exact answer IDs, and Blob storage +stays in the source table. Do not use `UNNEST` to assume that nested Blob values +become supported Function inputs; see the +[nested-Blob limits](/curation/create-function#signature-types). + ## Run a refresh on Enterprise {#async} Enterprise @@ -212,6 +300,31 @@ The wait helpers do not submit or cancel a refresh. They retry only the typed finalization-pending response and propagate other errors. */} +### Admission and waiting {#admission} + +Submission does not reserve a supervisor or GPU immediately. A refresh can wait +for source preparation/compaction, an earlier refresh, executor admission or +worker capacity. A lifecycle `running` value from `status()` alone does not +prove that Python code has begun executing. + +Use [`SHOW JOBS`](/sql/ddl/job#show) and the Console's job detail to inspect +available phase and row progress. On SDK/server versions with `job.progress()`, +the snapshot can also include `phase`, `queue_reason`, timestamps and row +counters. These optional fields are version-dependent; missing values are +unknown, not zero progress or an ETA. `creation_ms` is submission time, not +worker start time. `DESCRIBE JOB` provides the finished run report, rather than +a live queue-position API. + +Limits are deployment settings: the Agent dispatcher concurrency, executor +capacity, per-table automatic-refresh limit and Function-call +`max_concurrency` control different things. There is no universal five-refresh +limit per database. Ask your administrator for the effective settings and use +the [Enterprise operations guide](/enterprise/function-operations#admission) +for their configuration names. Repeated cancellation and resubmission does not +bypass those limits. Cancellation requests a stop, including while queued; +observe a terminal state before submitting replacement work. Committed work +is not rolled back. + ### Configure workers and resources {#resources} SQL exposes the worker budget directly, which is the lever when a backfill is @@ -229,6 +342,12 @@ up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not per-worker allocations or a guaranteed worker count. `num_workers` is only accepted for SQL-expression columns; registered Function columns reject it. +In particular, `gpu_count = 2` does not request two devices inside one Python +process or enable tensor parallelism. Inspect configured GPU classes and their +per-worker limits with `db.list_gpu_classes()` or `SHOW GPU CLASSES`. Choose a +model that fits the worker shape supported by your deployment; see +[GPU placement and budgets](/enterprise/function-operations#gpu). + The SDKs accept the same nested budget. CPU and memory are required; the GPU count inside the budget defaults to zero, so a CPU-only Function can omit it: diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx new file mode 100644 index 000000000..4546129fa --- /dev/null +++ b/docs/web/management/function-failures.mdx @@ -0,0 +1,151 @@ +--- +title: "Handle Function failures" +sidebarTitle: "Function Failures" +description: "Keep usable outputs, inspect row errors, retry by stable identity and isolate inputs that need attention." +tag: "Early access" +availability: + embedded: unavailable + enterprise: available +--- + +A Function refresh can encounter a bad row, fail to initialize a model, lose +a worker, or fail while publishing results. These need different remedies. +This guide uses the existing [refresh error policy](/sql/dml/refresh-column#options) +and Python error records; it does not require a new retry or quarantine API. + +## Choose a row-error policy {#policy} + +The default `fail` stops the job on a row error. `skip` writes null outputs for +failed rows and records errors, subject to the refresh's failure limits: + +```python +job = table.refresh_column_async( + "embedding", + error_policy="skip", + max_failed_rows=100, + max_failed_fraction=0.1, +) +result = job.wait() +print(result.rows_assigned, result.rows_failed, result.rows_remaining) +``` + +Choose limits for your workload; these example limits stop work when more +than 100 rows or more than 10% fail. `skip` does not make initialization, +infrastructure or publication failures successful. If `wait()` raises, +[refresh the job record](/basics/jobs#snapshots), inspect `job.failure`, and +inspect any recorded row errors. A failed/cancelled job can have committed +some output, but retention of every successful call is not guaranteed. +External effects are not rolled back and can be repeated during recovery. + +## Inspect and group recorded errors {#inspect} + +Scope diagnostics to the job you are investigating: + +```python +from collections import Counter + +errors = table.function_errors(job_id=job.id, column="embedding", limit=10000) +groups = Counter((r.error_type, r.error_message) for r in errors.records) +for cause, count in groups.most_common(): + print(count, cause) +for fragment in errors.fragments: + print(fragment.fragment_id, fragment.rows_skipped, fragment.rows_recorded) +print("listing truncated:", errors.truncated) +``` + +Each record includes the Function name/version, table version, error type and +message, creation time, and available row identities. `attempts` and traceback +details depend on the server/image version. This client-side grouping counts +only returned detail records. `truncated=True` or fragment summaries with +more skipped than recorded rows mean it is incomplete; do not label it a full +error census. See [`SHOW ERRORS`](/sql/ddl/job#errors) for SQL and its limits. + +Records are historical observations, not a deduplicated list of currently +failed rows. Reading errors without `job_id` can include older attempts that +have since succeeded. A null output can mean unfilled, skipped, or a computed +nullable field; output nullness alone is not a current-error test. + +## Retry exactly identified rows {#retry} + +On tables with stable row IDs, supporting server/SDK versions return +`record.row_id` from the refresh's pinned source version. Keep that table and +branch identity with the records. Compaction can move physical addresses, so +do not derive a row ID from fragment numbers or offsets. + +The following deliberately refuses incomplete or unidentified error sets. +Review historical records against the current inputs before using them as a +retry selection. Keep this selection small enough for a SQL predicate. + +```python +if errors.truncated or any(f.rows_skipped > f.rows_recorded for f in errors.fragments): + raise RuntimeError("Inspect a narrower job/error set before selecting retries") +if any(r.row_id is None for r in errors.records): + raise RuntimeError("This workflow requires stable row IDs in every error record") + +row_ids = sorted({int(r.row_id) for r in errors.records}) +if row_ids: + predicate = "_rowid IN (" + ", ".join(map(str, row_ids)) + ")" + retry_job = table.refresh_column_async("embedding", where=predicate) + retry_job.wait() +``` + +This recomputes every selected live row with the existing binding. It can +repeat a row already repaired since the error was recorded. Inspect the retry +job and its errors afterward; an older record need not disappear. On tables +without stable row IDs, resolve errors to application keys at the recorded +snapshot before retrying. Do not substitute `_rowaddr` after a rewrite. +Python `where=` requires a supporting SDK such as `0.42.0b9`, not stable +`0.41.0`, plus a matching server. + +## Repair with a newer Function {#new-version} + +Registering a new version does not change an existing column's immutable +binding. To evaluate a fix while retaining old outputs, register the corrected +callable and declare a separate output column. For example, with a corrected +`embed_fixed` callable already defined and a `text` input column: + +```python +from lancedb import col + +fixed = db.create_function(embed_fixed) +table.add_columns( + {"embedding_repaired": fixed(text=col("text"))}, + auto_refresh_enabled=False, +) +if row_ids: + repair_job = table.refresh_column_async("embedding_repaired", where=predicate) + repair_job.wait() +``` + +Only the reviewed failed-row selection is populated in the new column; other +rows remain unfilled. Compare those outputs before deciding how readers +should use them. This does not promise an in-place upgrade/retry operation or +per-row producing-version lookup for a column containing mixed executions. +Error records' Function versions describe failures, not the provenance of +every successful row. + +## Quarantine inputs for review {#quarantine} + +Use an application-owned table of source table/branch, recorded table version, +stable row ID or business key, Function version, cause and review disposition. +Keep Blob payloads in the source table; a quarantine entry can refer to their +source identity. Choose an ordinary table name such as `function_quarantine`, +and explicitly exclude its reviewed IDs in subsequent input selections. + +Quarantine is an application workflow here: there is no implied built-in +quarantine lifecycle, automatic current-error clearing or exactly-once retry. +Do not delete source rows merely to hide an error. For very large failure sets, +bounded error listings cannot select every row; use a smaller reviewed scope +or wait for a deployment with the required complete selection support. + +Native retry policies, full current-error summaries, in-place version upgrades +and materialized-view row-error handling have separate server/SDK prerequisites. +Do not apply `REFRESH COLUMN` options to a materialized view and assume the +same policy; consult the [MV refresh reference](/sql/dml/refresh-materialized-view) +for your deployment's accepted options. + +## Continue {#next} + +- [Function lifecycle and failures](/management/function#failures) +- [Conditional and list-element refresh](/feature-engineering/refresh-column#partial) +- [Job results and events](/basics/jobs#snapshots) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index aae67ceb9..27f45cb6a 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -420,6 +420,9 @@ full worked example. ## Failure handling {#failures} +For the full skip, inspect, grouped-error, stable-row-ID retry and quarantine +workflow, see [Handle Function failures](/management/function-failures). + By default, a Function that raises fails the refresh job. Choose how the refresh handles row errors with its error policy: @@ -495,6 +498,47 @@ In practice this means a function should be self-contained: take its inputs as arguments, import what it needs at module level, and avoid capturing state from the surrounding scope. +### Supported global captures {#captures} + +The Python SDK's source packager captures only these literal values: + +| Module-level value | Packaging behavior | +| --- | --- | +| `None`, exact `bool`, `int`, `str`, `bytes`, finite `float` | Inlined as a snapshot at registration. | +| Tuples containing only those values, including nested tuples | Recursively inlined. | +| Imported modules, importable functions/classes | Reconstructed as imports; declare their packages in `pip` or `conda`, or ship local source with `code`. | +| Arrow types/schemas, lists, dictionaries, sets, NumPy arrays, non-finite floats, other objects | Not captured as literals. Construct them inside the Function or class. | + +For example, a module-level `OUT_TYPE = pa.list_(pa.float32(), 3)` referenced +from the Function body is unsupported. Construct the type where it is used: + +```python +import pyarrow as pa +from lancedb import function + +@function( + input_schema=pa.schema([pa.field("value", pa.float32(), nullable=False)]), + output_schema=pa.list_(pa.float32(), 3), +) +def make_vector(value: pa.Array) -> pa.Array: + out_type = pa.list_(pa.float32(), 3) + return pa.array([[v, v, v] for v in value.to_pylist()], type=out_type) +``` + +Decorator schema arguments are serialized as the signature; this restriction +concerns values referenced by the packaged body. For an expensive constant or +model, build it in a class Function's `__init__` and keep it on `self`. + +Later mutations of a client global do not update a registered version. Register +a new version to change captured literals or source. The diagnostic fix in +[SDK #4938](https://github.com/lancedb/lancedb/pull/4938) names the unsupported +global and its type; it does not add Arrow/container capture support. There is +no supported arbitrary-object serialization or documented container-size limit +to rely on for those rejected types. + +See the [Function type matrix](/curation/create-function#signature-types) for +what can travel as row inputs and outputs rather than captured globals. + Pass `code=[module, ...]` to ship additional helper modules into the same image, for logic the function imports but that does not belong inlined into it -- a model-loading helper shared by several Functions, for example. diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index 9c17fc50b..b7ceb15ad 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -182,6 +182,56 @@ BM25 scores depend on the indexed corpus and its term statistics. Compare rankings on the dataset you will search; treat scores as relative relevance values rather than probabilities. +### Match any word or every word {#term-operators} + +A multi-word string such as `"happy puppy"` uses **OR**: a row can match either +term. Writing `"happy AND puppy"` does not select an AND operator; the string +is analyzed as search text. To require both terms, construct a match query: + + +```python Python icon="python" +from lancedb.query import FullTextOperator, MatchQuery + +query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND) +results = table.search(query, query_type="fts").limit(10).to_list() +``` + +```typescript TypeScript icon="square-js" +import { MatchQuery, Operator } from "@lancedb/lancedb"; + +const query = new MatchQuery("happy puppy", "text", { operator: Operator.And }); +const results = await tbl.query().fullTextSearch(query).limit(10).toArray(); +``` + +```rust Rust icon="rust" +use lance_index::scalar::{ + FullTextSearchQuery, + inverted::query::{MatchQuery, Operator}, +}; +use lancedb::query::{ExecutableQuery, QueryBase}; + +let query = MatchQuery::new("happy puppy".to_owned()) + .with_column(Some("text".to_owned())) + .with_operator(Operator::And); +let results = tbl + .query() + .full_text_search(FullTextSearchQuery::new_query(query.into())) + .limit(10) + .execute() + .await?; +``` + + +AND requires all analyzed terms, without requiring adjacency or order. Use +[`PhraseQuery`](#phrase-vs-terms-queries) for an ordered phrase, or combine +separate queries with [`&` and `|`](#boolean-queries). Python `and` and `or` +do not build queries. + +On Enterprise, the existing [`fts()` SQL reference](/sql/dql/fts#term-operators) +shows the equivalent JSON (`"operator":"And"`), `_score`, and a +[`COUNT(*)` workaround](/sql/dql/fts#count) for counting matches without a +top-k limit. `len(results)` counts only the returned result page. + ### Keeping the index up to date {#keeping-the-index-up-to-date} In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table. @@ -395,6 +445,13 @@ table.create_index("text", config=FTS(with_position=True, remove_stop_words=Fals Storing token positions increases the index size and adds indexing work. +On Enterprise, wait for the replacement index to finish before issuing the +phrase query, using `table.wait_for_index(["text_idx"])` with your actual +index name. An existing index without positions must be rebuilt; changing the +query does not add positions. A phrase query against such an index is rejected +with an error asking you to recreate it with positions, rather than returning +an empty match set. See [FTS index options](/indexing/fts-index#fts-parameters) +and the [SQL phrase reference](/sql/dql/fts#phrase). ### Fuzzy Search {#fuzzy-search} diff --git a/docs/web/sql/dql/dedupe.mdx b/docs/web/sql/dql/dedupe.mdx index dbb6717b4..452638ea3 100644 --- a/docs/web/sql/dql/dedupe.mdx +++ b/docs/web/sql/dql/dedupe.mdx @@ -55,6 +55,15 @@ current deployments. a subset of partitions and `id_column` are pair-query-only options, accepted by [`duplicate_pairs`](/sql/dql/duplicate-pairs#input) but refused here. +## Index and snapshot requirements {#requirements} + +Use one compatible, current vector index covering the source snapshot. +Full scans reject unindexed fragments. Comparisons stay within physical IVF +partitions and index segments; this does not enumerate cross-partition or +cross-segment duplicates. Quantized-index distances use encoded vector +representations. See [recall and scale limits](/curation/dedupe#limits) before +treating the result as globally exact deduplication. + ## Output {#output} One row per duplicate group, **in the table's own schema** -- every column of diff --git a/docs/web/sql/dql/duplicate-pairs.mdx b/docs/web/sql/dql/duplicate-pairs.mdx index daa078955..dc93d5180 100644 --- a/docs/web/sql/dql/duplicate-pairs.mdx +++ b/docs/web/sql/dql/duplicate-pairs.mdx @@ -60,6 +60,12 @@ only [`dedupe`](/sql/dql/dedupe#input) accepts it. ## Output {#output} +See [`dedupe` index prerequisites](/sql/dql/dedupe#requirements) and the +[recall limits](/curation/dedupe#limits). Pairs are found within each physical +partition and index segment, not across them. A full scan requires complete +index coverage; sampling is a diagnostic view of the selected indexed +partitions and does not prove coverage or recall for the rest of the table. + One row per close pair found, in a fixed schema independent of the source table: diff --git a/docs/web/sql/dql/fts.mdx b/docs/web/sql/dql/fts.mdx index 7b52f5e17..667d92cd6 100644 --- a/docs/web/sql/dql/fts.mdx +++ b/docs/web/sql/dql/fts.mdx @@ -30,14 +30,16 @@ INSERT INTO my_docs VALUES (3, 'The puppy catches a ball with great enthusiasm', 'sports', 'Alice'), (5, 'Puppy training requires patience and dedication', 'training', 'Alice'); -CREATE INDEX ON my_docs USING fts (text); +CREATE INDEX ON my_docs USING fts (text) WITH (with_position = true); ``` Phrase queries need position information, which costs extra index size. -Add `WITH (with_position = true)` to `CREATE INDEX`. Without it, -[phrase queries](#phrase) find nothing. See +The setup above enables it with `WITH (with_position = true)`. An existing +index without positions must be rebuilt before running a phrase query; the +server rejects the query and asks you to recreate the index with positions. +It does not silently return no matches. See [FTS parameters](/indexing/fts-index#fts-parameters). @@ -86,6 +88,44 @@ LIMIT 5 it behaves like any other column, but exists only in a relation that came from `fts()`. See [Data types](/sql/data-types#pseudo-columns). +## Match any term or every term {#term-operators} + +The default match operator is OR. `"happy puppy"` matches either analyzed +term. SQL JSON uses `"Or"` and `"And"`, with this casing; Python uses the +`FullTextOperator.OR` and `FullTextOperator.AND` enum members: + +```python +from lancedb.query import FullTextOperator, MatchQuery + +query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND) +json_query = query.to_json() +``` + +```sql +SELECT id, text, _score +FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}') +ORDER BY _score DESC +``` + +Both terms must occur, but they need not be adjacent. Do not embed `AND` or +`OR` in `terms` to select an operator. + +## Count matches {#count} + +Count the `fts()` relation before applying a top-k limit: + +```sql +SELECT COUNT(*) AS matching_rows +FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}') +``` + +This is an Enterprise SQL workaround when the SDK's FTS query builder does +not expose a match-count operation. `table.count_rows()` without an FTS +relation counts table rows, and taking the length of a limited search counts +only that result page. For list-element indexes, multiple matching elements +can produce multiple rows; use `COUNT(DISTINCT id)` when you need unique +application records. + ## Fuzzy {#fuzzy} Tolerates typos, up to a character-edit budget: @@ -109,6 +149,12 @@ PhraseQuery("puppy park", "text", slop=2) # up to 2 words between them ``` +```sql +SELECT id, text, _score +FROM fts('my_docs', '{"phrase":{"column":"text","terms":"happy puppy","slop":0}}') +ORDER BY _score DESC +``` + ## Boolean {#boolean} Combine queries with `&` (AND) or `|` (OR): @@ -120,6 +166,17 @@ MatchQuery("puppy", "text") | MatchQuery("kitten", "text") ``` +For SQL, serialize the composed query rather than writing occurrence enums +by hand: + +```python +query = MatchQuery("puppy", "text") & MatchQuery("happy", "text") +json_query = query.to_json() +``` + +Use that string as the second `fts()` argument. `.to_json()` supplies the +serialized Boolean field names for the SDK version you use. + ## Boost {#boost} Weight a query up or down relative to another: From e1a10eaa66c68aa87d40056f73f0bf97c95091c3 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Sat, 14 Nov 2026 20:22:13 +0800 Subject: [PATCH 35/36] chore(deps): upgrade Lance to v15.0.0-beta.21 (#5046) Upgrade the Rust Lance family from beta.18 to the published v15.0.0-beta.21 tag, and align Python test wheels and Java artifacts. This includes the explicit-empty-segment FTS fix in lance-format/lance#11063 needed by lancedb/sophon#10314. Enable Windows Git long paths so Cargo can check out Lance fixtures in the Rust, NPM and Python wheel builds. Beta.21 also contains lance-format/lance#9858: new NGram, RTree and MinHash LSH indexes use row addresses. Legacy row-ID segments remain readable, but index maintenance on stable-row-ID tables can require a rebuild. The NGram documentation now explains the consolidation requirement; NGram/RTree tables without stable row IDs retain their earlier format. The Python lock revision and unrelated dependency entries are unchanged. Validation: - The official Lance release and internal mirror match 80bc45a195279befdec42853dac8d15a37e0504d. The seven official Fury wheels and Maven POM/JAR were verified. - Exact executable/dependency state 7846a15e completed the full Rust, Python, Node, Java and CLI CI, including platform builds and package publication dry runs. Xuanwo approved that head; Gatekeeper recommended approve with a non-blocking qualification risk. - Follow-up a289cb2c only adds the requested seven-line NGram upgrade note. Static whitespace checks passed; new-head CI is running. No local correctness tests or test builds were run by this task owner. - Broader IVF/encoding/Blob/cache workload performance and the beta.21 Sophon composition remain separately qualified. Earlier Blob cancellation and DynamoDB failures on #4967 are retained in their original evidence; this PR does not count those historical failures as fixed. Current-head CI, full feedback and required review still gate merge. SDK publication is a separate action. Sophon adoption follows a published SDK release and mirror through its own dependency PR; its distributed performance acceptance remains in #10314. --- .../workflows/build_windows_wheel/action.yml | 3 + .github/workflows/npm-publish.yml | 4 + .github/workflows/rust.yml | 4 + Cargo.lock | 97 ++++++++++--------- Cargo.toml | 30 +++--- docs/web/indexing/scalar-index.mdx | 7 ++ java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 17 ++-- 9 files changed, 93 insertions(+), 73 deletions(-) diff --git a/.github/workflows/build_windows_wheel/action.yml b/.github/workflows/build_windows_wheel/action.yml index 954ee7d35..3d92d818a 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -12,6 +12,9 @@ inputs: runs: using: "composite" steps: + - name: Enable long paths for Lance dependencies + shell: bash + run: git config --global core.longpaths true - uses: ./.github/actions/setup-protoc - name: Build wheel uses: PyO3/maturin-action@v1 diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 1b7d3dcbc..ac95b5a47 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -162,6 +162,10 @@ jobs: working-directory: nodejs steps: - uses: actions/checkout@v6 + - name: Enable long paths for Windows dependencies + if: runner.os == 'Windows' + # Cargo also checks out Lance test fixtures below its git cache path. + run: git config --global core.longpaths true - name: Setup pnpm uses: pnpm/action-setup@v6 with: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a5e5c9c30..4c275240f 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -349,6 +349,8 @@ jobs: working-directory: rust/lancedb steps: - uses: actions/checkout@v6 + - name: Enable long paths for Lance dependencies + run: git config --global core.longpaths true - name: Set target run: rustup target add ${{ matrix.target }} - uses: Swatinem/rust-cache@v2 @@ -386,6 +388,8 @@ jobs: working-directory: rust/lancedb steps: - uses: actions/checkout@v6 + - name: Enable long paths for Lance dependencies + run: git config --global core.longpaths true - name: Set target run: rustup target add aarch64-pc-windows-msvc - uses: Swatinem/rust-cache@v2 diff --git a/Cargo.lock b/Cargo.lock index 22b0f1e6f..d1624f941 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3824,8 +3824,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5303,8 +5303,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5379,8 +5379,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5416,7 +5416,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5425,8 +5425,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrayref", "crunchy", @@ -5436,8 +5436,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5475,8 +5475,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5507,8 +5507,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5533,8 +5533,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5551,8 +5551,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "proc-macro2", "quote", @@ -5561,8 +5561,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-arith", "arrow-array", @@ -5595,8 +5595,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-arith", "arrow-array", @@ -5627,8 +5627,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5659,8 +5659,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5696,6 +5696,7 @@ dependencies = [ "lance-arrow-stats", "lance-bitpacking", "lance-core", + "lance-datafusion", "lance-datafusion-exec", "lance-encoding", "lance-file", @@ -5732,8 +5733,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5756,8 +5757,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5802,8 +5803,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "byteorder", "ethnum", @@ -5820,8 +5821,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5836,8 +5837,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "async-trait", @@ -5851,8 +5852,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5906,8 +5907,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5921,8 +5922,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5963,8 +5964,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5977,8 +5978,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index c45eef6da..bc9d85c72 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index f674a988d..fbd818b64 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -210,6 +210,13 @@ table.search().where("contains(text, 'needle')").limit(10).to_pandas() `list_indices()` reports the index type as `"NGram"`. + +Lance 15.0.0-beta.21 writes new NGram indexes using physical row addresses. On +tables with stable row IDs, rebuild legacy NGram indexes that store row IDs +before consolidating their segments. Consolidation rejects these legacy +row-ID segments. Tables without stable row IDs retain the earlier index format. + + ## Index UUID Columns LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys. diff --git a/java/pom.xml b/java/pom.xml index fc89ebe4c..196e6db9a 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.18 + 15.0.0-beta.21 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 6940dce4f..d464424c7 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b18", + "pylance==15.0.0b21", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 369d558d2..31ac68b4d 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b18" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b21" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b18" +version = "15.0.0b21" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_Rs8tZ/pylance-15.0.0b18-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:255e782b016555c3f8072bb3d2a33dfdb3cb67b5ccf10a6a999fd007c58b16ab" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1D7wV0/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11adaf98d8e2960bb25d30315720cb93a2ac291d3fec29cd9726e1085cd9e40f" }, - { url = "https://pypi.fury.io/lance-format/-/ver_pK9DO/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aea39d714821d561b655f2d046129700a5ff95c3352813edd6af15ec6d9d29e2" }, - { url = "https://pypi.fury.io/lance-format/-/ver_28PrEd/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c19b3293be41ae4a87a67123e8d7233b0c5508aa39012c26525ab9d19884386d" }, - { url = "https://pypi.fury.io/lance-format/-/ver_kV8Di/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7a48686ab4777b58fe9f0e17a68048b779c071879d48035afb3e79b81b9d47a1" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1pAhhP/pylance-15.0.0b18-cp310-abi3-win_amd64.whl", hash = "sha256:dc32e4731b78c8325d1bd0f0e23f13f7dab7ed1f0fcda47d52661d44c8bfc83a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_mzSgZ/pylance-15.0.0b21-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:251682fe543131c371a6af45d8c672ea53b6ee83b5f777885f15ce383144d820" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1UfHMZ/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cbc92a2bac73f179a382e1bdb495fa3631a17e35687c2f00721af073eeb445a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Ugv8b/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59bd56971aa41a21783e938e18a752fdaa97a37cfdd8940ed2f37d0c665d0fdd" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1mO0GG/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a0da124e95240e448daa981664a5e64e87bc99411eb4c408cbd50147096654f4" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1n5aaN/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:341a1abcd62e6134982968a5236f8128d88211ab288d329924a812d87e555555" }, + { url = "https://pypi.fury.io/lance-format/-/ver_RVDDc/pylance-15.0.0b21-cp310-abi3-win_amd64.whl", hash = "sha256:f5dbd51b2553d70b927c537672bad41075cd8615f5e951008d7cd59c7365e587" }, + { url = "https://pypi.fury.io/lance-format/-/ver_GJeqW/pylance-15.0.0b21-cp310-abi3-win_arm64.whl", hash = "sha256:ddd517d555c6674c94b0eeee78ed6c3c3ac7b32319e27c47dd6f78a2639d6837" }, ] [[package]] From 5de76bd8edebb1aae915591683bdcfa642807032 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sat, 14 Nov 2026 12:33:00 +0000 Subject: [PATCH 36/36] =?UTF-8?q?Bump=20version:=200.42.0-beta.12=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index e4989d1eb..04ce71470 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.12" +current_version = "0.42.0-beta.13" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index d1624f941..a84f1d6fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5992,7 +5992,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "ahash", "anyhow", @@ -6103,7 +6103,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "anyhow", "arrow-array", @@ -6146,7 +6146,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "arrow-array", "arrow-buffer", @@ -6171,7 +6171,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index ca77b251c..1aadbe68f 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.12 + 0.42.0-beta.13 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 792b434a1..e8a9a76ec 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.12 + 0.42.0-beta.13 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 196e6db9a..9b062f4e8 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.12 + 0.42.0-beta.13 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 22cfe6ecc..7f8468eb5 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 283a32fdc..0fb6fde09 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 5fd392245..24e779721 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index ec5103284..8ee7bd66b 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 1d45a2ed2..3c7c63b86 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index d17a3b4e7..75e68cacd 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index a7c4a74b6..3422e095c 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 0e3a4a626..e9ceb4dfb 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index b0d99fb60..512e390aa 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 5a2923216..0f7667320 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index ef5da44c5..2dac7bda3 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index b22a3b8d8..581504423 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" edition = "2021" license.workspace = true repository.workspace = true