Skip to content
Open
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
59 changes: 56 additions & 3 deletions sdk/python/feast/batch_feature_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
import functools
import warnings
from datetime import datetime, timedelta
from types import CodeType
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast

import dill
import numpy as np

from feast import flags_helper
from feast.aggregation import Aggregation
Expand Down Expand Up @@ -201,6 +203,25 @@ def __copy__(self) -> "BatchFeatureView":
fv._raw_feature_transformation_proto = self._raw_feature_transformation_proto
return fv

def __eq__(self, other):
if not super().__eq__(other):
return False

# FeatureView.__eq__ does not compare the transformation, so without
# this a view with a changed UDF equals the stored one.
raw = self._raw_feature_transformation_proto
other_raw = getattr(other, "_raw_feature_transformation_proto", None)
if raw is not None or other_raw is not None:
# Loaded with skip_udf=True: only the proto is available.
return raw == other_raw
return not _transformation_changed(
self.feature_transformation,
getattr(other, "feature_transformation", None),
)
Comment on lines +217 to +220

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Repeat apply fails after rollback

After a successful rollback to a different UDF, BatchFeatureView.__eq__ rejects the same pin declaration on the next apply. The pin check compares the declaration with the restored snapshot, not the definition it accepted before the rollback.

Learn more

To roll back a feature view, an operator changes only its version in the repository. The file registry and SQL registry validate that declaration against the active version, then replace the active definition with the older snapshot. They do not retain the declaration they accepted. On the next apply, the declaration is unchanged but the comparison target is now the older snapshot. Before this change, a UDF-only difference did not reject the repeat apply.

Example: Register v0 with UDF A, then v1 with UDF B. Set version="v0" without changing UDF B. The first apply activates A; the second apply of the same repository raises FeatureViewPinConflict.

Recommended fix: Make an exact repeat of an accepted pin a no-op in both registries. Retain the validated pin declaration or its stable fingerprint so the check can distinguish a repeat from a newly edited declaration. Do not bypass the guard solely because the requested version is already active, since that would silently discard new edits. Add a regression that repeats the successful pin and then attempts the same pin with a third UDF.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced on the file registry and a SQLite SqlRegistry. For a UDF-only rollback this is right: after version="v0" restores v0, applying the same declaration again raises FeatureViewPinConflict, where master accepted it.

The pin check already behaves this way on master for every field it compares. With v0 and v1 differing only in schema (plain FeatureView or BatchFeatureView), the first pin restores v0 and the identical second apply raises FeatureViewPinConflict on both registries:

v0 -> v1 change 2nd identical pin, master 2nd identical pin, this PR pin with a new edit, master pin with a new edit, this PR
schema FeatureViewPinConflict FeatureViewPinConflict FeatureViewPinConflict FeatureViewPinConflict
UDF only ok FeatureViewPinConflict ok, new UDF dropped FeatureViewPinConflict

The check compares the declaration with the active definition and does not keep the declaration it accepted, so it cannot tell a repeat from a new edit. Now that the UDF is compared, a UDF-only rollback behaves like a schema rollback. Keeping the accepted pin (or a fingerprint of it) would change the pin flow for all feature view types in both registries, so I left it out of this PR. I can open a follow-up for that if you want it.

Comment on lines +217 to +220

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 False pin conflicts for unchanged UDFs

When a UDF has no source text, BatchFeatureView.__eq__ rejects valid pins after the function moves to another line. _udf_changed also treats identical NumPy arrays captured by separately loaded UDFs as a change.

Learn more

The constructor accepts a callable with no source string. Feast serializes that callable and restores it when loading the active view. The new equality check sends these functions through _udf_changed, which compares whole code objects and captured values. Code-object equality includes the first line number. Tuple equality also needs a single truth value for each capture, which a multi-element NumPy array comparison cannot supply. The helper reports a change in either case, so the pin guard rejects the rollback even though its transformation did not change.

Example: Declare a SQL UDF in a factory without udf_string and publish v0 and v1. Add a blank line before the factory while preparing a rollback to v0. The v1 callable and stored callable return the same query, but the shifted first line triggers FeatureViewPinConflict. A Pandas UDF capturing np.array([1, 2]) can hit the same conflict without moving any code, because the stored callable has its own copy of the array.

Recommended fix: Compare executable code and constants without source positions, including for nested code objects. Compare supported array captures and defaults explicitly by shape, dtype, and contents. Keep regression tests for changed constants, defaults, and closures so the pin guard still rejects real edits.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in 565de02.

For a UDF without udf_string that dill stores by value (closures, lambdas, functions defined in __main__), the pin raised FeatureViewPinConflict when the factory only moved down one line, and when the UDF captured np.array([1, 2]). On master the same comparison already made a plain re-apply store a new version for these UDFs.

