Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions sdk/python/feast/feature_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -3630,15 +3630,15 @@ def _validate_vector_features(self, feature_view, df: pd.DataFrame) -> None:
ValueError: If vector dimension constraints are violated
"""
vector_field = _get_feature_view_vector_field_metadata(feature_view)
if vector_field is None or not vector_field.vector_length:
if vector_field is None or not vector_field.vector_index:
return

name = vector_field.name
if name not in df.columns:
return

expected = vector_field.vector_length
column = df[name]
declared = vector_field.vector_length or None

# Null vectors carry no length to compare. Skipping them keeps this
# consistent with the Arrow path, which also tolerates null rows, and
Expand All @@ -3652,6 +3652,21 @@ def _validate_vector_features(self, feature_view, df: pd.DataFrame) -> None:
)

not_a_sequence = lengths.isna() & ~is_null

expected = declared
if expected is None:
# No declared width, so take the contract from the first usable row.
# An ANN index needs a fixed width, so a ragged column is a defect
# regardless of whether anyone declared vector_length.
usable = lengths.notna()
if not usable.any():
# Nothing to infer from, so only the type check below applies.
if not not_a_sequence.any():
return
expected = -1
else:
expected = int(lengths[usable].iloc[0])

mismatched = lengths.notna() & (lengths != expected)
offending = not_a_sequence | mismatched
if not offending.any():
Expand All @@ -3669,10 +3684,14 @@ def _validate_vector_features(self, feature_view, df: pd.DataFrame) -> None:
f"Got: {type(column.iloc[position])}"
)

source = (
f"expected {expected}"
if declared
else f"expected {expected}, inferred from the first row"
)
raise ValueError(
f"Row {label}: Vector length {int(lengths.iloc[position])} does not match "
f"expected {expected} for feature '{name}' in feature view "
f"'{feature_view.name}'."
f"{source} for feature '{name}' in feature view '{feature_view.name}'."
)

def _get_feature_view_and_df_for_online_write(
Expand Down
56 changes: 40 additions & 16 deletions sdk/python/feast/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2027,62 +2027,86 @@ def _validate_vector_field_lengths(
table: Union[pyarrow.Table, pyarrow.RecordBatch],
feature_view,
) -> None:
"""Check an Arrow table's vector column against the declared ``vector_length``.
"""Check an Arrow table's vector column for a consistent width.

Called on the materialization path, where every compute engine funnels through
``_convert_arrow_to_proto``. The check is O(1) for fixed-size lists and a single
vectorized pass for variable-size lists, so it is safe to leave on.

A declared ``vector_length`` is a contract: a mismatch is an error, never a
silent truncation or a silently different response shape.
When the field declares a ``vector_length``, that is the contract and a mismatch
is an error, never a silent truncation or a silently different response shape.

When it does not, the width of the first non-null row is used as the contract for
the rest of the table. An approximate nearest neighbour index requires a fixed
width, so a ragged vector column is a defect either way, and inferring is strictly
better than skipping. ``vector_length`` is unset by default, including in the
bundled RAG templates, so skipping would leave the common case unchecked.

Args:
table: The Arrow table or record batch about to be converted.
feature_view: The feature view whose schema declares the vector field.

Raises:
ValueError: If the vector column's width disagrees with ``vector_length``.
ValueError: If the vector column's width is inconsistent, or disagrees with
a declared ``vector_length``.
"""
vector_field = _get_feature_view_vector_field_metadata(feature_view)
if vector_field is None or not vector_field.vector_length:
if vector_field is None or not vector_field.vector_index:
return

name = vector_field.name
if name not in table.schema.names:
return

expected = vector_field.vector_length
column = table.column(name)
column_type = column.type
declared = vector_field.vector_length or None

def _fail(actual, row: Optional[int] = None) -> None:
def _fail(actual, expected: int, row: Optional[int] = None) -> None:
where = f"Row {row}: " if row is not None else ""
source = (
f"expected {expected}"
if declared
else f"expected {expected}, inferred from the first row"
)
raise ValueError(
f"{where}Vector length {actual} does not match expected {expected} "
f"{where}Vector length {actual} does not match {source} "
f"for feature '{name}' in feature view '{feature_view.name}'."
)

if pyarrow.types.is_fixed_size_list(column_type):
if column_type.list_size != expected:
_fail(column_type.list_size)
# The width is a property of the type, so an undeclared column is uniform
# by construction and there is nothing left to check.
if declared and column_type.list_size != declared:
_fail(column_type.list_size, declared)
return

if pyarrow.types.is_list(column_type) or pyarrow.types.is_large_list(column_type):
lengths = pyarrow.compute.list_value_length(column)
valid = pyarrow.compute.is_valid(lengths)

