From 3f7a140385b09240cead4a694d4aeaebced0f0fe Mon Sep 17 00:00:00 2001 From: ntkathole Date: Thu, 1 Oct 2026 10:41:33 +0530 Subject: [PATCH 1/3] fix: Normalize Arrow-backed dtypes from Ray Dataset.to_pandas() for pyarrow >=25 compatibility Signed-off-by: ntkathole --- .../feast/infra/compute_engines/ray/job.py | 15 +++- .../contrib/ray_offline_store/ray.py | 5 +- sdk/python/feast/infra/ray_shared_utils.py | 74 +++++++++++++++++++ sdk/python/tests/utils/e2e_test_validation.py | 11 +-- 4 files changed, 92 insertions(+), 13 deletions(-) diff --git a/sdk/python/feast/infra/compute_engines/ray/job.py b/sdk/python/feast/infra/compute_engines/ray/job.py index e818220baff..2d678957ef9 100644 --- a/sdk/python/feast/infra/compute_engines/ray/job.py +++ b/sdk/python/feast/infra/compute_engines/ray/job.py @@ -24,6 +24,7 @@ from feast.infra.offline_stores.file_source import SavedDatasetFileStorage from feast.infra.offline_stores.offline_store import RetrievalJob, RetrievalMetadata from feast.infra.ray_initializer import get_ray_wrapper +from feast.infra.ray_shared_utils import normalize_arrow_dtypes from feast.repo_config import RepoConfig from feast.saved_dataset import SavedDatasetStorage @@ -121,7 +122,9 @@ def to_df( assert self._result_dataset is not None, ( "Dataset should not be None after execution" ) - self._result_df = self._result_dataset.to_pandas() + self._result_df = normalize_arrow_dtypes( + self._result_dataset.to_pandas() + ) # Handle validation if provided if validation_reference: @@ -157,7 +160,9 @@ def to_arrow( assert self._result_dataset is not None, ( "Dataset should not be None after execution" ) - self._result_arrow = self._result_dataset.to_pandas().to_arrow() + self._result_arrow = pa.Table.from_pandas( + normalize_arrow_dtypes(self._result_dataset.to_pandas()) + ) # Handle validation if provided if validation_reference: @@ -249,7 +254,7 @@ def _to_df_internal(self, timeout: Optional[int] = None) -> pd.DataFrame: assert self._result_dataset is not None, ( "Dataset should not be None after execution" ) - return self._result_dataset.to_pandas() + return normalize_arrow_dtypes(self._result_dataset.to_pandas()) def _to_arrow_internal(self, timeout: Optional[int] = None) -> pa.Table: """Internal method to get Arrow Table (used by parent class).""" @@ -257,7 +262,9 @@ def _to_arrow_internal(self, timeout: Optional[int] = None) -> pa.Table: assert self._result_dataset is not None, ( "Dataset should not be None after execution" ) - return self._result_dataset.to_pandas().to_arrow() + return pa.Table.from_pandas( + normalize_arrow_dtypes(self._result_dataset.to_pandas()) + ) @dataclass diff --git a/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py b/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py index 5230797d94b..c798be479ac 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py +++ b/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py @@ -47,6 +47,7 @@ apply_field_mapping, ensure_timestamp_compatibility, is_ray_data, + normalize_arrow_dtypes, normalize_timestamp_columns, ) from feast.infra.registry.base_registry import BaseRegistry @@ -1084,7 +1085,7 @@ def to_df( else: if self._prefer_ray_datasets: ray_ds = self._get_ray_dataset() - df = ray_ds.to_pandas() + df = normalize_arrow_dtypes(ray_ds.to_pandas()) else: result = self._resolve() if isinstance(result, pd.DataFrame): @@ -1191,7 +1192,7 @@ def to_sql(self) -> str: def _to_df_internal(self, timeout: Optional[int] = None) -> pd.DataFrame: if self._prefer_ray_datasets: ray_ds = self._get_ray_dataset() - return ray_ds.to_pandas() + return normalize_arrow_dtypes(ray_ds.to_pandas()) else: return self._resolve().to_pandas() diff --git a/sdk/python/feast/infra/ray_shared_utils.py b/sdk/python/feast/infra/ray_shared_utils.py index 1d26074290a..6e75be37256 100644 --- a/sdk/python/feast/infra/ray_shared_utils.py +++ b/sdk/python/feast/infra/ray_shared_utils.py @@ -7,6 +7,80 @@ from ray.data import Dataset +def normalize_arrow_dtypes(df: pd.DataFrame) -> pd.DataFrame: + """Convert non-standard extension dtypes from Ray to traditional types. + + Ray Data >= 2.58 with pyarrow >= 25 may produce extension dtype columns + from ``Dataset.to_pandas()``: + + * ``pd.ArrowDtype`` — Arrow-backed types (list, int, float, …) + * ``PythonObjectDtype`` — Ray's generic object extension for ragged lists + * ``TensorDtype`` — Ray's fixed-shape tensor extension for uniform lists + + Downstream Feast code expects traditional numpy-backed dtypes (``object`` + for list columns, ``float64`` with ``NaN`` for nullable numerics). This + function detects columns with non-standard extension dtypes and converts + list/array-like columns to ``object`` dtype with pure Python objects. + + Extension dtypes that pandas already recognises as scalar types (numeric, + string, datetime, boolean) are left untouched — this preserves both + ``pd.ArrowDtype(pa.int64())`` and pandas nullable dtypes like + ``pd.Int64Dtype()``. + + On older pandas or when no conversion is needed the function is a + fast no-op. + """ + # Well-known pandas extension dtypes that should always be preserved + _KEEP: tuple = (pd.CategoricalDtype,) + for attr in ("DatetimeTZDtype",): + cls = getattr(pd, attr, None) + if cls is not None: + _KEEP = (*_KEEP, cls) + + arrow_dtype_cls = getattr(pd, "ArrowDtype", None) + + cols_to_fix = [] + for c in df.columns: + dtype = df[c].dtype + if not isinstance(dtype, pd.api.extensions.ExtensionDtype): + continue + if isinstance(dtype, _KEEP): + continue + # Skip extension dtypes that pandas recognises as standard scalar + # categories. This preserves pd.ArrowDtype(int64), pd.Int64Dtype(), + # pd.ArrowDtype(float64), pd.Float64Dtype(), pd.StringDtype(), etc. + if ( + pd.api.types.is_numeric_dtype(dtype) + or pd.api.types.is_string_dtype(dtype) + or pd.api.types.is_datetime64_any_dtype(dtype) + or pd.api.types.is_object_dtype(dtype) + ): + continue + # For ArrowDtype, also preserve timestamp/date types that the + # generic checkers above may not recognise. + if arrow_dtype_cls and isinstance(dtype, arrow_dtype_cls): + pa_type = dtype.pyarrow_dtype + if pa.types.is_timestamp(pa_type) or pa.types.is_date(pa_type): + continue + cols_to_fix.append(c) + + if not cols_to_fix: + return df + + df = df.copy() + for col in cols_to_fix: + # Convert each element to a pure Python object. numpy arrays from + # Ray's TensorDtype are converted to Python lists via .tolist() so + # that downstream isinstance checks against (np.ndarray, list) and + # pa.Table.from_pandas() type inference both work correctly. + df[col] = pd.Series( + [v.tolist() if isinstance(v, np.ndarray) else v for v in df[col]], + index=df.index, + dtype=object, + ) + return df + + class RemoteDatasetProxy: """Proxy class that executes Ray Data operations remotely on cluster workers.""" diff --git a/sdk/python/tests/utils/e2e_test_validation.py b/sdk/python/tests/utils/e2e_test_validation.py index c89d61b9d5a..0dd94b146a3 100644 --- a/sdk/python/tests/utils/e2e_test_validation.py +++ b/sdk/python/tests/utils/e2e_test_validation.py @@ -1,4 +1,3 @@ -import math import os import time from datetime import datetime, timedelta, timezone @@ -159,18 +158,16 @@ def _check_offline_and_online_features( < 1e-6 ) else: - assert not df.to_dict(orient="list")[f"{fv.name}__value"] or math.isnan( - df.to_dict(orient="list")[f"{fv.name}__value"][0] - ) + val_list = df.to_dict(orient="list")[f"{fv.name}__value"] + assert not val_list or pd.isna(val_list[0]) else: if expected_value: assert ( abs(df.to_dict(orient="list")["value"][0] - expected_value) < 1e-6 ) else: - assert not df.to_dict(orient="list")["value"] or math.isnan( - df.to_dict(orient="list")["value"][0] - ) + val_list = df.to_dict(orient="list")["value"] + assert not val_list or pd.isna(val_list[0]) def make_feature_store_yaml( From 4dbb47804954500e93fa3ffaf21cda4bf37a57c7 Mon Sep 17 00:00:00 2001 From: ntkathole Date: Thu, 1 Oct 2026 12:05:30 +0530 Subject: [PATCH 2/3] fix: Detect Ray TensorDtype/PythonObjectDtype by module and normalize to_arrow RayRetrievalJob.to_arrow used Dataset.to_arrow_refs(), which preserves Ray extension types as ArrowPythonObjectType(large_binary). TensorDtype was also skipped by is_numeric_dtype. Detect Ray dtypes via module path, convert cells with .tolist(), and route to_arrow through the normalized pandas path. Signed-off-by: ntkathole --- .../contrib/ray_offline_store/ray.py | 42 +--- sdk/python/feast/infra/ray_shared_utils.py | 127 +++++++----- .../infra/test_ray_normalize_arrow_dtypes.py | 195 ++++++++++++++++++ 3 files changed, 278 insertions(+), 86 deletions(-) create mode 100644 sdk/python/tests/unit/infra/test_ray_normalize_arrow_dtypes.py diff --git a/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py b/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py index c798be479ac..9d280d3e64c 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py +++ b/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py @@ -1118,24 +1118,13 @@ def to_arrow( validation_reference=validation_reference, timeout=timeout ) - if self._prefer_ray_datasets: - try: - import ray as _ray - - ray_ds = self._get_ray_dataset() - return pa.concat_tables(_ray.get(ray_ds.to_arrow_refs())) - except Exception: - df = self.to_df( - validation_reference=validation_reference, timeout=timeout - ) - return pa.Table.from_pandas(df) - else: - result = self._resolve() - if isinstance(result, pd.DataFrame): - return pa.Table.from_pandas(result) - else: - df = result.to_pandas() - return pa.Table.from_pandas(df) + # Always go through the normalized pandas path. Ray's + # Dataset.to_arrow_refs() preserves TensorDtype / PythonObjectDtype as + # ArrowPythonObjectType(large_binary), which breaks list-feature type + # contracts. normalize_arrow_dtypes() in to_df() restores plain Python + # lists so pa.Table.from_pandas infers real Arrow list types. + df = self.to_df(validation_reference=validation_reference, timeout=timeout) + return pa.Table.from_pandas(df) def to_feast_df( self, @@ -1197,22 +1186,7 @@ def _to_df_internal(self, timeout: Optional[int] = None) -> pd.DataFrame: return self._resolve().to_pandas() def _to_arrow_internal(self, timeout: Optional[int] = None) -> pa.Table: - if self._prefer_ray_datasets: - try: - import ray as _ray - - ray_ds = self._get_ray_dataset() - return pa.concat_tables(_ray.get(ray_ds.to_arrow_refs())) - except Exception: - ray_ds = self._get_ray_dataset() - return pa.Table.from_pandas(ray_ds.to_pandas()) - else: - result = self._resolve() - if isinstance(result, pd.DataFrame): - return pa.Table.from_pandas(result) - else: - df = result.to_pandas() - return pa.Table.from_pandas(df) + return pa.Table.from_pandas(self._to_df_internal(timeout=timeout)) def persist( self, diff --git a/sdk/python/feast/infra/ray_shared_utils.py b/sdk/python/feast/infra/ray_shared_utils.py index 6e75be37256..9917896212b 100644 --- a/sdk/python/feast/infra/ray_shared_utils.py +++ b/sdk/python/feast/infra/ray_shared_utils.py @@ -7,74 +7,97 @@ from ray.data import Dataset +def _is_ray_extension_dtype(dtype: Any) -> bool: + """Return True for Ray-specific pandas extension dtypes. + + Ray Data registers custom extension types such as ``TensorDtype`` and + ``PythonObjectDtype``. These must *not* be identified via + ``pd.api.types.is_numeric_dtype`` / ``is_object_dtype`` because + ``TensorDtype(dtype=int64)`` reports as numeric and would otherwise be + skipped. + """ + module = type(dtype).__module__ + return module.startswith("ray.") or ".ray." in module + + +def _is_nested_arrow_dtype(dtype: Any) -> bool: + """Return True for ArrowDtype columns that hold list/struct/map values.""" + arrow_dtype_cls = getattr(pd, "ArrowDtype", None) + if arrow_dtype_cls is None or not isinstance(dtype, arrow_dtype_cls): + return False + pa_type = dtype.pyarrow_dtype + return ( + pa.types.is_list(pa_type) + or pa.types.is_large_list(pa_type) + or pa.types.is_fixed_size_list(pa_type) + or pa.types.is_struct(pa_type) + or pa.types.is_map(pa_type) + ) + + +def _cell_to_python(value: Any) -> Any: + """Convert a list/array-like cell to a plain Python object. + + Ray's ``TensorDtype`` yields ``TensorArrayElement`` values that print like + ``array([...])`` but are *not* ``isinstance(..., np.ndarray)``. Using + ``.tolist()`` / ``np.asarray(...).tolist()`` produces real Python lists so + that: + * ``isinstance(v, (np.ndarray, list))`` succeeds via ``list`` + * ``pa.Table.from_pandas`` infers a proper Arrow list type + """ + if value is None or isinstance(value, (list, tuple, str, bytes, dict)): + return list(value) if isinstance(value, tuple) else value + if isinstance(value, np.ndarray): + return value.tolist() + # Ray TensorArrayElement and similar array-likes + if hasattr(value, "tolist") and not isinstance(value, (pd.Timestamp,)): + try: + return value.tolist() + except Exception: + pass + if hasattr(value, "__array__"): + try: + arr = np.asarray(value) + if getattr(arr, "ndim", 0) > 0: + return arr.tolist() + except Exception: + pass + return value + + def normalize_arrow_dtypes(df: pd.DataFrame) -> pd.DataFrame: - """Convert non-standard extension dtypes from Ray to traditional types. + """Convert Ray/Arrow nested extension dtypes to traditional object columns. Ray Data >= 2.58 with pyarrow >= 25 may produce extension dtype columns from ``Dataset.to_pandas()``: - * ``pd.ArrowDtype`` — Arrow-backed types (list, int, float, …) + * ``pd.ArrowDtype(list<...>)`` — Arrow-backed list types * ``PythonObjectDtype`` — Ray's generic object extension for ragged lists * ``TensorDtype`` — Ray's fixed-shape tensor extension for uniform lists - Downstream Feast code expects traditional numpy-backed dtypes (``object`` - for list columns, ``float64`` with ``NaN`` for nullable numerics). This - function detects columns with non-standard extension dtypes and converts - list/array-like columns to ``object`` dtype with pure Python objects. + Downstream Feast code and universal type tests expect list feature columns + as plain ``object`` dtype containing Python ``list`` / ``np.ndarray`` + values, and Arrow tables with real ``list`` types (not + ``ArrowPythonObjectType(large_binary)``). - Extension dtypes that pandas already recognises as scalar types (numeric, - string, datetime, boolean) are left untouched — this preserves both - ``pd.ArrowDtype(pa.int64())`` and pandas nullable dtypes like - ``pd.Int64Dtype()``. - - On older pandas or when no conversion is needed the function is a - fast no-op. + Scalar pandas / Arrow extension dtypes (``Int64Dtype``, + ``ArrowDtype(int64)``, etc.) are left untouched. """ - # Well-known pandas extension dtypes that should always be preserved - _KEEP: tuple = (pd.CategoricalDtype,) - for attr in ("DatetimeTZDtype",): - cls = getattr(pd, attr, None) - if cls is not None: - _KEEP = (*_KEEP, cls) - - arrow_dtype_cls = getattr(pd, "ArrowDtype", None) - - cols_to_fix = [] - for c in df.columns: - dtype = df[c].dtype - if not isinstance(dtype, pd.api.extensions.ExtensionDtype): - continue - if isinstance(dtype, _KEEP): - continue - # Skip extension dtypes that pandas recognises as standard scalar - # categories. This preserves pd.ArrowDtype(int64), pd.Int64Dtype(), - # pd.ArrowDtype(float64), pd.Float64Dtype(), pd.StringDtype(), etc. - if ( - pd.api.types.is_numeric_dtype(dtype) - or pd.api.types.is_string_dtype(dtype) - or pd.api.types.is_datetime64_any_dtype(dtype) - or pd.api.types.is_object_dtype(dtype) - ): - continue - # For ArrowDtype, also preserve timestamp/date types that the - # generic checkers above may not recognise. - if arrow_dtype_cls and isinstance(dtype, arrow_dtype_cls): - pa_type = dtype.pyarrow_dtype - if pa.types.is_timestamp(pa_type) or pa.types.is_date(pa_type): - continue - cols_to_fix.append(c) - + cols_to_fix = [ + c + for c in df.columns + if isinstance(df[c].dtype, pd.api.extensions.ExtensionDtype) + and ( + _is_ray_extension_dtype(df[c].dtype) or _is_nested_arrow_dtype(df[c].dtype) + ) + ] if not cols_to_fix: return df df = df.copy() for col in cols_to_fix: - # Convert each element to a pure Python object. numpy arrays from - # Ray's TensorDtype are converted to Python lists via .tolist() so - # that downstream isinstance checks against (np.ndarray, list) and - # pa.Table.from_pandas() type inference both work correctly. df[col] = pd.Series( - [v.tolist() if isinstance(v, np.ndarray) else v for v in df[col]], + [_cell_to_python(v) for v in df[col]], index=df.index, dtype=object, ) diff --git a/sdk/python/tests/unit/infra/test_ray_normalize_arrow_dtypes.py b/sdk/python/tests/unit/infra/test_ray_normalize_arrow_dtypes.py new file mode 100644 index 00000000000..82d8577aae9 --- /dev/null +++ b/sdk/python/tests/unit/infra/test_ray_normalize_arrow_dtypes.py @@ -0,0 +1,195 @@ +"""Unit tests for Ray list-column dtype normalization.""" + +from __future__ import annotations + +from typing import Any, Sequence + +import numpy as np +import pandas as pd +import pyarrow as pa +import pytest +from pandas.api.extensions import ExtensionArray, register_extension_dtype + +from feast.infra.ray_shared_utils import ( + _cell_to_python, + _is_nested_arrow_dtype, + _is_ray_extension_dtype, + normalize_arrow_dtypes, +) + + +@register_extension_dtype +class FakeRayTensorDtype(pd.api.extensions.ExtensionDtype): + """Mimics ray.data TensorDtype (numeric-looking, Ray module path).""" + + name = "fake_ray_tensor" + type = object + kind = "O" + na_value = None + + @classmethod + def construct_array_type(cls): + return FakeRayTensorArray + + @classmethod + def construct_from_string(cls, string: str): + if string == cls.name: + return cls() + raise TypeError(f"Cannot construct FakeRayTensorDtype from {string!r}") + + +# Match Ray's module path so _is_ray_extension_dtype returns True. +FakeRayTensorDtype.__module__ = "ray.data._internal.object_extensions.pandas" + + +class FakeTensorElement: + """Mimics Ray TensorArrayElement: looks like ndarray, isn't one.""" + + def __init__(self, data): + self._data = np.asarray(data) + + def __repr__(self): + return repr(self._data) + + def tolist(self): + return self._data.tolist() + + def __array__(self, dtype=None): + return np.asarray(self._data, dtype=dtype) + + def __eq__(self, other): + if isinstance(other, FakeTensorElement): + return np.array_equal(self._data, other._data) + return NotImplemented + + +class FakeRayTensorArray(ExtensionArray): + """Minimal ExtensionArray backing FakeRayTensorDtype.""" + + def __init__(self, values: Sequence[Any]): + self._values = list(values) + + @property + def dtype(self): + return FakeRayTensorDtype() + + @property + def nbytes(self) -> int: + return len(self._values) + + def __len__(self) -> int: + return len(self._values) + + def __getitem__(self, item): + if isinstance(item, (int, np.integer)): + return self._values[int(item)] + if isinstance(item, slice): + return FakeRayTensorArray(self._values[item]) + return FakeRayTensorArray([self._values[i] for i in item]) + + def __array__(self, dtype=None): + return np.asarray(self._values, dtype=object) + + def isna(self): + return np.array([v is None for v in self._values], dtype=bool) + + def take(self, indices, allow_fill=False, fill_value=None): + vals = [] + for idx in indices: + if allow_fill and idx == -1: + vals.append(fill_value) + else: + vals.append(self._values[idx]) + return FakeRayTensorArray(vals) + + def copy(self): + return FakeRayTensorArray(list(self._values)) + + @classmethod + def _from_sequence(cls, scalars, dtype=None, copy=False): + return cls(list(scalars)) + + def _from_factor(cls, data, dtype=None, copy=False): + return cls(list(data)) + + +def test_is_ray_extension_dtype_detects_ray_module(): + dtype = FakeRayTensorDtype() + assert _is_ray_extension_dtype(dtype) + assert not _is_ray_extension_dtype(pd.Int64Dtype()) + assert not _is_ray_extension_dtype(np.dtype("int64")) + + +def test_is_nested_arrow_dtype(): + if not hasattr(pd, "ArrowDtype"): + pytest.skip("pandas ArrowDtype not available") + assert _is_nested_arrow_dtype(pd.ArrowDtype(pa.list_(pa.int64()))) + assert _is_nested_arrow_dtype(pd.ArrowDtype(pa.large_list(pa.float64()))) + assert not _is_nested_arrow_dtype(pd.ArrowDtype(pa.int64())) + assert not _is_nested_arrow_dtype(pd.Int64Dtype()) + + +def test_cell_to_python_converts_array_likes(): + assert _cell_to_python(np.array([1, 2])) == [1, 2] + value = FakeTensorElement([1, 1]) + assert not isinstance(value, (np.ndarray, list)) + assert _cell_to_python(value) == [1, 1] + assert isinstance(_cell_to_python(value), list) + assert _cell_to_python([3, 4]) == [3, 4] + assert _cell_to_python(None) is None + + +def test_normalize_ray_tensor_column_end_to_end(): + arr = FakeRayTensorArray([FakeTensorElement([1, 1]), FakeTensorElement([2, 2])]) + df = pd.DataFrame({"value": arr}) + + # Sanity: this is the dtype shape Ray 2.58 returns for uniform lists. + assert isinstance(df["value"].dtype, FakeRayTensorDtype) + assert _is_ray_extension_dtype(df["value"].dtype) + assert not isinstance(df["value"].iloc[0], (np.ndarray, list)) + + out = normalize_arrow_dtypes(df) + assert pd.api.types.is_object_dtype(out["value"].dtype) + assert isinstance(out["value"].iloc[0], list) + assert out["value"].iloc[0] == [1, 1] + + table = pa.Table.from_pandas(out) + assert pa.types.is_list(table.schema.field("value").type) + + +def test_normalize_arrow_list_column_to_object_and_arrow_list(): + if not hasattr(pd, "ArrowDtype"): + pytest.skip("pandas ArrowDtype not available") + + arrow_lists = pd.Series( + [[1, 1], [], [2, 2]], + dtype=pd.ArrowDtype(pa.list_(pa.int64())), + ) + df = pd.DataFrame({"value": arrow_lists, "id": [1, 2, 3]}) + out = normalize_arrow_dtypes(df) + + assert pd.api.types.is_object_dtype(out["value"].dtype) + assert pd.api.types.is_integer_dtype(out["id"].dtype) + assert isinstance(out["value"].iloc[0], list) + assert out["value"].iloc[1] == [] + + table = pa.Table.from_pandas(out) + assert pa.types.is_list(table.schema.field("value").type) + + +def test_normalize_preserves_scalar_extension_dtypes(): + df = pd.DataFrame( + { + "ints": pd.Series([1, 2], dtype="Int64"), + "floats": pd.Series([1.0, 2.0], dtype="Float64"), + } + ) + out = normalize_arrow_dtypes(df) + assert str(out["ints"].dtype) == "Int64" + assert str(out["floats"].dtype) == "Float64" + + +def test_normalize_preserves_plain_numpy_columns(): + df = pd.DataFrame({"value": np.array([1, 2], dtype="int64")}) + out = normalize_arrow_dtypes(df) + assert pd.api.types.is_integer_dtype(out["value"].dtype) From 8850a517930bd43a63e750e9e4581e219aa1859e Mon Sep 17 00:00:00 2001 From: ntkathole Date: Thu, 1 Oct 2026 13:01:45 +0530 Subject: [PATCH 3/3] fix: Recover Arrow list value types for empty-list historical features MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PIT joins with has_empty_list fixtures can return only empty lists, so from_pandas infers list. Keep typed empty ndarrays, and cast null list columns using Feast-declared Arrow types (float32→float64). Signed-off-by: ntkathole --- .../contrib/ray_offline_store/ray.py | 32 +++++++- sdk/python/feast/infra/ray_shared_utils.py | 79 +++++++++++++++---- .../infra/test_ray_normalize_arrow_dtypes.py | 37 +++++++-- 3 files changed, 125 insertions(+), 23 deletions(-) diff --git a/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py b/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py index 9d280d3e64c..793e48fa604 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py +++ b/sdk/python/feast/infra/offline_stores/contrib/ray_offline_store/ray.py @@ -49,6 +49,7 @@ is_ray_data, normalize_arrow_dtypes, normalize_timestamp_columns, + pandas_to_arrow_with_list_types, ) from feast.infra.registry.base_registry import BaseRegistry from feast.on_demand_feature_view import OnDemandFeatureView @@ -60,6 +61,7 @@ feast_value_type_to_pandas_type, pa_to_feast_value_type, ) +from feast.types import from_feast_to_pyarrow_type from feast.utils import ( _get_column_names, compute_non_entity_date_range, @@ -989,6 +991,7 @@ def __init__( self._feature_refs: List[str] = [] self._entity_df: Optional[pd.DataFrame] = None self._prefer_ray_datasets: bool = True + self._feature_pa_types: Dict[str, pa.DataType] = {} def _create_metadata(self) -> RetrievalMetadata: """Create metadata from the entity DataFrame and feature references.""" @@ -1122,9 +1125,10 @@ def to_arrow( # Dataset.to_arrow_refs() preserves TensorDtype / PythonObjectDtype as # ArrowPythonObjectType(large_binary), which breaks list-feature type # contracts. normalize_arrow_dtypes() in to_df() restores plain Python - # lists so pa.Table.from_pandas infers real Arrow list types. + # lists / ndarrays; feature Arrow types (when set) recover list value + # types for all-empty list columns (list → list). df = self.to_df(validation_reference=validation_reference, timeout=timeout) - return pa.Table.from_pandas(df) + return pandas_to_arrow_with_list_types(df, self._feature_pa_types) def to_feast_df( self, @@ -1186,7 +1190,9 @@ def _to_df_internal(self, timeout: Optional[int] = None) -> pd.DataFrame: return self._resolve().to_pandas() def _to_arrow_internal(self, timeout: Optional[int] = None) -> pa.Table: - return pa.Table.from_pandas(self._to_df_internal(timeout=timeout)) + return pandas_to_arrow_with_list_types( + self._to_df_internal(timeout=timeout), self._feature_pa_types + ) def persist( self, @@ -2603,5 +2609,25 @@ def finalize_result(batch: pd.DataFrame) -> pd.DataFrame: job._on_demand_feature_views = on_demand_feature_views job._feature_refs = feature_refs job._entity_df = entity_df_sample + # Preserve Feast-declared Arrow types so to_arrow() can recover + # list when a result column only contains empty lists. + # Promote list → list: the pandas materialization + # path historically returns float64 for float features, and the + # universal type tests assert pa.types.is_float64. + feature_pa_types: Dict[str, pa.DataType] = {} + for fv in regular_feature_views: + for feature in fv.features: + try: + pa_type = from_feast_to_pyarrow_type(feature.dtype) + except (ValueError, KeyError, TypeError): + continue + if pa.types.is_list(pa_type) and pa.types.is_float32( + pa_type.value_type + ): + pa_type = pa.list_(pa.float64()) + feature_pa_types[feature.name] = pa_type + if full_feature_names: + feature_pa_types[f"{fv.name}__{feature.name}"] = pa_type + job._feature_pa_types = feature_pa_types job._metadata = job._create_metadata() return job diff --git a/sdk/python/feast/infra/ray_shared_utils.py b/sdk/python/feast/infra/ray_shared_utils.py index 9917896212b..d1469f68e31 100644 --- a/sdk/python/feast/infra/ray_shared_utils.py +++ b/sdk/python/feast/infra/ray_shared_utils.py @@ -36,35 +36,84 @@ def _is_nested_arrow_dtype(dtype: Any) -> bool: def _cell_to_python(value: Any) -> Any: - """Convert a list/array-like cell to a plain Python object. + """Convert a Ray extension cell to a plain Python / NumPy object. Ray's ``TensorDtype`` yields ``TensorArrayElement`` values that print like - ``array([...])`` but are *not* ``isinstance(..., np.ndarray)``. Using - ``.tolist()`` / ``np.asarray(...).tolist()`` produces real Python lists so - that: - * ``isinstance(v, (np.ndarray, list))`` succeeds via ``list`` - * ``pa.Table.from_pandas`` infers a proper Arrow list type + ``array([...])`` but are *not* ``isinstance(..., np.ndarray)``. + + Empty list features are stored by Feast as typed empty NumPy arrays + (see ``convert_array_column``) so that Arrow can infer ``list`` + rather than ``list``. Therefore we prefer keeping values as + ``np.ndarray`` (including empty ones) over calling ``.tolist()``, which + would turn ``np.empty(0, dtype=int32)`` into a typeless ``[]``. """ - if value is None or isinstance(value, (list, tuple, str, bytes, dict)): - return list(value) if isinstance(value, tuple) else value + if value is None or isinstance(value, (str, bytes, dict)): + return value + if isinstance(value, list): + return value + if isinstance(value, tuple): + return list(value) if isinstance(value, np.ndarray): - return value.tolist() + return value # Ray TensorArrayElement and similar array-likes - if hasattr(value, "tolist") and not isinstance(value, (pd.Timestamp,)): + if hasattr(value, "__array__") and not isinstance(value, (pd.Timestamp,)): try: - return value.tolist() + arr = np.asarray(value) + if getattr(arr, "ndim", 0) >= 1: + return arr except Exception: pass - if hasattr(value, "__array__"): + if hasattr(value, "tolist") and not isinstance(value, (pd.Timestamp,)): try: - arr = np.asarray(value) - if getattr(arr, "ndim", 0) > 0: - return arr.tolist() + return value.tolist() except Exception: pass return value +def pandas_to_arrow_with_list_types( + df: pd.DataFrame, + column_pa_types: Optional[Dict[str, pa.DataType]] = None, +) -> pa.Table: + """Convert a DataFrame to Arrow, preserving list value types when possible. + + ``pa.Table.from_pandas`` infers ``list`` when a list column + contains only empty Python lists. When ``column_pa_types`` provides the + Feast-declared Arrow type for a column (e.g. ``list``), that type + is used to cast the column after conversion. + + List columns inferred as ``list`` are promoted to ``list`` + to match the historical pandas materialization path that universal type + tests assert against. + """ + table = pa.Table.from_pandas(df, preserve_index=False) + column_pa_types = column_pa_types or {} + + arrays = [] + fields = [] + for field in table.schema: + col = table.column(field.name) + target = column_pa_types.get(field.name) + col_type = field.type + + if ( + target is not None + and pa.types.is_list(target) + and pa.types.is_list(col_type) + and pa.types.is_null(col_type.value_type) + and not pa.types.is_null(target.value_type) + ): + col = col.cast(target) + col_type = target + elif pa.types.is_list(col_type) and pa.types.is_float32(col_type.value_type): + col_type = pa.list_(pa.float64()) + col = col.cast(col_type) + + arrays.append(col) + fields.append(pa.field(field.name, col_type, nullable=field.nullable)) + return pa.Table.from_arrays(arrays, schema=pa.schema(fields)) + + def normalize_arrow_dtypes(df: pd.DataFrame) -> pd.DataFrame: """Convert Ray/Arrow nested extension dtypes to traditional object columns. diff --git a/sdk/python/tests/unit/infra/test_ray_normalize_arrow_dtypes.py b/sdk/python/tests/unit/infra/test_ray_normalize_arrow_dtypes.py index 82d8577aae9..eda7a65ab7a 100644 --- a/sdk/python/tests/unit/infra/test_ray_normalize_arrow_dtypes.py +++ b/sdk/python/tests/unit/infra/test_ray_normalize_arrow_dtypes.py @@ -15,6 +15,7 @@ _is_nested_arrow_dtype, _is_ray_extension_dtype, normalize_arrow_dtypes, + pandas_to_arrow_with_list_types, ) @@ -130,15 +131,41 @@ def test_is_nested_arrow_dtype(): def test_cell_to_python_converts_array_likes(): - assert _cell_to_python(np.array([1, 2])) == [1, 2] + assert isinstance(_cell_to_python(np.array([1, 2])), np.ndarray) + np.testing.assert_array_equal(_cell_to_python(np.array([1, 2])), np.array([1, 2])) value = FakeTensorElement([1, 1]) assert not isinstance(value, (np.ndarray, list)) - assert _cell_to_python(value) == [1, 1] - assert isinstance(_cell_to_python(value), list) + converted = _cell_to_python(value) + assert isinstance(converted, np.ndarray) + np.testing.assert_array_equal(converted, np.array([1, 1])) assert _cell_to_python([3, 4]) == [3, 4] assert _cell_to_python(None) is None +def test_cell_to_python_preserves_typed_empty_ndarray(): + empty = np.empty(0, dtype=np.int32) + out = _cell_to_python(empty) + assert isinstance(out, np.ndarray) + assert out.dtype == np.int32 + assert len(out) == 0 + + +def test_pandas_to_arrow_casts_null_list_using_feature_types(): + df = pd.DataFrame({"value": [[], []]}) + table = pandas_to_arrow_with_list_types(df, {"value": pa.list_(pa.int32())}) + assert pa.types.is_list(table.schema.field("value").type) + assert pa.types.is_int32(table.schema.field("value").type.value_type) + + +def test_pandas_to_arrow_infers_from_typed_empty_ndarray(): + df = pd.DataFrame( + {"value": [np.empty(0, dtype=np.int32), np.empty(0, dtype=np.int32)]} + ) + table = pandas_to_arrow_with_list_types(df) + assert pa.types.is_list(table.schema.field("value").type) + assert pa.types.is_int32(table.schema.field("value").type.value_type) + + def test_normalize_ray_tensor_column_end_to_end(): arr = FakeRayTensorArray([FakeTensorElement([1, 1]), FakeTensorElement([2, 2])]) df = pd.DataFrame({"value": arr}) @@ -150,8 +177,8 @@ def test_normalize_ray_tensor_column_end_to_end(): out = normalize_arrow_dtypes(df) assert pd.api.types.is_object_dtype(out["value"].dtype) - assert isinstance(out["value"].iloc[0], list) - assert out["value"].iloc[0] == [1, 1] + assert isinstance(out["value"].iloc[0], (np.ndarray, list)) + np.testing.assert_array_equal(np.asarray(out["value"].iloc[0]), np.array([1, 1])) table = pa.Table.from_pandas(out) assert pa.types.is_list(table.schema.field("value").type)