diff --git a/sdk/python/feast/infra/data_sources/contrib/lance/__init__.py b/sdk/python/feast/infra/data_sources/contrib/lance/__init__.py new file mode 100644 index 00000000000..795103e69b2 --- /dev/null +++ b/sdk/python/feast/infra/data_sources/contrib/lance/__init__.py @@ -0,0 +1,9 @@ +from feast.infra.data_sources.contrib.lance.lance_source import ( + LanceSource, + validate_lance_source_schema, +) + +__all__ = [ + "LanceSource", + "validate_lance_source_schema", +] diff --git a/sdk/python/feast/infra/data_sources/contrib/lance/lance_source.py b/sdk/python/feast/infra/data_sources/contrib/lance/lance_source.py new file mode 100644 index 00000000000..b31216765db --- /dev/null +++ b/sdk/python/feast/infra/data_sources/contrib/lance/lance_source.py @@ -0,0 +1,471 @@ +# Copyright 2026 The Feast Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""A non-JVM read path for Lance datasets. + +``LanceFormat`` (``feast.table_format``) is a format descriptor only. Today it is +consumed by exactly one source, ``SparkSource``, which turns it into +``spark.read.format("lance")``. That makes Lance reachable through the JVM, and +nothing else. ``LanceSource`` is the engine-agnostic half: it addresses a Lance +dataset either by URI or through a Lance namespace catalog, applies the +``version``/``tag`` pin carried by ``LanceFormat``, and hands the result to the +offline store as a PyArrow table. + +Pin semantics follow what was argued upstream: **a pin selects data, never +shape.** The declared ``FeatureView`` schema stays the contract, so a pinned +version whose schema disagrees fails explicitly rather than silently returning a +different width. See :func:`validate_lance_source_schema`. +""" + +import json +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple + +from feast.data_source import DataSource +from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto +from feast.repo_config import RepoConfig +from feast.table_format import LanceFormat +from feast.type_map import pa_to_feast_value_type +from feast.value_type import ValueType + +if TYPE_CHECKING: + import pyarrow + + from feast.feature_view import FeatureView + + +_CLASS_TYPE = "feast.infra.data_sources.contrib.lance.lance_source.LanceSource" + + +class LanceSource(DataSource): + """Data source backed by a Lance dataset, readable without Spark. + + A Lance dataset is addressed in exactly one of two ways, which correspond to + the two layers of the read path: + + 1. **Path-based** — pass ``uri``. The dataset is opened directly off local + disk or object storage. This is the smaller layer and needs no catalog. + 2. **Catalog-based** — pass ``table`` plus ``namespace_impl``. The dataset is + resolved through ``lance_namespace.connect(impl, properties)`` and a + ``table_id``, which is built from the ``namespace`` on the attached + ``LanceFormat`` plus ``table``. + + Either way, the ``version``/``tag`` pin on the attached ``LanceFormat`` is + applied at read time. Lance accepts an ``int`` version or a tag name string + in the same ``version=`` argument, so a tag is resolved by Lance itself + rather than by Feast. + + Args: + uri: Path or object-storage URI of the Lance dataset. Mutually exclusive + with ``table``. + table: Table name within the namespace. Requires ``namespace_impl``. + Mutually exclusive with ``uri``. + table_format: The ``LanceFormat`` carrying ``catalog``, ``namespace`` and + the optional ``version``/``tag`` pin. One is created implicitly if + omitted, so that the pin accessors always have something to read. + namespace_impl: Lance namespace implementation. ``lance_namespace`` + ships ``"rest"`` and ``"dir"``; the ``lance-namespace-impls`` package + adds ``"polaris"``, ``"glue"``, ``"hive2"``, ``"hive3"``, + ``"iceberg"`` and ``"unity"``. ``"dir"`` is a local-filesystem + namespace and exercises the identical ``namespace_client`` code path + as a remote catalog with no server to run. + namespace_properties: Properties passed through to + ``lance_namespace.connect``, e.g. ``{"root": "/path/to/warehouse"}`` + for the ``dir`` impl. + storage_options: Object-storage options passed to ``lance.dataset``. + + Raises: + ValueError: If neither or both of ``uri`` and ``table`` are given, if + ``table`` is given without ``namespace_impl``, or if ``table_format`` + is not a ``LanceFormat``. + + Examples: + Path-based, reading the latest version: + + >>> source = LanceSource( # doctest: +SKIP + ... uri="/data/user_embeddings.lance", + ... timestamp_field="event_timestamp", + ... ) + + Catalog-based, pinned to a tag so an eval set is reproducible: + + >>> from feast.table_format import LanceFormat + >>> source = LanceSource( # doctest: +SKIP + ... table="user_embeddings", + ... namespace_impl="dir", + ... namespace_properties={"root": "/warehouse"}, + ... table_format=LanceFormat(namespace="features", tag="eval_2026_q1"), + ... timestamp_field="event_timestamp", + ... ) + """ + + def __init__( + self, + *, + uri: Optional[str] = None, + table: Optional[str] = None, + table_format: Optional[LanceFormat] = None, + namespace_impl: Optional[str] = None, + namespace_properties: Optional[Dict[str, str]] = None, + storage_options: Optional[Dict[str, str]] = None, + name: Optional[str] = None, + timestamp_field: Optional[str] = None, + created_timestamp_column: Optional[str] = None, + field_mapping: Optional[Dict[str, str]] = None, + description: Optional[str] = "", + tags: Optional[Dict[str, str]] = None, + owner: Optional[str] = "", + ): + if table_format is not None and not isinstance(table_format, LanceFormat): + raise ValueError( + "LanceSource requires a LanceFormat table_format, got " + f"{type(table_format).__name__}." + ) + if uri and table: + raise ValueError( + "LanceSource accepts either uri or table, not both. A uri addresses " + "the dataset directly; a table addresses it through a namespace." + ) + if not uri and not table: + raise ValueError( + "LanceSource requires either uri (path-based) or table " + "(catalog-based) to address the dataset." + ) + if table and not namespace_impl: + raise ValueError( + "LanceSource with a table requires namespace_impl, e.g. 'dir' for a " + "local filesystem namespace or 'rest' for a Lance namespace server." + ) + + # Keep a format object unconditionally so the pin accessors never have to + # branch on None. + self.table_format = table_format or LanceFormat() + + _name = name or self._default_name(uri, table, self.table_format) + super().__init__( + name=_name, + timestamp_field=timestamp_field, + created_timestamp_column=created_timestamp_column, + field_mapping=field_mapping, + description=description, + tags=tags, + owner=owner, + ) + self.uri = uri + self.lance_table = table + self.namespace_impl = namespace_impl + self.namespace_properties = namespace_properties or {} + self.storage_options = storage_options or {} + + @staticmethod + def _default_name( + uri: Optional[str], table: Optional[str], table_format: LanceFormat + ) -> str: + if uri: + return uri + parts = [p for p in (table_format.catalog, table_format.namespace, table) if p] + return ".".join(parts) + + # ------------------------------------------------------------------ pin + + @property + def is_catalog_based(self) -> bool: + """Whether this source resolves through a Lance namespace.""" + return self.lance_table is not None + + @property + def pin(self) -> Optional[Any]: + """The Lance ``version=`` argument for this source's pin, if pinned. + + Lance accepts either an ``int`` version or a tag name string in the same + argument, so a tag needs no separate resolution step here. + """ + if self.table_format.version is not None: + return self.table_format.version + if self.table_format.tag: + return self.table_format.tag + return None + + @property + def pin_description(self) -> str: + """Human-readable description of the pin, for error messages.""" + if self.table_format.version is not None: + return f"version {self.table_format.version}" + if self.table_format.tag: + return f"tag '{self.table_format.tag}'" + return "latest version" + + @property + def table_id(self) -> List[str]: + """The Lance namespace ``table_id`` for this source. + + A Lance ``table_id`` is a list of identifier components. The namespace on + the attached ``LanceFormat`` is split on ``.`` so that a hierarchical + namespace such as ``"a.b"`` becomes ``["a", "b", ""]``. The ``dir`` + impl is flat and so takes a single-element id. + """ + if not self.lance_table: + raise ValueError( + f"LanceSource '{self.name}' is path-based and has no table_id. " + "Use the uri instead." + ) + namespace = self.table_format.namespace + components = namespace.split(".") if namespace else [] + return [*components, self.lance_table] + + # --------------------------------------------------------------- reading + + def get_namespace_client(self) -> Any: + """Connect to the Lance namespace addressed by this source.""" + if not self.namespace_impl: + raise ValueError( + f"LanceSource '{self.name}' has no namespace_impl to connect with." + ) + import lance_namespace + + return lance_namespace.connect( + self.namespace_impl, dict(self.namespace_properties) + ) + + def get_dataset(self) -> Any: + """Open the pinned ``lance.LanceDataset`` this source addresses. + + ``lance.write_dataset`` and ``lance.dataset`` both reject being given a + uri and a ``namespace_client`` at the same time, which is why the two + addressing modes are mutually exclusive on the source as well. + """ + import lance + + kwargs: Dict[str, Any] = {} + pin = self.pin + if pin is not None: + kwargs["version"] = pin + if self.storage_options: + kwargs["storage_options"] = dict(self.storage_options) + + if self.is_catalog_based: + return lance.dataset( + namespace_client=self.get_namespace_client(), + table_id=self.table_id, + **kwargs, + ) + return lance.dataset(uri=self.uri, **kwargs) + + def get_schema(self) -> "pyarrow.Schema": + """Return the Arrow schema of the pinned dataset without scanning it.""" + return self.get_dataset().schema + + def to_arrow( + self, + columns: Optional[List[str]] = None, + feature_view: Optional["FeatureView"] = None, + ) -> "pyarrow.Table": + """Materialise the pinned dataset as a PyArrow table. + + Args: + columns: Optional column projection, pushed down into the Lance scan. + feature_view: When supplied, the declared schema is enforced against + the data actually read, so that a pin can never change the shape + of the result. + """ + dataset = self.get_dataset() + if feature_view is not None: + _validate_against_feature_view(self, dataset.schema, feature_view) + + table = dataset.to_table(columns=columns) + if feature_view is not None: + from feast.utils import _validate_vector_field_lengths + + _validate_vector_field_lengths(table, feature_view) + return table + + # ----------------------------------------------------------- DataSource + + def source_type(self) -> DataSourceProto.SourceType.ValueType: + return DataSourceProto.CUSTOM_SOURCE + + def __eq__(self, other): + if not isinstance(other, LanceSource): + raise TypeError("Comparisons should only involve LanceSource class objects") + return ( + super().__eq__(other) + and self.uri == other.uri + and self.lance_table == other.lance_table + and self.namespace_impl == other.namespace_impl + and self.namespace_properties == other.namespace_properties + and self.storage_options == other.storage_options + and self.table_format.to_dict() == other.table_format.to_dict() + ) + + def __hash__(self): + return super().__hash__() + + @staticmethod + def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]: + # Lance surfaces its schema as Arrow, so the Arrow decoder applies + # unchanged, exactly as it does for FileSource. + return pa_to_feast_value_type + + def get_table_column_names_and_types( + self, config: RepoConfig + ) -> Iterable[Tuple[str, str]]: + """Return ``(name, str(arrow_type))`` pairs for the **pinned** schema. + + Reading the pinned schema rather than the latest one is deliberate: the + schema that ``feast apply`` infers must be the schema that reads will + actually see. + """ + schema = self.get_schema() + return list(zip(schema.names, map(str, schema.types))) + + def validate(self, config: RepoConfig): + schema = self.get_schema() + if self.timestamp_field and self.timestamp_field not in schema.names: + raise ValueError( + f"Timestamp field '{self.timestamp_field}' is not present in Lance " + f"dataset '{self.name}' at {self.pin_description}. " + f"Available columns: {sorted(schema.names)}." + ) + + def get_table_query_string(self) -> str: + raise NotImplementedError( + "LanceSource is read through PyArrow, not SQL. It is supported by " + "offline stores that can accept an Arrow table." + ) + + def _to_proto_impl(self) -> DataSourceProto: + config_json = json.dumps( + { + "uri": self.uri, + "table": self.lance_table, + "namespace_impl": self.namespace_impl, + "namespace_properties": self.namespace_properties, + "storage_options": self.storage_options, + "table_format": self.table_format.to_dict(), + } + ) + return DataSourceProto( + name=self.name, + type=DataSourceProto.CUSTOM_SOURCE, + data_source_class_type=_CLASS_TYPE, + custom_options=DataSourceProto.CustomSourceOptions( + configuration=bytes(config_json, encoding="utf8") + ), + description=self.description, + tags=self.tags, + owner=self.owner, + timestamp_field=self.timestamp_field, + created_timestamp_column=self.created_timestamp_column, + field_mapping=self.field_mapping, + ) + + @staticmethod + def from_proto(data_source: DataSourceProto) -> Any: + assert data_source.HasField("custom_options") + config = json.loads( + str(data_source.custom_options.configuration, encoding="utf8") + ) + table_format_dict = config.get("table_format") or {} + table_format = ( + LanceFormat.from_dict(table_format_dict) if table_format_dict else None + ) + tags = dict(data_source.tags) + return LanceSource( + name=data_source.name, + uri=config.get("uri") or None, + table=config.get("table") or None, + table_format=table_format, + namespace_impl=config.get("namespace_impl") or None, + namespace_properties=config.get("namespace_properties") or None, + storage_options=config.get("storage_options") or None, + timestamp_field=data_source.timestamp_field, + created_timestamp_column=data_source.created_timestamp_column, + field_mapping=dict(data_source.field_mapping), + description=data_source.description, + tags=tags, + owner=data_source.owner, + ) + + +def _declared_columns(feature_view: "FeatureView") -> List[str]: + """Columns a feature view's declared schema requires from its source.""" + source = feature_view.batch_source + reverse_mapping = ( + {v: k for k, v in source.field_mapping.items()} if source is not None else {} + ) + + required: List[str] = [] + for field in feature_view.schema: + required.append(reverse_mapping.get(field.name, field.name)) + for entity_column in feature_view.entity_columns: + required.append(reverse_mapping.get(entity_column.name, entity_column.name)) + if source is not None: + if source.timestamp_field: + required.append(source.timestamp_field) + if source.created_timestamp_column: + required.append(source.created_timestamp_column) + + seen = set() + ordered = [] + for column in required: + if column not in seen: + seen.add(column) + ordered.append(column) + return ordered + + +def _validate_against_feature_view( + source: LanceSource, + schema: "pyarrow.Schema", + feature_view: "FeatureView", +) -> None: + """Fail if the pinned schema cannot satisfy the declared schema. + + A pin selects data, never shape. If a pinned version is missing a column the + declared ``FeatureView`` asks for, the honest outcome is an error naming the + pin, not a narrower result set. + """ + available = set(schema.names) + missing = [c for c in _declared_columns(feature_view) if c not in available] + if missing: + raise ValueError( + f"Lance dataset '{source.name}' at {source.pin_description} is missing " + f"column(s) {missing} required by the declared schema of feature view " + f"'{feature_view.name}'. A pin selects data, not shape: either pin a " + f"version whose schema matches the declared schema, or change the " + f"declared schema. Available columns: {sorted(available)}." + ) + + +def validate_lance_source_schema(feature_view: "FeatureView") -> None: + """Pre-flight check that a feature view's Lance pin agrees with its schema. + + Offline stores call this before building a retrieval plan. It reads only the + pinned dataset's schema, so it costs one metadata round trip and never scans + data. A no-op for feature views that are not Lance-backed. + + Vector widths are checked through ``_validate_vector_field_lengths``, the + validator added in #6909, rather than through a second implementation. Lance + stores vectors as ``fixed_size_list``, for which that validator's check is a + property of the Arrow type and so is exact on a zero-row table. + """ + source = getattr(feature_view, "batch_source", None) + if not isinstance(source, LanceSource): + return + + schema = source.get_schema() + _validate_against_feature_view(source, schema, feature_view) + + from feast.utils import _validate_vector_field_lengths + + _validate_vector_field_lengths(schema.empty_table(), feature_view) diff --git a/sdk/python/feast/infra/offline_stores/duckdb.py b/sdk/python/feast/infra/offline_stores/duckdb.py index 73dd9dd60af..46ca7723f69 100644 --- a/sdk/python/feast/infra/offline_stores/duckdb.py +++ b/sdk/python/feast/infra/offline_stores/duckdb.py @@ -10,6 +10,7 @@ from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source import ( IcebergSource, ) + from feast.infra.data_sources.contrib.lance.lance_source import LanceSource from feast.infra.data_sources.mlflow.mlflow_dataset_source import ( MlflowDatasetSource, ) @@ -60,6 +61,20 @@ def _read_data_source(data_source: DataSource, repo_path: str) -> Table: if isinstance(data_source, IcebergSource): return _read_iceberg_catalog_source(data_source, repo_path) + lance_source: Optional["LanceSource"] = None + try: + from feast.infra.data_sources.contrib.lance.lance_source import LanceSource + + if isinstance(data_source, LanceSource): + lance_source = data_source + except ImportError: + pass + # Deliberately outside the try: an ImportError raised by the read itself (a + # missing pylance, say) must surface rather than fall through to the + # FileSource assert below and be reported as the wrong source type. + if lance_source is not None: + return _read_lance_source(lance_source) + try: from feast.infra.data_sources.mlflow.mlflow_dataset_source import ( MlflowDatasetSource, @@ -197,6 +212,35 @@ def _read_mlflow_source(data_source: "MlflowDatasetSource") -> Table: return ibis.memtable(arrow_table) +def _read_lance_source(data_source: "LanceSource") -> Table: + """Read a Lance dataset without Spark. + + ``LanceSource`` resolves either a uri or a ``namespace_client`` + ``table_id`` + and applies the ``version``/``tag`` pin from its ``LanceFormat``, so the pin + is honoured before any data crosses into ibis. The declared-schema contract + is enforced separately, by ``validate_lance_source_schema``, because the + reader callback is handed a ``DataSource`` without its feature view. + """ + return ibis.memtable(data_source.to_arrow()) + + +def _validate_lance_feature_views(feature_views: List[FeatureView]) -> None: + """Enforce the Lance pin contract on every Lance-backed feature view. + + Runs before a retrieval plan is built. It reads schemas only, so a mismatch + is reported up front instead of surfacing as a short or mis-shaped result. + """ + try: + from feast.infra.data_sources.contrib.lance.lance_source import ( + validate_lance_source_schema, + ) + except ImportError: + return + + for feature_view in feature_views: + validate_lance_source_schema(feature_view) + + def _write_data_source( table: Table, data_source: DataSource, @@ -640,6 +684,9 @@ def get_historical_features( full_feature_names: bool = False, filter_by_created_timestamp: bool = False, ) -> RetrievalJob: + # A Lance pin selects data, never shape: reject a pinned version whose + # schema cannot satisfy the declared schema before planning any reads. + _validate_lance_feature_views(feature_views) return get_historical_features_ibis( config=config, feature_views=feature_views, diff --git a/sdk/python/tests/unit/infra/data_sources/test_lance_source.py b/sdk/python/tests/unit/infra/data_sources/test_lance_source.py new file mode 100644 index 00000000000..a720d85e178 --- /dev/null +++ b/sdk/python/tests/unit/infra/data_sources/test_lance_source.py @@ -0,0 +1,755 @@ +# Copyright 2026 The Feast Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the non-JVM Lance read path. + +Every catalog-based test uses the ``dir`` Lance namespace implementation, which +is a local-filesystem namespace. It drives the identical ``namespace_client`` + +``table_id`` code path as a remote catalog, so no server is needed. +""" + +from datetime import datetime, timedelta +from unittest.mock import MagicMock + +import pyarrow as pa +import pytest + +from feast.credentials import ConnectionRef +from feast.entity import Entity +from feast.feature_view import FeatureView +from feast.field import Field +from feast.infra.offline_stores.duckdb import ( + DuckDBOfflineStore, + DuckDBOfflineStoreConfig, +) +from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto +from feast.repo_config import RepoConfig +from feast.table_format import LanceFormat, TableFormatType +from feast.types import Array, Float32, Int64, String + +lance = pytest.importorskip("lance") +lance_namespace = pytest.importorskip("lance_namespace") + +from feast.infra.data_sources.contrib.lance.lance_source import ( # noqa: E402 + LanceSource, + validate_lance_source_schema, +) + +# --------------------------------------------------------------------- helpers + + +def _write(uri_or_ns, table, mode="create", table_id=None): + if table_id is None: + return lance.write_dataset(table, uri_or_ns, mode=mode) + return lance.write_dataset( + table, namespace_client=uri_or_ns, table_id=table_id, mode=mode + ) + + +@pytest.fixture +def dir_namespace(tmp_path): + """A local-filesystem Lance namespace, standing in for a remote catalog. + + Returns a ``(client, properties)`` pair: the client is used to write the + fixture data, and the properties are what a ``LanceSource`` is configured + with so that it connects for itself. + """ + root = tmp_path / "warehouse" + root.mkdir() + properties = {"root": str(root)} + return lance_namespace.connect("dir", dict(properties)), properties + + +def _driver_stats(n_rows=3, base_hour=10, conv_rate_offset=0.0): + return pa.table( + { + "driver_id": pa.array([1000 + i for i in range(n_rows)], pa.int64()), + "conv_rate": pa.array( + [0.1 * (i + 1) + conv_rate_offset for i in range(n_rows)], pa.float32() + ), + "event_timestamp": pa.array( + [datetime(2026, 1, 1, base_hour, i) for i in range(n_rows)], + pa.timestamp("us"), + ), + } + ) + + +def _feature_view(source, schema=None, name="driver_stats", ttl=timedelta(days=365)): + fv = FeatureView( + name=name, + entities=[Entity(name="driver", join_keys=["driver_id"])], + schema=schema + if schema is not None + else [Field(name="conv_rate", dtype=Float32)], + source=source, + ttl=ttl, + ) + # ``feast apply`` infers these; set them directly so the test needs no registry. + fv.entity_columns = [Field(name="driver_id", dtype=Int64)] + return fv + + +def _repo_config(tmp_path): + return RepoConfig( + project="lance_test", + registry=str(tmp_path / "registry.db"), + provider="local", + offline_store=DuckDBOfflineStoreConfig(), + entity_key_serialization_version=3, + ) + + +# ------------------------------------------------------- construction contract + + +def test_requires_an_address(): + with pytest.raises(ValueError, match="requires either uri .* or table"): + LanceSource() + + +def test_rejects_both_uri_and_table(): + with pytest.raises(ValueError, match="either uri or table, not both"): + LanceSource(uri="/tmp/x.lance", table="t", namespace_impl="dir") + + +def test_table_requires_a_namespace_impl(): + with pytest.raises(ValueError, match="requires namespace_impl"): + LanceSource(table="t") + + +def test_rejects_a_non_lance_table_format(): + from feast.table_format import IcebergFormat + + with pytest.raises(ValueError, match="requires a LanceFormat"): + LanceSource(uri="/tmp/x.lance", table_format=IcebergFormat()) + + +def test_rejects_an_unimplemented_connection_ref(): + with pytest.raises(TypeError, match="unexpected keyword argument 'connection_ref'"): + LanceSource( + uri="s3://bucket/emb.lance", + connection_ref=ConnectionRef(provider="env", name="LANCE"), + ) + + +def test_default_name_is_the_uri_for_a_path_based_source(): + assert LanceSource(uri="/tmp/x.lance").name == "/tmp/x.lance" + + +def test_default_name_is_the_fqn_for_a_catalog_based_source(): + source = LanceSource( + table="emb", + namespace_impl="dir", + table_format=LanceFormat(catalog="cat", namespace="ns"), + ) + assert source.name == "cat.ns.emb" + + +def test_table_id_splits_a_hierarchical_namespace(): + source = LanceSource( + table="emb", + namespace_impl="rest", + table_format=LanceFormat(namespace="a.b"), + ) + assert source.table_id == ["a", "b", "emb"] + + +def test_table_id_is_flat_without_a_namespace(): + source = LanceSource(table="emb", namespace_impl="dir") + assert source.table_id == ["emb"] + + +def test_table_id_is_unavailable_for_a_path_based_source(): + with pytest.raises(ValueError, match="path-based and has no table_id"): + _ = LanceSource(uri="/tmp/x.lance").table_id + + +# -------------------------------------------------------------- pin accessors + + +def test_pin_is_none_when_unpinned(): + source = LanceSource(uri="/tmp/x.lance") + assert source.pin is None + assert source.pin_description == "latest version" + + +def test_pin_is_the_int_version_when_pinned_by_version(): + source = LanceSource(uri="/tmp/x.lance", table_format=LanceFormat(version=2)) + assert source.pin == 2 + assert source.pin_description == "version 2" + + +def test_pin_is_the_tag_name_when_pinned_by_tag(): + # Lance accepts an int version or a tag name in the same ``version=`` arg. + source = LanceSource(uri="/tmp/x.lance", table_format=LanceFormat(tag="candidate")) + assert source.pin == "candidate" + assert source.pin_description == "tag 'candidate'" + + +# ------------------------------------------------------------- proto roundtrip + + +def test_proto_roundtrip_path_based(): + source = LanceSource( + uri="s3://bucket/emb.lance", + table_format=LanceFormat(version=4), + storage_options={"aws_region": "us-west-2"}, + timestamp_field="event_timestamp", + created_timestamp_column="created_ts", + field_mapping={"src": "dst"}, + description="d", + tags={"t": "v"}, + owner="o", + ) + restored = LanceSource.from_proto(source.to_proto()) + assert restored == source + assert restored.uri == "s3://bucket/emb.lance" + assert restored.storage_options == {"aws_region": "us-west-2"} + assert restored.table_format.version == 4 + assert restored.table_format.format_type == TableFormatType.LANCE + + +def test_proto_roundtrip_catalog_based(): + source = LanceSource( + table="emb", + namespace_impl="dir", + namespace_properties={"root": "/warehouse"}, + table_format=LanceFormat(catalog="cat", namespace="ns", tag="eval"), + timestamp_field="event_timestamp", + ) + restored = LanceSource.from_proto(source.to_proto()) + assert restored == source + assert restored.table_id == ["ns", "emb"] + assert restored.pin == "eval" + assert restored.namespace_properties == {"root": "/warehouse"} + + +def test_proto_uses_custom_source_so_no_registry_edit_is_needed(): + proto = LanceSource(uri="/tmp/x.lance").to_proto() + assert proto.type == DataSourceProto.CUSTOM_SOURCE + assert proto.data_source_class_type.endswith("lance_source.LanceSource") + + +def test_generic_data_source_from_proto_dispatches_to_lance_source(): + from feast.data_source import DataSource + + source = LanceSource(uri="/tmp/x.lance", timestamp_field="event_timestamp") + restored = DataSource.from_proto(source.to_proto()) + assert isinstance(restored, LanceSource) + assert restored == source + + +# ----------------------------------------------------- layer 1: path-based read + + +def test_path_based_read(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats()) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + assert source.to_arrow().num_rows == 3 + + +def test_path_based_read_projects_columns(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats()) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + assert source.to_arrow(columns=["driver_id"]).column_names == ["driver_id"] + + +def test_projection_validates_the_full_source_schema(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats()) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + feature_view = _feature_view(source) + + table = source.to_arrow(columns=["driver_id"], feature_view=feature_view) + + assert table.column_names == ["driver_id"] + + +def test_path_based_schema_inference(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats()) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + names_and_types = dict(source.get_table_column_names_and_types(MagicMock())) + assert names_and_types["driver_id"] == "int64" + assert names_and_types["conv_rate"] == "float" + + +def test_source_datatype_decoder_is_the_arrow_decoder(): + from feast.type_map import pa_to_feast_value_type + from feast.value_type import ValueType + + decoder = LanceSource.source_datatype_to_feast_value_type() + assert decoder is pa_to_feast_value_type + assert decoder("int64") == ValueType.INT64 + + +def test_validate_rejects_a_missing_timestamp_field(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats()) + source = LanceSource(uri=uri, timestamp_field="nope") + with pytest.raises(ValueError, match="Timestamp field 'nope' is not present"): + source.validate(MagicMock()) + + +def test_get_table_query_string_is_unsupported(tmp_path): + with pytest.raises(NotImplementedError, match="read through PyArrow, not SQL"): + LanceSource(uri="/tmp/x.lance").get_table_query_string() + + +# -------------------------------------------------- layer 2: catalog-based read + + +def test_catalog_based_read(dir_namespace): + client, properties = dir_namespace + _write(client, _driver_stats(), mode="create", table_id=["emb"]) + source = LanceSource( + table="emb", + namespace_impl="dir", + namespace_properties=properties, + timestamp_field="event_timestamp", + ) + assert source.to_arrow().num_rows == 3 + + +def test_catalog_based_read_without_a_server_uses_a_namespace_client(dir_namespace): + client, properties = dir_namespace + _write(client, _driver_stats(), mode="create", table_id=["emb"]) + source = LanceSource( + table="emb", + namespace_impl="dir", + namespace_properties=properties, + ) + # The source connects for itself, through the same namespace_client code + # path a remote catalog would use. + assert isinstance(source.get_namespace_client(), type(client)) + assert source.is_catalog_based is True + + +# ----------------------------------------------- the pin actually selects data + + +def _two_versions(dir_namespace): + """Write v1, tag it, then append v2. Returns the dir-namespace properties.""" + client, properties = dir_namespace + ds = _write(client, _driver_stats(n_rows=2), mode="create", table_id=["emb"]) + assert ds.version == 1 + ds.tags.create("eval_set", 1) + ds2 = _write( + client, + _driver_stats(n_rows=2, base_hour=12, conv_rate_offset=10.0), + mode="append", + table_id=["emb"], + ) + assert ds2.version == 2 + return properties + + +def test_a_tag_pin_changes_what_is_read(dir_namespace): + """Write two versions, tag the first, show the pinned read sees the earlier data.""" + props = _two_versions(dir_namespace) + + def source(table_format): + return LanceSource( + table="emb", + namespace_impl="dir", + namespace_properties=props, + table_format=table_format, + ) + + latest = source(LanceFormat()).to_arrow() + pinned = source(LanceFormat(tag="eval_set")).to_arrow() + + # v1 had 2 rows; the append brought the latest to 4. + assert latest.num_rows == 4 + assert pinned.num_rows == 2 + # And the pinned read sees the *original* values, not the appended ones. + assert pinned.column("conv_rate").to_pylist() == pytest.approx([0.1, 0.2]) + assert max(latest.column("conv_rate").to_pylist()) == pytest.approx(10.2) + + +def test_a_version_pin_changes_what_is_read(dir_namespace): + props = _two_versions(dir_namespace) + pinned = LanceSource( + table="emb", + namespace_impl="dir", + namespace_properties=props, + table_format=LanceFormat(version=1), + ).to_arrow() + assert pinned.num_rows == 2 + + +def test_a_tag_pin_and_the_version_it_names_read_identically(dir_namespace): + props = _two_versions(dir_namespace) + + def read(table_format): + return LanceSource( + table="emb", + namespace_impl="dir", + namespace_properties=props, + table_format=table_format, + ).to_arrow() + + assert read(LanceFormat(tag="eval_set")) == read(LanceFormat(version=1)) + + +def test_a_path_based_tag_pin_changes_what_is_read(tmp_path): + uri = str(tmp_path / "emb.lance") + ds = _write(uri, _driver_stats(n_rows=2)) + ds.tags.create("eval_set", 1) + _write(uri, _driver_stats(n_rows=2, base_hour=12), mode="append") + + assert LanceSource(uri=uri).to_arrow().num_rows == 4 + pinned = LanceSource(uri=uri, table_format=LanceFormat(tag="eval_set")).to_arrow() + assert pinned.num_rows == 2 + + +def test_schema_inference_reflects_the_pin_not_the_latest_version(tmp_path): + """``feast apply`` must infer the schema a pinned read will actually see.""" + uri = str(tmp_path / "emb.lance") + ds = _write(uri, _driver_stats(n_rows=2)) + ds.tags.create("narrow", 1) + wider = _driver_stats(n_rows=2).append_column("extra", pa.array([1, 2], pa.int64())) + _write(uri, wider, mode="overwrite") + + latest = dict(LanceSource(uri=uri).get_table_column_names_and_types(MagicMock())) + pinned = dict( + LanceSource( + uri=uri, table_format=LanceFormat(tag="narrow") + ).get_table_column_names_and_types(MagicMock()) + ) + assert "extra" in latest + assert "extra" not in pinned + + +# ----------------------------------- a pin selects data, never shape (contract) + + +def test_a_pin_missing_a_declared_column_fails_explicitly(tmp_path): + uri = str(tmp_path / "emb.lance") + ds = _write(uri, _driver_stats(n_rows=2)) + ds.tags.create("narrow", 1) + wider = _driver_stats(n_rows=2).append_column( + "acc_rate", pa.array([0.5, 0.6], pa.float32()) + ) + _write(uri, wider, mode="overwrite") + + # The declared schema asks for acc_rate, which only the latest version has. + fv = _feature_view( + LanceSource( + uri=uri, + table_format=LanceFormat(tag="narrow"), + timestamp_field="event_timestamp", + ), + schema=[ + Field(name="conv_rate", dtype=Float32), + Field(name="acc_rate", dtype=Float32), + ], + ) + with pytest.raises(ValueError) as err: + validate_lance_source_schema(fv) + message = str(err.value) + assert "acc_rate" in message + assert "tag 'narrow'" in message + assert "A pin selects data, not shape" in message + + +def test_an_unpinned_source_satisfying_the_declared_schema_validates(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats()) + fv = _feature_view(LanceSource(uri=uri, timestamp_field="event_timestamp")) + validate_lance_source_schema(fv) # does not raise + + +def test_validation_honours_field_mapping(tmp_path): + """A declared name that is mapped from a source column must not be reported missing.""" + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats()) + source = LanceSource( + uri=uri, + timestamp_field="event_timestamp", + field_mapping={"conv_rate": "conversion_rate"}, + ) + fv = _feature_view(source, schema=[Field(name="conversion_rate", dtype=Float32)]) + validate_lance_source_schema(fv) # does not raise + + +def test_validation_is_a_noop_for_a_non_lance_source(tmp_path): + from feast.infra.offline_stores.file_source import FileSource + + fv = _feature_view( + FileSource(path=str(tmp_path / "x.parquet"), timestamp_field="event_timestamp") + ) + validate_lance_source_schema(fv) # does not raise, and reads nothing + + +def _vector_table(width, declared_timestamp=True): + cols = { + "item_id": pa.array([1, 2], pa.int64()), + "embedding": pa.FixedSizeListArray.from_arrays( + pa.array([0.0] * (2 * width), pa.float32()), width + ), + } + if declared_timestamp: + cols["event_timestamp"] = pa.array( + [datetime(2026, 1, 1, 10), datetime(2026, 1, 1, 11)], pa.timestamp("us") + ) + return pa.table(cols) + + +def _vector_feature_view(source, declared_width): + fv = FeatureView( + name="item_emb", + entities=[Entity(name="item", join_keys=["item_id"])], + schema=[ + Field( + name="embedding", + dtype=Array(Float32), + vector_index=True, + vector_length=declared_width, + ) + ], + source=source, + ttl=timedelta(days=365), + ) + fv.entity_columns = [Field(name="item_id", dtype=Int64)] + return fv + + +def test_a_pin_with_a_different_vector_width_fails_explicitly(tmp_path): + """The reused #6909 validator rejects a pinned width that is not the declared one.""" + uri = str(tmp_path / "emb.lance") + ds = _write(uri, _vector_table(width=4)) + ds.tags.create("narrow", 1) + _write(uri, _vector_table(width=8), mode="overwrite") + + pinned = LanceSource( + uri=uri, + table_format=LanceFormat(tag="narrow"), + timestamp_field="event_timestamp", + ) + # Declared width 8 matches the latest version but not the pinned one. + with pytest.raises(ValueError, match="Vector length 4 does not match expected 8"): + validate_lance_source_schema(_vector_feature_view(pinned, declared_width=8)) + + # The same pin with the matching declared width is fine. + validate_lance_source_schema(_vector_feature_view(pinned, declared_width=4)) + + +def test_to_arrow_enforces_the_declared_schema_when_given_a_feature_view(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _vector_table(width=4)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + with pytest.raises(ValueError, match="Vector length 4 does not match expected 8"): + source.to_arrow(feature_view=_vector_feature_view(source, declared_width=8)) + + +# --------------------------------------------- DuckDB offline store integration + + +def test_duckdb_reader_dispatches_to_the_lance_reader(tmp_path): + from feast.infra.offline_stores.duckdb import _read_data_source + + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats()) + table = _read_data_source( + LanceSource(uri=uri, timestamp_field="event_timestamp"), str(tmp_path) + ) + assert sorted(table.columns) == ["conv_rate", "driver_id", "event_timestamp"] + assert table.to_pyarrow().num_rows == 3 + + +def test_pull_latest_from_a_lance_source(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _driver_stats(n_rows=3)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + job = DuckDBOfflineStore.pull_latest_from_table_or_query( + config=_repo_config(tmp_path), + data_source=source, + join_key_columns=["driver_id"], + feature_name_columns=["conv_rate"], + timestamp_field="event_timestamp", + created_timestamp_column=None, + start_date=datetime(2026, 1, 1), + end_date=datetime(2026, 1, 2), + ) + assert job.to_arrow().num_rows == 3 + + +def _pit_fixture(tmp_path, namespace=None): + """One driver with two feature rows, an hour apart. + + An entity query at 11:30 must see the 11:00 row, never the 12:00 one. + """ + rows = pa.table( + { + "driver_id": pa.array([1000, 1000], pa.int64()), + "conv_rate": pa.array([0.5, 0.9], pa.float32()), + "event_timestamp": pa.array( + [datetime(2026, 1, 1, 11), datetime(2026, 1, 1, 12)], + pa.timestamp("us"), + ), + } + ) + if namespace is not None: + client, properties = namespace + _write(client, rows, mode="create", table_id=["stats"]) + return LanceSource( + table="stats", + namespace_impl="dir", + namespace_properties=properties, + timestamp_field="event_timestamp", + ) + uri = str(tmp_path / "stats.lance") + _write(uri, rows) + return LanceSource(uri=uri, timestamp_field="event_timestamp") + + +def _historical(tmp_path, source, entity_hour=11, minute=30): + import pandas as pd + + entity_df = pd.DataFrame( + { + "driver_id": [1000], + "event_timestamp": [datetime(2026, 1, 1, entity_hour, minute)], + } + ) + return DuckDBOfflineStore.get_historical_features( + config=_repo_config(tmp_path), + feature_views=[_feature_view(source)], + feature_refs=["driver_stats:conv_rate"], + entity_df=entity_df, + registry=MagicMock(), + project="lance_test", + ).to_df() + + +def test_get_historical_features_is_point_in_time_correct_path_based(tmp_path): + df = _historical(tmp_path, _pit_fixture(tmp_path)) + assert len(df) == 1 + # 0.5 is the 11:00 row. 0.9 is the 12:00 row, which is in the future. + assert df["conv_rate"].iloc[0] == pytest.approx(0.5) + + +def test_get_historical_features_is_point_in_time_correct_catalog_based( + tmp_path, dir_namespace +): + df = _historical(tmp_path, _pit_fixture(tmp_path, namespace=dir_namespace)) + assert len(df) == 1 + assert df["conv_rate"].iloc[0] == pytest.approx(0.5) + + +def test_get_historical_features_picks_the_later_row_for_a_later_entity_query(tmp_path): + df = _historical(tmp_path, _pit_fixture(tmp_path), entity_hour=13) + assert df["conv_rate"].iloc[0] == pytest.approx(0.9) + + +def test_get_historical_features_honours_a_tag_pin(tmp_path): + """The motivating case: a tagged eval set retrieves the data it was built from.""" + uri = str(tmp_path / "stats.lance") + v1 = pa.table( + { + "driver_id": pa.array([1000], pa.int64()), + "conv_rate": pa.array([0.5], pa.float32()), + "event_timestamp": pa.array([datetime(2026, 1, 1, 11)], pa.timestamp("us")), + } + ) + ds = _write(uri, v1) + ds.tags.create("eval_set", 1) + # A later, *corrected* value for the very same (entity, timestamp). + v2 = pa.table( + { + "driver_id": pa.array([1000], pa.int64()), + "conv_rate": pa.array([0.77], pa.float32()), + "event_timestamp": pa.array([datetime(2026, 1, 1, 11)], pa.timestamp("us")), + } + ) + _write(uri, v2, mode="overwrite") + + latest = _historical( + tmp_path, LanceSource(uri=uri, timestamp_field="event_timestamp") + ) + pinned = _historical( + tmp_path, + LanceSource( + uri=uri, + table_format=LanceFormat(tag="eval_set"), + timestamp_field="event_timestamp", + ), + ) + assert latest["conv_rate"].iloc[0] == pytest.approx(0.77) + assert pinned["conv_rate"].iloc[0] == pytest.approx(0.5) + + +def test_get_historical_features_rejects_a_pin_that_breaks_the_declared_schema( + tmp_path, +): + uri = str(tmp_path / "stats.lance") + ds = _write(uri, _driver_stats(n_rows=2)) + ds.tags.create("narrow", 1) + _write( + uri, + _driver_stats(n_rows=2).append_column( + "acc_rate", pa.array([0.5, 0.6], pa.float32()) + ), + mode="overwrite", + ) + source = LanceSource( + uri=uri, + table_format=LanceFormat(tag="narrow"), + timestamp_field="event_timestamp", + ) + fv = _feature_view( + source, + schema=[ + Field(name="conv_rate", dtype=Float32), + Field(name="acc_rate", dtype=Float32), + ], + ) + import pandas as pd + + with pytest.raises(ValueError, match="A pin selects data, not shape"): + DuckDBOfflineStore.get_historical_features( + config=_repo_config(tmp_path), + feature_views=[fv], + feature_refs=["driver_stats:conv_rate", "driver_stats:acc_rate"], + entity_df=pd.DataFrame( + {"driver_id": [1000], "event_timestamp": [datetime(2026, 1, 1, 13)]} + ), + registry=MagicMock(), + project="lance_test", + ) + + +def test_a_string_column_survives_the_round_trip(tmp_path): + """Lance keeps vectors and scalars in one dataset; check a non-numeric scalar.""" + uri = str(tmp_path / "emb.lance") + _write( + uri, + pa.table( + { + "driver_id": pa.array([1000], pa.int64()), + "city": pa.array(["cupertino"], pa.string()), + "event_timestamp": pa.array( + [datetime(2026, 1, 1, 11)], pa.timestamp("us") + ), + } + ), + ) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + fv = _feature_view(source, schema=[Field(name="city", dtype=String)]) + validate_lance_source_schema(fv) + assert source.to_arrow().column("city").to_pylist() == ["cupertino"]