feat(python): make native tables and connections picklable (#5114)

## Summary

Adds `__getstate__`/`__setstate__` to native `LanceTable` and
`LanceDBConnection` so a PyTorch `Dataset` that keeps both can cross
`spawn` and `forkserver` worker boundaries. `Permutation` and
`StreamingDataset` now delegate to the same table state representation
while retaining compatibility with older pickle payloads.

## Pickle contract

- Reconnects from the serialized connection and preserves the table
name, namespace path, explicit storage overrides, location, index-cache
setting, managed versioning and pushdown routing.
- Standard mode reopens at latest; `checkout(version)` remains pinned to
the resolved branch/version; branch handles preserve their branch.
Cross-branch tag checkout records the actual live branch.
- `read_consistency_interval=timedelta(0)` remains distinct from `None`.
- `memory://` tables keep the existing Arrow snapshot export/rebuild
behavior.
- `Session` and unreconstructable custom namespace clients fail at
`pickle.dumps` with an explicit `TypeError`; declared namespace
configurations reconstruct, including an omitted properties map.
- Namespace storage options keep caller-only overrides layered over the
live provider, with vended values winning conflicts. Caller options
survive refresh, refreshed credentials replace old vended values, an
explicit provider remains selected on open, and an empty provider
response stays empty rather than restoring an expired seed.
- Declared Python namespace connections reopen through their connection
provider instead of turning the reconstructed client into an explicit
table provider.

## Verification

- Fresh binding build with `uv run --extra tests --extra dev maturin
develop --extras tests,dev`.
- End-to-end `DataLoader` holding `self._db` and `self._table`: spawn
and forkserver passed.
- `test_namespace.py`: 90 passed; `test_table.py` + `test_db.py` +
`test_permutation.py`: 700 passed, 17 skipped.
- Focused namespace provider/pickle regressions: passed, including
caller-only and vended keys after a declared-namespace refresh.
- Rust `test_namespace_connection_with_storage_options` and
`test_manifest_enabled_vend_input_storage_options`: passed.
- `cargo clippy -p lancedb --features remote --tests --examples`, `cargo
fmt --check`, exact CI Pyright (0 errors/0 warnings), and Ruff passed.
- DataLoader Workers documentation updated; Vale reports 0 findings.

## Scope

Does not change the fork hard-error policy, #3851, or direct
`LanceNamespaceDBConnection` pickling. It does not claim changes to the
existing namespace dir `index_cache_size` behavior. This supersedes the
earlier draft #3486, which only moved the table-state portion.
This commit is contained in:
Xuanwo
2026-11-20 20:21:27 +08:00
committed by GitHub
parent a9be4525a0
commit 5e9b17b639
12 changed files with 1027 additions and 45 deletions
+30 -1
View File
@@ -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)
+4 -1
View File
@@ -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,
+19 -10
View File
@@ -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"])
+171 -4
View File
@@ -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:
+24
View File
@@ -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
+420
View File
@@ -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(
+123
View File
@@ -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",
+41
View File
@@ -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