mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(python): persist permutation plans and reopen pinned snapshots (#5137)
## Summary Add `permutation_builder(base).persist(db, table_name, *, namespace_path=None, mode="create").execute()` for embedded local and object-store destinations. The native create request carries the namespace and create/overwrite mode, with no drop-before-create. The returned table keeps the destination connection context so it can be pickled and reopened directly, including namespaced and manifest-enabled connections. Persisted plans pickle by reference to their own branch and version, so a later overwrite or cross-branch checkout does not change what an existing pickle reads. In-memory plans, old serialized state, and shallow copies keep their existing behavior. `Permutation.base_version` and `base_branch` expose the recorded base snapshot from loaded metadata. Enterprise destinations remain rejected in v1 because reproducible remote plan ordering is follow-up work. ## Verification - `test_permutation.py`: 93 passed. - `test_torch.py`: 23 passed in a compatible torch 2.15 / NumPy 2.2 / PyArrow 26 environment using the abi3 extension. - S3 direct-result persistence/pickle test passed against a disposable loopback Moto server using the existing fixture's fake keys and explicit storage options. - Earlier targeted checks predate the live snapshot pin repair: Rust builder tests 12 passed; Rust check/clippy and Node type-check passed. - The live snapshot pin repair added private PyO3 glue and was verified with a rebuilt extension: `test_permutation.py` 93 passed, `test_torch.py` 23 passed, and one loopback S3 direct-result test passed. - `ruff format --check`, `ruff check`, `pyright`, `git diff --check`: passed.
This commit is contained in:
@@ -651,6 +651,7 @@ class Table:
|
||||
async def version(self) -> int: ...
|
||||
async def checkout(self, version: Union[int, str]): ...
|
||||
async def checkout_latest(self): ...
|
||||
async def _checkout_current(self) -> Table: ...
|
||||
async def restore(self, version: Optional[Union[int, str]] = None): ...
|
||||
async def prewarm_index(self, index_name: str) -> None: ...
|
||||
async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ...
|
||||
@@ -1356,6 +1357,14 @@ class AsyncPermutationBuilder:
|
||||
self, seed: Optional[int], clump_size: Optional[int]
|
||||
) -> "AsyncPermutationBuilder": ...
|
||||
def filter(self, filter: str) -> "AsyncPermutationBuilder": ...
|
||||
def persist(
|
||||
self,
|
||||
db: Connection,
|
||||
table_name: str,
|
||||
*,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
mode: str = "create",
|
||||
) -> "AsyncPermutationBuilder": ...
|
||||
async def execute(self) -> Table: ...
|
||||
|
||||
def async_permutation_builder(
|
||||
|
||||
@@ -8,6 +8,7 @@ import os
|
||||
from deprecation import deprecated
|
||||
import pyarrow as pa
|
||||
|
||||
from ._lancedb import Connection as NativeConnection
|
||||
from ._lancedb import async_permutation_builder, PermutationReader
|
||||
from .table import LanceTable, Table
|
||||
from .background_loop import LOOP
|
||||
@@ -16,11 +17,26 @@ from .util import (
|
||||
batch_to_tensor_columns,
|
||||
batch_to_tensor_dict,
|
||||
batch_to_tensor_rows,
|
||||
get_uri_scheme,
|
||||
)
|
||||
from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from lancedb.dependencies import pandas as pd, numpy as np, polars as pl
|
||||
from .db import DBConnection
|
||||
|
||||
|
||||
def _native_connection(db: Any) -> Any:
|
||||
"""Return the native connection wrapped by a sync or async connection."""
|
||||
async_connection = getattr(db, "_conn", None)
|
||||
if async_connection is not None:
|
||||
return _native_connection(async_connection)
|
||||
inner = getattr(db, "_inner", None)
|
||||
if inner is not None:
|
||||
return _native_connection(inner)
|
||||
if isinstance(db, NativeConnection):
|
||||
return db
|
||||
raise TypeError("db must be a LanceDB connection")
|
||||
|
||||
|
||||
class PermutationBuilder:
|
||||
@@ -43,7 +59,9 @@ class PermutationBuilder:
|
||||
be referenced by name in the future. If names are not provided then they can only
|
||||
be referenced by their ordinal index. There is no requirement to name every split.
|
||||
|
||||
The permutation is stored in memory and will be lost when the program exits.
|
||||
The permutation is stored in memory and will be lost when the program exits,
|
||||
unless [persist][lancedb.permutation.PermutationBuilder.persist] is called before
|
||||
[execute][lancedb.permutation.PermutationBuilder.execute].
|
||||
"""
|
||||
|
||||
def __init__(self, table: Table):
|
||||
@@ -56,6 +74,9 @@ class PermutationBuilder:
|
||||
Tables with an RTE write spec are rejected: unflushed rows have no row id.
|
||||
"""
|
||||
self._async = async_permutation_builder(table)
|
||||
self._persist_connection: Optional[Any] = None
|
||||
self._persist_table_name: Optional[str] = None
|
||||
self._persist_namespace_path: list[str] = []
|
||||
|
||||
def split_random(
|
||||
self,
|
||||
@@ -262,6 +283,76 @@ class PermutationBuilder:
|
||||
self._async.filter(filter)
|
||||
return self
|
||||
|
||||
def persist(
|
||||
self,
|
||||
db: "DBConnection",
|
||||
table_name: str,
|
||||
*,
|
||||
namespace_path: Optional[list[str]] = None,
|
||||
mode: Literal["create", "overwrite"] = "create",
|
||||
) -> "PermutationBuilder":
|
||||
"""
|
||||
Store the permutation table in an embedded database.
|
||||
|
||||
Persisting a plan makes the same split available to another process or
|
||||
another machine with access to the destination storage. The plan is an
|
||||
ordinary LanceDB table containing row ids and split ids; it can be
|
||||
opened with [open_table][lancedb.db.DBConnection.open_table] and passed to
|
||||
[Permutation.from_tables][lancedb.permutation.Permutation.from_tables].
|
||||
The table returned by ``execute`` keeps the destination connection and
|
||||
namespace context, so it can be pickled and reopened directly.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
db: DBConnection
|
||||
An embedded LanceDB connection. Local files and object storage are
|
||||
supported; LanceDB Enterprise connections are not supported yet.
|
||||
table_name: str
|
||||
The name of the permutation table to create.
|
||||
namespace_path: list[str], optional
|
||||
The namespace to create the table in. The default is the root
|
||||
namespace.
|
||||
mode: {"create", "overwrite"}, default "create"
|
||||
``create`` fails if the destination table already exists.
|
||||
``overwrite`` writes a new version of the table. Readers that already
|
||||
opened the previous version keep reading that snapshot.
|
||||
|
||||
Returns
|
||||
-------
|
||||
PermutationBuilder
|
||||
This builder, so ``persist`` can be chained with the split, filter,
|
||||
and execute methods.
|
||||
"""
|
||||
if mode not in ("create", "overwrite"):
|
||||
raise ValueError(f"Invalid mode {mode!r}; expected 'create' or 'overwrite'")
|
||||
|
||||
uri = getattr(db, "uri", None)
|
||||
if uri is None:
|
||||
raise TypeError("db must be a LanceDB connection")
|
||||
if get_uri_scheme(str(uri)) == "db":
|
||||
raise NotImplementedError(
|
||||
"Permutation persistence is not supported for LanceDB Enterprise "
|
||||
"connections yet; reproducible Enterprise plan ordering requires "
|
||||
"deterministic remote row ordering."
|
||||
)
|
||||
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
elif not isinstance(namespace_path, (list, tuple)):
|
||||
raise TypeError("namespace_path must be a list of strings or None")
|
||||
|
||||
namespace_path = list(namespace_path)
|
||||
self._async.persist(
|
||||
_native_connection(db),
|
||||
table_name,
|
||||
namespace_path=namespace_path,
|
||||
mode=mode,
|
||||
)
|
||||
self._persist_connection = db
|
||||
self._persist_table_name = table_name
|
||||
self._persist_namespace_path = namespace_path
|
||||
return self
|
||||
|
||||
def execute(self) -> LanceTable:
|
||||
"""
|
||||
Execute the configuration and create the permutation table.
|
||||
@@ -269,7 +360,14 @@ class PermutationBuilder:
|
||||
|
||||
async def do_execute():
|
||||
inner_tbl = await self._async.execute()
|
||||
return await LanceTable.from_inner(inner_tbl)
|
||||
if self._persist_connection is None:
|
||||
return await LanceTable.from_inner(inner_tbl)
|
||||
return await LanceTable.from_inner(
|
||||
inner_tbl,
|
||||
connection=self._persist_connection,
|
||||
name=self._persist_table_name,
|
||||
namespace_path=self._persist_namespace_path,
|
||||
)
|
||||
|
||||
return LOOP.run(do_execute())
|
||||
|
||||
@@ -411,6 +509,11 @@ class Transforms:
|
||||
DEFAULT_BATCH_SIZE = 100
|
||||
|
||||
|
||||
def _is_persisted_plan(table: Table) -> bool:
|
||||
"""Whether a permutation table lives in reopenable storage rather than memory."""
|
||||
return isinstance(table, LanceTable) and not table._conn.uri.startswith("memory://")
|
||||
|
||||
|
||||
def _table_to_pickle_state(table: Table) -> dict[str, Any]:
|
||||
from .remote.table import RemoteTable
|
||||
|
||||
@@ -497,6 +600,9 @@ class Permutation:
|
||||
limit: Optional[int] = None,
|
||||
connection_factory: Optional[Callable[[str], Table]] = None,
|
||||
_reader: Optional[PermutationReader] = None,
|
||||
_plan_metadata: Optional[dict[bytes, bytes]] = None,
|
||||
_plan_version: Optional[int] = None,
|
||||
_plan_branch: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Internal constructor. Use
|
||||
@@ -513,6 +619,9 @@ class Permutation:
|
||||
self.offset = offset
|
||||
self.limit = limit
|
||||
self.connection_factory = connection_factory
|
||||
self._plan_metadata = _plan_metadata
|
||||
self._plan_version = _plan_version
|
||||
self._plan_branch = _plan_branch
|
||||
if _reader is None:
|
||||
_reader = LOOP.run(self._build_reader())
|
||||
self.reader: PermutationReader = _reader
|
||||
@@ -652,6 +761,17 @@ class Permutation:
|
||||
then the first split will be used.
|
||||
"""
|
||||
assert base_table is not None, "base_table is required"
|
||||
persisted_plan = permutation_table is not None and _is_persisted_plan(
|
||||
permutation_table
|
||||
)
|
||||
if persisted_plan:
|
||||
# Pin before reading metadata or constructing the reader. The caller's
|
||||
# handle may keep tracking latest, but the live reader and pickle must
|
||||
# share one immutable plan snapshot.
|
||||
permutation_table = permutation_table._pin_current_snapshot()
|
||||
plan_metadata = None if permutation_table is not None else {}
|
||||
if permutation_table is not None and (isinstance(split, str) or persisted_plan):
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
if split is not None:
|
||||
if permutation_table is None:
|
||||
raise ValueError(
|
||||
@@ -659,12 +779,7 @@ class Permutation:
|
||||
" because no permutation table is provided"
|
||||
)
|
||||
if isinstance(split, str):
|
||||
if permutation_table.schema.metadata is None:
|
||||
raise ValueError(
|
||||
f"Cannot create a permutation on split `{split}`"
|
||||
" because no split names are defined in the permutation table"
|
||||
)
|
||||
raw = permutation_table.schema.metadata.get(b"split_names")
|
||||
raw = (plan_metadata or {}).get(b"split_names")
|
||||
split_names = raw.decode("utf-8") if raw is not None else None
|
||||
if split_names is None:
|
||||
raise ValueError(
|
||||
@@ -687,6 +802,14 @@ class Permutation:
|
||||
else:
|
||||
split = 0
|
||||
|
||||
plan_version = None
|
||||
plan_branch = None
|
||||
if persisted_plan:
|
||||
# Pin the pickled plan to the snapshot this object was created from,
|
||||
# not what the destination name points at after an overwrite.
|
||||
plan_version = permutation_table.version
|
||||
plan_branch = permutation_table.current_branch()
|
||||
|
||||
async def do_from_tables():
|
||||
reader = await PermutationReader.from_tables(
|
||||
base_table, permutation_table, split
|
||||
@@ -701,6 +824,9 @@ class Permutation:
|
||||
DEFAULT_BATCH_SIZE,
|
||||
Transforms.arrow2python,
|
||||
_reader=reader,
|
||||
_plan_metadata=plan_metadata,
|
||||
_plan_version=plan_version,
|
||||
_plan_branch=plan_branch,
|
||||
)
|
||||
|
||||
return LOOP.run(do_from_tables())
|
||||
@@ -710,18 +836,43 @@ class Permutation:
|
||||
|
||||
The base table is captured either via a user-supplied
|
||||
``connection_factory`` (see [with_connection_factory]) or, as a
|
||||
fallback, by the table's own picklable reopen state. The permutation
|
||||
table is captured as a pyarrow Table (which pickles via Arrow IPC
|
||||
natively). The reader is dropped from the wire format and rebuilt
|
||||
lazily on first use.
|
||||
fallback, by the table's own picklable reopen state. A permutation
|
||||
table in memory is captured as a pyarrow Table (which pickles via Arrow
|
||||
IPC natively). A persisted plan is reopened by reference and pinned to
|
||||
the plan snapshot this object was built from. The reader is dropped
|
||||
from the wire format and rebuilt lazily on first use.
|
||||
"""
|
||||
base_table_state = (
|
||||
None
|
||||
if self.connection_factory is not None
|
||||
else _table_to_pickle_state(self.base_table)
|
||||
)
|
||||
base_is_memory = (
|
||||
base_table_state is not None and base_table_state["kind"] == "memory"
|
||||
)
|
||||
|
||||
permutation_data: Optional[pa.Table] = None
|
||||
if self.permutation_table is not None:
|
||||
permutation_table_state: Optional[dict[str, Any]] = None
|
||||
if (
|
||||
self.permutation_table is not None
|
||||
and _is_persisted_plan(self.permutation_table)
|
||||
and not base_is_memory
|
||||
):
|
||||
plan_state = _table_to_pickle_state(self.permutation_table)
|
||||
# Keep the plan's own branch/version coordinate. A later overwrite
|
||||
# of the destination must not change what this pickle reads.
|
||||
table_state = plan_state["state"]
|
||||
if self._plan_version is not None:
|
||||
table_state["checkout_version"] = self._plan_version
|
||||
# None is the main branch. Restore it explicitly because the
|
||||
# live handle may have moved to another branch since capture.
|
||||
table_state["branch"] = self._plan_branch
|
||||
permutation_table_state = plan_state
|
||||
elif self.permutation_table is not None:
|
||||
permutation_data = self.permutation_table.to_arrow()
|
||||
|
||||
common = {
|
||||
"base_table_name": self.base_table.name,
|
||||
"permutation_data": permutation_data,
|
||||
"split": self.split,
|
||||
"selection": self.selection,
|
||||
"batch_size": self.batch_size,
|
||||
@@ -730,17 +881,13 @@ class Permutation:
|
||||
"limit": self.limit,
|
||||
"connection_factory": self.connection_factory,
|
||||
}
|
||||
|
||||
if self.connection_factory is not None:
|
||||
# The factory carries enough state to recover the base table on
|
||||
# its own; we don't need to capture the URI / storage options /
|
||||
# namespace from the existing connection.
|
||||
return common
|
||||
|
||||
return {
|
||||
**common,
|
||||
"base_table_state": _table_to_pickle_state(self.base_table),
|
||||
}
|
||||
if permutation_table_state is not None:
|
||||
common["permutation_table_state"] = permutation_table_state
|
||||
else:
|
||||
common["permutation_data"] = permutation_data
|
||||
if base_table_state is not None:
|
||||
common["base_table_state"] = base_table_state
|
||||
return common
|
||||
|
||||
def __setstate__(self, state: dict[str, Any]) -> None:
|
||||
from . import connect
|
||||
@@ -772,17 +919,32 @@ class Permutation:
|
||||
)
|
||||
|
||||
permutation_table: Optional[Table] = None
|
||||
permutation_data = state["permutation_data"]
|
||||
if permutation_data is not None:
|
||||
if rebuilt_base:
|
||||
# The base table was materialized from Arrow, so it is a fresh
|
||||
# single-version dataset and the recorded pin cannot resolve on it.
|
||||
permutation_data = _drop_base_version(permutation_data)
|
||||
mem_db = connect("memory://")
|
||||
permutation_table = mem_db.create_table("permutation", permutation_data)
|
||||
plan_metadata: dict[bytes, bytes] = {}
|
||||
plan_version = None
|
||||
plan_branch = None
|
||||
if "permutation_table_state" in state:
|
||||
plan_state = state["permutation_table_state"]
|
||||
permutation_table = _table_from_pickle_state(plan_state)
|
||||
nested_state = plan_state.get("state", {})
|
||||
plan_version = nested_state.get("checkout_version")
|
||||
plan_branch = nested_state.get("branch")
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
else:
|
||||
permutation_data = state.get("permutation_data")
|
||||
if permutation_data is not None:
|
||||
if rebuilt_base:
|
||||
# The base table was materialized from Arrow, so it is a fresh
|
||||
# single-version dataset and the recorded pin cannot resolve on it.
|
||||
permutation_data = _drop_base_version(permutation_data)
|
||||
mem_db = connect("memory://")
|
||||
permutation_table = mem_db.create_table("permutation", permutation_data)
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
|
||||
self.base_table = base_table
|
||||
self.permutation_table = permutation_table
|
||||
self._plan_metadata = plan_metadata
|
||||
self._plan_version = plan_version
|
||||
self._plan_branch = plan_branch
|
||||
self.split = state["split"]
|
||||
self.selection = state["selection"]
|
||||
self.batch_size = state["batch_size"]
|
||||
@@ -807,6 +969,44 @@ class Permutation:
|
||||
new.__dict__ = self.__dict__.copy()
|
||||
return new
|
||||
|
||||
def _loaded_plan_metadata(self) -> dict[bytes, bytes]:
|
||||
if self._plan_metadata is None:
|
||||
self._plan_metadata = (
|
||||
dict(self.permutation_table.schema.metadata or {})
|
||||
if self.permutation_table is not None
|
||||
else {}
|
||||
)
|
||||
return self._plan_metadata
|
||||
|
||||
@property
|
||||
def base_version(self) -> Optional[int]:
|
||||
"""The base table version recorded in the plan, or ``None`` for legacy plans.
|
||||
|
||||
This value comes from the plan's schema metadata, so reading it does not
|
||||
query the base table. Version numbers are per-branch; see
|
||||
[base_branch][lancedb.permutation.Permutation.base_branch].
|
||||
"""
|
||||
raw = self._loaded_plan_metadata().get(b"base_version")
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as error:
|
||||
raise ValueError(
|
||||
f"Permutation table has an unreadable base_version of {raw!r}"
|
||||
) from error
|
||||
|
||||
@property
|
||||
def base_branch(self) -> Optional[str]:
|
||||
"""The base table branch recorded in the plan, or ``None`` for main.
|
||||
|
||||
Legacy plans recorded no branch and therefore also return ``None``.
|
||||
"""
|
||||
raw = self._loaded_plan_metadata().get(b"base_branch")
|
||||
if raw is None:
|
||||
return None
|
||||
return raw.decode("utf-8")
|
||||
|
||||
def _ensure_open(self) -> None:
|
||||
pid = os.getpid()
|
||||
if self.reader is not None and getattr(self, "_pid", None) == pid:
|
||||
|
||||
@@ -4437,10 +4437,40 @@ class LanceTable(Table):
|
||||
return self._namespace_path
|
||||
|
||||
@classmethod
|
||||
async def from_inner(cls, tbl: LanceDBTable):
|
||||
async def from_inner(
|
||||
cls,
|
||||
tbl: LanceDBTable,
|
||||
*,
|
||||
connection: Optional["DBConnection"] = None,
|
||||
name: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
location: Optional[str] = None,
|
||||
):
|
||||
async_tbl = AsyncTable(tbl)
|
||||
if connection is not None:
|
||||
# A table created through a Python connection keeps that
|
||||
# connection's explicit options. Reconstructing a bare connection
|
||||
# from the native handle loses namespace, storage, manifest and
|
||||
# Session state needed by pickle.
|
||||
return cls(
|
||||
connection,
|
||||
name or async_tbl.name,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=getattr(connection, "storage_options", None),
|
||||
location=location,
|
||||
namespace_client=getattr(connection, "_namespace_client", None),
|
||||
managed_versioning=getattr(connection, "_managed_versioning", None),
|
||||
pushdown_operations=getattr(
|
||||
connection, "_namespace_client_pushdown_operations", None
|
||||
),
|
||||
route_pushdown_to_rust=getattr(
|
||||
connection, "_route_pushdown_to_rust", False
|
||||
),
|
||||
_async=async_tbl,
|
||||
)
|
||||
|
||||
from .db import AsyncConnection, LanceDBConnection
|
||||
|
||||
async_tbl = AsyncTable(tbl)
|
||||
inner_conn = tbl.database()
|
||||
read_consistency_interval = await AsyncConnection(
|
||||
inner_conn
|
||||
@@ -4670,6 +4700,16 @@ class LanceTable(Table):
|
||||
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
|
||||
return self._table.current_branch()
|
||||
|
||||
def _pin_current_snapshot(self) -> "LanceTable":
|
||||
"""Return an independent handle pinned to this table's current snapshot."""
|
||||
|
||||
async def do_pin():
|
||||
pinned = await self._table._checkout_current()
|
||||
return pinned, await pinned.version()
|
||||
|
||||
pinned, version = LOOP.run(do_pin())
|
||||
return self._wrap_branch_handle(pinned, version)
|
||||
|
||||
def _wrap_branch_handle(
|
||||
self, async_table: "AsyncTable", version: Optional[int] = None
|
||||
) -> "LanceTable":
|
||||
@@ -9664,6 +9704,10 @@ class AsyncTable:
|
||||
"""
|
||||
return await self._inner.version()
|
||||
|
||||
async def _checkout_current(self) -> "AsyncTable":
|
||||
"""Return an independent handle pinned to the currently selected snapshot."""
|
||||
return AsyncTable(await self._inner._checkout_current())
|
||||
|
||||
async def list_versions(self):
|
||||
"""
|
||||
List all versions of the table
|
||||
|
||||
@@ -5,7 +5,7 @@ import pyarrow as pa
|
||||
import math
|
||||
import pytest
|
||||
|
||||
from lancedb import DBConnection, Table, connect
|
||||
from lancedb import DBConnection, Session, Table, connect, connect_namespace
|
||||
from lancedb.background_loop import LOOP
|
||||
from lancedb.permutation import (
|
||||
DEFAULT_BATCH_SIZE,
|
||||
@@ -21,6 +21,18 @@ from utils import (
|
||||
)
|
||||
|
||||
|
||||
def _read_permutation_in_spawned_process(payload: bytes, output) -> None:
|
||||
import pickle
|
||||
|
||||
permutation = pickle.loads(payload)
|
||||
output.put(
|
||||
[
|
||||
row["id"]
|
||||
for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_split_random_ratios(mem_db):
|
||||
"""Test random splitting with ratios."""
|
||||
tbl = mem_db.create_table(
|
||||
@@ -87,6 +99,282 @@ def test_pickled_permutation_reads_pinned_version(tmp_path):
|
||||
assert sorted(row["idx"] for row in rows) == list(range(20))
|
||||
|
||||
|
||||
def test_persist_plan_create_overwrite_namespace_and_metadata(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
db.create_namespace(["plans"])
|
||||
namespace_path = ["plans"]
|
||||
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits", namespace_path=namespace_path)
|
||||
.execute()
|
||||
)
|
||||
assert plan.count_rows() == 20
|
||||
assert plan.namespace == namespace_path
|
||||
assert pickle.loads(pickle.dumps(plan)).namespace == namespace_path
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
assert permutation.base_version == tbl.version
|
||||
assert permutation.base_branch is None
|
||||
assert permutation.num_rows == 10
|
||||
|
||||
with pytest.raises((ValueError, RuntimeError), match="already exists"):
|
||||
(
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2)
|
||||
.persist(db, "splits", namespace_path=namespace_path)
|
||||
.execute()
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid mode"):
|
||||
permutation_builder(tbl).persist(db, "other", mode="replace")
|
||||
|
||||
class RemoteLike:
|
||||
uri = "db://example"
|
||||
|
||||
with pytest.raises(NotImplementedError, match="Enterprise"):
|
||||
permutation_builder(tbl).persist(RemoteLike(), "remote_splits")
|
||||
|
||||
tbl.add(pa.table({"id": range(20, 40)}))
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2)
|
||||
.persist(db, "splits", namespace_path=namespace_path, mode="overwrite")
|
||||
.execute()
|
||||
)
|
||||
assert plan.count_rows() == 40
|
||||
assert db.open_table("splits", namespace_path=namespace_path).count_rows() == 40
|
||||
# The earlier permutation still reads the plan and base snapshot it was built from.
|
||||
assert permutation.num_rows == 10
|
||||
assert [row["id"] for row in permutation.__getitems__([0, 1])] == [0, 1]
|
||||
|
||||
|
||||
def test_persist_namespace_connection_direct_result_pickle(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect_namespace("dir", {"root": str(tmp_path)})
|
||||
db.create_namespace(["plans"])
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits", namespace_path=["plans"])
|
||||
.execute()
|
||||
)
|
||||
assert plan.namespace == ["plans"]
|
||||
assert plan._conn is db
|
||||
|
||||
restored_plan = pickle.loads(pickle.dumps(plan))
|
||||
assert restored_plan.namespace == ["plans"]
|
||||
assert restored_plan.count_rows() == 20
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.num_rows == 10
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
) == list(range(10))
|
||||
|
||||
|
||||
def test_persist_direct_result_keeps_session_pickle_error(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, session=Session())
|
||||
tbl = db.create_table("base", pa.table({"id": range(5)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
with pytest.raises(TypeError, match="Session"):
|
||||
pickle.dumps(plan)
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan)
|
||||
with pytest.raises(TypeError, match="Session"):
|
||||
pickle.dumps(permutation)
|
||||
|
||||
|
||||
def test_persist_direct_result_preserves_manifest_connection_state(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, manifest_enabled=True)
|
||||
tbl = db.create_table("base", pa.table({"id": range(5)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
restored = pickle.loads(pickle.dumps(plan))
|
||||
assert restored._conn._manifest_enabled is True
|
||||
assert restored.count_rows() == 5
|
||||
|
||||
|
||||
def test_base_branch_property_reads_plan_metadata(tmp_path):
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(10)}))
|
||||
branch = tbl.branches.create("exp")
|
||||
branch.add(pa.table({"id": range(10, 20)}))
|
||||
|
||||
plan = permutation_builder(branch).persist(db, "branch_splits").execute()
|
||||
permutation = Permutation.from_tables(branch, plan)
|
||||
|
||||
assert permutation.base_branch == "exp"
|
||||
assert permutation.base_version == branch.version
|
||||
assert permutation.num_rows == 20
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_reopens_same_snapshot_after_overwrite(tmp_path):
|
||||
from datetime import timedelta
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = permutation_builder(tbl).filter("id < 10").persist(db, "splits").execute()
|
||||
permutation = Permutation.from_tables(tbl, plan)
|
||||
old_base_version = permutation.base_version
|
||||
old_plan_version = permutation._plan_version
|
||||
state = permutation.__getstate__()
|
||||
assert "permutation_data" not in state
|
||||
assert (
|
||||
state["permutation_table_state"]["state"]["checkout_version"]
|
||||
== old_plan_version
|
||||
)
|
||||
|
||||
# Replace the plan with disjoint rows of the same cardinality.
|
||||
permutation_builder(tbl).filter("id >= 10").persist(
|
||||
db, "splits", mode="overwrite"
|
||||
).execute()
|
||||
assert plan.version == old_plan_version + 1
|
||||
assert permutation.permutation_table.version == old_plan_version
|
||||
|
||||
live_ids = [
|
||||
row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
assert live_ids == list(range(10))
|
||||
|
||||
# A reader recreated after the overwrite must still use the pinned snapshot.
|
||||
permutation.reader = None
|
||||
permutation._pid = None
|
||||
recreated_ids = [
|
||||
row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
assert recreated_ids == list(range(10))
|
||||
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.base_version == old_base_version
|
||||
restored_ids = [
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
]
|
||||
assert restored_ids == list(range(10))
|
||||
|
||||
# A newly constructed permutation sees the overwritten plan.
|
||||
fresh = Permutation.from_tables(tbl, db.open_table("splits"))
|
||||
assert fresh.base_version == old_base_version
|
||||
fresh_ids = [row["id"] for row in fresh.__getitems__(list(range(fresh.num_rows)))]
|
||||
assert fresh_ids == list(range(10, 20))
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_uses_captured_main_branch(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
initial_plan = db.open_table("splits")
|
||||
initial_plan.branches.create("exp", from_version=1)
|
||||
|
||||
# Main plan version 2 still has all 20 rows.
|
||||
permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute()
|
||||
main_plan = db.open_table("splits")
|
||||
assert main_plan.version == 2
|
||||
|
||||
# Branch plan version 2 has different contents, so the numeric version alone
|
||||
# does not identify the snapshot.
|
||||
branch_plan = db.open_table("splits", branch="exp")
|
||||
branch_plan.add(
|
||||
pa.table(
|
||||
{
|
||||
"row_id": pa.array([0], type=pa.uint64()),
|
||||
"split_id": pa.array([0], type=pa.uint32()),
|
||||
}
|
||||
)
|
||||
)
|
||||
branch_plan = db.open_table("splits", branch="exp")
|
||||
assert branch_plan.version == 2
|
||||
assert branch_plan.count_rows() == 21
|
||||
branch_plan.tags.create("exp_v2", 2)
|
||||
|
||||
permutation = Permutation.from_tables(tbl, main_plan)
|
||||
|
||||
# Move the same passed-in plan handle to the other branch at the same
|
||||
# numeric version. Pickle must still reopen the captured main snapshot.
|
||||
main_plan.checkout("exp_v2")
|
||||
assert main_plan.current_branch() == "exp"
|
||||
assert main_plan.version == 2
|
||||
payload = pickle.dumps(permutation)
|
||||
|
||||
restored = pickle.loads(payload)
|
||||
assert restored.permutation_table.current_branch() is None
|
||||
assert restored.permutation_table.version == 2
|
||||
assert restored.num_rows == 20
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_reopens_in_spawned_process(tmp_path):
|
||||
import multiprocessing as mp
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(12)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
payload = pickle.dumps(Permutation.from_tables(tbl, plan))
|
||||
|
||||
tbl.add(pa.table({"id": range(12, 24)}))
|
||||
permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute()
|
||||
|
||||
context = mp.get_context("spawn")
|
||||
output = context.Queue()
|
||||
process = context.Process(
|
||||
target=_read_permutation_in_spawned_process, args=(payload, output)
|
||||
)
|
||||
process.start()
|
||||
try:
|
||||
ids = output.get(timeout=60)
|
||||
finally:
|
||||
process.join(timeout=60)
|
||||
|
||||
assert process.exitcode == 0
|
||||
assert sorted(ids) == list(range(12))
|
||||
|
||||
|
||||
def test_old_permutation_pickle_state_still_round_trips(tmp_path):
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = permutation_builder(tbl).execute()
|
||||
state = {
|
||||
"base_table_name": tbl.name,
|
||||
"permutation_data": plan.to_arrow(),
|
||||
"split": 0,
|
||||
"selection": {"id": "id"},
|
||||
"batch_size": DEFAULT_BATCH_SIZE,
|
||||
"transform_fn": Transforms.arrow2python,
|
||||
"offset": None,
|
||||
"limit": None,
|
||||
"connection_factory": None,
|
||||
"base_table_uri": str(tmp_path),
|
||||
"base_table_storage_options": None,
|
||||
"base_table_namespace": [],
|
||||
}
|
||||
|
||||
restored = Permutation.__new__(Permutation)
|
||||
restored.__setstate__(state)
|
||||
|
||||
assert restored.base_version == tbl.version
|
||||
assert restored.base_branch is None
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
) == list(range(20))
|
||||
|
||||
|
||||
def test_builder_copy_is_shallow_and_does_not_materialize(
|
||||
some_table: Table, some_perm_table: Table, monkeypatch
|
||||
):
|
||||
|
||||
@@ -11,6 +11,7 @@ import threading
|
||||
import pytest
|
||||
import pyarrow as pa
|
||||
import lancedb
|
||||
from lancedb.permutation import Permutation, permutation_builder
|
||||
|
||||
|
||||
# These are all keys that are accepted by storage_options
|
||||
@@ -87,6 +88,36 @@ def test_s3_lifecycle(s3_bucket: str):
|
||||
asyncio.run(test())
|
||||
|
||||
|
||||
@pytest.mark.s3_test
|
||||
def test_s3_permutation_persist_direct_result_pickle(s3_bucket: str):
|
||||
import pickle
|
||||
|
||||
storage_options = copy.copy(CONFIG)
|
||||
uri = f"s3://{s3_bucket}/test_permutation_persist"
|
||||
db = lancedb.connect(uri, storage_options=storage_options)
|
||||
try:
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits")
|
||||
.execute()
|
||||
)
|
||||
assert plan._storage_options == storage_options
|
||||
|
||||
restored_plan = pickle.loads(pickle.dumps(plan))
|
||||
assert restored_plan.count_rows() == 20
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.num_rows == 10
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
) == list(range(10))
|
||||
finally:
|
||||
db.drop_all_tables()
|
||||
|
||||
|
||||
@pytest.mark.s3_test
|
||||
def test_concurrent_open_table(s3_bucket: str):
|
||||
uri = f"s3://{s3_bucket}/test_concurrent_open_table"
|
||||
|
||||
Reference in New Issue
Block a user