From 8fd1c716d9af7cada88503750b4d911f34b775e2 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 06:27:27 +0800 Subject: [PATCH] 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. --- docs/web/training/permutation.mdx | 36 +++ python/python/lancedb/_lancedb.pyi | 9 + python/python/lancedb/permutation.py | 266 ++++++++++++++-- python/python/lancedb/table.py | 48 ++- python/python/tests/test_permutation.py | 290 +++++++++++++++++- python/python/tests/test_s3.py | 31 ++ python/src/permutation.rs | 38 ++- python/src/table.rs | 9 + .../src/dataloader/permutation/builder.rs | 164 +++++++++- 9 files changed, 844 insertions(+), 47 deletions(-) diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx index 0da10f947..952341ea9 100644 --- a/docs/web/training/permutation.mdx +++ b/docs/web/training/permutation.mdx @@ -29,6 +29,42 @@ In specific use cases, you may need the flexibility to shuffle, split, and selec functionality `StreamingDataset` is built on. A `Permutation` defines a customizable row ordering, and supports map-style access through `__getitem__()` and batched access through `__getitems__()`. +## Persisting a permutation {#persisting} + +By default a permutation table is stored in memory. Call `persist` before `execute` to write it to an embedded +LanceDB connection backed by local files or object storage. The plan becomes an ordinary table, so another process +with access to the same storage can open it and use `Permutation.from_tables` to read the same split. + + +```py Python icon=Python +from lancedb.permutation import Permutation, permutation_builder + +db = lancedb.connect("file://some/db/path") +table = db.open_table("some_table") +plan = ( + permutation_builder(table) + .split_random(ratios=[0.8, 0.2], seed=42, split_names=["train", "validation"]) + .persist(db, "splits_v1") + .execute() +) +train = Permutation.from_tables(table, db.open_table("splits_v1"), split="train") +print(train.base_version, train.base_branch) +``` + + +The table returned by `execute` keeps the destination connection and namespace context, so it can be pickled and +reopened directly in a worker process. + +`mode="create"` is the default and fails when the destination table already exists. Pass `mode="overwrite"` to +replace it explicitly. Overwriting writes a new table version; readers that already opened the previous version keep +reading that snapshot. Use `namespace_path` to create the plan in a namespace. Persisting to LanceDB Enterprise +connections is not supported yet, because reproducible Enterprise plan ordering requires deterministic remote row +ordering. + +The plan records the base table version and branch in its schema metadata. `Permutation.base_version` and +`Permutation.base_branch` read those values without querying the base table; both are `None` for older plans that did +not record them. + ## Version Pinning {#version-pinning} A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 129304f0a..82b2a3513 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -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( diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 2a45f4cc4..0369ccec5 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -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: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index c241ab725..57588948f 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -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 diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 4a4c54a56..22df4570c 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -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 ): diff --git a/python/python/tests/test_s3.py b/python/python/tests/test_s3.py index 70b423adb..348f0ea78 100644 --- a/python/python/tests/test_s3.py +++ b/python/python/tests/test_s3.py @@ -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" diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 9cb4da247..f29cc7265 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -9,7 +9,10 @@ use crate::{ use arrow::pyarrow::{PyArrowType, ToPyArrow}; use lancedb::{ dataloader::permutation::{ - builder::{PermutationBuilder as LancePermutationBuilder, ShuffleStrategy}, + builder::{ + PermutationBuilder as LancePermutationBuilder, PermutationPersistMode, + PermutationPersistOptions, ShuffleStrategy, + }, reader::PermutationReader, split::{SplitSizes, SplitStrategy}, }, @@ -17,7 +20,7 @@ use lancedb::{ }; use pyo3::{ Bound, PyAny, PyRef, PyRefMut, PyResult, Python, - exceptions::PyRuntimeError, + exceptions::{PyRuntimeError, PyValueError}, pyclass, pymethods, types::{PyAnyMethods, PyDict, PyDictMethods, PyType}, }; @@ -247,6 +250,37 @@ impl PyAsyncPermutationBuilder { slf.modify(|builder| builder.with_filter(filter)) } + /// Store the permutation table in a database. + /// + /// This is only supported for embedded databases. The destination table is + /// created in the selected namespace, and an existing table is replaced only + /// when ``mode="overwrite"`` is explicit. + #[pyo3(signature = (db, table_name, *, namespace_path=None, mode="create"))] + pub fn persist( + slf: PyRefMut<'_, Self>, + db: PyRef<'_, crate::connection::Connection>, + table_name: String, + namespace_path: Option>, + mode: &str, + ) -> PyResult { + let mode = match mode { + "create" => PermutationPersistMode::Create, + "overwrite" => PermutationPersistMode::Overwrite, + other => { + return Err(PyValueError::new_err(format!( + "Invalid mode {other}; expected 'create' or 'overwrite'" + ))); + } + }; + let database = db.database()?; + let options = PermutationPersistOptions { + namespace_path: namespace_path.unwrap_or_default(), + mode, + }; + + slf.modify(|builder| builder.persist_with_options(database, table_name, options)) + } + pub fn execute(slf: PyRefMut<'_, Self>) -> PyResult> { let mut state = slf.state.lock().unwrap(); let builder = state diff --git a/python/src/table.rs b/python/src/table.rs index 227247307..35337b194 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2120,6 +2120,15 @@ impl Table { }) } + /// Return an independent handle pinned to the currently selected snapshot. + pub fn _checkout_current(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let current = inner.checkout_current().await.infer_error()?; + Ok(Table::new(current)) + }) + } + #[pyo3(signature = (version=None))] pub fn restore( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 770a956eb..93efb130f 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -15,7 +15,7 @@ use crate::{ Error, Result, Table, arrow::{SendableRecordBatchStream, SendableRecordBatchStreamExt, SimpleRecordBatchStream}, connect, - database::{CreateTableRequest, Database}, + database::{CreateTableMode, CreateTableRequest, Database}, dataloader::permutation::{ shuffle::{Shuffler, ShufflerConfig}, split::{SPLIT_ID_COLUMN, SplitStrategy, Splitter}, @@ -43,7 +43,34 @@ enum PermutationDestination { #[default] Temporary, /// The permutation table is a permanent table in a database - Permanent(Arc, String), + Permanent { + database: Arc, + table_name: String, + namespace_path: Vec, + mode: PermutationPersistMode, + }, +} + +/// How a persisted permutation table handles an existing table of the same name. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum PermutationPersistMode { + /// Fail if the destination table already exists. + #[default] + Create, + /// Replace the destination table with the new plan. + /// + /// The previous table version remains readable by handles that were already + /// opened against it. + Overwrite, +} + +/// Options for storing a permutation table in a database. +#[derive(Debug, Clone, Default)] +pub struct PermutationPersistOptions { + /// The namespace path to create the table in. Empty means the root namespace. + pub namespace_path: Vec, + /// Whether an existing table may be replaced. + pub mode: PermutationPersistMode, } /// Configuration for creating a permutation table @@ -161,9 +188,29 @@ impl PermutationBuilder { /// Stores the permutation as a table in a database /// /// By default, the permutation is stored in memory. If this method is called then - /// the permutation will be stored as a table in the given database. - pub fn persist(mut self, database: Arc, table_name: String) -> Self { - self.config.destination = PermutationDestination::Permanent(database, table_name); + /// the permutation will be stored as a table in the given database. The table is + /// created in the root namespace and an existing table is not replaced; use + /// [`Self::persist_with_options`] to choose a namespace or overwrite mode. + pub fn persist(self, database: Arc, table_name: String) -> Self { + self.persist_with_options(database, table_name, PermutationPersistOptions::default()) + } + + /// Stores the permutation as a table in a database with explicit options. + /// + /// This is the same as [`Self::persist`] but lets the caller select the target + /// namespace and whether an existing table may be overwritten. + pub fn persist_with_options( + mut self, + database: Arc, + table_name: String, + options: PermutationPersistOptions, + ) -> Self { + self.config.destination = PermutationDestination::Permanent { + database, + table_name, + namespace_path: options.namespace_path, + mode: options.mode, + }; self } @@ -369,17 +416,31 @@ impl PermutationBuilder { let streaming_data = Self::add_config_metadata(renamed, metadata)?; let (name, database) = match &self.config.destination { - PermutationDestination::Permanent(database, table_name) => { - (table_name.as_str(), database.clone()) - } + PermutationDestination::Permanent { + database, + table_name, + .. + } => (table_name.as_str(), database.clone()), PermutationDestination::Temporary => { let conn = connect("memory:///").execute().await?; ("permutation", conn.database().clone()) } }; - let create_table_request = + let mut create_table_request = CreateTableRequest::new(name.to_string(), Box::new(streaming_data)); + if let PermutationDestination::Permanent { + namespace_path, + mode, + .. + } = &self.config.destination + { + create_table_request.namespace_path = namespace_path.clone(); + create_table_request.mode = match mode { + PermutationPersistMode::Create => CreateTableMode::Create, + PermutationPersistMode::Overwrite => CreateTableMode::Overwrite, + }; + } let table = database.create_table(create_table_request).await?; @@ -1034,4 +1095,89 @@ mod tests { ); assert!(metadata.contains_key(BASE_VERSION_CONFIG_KEY)); } + + #[tokio::test] + async fn test_permutation_persist_create_overwrite_and_namespace() { + use lance_namespace::models::CreateNamespaceRequest; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let initial_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(100), BatchCount::from(1)); + let data_table = db + .create_table("base_tbl", initial_data) + .execute() + .await + .unwrap(); + + let namespace_path = vec!["plans".to_string()]; + db.create_namespace(CreateNamespaceRequest { + id: Some(namespace_path.clone()), + ..Default::default() + }) + .await + .unwrap(); + + let persist = |mode| PermutationPersistOptions { + namespace_path: namespace_path.clone(), + mode, + }; + let first_plan = PermutationBuilder::new(data_table.clone()) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Create), + ) + .build() + .await + .unwrap(); + let first_version = first_plan.version().await.unwrap(); + assert_eq!(first_plan.count_rows(None).await.unwrap(), 100); + + let opened = db + .open_table("splits") + .namespace(namespace_path.clone()) + .execute() + .await + .unwrap(); + assert_eq!(opened.count_rows(None).await.unwrap(), 100); + + let err = PermutationBuilder::new(data_table.clone()) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Create), + ) + .build() + .await + .unwrap_err(); + assert!( + matches!(err, Error::TableAlreadyExists { .. }), + "expected TableAlreadyExists, got: {err:?}" + ); + + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(50), BatchCount::from(1)); + data_table.add(more_data).execute().await.unwrap(); + + let second_plan = PermutationBuilder::new(data_table) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Overwrite), + ) + .build() + .await + .unwrap(); + assert_eq!(second_plan.count_rows(None).await.unwrap(), 150); + + // Overwrite creates a new table version; the old handle stays on its snapshot. + assert_eq!(first_plan.count_rows(None).await.unwrap(), 100); + assert_eq!(first_plan.version().await.unwrap(), first_version); + } }