_udf_changed now clears the source positions (first line number and line table, nested code included) before comparing code objects, and compares arrays by shape, dtype and contents. A moved, reformatted or array-capturing UDF no longer raises on a pin or stores a new version on re-apply. A changed constant, default, closure value or array still does. A module-level function in an importable module is pickled by reference and was not affected before or after.

Added test_pin_batch_feature_view_compares_udf_without_source (moved, reformatted, moved_and_edited, same_array, edited_array). moved, reformatted and same_array fail without the fix.


def __hash__(self) -> int:
return super().__hash__()

def _schema_or_udf_changed(self, other: BaseFeatureView) -> bool:
"""Check for BatchFeatureView schema/UDF changes."""
if super()._schema_or_udf_changed(other):
Expand Down Expand Up @@ -254,25 +275,57 @@ def _udf_changed(new_udf: Callable, old_udf: Callable) -> bool:
Bytecode alone misses constants: ``lambda _: "SELECT 1"`` and
``lambda _: "SELECT 2"`` share it. The code object also holds the
constants, so compare it whole, plus the default arguments and the values
captured in the closure.
captured in the closure. Source positions are left out, so a UDF that only
moved within its file is not a change.
"""

def state(udf: Callable) -> tuple:
closure = tuple(cell.cell_contents for cell in udf.__closure__ or ()) # type: ignore[attr-defined]
return (
udf.__code__, # type: ignore[attr-defined]
_without_positions(udf.__code__), # type: ignore[attr-defined]
udf.__defaults__, # type: ignore[attr-defined]
udf.__kwdefaults__, # type: ignore[attr-defined]
closure,
)

try:
return bool(state(new_udf) != state(old_udf))
return not _same_value(state(new_udf), state(old_udf))
except Exception:
# Values that cannot be compared count as a change, so the new UDF is stored.
return True


def _without_positions(code: CodeType) -> CodeType:
"""Clear the source positions of a code object and the code nested in it."""
consts = tuple(
_without_positions(const) if isinstance(const, CodeType) else const
for const in code.co_consts
)
return code.replace(co_firstlineno=1, co_linetable=b"", co_consts=consts)


def _same_value(a: Any, b: Any) -> bool:
"""Compare like ``==``, but compare NumPy arrays by shape, dtype and contents.

``==`` on two arrays gives an array, which has no single truth value, and a
UDF loaded back from the registry holds its own copy of each captured array.
"""
if a is b:
return True
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return (
type(a) is type(b)
and a.shape == b.shape
and a.dtype == b.dtype
and bool(np.array_equal(a, b, equal_nan=a.dtype.kind in "fc"))
)
if isinstance(a, (tuple, list)) and type(a) is type(b):
return len(a) == len(b) and all(map(_same_value, a, b))
if isinstance(a, dict) and type(a) is type(b):
return a.keys() == b.keys() and all(_same_value(a[k], b[k]) for k in a)
return bool(a == b)


def batch_feature_view(
*,
name: Optional[str] = None,
Expand Down
140 changes: 139 additions & 1 deletion sdk/python/tests/unit/infra/registry/test_file_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from feast.batch_feature_view import BatchFeatureView
from feast.data_source import PushSource
from feast.entity import Entity
from feast.errors import ConflictingFeatureViewNames
from feast.errors import ConflictingFeatureViewNames, FeatureViewPinConflict
from feast.feature_view import FeatureView
from feast.infra.offline_stores.file_source import FileSource
from feast.infra.registry.registry import Registry
Expand Down Expand Up @@ -127,6 +127,144 @@ def make_view(udf):
assert stored.feature_transformation.udf(None) == "SELECT 2"


def test_pin_batch_feature_view_rejects_changed_udf(file_registry):
"""Pinning a version while also changing the UDF raises instead of dropping it."""
entity = Entity(name="driver", join_keys=["driver_id"])
file_registry.apply_entity(entity, "test_project")
file_source, _ = _make_sources()

def make_view(udf, udf_string, version="latest"):
return BatchFeatureView(
name="driver_bfv",
entities=[entity],
mode="pandas",
source=file_source,
schema=[Field(name="out", dtype=Float32)],
ttl=timedelta(days=1),
udf=udf,
udf_string=udf_string,
version=version,
)

def udf_a(df):
return df

def udf_b(df):
return df

def udf_c(df):
return df

file_registry.apply_feature_view(make_view(udf_a, "udf_a source"), "test_project")
file_registry.apply_feature_view(make_view(udf_b, "udf_b source"), "test_project")

with pytest.raises(FeatureViewPinConflict):
file_registry.apply_feature_view(
make_view(udf_c, "udf_c source", version="v0"), "test_project"
)

# Pinning with the active definition unchanged still restores v0.
file_registry.apply_feature_view(
make_view(udf_b, "udf_b source", version="v0"), "test_project"
)
stored = file_registry.get_feature_view("driver_bfv", "test_project")
assert stored.feature_transformation.udf_string == "udf_a source"


_UDF_FACTORIES = """
import numpy as np


