fix(python): honor bad-vector policies for inferred vector columns (#5243)

Fixes #5241

## Summary

Python inferred fixed-size vectors from names such as `text_embedding`,
but the bad-vector sanitizer used a narrower naming rule. Ragged rows
could reach Arrow and fail the cast, and schema inference could accept
an `embedding` row containing NaN.

Use the schema-inference name check when selecting floating-point
vectors for sanitization. When a target schema exists, apply the
expanded naming rule to fixed-size lists so an explicitly
variable-length column such as `embedding_history` keeps its list
semantics. Creation now rejects NaNs in these inferred vectors under the
default `error` policy. The `drop`, `fill`, and `null` policies handle
them during creation, append, and overwrite.

The four streaming bad-vector policy regression cases come from
[#5003](https://github.com/lancedb/lancedb/pull/5003).

Fixes #5241.

## Testing

Tests: `/bin/sh -c 'cd python && PYTHONPATH=python
UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest
python/tests/test_table.py -k bad_vectors_in_name_inferred_columns -q
--tb=short'`.
Result: Existing related tests on base, cd python && PYTHONPATH=python
UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest
python/tests/test_table.py -k 'bad_vectors or with_nans or null_elements
or empty_fixed_size_list or integer_embeddings or infer' -q — exit 0, 75
passed, 501 deselected in 1.18s.
Result: Base regression, cd python && PYTHONPATH=python
UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest
python/tests/test_table.py -k bad_vectors_in_name_inferred_columns -q
--tb=short — exit 1, 19 failed, 9 passed, 576 deselected in 5.29s. The
nine default vector controls passed. Output is in OSSCOUT_BASE.log.
Result: Patched regression, cd python && PYTHONPATH=python
UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest
python/tests/test_table.py -k bad_vectors_in_name_inferred_columns -q
--tb=short — exit 0, 28 passed, 576 deselected in 0.54s. Output is in
OSSCOUT_PATCHED.log.
Result: Patched affected modules, cd python && PYTHONPATH=python
UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest
python/tests/test_table.py python/tests/test_util.py
python/tests/test_embeddings.py -m 'not slow and not s3_test' -q
--tb=short — exit 0, 822 passed, 19 skipped, 8 deselected, 32 warnings
in 15.11s.
Result: Patched namespace creation checks, cd python &&
PYTHONPATH=python UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv
run --no-sync pytest python/tests/test_namespace.py -k create_table -m
'not slow and not s3_test' -q --tb=short — exit 0, 5 passed, 89
deselected, 4 warnings in 0.20s.
Result: From the repository root, /tmp/osscout-lancedb-venv/bin/ruff
format python/python/lancedb/table.py python/python/tests/test_table.py
left both files unchanged. /tmp/osscout-lancedb-venv/bin/ruff check
python passed.
Result: From the repository root, /tmp/osscout-lancedb-venv/bin/ruff
format --check . and /tmp/osscout-lancedb-venv/bin/ruff check .
--output-format concise flagged six files for reformatting and 59 lint
findings, respectively, all under unchanged docs/web-tests paths.
Result: git diff --check passed.
Regression coverage: `python/python/tests/test_table.py`.
<!-- oss-scout-job:job-f4fee21f-9051-4409-b66f-195dad93a5df -->

---------

Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
Co-authored-by: Xuanwo <github@xuanwo.io>
Co-authored-by: Aditya Gupta <84338325+MaiAditya@users.noreply.github.com>
This commit is contained in:
wangshun
2026-12-02 11:52:07 +08:00
committed by GitHub
co-authored by Xuanwo Aditya Gupta
parent 0abc7d48be
commit 9bdb1b7219
3 changed files with 383 additions and 84 deletions
+112 -59
View File
@@ -13,6 +13,7 @@ from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from functools import cached_property
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
@@ -46,7 +47,7 @@ from ._blob import (
validate_blob_mode,
)
from .types import BlobMode
from lancedb.arrow import AsyncRecordBatchReader, peek_reader
from lancedb.arrow import AsyncRecordBatchReader
from lancedb.sql import QueryParameters, to_parameter_batch
from lancedb.background_loop import LOOP, embedding_executor
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
@@ -699,6 +700,7 @@ def _sanitize_data(
fill_value: float = 0.0,
*,
allow_subschema: bool = False,
overwrite_schema: Optional[pa.Schema] = None,
) -> pa.RecordBatchReader:
"""
Handle input data, applying all standard transformations.
@@ -720,6 +722,10 @@ def _sanitize_data(
If True, the input table is allowed to omit columns from the target schema.
The target schema will be filtered to only include columns that are present
in the input table before casting.
overwrite_schema : Optional[pa.Schema], default None
For an overwrite, use existing fixed-size vector fields as a fallback
for parent nullability. Infer the replacement types and dimensions from
the incoming data.
metadata : Optional[dict], default None
The embedding metadata to add to the schema.
on_bad_vectors : Literal["error", "drop", "fill", "null"], default "error"
@@ -745,6 +751,7 @@ def _sanitize_data(
fill_value=fill_value,
target_schema=target_schema,
metadata=metadata,
overwrite_schema=overwrite_schema,
)
if target_schema is None:
@@ -1372,6 +1379,8 @@ def sanitize_create_table(
metadata=None,
on_bad_vectors: OnBadVectorsType = "error",
fill_value: float = 0.0,
*,
overwrite_schema: Optional[pa.Schema] = None,
):
if inspect.isclass(schema) and issubclass(schema, LanceModel):
# convert LanceModel to pyarrow schema
@@ -1388,6 +1397,7 @@ def sanitize_create_table(
metadata=metadata,
on_bad_vectors=on_bad_vectors,
fill_value=fill_value,
overwrite_schema=overwrite_schema,
)
schema = data.schema
else:
@@ -1461,7 +1471,6 @@ def _append_vector_columns(
if not functions:
return reader
target_schema = schema
fields = list(reader.schema)
for vector_column, conf in functions.items():
if vector_column not in reader.schema.names:
@@ -1471,7 +1480,7 @@ def _append_vector_columns(
dtype = pa.list_(pa.float32(), conf.function.ndims())
field = pa.field(vector_column, type=dtype, nullable=True)
fields.append(field)
schema = pa.schema(fields, metadata=reader.schema.metadata)
output_schema = pa.schema(fields, metadata=reader.schema.metadata)
def gen():
for batch in reader:
@@ -1482,42 +1491,46 @@ def _append_vector_columns(
col_data = func.compute_source_embeddings_with_retry(
batch[conf.source_column]
)
# Replace vectors with wrong length (including empty lists
# returned for inputs like empty strings) with None so that
# _handle_bad_vectors can process them according to the
# on_bad_vectors policy instead of crashing when PyArrow
# tries to cast them into a fixed-size list array.
# A fixed-size column already records the width, so only ask
# the function when it doesn't. Tables can use models whose
# dimension the function doesn't know.
field = schema.field(vector_column)
if (
target_schema is not None
and vector_column in target_schema.names
):
field = target_schema.field(vector_column)
field = output_schema.field(vector_column)
sanitize_type = (
schema.field(vector_column).type
if schema is not None and vector_column in schema.names
else field.type
)
# A fixed-size input array must be built at its own width.
# Sanitization can then apply the target column's width.
if pa.types.is_fixed_size_list(field.type):
expected_ndims = field.type.list_size
elif pa.types.is_fixed_size_list(sanitize_type):
expected_ndims = sanitize_type.list_size
else:
expected_ndims = conf.function.ndims()
expected_ndims = func.ndims()
# Only floating-point vectors go through bad-vector
# sanitization. Use a marker that lets it distinguish
# generation failures from valid null parents. For types
# it skips, such as binary vectors, keep a null parent so
# the failure is never stored as a searchable vector.
invalid_vector = (
[None] * expected_ndims
if _is_floating_list_type(sanitize_type)
else None
)
col_data = [
v if v is not None and len(v) == expected_ndims else None
v
if v is not None and len(v) == expected_ndims
else invalid_vector
for v in col_data
]
array = pa.array(col_data, type=field.type)
if no_vector_column:
batch = batch.append_column(
schema.field(vector_column),
pa.array(col_data, type=schema.field(vector_column).type),
)
batch = batch.append_column(field, array)
else:
batch = batch.set_column(
batch.column_names.index(vector_column),
schema.field(vector_column),
pa.array(col_data, type=schema.field(vector_column).type),
batch.column_names.index(vector_column), field, array
)
yield batch
return pa.RecordBatchReader.from_batches(schema, gen())
return pa.RecordBatchReader.from_batches(output_schema, gen())
def _table_path(base: str, table_name: str) -> str:
@@ -7104,8 +7117,12 @@ def _handle_bad_vectors(
fill_value: float = 0.0,
target_schema: Optional[pa.Schema] = None,
metadata: Optional[dict] = None,
*,
overwrite_schema: Optional[pa.Schema] = None,
) -> pa.RecordBatchReader:
vector_columns = _find_vector_columns(reader.schema, target_schema, metadata)
vector_columns = _find_vector_columns(
reader.schema, target_schema, metadata, overwrite_schema=overwrite_schema
)
if not vector_columns:
return reader
@@ -7116,7 +7133,7 @@ def _handle_bad_vectors(
pending_dims = []
for vector_column in vector_columns:
dim = vector_column["expected_dim"]
if target_schema is not None and dim is None:
if dim is None:
dim = _infer_vector_dim(batch[vector_column["name"]])
pending_dims.append(vector_column)
batch = _handle_bad_vector_column(
@@ -7126,6 +7143,7 @@ def _handle_bad_vectors(
fill_value=fill_value,
expected_dim=dim,
expected_value_type=vector_column["expected_value_type"],
preserve_parent_nulls=vector_column["preserve_parent_nulls"],
)
for vector_column in pending_dims:
if vector_column["expected_dim"] is None:
@@ -7152,49 +7170,68 @@ def _find_vector_columns(
reader_schema: pa.Schema,
target_schema: Optional[pa.Schema],
metadata: Optional[dict],
*,
overwrite_schema: Optional[pa.Schema] = None,
) -> List[dict]:
active_metadata = _merge_metadata(
target_schema.metadata if target_schema is not None else None, metadata
)
embedding_function_columns = set(
EmbeddingFunctionRegistry.get_instance().parse_functions(active_metadata).keys()
)
if target_schema is None:
existing_fields = (
{field.name: field for field in overwrite_schema}
if overwrite_schema is not None
else {}
)
vector_columns = []
for field in reader_schema:
named_vector_col = (
_is_list_like(field.type)
and pa.types.is_floating(field.type.value_type)
and field.name == VECTOR_COLUMN_NAME
)
likely_vector_col = (
pa.types.is_fixed_size_list(field.type)
and pa.types.is_floating(field.type.value_type)
and (field.type.list_size >= 10)
)
if named_vector_col or likely_vector_col:
if not _is_floating_list_type(field.type):
continue
fixed_size = pa.types.is_fixed_size_list(field.type)
if (
field.name in embedding_function_columns
or _name_suggests_vector_column(field.name)
or (fixed_size and field.type.list_size >= 10)
):
# Typed input declares its own nullability. For inferred list
# input on overwrite, carry forward the old null policy only.
declared_field = (
field if fixed_size else existing_fields.get(field.name)
)
vector_columns.append(
{
"name": field.name,
"expected_dim": None,
"expected_dim": field.type.list_size if fixed_size else None,
"expected_value_type": None,
"preserve_parent_nulls": (
declared_field is not None
and declared_field.nullable
and pa.types.is_fixed_size_list(declared_field.type)
and pa.types.is_floating(declared_field.type.value_type)
),
}
)
return vector_columns
reader_column_names = set(reader_schema.names)
active_metadata = _merge_metadata(target_schema.metadata, metadata)
embedding_function_columns = set(
EmbeddingFunctionRegistry.get_instance().parse_functions(active_metadata).keys()
)
vector_columns = []
for field in target_schema:
if field.name not in reader_column_names:
continue
if not _is_list_like(field.type) or not pa.types.is_floating(
field.type.value_type
):
if not _is_floating_list_type(field.type):
continue
reader_field = reader_schema.field(field.name)
named_vector_col = (
field.name in embedding_function_columns
or field.name == VECTOR_COLUMN_NAME
or (field.name == "embedding" and pa.types.is_fixed_size_list(field.type))
or (
pa.types.is_fixed_size_list(field.type)
and _name_suggests_vector_column(field.name)
)
)
typed_fixed_vector_col = (
pa.types.is_fixed_size_list(reader_field.type)
@@ -7212,6 +7249,9 @@ def _find_vector_columns(
else None
),
"expected_value_type": field.type.value_type,
"preserve_parent_nulls": (
field.nullable and pa.types.is_fixed_size_list(field.type)
),
}
)
@@ -7262,6 +7302,7 @@ def _handle_bad_vector_column(
fill_value: float = 0.0,
expected_dim: Optional[int] = None,
expected_value_type: Optional[pa.DataType] = None,
preserve_parent_nulls: bool = False,
) -> pa.RecordBatch:
"""
Ensure that the vector column exists and has type fixed_size_list(float)
@@ -7314,13 +7355,12 @@ def _handle_bad_vector_column(
return data
is_null = pc.is_null(vec_arr)
# pc.list_value_length returns null for null list entries, so
# pc.not_equal(null, dim) also returns null. Use or_kleene so that
# True OR null = True (Kleene three-valued logic), ensuring null vectors
# are counted as wrong-dim.
has_wrong_dim = pc.or_kleene(
is_null,
# Null parent lists are valid in a declared nullable fixed-size column.
# Null child elements and incorrect dimensions still follow the bad-vector
# policy. For other vector columns retain the existing parent-null behavior.
has_wrong_dim = pc.fill_null(
pc.not_equal(pc.list_value_length(vec_arr), dim),
not preserve_parent_nulls,
)
has_bad_vectors = pc.any(has_nan).as_py() or pc.any(has_wrong_dim).as_py()
@@ -7357,6 +7397,10 @@ def _handle_bad_vector_column(
"`fill_value` must not be None if `on_bad_vectors` is 'fill'"
)
vec_arr = _fill_bad_vector_values(vec_arr, dim, fill_value)
if preserve_parent_nulls:
vec_arr = pc.if_else(
is_null, pa.scalar(None, type=vec_arr.type), vec_arr
)
else:
raise ValueError(f"Invalid value for on_bad_vectors: {on_bad_vectors}")
@@ -7424,6 +7468,10 @@ def _is_list_like(data_type: pa.DataType) -> bool:
)
def _is_floating_list_type(data_type: pa.DataType) -> bool:
return _is_list_like(data_type) and pa.types.is_floating(data_type.value_type)
def _merge_metadata(*metadata_dicts: Optional[dict]) -> dict:
merged = {}
for metadata in metadata_dicts:
@@ -7457,10 +7505,14 @@ def _infer_target_schema(
if _name_suggests_vector_column(field.name) and is_list_type:
if peeked is None:
try:
peeked, reader = peek_reader(reader)
except StopIteration:
return schema, reader
# Sanitization can remove every row in an earlier batch. Peek
# at the first surviving batch rather than inferring from no rows.
peeked = next((batch for batch in reader if batch.num_rows), None)
if peeked is None:
return schema, pa.RecordBatchReader.from_batches(schema, [])
reader = pa.RecordBatchReader.from_batches(
schema, chain([peeked], reader)
)
# Use the most common length of the list as the dimensions
dim = _modal_list_size(peeked.column(i))
@@ -8542,6 +8594,7 @@ class AsyncTable:
None,
on_bad_vectors=on_bad_vectors,
fill_value=fill_value,
overwrite_schema=schema,
)
if blob_v2_column_paths(schema):
# Plain bytes cannot be inferred as blob v2. Keep matching blob
+78 -25
View File
@@ -360,27 +360,19 @@ def test_embedding_with_bad_results(tmp_path):
assert tbl["vector"].null_count == 1
def test_embedding_with_empty_output_vectors(tmp_path):
"""Regression test for issue #1672.
When an embedding function returns an empty list (e.g. for empty-string
inputs), _append_vector_columns used to crash because PyArrow cannot cast
[] into a fixed-size list element. The fix replaces wrong-length vectors
with None before building the Arrow array so that _handle_bad_vectors can
process them normally.
"""
@pytest.mark.parametrize("operation", ["create", "append"])
@pytest.mark.parametrize("policy", ["error", "drop", "fill", "null"])
def test_embedding_with_empty_output_vectors(tmp_path, operation, policy):
"""Unusable generated embeddings must still obey the bad-vector policy."""
@register("empty-vec-embedding")
class EmptyVecEmbeddingFunction(TextEmbeddingFunction):
def ndims(self):
return 128
return 2
def generate_embeddings(self, texts: Union[List[str], np.ndarray]) -> list:
# Simulate a model that returns an empty list for blank inputs
return [
[] if text.strip() == "" else np.random.randn(self.ndims()).tolist()
for text in texts
]
outputs = {"empty": [], "missing": None, "wrong_width": [6.0]}
return [outputs.get(text, [1.0, 2.0]) for text in texts]
db = lancedb.connect(tmp_path)
registry = EmbeddingFunctionRegistry.get_instance()
@@ -388,19 +380,80 @@ def test_embedding_with_empty_output_vectors(tmp_path):
class Schema(LanceModel):
text: str = model.SourceField()
vector: Vector(model.ndims()) = model.VectorField()
feature: Vector(model.ndims(), nullable=True) = model.VectorField()
table = db.create_table("test_empty_vec", schema=Schema, mode="overwrite")
table_name = "test_empty_vec"
if operation == "append":
table = db.create_table(table_name, schema=Schema)
# Should not crash; the row with the empty string should be dropped
table.add(
[{"text": "hello world"}, {"text": ""}, {"text": "foo"}],
on_bad_vectors="drop",
good = {"text": "good", "feature": [1.0, 2.0]}
texts = ["good", "empty", "missing", "wrong_width"]
data = [{"text": text} for text in texts]
def write():
options = dict(on_bad_vectors=policy, fill_value=-1.0)
if operation == "append":
table.add(data, **options)
else:
config = EmbeddingFunctionConfig(
source_column="text", vector_column="feature", function=model
)
db.create_table(table_name, data, embedding_functions=[config], **options)
if policy == "error":
with pytest.raises((RuntimeError, ValueError), match="Vector column 'feature'"):
write()
if operation == "append":
assert db.open_table(table_name).count_rows() == 0
return
write()
expected = [good]
if policy != "drop":
replacement = [-1.0, -1.0] if policy == "fill" else None
expected.extend({"text": text, "feature": replacement} for text in texts[1:])
assert db.open_table(table_name).to_arrow().to_pylist() == expected
@pytest.mark.parametrize("operation", ["create", "append"])
@pytest.mark.parametrize("policy", ["error", "drop", "fill", "null"])
def test_failed_binary_embeddings_stay_null(tmp_path, operation, policy):
@register("binary-embedding")
class BinaryEmbeddingFunction(TextEmbeddingFunction):
def ndims(self):
return 2
def generate_embeddings(self, texts: Union[List[str], np.ndarray]) -> list:
outputs = {"empty": [], "missing": None, "wrong_width": [6]}
return [outputs.get(text, [255, 255]) for text in texts]
model = BinaryEmbeddingFunction.create()
class Schema(LanceModel):
text: str = model.SourceField()
vector: Vector(model.ndims(), value_type=pa.uint8()) = model.VectorField()
db = lancedb.connect(tmp_path)
texts = ["empty", "valid", "missing", "wrong_width"]
data = [{"text": text} for text in texts]
if operation == "create":
db.create_table("binary", data, schema=Schema, on_bad_vectors=policy)
else:
db.create_table("binary", schema=Schema).add(data, on_bad_vectors=policy)
reopened = db.open_table("binary")
assert reopened.schema.field("vector").type == pa.list_(pa.uint8(), 2)
results = (
reopened.search(np.array([0, 0], dtype=np.uint8))
.distance_type("hamming")
.limit(len(texts))
.to_arrow()
)
assert len(table) == 2
texts = table.to_arrow()["text"].to_pylist()
assert "" not in texts
assert results["text"].to_pylist() == ["valid"]
assert reopened.to_arrow().to_pylist() == [
{"text": text, "vector": [255, 255] if text == "valid" else None}
for text in texts
]
def test_with_existing_vectors(tmp_path):
+193
View File
@@ -2992,6 +2992,69 @@ def test_create_with_nans(mem_db: DBConnection):
assert np.allclose(filled_vectors[22.0], np.array([5.0, 0.0]))
def _batches_with_bad_vectors_in_later_batch():
# The second batch's majority dimension (3) differs from the first one's (2)
yield pa.RecordBatch.from_pylist(
[{"vector": [1.0, 2.0], "id": 0}, {"vector": [3.0, 4.0], "id": 1}]
)
yield pa.RecordBatch.from_pylist(
[
{"vector": [5.0, 6.0, 7.0], "id": 2},
{"vector": [8.0, 9.0, 10.0], "id": 3},
{"vector": [11.0, 12.0], "id": 4},
{"vector": [13.0], "id": 5},
]
)
@pytest.mark.parametrize("on_bad_vectors", ["drop", "fill", "null"])
def test_create_from_batches_with_bad_vectors_in_later_batch(
mem_db: DBConnection, on_bad_vectors
):
# The vector dimension guessed from the first batch must be used for
# later batches too, even when their own majority dimension differs.
table = mem_db.create_table(
"test",
data=_batches_with_bad_vectors_in_later_batch(),
on_bad_vectors=on_bad_vectors,
fill_value=42.0,
)
assert table.schema.field("vector").type == pa.list_(pa.float32(), 2)
if on_bad_vectors == "drop":
expected = [
{"vector": [1.0, 2.0], "id": 0},
{"vector": [3.0, 4.0], "id": 1},
{"vector": [11.0, 12.0], "id": 4},
]
else:
# "fill" truncates vectors that are too long and pads short ones
fill = on_bad_vectors == "fill"
expected = [
{"vector": [1.0, 2.0], "id": 0},
{"vector": [3.0, 4.0], "id": 1},
{"vector": [5.0, 6.0] if fill else None, "id": 2},
{"vector": [8.0, 9.0] if fill else None, "id": 3},
{"vector": [11.0, 12.0], "id": 4},
{"vector": [13.0, 42.0] if fill else None, "id": 5},
]
assert table.to_arrow().to_pylist() == expected
def test_create_from_batches_errors_on_bad_vectors_in_later_batch(
mem_db: DBConnection,
):
# Every vector in the second batch has the same, wrong, dimension
def batches():
yield pa.RecordBatch.from_pylist([{"vector": [1.0, 2.0], "id": 0}])
yield pa.RecordBatch.from_pylist([{"vector": [3.0, 4.0, 5.0], "id": 1}])
# The ValueError raised while reading the batches is wrapped in a
# RuntimeError by the writer.
with pytest.raises(RuntimeError, match="variable length vectors"):
mem_db.create_table("test", data=batches(), on_bad_vectors="error")
def test_add_with_nans(mem_db: DBConnection):
schema = pa.schema(
[
@@ -3114,6 +3177,136 @@ def test_write_vectors_with_null_elements(
assert table.to_arrow().to_pylist() == expected
@pytest.mark.parametrize("column", ["vector", "text_embedding", "image_VECTOR"])
@pytest.mark.parametrize("operation", ["create", "append", "overwrite"])
@pytest.mark.parametrize(
"policy, expected_vectors",
[
("drop", [[1.0, 2.0], [3.0, 4.0]]),
("fill", [[1.0, 2.0], [3.0, 4.0], [5.0, -1.0], [-1.0, 6.0]]),
("null", [[1.0, 2.0], [3.0, 4.0], None, None]),
],
)
def test_bad_vectors_in_name_inferred_columns(
mem_db: DBConnection, column, operation, policy, expected_vectors
):
vectors = [[1.0, 2.0], [3.0, 4.0], [5.0], [np.nan, 6.0]]
rows = [{"id": i, column: vector} for i, vector in enumerate(vectors)]
options = {"on_bad_vectors": policy, "fill_value": -1.0}
if operation == "create":
table = mem_db.create_table("test", rows, **options)
expected_rows = []
else:
initial_row = {"id": -1, column: [7.0, 8.0]}
table = mem_db.create_table("test", [initial_row])
table.add(rows, mode=operation, **options)
expected_rows = [initial_row] if operation == "append" else []
expected_rows.extend(
{"id": i, column: vector} for i, vector in enumerate(expected_vectors)
)
assert table.schema.field(column).type == pa.list_(pa.float32(), 2)
assert table.to_arrow().to_pylist() == expected_rows
def test_bad_vectors_in_name_inferred_columns_default_error(mem_db: DBConnection):
with pytest.raises(ValueError, match="Vector column 'embedding' has NaNs"):
mem_db.create_table(
"test", [{"embedding": [1.0, 2.0]}, {"embedding": [np.nan, 4.0]}]
)
@pytest.mark.parametrize("operation", ["create", "append", "overwrite"])
@pytest.mark.parametrize("input_type", ["rows", "arrow"])
@pytest.mark.parametrize("policy", ["drop", "fill"])
def test_bad_vectors_preserve_declared_nullable_parent(
mem_db: DBConnection, operation, input_type, policy
):
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("vector", pa.list_(pa.float32(), 2), nullable=True),
pa.field("embedding_history", pa.list_(pa.float32(), 2), nullable=True),
]
)
rows = [
{"id": 0, "vector": [1.0, 2.0], "embedding_history": None},
{"id": 1, "vector": [3.0, 4.0], "embedding_history": [10.0, 11.0]},
{"id": 2, "vector": [np.nan, 6.0], "embedding_history": [12.0, 13.0]},
{"id": 3, "vector": [7.0, 8.0], "embedding_history": [np.nan, 15.0]},
]
input_schema = schema
if operation == "overwrite":
# The existing schema establishes nullability, not the replacement width.
input_schema = schema.set(1, pa.field("vector", pa.list_(pa.float32(), 3)))
rows = [{**row, "vector": [*row["vector"], 7.0]} for row in rows]
data = (
pa.RecordBatch.from_pylist(rows, schema=input_schema)
if input_type == "arrow"
else rows
)
options = {"on_bad_vectors": policy, "fill_value": -1.0}
initial = {"id": -1, "vector": [9.0, 9.0], "embedding_history": None}
if operation == "create":
# An Arrow batch already declares its field types and nullability.
mem_db.create_table(
"test",
data=data,
schema=schema if input_type == "rows" else None,
**options,
)
else:
table = mem_db.create_table("test", data=[initial], schema=schema)
table.add(data, mode=operation, **options)
expected = [initial] if operation == "append" else []
expected.extend(rows[:2])
if policy == "fill":
expected.extend(
[
{**rows[2], "vector": [-1.0, *rows[2]["vector"][1:]]},
{**rows[3], "embedding_history": [-1.0, 15.0]},
]
)
reopened = mem_db.open_table("test")
assert reopened.schema == input_schema
assert reopened.to_arrow().to_pylist() == expected
@pytest.mark.parametrize("bad_prefix", [[np.nan, 3.0], [np.nan, 3.0, 4.0]])
def test_bad_vectors_inferred_reader_uses_surviving_rows(
mem_db: DBConnection, bad_prefix
):
first = pa.record_batch({"id": [0], "text_embedding": [bad_prefix]})
second = pa.record_batch({"id": [1, 2], "text_embedding": [[1.0, 2.0], [3.0, 4.0]]})
third = pa.record_batch(
{
"id": [3, 4, 5],
"text_embedding": [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [5.0, 6.0]],
}
)
reader = pa.RecordBatchReader.from_batches(first.schema, [first, second, third])
mem_db.create_table("test", reader, on_bad_vectors="drop")
reopened = mem_db.open_table("test")
assert reopened.schema.field("text_embedding").type == pa.list_(pa.float32(), 2)
assert reopened.to_arrow().to_pylist() == [
{"id": 1, "text_embedding": [1.0, 2.0]},
{"id": 2, "text_embedding": [3.0, 4.0]},
{"id": 5, "text_embedding": [5.0, 6.0]},
]
result = (
reopened.search([1.0, 2.0], vector_column_name="text_embedding")
.limit(1)
.to_arrow()
)
assert result["id"].to_pylist() == [1]
def test_add_with_empty_fixed_size_list_drops_bad_rows(mem_db: DBConnection):
class Schema(LanceModel):
text: str