-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathsql.py
More file actions
1715 lines (1557 loc) · 63.3 KB
/
sql.py
File metadata and controls
1715 lines (1557 loc) · 63.3 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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Union, cast
from pydantic import StrictInt, StrictStr
from sqlalchemy import ( # type: ignore
BigInteger,
Column,
Index,
Integer,
LargeBinary,
MetaData,
String,
Table,
Text,
create_engine,
delete,
func,
insert,
select,
update,
)
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from feast import utils
from feast.base_feature_view import BaseFeatureView
from feast.data_source import DataSource
from feast.entity import Entity
from feast.errors import (
ConcurrentVersionConflict,
DataSourceObjectNotFoundException,
EntityNotFoundException,
FeatureServiceNotFoundException,
FeatureViewNotFoundException,
FeatureViewPinConflict,
FeatureViewVersionNotFound,
PermissionNotFoundException,
ProjectNotFoundException,
ProjectObjectNotFoundException,
SavedDatasetNotFound,
ValidationReferenceNotFound,
)
from feast.feature_service import FeatureService
from feast.feature_view import FeatureView
from feast.infra.infra_object import Infra
from feast.infra.registry.caching_registry import CachingRegistry
from feast.on_demand_feature_view import OnDemandFeatureView
from feast.permissions.permission import Permission
from feast.project import Project
from feast.project_metadata import ProjectMetadata
from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto
from feast.protos.feast.core.Entity_pb2 import Entity as EntityProto
from feast.protos.feast.core.FeatureService_pb2 import (
FeatureService as FeatureServiceProto,
)
from feast.protos.feast.core.FeatureView_pb2 import FeatureView as FeatureViewProto
from feast.protos.feast.core.InfraObject_pb2 import Infra as InfraProto
from feast.protos.feast.core.OnDemandFeatureView_pb2 import (
OnDemandFeatureView as OnDemandFeatureViewProto,
)
from feast.protos.feast.core.Permission_pb2 import Permission as PermissionProto
from feast.protos.feast.core.Project_pb2 import Project as ProjectProto
from feast.protos.feast.core.Registry_pb2 import Registry as RegistryProto
from feast.protos.feast.core.SavedDataset_pb2 import SavedDataset as SavedDatasetProto
from feast.protos.feast.core.StreamFeatureView_pb2 import (
StreamFeatureView as StreamFeatureViewProto,
)
from feast.protos.feast.core.ValidationProfile_pb2 import (
ValidationReference as ValidationReferenceProto,
)
from feast.repo_config import RegistryConfig
from feast.saved_dataset import SavedDataset, ValidationReference
from feast.stream_feature_view import StreamFeatureView
from feast.utils import _utc_now
from feast.version_utils import (
generate_version_id,
parse_version,
version_tag,
)
metadata = MetaData()
projects = Table(
"projects",
metadata,
Column("project_id", String(255), primary_key=True),
Column("project_name", String(255), nullable=False),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("project_proto", LargeBinary, nullable=False),
)
Index("idx_projects_project_id", projects.c.project_id)
entities = Table(
"entities",
metadata,
Column("entity_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("entity_proto", LargeBinary, nullable=False),
)
Index("idx_entities_project_id", entities.c.project_id)
data_sources = Table(
"data_sources",
metadata,
Column("data_source_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("data_source_proto", LargeBinary, nullable=False),
)
Index("idx_data_sources_project_id", data_sources.c.project_id)
feature_views = Table(
"feature_views",
metadata,
Column("feature_view_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("materialized_intervals", LargeBinary, nullable=True),
Column("feature_view_proto", LargeBinary, nullable=False),
Column("user_metadata", LargeBinary, nullable=True),
)
Index("idx_feature_views_project_id", feature_views.c.project_id)
stream_feature_views = Table(
"stream_feature_views",
metadata,
Column("feature_view_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("feature_view_proto", LargeBinary, nullable=False),
Column("user_metadata", LargeBinary, nullable=True),
)
Index("idx_stream_feature_views_project_id", stream_feature_views.c.project_id)
on_demand_feature_views = Table(
"on_demand_feature_views",
metadata,
Column("feature_view_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("feature_view_proto", LargeBinary, nullable=False),
Column("user_metadata", LargeBinary, nullable=True),
)
Index("idx_on_demand_feature_views_project_id", on_demand_feature_views.c.project_id)
feature_services = Table(
"feature_services",
metadata,
Column("feature_service_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("feature_service_proto", LargeBinary, nullable=False),
)
Index("idx_feature_services_project_id", feature_services.c.project_id)
saved_datasets = Table(
"saved_datasets",
metadata,
Column("saved_dataset_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("saved_dataset_proto", LargeBinary, nullable=False),
)
Index("idx_saved_datasets_project_id", saved_datasets.c.project_id)
validation_references = Table(
"validation_references",
metadata,
Column("validation_reference_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("validation_reference_proto", LargeBinary, nullable=False),
)
Index("idx_validation_references_project_id", validation_references.c.project_id)
managed_infra = Table(
"managed_infra",
metadata,
Column("infra_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("infra_proto", LargeBinary, nullable=False),
)
Index("idx_managed_infra_project_id", managed_infra.c.project_id)
permissions = Table(
"permissions",
metadata,
Column("permission_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("last_updated_timestamp", BigInteger, nullable=False),
Column("permission_proto", LargeBinary, nullable=False),
)
Index("idx_permissions_project_id", permissions.c.project_id)
feature_view_version_history = Table(
"feature_view_version_history",
metadata,
Column("feature_view_name", String(255), primary_key=True),
Column("project_id", String(255), primary_key=True),
Column("version_number", Integer, primary_key=True),
Column("feature_view_type", String(50), nullable=False),
Column("feature_view_proto", LargeBinary, nullable=False),
Column("created_timestamp", BigInteger, nullable=False),
Column("description", Text, nullable=True),
Column("version_id", String(36), nullable=False),
)
Index(
"idx_fv_version_history_project_id",
feature_view_version_history.c.project_id,
)
class FeastMetadataKeys(Enum):
LAST_UPDATED_TIMESTAMP = "last_updated_timestamp"
PROJECT_UUID = "project_uuid"
feast_metadata = Table(
"feast_metadata",
metadata,
Column("project_id", String(255), primary_key=True),
Column("metadata_key", String(50), primary_key=True),
Column("metadata_value", Text, nullable=False),
Column("last_updated_timestamp", BigInteger, nullable=False),
)
Index("idx_feast_metadata_project_id", feast_metadata.c.project_id)
logger = logging.getLogger(__name__)
class SqlRegistryConfig(RegistryConfig):
registry_type: StrictStr = "sql"
""" str: Provider name or a class name that implements Registry."""
path: StrictStr = ""
""" str: Path to metadata store.
If registry_type is 'sql', then this is a database URL as expected by SQLAlchemy """
read_path: Optional[StrictStr] = None
""" str: Read Path to metadata store if different from path.
If registry_type is 'sql', then this is a Read Endpoint for database URL. If not set, path will be used for read and write. """
sqlalchemy_config_kwargs: Dict[str, Any] = {"echo": False}
""" Dict[str, Any]: Extra arguments to pass to SQLAlchemy.create_engine. """
thread_pool_executor_worker_count: StrictInt = 0
""" int: Number of worker threads to use for asynchronous caching in SQL Registry. If set to 0, it doesn't use ThreadPoolExecutor. """
class SqlRegistry(CachingRegistry):
def __init__(
self,
registry_config,
project: str,
repo_path: Optional[Path],
):
assert registry_config is not None and isinstance(
registry_config, SqlRegistryConfig
), "SqlRegistry needs a valid registry_config"
self.registry_config = registry_config
self.write_engine: Engine = create_engine(
registry_config.path, **registry_config.sqlalchemy_config_kwargs
)
if registry_config.read_path:
self.read_engine: Engine = create_engine(
registry_config.read_path,
**registry_config.sqlalchemy_config_kwargs,
)
else:
self.read_engine = self.write_engine
metadata.create_all(self.write_engine)
self.thread_pool_executor_worker_count = (
registry_config.thread_pool_executor_worker_count
)
self.purge_feast_metadata = registry_config.purge_feast_metadata
self.enable_online_versioning = (
registry_config.enable_online_feature_view_versioning
)
super().__init__(
project=project,
cache_ttl_seconds=registry_config.cache_ttl_seconds,
cache_mode=registry_config.cache_mode,
)
# Sync feast_metadata to projects table
# when purge_feast_metadata is set to True, Delete data from
# feast_metadata table and list_project_metadata will not return any data
self._sync_feast_metadata_to_projects_table()
if not self.purge_feast_metadata:
self._maybe_init_project_metadata(project)
def _sync_feast_metadata_to_projects_table(self):
feast_metadata_projects: dict = {}
projects_set: set = []
with self.read_engine.begin() as conn:
stmt = select(feast_metadata).where(
feast_metadata.c.metadata_key == FeastMetadataKeys.PROJECT_UUID.value
)
rows = conn.execute(stmt).all()
for row in rows:
feast_metadata_projects[row._mapping["project_id"]] = int(
row._mapping["last_updated_timestamp"]
)
if len(feast_metadata_projects) > 0:
with self.read_engine.begin() as conn:
stmt = select(projects)
rows = conn.execute(stmt).all()
for row in rows:
projects_set.append(row._mapping["project_id"])
# Find object in feast_metadata_projects but not in projects
projects_to_sync = set(feast_metadata_projects.keys()) - set(projects_set)
for project_name in projects_to_sync:
try:
self.apply_project(
Project(
name=project_name,
created_timestamp=datetime.fromtimestamp(
feast_metadata_projects[project_name], tz=timezone.utc
),
),
commit=True,
)
except IntegrityError:
logger.info(
"Project %s already created in projects table by another process.",
project_name,
)
if self.purge_feast_metadata:
with self.write_engine.begin() as conn:
for project_name in feast_metadata_projects:
stmt = delete(feast_metadata).where(
feast_metadata.c.project_id == project_name
)
conn.execute(stmt)
def teardown(self):
for t in {
entities,
data_sources,
feature_views,
stream_feature_views,
feature_services,
on_demand_feature_views,
saved_datasets,
validation_references,
permissions,
feature_view_version_history,
}:
with self.write_engine.begin() as conn:
stmt = delete(t)
conn.execute(stmt)
def _get_stream_feature_view(self, name: str, project: str):
return self._get_object(
table=stream_feature_views,
name=name,
project=project,
proto_class=StreamFeatureViewProto,
python_class=StreamFeatureView,
id_field_name="feature_view_name",
proto_field_name="feature_view_proto",
not_found_exception=FeatureViewNotFoundException,
)
def _list_stream_feature_views(
self, project: str, tags: Optional[dict[str, str]]
) -> List[StreamFeatureView]:
return self._list_objects(
stream_feature_views,
project,
StreamFeatureViewProto,
StreamFeatureView,
"feature_view_proto",
tags=tags,
)
def apply_entity(self, entity: Entity, project: str, commit: bool = True):
return self._apply_object(
table=entities,
project=project,
id_field_name="entity_name",
obj=entity,
proto_field_name="entity_proto",
)
def _get_entity(self, name: str, project: str) -> Entity:
return self._get_object(
table=entities,
name=name,
project=project,
proto_class=EntityProto,
python_class=Entity,
id_field_name="entity_name",
proto_field_name="entity_proto",
not_found_exception=EntityNotFoundException,
)
def _get_any_feature_view(self, name: str, project: str) -> BaseFeatureView:
fv = self._get_object(
table=feature_views,
name=name,
project=project,
proto_class=FeatureViewProto,
python_class=FeatureView,
id_field_name="feature_view_name",
proto_field_name="feature_view_proto",
not_found_exception=None,
)
if not fv:
fv = self._get_object(
table=on_demand_feature_views,
name=name,
project=project,
proto_class=OnDemandFeatureViewProto,
python_class=OnDemandFeatureView,
id_field_name="feature_view_name",
proto_field_name="feature_view_proto",
not_found_exception=None,
)
if not fv:
fv = self._get_object(
table=stream_feature_views,
name=name,
project=project,
proto_class=StreamFeatureViewProto,
python_class=StreamFeatureView,
id_field_name="feature_view_name",
proto_field_name="feature_view_proto",
not_found_exception=FeatureViewNotFoundException,
)
return fv
def _list_all_feature_views(
self, project: str, tags: Optional[dict[str, str]]
) -> List[BaseFeatureView]:
return (
cast(
list[BaseFeatureView],
self._list_feature_views(project=project, tags=tags),
)
+ cast(
list[BaseFeatureView],
self._list_stream_feature_views(project=project, tags=tags),
)
+ cast(
list[BaseFeatureView],
self._list_on_demand_feature_views(project=project, tags=tags),
)
)
def _get_feature_view(self, name: str, project: str) -> FeatureView:
return self._get_object(
table=feature_views,
name=name,
project=project,
proto_class=FeatureViewProto,
python_class=FeatureView,
id_field_name="feature_view_name",
proto_field_name="feature_view_proto",
not_found_exception=FeatureViewNotFoundException,
)
def _get_on_demand_feature_view(
self, name: str, project: str
) -> OnDemandFeatureView:
return self._get_object(
table=on_demand_feature_views,
name=name,
project=project,
proto_class=OnDemandFeatureViewProto,
python_class=OnDemandFeatureView,
id_field_name="feature_view_name",
proto_field_name="feature_view_proto",
not_found_exception=FeatureViewNotFoundException,
)
def _get_feature_service(self, name: str, project: str) -> FeatureService:
return self._get_object(
table=feature_services,
name=name,
project=project,
proto_class=FeatureServiceProto,
python_class=FeatureService,
id_field_name="feature_service_name",
proto_field_name="feature_service_proto",
not_found_exception=FeatureServiceNotFoundException,
)
def _get_saved_dataset(self, name: str, project: str) -> SavedDataset:
return self._get_object(
table=saved_datasets,
name=name,
project=project,
proto_class=SavedDatasetProto,
python_class=SavedDataset,
id_field_name="saved_dataset_name",
proto_field_name="saved_dataset_proto",
not_found_exception=SavedDatasetNotFound,
)
def _get_validation_reference(self, name: str, project: str) -> ValidationReference:
return self._get_object(
table=validation_references,
name=name,
project=project,
proto_class=ValidationReferenceProto,
python_class=ValidationReference,
id_field_name="validation_reference_name",
proto_field_name="validation_reference_proto",
not_found_exception=ValidationReferenceNotFound,
)
def _list_validation_references(
self, project: str, tags: Optional[dict[str, str]] = None
) -> List[ValidationReference]:
return self._list_objects(
table=validation_references,
project=project,
proto_class=ValidationReferenceProto,
python_class=ValidationReference,
proto_field_name="validation_reference_proto",
tags=tags,
)
def _list_entities(
self, project: str, tags: Optional[dict[str, str]]
) -> List[Entity]:
return self._list_objects(
entities, project, EntityProto, Entity, "entity_proto", tags=tags
)
def delete_entity(self, name: str, project: str, commit: bool = True):
return self._delete_object(
entities, name, project, "entity_name", EntityNotFoundException
)
def delete_feature_view(self, name: str, project: str, commit: bool = True):
with self.write_engine.begin() as conn:
deleted_count = 0
for table in {
feature_views,
on_demand_feature_views,
stream_feature_views,
}:
stmt = delete(table).where(
table.c.feature_view_name == name,
table.c.project_id == project,
)
rows = conn.execute(stmt)
deleted_count += rows.rowcount
if deleted_count == 0:
raise FeatureViewNotFoundException(name, project)
# Clean up version history in the same transaction
stmt = delete(feature_view_version_history).where(
feature_view_version_history.c.feature_view_name == name,
feature_view_version_history.c.project_id == project,
)
conn.execute(stmt)
self.apply_project(
self.get_project(name=project, allow_cache=False), commit=True
)
if not self.purge_feast_metadata:
with self.write_engine.begin() as conn:
self._set_last_updated_metadata(_utc_now(), project, conn)
if self.cache_mode == "sync":
self.refresh()
def delete_feature_service(self, name: str, project: str, commit: bool = True):
return self._delete_object(
feature_services,
name,
project,
"feature_service_name",
FeatureServiceNotFoundException,
)
def _get_data_source(self, name: str, project: str) -> DataSource:
return self._get_object(
table=data_sources,
name=name,
project=project,
proto_class=DataSourceProto,
python_class=DataSource,
id_field_name="data_source_name",
proto_field_name="data_source_proto",
not_found_exception=DataSourceObjectNotFoundException,
)
def _list_data_sources(
self, project: str, tags: Optional[dict[str, str]]
) -> List[DataSource]:
return self._list_objects(
data_sources,
project,
DataSourceProto,
DataSource,
"data_source_proto",
tags=tags,
)
def apply_data_source(
self, data_source: DataSource, project: str, commit: bool = True
):
return self._apply_object(
data_sources, project, "data_source_name", data_source, "data_source_proto"
)
def apply_feature_view(
self,
feature_view: BaseFeatureView,
project: str,
commit: bool = True,
no_promote: bool = False,
):
feature_view.ensure_valid()
self._ensure_feature_view_name_is_unique(feature_view, project)
fv_table = self._infer_fv_table(feature_view)
fv_type_str = self._infer_fv_type_string(feature_view)
is_latest, pin_version = parse_version(feature_view.version)
if not is_latest:
# Explicit version: check if it exists (pin/revert) or not (forward declaration)
snapshot = self._get_version_snapshot(
feature_view.name, project, pin_version
)
if snapshot is not None:
# Version exists → pin/revert to that snapshot
# Check that the user hasn't also modified the definition.
# Compare user's FV (with version="latest") against active FV.
try:
active_fv = self._get_any_feature_view(feature_view.name, project)
user_fv_copy = feature_view.__copy__()
user_fv_copy.version = "latest"
active_fv.version = "latest"
# Clear metadata that differs due to registry state
user_fv_copy.created_timestamp = active_fv.created_timestamp
user_fv_copy.last_updated_timestamp = (
active_fv.last_updated_timestamp
)
user_fv_copy.current_version_number = (
active_fv.current_version_number
)
if hasattr(active_fv, "materialization_intervals"):
user_fv_copy.materialization_intervals = (
active_fv.materialization_intervals
)
if user_fv_copy != active_fv:
raise FeatureViewPinConflict(
feature_view.name, version_tag(pin_version)
)
except FeatureViewNotFoundException:
pass
snap_type, snap_proto_bytes = snapshot
proto_class, python_class = self._proto_class_for_type(snap_type)
snap_proto = proto_class.FromString(snap_proto_bytes)
restored_fv = python_class.from_proto(snap_proto)
restored_fv.version = feature_view.version
restored_fv.current_version_number = pin_version
return self._apply_object(
fv_table,
project,
"feature_view_name",
restored_fv,
"feature_view_proto",
)
else:
# Version doesn't exist → forward declaration: create it
feature_view.current_version_number = pin_version
snapshot_proto = feature_view.to_proto()
snapshot_proto.spec.project = project
snapshot_proto_bytes = snapshot_proto.SerializeToString()
try:
self._save_version_snapshot(
feature_view.name,
project,
pin_version,
fv_type_str,
snapshot_proto_bytes,
)
except IntegrityError:
raise ConcurrentVersionConflict(
f"Version v{pin_version} of '{feature_view.name}' was just created by "
f"another concurrent apply. Pull latest and retry."
)
# Apply the FV as active
return self._apply_object(
fv_table,
project,
"feature_view_name",
feature_view,
"feature_view_proto",
)
# Normal (latest) apply: snapshot old version if changed, then save new
# First check if the FV already exists so we can snapshot the old one.
# Use write_engine for both reads to avoid read replica lag issues.
old_proto_bytes = None
with self.write_engine.begin() as conn:
stmt = select(fv_table).where(
fv_table.c.feature_view_name == feature_view.name,
fv_table.c.project_id == project,
)
row = conn.execute(stmt).first()
if row:
old_proto_bytes = row._mapping["feature_view_proto"]
# Apply the object (handles idempotency check internally)
# We need to detect if _apply_object actually made a change
# by checking before/after
self._apply_object(
fv_table, project, "feature_view_name", feature_view, "feature_view_proto"
)
# After apply, read the current proto to see if it changed
with self.write_engine.begin() as conn:
stmt = select(fv_table).where(
fv_table.c.feature_view_name == feature_view.name,
fv_table.c.project_id == project,
)
row = conn.execute(stmt).first()
if row:
new_proto_bytes = row._mapping["feature_view_proto"]
else:
return # shouldn't happen
if old_proto_bytes is not None:
# Deserialize both versions to compare schema/UDF changes
proto_class, fv_class = self._proto_class_for_type(fv_type_str)
old_proto = proto_class.FromString(old_proto_bytes)
new_proto = proto_class.FromString(new_proto_bytes)
old_fv = fv_class.from_proto(old_proto)
new_fv = fv_class.from_proto(new_proto)
if not new_fv._schema_or_udf_changed(old_fv):
# No version-significant change, skip version creation
return
# Something changed (or new FV). Save version snapshot(s).
if old_proto_bytes is not None:
# Snapshot the old version first (if not already in history)
next_ver = self._get_next_version_number(feature_view.name, project)
if next_ver == 0:
# First time versioning: save old as v0
self._save_version_snapshot(
feature_view.name,
project,
0,
fv_type_str,
old_proto_bytes,
)
next_ver = 1
# Retry loop: if a concurrent apply claimed the same version number,
# re-read MAX+1 and try again. The client said "latest" so the
# exact number doesn't matter.
max_retries = 3
for attempt in range(max_retries):
# Update current_version_number before saving snapshot
feature_view.current_version_number = next_ver
snapshot_proto = feature_view.to_proto()
snapshot_proto.spec.project = project
snapshot_proto_bytes = snapshot_proto.SerializeToString()
try:
# Save new as next version (with correct current_version_number)
self._save_version_snapshot(
feature_view.name,
project,
next_ver,
fv_type_str,
snapshot_proto_bytes,
)
break
except IntegrityError:
if attempt == max_retries - 1:
raise ConcurrentVersionConflict(
f"Failed to assign version for '{feature_view.name}' after "
f"{max_retries} attempts due to concurrent applies. "
f"Please retry."
)
# Re-read the next available version number
next_ver = self._get_next_version_number(feature_view.name, project)
if no_promote:
# Save version snapshot but skip updating the active row.
# The new version is accessible only via explicit @v<N> reads.
return
# Re-serialize with updated version number
with self.write_engine.begin() as conn:
update_stmt = (
update(fv_table)
.where(
fv_table.c.feature_view_name == feature_view.name,
fv_table.c.project_id == project,
)
.values(
feature_view_proto=snapshot_proto_bytes,
)
)
conn.execute(update_stmt)
else:
# New FV: save as v0
feature_view.current_version_number = 0
snapshot_proto = feature_view.to_proto()
snapshot_proto.spec.project = project
snapshot_proto_bytes = snapshot_proto.SerializeToString()
self._save_version_snapshot(
feature_view.name,
project,
0,
fv_type_str,
snapshot_proto_bytes,
)
with self.write_engine.begin() as conn:
update_stmt = (
update(fv_table)
.where(
fv_table.c.feature_view_name == feature_view.name,
fv_table.c.project_id == project,
)
.values(
feature_view_proto=snapshot_proto_bytes,
)
)
conn.execute(update_stmt)
def apply_feature_service(
self, feature_service: FeatureService, project: str, commit: bool = True
):
return self._apply_object(
feature_services,
project,
"feature_service_name",
feature_service,
"feature_service_proto",
)
def delete_data_source(self, name: str, project: str, commit: bool = True):
with self.write_engine.begin() as conn:
stmt = delete(data_sources).where(
data_sources.c.data_source_name == name,
data_sources.c.project_id == project,
)
rows = conn.execute(stmt)
if rows.rowcount < 1:
raise DataSourceObjectNotFoundException(name, project)
def _list_feature_services(
self, project: str, tags: Optional[dict[str, str]]
) -> List[FeatureService]:
return self._list_objects(
feature_services,
project,
FeatureServiceProto,
FeatureService,
"feature_service_proto",
tags=tags,
)
def _list_feature_views(
self, project: str, tags: Optional[dict[str, str]]
) -> List[FeatureView]:
return self._list_objects(
feature_views,
project,
FeatureViewProto,
FeatureView,
"feature_view_proto",
tags=tags,
)
def _list_saved_datasets(
self, project: str, tags: Optional[dict[str, str]] = None
) -> List[SavedDataset]:
return self._list_objects(
saved_datasets,
project,
SavedDatasetProto,
SavedDataset,
"saved_dataset_proto",
tags=tags,
)
def _list_on_demand_feature_views(
self, project: str, tags: Optional[dict[str, str]]
) -> List[OnDemandFeatureView]:
return self._list_objects(
on_demand_feature_views,
project,
OnDemandFeatureViewProto,
OnDemandFeatureView,
"feature_view_proto",
tags=tags,
)
def _list_project_metadata(self, project: str) -> List[ProjectMetadata]:
with self.read_engine.begin() as conn:
stmt = select(feast_metadata).where(
feast_metadata.c.project_id == project,
)
rows = conn.execute(stmt).all()
if rows:
project_metadata = ProjectMetadata(project_name=project)
for row in rows:
if (
row._mapping["metadata_key"]
== FeastMetadataKeys.PROJECT_UUID.value
):
project_metadata.project_uuid = row._mapping["metadata_value"]
break
# TODO(adchia): Add other project metadata in a structured way
return [project_metadata]
return []
def apply_saved_dataset(
self,
saved_dataset: SavedDataset,
project: str,
commit: bool = True,
):
return self._apply_object(
saved_datasets,
project,
"saved_dataset_name",
saved_dataset,
"saved_dataset_proto",
)
def apply_validation_reference(
self,
validation_reference: ValidationReference,
project: str,
commit: bool = True,
):
return self._apply_object(
validation_references,
project,
"validation_reference_name",
validation_reference,
"validation_reference_proto",
)
def apply_materialization(
self,
feature_view: Union[FeatureView, OnDemandFeatureView],
project: str,
start_date: datetime,
end_date: datetime,
commit: bool = True,
):
table = self._infer_fv_table(feature_view)
python_class, proto_class = self._infer_fv_classes(feature_view)
if python_class in {OnDemandFeatureView}:
raise ValueError(
f"Cannot apply materialization for feature {feature_view.name} of type {python_class}"
)
fv: Union[FeatureView, StreamFeatureView] = self._get_object(
table,
feature_view.name,
project,
proto_class,
python_class,
"feature_view_name",
"feature_view_proto",
FeatureViewNotFoundException,
)
fv.materialization_intervals.append((start_date, end_date))