def make_query_udf(query):
def udf(df):
return " ".join(word for word in query.split())

return udf


def make_array_udf(values):
weights = np.array(values)

def udf(df):
return df * weights

return udf
"""


_SOURCE_EDITS = {
"none": lambda source: source,
# A line added above the factories moves every UDF down.
"moved": lambda source: "\n" + source,
# A blank line inside the UDF body changes only its line table.
"reformatted": lambda source: source.replace("(df):\n", "(df):\n\n"),
}


def _load_udf(factory, arg, edit="none"):
"""Build a UDF from a module that is not importable, so dill stores it by value."""
namespace = {"__name__": "feature_definitions_not_importable"}
source = _SOURCE_EDITS[edit](_UDF_FACTORIES)
exec(compile(source, "feature_definitions.py", "exec"), namespace)
return namespace[factory](arg)


@pytest.mark.parametrize(
"factory, arg, edit, changed",
[
("make_query_udf", "SELECT 1", "moved", False),
("make_query_udf", "SELECT 1", "reformatted", False),
("make_query_udf", "SELECT 2", "moved", True),
("make_array_udf", [1, 2], "none", False),
("make_array_udf", [1, 3], "none", True),
],
ids=["moved", "reformatted", "moved_and_edited", "same_array", "edited_array"],
)
def test_pin_batch_feature_view_compares_udf_without_source(
file_registry, factory, arg, edit, changed
):
"""Without a udf_string, moving the UDF or capturing an array is not an edit."""
entity = Entity(name="driver", join_keys=["driver_id"])
file_registry.apply_entity(entity, "test_project")
file_source, _ = _make_sources()

def make_view(udf, version="latest"):
return BatchFeatureView(
name="driver_bfv",
entities=[entity],
mode="pandas",
source=file_source,
schema=[Field(name="out", dtype=Float32)],
ttl=timedelta(days=1),
udf=udf,
udf_string="",
version=version,
)

base_arg = {"make_query_udf": "SELECT 1", "make_array_udf": [1, 2]}[factory]
file_registry.apply_feature_view(
make_view(_load_udf("make_query_udf", "SELECT 0")), "test_project"
)
file_registry.apply_feature_view(
make_view(_load_udf(factory, base_arg)), "test_project"
)

# The version check and the pin check agree on what counts as an edit.
active = file_registry.get_feature_view("driver_bfv", "test_project")
candidate = make_view(_load_udf(factory, arg, edit))
assert candidate._schema_or_udf_changed(active) is changed

pinned = make_view(_load_udf(factory, arg, edit), version="v0")
if changed:
with pytest.raises(FeatureViewPinConflict):
file_registry.apply_feature_view(pinned, "test_project")
else:
file_registry.apply_feature_view(pinned, "test_project")
stored = file_registry.get_feature_view("driver_bfv", "test_project")
assert stored.current_version_number == 0
assert stored.feature_transformation.udf(None) == "SELECT 0"


def test_same_project_name_conflict_batch_vs_stream(file_registry):
"""A FeatureView and StreamFeatureView with the same name in the same project must raise ConflictingFeatureViewNames."""
entity = Entity(name="driver", value_type=ValueType.STRING, join_keys=["driver_id"])
Expand Down
35 changes: 35 additions & 0 deletions sdk/python/tests/unit/test_feature_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,41 @@ def test_batch_feature_view_copy_keeps_online_config() -> None:
assert copy.copy(bfv).online_config == online_config


def test_batch_feature_view_eq_compares_transformation() -> None:
def udf_a(df: pd.DataFrame) -> pd.DataFrame:
return df

def udf_b(df: pd.DataFrame) -> pd.DataFrame:
return df

def make_view(udf, udf_string):
return BatchFeatureView(
name="test_batch_feature_view",
entities=[Entity(name="test_entity", join_keys=["entity_id"])],
schema=[Field(name="input_feature", dtype=Int64)],
source=FileSource(
name="test-source",
path="test_data.parquet",
timestamp_field="event_timestamp",
),
ttl=timedelta(days=1),
udf=udf,
udf_string=udf_string,
mode="pandas",
)

bfv = make_view(udf_a, "udf_a source")
other = make_view(udf_b, "udf_b source")
assert bfv != other
assert bfv == BatchFeatureView.from_proto(bfv.to_proto())
assert len({bfv, make_view(udf_a, "udf_a source")}) == 1

# Views loaded with skip_udf=True only carry the transformation proto.
skipped = BatchFeatureView.from_proto(bfv.to_proto(), skip_udf=True)
assert skipped == BatchFeatureView.from_proto(bfv.to_proto(), skip_udf=True)
assert skipped != BatchFeatureView.from_proto(other.to_proto(), skip_udf=True)


def test_transformation_mode_serialization():
"""
Test that transformation mode is properly serialized to proto and deserialized back.
Expand Down
Loading