Merge main and align cosine patch with Lance beta.34

This commit is contained in:
Gatefixer
2026-11-25 00:45:44 +00:00
57 changed files with 2517 additions and 455 deletions
+2 -2
View File
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.0.0b32",
"pylance==15.0.0b34",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
@@ -75,7 +75,7 @@ dev = [
"pyright>=1.1.350",
"maturin>=1.10",
]
docs = ["mkdocs", "mkdocs-jupyter", "mkdocs-material", "mkdocstrings-python"]
docs = ["mkdocs", "mkdocs-jupyter", "mkdocs-material>=9.8.2", "mkdocstrings[python]>=1.0.7,<2"]
clip = ["torch", "pillow>=13.0.0", "open-clip-torch"]
siglip = ["torch", "pillow>=13.0.0", "transformers>=4.41.0","sentencepiece"]
embeddings = [
+3
View File
@@ -27,6 +27,7 @@ from .index import (
NGram,
ZoneMap,
RTree,
ScalarPlugin,
HnswPq,
HnswSq,
HnswFlat,
@@ -682,6 +683,7 @@ class Table:
NGram,
ZoneMap,
RTree,
ScalarPlugin,
FTS,
],
replace: Optional[bool],
@@ -708,6 +710,7 @@ class Table:
NGram,
ZoneMap,
RTree,
ScalarPlugin,
FTS,
],
replace: Optional[bool],
+5 -2
View File
@@ -99,8 +99,6 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
texts: list[str] or np.ndarray (of str)
The texts to embed
"""
openai = attempt_import_or_raise("openai")
valid_texts = []
valid_indices = []
for idx, text in enumerate(texts):
@@ -108,6 +106,11 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
valid_texts.append(text)
valid_indices.append(idx)
if not valid_texts:
return [None] * len(texts)
openai = attempt_import_or_raise("openai")
# TODO retry, rate limit, token limit
def embed_batch(texts_batch, indices_batch):
kwargs = {
+81 -1
View File
@@ -2,7 +2,8 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from dataclasses import dataclass
from typing import List, Literal, Optional
import json
from typing import Any, Dict, List, Literal, Optional, Union
from ._lancedb import (
IndexConfig,
@@ -186,6 +187,84 @@ class RTree:
page_size: Optional[int] = None
@dataclass
class ScalarPlugin:
"""Configure a scalar index of a type recognized by a registered database plugin.
Use this for index types without a dedicated configuration class.
Prefer a dedicated class, such as [BTree][lancedb.index.BTree], when one
is available.
An unknown plugin name or invalid parameters cause index creation to fail.
Examples
--------
>>> from lancedb.index import ScalarPlugin
>>> ScalarPlugin("bloomfilter", params={"number_of_items": 4096})
ScalarPlugin(index_type='bloomfilter', params={'number_of_items': 4096})
Pass it as ``config`` to ``create_index``:
>>> table.create_index( # doctest: +SKIP
... "id",
... config=ScalarPlugin("bloomfilter", '{"probability": 0.01}'),
... )
Attributes
----------
index_type: str
The index type, case-insensitive. Surrounding whitespace is ignored.
Must not be empty.
params: dict or str, optional
The index parameters, as a dict or as a string holding a JSON object.
They are passed as given. Each plugin defines its parameters and
defaults; refer to the plugin's documentation for guidance.
Raises
------
ValueError
If ``index_type`` is empty, or ``params`` is a string that is not a
JSON object.
TypeError
If ``index_type`` is not a string, or ``params`` is not a dict, a
string or None.
"""
index_type: str
params: Optional[Union[Dict[str, Any], str]] = None
def __post_init__(self):
if not isinstance(self.index_type, str):
raise TypeError(
"ScalarPlugin index_type must be a str, got "
+ type(self.index_type).__name__
)
if not self.index_type.strip():
raise ValueError("ScalarPlugin index_type must not be empty")
if isinstance(self.params, str):
try:
parsed = json.loads(self.params)
except json.JSONDecodeError as e:
raise ValueError(f"ScalarPlugin params are not valid JSON: {e}") from e
if not isinstance(parsed, dict):
raise ValueError(
"ScalarPlugin params must be a JSON object, got "
+ type(parsed).__name__
)
elif self.params is not None and not isinstance(self.params, dict):
raise TypeError(
"ScalarPlugin params must be a dict, a JSON string or None, got "
+ type(self.params).__name__
)
@property
def _params_json(self) -> Optional[str]:
# Read by the native layer, which checks again that this is an object.
if self.params is None or isinstance(self.params, str):
return self.params
return json.dumps(self.params)
@dataclass
class FTS:
"""Describe a FTS index configuration.
@@ -1041,4 +1120,5 @@ __all__ = [
"Fm",
"NGram",
"RTree",
"ScalarPlugin",
]
+200 -2
View File
@@ -512,6 +512,88 @@ class Transforms:
# HuggingFace uses 10 which is pretty small
DEFAULT_BATCH_SIZE = 100
_MAP_FORMAT_ERROR = (
"map cannot be combined with with_format or with_transform; convert the "
"output inside the map callback or in the DataLoader collate_fn instead"
)
def _map_rows(data: Any, num_rows: int) -> list[dict[str, Any]]:
"""Return the data flowing through a map chain as a list of row dicts."""
if isinstance(data, pa.RecordBatch):
return data.to_pylist()
if isinstance(data, dict):
return [
{name: values[i] for name, values in data.items()} for i in range(num_rows)
]
return data
def _map_columns(data: Any) -> dict[str, Any]:
"""Return the data flowing through a map chain as a dict of columns."""
if isinstance(data, pa.RecordBatch):
return data.to_pydict()
if isinstance(data, list):
names = data[0].keys()
if any(row.keys() != names for row in data):
raise ValueError(
"Cannot pass rows to a batched map callback because the previous "
"callback did not return the same keys for every row"
)
return {name: [row[name] for row in data] for name in names}
return data
class _MapTransform:
"""
The transform installed by [map][lancedb.permutation.Permutation.map]
Each step is a ``(fn, batched)`` pair. This is a module-level class, and not a
closure, so that a mapped permutation pickles whenever its callbacks do.
"""
def __init__(self, steps: tuple[tuple[Callable, bool], ...]):
self.steps = steps
def __call__(self, batch: pa.RecordBatch) -> list[dict[str, Any]]:
num_rows = batch.num_rows
if num_rows == 0:
return []
# The layout is only converted when a callback needs the other one
data = batch
for fn, batched in self.steps:
if batched:
data = fn(_map_columns(data))
if not isinstance(data, dict):
raise TypeError(
"A batched map callback must return a dict of columns, "
f"got {type(data).__name__}"
)
for name, values in data.items():
# A str or dict can be indexed but is not a column of values
if isinstance(values, (str, bytes, dict)) or not hasattr(
values, "__getitem__"
):
raise TypeError(
"A batched map callback must return a list of values "
f"for column `{name}`, got {type(values).__name__}"
)
if len(values) != num_rows:
raise ValueError(
f"A batched map callback returned {len(values)} values "
f"for column `{name}` but the batch has {num_rows} rows"
)
else:
data = [fn(row) for row in _map_rows(data, num_rows)]
for row in data:
if not isinstance(row, dict):
raise TypeError(
"A map callback must return a dict for each row, "
f"got {type(row).__name__}"
)
return _map_rows(data, num_rows)
def _is_persisted_plan(table: Table) -> bool:
"""Whether a permutation table lives in reopenable storage rather than memory."""
@@ -619,6 +701,9 @@ class Permutation:
self.split = split
self.selection = selection
self.transform_fn = transform_fn
# Whether the default transform was replaced, by with_format, by
# with_transform, or by a caller passing its own transform here
self._explicit_transform = transform_fn is not Transforms.arrow2python
self.batch_size = batch_size
self.offset = offset
self.limit = limit
@@ -881,6 +966,7 @@ class Permutation:
"selection": self.selection,
"batch_size": self.batch_size,
"transform_fn": self.transform_fn,
"explicit_transform": self._explicit_transform,
"offset": self.offset,
"limit": self.limit,
"connection_factory": self.connection_factory,
@@ -953,6 +1039,11 @@ class Permutation:
self.selection = state["selection"]
self.batch_size = state["batch_size"]
self.transform_fn = state["transform_fn"]
# Pickles written before this flag existed still carry their transform.
# Anything but the default must have been set explicitly.
self._explicit_transform = state.get(
"explicit_transform", self.transform_fn is not Transforms.arrow2python
)
self.offset = state["offset"]
self.limit = state["limit"]
self.connection_factory = connection_factory
@@ -1304,8 +1395,16 @@ class Permutation:
For custom formatting, use
[with_transform][lancedb.permutation.Permutation.with_transform] which
overrides this method.
A format cannot be combined with
[map][lancedb.permutation.Permutation.map], which always yields a list
of dicts. Doing so raises a ValueError.
"""
assert format is not None, "format is required"
# Checked before with_transform does, so that a format with an optional
# dependency cannot fail on its import first
if isinstance(self.transform_fn, _MapTransform):
raise ValueError(_MAP_FORMAT_ERROR)
if format == "python":
return self.with_transform(Transforms.arrow2python)
if format == "python_col":
@@ -1338,10 +1437,109 @@ class Permutation:
Note: transforms are not invoked in parallel. This method is not a good place
for expensive operations such as image decoding.
For a higher-level API that works with Python dicts, see
[map][lancedb.permutation.Permutation.map]. A transform cannot be combined
with ``map``. Doing so raises a ValueError.
"""
assert transform is not None, "transform is required"
if isinstance(self.transform_fn, _MapTransform):
raise ValueError(_MAP_FORMAT_ERROR)
new = copy.copy(self)
new.transform_fn = transform
new._explicit_transform = True
return new
def map(
self,
fn: Callable[[dict[str, Any]], dict[str, Any]],
*,
batched: bool = False,
) -> "Permutation":
"""
Apply a function to the rows of the permutation
This is a dict-based alternative to
[with_transform][lancedb.permutation.Permutation.with_transform], loosely
modeled after the huggingface ``Dataset.map``. It is lazy: ``fn`` is not
called until data is read.
Calls to ``map`` can be chained. The callbacks run in order and the dict
returned by a callback replaces the row entirely, so the next callback only
sees what the previous one returned. Unlike the huggingface method, the
returned dict is not merged into the row: return every column to keep.
A mapped permutation always yields a list of dicts (one per row) for each
batch, which is the same shape as the default "python" format. ``batched``
only controls what ``fn`` receives. Rows keep their position, so a callback
cannot add, drop, or reorder rows.
Since ``map`` decides the output format it cannot be combined with
[with_format][lancedb.permutation.Permutation.with_format] or
[with_transform][lancedb.permutation.Permutation.with_transform]. Calling
one after the other, in either order, raises a ValueError. Convert the
mapped rows to tensors in the DataLoader ``collate_fn`` instead.
[select_columns][lancedb.permutation.Permutation.select_columns],
[remove_columns][lancedb.permutation.Permutation.remove_columns],
[rename_column][lancedb.permutation.Permutation.rename_column] and
[schema][lancedb.permutation.Permutation.schema] describe the columns read
from the base table, which are the input of the first callback. They do
not describe the output of ``map``, whether they are used before or after it.
Parameters
----------
fn: Callable
The function to apply. It receives and returns a single row as a dict
mapping column names to values. If ``batched`` is True it instead
receives and returns a whole batch as a dict mapping column names to
lists of values, and every returned column must have one value per
input row.
DataLoader workers started with ``spawn`` or ``forkserver`` receive a
pickled copy of the permutation, so ``fn`` must then be picklable.
Use a top-level function; lambdas and local functions do not pickle.
batched: bool, default False
Whether ``fn`` is called once per batch instead of once per row.
Examples
--------
>>> import lancedb
>>> db = lancedb.connect("memory:///")
>>> tbl = db.create_table("tbl", data=[{"x": x} for x in range(3)])
>>> def add_y(row):
... return {**row, "y": row["x"] * 2}
>>> def add_z(batch):
... return {**batch, "z": [x + y for x, y in zip(batch["x"], batch["y"])]}
>>> permutation = Permutation.identity(tbl).map(add_y).map(add_z, batched=True)
>>> permutation.take_offsets([0, 1])
[{'x': 0, 'y': 0, 'z': 0}, {'x': 1, 'y': 2, 'z': 3}]
With a PyTorch DataLoader, a ``collate_fn`` turns the mapped rows of each
batch into tensors::
import torch
def collate(rows):
return {
"x": torch.tensor([row["x"] for row in rows]),
"z": torch.tensor([row["z"] for row in rows]),
}
dataloader = torch.utils.data.DataLoader(
permutation, batch_size=32, shuffle=True, collate_fn=collate
)
"""
if not callable(fn):
raise TypeError("fn must be callable")
if self._explicit_transform:
raise ValueError(_MAP_FORMAT_ERROR)
steps = ((fn, batched),)
if isinstance(self.transform_fn, _MapTransform):
steps = self.transform_fn.steps + steps
new = copy.copy(self)
new.transform_fn = _MapTransform(steps)
return new
def take_offsets(self, offsets: list[int]) -> Any:
@@ -1349,8 +1547,8 @@ class Permutation:
Take rows from the permutation by offset
The returned value is passed through the permutation's current transform,
so `with_format` and `with_transform` affect this method in the same way
they affect iteration.
so `with_format`, `with_transform`, and `map` affect this method in the
same way they affect iteration.
"""
self._ensure_open()
+1 -1
View File
@@ -619,7 +619,7 @@ class RemoteTable(Table):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
wait_timeout : timedelta, optional
+9 -4
View File
@@ -82,6 +82,7 @@ from .index import (
NGram,
ZoneMap,
RTree,
ScalarPlugin,
HnswPq,
HnswSq,
HnswFlat,
@@ -354,6 +355,7 @@ IndexConfigType = Union[
NGram,
ZoneMap,
RTree,
ScalarPlugin,
FTS,
]
@@ -2028,7 +2030,7 @@ class Table(ABC):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
@@ -5162,7 +5164,7 @@ class LanceTable(Table):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
@@ -7873,6 +7875,7 @@ class AsyncTable:
NGram,
ZoneMap,
RTree,
ScalarPlugin,
FTS,
]
] = None,
@@ -7955,13 +7958,14 @@ class AsyncTable:
NGram,
ZoneMap,
RTree,
ScalarPlugin,
FTS,
),
):
raise TypeError(
"config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
" BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, or FTS,"
" but got " + str(type(config))
" BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree,"
" ScalarPlugin, or FTS, but got " + str(type(config))
)
try:
await self._inner.create_index(
@@ -8002,6 +8006,7 @@ class AsyncTable:
NGram,
ZoneMap,
RTree,
ScalarPlugin,
FTS,
]
] = None,
+41
View File
@@ -1107,6 +1107,47 @@ def test_openai_bad_request_partial_batch_recovery():
assert embeddings[1] is None
@pytest.fixture
def mock_openai_client(monkeypatch):
client = MagicMock()
client.embeddings.create.return_value.data = []
monkeypatch.setattr(
"lancedb.embeddings.openai.attempt_import_or_raise", MagicMock()
)
monkeypatch.setattr(get_registry().get("openai"), "_openai_client", client)
return client
@pytest.mark.parametrize(
("texts", "expected"),
[([], []), ([None, ""], [None, None])],
ids=["empty-batch", "all-inputs-filtered"],
)
def test_openai_skips_batches_without_valid_text(mock_openai_client, texts, expected):
model = get_registry().get("openai").create()
assert model.compute_source_embeddings(texts) == expected
mock_openai_client.embeddings.create.assert_not_called()
def test_openai_add_all_invalid_texts_as_null_vectors(mock_openai_client, tmp_path):
model = get_registry().get("openai").create(name="text-embedding-3-small", dim=2)
class TextModel(LanceModel):
text: Optional[str] = model.SourceField()
vector: Optional[Vector(model.ndims())] = model.VectorField()
db = lancedb.connect(tmp_path)
table = db.create_table("words", schema=TextModel)
table.add([{"text": None}, {"text": ""}], on_bad_vectors="null")
assert table.to_arrow().to_pylist() == [
{"text": None, "vector": None},
{"text": "", "vector": None},
]
mock_openai_client.embeddings.create.assert_not_called()
def test_ollama_embeddings_pickle():
"""OllamaEmbeddings must pickle even after the cached client is created."""
registry = get_registry()
+127
View File
@@ -26,6 +26,7 @@ from lancedb.index import (
NGram,
ZoneMap,
RTree,
ScalarPlugin,
HnswPq,
HnswSq,
HnswFlat,
@@ -687,6 +688,132 @@ async def test_create_zonemap_index(db_async):
assert sorted(result["id"].to_pylist()) == list(range(90, 100))
def plugin_table_data():
return pa.table(
{"id": [1, 2, 3, 4], "text": ["abc", "xyz", None, ""]},
schema=pa.schema([("id", pa.int32()), ("text", pa.string())]),
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"index_type, params, column, expected_type, predicate, expected_ids",
[
("ZoneMap", None, "id", "ZoneMap", "id >= 2 AND id < 4", [2, 3]),
(" BTREE ", None, "id", "BTree", "id = 3", [3]),
(
"bloomfilter",
{"number_of_items": 2, "probability": 0.01},
"text",
"BloomFilter",
"text = 'abc'",
[1],
),
(
"BloomFilter",
'{"number_of_items": 2}',
"text",
"BloomFilter",
"text = 'abc'",
[1],
),
],
)
async def test_create_scalar_plugin_index(
db_async, index_type, params, column, expected_type, predicate, expected_ids
):
# Lance's built-in plugins, created by name, are listed with the same type
# as their dedicated configs and serve the filters those configs serve.
table = await db_async.create_table("plugin_table", plugin_table_data())
config = ScalarPlugin(index_type, params)
await table.create_index(column, config=config, name="plugin_idx")
indices = await table.list_indices()
assert [(i.name, i.index_type, i.columns) for i in indices] == [
("plugin_idx", expected_type, [column])
]
stats = await table.index_stats("plugin_idx")
assert stats.num_indexed_rows == 4
query = table.query().where(predicate)
assert "ScalarIndexQuery" in await query.explain_plan()
result = await query.to_arrow()
assert sorted(result["id"].to_pylist()) == expected_ids
@pytest.mark.asyncio
async def test_scalar_plugin_without_lancedb_type_lists_plugin_name(db_async):
data = pa.table({"text": ["alpha beta", "beta gamma", "gamma delta"]})
table = await db_async.create_table("minhash_table", data)
await table.create_index("text", config=ScalarPlugin("minhashlsh"))
indices = await table.list_indices()
assert len(indices) == 1
assert indices[0].index_type == "MinHashLsh"
assert 'index_type="MinHashLsh"' in repr(indices[0])
stats = await table.index_stats(indices[0].name)
assert stats.index_type == "MinHashLsh"
def test_scalar_plugin_sync_table_and_job(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("plugin_table", plugin_table_data())
table.create_index("id", config=ScalarPlugin("zonemap"))
job = table.create_index_async(
"text",
config=ScalarPlugin("bloomfilter", {"probability": 0.01}),
name="text_bloom",
)
job.wait()
types = {index.name: index.index_type for index in table.list_indices()}
assert types == {"id_idx": "ZoneMap", "text_bloom": "BloomFilter"}
assert "ScalarIndexQuery" in table.search().where("text = 'abc'").explain_plan()
@pytest.mark.parametrize(
"kwargs, error, match",
[
({"index_type": ""}, ValueError, "must not be empty"),
({"index_type": " "}, ValueError, "must not be empty"),
({"index_type": None}, TypeError, "index_type must be a str"),
({"index_type": "zonemap", "params": "[1]"}, ValueError, "got list"),
({"index_type": "zonemap", "params": "null"}, ValueError, "got NoneType"),
({"index_type": "zonemap", "params": "{x"}, ValueError, "not valid JSON"),
({"index_type": "zonemap", "params": [1]}, TypeError, "got list"),
({"index_type": "zonemap", "params": 1}, TypeError, "got int"),
],
)
def test_scalar_plugin_rejects_invalid_config(kwargs, error, match):
with pytest.raises(error, match=match):
ScalarPlugin(**kwargs)
@pytest.mark.asyncio
async def test_scalar_plugin_errors_reach_the_caller(db_async):
table = await db_async.create_table("plugin_table", plugin_table_data())
# The native layer checks the params again, after the dataclass is mutated.
config = ScalarPlugin("zonemap")
config.params = "[1]"
with pytest.raises(ValueError, match="must be a JSON object, got an array"):
await table.create_index("id", config=config)
with pytest.raises(
ValueError, match="No scalar index plugin found for name 'nosuchplugin'"
):
await table.create_index("id", config=ScalarPlugin("NoSuchPlugin"))
with pytest.raises(ValueError, match="ngram index can only be created on a Utf8"):
await table.create_index("id", config=ScalarPlugin("ngram"))
with pytest.raises(RuntimeError, match='invalid type: string "many"'):
await table.create_index(
"text",
config=ScalarPlugin("bloomfilter", {"number_of_items": "many"}),
)
assert await table.list_indices() == []
@pytest.mark.asyncio
async def test_create_bitmap_index(some_table: AsyncTable):
await some_table.create_index("id", config=Bitmap())
+241
View File
@@ -1856,3 +1856,244 @@ def test_from_tables_split_without_permutation_table(mem_db):
with pytest.raises(ValueError, match="permutation on split `train` because no"):
Permutation.from_tables(tbl, split="train")
def _double_value_row(row):
return {"id": row["id"], "value": row["value"] * 2}
def _double_value_batch(batch):
return {"id": batch["id"], "value": [value * 2 for value in batch["value"]]}
def test_map_row_by_row(some_permutation: Permutation):
"""Test .map() applies fn to each row individually."""
mapped = some_permutation.map(_double_value_row)
batches = list(mapped.iter(10, skip_last_batch=False))
first_batch = batches[0]
assert len(first_batch) == 10
assert isinstance(first_batch[0], dict)
for row in first_batch:
assert row["value"] == row["id"] * 2
def test_map_batched(some_permutation: Permutation):
"""Test batched only changes what fn receives, not what is yielded."""
seen = []
def double_value(batch):
seen.append(batch)
return _double_value_batch(batch)
mapped = some_permutation.map(double_value, batched=True)
first_batch = next(mapped.iter(10, skip_last_batch=False))
assert isinstance(seen[0], dict)
assert len(seen[0]["id"]) == 10
assert first_batch == next(
some_permutation.map(_double_value_row).iter(10, skip_last_batch=False)
)
def test_map_chain(some_permutation: Permutation):
"""Test chained maps run in order and each one replaces the whole row."""
def add_doubled(row):
return {**row, "doubled": row["value"] * 2}
def to_total(batch):
return {
"total": [a + b for a, b in zip(batch["value"], batch["doubled"])],
}
def add_label(row):
return {**row, "label": str(row["total"])}
first = some_permutation.map(add_doubled)
mapped = first.map(to_total, batched=True).map(add_label)
expected = [
{"total": row["value"] * 3, "label": str(row["value"] * 3)}
for row in some_permutation.take_offsets([0, 1, 2])
]
assert mapped.take_offsets([0, 1, 2]) == expected
assert next(mapped.iter(3, skip_last_batch=False)) == expected
# Extending a chain does not change the permutation it was derived from
assert set(first.take_offsets([0])[0]) == {"id", "value", "doubled"}
@pytest.mark.parametrize(
"explicit",
[
lambda permutation: permutation.with_format("python"),
lambda permutation: permutation.with_format("arrow"),
lambda permutation: permutation.with_transform(Transforms.arrow2arrow),
],
)
def test_map_rejects_format_and_transform(some_permutation: Permutation, explicit):
"""Test .map() cannot be mixed with with_format or with_transform."""
with pytest.raises(ValueError, match="map cannot be combined"):
explicit(some_permutation).map(_double_value_row)
with pytest.raises(ValueError, match="map cannot be combined"):
explicit(some_permutation.map(_double_value_row))
def test_map_rejects_format_without_optional_dependency(
some_permutation: Permutation, monkeypatch
):
"""Test the map check runs before a format imports an optional dependency."""
import sys
# Make polars fail to import, as it does on an install without extras
monkeypatch.setitem(sys.modules, "polars", None)
with pytest.raises(ValueError, match="map cannot be combined"):
some_permutation.map(_double_value_row).with_format("polars")
def test_map_rejects_explicit_transform_from_old_pickle(
some_permutation: Permutation,
):
"""Test pickles written before explicit_transform existed keep the guard."""
def restore_without_flag(permutation):
state = permutation.__getstate__()
del state["explicit_transform"]
restored = Permutation.__new__(Permutation)
restored.__setstate__(state)
return restored
with pytest.raises(ValueError, match="map cannot be combined"):
restore_without_flag(some_permutation.with_format("arrow")).map(
_double_value_row
)
# The default transform is indistinguishable from an explicit "python" format
mapped = restore_without_flag(some_permutation).map(_double_value_row)
assert mapped.take_offsets([0]) == [
_double_value_row(row) for row in some_permutation.take_offsets([0])
]
def test_map_rejects_transform_passed_to_constructor(some_table: Table):
"""Test a transform given to the constructor counts as explicit too."""
permutation = Permutation(
some_table,
None,
0,
{"id": "id"},
DEFAULT_BATCH_SIZE,
Transforms.arrow2arrow,
)
with pytest.raises(ValueError, match="map cannot be combined"):
permutation.map(_double_value_row)
def test_map_take_offsets(some_permutation: Permutation):
"""Test .map() keeps the positions and duplicates of the requested offsets."""
calls = []
def record(batch):
calls.append(batch)
return batch
mapped = some_permutation.map(_double_value_row).map(record, batched=True)
offsets = [5, 0, 5, 2]
expected = [
_double_value_row(row) for row in some_permutation.take_offsets(offsets)
]
assert mapped.take_offsets(offsets) == expected
assert mapped.__getitems__(offsets) == expected
calls.clear()
assert mapped.take_offsets([]) == []
assert calls == []
def test_map_validates_output(some_permutation: Permutation):
"""Test .map() rejects callback output that would break the batch shape."""
with pytest.raises(ValueError, match="returned 1 values for column `id`"):
some_permutation.map(
lambda batch: {"id": batch["id"][:1]}, batched=True
).take_offsets([0, 1])
with pytest.raises(TypeError, match="must return a dict of columns, got list"):
some_permutation.map(
lambda batch: list(batch.values()), batched=True
).take_offsets([0, 1])
# A str has the right length here but is still not a column of values
for value in (2, "ab"):
with pytest.raises(TypeError, match="list of values for column `n`, got"):
some_permutation.map(lambda batch: {"n": value}, batched=True).take_offsets(
[0, 1]
)
with pytest.raises(
TypeError, match="must return a dict for each row, got NoneType"
):
some_permutation.map(lambda row: None).take_offsets([0, 1])
with pytest.raises(ValueError, match="did not return the same keys for every row"):
some_permutation.map(
lambda row: row if row["id"] % 2 else {"id": row["id"]}
).map(lambda batch: batch, batched=True).take_offsets(list(range(10)))
def test_map_projection_and_schema(some_permutation: Permutation):
"""Test the selection and schema describe the read that feeds the callbacks."""
def to_str(row):
return {name: str(value) for name, value in row.items()}
mapped = some_permutation.map(to_str)
assert mapped.schema == some_permutation.schema
assert mapped.column_names == ["id", "value"]
for projected in (
some_permutation.select_columns(["id"]).map(to_str),
mapped.select_columns(["id"]),
mapped.remove_columns(["value"]),
):
assert projected.schema == some_permutation.select_columns(["id"]).schema
assert list(projected.take_offsets([0])[0]) == ["id"]
renamed = mapped.rename_column("value", "data")
assert renamed.column_names == ["id", "data"]
assert list(renamed.take_offsets([0])[0]) == ["id", "data"]
def test_map_is_lazy(some_permutation: Permutation):
"""Test .map() does not call fn until iteration."""
call_count = [0]
def counting_fn(row):
call_count[0] += 1
return row
mapped = some_permutation.map(counting_fn)
assert call_count[0] == 0
mapped.__getitems__([0])
assert call_count[0] == 1
def test_map_non_callable(some_permutation: Permutation):
"""Test .map() raises TypeError for non-callable fn."""
with pytest.raises(TypeError, match="fn must be callable"):
some_permutation.map("not a function")
@pytest.mark.parametrize(
"fn, batched", [(_double_value_row, False), (_double_value_batch, True)]
)
def test_map_pickle_round_trip(some_permutation: Permutation, fn, batched):
"""Test a mapped permutation reads the same data after a pickle round trip."""
import pickle
mapped = some_permutation.map(fn, batched=batched)
restored = pickle.loads(pickle.dumps(mapped))
offsets = [3, 1, 3]
assert restored.take_offsets(offsets) == mapped.take_offsets(offsets)
assert restored.take_offsets(offsets)[0]["value"] == (
some_permutation.take_offsets(offsets)[0]["value"] * 2
)
# The restored permutation keeps enforcing the map / format constraint
with pytest.raises(ValueError, match="map cannot be combined"):
restored.with_format("arrow")
explicit = pickle.loads(pickle.dumps(some_permutation.with_format("arrow")))
with pytest.raises(ValueError, match="map cannot be combined"):
explicit.map(fn, batched=batched)
+68
View File
@@ -3526,6 +3526,74 @@ def test_remote_create_rtree_index():
]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_remote_scalar_plugin_nests_params(use_async):
from lancedb.index import ScalarPlugin
received_requests = []
def handler(request):
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
if request.path == "/v1/table/test/describe/":
fields = [{"name": "id", "type": {"type": "int32"}, "nullable": False}]
request.wfile.write(
json.dumps({"version": 1, "schema": {"fields": fields}}).encode()
)
elif request.path == "/v1/table/test/create_index/":
received_requests.append(read_json_body(request))
request.wfile.write(b"{}")
else:
raise AssertionError(f"Unexpected request: {request.path}")
cases = [
(ScalarPlugin(" ZoneMap "), {}),
(
ScalarPlugin("bloomfilter", {"number_of_items": 4096, "column": "not_id"}),
{"name": "id_bloom", "replace": False},
),
(ScalarPlugin("bloomfilter", '{"probability": 0.01}'), {}),
(ScalarPlugin("zonemap", {}), {}),
]
if use_async:
async with mock_lancedb_connection_async(handler) as db:
table = await db.open_table("test")
for config, options in cases:
await table.create_index("id", config=config, **options)
else:
with mock_lancedb_connection(handler) as db:
table = db.open_table("test")
for config, options in cases:
table.create_index("id", config=config, **options)
assert received_requests == [
{"column": "id", "index_type": "PLUGIN", "plugin_type": "ZONEMAP"},
{
"column": "id",
"index_type": "PLUGIN",
"plugin_type": "BLOOMFILTER",
"name": "id_bloom",
"replace": False,
"params": {"number_of_items": 4096, "column": "not_id"},
},
{
"column": "id",
"index_type": "PLUGIN",
"plugin_type": "BLOOMFILTER",
"params": {"probability": 0.01},
},
{
"column": "id",
"index_type": "PLUGIN",
"plugin_type": "ZONEMAP",
"params": {},
},
]
@pytest.mark.parametrize(
"rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}]
)
+32
View File
@@ -631,6 +631,38 @@ def test_permutation_torch_dict_dataloader_spawn(tmp_db):
assert sorted(seen) == list(range(11))
def _map_add_scaled(row):
return {**row, "scaled": row["a"] * 2}
def _map_add_total(batch):
total = [a + scaled for a, scaled in zip(batch["a"], batch["scaled"])]
return {**batch, "total": total}
def test_permutation_map_dataloader_spawn(tmp_db):
"""A map chain must be picklable so spawned DataLoader workers can run it."""
table = tmp_db.create_table("test_table", pa.table({"a": range(100)}))
permutation = (
Permutation.identity(table)
.map(_map_add_scaled)
.map(_map_add_total, batched=True)
)
dataloader = torch.utils.data.DataLoader(
permutation,
batch_size=10,
num_workers=1,
multiprocessing_context="spawn",
)
seen = []
for batch in dataloader:
assert set(batch) == {"a", "scaled", "total"}
assert torch.equal(batch["total"], batch["a"] * 3)
seen.extend(batch["a"].tolist())
assert seen == list(range(100))
def test_batch_to_tensor_columns_zero_copy_and_slice_offsets():
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
nested_values = np.arange(5 * 3 * 2, dtype=np.float32).reshape(5, 3, 2)
+25 -4
View File
@@ -7,10 +7,10 @@ use lancedb::index::vector::{
IvfPqIndexBuilder, IvfRqIndexBuilder, IvfSqIndexBuilder,
};
use lancedb::index::{
Index as LanceDbIndex,
Index as LanceDbIndex, IndexType,
scalar::{
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
RTreeIndexBuilder, ZoneMapIndexBuilder,
PluginIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder,
},
};
use pyo3::IntoPyObject;
@@ -129,6 +129,15 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
}
Ok(LanceDbIndex::RTree(builder))
}
"ScalarPlugin" => {
let params = source.extract::<ScalarPluginParams>()?;
let invalid = |err: lancedb::Error| PyValueError::new_err(err.to_string());
let mut builder = PluginIndexBuilder::new(params.index_type).map_err(invalid)?;
if let Some(json) = params.params_json {
builder = builder.params_json(json).map_err(invalid)?;
}
Ok(LanceDbIndex::Plugin(builder))
}
"FTS" => {
let params = source.extract::<FtsParams>()?;
let code_options = CodeAnalyzerOptions {
@@ -303,7 +312,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
Ok(LanceDbIndex::IvfHnswFlat(hnsw_flat_builder))
}
not_supported => Err(PyValueError::new_err(format!(
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
not_supported
))),
}
@@ -312,6 +321,13 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
}
}
#[derive(FromPyObject)]
struct ScalarPluginParams {
index_type: String,
#[pyo3(attribute("_params_json"))]
params_json: Option<String>,
}
#[derive(FromPyObject)]
struct FtsParams {
with_position: bool,
@@ -554,7 +570,12 @@ fn parse_index_details(py: Python<'_>, s: String) -> Py<PyAny> {
impl IndexConfig {
pub fn from_lancedb(py: Python<'_>, value: lancedb::index::IndexConfig) -> Self {
let index_type = format!("{:?}", value.index_type);
// A registered plugin's type is its display name, such as "MinHashLsh",
// which `Debug` would render as `Custom("MinHashLsh")`.
let index_type = match value.index_type {
IndexType::Custom(name) => name,
index_type => format!("{index_type:?}"),
};
Self {
index_type,
columns: value.columns,
+24 -19
View File
@@ -1,5 +1,5 @@
version = 1
revision = 3
revision = 5
requires-python = ">=3.11"
resolution-markers = [
"python_full_version >= '3.14' and sys_platform == 'win32'",
@@ -1813,7 +1813,7 @@ docs = [
{ name = "mkdocs" },
{ name = "mkdocs-jupyter" },
{ name = "mkdocs-material" },
{ name = "mkdocstrings-python" },
{ name = "mkdocstrings", extra = ["python"] },
]
embeddings = [
{ name = "awscli" },
@@ -1888,8 +1888,8 @@ requires-dist = [
{ name = "maturin", marker = "extra == 'dev'", specifier = ">=1.10" },
{ name = "mkdocs", marker = "extra == 'docs'" },
{ name = "mkdocs-jupyter", marker = "extra == 'docs'" },
{ name = "mkdocs-material", marker = "extra == 'docs'" },
{ name = "mkdocstrings-python", marker = "extra == 'docs'" },
{ name = "mkdocs-material", marker = "extra == 'docs'", specifier = ">=9.8.2" },
{ name = "mkdocstrings", extras = ["python"], marker = "extra == 'docs'", specifier = ">=1.0.7,<2" },
{ name = "numpy", specifier = ">=1.24.0" },
{ name = "oci", marker = "extra == 'embeddings'", specifier = ">=2.165.1" },
{ name = "ollama", marker = "extra == 'embeddings'", specifier = ">=0.3.0" },
@@ -1912,7 +1912,7 @@ requires-dist = [
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
{ name = "pydantic", specifier = ">=2.7.4,<3" },
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b32" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b34" },
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
@@ -2182,7 +2182,7 @@ wheels = [
[[package]]
name = "mkdocs-material"
version = "9.7.6"
version = "9.8.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "babel" },
@@ -2197,9 +2197,9 @@ dependencies = [
{ name = "pymdown-extensions" },
{ name = "requests" },
]
sdist = { url = "https://files.pythonhosted.org/packages/45/29/6d2bcf41ae40802c4beda2432396fff97b8456fb496371d1bc7aad6512ec/mkdocs_material-9.7.6.tar.gz", hash = "sha256:00bdde50574f776d328b1862fe65daeaf581ec309bd150f7bff345a098c64a69", size = 4097959, upload-time = "2026-03-19T15:41:58.161Z" }
sdist = { url = "https://files.pythonhosted.org/packages/99/bf/c47389fa622b513c2d115eb4c16075ef04a5f4d8156039f46cb26e5c70a9/mkdocs_material-9.8.2.tar.gz", hash = "sha256:005d942bdbfa22efa049f4818c31d42fb36bed6d362adb641dd7a2e948078f9d", size = 4160697, upload-time = "2026-11-19T19:52:25.799Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2c/01/bc663630c510822c95c47a66af9fa7a443c295b47d5f041e5e6ae62ef659/mkdocs_material-9.7.6-py3-none-any.whl", hash = "sha256:71b84353921b8ea1ba84fe11c50912cc512da8fe0881038fcc9a0761c0e635ba", size = 9305470, upload-time = "2026-03-19T15:41:55.217Z" },
{ url = "https://files.pythonhosted.org/packages/18/86/9204441dd9e224f1dc3f1a32edf6a474e84696bfa493c7df067dcde36366/mkdocs_material-9.8.2-py3-none-any.whl", hash = "sha256:ef1414cab33d64fcc13387e972af5ba4620f55f93482d1842933399ed2c69b02", size = 9302480, upload-time = "2026-11-19T19:52:22.436Z" },
]
[[package]]
@@ -2213,7 +2213,7 @@ wheels = [
[[package]]
name = "mkdocstrings"
version = "1.0.4"
version = "1.0.7"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "jinja2" },
@@ -2223,9 +2223,14 @@ dependencies = [
{ name = "mkdocs-autorefs" },
{ name = "pymdown-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1d/5d/f888d4d3eb31359b327bc9b17a212d6ef03fe0b0682fbb3fc2cb849fb12b/mkdocstrings-1.0.4.tar.gz", hash = "sha256:3969a6515b77db65fd097b53c1b7aa4ae840bd71a2ee62a6a3e89503446d7172", size = 100088, upload-time = "2026-04-15T09:16:53.376Z" }
sdist = { url = "https://files.pythonhosted.org/packages/f5/e8/445b19834bf9559ebbbaa76897e965665b83d2861461eed8d8de4d122057/mkdocstrings-1.0.7.tar.gz", hash = "sha256:0951b147f352118a45a3db85f0f3b660833d34cb5120a2751315b8d08dafd159", size = 103739, upload-time = "2026-10-10T13:50:59.957Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/6e/94/be70f8ee9c45f2f62b39a1f0e9303bc20e138a8f3b8e50ffd89498e177e1/mkdocstrings-1.0.4-py3-none-any.whl", hash = "sha256:63464b4b29053514f32a1dbbf604e52876d5e638111b0c295ab7ed3cac73ca9b", size = 35560, upload-time = "2026-04-15T09:16:51.436Z" },
{ url = "https://files.pythonhosted.org/packages/22/c3/9062531735ff1fd27f3a79c353c4cf4d822eeffd062fd90b2c553a96f4bb/mkdocstrings-1.0.7-py3-none-any.whl", hash = "sha256:9563828667eeb35256f87a6b61fe857676ac628ec1abbce9aea9839a502c9cb1", size = 41597, upload-time = "2026-10-10T13:50:58.43Z" },
]
[package.optional-dependencies]
python = [
{ name = "mkdocstrings-python" },
]
[[package]]
@@ -3644,20 +3649,20 @@ crypto = [
[[package]]
name = "pylance"
version = "15.0.0b32"
version = "15.0.0b34"
source = { registry = "https://pypi.fury.io/lance-format/" }
dependencies = [
{ name = "lance-namespace" },
{ name = "pyarrow" },
]
wheels = [
{ url = "https://pypi.fury.io/lance-format/-/ver_1mmPD/pylance-15.0.0b32-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:1946f9559385773909c685fe46c474e988d4d283d78cab5bbcfa6f32769e8623" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1fg8VI/pylance-15.0.0b32-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c5623245aa21700fe7377f9c25c15d87e3e38ea178eb315877a184352c6e399" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1rf9nS/pylance-15.0.0b32-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:87e6b46d8c629fbf3d0383e5d515a95857bc8a5635c5d19d0b5e8a562b218ba6" },
{ url = "https://pypi.fury.io/lance-format/-/ver_176TqH/pylance-15.0.0b32-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:2cd78d8a4472f31d292bd8ccc530a83af8b3e11563898a9748d8404d12c12b03" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1gbxKE/pylance-15.0.0b32-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b6ebff00b80f00bd5c809b83a046981f9ba3f33bac8b347cc44b95ec235c16c0" },
{ url = "https://pypi.fury.io/lance-format/-/ver_qSF36/pylance-15.0.0b32-cp310-abi3-win_amd64.whl", hash = "sha256:5edc7d24a93e363186e0ffe561aa00eaeda7140cad26885043b378ffe64f10e0" },
{ url = "https://pypi.fury.io/lance-format/-/ver_JyVBF/pylance-15.0.0b32-cp310-abi3-win_arm64.whl", hash = "sha256:0d066b44acb0949b3f59eefe30092c982f9797dcb41423dd10fcd63210a2f06e" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2c6cEN/pylance-15.0.0b34-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:a57e6864acf83fef3729ce51e27edf5a76179c308eb747ef0ec6cc51231ef968" },
{ url = "https://pypi.fury.io/lance-format/-/ver_oRvqr/pylance-15.0.0b34-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6546b3631fcf8a1dd18b144c0d29fe152320b2e91c3a83ccdca2e3b36d66afb6" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1uoRCM/pylance-15.0.0b34-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2077fdfba60fb40db49b2afbb0c35a0fa1935977a7c3820007eef36f4bc758af" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2auLpe/pylance-15.0.0b34-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:97a5a3d24388619eec61bee71589794517ff7df41fcfdaae2e56e5e8fb1da80d" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1pf71p/pylance-15.0.0b34-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b0f20b4957d81e0ca5461b3fbd27a37863124d4303a232925c25efab614449b2" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1p6L6I/pylance-15.0.0b34-cp310-abi3-win_amd64.whl", hash = "sha256:780e85cfae25ae26c8eccd5dc40ae38003e8fe0752a5e5b4e124f14d8288bd87" },
{ url = "https://pypi.fury.io/lance-format/-/ver_9H5Qj/pylance-15.0.0b34-cp310-abi3-win_arm64.whl", hash = "sha256:05edaf5e3254ae798437bae276791fd311e110db86e62a002b2fa909b3f3b8cf" },
]
[[package]]