From c2cbfeb7aaa53113c0457bf3898cd6680ed59009 Mon Sep 17 00:00:00 2001 From: hao-xu5 Date: Wed, 30 Sep 2026 10:55:00 -0700 Subject: [PATCH 1/2] fix: Make vector length validation reachable, schema-driven and vectorized Addresses three of the five items in #6907. Validation was reachable only from the online-write path. _validate_vector_features had a single call site inside _get_feature_view_and_df_for_online_write, so materialize, materialize_incremental and get_historical_features never ran it. Embedding workloads are overwhelmingly batch, so the path carrying vectors at volume was the unvalidated one. Every compute engine (local, spark, ray, flink, kubernetes, aws_lambda) and the passthrough provider funnel through utils._convert_arrow_to_proto, so a single Arrow-level check placed in _convert_arrow_fv_to_proto covers all of them. _validate_vector_field_lengths is O(1) for fixed-size lists and one vectorized pass for variable-size lists, so it is cheap enough to leave on. Null rows are tolerated; a non-list column with a declared vector_length is an error. Note the snowflake compute engine builds its rows without going through _convert_arrow_to_proto, so it is not covered by this change. The check assumed the vector was the first feature. feature_view.features[0].vector_index meant that declaring any field before the vector field silently disabled validation. Both validators now resolve the field via _get_feature_view_vector_field_metadata, which scans the schema and is already used elsewhere in feature_store.py. iterrows() did not scale. Replaced with a single pass over the column, which measured ~60x faster on 200k rows (1.51s to 0.025s) while keeping the row index and the two distinct failure messages. Not included, since #6907 raises them as behaviour decisions rather than fixes: requiring vector_length when vector_index=True (item 3), and whether Field.__eq__ should compare vector_index and vector_search_metric (item 5). Adds sdk/python/tests/unit/test_vector_length_validation.py with 16 tests covering both validators, including regression tests for the vector field not being first. Signed-off-by: hao-xu5 --- sdk/python/feast/feature_store.py | 46 +++-- sdk/python/feast/utils.py | 65 +++++++ .../unit/test_vector_length_validation.py | 174 ++++++++++++++++++ 3 files changed, 271 insertions(+), 14 deletions(-) create mode 100644 sdk/python/tests/unit/test_vector_length_validation.py diff --git a/sdk/python/feast/feature_store.py b/sdk/python/feast/feature_store.py index 2915e138bc0..b3a60405c52 100644 --- a/sdk/python/feast/feature_store.py +++ b/sdk/python/feast/feature_store.py @@ -3619,6 +3619,9 @@ def _validate_vector_features(self, feature_view, df: pd.DataFrame) -> None: """ Validates vector features in the DataFrame against the feature view specifications. + Resolves the vector field from the feature view schema rather than assuming it is + the first feature, and checks lengths in a single pass over the column. + Args: feature_view: The feature view containing vector feature specifications df: The DataFrame to validate @@ -3626,20 +3629,35 @@ def _validate_vector_features(self, feature_view, df: pd.DataFrame) -> None: Raises: ValueError: If vector dimension constraints are violated """ - if feature_view.features and feature_view.features[0].vector_index: - fv_vector_feature_name = feature_view.features[0].name - if feature_view.features[0].vector_length != 0: - for i, row in df.iterrows(): - vector = row[fv_vector_feature_name] - if not hasattr(vector, "__len__"): - raise ValueError( - f"Row {i}: Vector feature '{fv_vector_feature_name}' is not a sequence. Got: {type(vector)}" - ) - if len(vector) != feature_view.features[0].vector_length: - raise ValueError( - f"Row {i}: Vector length {len(vector)} does not match expected {feature_view.features[0].vector_length} " - f"for feature '{fv_vector_feature_name}' in feature view '{feature_view.name}'." - ) + vector_field = _get_feature_view_vector_field_metadata(feature_view) + if vector_field is None or not vector_field.vector_length: + return + + name = vector_field.name + if name not in df.columns: + return + + expected = vector_field.vector_length + column = df[name] + + # Single pass over the column. Sequences report their length, anything else + # reports None so the two failure modes stay distinguishable. + lengths = column.map(lambda v: len(v) if hasattr(v, "__len__") else None) + + not_a_sequence = lengths.isna() + if not_a_sequence.any(): + i = not_a_sequence.idxmax() + raise ValueError( + f"Row {i}: Vector feature '{name}' is not a sequence. Got: {type(column[i])}" + ) + + mismatched = lengths != expected + if mismatched.any(): + i = mismatched.idxmax() + raise ValueError( + f"Row {i}: Vector length {lengths[i]} does not match expected {expected} " + f"for feature '{name}' in feature view '{feature_view.name}'." + ) def _get_feature_view_and_df_for_online_write( self, diff --git a/sdk/python/feast/utils.py b/sdk/python/feast/utils.py index 54891416190..667ced33c25 100644 --- a/sdk/python/feast/utils.py +++ b/sdk/python/feast/utils.py @@ -571,6 +571,8 @@ def _convert_arrow_fv_to_proto( f"Feature view '{feature_view.name}' has no batch_source and cannot be converted to proto." ) + _validate_vector_field_lengths(table, feature_view) + # TODO: This will break if the feature view has aggregations or transformations columns = [ (field.name, field.dtype.to_value_type()) for field in feature_view.features @@ -2015,6 +2017,69 @@ def _get_feature_view_vector_field_metadata( return vector_fields[0] +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``. + + 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. + + 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``. + """ + vector_field = _get_feature_view_vector_field_metadata(feature_view) + if vector_field is None or not vector_field.vector_length: + 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 + + def _fail(actual, row: Optional[int] = None) -> None: + where = f"Row {row}: " if row is not None else "" + raise ValueError( + f"{where}Vector length {actual} does not match expected {expected} " + 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) + return + + if pyarrow.types.is_list(column_type) or pyarrow.types.is_large_list(column_type): + lengths = pyarrow.compute.list_value_length(column) + # 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), + ) + if pyarrow.compute.any(mismatched).as_py(): + row = pyarrow.compute.index(mismatched, True).as_py() + _fail(lengths[row].as_py(), row=row) + return + + # Any other type cannot hold a vector of the declared width. + 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}." + ) + + def _distance_to_score(distance: float, metric: Optional[str] = None) -> float: """Convert a raw distance value into a higher-is-better relevance score. diff --git a/sdk/python/tests/unit/test_vector_length_validation.py b/sdk/python/tests/unit/test_vector_length_validation.py new file mode 100644 index 00000000000..005a065738c --- /dev/null +++ b/sdk/python/tests/unit/test_vector_length_validation.py @@ -0,0 +1,174 @@ +"""Tests for vector length validation on both the write and materialization paths. + +Covers three fixes: + * the vector field is resolved from the schema, not assumed to be ``features[0]`` + * the check is reachable from the materialization path via ``_convert_arrow_to_proto`` + * length checking is a single vectorized pass rather than a per-row loop +""" + +import numpy as np +import pandas as pd +import pyarrow +import pytest + +from feast import Entity, FeatureView, Field, FileSource +from feast.feature_store import FeatureStore +from feast.types import Array, Float32, String +from feast.utils import _validate_vector_field_lengths +from feast.value_type import ValueType + +VECTOR_LENGTH = 4 + + +def _feature_view(vector_first: bool = True, vector_length: int = VECTOR_LENGTH): + """Build a feature view whose vector field is first or second in the schema.""" + vector = Field( + name="embedding", + dtype=Array(Float32), + vector_index=True, + vector_length=vector_length, + vector_search_metric="COSINE", + ) + label = Field(name="label", dtype=String) + return FeatureView( + name="fv", + entities=[ + Entity(name="item_id", join_keys=["item_id"], value_type=ValueType.INT64) + ], + schema=[vector, label] if vector_first else [label, vector], + source=FileSource( + path="/tmp/unused.parquet", timestamp_field="event_timestamp" + ), + ) + + +def _fixed_size_list(dim: int, num_rows: int = 3) -> pyarrow.Array: + values = pyarrow.array(np.zeros(dim * num_rows, dtype=np.float32)) + return pyarrow.FixedSizeListArray.from_arrays(values, dim) + + +def _variable_list(lengths) -> pyarrow.Array: + return pyarrow.array( + [None if length is None else [0.0] * length for length in lengths], + pyarrow.list_(pyarrow.float32()), + ) + + +def _table(embedding: pyarrow.Array) -> pyarrow.Table: + num_rows = len(embedding) + return pyarrow.table( + { + "embedding": embedding, + "label": pyarrow.array(["a"] * num_rows), + "item_id": pyarrow.array(list(range(num_rows))), + } + ) + + +def _validate_df(feature_view, df: pd.DataFrame) -> None: + """Invoke the DataFrame validator without standing up a FeatureStore. + + ``_validate_vector_features`` does not touch instance state, so an + uninitialized instance is enough. + """ + store = FeatureStore.__new__(FeatureStore) + store._validate_vector_features(feature_view, df) + + +class TestArrowVectorLengthValidation: + """``_validate_vector_field_lengths`` guards the materialization path.""" + + def test_fixed_size_list_matching_length_passes(self): + _validate_vector_field_lengths( + _table(_fixed_size_list(VECTOR_LENGTH)), _feature_view() + ) + + def test_fixed_size_list_wrong_length_raises(self): + with pytest.raises(ValueError, match="does not match expected 4"): + _validate_vector_field_lengths(_table(_fixed_size_list(8)), _feature_view()) + + def test_variable_list_reports_first_offending_row(self): + table = _table(_variable_list([4, 4, 7, 4])) + with pytest.raises(ValueError, match="Row 2: Vector length 7"): + _validate_vector_field_lengths(table, _feature_view()) + + def test_vector_field_not_first_is_still_validated(self): + """Regression: the old check read features[0] and skipped this case.""" + with pytest.raises(ValueError, match="does not match expected 4"): + _validate_vector_field_lengths( + _table(_fixed_size_list(8)), _feature_view(vector_first=False) + ) + + def test_unset_vector_length_is_a_no_op(self): + _validate_vector_field_lengths( + _table(_fixed_size_list(8)), _feature_view(vector_length=0) + ) + + def test_null_rows_are_tolerated(self): + table = _table(_variable_list([4, None, 4])) + _validate_vector_field_lengths(table, _feature_view()) + + def test_missing_column_is_a_no_op(self): + table = pyarrow.table({"label": pyarrow.array(["a", "b"])}) + _validate_vector_field_lengths(table, _feature_view()) + + def test_non_list_arrow_type_raises(self): + table = pyarrow.table( + { + "embedding": pyarrow.array([1.0, 2.0]), + "label": pyarrow.array(["a", "b"]), + } + ) + with pytest.raises(ValueError, match="non-list Arrow type"): + _validate_vector_field_lengths(table, _feature_view()) + + def test_record_batch_is_accepted(self): + batch = _table(_fixed_size_list(8)).to_batches()[0] + with pytest.raises(ValueError, match="does not match expected 4"): + _validate_vector_field_lengths(batch, _feature_view()) + + +class TestDataFrameVectorLengthValidation: + """``_validate_vector_features`` guards the online write path.""" + + def test_matching_lengths_pass(self): + df = pd.DataFrame({"embedding": [[0.0] * 4] * 3, "label": list("abc")}) + _validate_df(_feature_view(), df) + + def test_wrong_length_reports_first_offending_row(self): + df = pd.DataFrame( + {"embedding": [[0.0] * 4, [0.0] * 9, [0.0] * 4], "label": list("abc")} + ) + with pytest.raises(ValueError, match="Row 1: Vector length 9"): + _validate_df(_feature_view(), df) + + def test_non_sequence_value_reports_its_type(self): + df = pd.DataFrame( + {"embedding": [[0.0] * 4, 3.14, [0.0] * 4], "label": list("abc")} + ) + with pytest.raises(ValueError, match="is not a sequence"): + _validate_df(_feature_view(), df) + + def test_vector_field_not_first_is_still_validated(self): + """Regression: the old check read features[0] and skipped this case.""" + df = pd.DataFrame( + {"embedding": [[0.0] * 4, [0.0] * 9, [0.0] * 4], "label": list("abc")} + ) + with pytest.raises(ValueError, match="Row 1: Vector length 9"): + _validate_df(_feature_view(vector_first=False), df) + + def test_unset_vector_length_is_a_no_op(self): + df = pd.DataFrame({"embedding": [[0.0] * 9] * 3, "label": list("abc")}) + _validate_df(_feature_view(vector_length=0), df) + + def test_missing_column_is_a_no_op(self): + _validate_df(_feature_view(), pd.DataFrame({"label": list("abc")})) + + def test_numpy_vectors_are_accepted(self): + df = pd.DataFrame( + { + "embedding": [np.zeros(VECTOR_LENGTH, dtype=np.float32)] * 3, + "label": list("abc"), + } + ) + _validate_df(_feature_view(), df) From 2aa437bbedf02a09eeeda5d9254d9ab0a9da7cf4 Mon Sep 17 00:00:00 2001 From: hao-xu5 Date: Thu, 1 Oct 2026 00:52:08 -0700 Subject: [PATCH 2/2] fix: Address review feedback on vector length validation Three findings from review of #6909. Tolerate genuine nulls on the DataFrame path (@ntkathole). lengths.isna() was true both for values that were not sequences and for rows that were genuinely null, so a null vector was reported as "not a sequence". Nulls are now skipped, which also makes this path consistent with the Arrow path, which already tolerated null rows. Report the first offending row across both failure modes (Copilot). Checking the not-a-sequence mask fully before the length mask meant a non-sequence in a later row was reported ahead of a wrong length in an earlier one. The masks are now unioned and the first offending position selected before choosing the message, which restores the row ordering the original iterrows loop had. Value lookup is positional so a DataFrame with a duplicate index reports a scalar type rather than a Series. Validate the on-demand branch too (Copilot). _convert_arrow_to_proto dispatches to _convert_arrow_odfv_to_proto or _convert_arrow_fv_to_proto, and the check sat in the regular branch only, so a stored ODFV declaring vector_length had its transformed output unchecked. The call moved up into the dispatcher, ahead of the branch, so both paths are covered. Each finding has a test that fails against the previous commit and passes here. Signed-off-by: hao-xu5 --- sdk/python/feast/feature_store.py | 44 ++++++---- sdk/python/feast/utils.py | 5 +- .../unit/test_vector_length_validation.py | 82 ++++++++++++++++++- 3 files changed, 113 insertions(+), 18 deletions(-) diff --git a/sdk/python/feast/feature_store.py b/sdk/python/feast/feature_store.py index b3a60405c52..d19f6467d4b 100644 --- a/sdk/python/feast/feature_store.py +++ b/sdk/python/feast/feature_store.py @@ -3640,25 +3640,41 @@ def _validate_vector_features(self, feature_view, df: pd.DataFrame) -> None: expected = vector_field.vector_length column = df[name] - # Single pass over the column. Sequences report their length, anything else - # reports None so the two failure modes stay distinguishable. - lengths = column.map(lambda v: len(v) if hasattr(v, "__len__") else None) + # Null vectors carry no length to compare. Skipping them keeps this + # consistent with the Arrow path, which also tolerates null rows, and + # stops a genuine null being reported as "not a sequence". + is_null = column.isna() + + # Single pass over the column. na_action leaves nulls as NaN, so a NaN + # length that is not null means the value was not a sequence at all. + lengths = column.map( + lambda v: len(v) if hasattr(v, "__len__") else None, na_action="ignore" + ) - not_a_sequence = lengths.isna() - if not_a_sequence.any(): - i = not_a_sequence.idxmax() - raise ValueError( - f"Row {i}: Vector feature '{name}' is not a sequence. Got: {type(column[i])}" - ) + not_a_sequence = lengths.isna() & ~is_null + mismatched = lengths.notna() & (lengths != expected) + offending = not_a_sequence | mismatched + if not offending.any(): + return - mismatched = lengths != expected - if mismatched.any(): - i = mismatched.idxmax() + # Report the first offending row across both failure modes, by position, + # so the message is right regardless of which failure comes first and + # correct even when the index has duplicates. + position = int(offending.to_numpy().argmax()) + label = column.index[position] + + if bool(not_a_sequence.to_numpy()[position]): raise ValueError( - f"Row {i}: Vector length {lengths[i]} does not match expected {expected} " - f"for feature '{name}' in feature view '{feature_view.name}'." + f"Row {label}: Vector feature '{name}' is not a sequence. " + f"Got: {type(column.iloc[position])}" ) + 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}'." + ) + def _get_feature_view_and_df_for_online_write( self, feature_view_name: str, diff --git a/sdk/python/feast/utils.py b/sdk/python/feast/utils.py index 667ced33c25..d2b8e2b876a 100644 --- a/sdk/python/feast/utils.py +++ b/sdk/python/feast/utils.py @@ -548,6 +548,9 @@ def _convert_arrow_to_proto( ) -> List[Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]]]: # This is a workaround for isinstance(feature_view, OnDemandFeatureView), which triggers a circular import # Check for source_request_sources or source_feature_view_projections attributes to identify ODFVs + # Validate before branching so both regular and on-demand feature views are covered. + _validate_vector_field_lengths(table, feature_view) + if ( getattr(feature_view, "source_request_sources", None) is not None or getattr(feature_view, "source_feature_view_projections", None) is not None @@ -571,8 +574,6 @@ def _convert_arrow_fv_to_proto( f"Feature view '{feature_view.name}' has no batch_source and cannot be converted to proto." ) - _validate_vector_field_lengths(table, feature_view) - # TODO: This will break if the feature view has aggregations or transformations columns = [ (field.name, field.dtype.to_value_type()) for field in feature_view.features diff --git a/sdk/python/tests/unit/test_vector_length_validation.py b/sdk/python/tests/unit/test_vector_length_validation.py index 005a065738c..6f6d78e68d6 100644 --- a/sdk/python/tests/unit/test_vector_length_validation.py +++ b/sdk/python/tests/unit/test_vector_length_validation.py @@ -11,10 +11,10 @@ import pyarrow import pytest -from feast import Entity, FeatureView, Field, FileSource +from feast import Entity, FeatureView, Field, FileSource, RequestSource from feast.feature_store import FeatureStore from feast.types import Array, Float32, String -from feast.utils import _validate_vector_field_lengths +from feast.utils import _convert_arrow_to_proto, _validate_vector_field_lengths from feast.value_type import ValueType VECTOR_LENGTH = 4 @@ -172,3 +172,81 @@ def test_numpy_vectors_are_accepted(self): } ) _validate_df(_feature_view(), df) + + +class TestReviewFeedback: + """Cases raised in review of #6909.""" + + def test_null_vectors_are_tolerated_on_the_dataframe_path(self): + """A genuine null has no length, and must not be called 'not a sequence'. + + Matches the Arrow path, which already tolerates null rows. + """ + df = pd.DataFrame( + { + "embedding": [[0.0] * VECTOR_LENGTH, None, np.nan], + "label": list("abc"), + } + ) + _validate_df(_feature_view(), df) + + def test_first_offending_row_wins_across_both_failure_modes(self): + """A bad length in row 0 outranks a non-sequence in row 1.""" + df = pd.DataFrame( + {"embedding": [[0.0] * 9, 3.14, [0.0] * 4], "label": list("abc")} + ) + with pytest.raises(ValueError, match="Row 0: Vector length 9"): + _validate_df(_feature_view(), df) + + def test_non_sequence_wins_when_it_comes_first(self): + df = pd.DataFrame( + {"embedding": [3.14, [0.0] * 9, [0.0] * 4], "label": list("abc")} + ) + with pytest.raises( + ValueError, match="Row 0: Vector feature .* is not a sequence" + ): + _validate_df(_feature_view(), df) + + def test_duplicate_index_reports_a_scalar_type_not_a_series(self): + """Positional access keeps a duplicate index from yielding a Series.""" + df = pd.DataFrame( + {"embedding": [[0.0] * 4, 3.14, [0.0] * 4], "label": list("abc")}, + index=[7, 7, 7], + ) + with pytest.raises(ValueError, match=r"Got: "): + _validate_df(_feature_view(), df) + + def test_on_demand_feature_view_output_is_validated(self): + """_convert_arrow_to_proto must validate before it branches to the ODFV path.""" + from feast.on_demand_feature_view import on_demand_feature_view + + request_source = RequestSource( + name="req", + schema=[Field(name="raw", dtype=String)], + ) + + @on_demand_feature_view( + sources=[request_source], + schema=[ + Field( + name="embedding", + dtype=Array(Float32), + vector_index=True, + vector_length=VECTOR_LENGTH, + ) + ], + mode="python", + write_to_online_store=True, + ) + def odfv(inputs): + return {"embedding": inputs["raw"]} + + # Width 8 against a declared 4 must be rejected on the ODFV branch too. + table = pyarrow.table( + { + "embedding": _fixed_size_list(8, num_rows=2), + "req": pyarrow.array(["a", "b"]), + } + ) + with pytest.raises(ValueError, match="does not match expected 4"): + _convert_arrow_to_proto(table, odfv, {})