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
39 changes: 39 additions & 0 deletions sdk/python/feast/online_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,33 @@

TIMESTAMP_POSTFIX: str = "__ts"

# The Arrow type to_arrow() infers for a feature's values when some are present,
# used when every value is missing so the column type does not depend on the batch.
_ALL_MISSING_ARROW_TYPES: Dict[Optional[ValueType], pa.DataType] = {
ValueType.INT32: pa.int64(),
ValueType.INT64: pa.int64(),
ValueType.FLOAT: pa.float64(),
ValueType.DOUBLE: pa.float64(),
ValueType.STRING: pa.string(),
ValueType.BYTES: pa.binary(),
ValueType.PDF_BYTES: pa.binary(),
ValueType.IMAGE_BYTES: pa.binary(),
ValueType.BOOL: pa.bool_(),
Comment on lines +41 to +45

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.

🟡 Missing PDF and image features lose their type

_ALL_MISSING_ARROW_TYPES leaves PDF and image features as Arrow null when every entity lacks them. Both serialize as bytes, so populated batches use binary and the schema still changes between batches.

Learn more

Feast gives PDF and image features distinct schema types, but its protobuf serializer stores both as ordinary byte values. OnlineStore passes the distinct declared types to OnlineResponse, so a lookup for ordinary BYTES does not cover either alias.

Example: A request for an ImageBytes feature returns Arrow binary for a known item and Arrow null for a batch containing only unmaterialized items.

Recommended fix: Map both aliases to pa.binary() and add one Value(bytes_val=...) case for each alias to the parameterized Arrow test matrix.

Suggested change
ValueType.STRING: pa.string(),
ValueType.BYTES: pa.binary(),
ValueType.BOOL: pa.bool_(),
ValueType.STRING: pa.string(),
ValueType.BYTES: pa.binary(),
ValueType.PDF_BYTES: pa.binary(),
ValueType.IMAGE_BYTES: pa.binary(),
ValueType.BOOL: pa.bool_(),

Devin Review


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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 212e697: PdfBytes and ImageBytes map to binary, with a case for each in the parametrized test.

ValueType.UNIX_TIMESTAMP: pa.timestamp("us", tz="UTC"),
ValueType.UUID: pa.string(),
ValueType.TIME_UUID: pa.string(),
ValueType.INT32_LIST: pa.list_(pa.int64()),
ValueType.INT64_LIST: pa.list_(pa.int64()),
ValueType.FLOAT_LIST: pa.list_(pa.float64()),
ValueType.DOUBLE_LIST: pa.list_(pa.float64()),
ValueType.STRING_LIST: pa.list_(pa.string()),
ValueType.BYTES_LIST: pa.list_(pa.binary()),
ValueType.BOOL_LIST: pa.list_(pa.bool_()),
ValueType.UNIX_TIMESTAMP_LIST: pa.list_(pa.timestamp("us", tz="UTC")),
ValueType.UUID_LIST: pa.list_(pa.string()),
ValueType.TIME_UUID_LIST: pa.list_(pa.string()),
}


class OnlineResponse:
"""
Expand Down Expand Up @@ -102,8 +129,20 @@ def to_arrow(self, include_event_timestamps: bool = False) -> pa.Table:
Args:
include_event_timestamps: bool Optionally include feature timestamps in the table
"""
return self._to_arrow(include_event_timestamps, type_missing=True)

def _to_arrow(
self, include_event_timestamps: bool = False, type_missing: bool = False
) -> pa.Table:
# On demand transformations read this table through pandas, where a typed
# all-missing column becomes NaN/NaT instead of None, so they keep the null type.
result = self.to_dict(include_event_timestamps)
result = _convert_uuids_for_arrow(result)
if type_missing:
for name, values in result.items():
arrow_type = _ALL_MISSING_ARROW_TYPES.get(self._feature_types.get(name))
if arrow_type is not None and all(v is None for v in values):
result[name] = pa.nulls(len(values), type=arrow_type)
return pa.Table.from_pydict(result)

