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 index b9aff161802..726fef55579 100644 --- a/sdk/python/feast/infra/data_sources/contrib/lance/lance_source.py +++ b/sdk/python/feast/infra/data_sources/contrib/lance/lance_source.py @@ -33,7 +33,11 @@ from feast.data_source import DataSource from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto +from feast.protos.feast.core.SavedDataset_pb2 import ( + SavedDatasetStorage as SavedDatasetStorageProto, +) from feast.repo_config import RepoConfig +from feast.saved_dataset import SavedDatasetStorage from feast.table_format import LanceFormat from feast.type_map import pa_to_feast_value_type from feast.value_type import ValueType @@ -590,3 +594,124 @@ def validate_lance_write_shape( f"whose vectors cannot be compared with each other. Write the re-embedded " f"data to a new dataset instead of overwriting this one." ) + + +class SavedDatasetLanceStorage(SavedDatasetStorage): + """Records an existing Lance dataset as a saved dataset. + + This is the registry entry for "a dataset I produced, at this version, with + these properties". The data is not moved or rewritten: the storage holds the + address, and :meth:`BaseRegistry.apply_saved_dataset` records it as metadata. + That is the path for a dataset built outside Feast, by a Ray or Spark job, + which ``FeatureStore.create_saved_dataset`` cannot serve because it executes + a ``RetrievalJob`` and persists its result. + + The format must pin a version or a tag. A saved dataset addressing the latest + version is a contradiction: the rows it refers to change under it, so any + measurement recorded against it stops being attributable. Prefer ``version`` + over ``tag``, because a tag can be moved to another version afterwards while + a version number cannot. + """ + + _proto_attr_name = "custom_storage" + + def __init__( + self, + table_format: LanceFormat, + *, + uri: Optional[str] = None, + table: Optional[str] = None, + namespace_impl: Optional[str] = None, + namespace_properties: Optional[Dict[str, str]] = None, + storage_options: Optional[Dict[str, str]] = None, + ): + if not isinstance(table_format, LanceFormat): + raise ValueError( + f"SavedDatasetLanceStorage requires a LanceFormat, got " + f"{type(table_format).__name__}." + ) + if not table_format.is_pinned: + raise ValueError( + "SavedDatasetLanceStorage requires LanceFormat to pin a version " + "or a tag. Without a pin the saved dataset addresses whatever " + "version is latest at read time, so it does not identify the " + "rows it was created from." + ) + if bool(uri) == bool(table): + raise ValueError( + "SavedDatasetLanceStorage takes either uri or table, not both " + "and not neither. A uri addresses the dataset directly; a table " + "addresses it through a namespace." + ) + if table and not namespace_impl: + raise ValueError( + "SavedDatasetLanceStorage with a table requires namespace_impl, " + "the same as LanceSource." + ) + + self.table_format = table_format + 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 from_proto(storage_proto: SavedDatasetStorageProto) -> SavedDatasetStorage: + config = json.loads( + str(storage_proto.custom_storage.configuration, encoding="utf8") + ) + return SavedDatasetLanceStorage( + LanceFormat.from_dict(config.get("table_format") or {}), + uri=config.get("uri"), + table=config.get("table"), + namespace_impl=config.get("namespace_impl"), + namespace_properties=config.get("namespace_properties"), + storage_options=config.get("storage_options"), + ) + + def to_proto(self) -> SavedDatasetStorageProto: + 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(), + } + ) + # Routed through the base class so the writing class is recorded in the + # payload. Several storage classes share the custom_storage field, and + # without that record from_proto resolves by import order. + return self._custom_storage_proto( + DataSourceProto.CustomSourceOptions( + configuration=bytes(config_json, encoding="utf8") + ) + ) + + def to_data_source(self) -> DataSource: + return LanceSource( + uri=self.uri, + table=self.lance_table, + table_format=self.table_format, + namespace_impl=self.namespace_impl, + namespace_properties=self.namespace_properties, + storage_options=self.storage_options, + ) + + @staticmethod + def from_data_source(data_source: DataSource) -> SavedDatasetStorage: + if not isinstance(data_source, LanceSource): + raise ValueError( + f"SavedDatasetLanceStorage.from_data_source requires a " + f"LanceSource, got {type(data_source).__name__}." + ) + return SavedDatasetLanceStorage( + data_source.table_format, + uri=data_source.uri, + table=data_source.lance_table, + namespace_impl=data_source.namespace_impl, + namespace_properties=data_source.namespace_properties, + storage_options=data_source.storage_options, + ) diff --git a/sdk/python/feast/saved_dataset.py b/sdk/python/feast/saved_dataset.py index 9a66a9b2d8d..7b62cdeaaf0 100644 --- a/sdk/python/feast/saved_dataset.py +++ b/sdk/python/feast/saved_dataset.py @@ -86,6 +86,7 @@ def _read_custom_storage_class( _DATA_SOURCE_TO_SAVED_DATASET_STORAGE = { "FileSource": "feast.infra.offline_stores.file_source.SavedDatasetFileStorage", "SparkSource": "feast.infra.offline_stores.contrib.spark_offline_store.spark_source.SavedDatasetSparkStorage", + "LanceSource": "feast.infra.data_sources.contrib.lance.lance_source.SavedDatasetLanceStorage", } diff --git a/sdk/python/tests/unit/infra/data_sources/test_saved_dataset_lance_storage.py b/sdk/python/tests/unit/infra/data_sources/test_saved_dataset_lance_storage.py new file mode 100644 index 00000000000..af7853f8438 --- /dev/null +++ b/sdk/python/tests/unit/infra/data_sources/test_saved_dataset_lance_storage.py @@ -0,0 +1,163 @@ +import json + +import pytest + +from feast.data_source import DataSource +from feast.saved_dataset import ( + _DATA_SOURCE_TO_SAVED_DATASET_STORAGE, + SavedDatasetStorage, +) +from feast.table_format import LanceFormat + +lance_source = pytest.importorskip( + "feast.infra.data_sources.contrib.lance.lance_source" +) +LanceSource = lance_source.LanceSource +SavedDatasetLanceStorage = lance_source.SavedDatasetLanceStorage + + +def test_a_pinned_version_round_trips(): + written = SavedDatasetLanceStorage(LanceFormat(version=7), uri="s3://bucket/ds") + + read_back = SavedDatasetLanceStorage.from_proto(written.to_proto()) + + assert isinstance(read_back, SavedDatasetLanceStorage) + assert read_back.table_format.version == 7 + assert read_back.uri == "s3://bucket/ds" + + +def test_a_namespace_addressed_dataset_round_trips(): + written = SavedDatasetLanceStorage( + LanceFormat(tag="candidate"), + table="embeddings", + namespace_impl="dir", + namespace_properties={"root": "/warehouse"}, + ) + + read_back = SavedDatasetLanceStorage.from_proto(written.to_proto()) + + assert read_back.lance_table == "embeddings" + assert read_back.namespace_impl == "dir" + assert read_back.namespace_properties == {"root": "/warehouse"} + assert read_back.table_format.tag == "candidate" + + +def test_the_written_payload_records_the_storage_class(): + """Four classes share custom_storage, so the writer must be recorded.""" + proto = SavedDatasetLanceStorage( + LanceFormat(version=1), uri="s3://bucket/ds" + ).to_proto() + + config = json.loads(proto.custom_storage.configuration.decode("utf8")) + + assert config["saved_dataset_storage_class"].endswith("SavedDatasetLanceStorage") + + +def test_an_unpinned_format_is_refused(): + """A saved dataset addressing 'latest' does not identify its own rows.""" + with pytest.raises(ValueError) as error: + SavedDatasetLanceStorage(LanceFormat(), uri="s3://bucket/ds") + + assert "pin a version" in str(error.value) + + +def test_a_format_of_the_wrong_type_is_refused(): + with pytest.raises(ValueError) as error: + SavedDatasetLanceStorage("not-a-format", uri="s3://bucket/ds") + + assert "requires a LanceFormat" in str(error.value) + + +@pytest.mark.parametrize( + "kwargs", + [ + {}, + {"uri": "s3://bucket/ds", "table": "embeddings"}, + ], + ids=["neither", "both"], +) +def test_uri_and_table_are_exclusive(kwargs): + with pytest.raises(ValueError) as error: + SavedDatasetLanceStorage(LanceFormat(version=1), **kwargs) + + assert "either uri or table" in str(error.value) + + +def test_a_table_without_a_namespace_impl_is_refused(): + with pytest.raises(ValueError) as error: + SavedDatasetLanceStorage(LanceFormat(version=1), table="embeddings") + + assert "requires namespace_impl" in str(error.value) + + +def test_to_data_source_keeps_the_pin(): + storage = SavedDatasetLanceStorage(LanceFormat(version=7), uri="s3://bucket/ds") + + source = storage.to_data_source() + + assert isinstance(source, LanceSource) + assert source.uri == "s3://bucket/ds" + assert source.table_format.version == 7 + + +def test_from_data_source_carries_the_pin_over(): + source = LanceSource(uri="s3://bucket/ds", table_format=LanceFormat(version=7)) + + storage = SavedDatasetLanceStorage.from_data_source(source) + + assert storage.table_format.version == 7 + assert storage.uri == "s3://bucket/ds" + + +def test_from_data_source_refuses_an_unpinned_source(): + """LanceSource defaults to an unpinned LanceFormat, never None.""" + source = LanceSource(uri="s3://bucket/ds") + assert source.table_format is not None + assert not source.table_format.is_pinned + + with pytest.raises(ValueError) as error: + SavedDatasetLanceStorage.from_data_source(source) + + assert "pin a version" in str(error.value) + + +def test_from_data_source_refuses_a_non_lance_source(): + class NotLance(DataSource): + pass + + with pytest.raises(ValueError) as error: + SavedDatasetLanceStorage.from_data_source(NotLance.__new__(NotLance)) + + assert "requires a LanceSource" in str(error.value) + + +def test_lance_source_is_registered_for_dispatch(): + """So SavedDatasetStorage.from_data_source resolves a LanceSource.""" + assert "LanceSource" in _DATA_SOURCE_TO_SAVED_DATASET_STORAGE + + source = LanceSource(uri="s3://bucket/ds", table_format=LanceFormat(version=7)) + storage = SavedDatasetStorage.from_data_source(source) + + assert isinstance(storage, SavedDatasetLanceStorage) + assert storage.table_format.version == 7 + + +def test_dispatch_resolves_lance_among_every_custom_storage_claimant(): + """Lance is the fourth class to claim ``custom_storage``. + + Before the writing class was recorded in the payload, dispatch depended on + which module was imported last. + """ + for module in ( + "feast.infra.offline_stores.contrib.postgres_offline_store.postgres_source", + "feast.infra.offline_stores.contrib.clickhouse_offline_store.clickhouse_source", + "feast.infra.offline_stores.contrib.couchbase_offline_store.couchbase_source", + ): + pytest.importorskip(module) + + written = SavedDatasetLanceStorage(LanceFormat(version=7), uri="s3://bucket/ds") + + read_back = SavedDatasetStorage.from_proto(written.to_proto()) + + assert type(read_back) is SavedDatasetLanceStorage + assert read_back.table_format.version == 7