From be910b2959057563a46758fca31fcc2029f0c967 Mon Sep 17 00:00:00 2001 From: hao-xu5 Date: Fri, 9 Oct 2026 12:11:59 -0700 Subject: [PATCH] fix: Record which storage class wrote a custom_storage payload Three SavedDatasetStorage subclasses declare _proto_attr_name = "custom_storage", and _StorageRegistry keys a flat dict on that name, so the last class imported won the field and from_proto dispatched to it regardless of which class had written the payload. PostgreSQL and Clickhouse serialize an identical {name, query, table} configuration, so the content could not be used to tell them apart either. Writing a SavedDatasetPostgreSQLStorage and reading it back in an environment that also installed Couchbase raised KeyError: 'database'. SavedDatasetStorage now records its concrete class path in the CustomSourceOptions.configuration JSON, which the proto documents as owned by the implementer, and resolves that on read through the existing get_saved_dataset_storage_class_from_path. Payloads written before this key existed cannot be disambiguated, because the bytes of these classes are identical and the information was never stored; those now report the competing classes by name instead of mis-dispatching. A field with a single claimant is unaffected, and an unresolvable recorded path falls back rather than surfacing an import error. Signed-off-by: hao-xu5 --- .../clickhouse_source.py | 4 +- .../couchbase_source.py | 4 +- .../postgres_offline_store/postgres_source.py | 2 +- sdk/python/feast/saved_dataset.py | 93 +++++++- .../test_saved_dataset_storage_dispatch.py | 206 ++++++++++++++++++ 5 files changed, 300 insertions(+), 9 deletions(-) create mode 100644 sdk/python/tests/unit/test_saved_dataset_storage_dispatch.py diff --git a/sdk/python/feast/infra/offline_stores/contrib/clickhouse_offline_store/clickhouse_source.py b/sdk/python/feast/infra/offline_stores/contrib/clickhouse_offline_store/clickhouse_source.py index 27a72d2ccb6..fce6ae23e81 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/clickhouse_offline_store/clickhouse_source.py +++ b/sdk/python/feast/infra/offline_stores/contrib/clickhouse_offline_store/clickhouse_source.py @@ -174,9 +174,7 @@ def from_proto(storage_proto: SavedDatasetStorageProto) -> SavedDatasetStorage: ) def to_proto(self) -> SavedDatasetStorageProto: - return SavedDatasetStorageProto( - custom_storage=self.clickhouse_options.to_proto() - ) + return self._custom_storage_proto(self.clickhouse_options.to_proto()) def to_data_source(self) -> DataSource: return ClickhouseSource(table=self.clickhouse_options._table) diff --git a/sdk/python/feast/infra/offline_stores/contrib/couchbase_offline_store/couchbase_source.py b/sdk/python/feast/infra/offline_stores/contrib/couchbase_offline_store/couchbase_source.py index 84eeea63a9f..68307940533 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/couchbase_offline_store/couchbase_source.py +++ b/sdk/python/feast/infra/offline_stores/contrib/couchbase_offline_store/couchbase_source.py @@ -343,9 +343,7 @@ def from_proto(storage_proto: SavedDatasetStorageProto) -> SavedDatasetStorage: ) def to_proto(self) -> SavedDatasetStorageProto: - return SavedDatasetStorageProto( - custom_storage=self.couchbase_options.to_proto() - ) + return self._custom_storage_proto(self.couchbase_options.to_proto()) def to_data_source(self) -> DataSource: return CouchbaseColumnarSource( diff --git a/sdk/python/feast/infra/offline_stores/contrib/postgres_offline_store/postgres_source.py b/sdk/python/feast/infra/offline_stores/contrib/postgres_offline_store/postgres_source.py index 7cffc187c7d..bc56c676a81 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/postgres_offline_store/postgres_source.py +++ b/sdk/python/feast/infra/offline_stores/contrib/postgres_offline_store/postgres_source.py @@ -234,7 +234,7 @@ def from_proto(storage_proto: SavedDatasetStorageProto) -> SavedDatasetStorage: ) def to_proto(self) -> SavedDatasetStorageProto: - return SavedDatasetStorageProto(custom_storage=self.postgres_options.to_proto()) + return self._custom_storage_proto(self.postgres_options.to_proto()) def to_data_source(self) -> DataSource: return PostgreSQLSource(table=self.postgres_options._table) diff --git a/sdk/python/feast/saved_dataset.py b/sdk/python/feast/saved_dataset.py index 555872d1ab4..9a66a9b2d8d 100644 --- a/sdk/python/feast/saved_dataset.py +++ b/sdk/python/feast/saved_dataset.py @@ -1,3 +1,4 @@ +import json from abc import abstractmethod from datetime import datetime from typing import TYPE_CHECKING, Dict, List, Optional, Type, cast @@ -9,6 +10,7 @@ from feast.data_source import DataSource from feast.dqm.profilers.profiler import Profile, Profiler from feast.importer import import_class +from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto from feast.protos.feast.core.SavedDataset_pb2 import SavedDataset as SavedDatasetProto from feast.protos.feast.core.SavedDataset_pb2 import SavedDatasetMeta, SavedDatasetSpec from feast.protos.feast.core.SavedDataset_pb2 import ( @@ -24,14 +26,63 @@ class _StorageRegistry(type): classes_by_proto_attr_name: Dict[str, Type["SavedDatasetStorage"]] = {} + # Several storage classes share the ``custom_storage`` oneof field, so the + # mapping above cannot identify them. Every claimant is recorded here in + # registration order so that dispatch can tell "one obvious class" apart + # from "several, pick deliberately". + all_classes_by_proto_attr_name: Dict[str, List[Type["SavedDatasetStorage"]]] = {} def __new__(cls, name, bases, dct): kls = type.__new__(cls, name, bases, dct) - if dct.get("_proto_attr_name"): - cls.classes_by_proto_attr_name[dct["_proto_attr_name"]] = kls + proto_attr_name = dct.get("_proto_attr_name") + if proto_attr_name: + cls.classes_by_proto_attr_name[proto_attr_name] = kls + claimants = cls.all_classes_by_proto_attr_name.setdefault( + proto_attr_name, [] + ) + if kls not in claimants: + claimants.append(kls) return kls +# Key under which a custom_storage payload records the concrete storage class +# that wrote it. CustomSourceOptions.configuration is an opaque byte string the +# implementer owns, and every claimant already reads it as JSON by explicit key, +# so an extra key is ignored by older readers. +CUSTOM_STORAGE_CLASS_KEY = "saved_dataset_storage_class" + + +def _class_path(cls: type) -> str: + return f"{cls.__module__}.{cls.__qualname__}" + + +def _read_custom_storage_class( + options_proto: DataSourceProto.CustomSourceOptions, +) -> Optional[Type["SavedDatasetStorage"]]: + """Resolve the class recorded in a custom_storage payload, if it has one. + + Returns ``None`` for a payload written before this key existed, or one whose + configuration is not the JSON object the claimants write, so the caller can + fall back instead of failing on data it could previously read. + """ + try: + config = json.loads(options_proto.configuration.decode("utf8")) + except (UnicodeDecodeError, ValueError): + return None + if not isinstance(config, dict): + return None + class_path = config.get(CUSTOM_STORAGE_CLASS_KEY) + if not isinstance(class_path, str) or not class_path: + return None + try: + return get_saved_dataset_storage_class_from_path(class_path) + except Exception: + # A recorded path can be unresolvable here: the class may live in an + # extra that is not installed, or may not be importable at all. Fall + # back rather than turn a readable payload into an import failure. + return None + + _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", @@ -49,10 +100,48 @@ class SavedDatasetStorage(metaclass=_StorageRegistry): @staticmethod def from_proto(storage_proto: SavedDatasetStorageProto) -> "SavedDatasetStorage": proto_attr_name = cast(str, storage_proto.WhichOneof("kind")) + + if proto_attr_name == "custom_storage": + recorded = _read_custom_storage_class(storage_proto.custom_storage) + if recorded is not None: + return recorded.from_proto(storage_proto) + + claimants = _StorageRegistry.all_classes_by_proto_attr_name.get( + proto_attr_name, [] + ) + if len(claimants) > 1: + raise ValueError( + f"{len(claimants)} storage classes claim the " + f"'{proto_attr_name}' field and this payload does not record " + f"which one wrote it, so it cannot be read back unambiguously: " + f"{', '.join(sorted(_class_path(c) for c in claimants))}. " + f"Saved datasets written after this version record their class " + f"under the '{CUSTOM_STORAGE_CLASS_KEY}' key; this one predates " + f"that, and the payloads of these classes are not otherwise " + f"distinguishable. Call the intended class's from_proto directly." + ) + return _StorageRegistry.classes_by_proto_attr_name[proto_attr_name].from_proto( storage_proto ) + def _custom_storage_proto( + self, options_proto: DataSourceProto.CustomSourceOptions + ) -> SavedDatasetStorageProto: + """Wrap custom source options, recording which class wrote them. + + Classes that share the ``custom_storage`` field must use this instead of + constructing the proto directly, otherwise ``from_proto`` has nothing to + dispatch on and has to guess from import order. + """ + config = json.loads(options_proto.configuration.decode("utf8")) + config[CUSTOM_STORAGE_CLASS_KEY] = _class_path(type(self)) + return SavedDatasetStorageProto( + custom_storage=DataSourceProto.CustomSourceOptions( + configuration=json.dumps(config).encode() + ) + ) + @abstractmethod def to_proto(self) -> SavedDatasetStorageProto: pass diff --git a/sdk/python/tests/unit/test_saved_dataset_storage_dispatch.py b/sdk/python/tests/unit/test_saved_dataset_storage_dispatch.py new file mode 100644 index 00000000000..5be8263a2fc --- /dev/null +++ b/sdk/python/tests/unit/test_saved_dataset_storage_dispatch.py @@ -0,0 +1,206 @@ +import json +import sys +import types + +import pytest + +from feast.infra.offline_stores.file_source import SavedDatasetFileStorage +from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto +from feast.protos.feast.core.SavedDataset_pb2 import ( + SavedDatasetStorage as SavedDatasetStorageProto, +) +from feast.saved_dataset import ( + CUSTOM_STORAGE_CLASS_KEY, + SavedDatasetStorage, + _StorageRegistry, +) + +SYNTHETIC_MODULE = "feast_test_synthetic_storage" + +# Two storage classes that share a proto field, in a real importable module so +# that the class path recorded in a payload can actually be resolved. +SYNTHETIC_SOURCE = """ +import json + +from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto +from feast.saved_dataset import SavedDatasetStorage + + +def _options(**config): + return DataSourceProto.CustomSourceOptions( + configuration=json.dumps(config).encode() + ) + + +class FirstSharedStorage(SavedDatasetStorage): + _proto_attr_name = "custom_storage" + + def to_proto(self): + return self._custom_storage_proto(_options(table="first")) + + @staticmethod + def from_proto(storage_proto): + return FirstSharedStorage() + + def to_data_source(self): + raise NotImplementedError + + +class SecondSharedStorage(SavedDatasetStorage): + _proto_attr_name = "custom_storage" + + def to_proto(self): + return self._custom_storage_proto(_options(table="second")) + + @staticmethod + def from_proto(storage_proto): + return SecondSharedStorage() + + def to_data_source(self): + raise NotImplementedError + + +""" + + +@pytest.fixture +def synthetic_storage(): + """Register synthetic storage classes, then undo the registration. + + The registry is process-global, so without the teardown these classes would + remain claimants for every test that runs afterwards. + """ + by_name = dict(_StorageRegistry.classes_by_proto_attr_name) + all_by_name = { + key: list(value) + for key, value in _StorageRegistry.all_classes_by_proto_attr_name.items() + } + + module = types.ModuleType(SYNTHETIC_MODULE) + sys.modules[SYNTHETIC_MODULE] = module + exec(compile(SYNTHETIC_SOURCE, SYNTHETIC_MODULE, "exec"), module.__dict__) + + yield module + + sys.modules.pop(SYNTHETIC_MODULE, None) + _StorageRegistry.classes_by_proto_attr_name.clear() + _StorageRegistry.classes_by_proto_attr_name.update(by_name) + _StorageRegistry.all_classes_by_proto_attr_name.clear() + _StorageRegistry.all_classes_by_proto_attr_name.update(all_by_name) + + +def _custom_options(**config) -> DataSourceProto.CustomSourceOptions: + return DataSourceProto.CustomSourceOptions( + configuration=json.dumps(config).encode() + ) + + +def test_a_field_with_one_claimant_is_unaffected(): + storage = SavedDatasetFileStorage(path="data/driver_stats.parquet") + + read_back = SavedDatasetStorage.from_proto(storage.to_proto()) + + assert isinstance(read_back, SavedDatasetFileStorage) + assert read_back.file_options.uri == "data/driver_stats.parquet" + + +def test_sharing_a_field_round_trips_to_the_class_that_wrote_it(synthetic_storage): + first = synthetic_storage.FirstSharedStorage() + second = synthetic_storage.SecondSharedStorage() + + # SecondSharedStorage was defined last, so the flat registry points at it. + # Both must still read back as themselves. + assert isinstance( + SavedDatasetStorage.from_proto(first.to_proto()), + synthetic_storage.FirstSharedStorage, + ) + assert isinstance( + SavedDatasetStorage.from_proto(second.to_proto()), + synthetic_storage.SecondSharedStorage, + ) + + +def test_the_written_proto_records_the_concrete_class(synthetic_storage): + proto = synthetic_storage.FirstSharedStorage().to_proto() + + config = json.loads(proto.custom_storage.configuration.decode("utf8")) + + assert config[CUSTOM_STORAGE_CLASS_KEY] == ( + f"{SYNTHETIC_MODULE}.FirstSharedStorage" + ) + # The payload the class itself wrote is preserved alongside the new key. + assert config["table"] == "first" + + +def test_an_untagged_payload_with_several_claimants_names_them(synthetic_storage): + # What an older version wrote: no class recorded in the payload. + legacy = _custom_options(table="first") + assert CUSTOM_STORAGE_CLASS_KEY not in json.loads( + legacy.configuration.decode("utf8") + ) + + with pytest.raises(ValueError) as error: + SavedDatasetStorage.from_proto(SavedDatasetStorageProto(custom_storage=legacy)) + + message = str(error.value) + assert CUSTOM_STORAGE_CLASS_KEY in message + # Every claimant is named so the reader knows which to call directly. + assert f"{SYNTHETIC_MODULE}.FirstSharedStorage" in message + assert f"{SYNTHETIC_MODULE}.SecondSharedStorage" in message + + +def test_an_unresolvable_recorded_class_does_not_raise_an_import_error( + synthetic_storage, +): + """A recorded class whose module is not installed must fall back. + + The fallback still cannot disambiguate, so this reports the ambiguity + rather than leaking an import failure from the recorded path. + """ + payload = _custom_options( + table="t", **{CUSTOM_STORAGE_CLASS_KEY: "not_a_module.NotAClass"} + ) + + with pytest.raises(ValueError) as error: + SavedDatasetStorage.from_proto(SavedDatasetStorageProto(custom_storage=payload)) + + assert CUSTOM_STORAGE_CLASS_KEY in str(error.value) + + +@pytest.mark.parametrize( + "module_path, class_name, kwargs", + [ + ( + "feast.infra.offline_stores.contrib.postgres_offline_store.postgres_source", + "SavedDatasetPostgreSQLStorage", + {"table_ref": "public.saved_dataset"}, + ), + ( + "feast.infra.offline_stores.contrib.clickhouse_offline_store.clickhouse_source", + "SavedDatasetClickhouseStorage", + {"table_ref": "public.saved_dataset"}, + ), + ( + "feast.infra.offline_stores.contrib.couchbase_offline_store.couchbase_source", + "SavedDatasetCouchbaseColumnarStorage", + { + "database_ref": "db", + "scope_ref": "scope", + "collection_ref": "collection", + }, + ), + ], +) +def test_the_real_custom_storage_classes_round_trip(module_path, class_name, kwargs): + """The three in-tree classes that share ``custom_storage``. + + Postgres and Clickhouse serialize identical payloads, so before the writing + class was recorded these two could only be told apart by import order. + """ + module = pytest.importorskip(module_path) + storage_class = getattr(module, class_name) + + written = storage_class(**kwargs) + read_back = SavedDatasetStorage.from_proto(written.to_proto()) + + assert type(read_back) is storage_class