expected = declared
if expected is None:
# Nulls carry no width, so take the contract from the first row that does.
first = pyarrow.compute.index(valid, True).as_py()
if first == -1:
return
expected = lengths[first].as_py()

# Nulls have no length to compare; only non-null rows carry the contract.
mismatched = pyarrow.compute.and_kleene(
pyarrow.compute.is_valid(lengths),
pyarrow.compute.not_equal(lengths, expected),
valid, pyarrow.compute.not_equal(lengths, expected)
)
if pyarrow.compute.any(mismatched).as_py():
row = pyarrow.compute.index(mismatched, True).as_py()
_fail(lengths[row].as_py(), row=row)
_fail(lengths[row].as_py(), expected, row=row)
return

# Any other type cannot hold a vector of the declared width.
# Any other type cannot hold a vector.
declared_note = f" declares vector_length={declared} but" if declared else ""
raise ValueError(
f"Vector feature '{name}' in feature view '{feature_view.name}' declares "
f"vector_length={expected} but has non-list Arrow type {column_type}."
f"Vector feature '{name}' in feature view '{feature_view.name}'{declared_note} "
f"has non-list Arrow type {column_type}."
)


Expand Down
76 changes: 76 additions & 0 deletions sdk/python/tests/unit/test_vector_length_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,79 @@ def odfv(inputs):
)
with pytest.raises(ValueError, match="does not match expected 4"):
_convert_arrow_to_proto(table, odfv, {})


class TestUndeclaredVectorLength:
"""When vector_length is unset, the width is inferred rather than unchecked.

vector_length defaults to 0, including in the bundled RAG templates and several
examples, so skipping validation left the common case unprotected. An ANN index
requires a fixed width, so a ragged column is a defect either way.
"""

def test_arrow_ragged_column_is_rejected_without_a_declaration(self):
table = _table(_variable_list([4, 4, 7, 4]))
with pytest.raises(ValueError, match="inferred from the first row"):
_validate_vector_field_lengths(table, _feature_view(vector_length=0))

def test_arrow_uniform_column_passes_without_a_declaration(self):
table = _table(_variable_list([5, 5, 5]))
_validate_vector_field_lengths(table, _feature_view(vector_length=0))

def test_arrow_fixed_size_list_is_uniform_by_construction(self):
"""A fixed-size list cannot be ragged, so any width is acceptable."""
_validate_vector_field_lengths(
_table(_fixed_size_list(99)), _feature_view(vector_length=0)
)

def test_arrow_declaration_still_wins_over_inference(self):
table = _table(_variable_list([5, 5, 5]))
with pytest.raises(ValueError, match="expected 4 for feature"):
_validate_vector_field_lengths(table, _feature_view())

def test_arrow_nulls_do_not_become_the_inferred_width(self):
table = _table(_variable_list([None, 6, 6]))
_validate_vector_field_lengths(table, _feature_view(vector_length=0))

def test_arrow_all_null_column_is_a_no_op(self):
table = _table(_variable_list([None, None]))
_validate_vector_field_lengths(table, _feature_view(vector_length=0))

def test_dataframe_ragged_column_is_rejected_without_a_declaration(self):
df = pd.DataFrame(
{"embedding": [[0.0] * 4, [0.0] * 4, [0.0] * 7], "label": list("abc")}
)
with pytest.raises(ValueError, match="inferred from the first row"):
_validate_df(_feature_view(vector_length=0), df)

def test_dataframe_uniform_column_passes_without_a_declaration(self):
df = pd.DataFrame({"embedding": [[0.0] * 9] * 3, "label": list("abc")})
_validate_df(_feature_view(vector_length=0), df)

def test_dataframe_non_sequence_still_caught_without_a_declaration(self):
df = pd.DataFrame({"embedding": [[0.0] * 4, 3.14], "label": list("ab")})
with pytest.raises(ValueError, match="is not a sequence"):
_validate_df(_feature_view(vector_length=0), df)

def test_dataframe_all_null_column_is_a_no_op(self):
df = pd.DataFrame({"embedding": [None, np.nan], "label": list("ab")})
_validate_df(_feature_view(vector_length=0), df)

def test_non_vector_field_is_untouched(self):
"""vector_index=False means the field is not a vector at all."""
fv = FeatureView(
name="fv",
entities=[
Entity(
name="item_id", join_keys=["item_id"], value_type=ValueType.INT64
)
],
schema=[
Field(name="embedding", dtype=Array(Float32)),
Field(name="label", dtype=String),
],
source=FileSource(
path="/tmp/unused.parquet", timestamp_field="event_timestamp"
),
)
_validate_vector_field_lengths(_table(_variable_list([4, 9, 2])), fv)
Loading