-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathprovider.py
More file actions
538 lines (472 loc) · 18.6 KB
/
provider.py
File metadata and controls
538 lines (472 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
from abc import ABC, abstractmethod
from datetime import datetime
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Union,
)
import pandas as pd
import pyarrow
from tqdm import tqdm
from feast import FeatureService, errors
from feast.base_feature_view import BaseFeatureView
from feast.data_source import DataSource
from feast.entity import Entity
from feast.feature_view import FeatureView
from feast.importer import import_class
from feast.infra.infra_object import Infra
from feast.infra.offline_stores.offline_store import RetrievalJob
from feast.infra.registry.base_registry import BaseRegistry
from feast.infra.supported_async_methods import ProviderAsyncMethods
from feast.on_demand_feature_view import OnDemandFeatureView
from feast.online_response import OnlineResponse
from feast.protos.feast.core.Registry_pb2 import Registry as RegistryProto
from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto
from feast.protos.feast.types.Value_pb2 import RepeatedValue
from feast.protos.feast.types.Value_pb2 import Value as ValueProto
from feast.repo_config import RepoConfig
from feast.saved_dataset import SavedDataset
PROVIDERS_CLASS_FOR_TYPE = {
"gcp": "feast.infra.passthrough_provider.PassthroughProvider",
"aws": "feast.infra.passthrough_provider.PassthroughProvider",
"local": "feast.infra.passthrough_provider.PassthroughProvider",
"azure": "feast.infra.passthrough_provider.PassthroughProvider",
}
class Provider(ABC):
"""
A provider defines an implementation of a feature store object. It orchestrates the various
components of a feature store, such as the offline store, online store, and materialization
engine. It is configured through a RepoConfig object.
"""
@abstractmethod
def __init__(self, config: RepoConfig):
pass
@property
def async_supported(self) -> ProviderAsyncMethods:
return ProviderAsyncMethods()
@abstractmethod
def update_infra(
self,
project: str,
tables_to_delete: Sequence[FeatureView],
tables_to_keep: Sequence[Union[FeatureView, OnDemandFeatureView]],
entities_to_delete: Sequence[Entity],
entities_to_keep: Sequence[Entity],
partial: bool,
):
"""
Reconciles cloud resources with the specified set of Feast objects.
Args:
project: Feast project to which the objects belong.
tables_to_delete: Feature views whose corresponding infrastructure should be deleted.
tables_to_keep: Feature views whose corresponding infrastructure should not be deleted, and
may need to be updated.
entities_to_delete: Entities whose corresponding infrastructure should be deleted.
entities_to_keep: Entities whose corresponding infrastructure should not be deleted, and
may need to be updated.
partial: If true, tables_to_delete and tables_to_keep are not exhaustive lists, so
infrastructure corresponding to other feature views should be not be touched.
"""
pass
def plan_infra(
self, config: RepoConfig, desired_registry_proto: RegistryProto
) -> Infra:
"""
Returns the Infra required to support the desired registry.
Args:
config: The RepoConfig for the current FeatureStore.
desired_registry_proto: The desired registry, in proto form.
"""
return Infra()
@abstractmethod
def teardown_infra(
self,
project: str,
tables: Sequence[FeatureView],
entities: Sequence[Entity],
):
"""
Tears down all cloud resources for the specified set of Feast objects.
Args:
project: Feast project to which the objects belong.
tables: Feature views whose corresponding infrastructure should be deleted.
entities: Entities whose corresponding infrastructure should be deleted.
"""
pass
@abstractmethod
def online_write_batch(
self,
config: RepoConfig,
table: FeatureView,
data: List[
Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]]
],
progress: Optional[Callable[[int], Any]],
) -> None:
"""
Writes a batch of feature rows to the online store.
If a tz-naive timestamp is passed to this method, it is assumed to be UTC.
Args:
config: The config for the current feature store.
table: Feature view to which these feature rows correspond.
data: A list of quadruplets containing feature data. Each quadruplet contains an entity
key, a dict containing feature values, an event timestamp for the row, and the created
timestamp for the row if it exists.
progress: Function to be called once a batch of rows is written to the online store, used
to show progress.
"""
pass
@abstractmethod
async def online_write_batch_async(
self,
config: RepoConfig,
table: FeatureView,
data: List[
Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]]
],
progress: Optional[Callable[[int], Any]],
) -> None:
"""
Writes a batch of feature rows to the online store asynchronously.
If a tz-naive timestamp is passed to this method, it is assumed to be UTC.
Args:
config: The config for the current feature store.
table: Feature view to which these feature rows correspond.
data: A list of quadruplets containing feature data. Each quadruplet contains an entity
key, a dict containing feature values, an event timestamp for the row, and the created
timestamp for the row if it exists.
progress: Function to be called once a batch of rows is written to the online store, used
to show progress.
"""
pass
def ingest_df(
self,
feature_view: Union[BaseFeatureView, FeatureView, OnDemandFeatureView],
df: pd.DataFrame,
field_mapping: Optional[Dict] = None,
):
"""
Persists a dataframe to the online store.
Args:
feature_view: The feature view to which the dataframe corresponds.
df: The dataframe to be persisted.
field_mapping: A dictionary mapping dataframe column names to feature names.
"""
pass
async def ingest_df_async(
self,
feature_view: Union[BaseFeatureView, FeatureView, OnDemandFeatureView],
df: pd.DataFrame,
field_mapping: Optional[Dict] = None,
):
"""
Persists a dataframe to the online store asynchronously.
Args:
feature_view: The feature view to which the dataframe corresponds.
df: The dataframe to be persisted.
field_mapping: A dictionary mapping dataframe column names to feature names.
"""
pass
def ingest_df_to_offline_store(
self,
feature_view: FeatureView,
df: pyarrow.Table,
):
"""
Persists a dataframe to the offline store.
Args:
feature_view: The feature view to which the dataframe corresponds.
df: The dataframe to be persisted.
"""
pass
@abstractmethod
def materialize_single_feature_view(
self,
config: RepoConfig,
feature_view: FeatureView,
start_date: datetime,
end_date: datetime,
registry: BaseRegistry,
project: str,
tqdm_builder: Callable[[int], tqdm],
) -> None:
"""
Writes latest feature values in the specified time range to the online store.
Args:
config: The config for the current feature store.
feature_view: The feature view to materialize.
start_date: The start of the time range.
end_date: The end of the time range.
registry: The registry for the current feature store.
project: Feast project to which the objects belong.
tqdm_builder: A function to monitor the progress of materialization.
"""
pass
@abstractmethod
def get_historical_features(
self,
config: RepoConfig,
feature_views: List[Union[FeatureView, OnDemandFeatureView]],
feature_refs: List[str],
entity_df: Union[pd.DataFrame, str],
registry: BaseRegistry,
project: str,
full_feature_names: bool,
) -> RetrievalJob:
"""
Retrieves the point-in-time correct historical feature values for the specified entity rows.
Args:
config: The config for the current feature store.
feature_views: A list containing all feature views that are referenced in the entity rows.
feature_refs: The features to be retrieved.
entity_df: A collection of rows containing all entity columns on which features need to be joined,
as well as the timestamp column used for point-in-time joins. Either a pandas dataframe can be
provided or a SQL query.
registry: The registry for the current feature store.
project: Feast project to which the feature views belong.
full_feature_names: If True, feature names will be prefixed with the corresponding feature view name,
changing them from the format "feature" to "feature_view__feature" (e.g. "daily_transactions"
changes to "customer_fv__daily_transactions").
Returns:
A RetrievalJob that can be executed to get the features.
"""
pass
@abstractmethod
def online_read(
self,
config: RepoConfig,
table: FeatureView,
entity_keys: List[EntityKeyProto],
requested_features: Optional[List[str]] = None,
) -> List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]]:
"""
Reads features values for the given entity keys.
Args:
config: The config for the current feature store.
table: The feature view whose feature values should be read.
entity_keys: The list of entity keys for which feature values should be read.
requested_features: The list of features that should be read.
Returns:
A list of the same length as entity_keys. Each item in the list is a tuple where the first
item is the event timestamp for the row, and the second item is a dict mapping feature names
to values, which are returned in proto format.
"""
pass
@abstractmethod
def get_online_features(
self,
config: RepoConfig,
features: Union[List[str], FeatureService],
entity_rows: Union[
List[Dict[str, Any]],
Mapping[str, Union[Sequence[Any], Sequence[ValueProto], RepeatedValue]],
],
registry: BaseRegistry,
project: str,
full_feature_names: bool = False,
) -> OnlineResponse:
pass
@abstractmethod
async def get_online_features_async(
self,
config: RepoConfig,
features: Union[List[str], FeatureService],
entity_rows: Union[
List[Dict[str, Any]],
Mapping[str, Union[Sequence[Any], Sequence[ValueProto], RepeatedValue]],
],
registry: BaseRegistry,
project: str,
full_feature_names: bool = False,
) -> OnlineResponse:
pass
@abstractmethod
async def online_read_async(
self,
config: RepoConfig,
table: FeatureView,
entity_keys: List[EntityKeyProto],
requested_features: Optional[List[str]] = None,
) -> List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]]:
"""
Reads features values for the given entity keys asynchronously.
Args:
config: The config for the current feature store.
table: The feature view whose feature values should be read.
entity_keys: The list of entity keys for which feature values should be read.
requested_features: The list of features that should be read.
Returns:
A list of the same length as entity_keys. Each item in the list is a tuple where the first
item is the event timestamp for the row, and the second item is a dict mapping feature names
to values, which are returned in proto format.
"""
pass
@abstractmethod
def retrieve_saved_dataset(
self, config: RepoConfig, dataset: SavedDataset
) -> RetrievalJob:
"""
Reads a saved dataset.
Args:
config: The config for the current feature store.
dataset: A SavedDataset object containing all parameters necessary for retrieving the dataset.
Returns:
A RetrievalJob that can be executed to get the saved dataset.
"""
pass
@abstractmethod
def write_feature_service_logs(
self,
feature_service: FeatureService,
logs: Union[pyarrow.Table, Path],
config: RepoConfig,
registry: BaseRegistry,
):
"""
Writes features and entities logged by a feature server to the offline store.
The schema of the logs table is inferred from the specified feature service. Only feature
services with configured logging are accepted.
Args:
feature_service: The feature service to be logged.
logs: The logs, either as an arrow table or as a path to a parquet directory.
config: The config for the current feature store.
registry: The registry for the current feature store.
"""
pass
@abstractmethod
def retrieve_feature_service_logs(
self,
feature_service: FeatureService,
start_date: datetime,
end_date: datetime,
config: RepoConfig,
registry: BaseRegistry,
) -> RetrievalJob:
"""
Reads logged features for the specified time window.
Args:
feature_service: The feature service whose logs should be retrieved.
start_date: The start of the window.
end_date: The end of the window.
config: The config for the current feature store.
registry: The registry for the current feature store.
Returns:
A RetrievalJob that can be executed to get the feature service logs.
"""
pass
def get_feature_server_endpoint(self) -> Optional[str]:
"""Returns endpoint for the feature server, if it exists."""
return None
@abstractmethod
def retrieve_online_documents(
self,
config: RepoConfig,
table: FeatureView,
requested_features: Optional[List[str]],
query: List[float],
top_k: int,
distance_metric: Optional[str] = None,
) -> List[
Tuple[
Optional[datetime],
Optional[EntityKeyProto],
Optional[ValueProto],
Optional[ValueProto],
Optional[ValueProto],
],
]:
"""
Searches for the top-k most similar documents in the online document store.
Args:
distance_metric: distance metric to use for the search.
config: The config for the current feature store.
table: The feature view whose embeddings should be searched.
requested_features: the requested document feature names.
query: The query embedding to search for.
top_k: The number of documents to return.
Returns:
A list of dictionaries, where each dictionary contains the document feature.
"""
pass
@abstractmethod
def retrieve_online_documents_v2(
self,
config: RepoConfig,
table: FeatureView,
requested_features: List[str],
query: Optional[List[float]],
top_k: int,
distance_metric: Optional[str] = None,
query_string: Optional[str] = None,
) -> List[
Tuple[
Optional[datetime],
Optional[EntityKeyProto],
Optional[Dict[str, ValueProto]],
]
]:
"""
Searches for the top-k most similar documents in the online document store.
Args:
distance_metric: distance metric to use for the search.
config: The config for the current feature store.
table: The feature view whose embeddings should be searched.
requested_features: the requested document feature names.
query: The query embedding to search for (optional).
top_k: The number of documents to return.
query_string: The query string to search for using keyword search (bm25) (optional)
Returns:
A list of dictionaries, where each dictionary contains the datetime, entitykey, and a dictionary
of feature key value pairs
"""
pass
@abstractmethod
def validate_data_source(
self,
config: RepoConfig,
data_source: DataSource,
):
"""
Validates the underlying data source.
Args:
config: Configuration object used to configure a feature store.
data_source: DataSource object that needs to be validated
"""
pass
@abstractmethod
def get_table_column_names_and_types_from_data_source(
self, config: RepoConfig, data_source: DataSource
) -> Iterable[Tuple[str, str]]:
"""
Returns the list of column names and raw column types for a DataSource.
Args:
config: Configuration object used to configure a feature store.
data_source: DataSource object
"""
pass
@abstractmethod
async def initialize(self, config: RepoConfig) -> None:
pass
@abstractmethod
async def close(self) -> None:
pass
def get_provider(config: RepoConfig) -> Provider:
if "." not in config.provider:
if config.provider not in PROVIDERS_CLASS_FOR_TYPE:
raise errors.FeastProviderNotImplementedError(config.provider)
provider = PROVIDERS_CLASS_FOR_TYPE[config.provider]
else:
provider = config.provider
# Split provider into module and class names by finding the right-most dot.
# For example, provider 'foo.bar.MyProvider' will be parsed into 'foo.bar' and 'MyProvider'
module_name, class_name = provider.rsplit(".", 1)
cls = import_class(module_name, class_name, "Provider")
return cls(config)