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 b31216765db..b9aff161802 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 @@ -289,6 +289,70 @@ def to_arrow( _validate_vector_field_lengths(table, feature_view) return table + # --------------------------------------------------------------- writing + + def get_write_target(self) -> Dict[str, Any]: + """Keyword arguments addressing this source for ``lance.write_dataset``. + + Deliberately omits ``version``. A Lance commit always produces a new + version, so there is no argument that writes *into* an existing one; + ``write_dataset`` has no ``version`` parameter at all. Callers must + reject a pinned source before reaching a write, which + ``assert_writable`` does. + """ + kwargs: Dict[str, Any] = {} + if self.storage_options: + kwargs["storage_options"] = dict(self.storage_options) + + if self.is_catalog_based: + kwargs["namespace_client"] = self.get_namespace_client() + kwargs["table_id"] = self.table_id + else: + kwargs["uri"] = self.uri + return kwargs + + def assert_writable(self) -> None: + """Refuse to write through a pinned source. + + A write commits a new version, which a source pinned to an older version + or to a tag does not read. The write would therefore succeed and then be + invisible through the very source that performed it, so the only honest + outcome is to refuse up front. + """ + if self.pin is None: + return + raise ValueError( + f"LanceSource '{self.name}' is pinned to {self.pin_description} and " + f"cannot be written through. A Lance write commits a new version, so " + f"it would not be visible through this pin. Write through an unpinned " + f"LanceSource addressing the same dataset, then move the tag or re-pin " + f"to the version the write produced." + ) + + def get_existing_schema(self) -> Optional["pyarrow.Schema"]: + """Schema of the dataset this source addresses, or ``None`` if absent. + + Used to choose between creating and appending, and to compare shapes + before handing data to Lance. A failure to open is reported as absent + rather than raised, because the only distinction the caller draws is + whether there is an existing shape to honour. + """ + import lance + + kwargs = self.get_write_target() + try: + if self.is_catalog_based: + return lance.dataset( + namespace_client=kwargs["namespace_client"], + table_id=kwargs["table_id"], + storage_options=kwargs.get("storage_options"), + ).schema + return lance.dataset( + uri=kwargs["uri"], storage_options=kwargs.get("storage_options") + ).schema + except Exception: + return None + # ----------------------------------------------------------- DataSource def source_type(self) -> DataSourceProto.SourceType.ValueType: @@ -469,3 +533,60 @@ def validate_lance_source_schema(feature_view: "FeatureView") -> None: from feast.utils import _validate_vector_field_lengths _validate_vector_field_lengths(schema.empty_table(), feature_view) + + +def _vector_widths(schema: "pyarrow.Schema") -> Dict[str, int]: + """Width of every fixed-width vector column in an Arrow schema.""" + import pyarrow + + widths: Dict[str, int] = {} + for field in schema: + if pyarrow.types.is_fixed_size_list(field.type): + widths[field.name] = field.type.list_size + return widths + + +def validate_lance_write_shape( + table: "pyarrow.Table", + source: LanceSource, + existing_schema: Optional["pyarrow.Schema"], +) -> None: + """Refuse a write that would change an existing vector column's width. + + Lance rejects an ``append`` whose schema disagrees with the dataset, but it + accepts an ``overwrite`` that replaces a vector column with one of a + different width, silently rewriting the declared shape and leaving a version + history whose vectors are not mutually comparable. Every ANN index and every + downstream consumer built against the old width is invalidated by such a + write, and no legitimate schema evolution changes an embedding's dimension, + so this is reported as an error rather than carried out. + + Only vector widths are policed here. Other kinds of type change remain + Lance's business, because for those an ``overwrite`` is a defensible + evolution. + """ + if existing_schema is None: + return + + existing = _vector_widths(existing_schema) + incoming = _vector_widths(table.schema) + + changed = { + name: (existing[name], incoming[name]) + for name in existing.keys() & incoming.keys() + if existing[name] != incoming[name] + } + if not changed: + return + + detail = ", ".join( + f"'{name}' is {was} in the dataset but {now} in the data being written" + for name, (was, now) in sorted(changed.items()) + ) + raise ValueError( + f"Write to Lance dataset '{source.name}' would change the width of " + f"vector column(s): {detail}. A width change invalidates every index and " + f"consumer built against the current width, and leaves a version history " + f"whose vectors cannot be compared with each other. Write the re-embedded " + f"data to a new dataset instead of overwriting this one." + ) diff --git a/sdk/python/feast/infra/offline_stores/duckdb.py b/sdk/python/feast/infra/offline_stores/duckdb.py index 46ca7723f69..8672f965fe6 100644 --- a/sdk/python/feast/infra/offline_stores/duckdb.py +++ b/sdk/python/feast/infra/offline_stores/duckdb.py @@ -53,6 +53,25 @@ from feast.repo_config import FeastConfigBaseModel, RepoConfig +def _as_lance_source(data_source: Optional[DataSource]) -> Optional["LanceSource"]: + """Narrow a DataSource to a LanceSource, or ``None`` if it is not one. + + ``None`` is accepted so that a caller holding an optional source, such as + ``FeatureView.batch_source``, can ask the question without narrowing first. + + The import is guarded because the Lance extra is optional: a repo that does + not install it must still be able to read and write every other source + type. Only the ``isinstance`` check is guarded, never the caller's + subsequent work, so an ImportError raised by a Lance read or write itself + surfaces instead of being mistaken for "not a Lance source". + """ + try: + from feast.infra.data_sources.contrib.lance.lance_source import LanceSource + except ImportError: + return None + return data_source if isinstance(data_source, LanceSource) else None + + def _read_data_source(data_source: DataSource, repo_path: str) -> Table: from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source import ( IcebergSource, @@ -61,17 +80,7 @@ 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. + lance_source = _as_lance_source(data_source) if lance_source is not None: return _read_lance_source(lance_source) @@ -241,6 +250,58 @@ def _validate_lance_feature_views(feature_views: List[FeatureView]) -> None: validate_lance_source_schema(feature_view) +def _write_lance_data_source( + table: Table, + data_source: "LanceSource", + mode: str = "append", + allow_overwrite: bool = False, +) -> None: + """Write an ibis table to a LanceSource without Spark. + + Mirrors ``_read_lance_source``: the source resolves either a uri or a + ``namespace_client`` + ``table_id``, and the same resolution is reused for + the write, so a catalog-addressed dataset is written to the location its + namespace resolves rather than to one assembled here. + + How far the namespace is involved depends on the operation. Creating a table + declares it through the namespace; appending only describes the table to + resolve its location, and the version the append produces is not reported + back. A Lance namespace therefore records that a table exists and where it + lives, and does not track its versions. That is why a pin is a Lance-level + concern that ``assert_writable`` has to enforce here: no catalog is going to + reject the write on the pin's behalf. + + Three things are settled before Lance is called. A pinned source is refused, + because a commit produces a new version that the pin would not read. An + absent dataset is created rather than appended to, since Lance has no + create-or-append mode. An existing dataset's vector widths are compared + against the incoming data, which closes the one case Lance itself permits + silently. + """ + import lance + + from feast.infra.data_sources.contrib.lance.lance_source import ( + validate_lance_write_shape, + ) + + data_source.assert_writable() + + arrow_table = table.to_pyarrow() + existing_schema = data_source.get_existing_schema() + + if existing_schema is None: + lance_mode = "create" + else: + if mode == "overwrite" and not allow_overwrite: + raise SavedDatasetLocationAlreadyExists( + location=data_source.uri or ".".join(data_source.table_id) + ) + validate_lance_write_shape(arrow_table, data_source, existing_schema) + lance_mode = mode + + lance.write_dataset(arrow_table, mode=lance_mode, **data_source.get_write_target()) + + def _write_data_source( table: Table, data_source: DataSource, @@ -256,6 +317,11 @@ def _write_data_source( _write_iceberg_data_source(table, data_source, mode) return + lance_source = _as_lance_source(data_source) + if lance_source is not None: + _write_lance_data_source(table, lance_source, mode, allow_overwrite) + return + assert isinstance(data_source, FileSource) file_options = data_source.file_options @@ -735,6 +801,15 @@ def offline_write_batch( table: pyarrow.Table, progress: Optional[Callable[[int], Any]], ): + # Checked here rather than in the writer callback, which is handed a + # DataSource and so cannot see the declared schema. Creating a Lance + # dataset whose vectors are a different width from the declared + # vector_length would otherwise succeed and fail only on the next read. + if _as_lance_source(feature_view.batch_source) is not None: + from feast.utils import _validate_vector_field_lengths + + _validate_vector_field_lengths(table, feature_view) + offline_write_batch_ibis( config=config, feature_view=feature_view, 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 index a720d85e178..4c68ec8db54 100644 --- a/sdk/python/tests/unit/infra/data_sources/test_lance_source.py +++ b/sdk/python/tests/unit/infra/data_sources/test_lance_source.py @@ -32,6 +32,8 @@ from feast.infra.offline_stores.duckdb import ( DuckDBOfflineStore, DuckDBOfflineStoreConfig, + _read_data_source, + _write_lance_data_source, ) from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto from feast.repo_config import RepoConfig @@ -44,6 +46,7 @@ from feast.infra.data_sources.contrib.lance.lance_source import ( # noqa: E402 LanceSource, validate_lance_source_schema, + validate_lance_write_shape, ) # --------------------------------------------------------------------- helpers @@ -753,3 +756,305 @@ def test_a_string_column_survives_the_round_trip(tmp_path): fv = _feature_view(source, schema=[Field(name="city", dtype=String)]) validate_lance_source_schema(fv) assert source.to_arrow().column("city").to_pylist() == ["cupertino"] + + +# ------------------------------------------------------------- the write path + + +def _ibis_table(arrow_table): + import ibis + + return ibis.memtable(arrow_table) + + +def test_get_existing_schema_is_none_for_an_absent_dataset(tmp_path): + source = LanceSource(uri=str(tmp_path / "absent.lance")) + assert source.get_existing_schema() is None + + +def test_get_write_target_omits_the_version(tmp_path): + """``write_dataset`` has no ``version``; a write always makes a new one.""" + uri = str(tmp_path / "d.lance") + _write(uri, _driver_stats()) + source = LanceSource(uri=uri, table_format=LanceFormat(version=1)) + assert "version" not in source.get_write_target() + + +def test_write_creates_an_absent_path_based_dataset(tmp_path): + uri = str(tmp_path / "new.lance") + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + + _write_lance_data_source(_ibis_table(_driver_stats(n_rows=3)), source) + + assert lance.dataset(uri).count_rows() == 3 + assert lance.dataset(uri).version == 1 + + +def test_write_appends_to_an_existing_path_based_dataset(tmp_path): + uri = str(tmp_path / "d.lance") + _write(uri, _driver_stats(n_rows=3)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + + _write_lance_data_source(_ibis_table(_driver_stats(n_rows=2, base_hour=12)), source) + + dataset = lance.dataset(uri) + assert dataset.count_rows() == 5 + assert dataset.version == 2 + + +def test_write_creates_an_absent_catalog_based_dataset(dir_namespace): + _, properties = dir_namespace + source = LanceSource( + table="brand_new", + namespace_impl="dir", + namespace_properties=properties, + timestamp_field="event_timestamp", + ) + + _write_lance_data_source(_ibis_table(_driver_stats(n_rows=4)), source) + + assert source.to_arrow().num_rows == 4 + + +def test_write_appends_to_an_existing_catalog_based_dataset(dir_namespace): + client, properties = dir_namespace + _write(client, _driver_stats(n_rows=3), table_id=["driver"]) + source = LanceSource( + table="driver", + namespace_impl="dir", + namespace_properties=properties, + timestamp_field="event_timestamp", + ) + + _write_lance_data_source(_ibis_table(_driver_stats(n_rows=2, base_hour=12)), source) + + assert source.to_arrow().num_rows == 5 + + +def test_write_through_a_version_pin_is_refused(tmp_path): + uri = str(tmp_path / "d.lance") + _write(uri, _driver_stats()) + source = LanceSource(uri=uri, table_format=LanceFormat(version=1)) + + with pytest.raises(ValueError, match="pinned to version 1"): + _write_lance_data_source(_ibis_table(_driver_stats()), source) + + +def test_write_through_a_tag_pin_is_refused(tmp_path): + uri = str(tmp_path / "d.lance") + _write(uri, _driver_stats()) + lance.dataset(uri).tags.create("prod", 1) + source = LanceSource(uri=uri, table_format=LanceFormat(tag="prod")) + + with pytest.raises(ValueError, match="pinned to tag 'prod'"): + _write_lance_data_source(_ibis_table(_driver_stats()), source) + + +def test_a_refused_pinned_write_leaves_the_dataset_untouched(tmp_path): + uri = str(tmp_path / "d.lance") + _write(uri, _driver_stats(n_rows=3)) + source = LanceSource(uri=uri, table_format=LanceFormat(version=1)) + + with pytest.raises(ValueError): + _write_lance_data_source(_ibis_table(_driver_stats(n_rows=9)), source) + + assert lance.dataset(uri).version == 1 + assert lance.dataset(uri).count_rows() == 3 + + +def test_an_append_is_invisible_to_an_earlier_pin(tmp_path): + """Why a pinned write is refused: the pin would not show the write.""" + uri = str(tmp_path / "d.lance") + _write(uri, _driver_stats(n_rows=3)) + unpinned = LanceSource(uri=uri, timestamp_field="event_timestamp") + pinned = LanceSource( + uri=uri, table_format=LanceFormat(version=1), timestamp_field="event_timestamp" + ) + + _write_lance_data_source( + _ibis_table(_driver_stats(n_rows=2, base_hour=12)), unpinned + ) + + assert unpinned.to_arrow().num_rows == 5 + assert pinned.to_arrow().num_rows == 3 + + +def test_overwrite_without_allow_overwrite_is_refused(tmp_path): + from feast.errors import SavedDatasetLocationAlreadyExists + + uri = str(tmp_path / "d.lance") + _write(uri, _driver_stats(n_rows=3)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + + with pytest.raises(SavedDatasetLocationAlreadyExists): + _write_lance_data_source(_ibis_table(_driver_stats()), source, mode="overwrite") + assert lance.dataset(uri).count_rows() == 3 + + +def test_overwrite_with_allow_overwrite_replaces_the_data(tmp_path): + uri = str(tmp_path / "d.lance") + _write(uri, _driver_stats(n_rows=5)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + + _write_lance_data_source( + _ibis_table(_driver_stats(n_rows=2)), + source, + mode="overwrite", + allow_overwrite=True, + ) + + assert lance.dataset(uri).count_rows() == 2 + + +def test_overwrite_changing_a_vector_width_is_refused(tmp_path): + """Lance permits this silently; Feast must not. + + An ``overwrite`` that replaces a 8-wide embedding column with a 32-wide one + succeeds in Lance and leaves a version history whose vectors cannot be + compared with each other, invalidating every index built on the old width. + """ + uri = str(tmp_path / "emb.lance") + _write(uri, _vector_table(8)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + + with pytest.raises(ValueError, match="would change the width"): + _write_lance_data_source( + _ibis_table(_vector_table(32)), + source, + mode="overwrite", + allow_overwrite=True, + ) + + assert lance.dataset(uri).schema.field("embedding").type.list_size == 8 + assert lance.dataset(uri).version == 1 + + +def test_overwrite_keeping_the_vector_width_is_allowed(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _vector_table(8)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + + _write_lance_data_source( + _ibis_table(_vector_table(8)), source, mode="overwrite", allow_overwrite=True + ) + + assert lance.dataset(uri).schema.field("embedding").type.list_size == 8 + assert lance.dataset(uri).version == 2 + + +def test_a_non_vector_type_change_is_left_to_lance(tmp_path): + """The width guard is narrow on purpose: only vectors are policed.""" + uri = str(tmp_path / "d.lance") + _write(uri, pa.table({"a": pa.array([1], pa.int64())})) + source = LanceSource(uri=uri) + + _write_lance_data_source( + _ibis_table(pa.table({"a": pa.array(["x"], pa.string())})), + source, + mode="overwrite", + allow_overwrite=True, + ) + + assert lance.dataset(uri).schema.field("a").type == pa.string() + + +def test_a_width_guard_ignores_a_column_absent_from_the_write(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _vector_table(8)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + + validate_lance_write_shape( + pa.table({"item_id": pa.array([1], pa.int64())}), + source, + lance.dataset(uri).schema, + ) + + +def test_write_then_read_round_trips_through_the_offline_store(tmp_path): + uri = str(tmp_path / "d.lance") + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + + _write_lance_data_source(_ibis_table(_driver_stats(n_rows=3)), source) + read_back = _read_data_source(source, str(tmp_path)) + + assert read_back.to_pyarrow().num_rows == 3 + + +def test_offline_write_batch_rejects_a_width_other_than_the_declared_one(tmp_path): + """The declared vector_length is enforced at the write, not at the next read. + + Checked at the store entry point because the writer callback is handed a + DataSource and cannot see the declared schema. + """ + uri = str(tmp_path / "emb.lance") + _write(uri, _vector_table(8)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + fv = _vector_feature_view(source, declared_width=8) + + with pytest.raises(ValueError): + DuckDBOfflineStore.offline_write_batch( + _repo_config(tmp_path), fv, _vector_table(32), None + ) + + assert lance.dataset(uri).count_rows() == 2 + + +def test_offline_write_batch_appends_a_declared_width_batch(tmp_path): + uri = str(tmp_path / "emb.lance") + _write(uri, _vector_table(8)) + source = LanceSource(uri=uri, timestamp_field="event_timestamp") + fv = _vector_feature_view(source, declared_width=8) + + DuckDBOfflineStore.offline_write_batch( + _repo_config(tmp_path), fv, _vector_table(8), None + ) + + assert lance.dataset(uri).count_rows() == 4 + assert lance.dataset(uri).version == 2 + + +def test_a_namespace_resolves_a_write_but_does_not_track_its_versions(dir_namespace): + """Pins how far a Lance namespace is involved in a write. + + Creating a table declares it through the namespace. Appending only describes + the table, to resolve its location; the version the append produces is not + reported back. So a namespace records that a table exists and where it + lives, and is not a version coordinator -- which is why `assert_writable` + has to enforce the pin contract locally. + """ + client, properties = dir_namespace + calls: list[str] = [] + + class RecordingNamespace: + def __init__(self, inner): + self._inner = inner + + def __getattr__(self, name): + attribute = getattr(self._inner, name) + if not callable(attribute): + return attribute + + def recorded(*args, **kwargs): + calls.append(name) + return attribute(*args, **kwargs) + + return recorded + + source = LanceSource( + table="tracked", + namespace_impl="dir", + namespace_properties=properties, + timestamp_field="event_timestamp", + ) + spy = RecordingNamespace(client) + source.get_namespace_client = lambda: spy # type: ignore[method-assign] + + _write_lance_data_source(_ibis_table(_driver_stats(n_rows=3)), source) + assert "declare_table" in calls + + calls.clear() + _write_lance_data_source(_ibis_table(_driver_stats(n_rows=2, base_hour=12)), source) + assert "declare_table" not in calls + assert "describe_table" in calls + + assert source.to_arrow().num_rows == 5