mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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:
@@ -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
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user