def to_tensor(
Expand Down
4 changes: 2 additions & 2 deletions sdk/python/feast/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -964,7 +964,7 @@ def _is_metrics_active():
)
elif odfv.mode in {"pandas", "substrait"}:
if initial_response_arrow is None:
initial_response_arrow = initial_response.to_arrow()
initial_response_arrow = initial_response._to_arrow()
initial_response_arrow = _apply_aggregations_to_response(
initial_response_arrow,
odfv.aggregations,
Expand Down Expand Up @@ -1016,7 +1016,7 @@ def _is_metrics_active():
)
elif odfv.mode in {"pandas", "substrait"}:
if initial_response_arrow is None:
initial_response_arrow = initial_response.to_arrow()
initial_response_arrow = initial_response._to_arrow()
odfv_input_arrow = initial_response_arrow
if odfv.mode == "pandas":
odfv_input_arrow = initial_response_arrow.select(
Expand Down
58 changes: 58 additions & 0 deletions sdk/python/tests/unit/test_on_demand_pandas_transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from datetime import datetime, timedelta

import pandas as pd
import pyarrow as pa
import pytest

from feast import (
Expand Down Expand Up @@ -655,3 +656,60 @@ def scaled(inputs: dict) -> dict:
assert response["scaled_alias__conv_rate_x10"] == [
pytest.approx(response["fv1__conv_rate"][0] * 10)
]


def test_pandas_odfv_sees_none_for_feature_missing_for_every_entity():
"""A pandas UDF must see None, not NaN, when no requested entity has the feature."""
with tempfile.TemporaryDirectory() as data_dir:
store = FeatureStore(
config=RepoConfig(
project="test_odfv_all_missing_input",
registry=os.path.join(data_dir, "registry.db"),
provider="local",
entity_key_serialization_version=3,
online_store=SqliteOnlineStoreConfig(
path=os.path.join(data_dir, "online.db")
),
)
)
end_date = datetime.now().replace(microsecond=0, second=0, minute=0)
start_date = end_date - timedelta(days=15)
driver_df = create_driver_hourly_stats_df([1001], start_date, end_date)
path = os.path.join(data_dir, "driver_stats.parquet")
driver_df.to_parquet(path=path, allow_truncated_timestamps=True)
driver = Entity(name="driver", join_keys=["driver_id"])
source = FileSource(
name="driver_hourly_stats_source",
path=path,
timestamp_field="event_timestamp",
created_timestamp_column="created",
)
driver_stats = FeatureView(
name="driver_stats",
entities=[driver],
ttl=timedelta(days=0),
schema=[Field(name="avg_daily_trips", dtype=Int64)],
online=True,
source=source,
)

@on_demand_feature_view(
sources=[driver_stats],
schema=[Field(name="is_new_driver", dtype=Bool)],
mode="pandas",
)
def new_driver_view(inputs: pd.DataFrame) -> pd.DataFrame:
out = pd.DataFrame()
out["is_new_driver"] = inputs["avg_daily_trips"].map(lambda v: v is None)
return out

store.apply([driver, source, driver_stats, new_driver_view])
store.write_to_online_store(feature_view_name="driver_stats", df=driver_df)

response = store.get_online_features(
entity_rows=[{"driver_id": 9999}],
features=["driver_stats:avg_daily_trips", "new_driver_view:is_new_driver"],
)

assert response.to_dict()["is_new_driver"] == [True]
assert response.to_arrow().schema.field("avg_daily_trips").type == pa.int64()
110 changes: 106 additions & 4 deletions sdk/python/tests/unit/test_online_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,31 @@

import math

from feast.online_response import OnlineResponse
import pyarrow as pa
import pytest

from feast.online_response import _ALL_MISSING_ARROW_TYPES, OnlineResponse
from feast.protos.feast.serving.ServingService_pb2 import GetOnlineFeaturesResponse
from feast.protos.feast.types.Value_pb2 import Value
from feast.protos.feast.types.Value_pb2 import (
BoolList,
BytesList,
DoubleList,
FloatList,
Int32List,
Int64List,
StringList,
Value,
)
from feast.value_type import ValueType


def _response(feature_name, values):
def _response(feature_name, values, feature_types=None):
resp = GetOnlineFeaturesResponse()
resp.metadata.feature_names.val.extend([feature_name])
vector = resp.results.add()
for v in values:
vector.values.append(v)
return OnlineResponse(resp)
return OnlineResponse(resp, feature_types=feature_types)


def test_to_tensor_string_feature_with_missing_first_row():
Expand All @@ -49,3 +62,92 @@ def test_to_tensor_numeric_feature_all_missing_still_tensor():
# numeric-looking default keeps the tensor path (regression guard)
assert hasattr(tensors["trips"], "shape")
assert tensors["trips"].shape[0] == 2


_UUID = "00000000-0000-0000-0000-000000000001"


_PRESENT_VALUES = [
(ValueType.INT32, Value(int32_val=1)),
(ValueType.INT64, Value(int64_val=1)),
(ValueType.FLOAT, Value(float_val=0.5)),
(ValueType.DOUBLE, Value(double_val=0.5)),
(ValueType.STRING, Value(string_val="a")),
(ValueType.BYTES, Value(bytes_val=b"a")),
(ValueType.PDF_BYTES, Value(bytes_val=b"%PDF")),
(ValueType.IMAGE_BYTES, Value(bytes_val=b"\x89PNG")),
(ValueType.BOOL, Value(bool_val=True)),
(ValueType.UNIX_TIMESTAMP, Value(unix_timestamp_val=1700000000)),
(ValueType.UUID, Value(uuid_val=_UUID)),
(ValueType.TIME_UUID, Value(time_uuid_val=_UUID)),
(ValueType.INT32_LIST, Value(int32_list_val=Int32List(val=[1]))),
(ValueType.INT64_LIST, Value(int64_list_val=Int64List(val=[1]))),
(ValueType.FLOAT_LIST, Value(float_list_val=FloatList(val=[0.5]))),
(ValueType.DOUBLE_LIST, Value(double_list_val=DoubleList(val=[0.5]))),
(ValueType.STRING_LIST, Value(string_list_val=StringList(val=["a"]))),
(ValueType.BYTES_LIST, Value(bytes_list_val=BytesList(val=[b"a"]))),
(ValueType.BOOL_LIST, Value(bool_list_val=BoolList(val=[True]))),
(
ValueType.UNIX_TIMESTAMP_LIST,
Value(unix_timestamp_list_val=Int64List(val=[1700000000])),
),
(ValueType.UUID_LIST, Value(uuid_list_val=StringList(val=[_UUID]))),
(ValueType.TIME_UUID_LIST, Value(time_uuid_list_val=StringList(val=[_UUID]))),
]


@pytest.mark.parametrize(
"value_type,present",
_PRESENT_VALUES,
ids=[value_type.name for value_type, _ in _PRESENT_VALUES],
)
def test_to_arrow_all_missing_feature_keeps_its_type(value_type, present):
# A batch where no entity has the feature must not change the column type.
found = _response("f", [present, Value()], {"f": value_type})
missing = _response("f", [Value(), Value()], {"f": value_type})

expected = found.to_arrow().schema.field("f").type
table = missing.to_arrow()

assert table.schema.field("f").type == expected
assert table.column("f").to_pylist() == [None, None]


def test_to_arrow_all_missing_cases_cover_every_mapped_type():
assert {value_type for value_type, _ in _PRESENT_VALUES} == set(
_ALL_MISSING_ARROW_TYPES
)


def test_to_arrow_all_missing_feature_with_full_feature_name():
response = _response(
"driver_fv__trips",
[Value(), Value()],
{"trips": ValueType.INT64, "driver_fv__trips": ValueType.INT64},
)

assert response.to_arrow().schema.field("driver_fv__trips").type == pa.int64()


def test_to_arrow_all_missing_feature_without_known_type_stays_null():
response = _response("f", [Value(), Value()], {})

assert response.to_arrow().schema.field("f").type == pa.null()


def test_to_arrow_partially_missing_feature_is_unchanged():
response = _response("f", [Value(float_val=0.5), Value()], {"f": ValueType.FLOAT})

table = response.to_arrow()

assert table.schema.field("f").type == pa.float64()
assert table.column("f").to_pylist() == [0.5, None]


def test_to_arrow_zero_rows_keeps_feature_type():
response = _response("f", [], {"f": ValueType.INT64})

table = response.to_arrow()

assert table.num_rows == 0
assert table.schema.field("f").type == pa.int64()