diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index 1e4989cf9..2a3250105 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -217,12 +217,23 @@ dataloader = torch.utils.data.DataLoader( ``` -By default, `StreamingDataset` serializes enough table state to reopen the -table in each worker. Remote LanceDB Enterprise tables (`db://...`) work the -same way: workers reopen the table from the pickled connection state. -Replace the URI, API key, region and endpoint below with your deployment -details. In application code, load credentials from environment variables -or a secrets manager: +By default, `StreamingDataset` and `Permutation` pickle the native table's +reopen state, including its connection, table identity, open options and +explicit storage overrides. A standard-mode handle reopens at the latest +version; `checkout(version)` and branch-scoped handles keep their pinned +version and branch. `memory://` tables are exported as an Arrow snapshot, so +workers see the data as of pickling; an in-memory connection by itself is not +picklable. + +Connections opened with a `Session` cannot be pickled. For a Session-backed +table, pass a picklable `connection_factory` to +`Permutation.with_connection_factory` or `StreamingDataset(connection_factory=...)` +so each worker creates its own connection and Session. + +Remote LanceDB Enterprise tables (`db://...`) work the same way: workers +reopen the table from the pickled connection state. Replace the URI, API key, +region and endpoint below with your deployment details. In application code, +load credentials from environment variables or a secrets manager: ```py Python icon=Python diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 86001ef10..aa1d73b29 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1936,11 +1936,40 @@ class LanceDBConnection(DBConnection): "manifest_enabled": self._manifest_enabled, "namespace_client_properties": self._namespace_client_properties, "read_consistency_interval_seconds": ( - rci.total_seconds() if rci else None + rci.total_seconds() if rci is not None else None ), } ) + def _pickle_state(self) -> str: + """Serialize this connection for pickle-based workers.""" + if self._session is not None: + raise TypeError( + "Cannot pickle a LanceDBConnection created with a Session; " + "Session objects are not serializable. Create the Session in " + "each worker process instead." + ) + if self.uri.startswith("memory://"): + raise TypeError( + "Cannot pickle an in-memory LanceDBConnection because its tables " + "exist only in this process. Pickle a LanceTable instead to " + "export its data, or connect to a persistent URI." + ) + return self.serialize() + + def __getstate__(self) -> dict[str, str]: + return {"serialized": self._pickle_state()} + + def __setstate__(self, state: dict[str, str]) -> None: + from . import deserialize_conn + + connection = deserialize_conn(state["serialized"], for_worker=True) + if not isinstance(connection, LanceDBConnection): + raise TypeError( + "Serialized connection did not reconstruct a LanceDBConnection" + ) + self.__dict__.update(connection.__dict__) + async def _async_get_table_names(self, start_after: Optional[str], limit: int): conn = AsyncConnection(await lancedb_connect(self.uri)) return await conn.table_names(start_after=start_after, limit=limit) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 463536619..1de49d935 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -584,7 +584,7 @@ class LanceNamespaceDBConnection(DBConnection): "storage_options": self.storage_options or None, "read_consistency_interval_seconds": ( self.read_consistency_interval.total_seconds() - if self.read_consistency_interval + if self.read_consistency_interval is not None else None ), } @@ -668,6 +668,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, namespace_client=self._namespace_client, pushdown_operations=self._namespace_client_pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, @@ -706,6 +707,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, namespace_client=self._namespace_client, pushdown_operations=self._namespace_client_pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, @@ -1132,6 +1134,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, location=table_uri, namespace_client=namespace_client, managed_versioning=managed_versioning, diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index a6f584f8a..c8e6f84e0 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -410,6 +410,8 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: from .remote.table import RemoteTable if isinstance(table, RemoteTable): + # RemoteTable already owns its reopen state; keep the table object so + # pickle delegates to its __getstate__ without duplicating the fields. return { "kind": "remote", "table": table, @@ -418,20 +420,15 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: if not isinstance(table, LanceTable): raise ValueError(f"Cannot pickle table of type {type(table)!r}") - base_uri = table._conn.uri - if base_uri.startswith("memory://"): + state = table.__getstate__() + if state.get("kind") == "memory": return { "kind": "memory", - "name": table.name, - "data": table.to_arrow(), + "state": state, } - return { - "kind": "local", - "name": table.name, - "uri": base_uri, - "namespace": table._namespace_path, - "storage_options": table._conn.storage_options, + "kind": "lance", + "state": state, } @@ -444,13 +441,25 @@ def _drop_base_version(permutation_data: pa.Table) -> pa.Table: return permutation_data.replace_schema_metadata(metadata) +def _lance_table_from_pickle_state(state: dict[str, Any]) -> LanceTable: + table = LanceTable.__new__(LanceTable) + table.__setstate__(state) + return table + + def _table_from_pickle_state(state: dict[str, Any]) -> Table: from . import connect kind = state["kind"] if kind == "remote": return state["table"] + if kind == "lance": + return _lance_table_from_pickle_state(state["state"]) if kind == "memory": + if "state" in state: + return _lance_table_from_pickle_state(state["state"]) + # Backward compatibility for pickles written before tables carried + # their own state. return connect("memory://").create_table(state["name"], state["data"]) if kind == "local": db = connect(state["uri"], storage_options=state["storage_options"]) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ff014396c..ea9dee024 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -299,7 +299,7 @@ def _maybe_add_fts_error_note( if TYPE_CHECKING: - from .db import LanceDBConnection + from .db import DBConnection, LanceDBConnection from ._lancedb import ( Table as LanceDBTable, OptimizeStats, @@ -4191,7 +4191,10 @@ class LanceTable(Table): namespace_path = [] self._conn = connection self._namespace_path = namespace_path + self._storage_options = storage_options + self._index_cache_size = index_cache_size self._location = location # Store location for use in _dataset_path + self._managed_versioning = managed_versioning self._namespace_client = namespace_client self._pushdown_operations = pushdown_operations or set() # When the connection built the namespace client natively (e.g. an @@ -4218,6 +4221,154 @@ class LanceTable(Table): ) # Take queries read the pushdown set from the inner table. self._table._pushdown_operations = self._pushdown_operations + # These coordinates live on the Python wrapper: the native table only + # reports its current branch and version, not whether it is pinned. + self._branch = self._table.current_branch() + self._checkout_version: Optional[int] = None + + def _pickle_connection_state(self) -> str: + """Serialize the connection, rejecting state a worker cannot recreate.""" + connection = self._conn + namespace_client = getattr(connection, "_namespace_client", None) + namespace_impl = getattr(connection, "_namespace_client_impl", None) + if namespace_client is not None and namespace_impl is None: + raise TypeError( + f"Cannot pickle LanceTable {self.name!r} backed by a namespace " + "connection whose custom namespace_client cannot be " + "reconstructed. Connect through connect_namespace(impl, " + "properties) or provide a picklable worker-side namespace " + "connection instead." + ) + + pickle_state = getattr(connection, "_pickle_state", None) + if pickle_state is not None: + return pickle_state() + + session = getattr(connection, "session", None) + if session is not None: + raise TypeError( + "Cannot pickle a LanceTable whose connection was created with a " + "Session; Session objects are not serializable. Create the " + "Session in each worker process instead." + ) + return connection.serialize() + + def _namespace_client_for_pickle(self) -> Optional[Any]: + """Keep a table-level namespace client only when pickle can carry it.""" + namespace_client = self._namespace_client + if namespace_client is None: + return None + if namespace_client is getattr(self._conn, "_namespace_client", None): + # The serialized connection rebuilds its own namespace client. + return None + if namespace_client is getattr(self._conn, "_cached_namespace_client", None): + # Local manifest-mode connections cache their namespace client here. + return None + + import pickle + + try: + pickle.dumps(namespace_client) + except Exception as error: + raise TypeError( + f"Cannot pickle LanceTable {self.name!r}: its custom " + f"namespace_client ({type(namespace_client).__name__}) is not " + "serializable. Reopen the table in the worker through a " + "picklable namespace connection instead." + ) from error + return namespace_client + + @classmethod + def _open_from_pickle_state( + cls, connection: "DBConnection", state: dict[str, Any] + ) -> "LanceTable": + """Reopen a table from the state returned by ``__getstate__``.""" + async_connection = getattr(connection, "_conn", None) + if async_connection is None: + async_connection = connection._inner + + # Only a table-level explicit client travels in the state. A connection + # namespace client must reopen through its own provider path so caller + # storage options keep their layering; passing the reconstructed client + # here would turn it into an explicit table provider. + namespace_client = state.get("namespace_client") + + async_table = LOOP.run( + async_connection.open_table( + state["name"], + namespace_path=state["namespace_path"], + storage_options=state["storage_options"], + index_cache_size=state["index_cache_size"], + location=state["location"], + namespace_client=namespace_client, + managed_versioning=state["managed_versioning"], + ) + ) + table = cls( + connection, + state["name"], + namespace_path=state["namespace_path"], + storage_options=state["storage_options"], + index_cache_size=state["index_cache_size"], + location=state["location"], + namespace_client=namespace_client, + managed_versioning=state["managed_versioning"], + pushdown_operations=state["pushdown_operations"], + route_pushdown_to_rust=state["route_pushdown_to_rust"], + _async=async_table, + ) + + version = state["checkout_version"] + if state["branch"] is not None: + table = table.branches.checkout(state["branch"], version) + elif version is not None: + table.checkout(version) + return table + + def __getstate__(self) -> dict[str, Any]: + """Return a process-independent state for pickle-based workers.""" + if self._conn.uri.startswith("memory://"): + # In-memory databases cannot be reopened by name in another process. + # Keep the established behavior of exporting the visible table. + return {"kind": "memory", "name": self.name, "data": self.to_arrow()} + + # The native handle is authoritative: a tag checkout can move this + # wrapper onto another branch, so never trust the branch captured at + # construction time. + self._branch = self.current_branch() + return { + "kind": "lance", + "connection_state": self._pickle_connection_state(), + "name": self.name, + "namespace_path": list(self._namespace_path), + # Only caller-supplied overrides are safe to replay. Namespace-provided + # initial options may contain rotating credentials and must be fetched + # again by the reopened connection's storage-options provider. + "storage_options": self._storage_options, + "index_cache_size": self._index_cache_size, + "location": self._location, + "namespace_client": self._namespace_client_for_pickle(), + "managed_versioning": self._managed_versioning, + "pushdown_operations": set(self._pushdown_operations), + "route_pushdown_to_rust": self._route_pushdown_to_rust, + "branch": self._branch, + "checkout_version": self._checkout_version, + } + + def __setstate__(self, state: dict[str, Any]) -> None: + """Rebuild a table from ``__getstate__`` in the current process.""" + if state.get("kind") == "memory": + from . import connect + + rebuilt = connect("memory://").create_table(state["name"], state["data"]) + self.__dict__.update(rebuilt.__dict__) + return + + from . import deserialize_conn + + connection = deserialize_conn(state["connection_state"], for_worker=True) + reopened = type(self)._open_from_pickle_state(connection, state) + self.__dict__.update(reopened.__dict__) @property def name(self) -> str: @@ -4456,18 +4607,23 @@ class LanceTable(Table): def _wrap_branch_handle( self, async_table: "AsyncTable", version: Optional[int] = None ) -> "LanceTable": - # version is unused locally: the pin already lives on async_table and a - # local handle is not reopened via a serialized connection. - return LanceTable( + table = LanceTable( self._conn, async_table.name, namespace_path=self._namespace_path, + storage_options=self._storage_options, + index_cache_size=self._index_cache_size, namespace_client=self._namespace_client, + managed_versioning=self._managed_versioning, pushdown_operations=self._pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, location=self._location, _async=async_table, ) + # The native handle knows its branch but not whether this wrapper is a + # pinned branch version, so carry that coordinate explicitly. + table._checkout_version = version + return table def checkout(self, version: Union[int, str]): """Checkout a version of the table. This is an in-place operation. @@ -4506,6 +4662,8 @@ class LanceTable(Table): 0 [1.1, 0.9] vector """ LOOP.run(self._table.checkout(version)) + self._checkout_version = self.version + self._branch = self.current_branch() def checkout_latest(self): """Checkout the latest version of the table. This is an in-place operation. @@ -4514,6 +4672,8 @@ class LanceTable(Table): version of the table. """ LOOP.run(self._table.checkout_latest()) + self._checkout_version = None + self._branch = self.current_branch() def restore(self, version: Optional[Union[int, str]] = None): """Restore a version of the table. This is an in-place operation. @@ -4562,6 +4722,8 @@ class LanceTable(Table): if version is not None: LOOP.run(self._table.checkout(version)) LOOP.run(self._table.restore()) + self._checkout_version = None + self._branch = self.current_branch() def count_rows(self, filter: Optional[str] = None) -> int: return LOOP.run(self._table.count_rows(filter)) @@ -5651,7 +5813,9 @@ class LanceTable(Table): self = cls.__new__(cls) self._conn = db self._namespace_path = namespace_path + self._index_cache_size = None self._location = location + self._managed_versioning = None self._namespace_client = namespace_client self._pushdown_operations = pushdown_operations or set() self._route_pushdown_to_rust = route_pushdown_to_rust @@ -5679,6 +5843,7 @@ class LanceTable(Table): enable_v2_manifest_paths ).lower() + self._storage_options = storage_options self._table = LOOP.run( self._conn._conn.create_table( name, @@ -5695,6 +5860,8 @@ class LanceTable(Table): namespace_client=namespace_client, ) ) + self._branch = self._table.current_branch() + self._checkout_version = None return self def delete(self, where: Union[str, Expr]) -> DeleteResult: diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 80a98bc18..fa09a9e19 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -4,6 +4,7 @@ import contextlib import inspect +import pickle import re import sys from datetime import timedelta @@ -69,6 +70,29 @@ def test_basic(tmp_path): assert db.open_table("test").name == db["test"].name +def test_lance_db_connection_pickle_roundtrip(tmp_path): + interval = timedelta(seconds=2) + db = lancedb.connect(tmp_path, read_consistency_interval=interval) + db.create_table("pickle_conn", pa.table({"id": [1, 2]})) + + restored = pickle.loads(pickle.dumps(db)) + + assert restored.uri == str(tmp_path) + assert restored.read_consistency_interval == interval + assert restored.open_table("pickle_conn").to_arrow()["id"].to_pylist() == [1, 2] + + +def test_lance_db_connection_pickle_preserves_zero_read_consistency(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) + table = db.create_table("pickle_zero", pa.table({"id": [1]})) + + restored_db, restored_table = pickle.loads(pickle.dumps((db, table))) + lancedb.connect(tmp_path).open_table("pickle_zero").add(pa.table({"id": [2]})) + + assert restored_db.read_consistency_interval == timedelta(0) + assert restored_table.to_arrow()["id"].to_pylist() == [1, 2] + + def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeypatch): from lancedb.background_loop import LOOP diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index b4ca746b0..c965618cd 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -6,6 +6,8 @@ import tempfile import shutil import importlib +import asyncio +import pickle import warnings import http.server import json @@ -16,6 +18,7 @@ import copy import pyarrow as pa import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError +from lance_namespace import DescribeTableResponse from utils import start_server_thread from lancedb.listing import AsyncListing, Listing from lancedb.index import FTS @@ -35,6 +38,37 @@ PUSHDOWN_DATA = pa.table( ) +class _RefreshNamespaceWithExpiringOptions(LanceNamespace): + def __init__(self, root): + self.root = root + + def namespace_id(self): + return f"refresh-test:{self.root}" + + def describe_table(self, request): + from pathlib import Path + + return DescribeTableResponse( + location=str(Path(self.root) / "t.lance"), + storage_options={"vended": "fresh", "expires_at_millis": "1"}, + ) + + +class _DeclaredNamespaceWithoutProperties(LanceNamespace): + root = None + + def __init__(self): + from lance.namespace import DirectoryNamespace + + self.client = DirectoryNamespace(root=self.root) + + def namespace_id(self): + return self.client.namespace_id() + + def describe_table(self, request): + return self.client.describe_table(request) + + @pytest.mark.asyncio @pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]]) async def test_custom_namespace_table_exists_uses_namespace_api(table_id): @@ -56,6 +90,70 @@ async def test_custom_namespace_table_exists_uses_namespace_api(table_id): assert await adb.table_exists(table_id) is (table_id != ["missing"]) +def test_table_pickle_rejects_custom_namespace_connection(tmp_path): + pytest.importorskip("lance") + from lance.namespace import DirectoryNamespace + + lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table( + "t", [{"id": 1}] + ) + + class UnserializableNamespace(LanceNamespace): + def __init__(self, root): + from threading import Lock + + self.client = DirectoryNamespace(root=str(root)) + self.lock = Lock() + + def namespace_id(self): + return self.client.namespace_id() + + def describe_table(self, request): + return self.client.describe_table(request) + + db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path)) + table = db.open_table("t") + + with pytest.raises(TypeError, match="namespace"): + pickle.dumps(table) + + +def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path): + lancedb.connect(tmp_path).create_table("t", [{"id": 1}]) + db = lancedb.connect_namespace( + f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)} + ) + table = db.open_table("t", storage_options={"caller_only": "keep"}) + + restored = pickle.loads(pickle.dumps(table)) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_only"] == "keep" + assert options["vended"] == "fresh" + + +def test_table_pickle_allows_declared_namespace_without_properties(tmp_path): + pytest.importorskip("lance") + + lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table( + "t", [{"id": 1}] + ) + _DeclaredNamespaceWithoutProperties.root = str(tmp_path) + try: + impl = f"{__name__}._DeclaredNamespaceWithoutProperties" + db = LanceNamespaceDBConnection( + _DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl + ) + table = db.open_table("t") + + restored = pickle.loads(pickle.dumps(table)) + + assert restored.to_arrow()["id"].to_pylist() == [1] + finally: + _DeclaredNamespaceWithoutProperties.root = None + + class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) @@ -309,6 +407,328 @@ def paginated_rest_namespace(): thread.join() +def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path): + from time import time + + local = lancedb.connect(tmp_path) + local.create_table("t", [{"id": 1}]) + location = str(tmp_path / "t.lance") + ipc = _ipc_file(pa.table({"id": [42]})) + seen = [] + current_options = { + "block_size": "4096", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + seen.append(path) + if path.endswith("/describe"): + body = json.dumps( + {"location": location, "storage_options": current_options} + ).encode() + content_type = "application/json" + elif path.endswith("/query"): + body = ipc + content_type = "application/vnd.apache.arrow.file" + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", + {"uri": f"http://127.0.0.1:{server.server_port}"}, + namespace_client_pushdown_operations=["QueryTable"], + ) + table = db.open_table("t") + restored = pickle.loads(pickle.dumps(table)) + + seen.clear() + assert restored.search().limit(1).to_list() == [{"id": 42}] + assert seen == ["/v1/table/t/query"] + + current_options = { + "block_size": "8192", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + } + assert table.latest_storage_options()["block_size"] == "8192" + assert restored.latest_storage_options()["block_size"] == "8192" + finally: + server.shutdown() + thread.join() + + +def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path): + from time import time + + location = str(tmp_path / "t.lance") + current_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if not (path.endswith("/declare") or path.endswith("/describe")): + self.send_error(404) + return + body = json.dumps( + {"location": location, "storage_options": current_options} + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", {"uri": f"http://127.0.0.1:{server.server_port}"} + ) + table = db.create_table("t", [{"id": 1}]) + payload = pickle.dumps(table) + assert b"short-lived" not in payload + restored = pickle.loads(payload) + + current_options = {} + assert table.latest_storage_options() == {} + assert restored.latest_storage_options() == {} + finally: + server.shutdown() + thread.join() + + +@pytest.mark.parametrize("entrypoint", ["create", "open"]) +def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint): + from time import time + + location = str(tmp_path / "t.lance") + caller_options = {"caller_option": "kept", "conflict": "caller"} + vended_options = { + "vended_1": "old", + "conflict": "vended", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if path.endswith("/declare") or path.endswith("/describe"): + body = json.dumps( + {"location": location, "storage_options": vended_options} + ).encode() + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", + {"uri": f"http://127.0.0.1:{server.server_port}"}, + ) + if entrypoint == "create": + table = db.create_table( + "t", [{"id": 1}], storage_options=caller_options + ) + else: + db.create_table("t", [{"id": 1}]) + table = db.open_table("t", storage_options=caller_options) + restored = pickle.loads(pickle.dumps(table)) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_option"] == "kept" + assert options["conflict"] == "vended" + + vended_options.update( + { + "vended_2": "new", + "conflict": "vended-new", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + } + ) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_option"] == "kept" + assert options["vended_2"] == "new" + assert options["conflict"] == "vended-new" + finally: + server.shutdown() + thread.join() + + +def test_namespace_open_uses_explicit_storage_options_provider(tmp_path): + from time import time + + from lancedb._lancedb import connect_namespace as connect_namespace_inner + from lancedb.db import AsyncConnection + + location = str(tmp_path / "t.lance") + seed_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if not (path.endswith("/declare") or path.endswith("/describe")): + self.send_error(404) + return + result = {"location": location, "storage_options": seed_options} + body = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + class ExplicitClient(LanceNamespace): + calls = 0 + + def namespace_id(self): + return "explicit-storage-options-provider" + + def describe_table(self, request): + self.calls += 1 + return DescribeTableResponse( + location=location, + storage_options={ + "explicit_provider": "fresh", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + }, + ) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + properties = {"uri": f"http://127.0.0.1:{server.server_port}"} + db = lancedb.connect_namespace("rest", properties) + db.create_table("t", [{"id": 1}]) + + async def check(): + connection = AsyncConnection( + connect_namespace_inner("rest", properties) + ) + client = ExplicitClient() + table = await connection.open_table("t", namespace_client=client) + options = await table.latest_storage_options() + assert client.calls > 0 + assert options["explicit_provider"] == "fresh" + + asyncio.run(check()) + finally: + server.shutdown() + thread.join() + + +def test_namespace_create_without_seed_uses_connection_provider(tmp_path): + from time import time + + from lancedb._lancedb import connect_namespace as connect_namespace_inner + from lancedb.db import AsyncConnection + + location = str(tmp_path / "t.lance") + seed_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + result = {"location": location} + if path.endswith("/describe"): + result["storage_options"] = seed_options + elif not path.endswith("/declare"): + self.send_error(404) + return + body = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + class ExplicitClient(LanceNamespace): + calls = 0 + + def namespace_id(self): + return "explicit-storage-options-provider" + + def describe_table(self, request): + self.calls += 1 + return DescribeTableResponse( + location=location, + storage_options={ + "explicit_provider": "fresh", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + }, + ) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + properties = {"uri": f"http://127.0.0.1:{server.server_port}"} + + async def check(): + connection = AsyncConnection( + connect_namespace_inner("rest", properties) + ) + client = ExplicitClient() + table = await connection.create_table( + "t", [{"id": 1}], namespace_client=client + ) + options = await table.latest_storage_options() + assert client.calls == 0 + assert options["vended_seed"] == "short-lived" + + asyncio.run(check()) + finally: + server.shutdown() + thread.join() + + @pytest.mark.asyncio @pytest.mark.parametrize("namespace_path", [[], ["n"]]) async def test_rest_namespace_table_names_collects_pages( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 90ae62d1b..e999390a1 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6,6 +6,7 @@ import ctypes import gc import json import os +import pickle import sys import threading import warnings @@ -1228,6 +1229,128 @@ def test_list_versions_timestamp_precision_remote(): assert versions[0]["timestamp"].microsecond == 274000 +def test_lance_table_is_picklable(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_table", pa.table({"id": [1, 2, 3]})) + payload = pickle.dumps(table) + + # A standard-mode handle must reopen at latest, not freeze the version that + # happened to be current when pickle.dumps ran. + tmp_db.open_table("pickle_table").add(pa.table({"id": [4]})) + + restored = pickle.loads(payload) + assert restored.name == "pickle_table" + assert restored.count_rows() == 4 + assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3, 4] + + +def test_lance_table_pickle_preserves_checkout(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_checkout", pa.table({"id": [1]})) + table.add(pa.table({"id": [2]})) + table.checkout(1) + payload = pickle.dumps(table) + + tmp_db.open_table("pickle_checkout").add(pa.table({"id": [3]})) + + restored = pickle.loads(payload) + assert restored.version == 1 + assert restored.to_arrow()["id"].to_pylist() == [1] + + restored.checkout_latest() + assert restored.version == 3 + assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3] + + +def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path): + db = lancedb.connect(tmp_path) + main = db.create_table("pickle_tag_branch", pa.table({"id": [0]})) + branch = main.branches.create("exp") + branch.add(pa.table({"id": [1]})) + branch.tags.create("exp_tag", branch.version) + + # Advance main independently, then resolve a tag that points into exp. + main.add(pa.table({"id": [9]})) + main.checkout("exp_tag") + assert main.current_branch() == "exp" + assert main.version == 2 + assert main.to_arrow()["id"].to_pylist() == [0, 1] + + restored = pickle.loads(pickle.dumps(main)) + assert restored.current_branch() == "exp" + assert restored.version == 2 + assert restored.to_arrow()["id"].to_pylist() == [0, 1] + + +def test_lance_table_pickle_preserves_branch_and_version(tmp_path): + db = lancedb.connect(tmp_path) + main = db.create_table("pickle_branch", pa.table({"id": [0]})) + branch = main.branches.create("exp") + branch.add(pa.table({"id": [1]})) + branch_version = branch.version + + branch_payload = pickle.dumps(branch) + pinned = db.open_table("pickle_branch", branch="exp", version=branch_version) + pinned_payload = pickle.dumps(pinned) + + db.open_table("pickle_branch", branch="exp").add(pa.table({"id": [2]})) + + restored_branch = pickle.loads(branch_payload) + assert restored_branch.current_branch() == "exp" + assert restored_branch.to_arrow()["id"].to_pylist() == [0, 1, 2] + + restored_pinned = pickle.loads(pinned_payload) + assert restored_pinned.current_branch() == "exp" + assert restored_pinned.version == branch_version + assert restored_pinned.to_arrow()["id"].to_pylist() == [0, 1] + assert main.count_rows() == 1 + + +def test_lance_table_pickle_memory_uses_arrow_snapshot(mem_db: DBConnection): + table = mem_db.create_table("pickle_memory", pa.table({"id": [1, 2]})) + payload = pickle.dumps(table) + + table.add(pa.table({"id": [3]})) + + restored = pickle.loads(payload) + assert restored.name == "pickle_memory" + assert restored.to_arrow()["id"].to_pylist() == [1, 2] + + +def test_memory_connection_pickle_requires_a_table_snapshot(mem_db: DBConnection): + with pytest.raises(TypeError, match="in-memory LanceDBConnection"): + pickle.dumps(mem_db) + + +def test_pickle_rejects_session_backed_connection(tmp_path): + db = lancedb.connect(tmp_path, session=lancedb.Session()) + table = db.create_table("pickle_session", pa.table({"id": [1]})) + + with pytest.raises(TypeError, match="Session"): + pickle.dumps(db) + with pytest.raises(TypeError, match="Session"): + pickle.dumps(table) + + +def test_pickle_rejects_custom_namespace_client(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_custom_ns", pa.table({"id": [1]})) + table._namespace_client = threading.Lock() + + with pytest.raises(TypeError, match="namespace_client"): + pickle.dumps(table) + + +def test_lance_table_pickle_preserves_namespace_path(tmp_path): + pytest.importorskip("lance") + db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + db.create_namespace(["ns1"]) + table = db.create_table("pickle_ns", pa.table({"id": [1]}), namespace_path=["ns1"]) + + restored = pickle.loads(pickle.dumps(table)) + + assert restored.namespace == ["ns1"] + assert restored.count_rows() == 1 + assert restored._conn._namespace_client_properties == {"root": str(tmp_path)} + + def test_versioning(mem_db: DBConnection): table = mem_db.create_table( "test", diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index befa3c10f..1cc6500bd 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -135,6 +135,23 @@ def _open_native_table(uri: str, table_name: str): return lancedb.connect(uri).open_table(table_name) +class _DatasetHoldingConnectionAndTable(torch.utils.data.Dataset): + """User-style Dataset that keeps both the connection and table.""" + + def __init__(self, db, table): + self._db = db + self._table = table + + def __len__(self): + return self._table.count_rows() + + def __getitem__(self, index): + row = self._table.take_offsets([index]).to_arrow().to_pylist()[0] + # Touch the connection too, so workers prove both objects were restored. + row["db_uri"] = self._db.uri + return row + + def test_table_dataloader(mem_db): table = mem_db.create_table("test_table", pa.table({"a": range(1000)})) dataloader = torch.utils.data.DataLoader( @@ -229,6 +246,30 @@ def test_permutation_with_memory_base_is_picklable(mem_db): assert restored.__getitems__([0, 10, 49]) == [{"a": 0}, {"a": 10}, {"a": 49}] +@pytest.mark.parametrize("start_method", ["spawn", "forkserver"]) +def test_dataset_with_connection_and_table_dataloader(tmp_path, start_method): + if start_method not in mp.get_all_start_methods(): + pytest.skip(f"{start_method} start method is not available") + + db = lancedb.connect(tmp_path) + table = db.create_table("test_table", pa.table({"a": range(20)})) + dataset = _DatasetHoldingConnectionAndTable(db, table) + + dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=4, + num_workers=2, + multiprocessing_context=start_method, + ) + + seen = [] + expected_uri = str(tmp_path) + for batch in dataloader: + seen.extend(batch["a"].tolist()) + assert all(uri == expected_uri for uri in batch["db_uri"]) + assert sorted(seen) == list(range(20)) + + def test_permutation_dataloader_multiprocessing(tmp_db): """Using a Permutation with a PyTorch DataLoader that has num_workers > 0 must work end-to-end. Each worker process gets a pickled copy of the diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index bbefc3ca8..db6aa2ba8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -90,6 +90,75 @@ fn set_storage_options_provider( store_params.storage_options_accessor = Some(Arc::new(accessor)); } +/// Preserve caller-supplied options across provider refreshes. +/// +/// Namespace providers return a fresh credential map and replace the accessor +/// cache, so a plain initial-options accessor would drop caller-only settings +/// after the first refresh. This wrapper merges the caller options into every +/// provider result, with provider values winning overlapping keys. +#[derive(Debug)] +pub(crate) struct LayeredStorageOptionsProvider { + caller_options: HashMap, + inner: Arc, +} + +impl LayeredStorageOptionsProvider { + pub(crate) fn new( + caller_options: HashMap, + inner: Arc, + ) -> Self { + Self { + caller_options, + inner, + } + } + + fn layer( + &self, + mut options: Option>, + ) -> Option> { + let mut merged = self.caller_options.clone(); + match options.take() { + Some(options) => { + merged.extend(options); + Some(merged) + } + None if merged.is_empty() => None, + None => Some(merged), + } + } +} + +#[async_trait::async_trait] +impl StorageOptionsProvider for LayeredStorageOptionsProvider { + async fn fetch_storage_options(&self) -> lance_core::Result>> { + Ok(self.layer(self.inner.fetch_storage_options().await?)) + } + + async fn force_fetch_storage_options( + &self, + ) -> lance_core::Result>> { + Ok(self.layer(self.inner.force_fetch_storage_options().await?)) + } + + fn provider_id(&self) -> String { + use std::hash::{Hash, Hasher}; + + let mut entries: Vec<_> = self.caller_options.iter().collect(); + entries.sort_by_key(|(key, _)| *key); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for (key, value) in entries { + key.hash(&mut hasher); + value.hash(&mut hasher); + } + format!( + "layered(caller_options={:x},{})", + hasher.finish(), + self.inner.provider_id() + ) + } +} + /// A builder for configuring a [`Connection::table_names`] operation pub struct TableNamesBuilder { parent: Arc, diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 4e61710ff..d603a878b 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -9,7 +9,10 @@ use std::sync::{Arc, Mutex}; use async_trait::async_trait; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; -use lance_io::object_store::{ObjectStoreParams, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, ObjectStoreParams, StorageOptionsAccessor, + StorageOptionsProvider, +}; use lance_namespace::{ LanceNamespace, error::{ErrorCode, NamespaceError}, @@ -25,7 +28,9 @@ use lance_table::io::commit::CommitHandler; use lance_table::io::commit::external_manifest::ExternalManifestCommitHandler; use crate::blob::ensure_blob_storage_version; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{ + LayeredStorageOptionsProvider, NamespaceClientPushdownOperation, merge_storage_options, +}; use crate::database::ReadConsistency; use crate::database::listing::{NewTableConfig, take_request_creation_overrides}; use crate::database::read_freshness::{ @@ -465,13 +470,29 @@ impl Database for LanceNamespaceDatabase { params.mode = WriteMode::Overwrite; } - // Set up storage options if provided + // Set up storage options if provided. Namespace options take + // precedence for overlapping keys, but must not discard caller-only + // options supplied with the create request. + let store_params = params + .store_params + .get_or_insert_with(ObjectStoreParams::default); + let caller_storage_options = store_params.storage_options().cloned().unwrap_or_default(); if let Some(storage_opts) = initial_storage_options { - let store_params = params - .store_params - .get_or_insert_with(ObjectStoreParams::default); + merge_storage_options(store_params, storage_opts); + } + if let Some(initial_options) = store_params + .storage_options() + .cloned() + .filter(|options| !options.is_empty()) + { + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(self.namespace.clone(), table_id.clone()), + ); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(caller_storage_options, namespace_provider), + ); store_params.storage_options_accessor = Some(Arc::new( - StorageOptionsAccessor::with_static_options(storage_opts), + StorageOptionsAccessor::with_initial_and_provider(initial_options, provider), )); } @@ -618,6 +639,7 @@ mod tests { use arrow_array::{Int32Array, RecordBatch, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; + use lance_io::object_store::StorageOptionsAccessor; use tempfile::tempdir; #[derive(Debug)] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 775261bb5..4d663649e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -29,7 +29,9 @@ use lance::index::scalar::load_segment_params; use lance::io::{ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; use lance_index::IndexCriteria; -use lance_io::object_store::{LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor, StorageOptionsProvider, +}; pub use query::AnyQuery; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; @@ -49,7 +51,7 @@ use std::format; use std::path::Path; use std::sync::Arc; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{LayeredStorageOptionsProvider, NamespaceClientPushdownOperation}; use crate::DistanceType; use crate::blob::BlobRangeRequest; @@ -3679,7 +3681,7 @@ impl NativeTable { } // patch the params if we have a write store wrapper - let params = match write_store_wrapper.clone() { + let mut params = match write_store_wrapper.clone() { Some(wrapper) => params.patch_with_store_wrapper(wrapper)?, None => params, }; @@ -3690,9 +3692,49 @@ impl NativeTable { // Use DatasetBuilder::from_namespace which automatically fetches location // and storage options from the namespace - let builder = DatasetBuilder::from_namespace(namespace_client.clone(), table_id) - .await - .map_err(|e| map_namespace_lance_error(e, name))?; + let mut builder = + DatasetBuilder::from_namespace(namespace_client.clone(), table_id.clone()) + .await + .map_err(|e| map_namespace_lance_error(e, name))?; + + // A caller-supplied read-params accessor replaces the namespace-backed + // accessor in with_read_params. Preserve an explicit provider/accessor; + // only layer static caller options onto the live namespace provider so + // refresh keeps working and namespace values retain their precedence. + if let Some(mut store_options) = params.store_options.take() { + if let Some(accessor) = store_options.get_accessor() { + if accessor.provider().is_some() { + builder = builder.with_store_params(store_options); + } else { + let caller_options = accessor + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let namespace_provider: Arc = + Arc::new(LanceNamespaceStorageOptionsProvider::new( + namespace_client.clone(), + table_id, + )); + let provider: Arc = + Arc::new(LayeredStorageOptionsProvider::new( + caller_options.clone(), + namespace_provider, + )); + let accessor = if caller_options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + caller_options, + provider, + )) + }; + store_options.storage_options_accessor = Some(accessor); + builder = builder.with_store_params(store_options); + } + } else { + builder = builder.with_store_params(store_options); + } + } let dataset = builder .with_read_params(params) @@ -3901,10 +3943,9 @@ impl NativeTable { table_id.push(name.to_string()); // Set up storage options provider from namespace - let storage_options_provider = Arc::new(LanceNamespaceStorageOptionsProvider::new( - namespace_client.clone(), - table_id, - )); + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(namespace_client.clone(), table_id), + ); // Start with provided params or defaults let mut params = params.unwrap_or_default(); @@ -3914,17 +3955,40 @@ impl NativeTable { params.session = Some(sess); } - // Ensure store_params exists and set the storage options provider + // Ensure store_params exists and preserve an already-layered provider + // from create_table, or attach the namespace provider to the caller's + // initial options for other callers. let store_params = params .store_params .get_or_insert_with(ObjectStoreParams::default); - let accessor = match store_params.storage_options().cloned() { - Some(options) => { - StorageOptionsAccessor::with_initial_and_provider(options, storage_options_provider) + let accessor = match store_params.storage_options_accessor.take() { + Some(existing) + if existing.provider().is_some() + && existing.initial_storage_options().is_some() => + { + existing } - None => StorageOptionsAccessor::with_provider(storage_options_provider), + Some(existing) => { + let options = existing + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(options.clone(), namespace_provider), + ); + if options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + options, provider, + )) + } + } + None => Arc::new(StorageOptionsAccessor::with_provider(Arc::new( + LayeredStorageOptionsProvider::new(HashMap::new(), namespace_provider), + ))), }; - store_params.storage_options_accessor = Some(Arc::new(accessor)); + store_params.storage_options_accessor = Some(accessor); // Patch the params if we have a write store wrapper let params = match write_store_wrapper.clone() {