diff --git a/sdk/python/feast/transformation/python_transformation.py b/sdk/python/feast/transformation/python_transformation.py index 951fde11ba1..b38ed68c454 100644 --- a/sdk/python/feast/transformation/python_transformation.py +++ b/sdk/python/feast/transformation/python_transformation.py @@ -88,6 +88,19 @@ def transform(self, input_dict: dict) -> dict: return {**input_dict, **output_dict} def transform_singleton(self, input_dict: dict) -> dict: + # Each value in input_dict is a list with one entry per entity row. + # A singleton UDF takes a single row, so with more than one row it is + # called once per row and the results are collected back into lists. + if any(len(v) > 1 for v in input_dict.values()): + num_rows = max(len(v) for v in input_dict.values()) + results = [] + for i in range(num_rows): + row = {k: v[i] for k, v in input_dict.items()} + output_row = self.udf.__call__(row) + results.append({**row, **output_row}) + columns = dict.fromkeys(k for result in results for k in result) + return {k: [result.get(k) for result in results] for k in columns} + # This flattens the list of elements to extract the first one # in the case of a singleton element, it takes the value directly # in the case of a list of lists, it takes the first list diff --git a/sdk/python/tests/unit/test_on_demand_python_transformation.py b/sdk/python/tests/unit/test_on_demand_python_transformation.py index a34da5f7ee5..522c0c53a39 100644 --- a/sdk/python/tests/unit/test_on_demand_python_transformation.py +++ b/sdk/python/tests/unit/test_on_demand_python_transformation.py @@ -276,6 +276,30 @@ def test_python_singleton_view(self): + online_python_response["acc_rate"][0] ) + def test_python_singleton_view_multiple_entity_rows(self): + entity_rows = [ + {"driver_id": 1001}, + {"driver_id": 1002}, + {"driver_id": 1003}, + ] + + online_python_response = self.store.get_online_features( + entity_rows=entity_rows, + features=[ + "driver_hourly_stats:conv_rate", + "driver_hourly_stats:acc_rate", + "python_singleton_view:conv_rate_plus_acc_python_singleton", + ], + ).to_dict() + + # one transformed value per entity row, each from that row's own inputs + assert len(online_python_response["conv_rate_plus_acc_python_singleton"]) == 3 + for i in range(3): + assert online_python_response["conv_rate_plus_acc_python_singleton"][i] == ( + online_python_response["conv_rate"][i] + + online_python_response["acc_rate"][i] + ) + def test_python_pandas_parity(self): entity_rows = [ {