-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathon_demand_feature_view.py
More file actions
1275 lines (1107 loc) · 51.8 KB
/
on_demand_feature_view.py
File metadata and controls
1275 lines (1107 loc) · 51.8 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 copy
import functools
import warnings
from types import FunctionType
from typing import Any, List, Optional, Union, cast
import dill
import pyarrow
from typeguard import typechecked
from feast.aggregation import Aggregation
from feast.base_feature_view import BaseFeatureView
from feast.data_source import RequestSource
from feast.entity import Entity
from feast.errors import RegistryInferenceFailure, SpecifiedFeaturesNotPresentError
from feast.feature_view import DUMMY_ENTITY_NAME, FeatureView
from feast.feature_view_projection import FeatureViewProjection
from feast.field import Field, from_value_type
from feast.proto_utils import transformation_to_proto
from feast.protos.feast.core.OnDemandFeatureView_pb2 import (
OnDemandFeatureView as OnDemandFeatureViewProto,
)
from feast.protos.feast.core.OnDemandFeatureView_pb2 import (
OnDemandFeatureViewMeta,
OnDemandFeatureViewSpec,
OnDemandSource,
)
from feast.protos.feast.core.Transformation_pb2 import (
UserDefinedFunctionV2 as UserDefinedFunctionProto,
)
from feast.transformation.base import Transformation
from feast.transformation.mode import TransformationMode
from feast.transformation.pandas_transformation import PandasTransformation
from feast.transformation.python_transformation import PythonTransformation
from feast.transformation.substrait_transformation import SubstraitTransformation
from feast.utils import _utc_now
from feast.value_type import ValueType
from feast.version_utils import normalize_version_string
warnings.simplefilter("once", DeprecationWarning)
OnDemandSourceType = Union[FeatureView, FeatureViewProjection, RequestSource]
class ODFVErrorMessages:
"""Centralized error message templates for OnDemandFeatureView."""
@staticmethod
def unsupported_source_type(source_type: type, supported_types: str) -> str:
return (
f"Unsupported source type: {source_type.__name__}. "
f"Supported types are {supported_types}."
)
@staticmethod
def singleton_mode_requires_python(current_mode: str) -> str:
return (
f"Singleton mode is only supported with mode='python', "
f"but mode='{current_mode}' was specified. Either disable singleton "
f"(singleton=False) or change mode to 'python'."
)
@staticmethod
def online_store_requires_entities() -> str:
return (
"OnDemandFeatureView configured with write_to_online_store=True "
"must have at least one entity defined. Either add entities or "
"set write_to_online_store=False."
)
@staticmethod
def no_transformation_provided() -> str:
return (
"OnDemandFeatureView must have a valid feature_transformation. "
"Provide either a udf parameter or a feature_transformation parameter."
)
@staticmethod
def duplicate_source_names(overlapping_names: set) -> str:
return (
f"Source names must be unique across all source types. "
f"Found duplicate names: {overlapping_names}"
)
@staticmethod
def no_sources_configured() -> str:
return (
"OnDemandFeatureView must have at least one source. "
"Add either FeatureView/FeatureViewProjection sources or RequestSource sources."
)
@staticmethod
def mode_transformation_mismatch(
mode: str, expected_type: str, actual_type: str
) -> str:
return f"Mode '{mode}' requires {expected_type}, but got {actual_type}."
@staticmethod
def unknown_source_type_in_proto(source_type: str | None) -> str:
return f"Unknown source type in protobuf: {source_type}"
@staticmethod
def unsupported_transformation_type(transformation_type: str) -> str:
return f"Unsupported transformation type: {transformation_type}"
@staticmethod
def backward_compatible_udf_missing() -> str:
return "Backward compatible UDF requires user_defined_function field"
@staticmethod
def unsupported_mode_for_udf(mode: str) -> str:
return f"Unsupported mode '{mode}' for user_defined_function"
@typechecked
class OnDemandFeatureView(BaseFeatureView):
"""
[Experimental] An OnDemandFeatureView defines a logical group of features that are
generated by applying a transformation on a set of input sources, such as feature
views and request data sources.
Attributes:
name: The unique name of the on demand feature view.
features: The list of features in the output of the on demand feature view.
source_feature_view_projections: A map from input source names to actual input
sources with type FeatureViewProjection.
source_request_sources: A map from input source names to the actual input
sources with type RequestSource.
feature_transformation: The user defined transformation.
description: A human-readable description.
tags: A dictionary of key-value pairs to store arbitrary metadata.
owner: The owner of the on demand feature view, typically the email of the primary
maintainer.
"""
_TRACK_METRICS_TAG = "feast:track_metrics"
name: str
entities: Optional[List[str]]
features: List[Field]
source_feature_view_projections: dict[str, FeatureViewProjection]
source_request_sources: dict[str, RequestSource]
feature_transformation: Transformation
mode: str
description: str
tags: dict[str, str]
owner: str
write_to_online_store: bool
singleton: bool
track_metrics: bool
udf: Optional[FunctionType]
udf_string: Optional[str]
aggregations: List[Aggregation]
def __init__( # noqa: C901
self,
*,
name: str,
entities: Optional[List[Entity]] = None,
schema: Optional[List[Field]] = None,
sources: List[OnDemandSourceType],
udf: Optional[FunctionType] = None,
udf_string: Optional[str] = "",
feature_transformation: Optional[Transformation] = None,
mode: str = "pandas",
description: str = "",
tags: Optional[dict[str, str]] = None,
owner: str = "",
write_to_online_store: bool = False,
singleton: bool = False,
track_metrics: bool = False,
aggregations: Optional[List[Aggregation]] = None,
version: str = "latest",
):
"""
Creates an OnDemandFeatureView object.
Args:
name: The unique name of the on demand feature view.
entities (optional): The list of names of entities that this feature view is associated with.
schema: The list of features in the output of the on demand feature view, after
the transformation has been applied.
sources: A map from input source names to the actual input sources, which may be
feature views, or request data sources. These sources serve as inputs to the udf,
which will refer to them by name.
udf: The user defined transformation function, which must take pandas
dataframes as inputs.
udf_string: The source code version of the udf (for diffing and displaying in Web UI)
feature_transformation: The user defined transformation.
mode: Mode of execution (e.g., Pandas or Python native)
description (optional): A human-readable description.
tags (optional): A dictionary of key-value pairs to store arbitrary metadata.
owner (optional): The owner of the on demand feature view, typically the email
of the primary maintainer.
write_to_online_store (optional): A boolean that indicates whether to write the on demand feature view to
the online store for faster retrieval.
singleton (optional): A boolean that indicates whether the transformation is executed on a singleton
(only applicable when mode="python").
track_metrics (optional): Whether to emit Prometheus timing metrics
(``feast_feature_server_transformation_duration_seconds``) for
this ODFV. Defaults to ``False``. Set to ``True`` to opt in
to per-ODFV transformation duration tracking when the server
is started with metrics enabled.
aggregations (optional): List of aggregations to apply before transformation.
"""
super().__init__(
name=name,
features=schema,
description=description,
tags=tags,
owner=owner,
)
self.version = version
schema = schema or []
self.entities = [e.name for e in entities] if entities else [DUMMY_ENTITY_NAME]
self.sources = sources
self.mode = mode.lower()
self.udf = udf
self.udf_string = udf_string
self.source_feature_view_projections: dict[str, FeatureViewProjection] = {}
self.source_request_sources: dict[str, RequestSource] = {}
# Process each source with explicit type handling
for odfv_source in sources:
self._add_source_to_collections(odfv_source)
features: List[Field] = []
self.entity_columns = []
join_keys: List[str] = []
if entities:
for entity in entities:
join_keys.append(entity.join_key)
# Ensure that entities have unique join keys.
if len(set(join_keys)) < len(join_keys):
raise ValueError(
"A feature view should not have entities that share a join key."
)
for field in schema:
if field.name in join_keys:
self.entity_columns.append(field)
# Confirm that the inferred type matches the specified entity type, if it exists.
matching_entities = (
[e for e in entities if e.join_key == field.name]
if entities
else []
)
assert len(matching_entities) == 1
entity = matching_entities[0]
if entity.value_type != ValueType.UNKNOWN:
if from_value_type(entity.value_type) != field.dtype:
raise ValueError(
f"Entity {entity.name} has type {entity.value_type}, which does not match the inferred type {field.dtype}."
)
else:
features.append(field)
self.features = features
self.feature_transformation = (
feature_transformation or self.get_feature_transformation()
)
self.write_to_online_store = write_to_online_store
self.singleton = singleton
if self.singleton and self.mode != "python":
raise ValueError(
ODFVErrorMessages.singleton_mode_requires_python(self.mode)
)
self.track_metrics = track_metrics
self.aggregations = aggregations or []
def _add_source_to_collections(self, odfv_source: OnDemandSourceType) -> None:
"""
Add a source to the appropriate collection with explicit type checking.
Args:
odfv_source: The source to add (RequestSource, FeatureViewProjection, or FeatureView)
Raises:
ValueError: If the source type is not supported
"""
if isinstance(odfv_source, RequestSource):
self.source_request_sources[odfv_source.name] = odfv_source
elif isinstance(odfv_source, FeatureViewProjection):
self.source_feature_view_projections[odfv_source.name] = odfv_source
elif isinstance(odfv_source, FeatureView):
# FeatureView sources use their projection
self.source_feature_view_projections[odfv_source.name] = (
odfv_source.projection
)
else:
raise ValueError(
ODFVErrorMessages.unsupported_source_type(
type(odfv_source),
"RequestSource, FeatureViewProjection, and FeatureView",
)
)
def get_feature_transformation(self) -> Transformation:
if not self.udf:
raise ValueError(ODFVErrorMessages.no_transformation_provided())
if self.mode in (
TransformationMode.PANDAS,
TransformationMode.PYTHON,
) or self.mode in ("pandas", "python"):
return Transformation(
mode=self.mode, udf=self.udf, udf_string=self.udf_string or ""
)
elif self.mode == TransformationMode.SUBSTRAIT or self.mode == "substrait":
return SubstraitTransformation.from_ibis(self.udf, self.sources)
else:
raise ValueError(
f"Unsupported transformation mode: {self.mode} for OnDemandFeatureView"
)
@property
def proto_class(self) -> type[OnDemandFeatureViewProto]:
return OnDemandFeatureViewProto
def __copy__(self):
fv = OnDemandFeatureView(
name=self.name,
schema=self.features,
sources=list(self.source_feature_view_projections.values())
+ list(self.source_request_sources.values()),
feature_transformation=self.feature_transformation,
mode=self.mode,
description=self.description,
tags=self.tags,
owner=self.owner,
write_to_online_store=self.write_to_online_store,
singleton=self.singleton,
version=self.version,
track_metrics=self.track_metrics,
)
fv.entities = self.entities
fv.features = self.features
fv.projection = copy.copy(self.projection)
fv.entity_columns = copy.copy(self.entity_columns)
return fv
def _schema_or_udf_changed(self, other: "BaseFeatureView") -> bool:
"""Check for OnDemandFeatureView schema/UDF changes."""
if super()._schema_or_udf_changed(other):
return True
if not isinstance(other, OnDemandFeatureView):
return True
# UDF/transformation changes
# Handle None cases for feature_transformation
if (
self.feature_transformation is None
and other.feature_transformation is not None
):
return True
if (
self.feature_transformation is not None
and other.feature_transformation is None
):
return True
if (
self.feature_transformation is not None
and other.feature_transformation is not None
and self.feature_transformation != other.feature_transformation
):
return True
if self.mode != other.mode:
return True
if (
self.source_feature_view_projections
!= other.source_feature_view_projections
):
return True
if self.source_request_sources != other.source_request_sources:
return True
if sorted(self.entity_columns) != sorted(other.entity_columns):
return True
if self.aggregations != other.aggregations:
return True
# Skip configuration: write_to_online_store, singleton
return False
def __eq__(self, other):
if not isinstance(other, OnDemandFeatureView):
raise TypeError(
"Comparisons should only involve OnDemandFeatureView class objects."
)
# Note, no longer evaluating the base feature view layer as ODFVs can have
# multiple datasources and a base_feature_view only has one source
# though maybe that shouldn't be true
if (
self.source_feature_view_projections
!= other.source_feature_view_projections
or self.description != other.description
or self.source_request_sources != other.source_request_sources
or self.mode != other.mode
or self.feature_transformation != other.feature_transformation
or self.write_to_online_store != other.write_to_online_store
or sorted(self.entity_columns) != sorted(other.entity_columns)
or self.singleton != other.singleton
or self.track_metrics != other.track_metrics
or self.aggregations != other.aggregations
or normalize_version_string(self.version)
!= normalize_version_string(other.version)
):
return False
return True
@property
def join_keys(self) -> List[str]:
"""Returns a list of all the join keys."""
return [entity.name for entity in self.entity_columns]
@property
def schema(self) -> List[Field]:
return list(set(self.entity_columns + self.features))
def ensure_valid(self):
"""
Validates the state of this feature view locally.
Raises:
ValueError: If the OnDemandFeatureView configuration is invalid.
"""
super().ensure_valid()
# Validate write_to_online_store configuration
self._validate_online_store_config()
# Validate singleton mode configuration
self._validate_singleton_config()
# Validate sources configuration
self._validate_sources_config()
# Validate transformation compatibility
self._validate_transformation_config()
def _validate_online_store_config(self) -> None:
"""Validate write_to_online_store configuration."""
if self.write_to_online_store and not self.entities:
raise ValueError(ODFVErrorMessages.online_store_requires_entities())
def _validate_singleton_config(self) -> None:
"""Validate singleton mode configuration."""
if self.singleton and self.mode != "python":
raise ValueError(
ODFVErrorMessages.singleton_mode_requires_python(self.mode)
)
def _validate_sources_config(self) -> None:
"""Validate sources configuration."""
if not self.source_feature_view_projections and not self.source_request_sources:
raise ValueError(ODFVErrorMessages.no_sources_configured())
# Validate source names are unique
fv_names = set(self.source_feature_view_projections.keys())
req_names = set(self.source_request_sources.keys())
overlapping_names = fv_names.intersection(req_names)
if overlapping_names:
raise ValueError(
ODFVErrorMessages.duplicate_source_names(overlapping_names)
)
def _validate_transformation_config(self) -> None:
"""Validate transformation configuration."""
if not self.feature_transformation:
raise ValueError(ODFVErrorMessages.no_transformation_provided())
# Validate mode compatibility with transformation type
if self.mode in ("pandas", "python"):
from feast.transformation.pandas_transformation import PandasTransformation
from feast.transformation.python_transformation import PythonTransformation
expected_types = (PandasTransformation, PythonTransformation)
if not isinstance(self.feature_transformation, expected_types):
raise ValueError(
ODFVErrorMessages.mode_transformation_mismatch(
self.mode,
"PandasTransformation or PythonTransformation",
type(self.feature_transformation).__name__,
)
)
elif self.mode == "substrait":
from feast.transformation.substrait_transformation import (
SubstraitTransformation,
)
if not isinstance(self.feature_transformation, SubstraitTransformation):
raise ValueError(
ODFVErrorMessages.mode_transformation_mismatch(
self.mode,
"SubstraitTransformation",
type(self.feature_transformation).__name__,
)
)
def __hash__(self):
return super().__hash__()
def to_proto(self) -> OnDemandFeatureViewProto:
"""
Converts an on demand feature view object to its protobuf representation.
Returns:
A OnDemandFeatureViewProto protobuf.
"""
meta = OnDemandFeatureViewMeta()
if self.created_timestamp:
meta.created_timestamp.FromDatetime(self.created_timestamp)
if self.last_updated_timestamp:
meta.last_updated_timestamp.FromDatetime(self.last_updated_timestamp)
if self.current_version_number is not None:
meta.current_version_number = self.current_version_number
sources = {}
for source_name, fv_projection in self.source_feature_view_projections.items():
sources[source_name] = OnDemandSource(
feature_view_projection=fv_projection.to_proto(),
)
for (
source_name,
request_sources,
) in self.source_request_sources.items():
sources[source_name] = OnDemandSource(
request_data_source=request_sources.to_proto()
)
feature_transformation = transformation_to_proto(self.feature_transformation)
tags = dict(self.tags) if self.tags else {}
if self.track_metrics:
tags[self._TRACK_METRICS_TAG] = "true"
else:
tags.pop(self._TRACK_METRICS_TAG, None)
spec = OnDemandFeatureViewSpec(
name=self.name,
entities=self.entities or None,
entity_columns=[
field.to_proto() for field in self.entity_columns if self.entity_columns
],
features=[feature.to_proto() for feature in self.features],
sources=sources,
feature_transformation=feature_transformation,
mode=self.mode,
description=self.description,
tags=tags,
owner=self.owner,
write_to_online_store=self.write_to_online_store,
singleton=self.singleton or False,
aggregations=self.aggregations,
version=self.version,
)
return OnDemandFeatureViewProto(spec=spec, meta=meta)
@classmethod
def from_proto(
cls,
on_demand_feature_view_proto: OnDemandFeatureViewProto,
skip_udf: bool = False,
):
"""
Creates an on demand feature view from a protobuf representation.
Args:
on_demand_feature_view_proto: A protobuf representation of an on-demand feature view.
skip_udf: A boolean indicating whether to skip loading the udf
Returns:
A OnDemandFeatureView object based on the on-demand feature view protobuf.
"""
# Parse sources from proto
sources = cls._parse_sources_from_proto(on_demand_feature_view_proto)
# Parse transformation from proto
transformation = cls._parse_transformation_from_proto(
on_demand_feature_view_proto
)
# Parse optional fields with defaults
optional_fields = cls._parse_optional_fields_from_proto(
on_demand_feature_view_proto
)
# Extract track_metrics from proto tags and strip the internal key
# so it doesn't leak into user-facing self.tags.
proto_tags = dict(on_demand_feature_view_proto.spec.tags)
track_metrics = (
proto_tags.pop(cls._TRACK_METRICS_TAG, "false").lower() == "true"
)
# Create the OnDemandFeatureView object
on_demand_feature_view_obj = cls(
name=on_demand_feature_view_proto.spec.name,
schema=cls._parse_features_from_proto(on_demand_feature_view_proto),
sources=cast(List[OnDemandSourceType], sources),
feature_transformation=transformation,
mode=on_demand_feature_view_proto.spec.mode or "pandas",
description=on_demand_feature_view_proto.spec.description,
tags=proto_tags,
owner=on_demand_feature_view_proto.spec.owner,
write_to_online_store=optional_fields["write_to_online_store"],
singleton=optional_fields["singleton"],
track_metrics=track_metrics,
aggregations=optional_fields["aggregations"],
)
# Set additional attributes that aren't part of the constructor
on_demand_feature_view_obj.entities = optional_fields["entities"]
on_demand_feature_view_obj.entity_columns = optional_fields["entity_columns"]
# FeatureViewProjections are not saved in the OnDemandFeatureView proto.
# Create the default projection.
on_demand_feature_view_obj.projection = FeatureViewProjection.from_definition(
on_demand_feature_view_obj
)
# Restore version fields.
spec_version = on_demand_feature_view_proto.spec.version
on_demand_feature_view_obj.version = spec_version or "latest"
cvn = on_demand_feature_view_proto.meta.current_version_number
if cvn > 0:
on_demand_feature_view_obj.current_version_number = cvn
elif cvn == 0 and spec_version and spec_version.lower() != "latest":
on_demand_feature_view_obj.current_version_number = 0
else:
on_demand_feature_view_obj.current_version_number = None
# Set timestamps if present
cls._set_timestamps_from_proto(
on_demand_feature_view_proto, on_demand_feature_view_obj
)
return on_demand_feature_view_obj
@classmethod
def _parse_sources_from_proto(
cls, proto: OnDemandFeatureViewProto
) -> List[OnDemandSourceType]:
"""Parse and convert sources from the protobuf representation."""
sources: List[OnDemandSourceType] = []
for _, on_demand_source in proto.spec.sources.items():
source_type = on_demand_source.WhichOneof("source")
if source_type == "feature_view":
sources.append(
FeatureView.from_proto(on_demand_source.feature_view).projection
)
elif source_type == "feature_view_projection":
sources.append(
FeatureViewProjection.from_proto(
on_demand_source.feature_view_projection
)
)
elif source_type == "request_data_source":
sources.append(
RequestSource.from_proto(on_demand_source.request_data_source)
)
else:
raise ValueError(
ODFVErrorMessages.unknown_source_type_in_proto(source_type)
)
return sources
@classmethod
def _parse_transformation_from_proto(
cls, proto: OnDemandFeatureViewProto
) -> Transformation:
"""Parse and convert the transformation from the protobuf representation."""
feature_transformation = proto.spec.feature_transformation
transformation_type = feature_transformation.WhichOneof("transformation")
mode = proto.spec.mode
if transformation_type == "user_defined_function":
udf_proto = feature_transformation.user_defined_function
# Check for non-empty UDF body
if udf_proto.body_text:
if mode == "pandas":
return PandasTransformation.from_proto(udf_proto)
elif mode == "python":
return PythonTransformation.from_proto(udf_proto)
else:
raise ValueError(ODFVErrorMessages.unsupported_mode_for_udf(mode))
else:
# Handle backward compatibility case with empty body_text
return cls._handle_backward_compatible_udf(proto)
elif transformation_type == "substrait_transformation":
return SubstraitTransformation.from_proto(
feature_transformation.substrait_transformation
)
elif transformation_type is None:
# Handle backward compatibility case where feature_transformation is cleared
return cls._handle_backward_compatible_udf(proto)
else:
raise ValueError(
ODFVErrorMessages.unsupported_transformation_type(transformation_type)
)
@classmethod
def _handle_backward_compatible_udf(
cls, proto: OnDemandFeatureViewProto
) -> Transformation:
"""Handle backward compatibility for UDFs with empty body_text."""
if not hasattr(proto.spec, "user_defined_function"):
raise ValueError(ODFVErrorMessages.backward_compatible_udf_missing())
old_udf = proto.spec.user_defined_function
backwards_compatible_udf = UserDefinedFunctionProto(
name=old_udf.name,
body=old_udf.body,
body_text=old_udf.body_text,
)
return PandasTransformation.from_proto(
user_defined_function_proto=backwards_compatible_udf,
)
@classmethod
def _parse_features_from_proto(cls, proto: OnDemandFeatureViewProto) -> List[Field]:
"""Parse features from the protobuf representation."""
return [
Field(
name=feature.name,
dtype=from_value_type(ValueType(feature.value_type)),
vector_index=feature.vector_index,
vector_length=feature.vector_length,
vector_search_metric=feature.vector_search_metric,
)
for feature in proto.spec.features
]
@classmethod
def _parse_optional_fields_from_proto(cls, proto: OnDemandFeatureViewProto) -> dict:
"""Parse optional fields from protobuf with appropriate defaults."""
spec = proto.spec
# Parse write_to_online_store
write_to_online_store = False
if hasattr(spec, "write_to_online_store"):
write_to_online_store = spec.write_to_online_store
# Parse entities
entities = []
if hasattr(spec, "entities"):
entities = list(spec.entities)
# Parse entity_columns
entity_columns = []
if hasattr(spec, "entity_columns"):
entity_columns = [
Field.from_proto(field_proto) for field_proto in spec.entity_columns
]
# Parse singleton
singleton = False
if hasattr(spec, "singleton"):
singleton = spec.singleton
# Parse aggregations
aggregations = []
if hasattr(spec, "aggregations"):
aggregations = [
Aggregation.from_proto(aggregation_proto)
for aggregation_proto in spec.aggregations
]
return {
"write_to_online_store": write_to_online_store,
"entities": entities,
"entity_columns": entity_columns,
"singleton": singleton,
"aggregations": aggregations,
}
@classmethod
def _set_timestamps_from_proto(
cls, proto: OnDemandFeatureViewProto, obj: "OnDemandFeatureView"
) -> None:
"""Set timestamp fields on the object if they exist in the proto."""
if proto.meta.HasField("created_timestamp"):
obj.created_timestamp = proto.meta.created_timestamp.ToDatetime()
if proto.meta.HasField("last_updated_timestamp"):
obj.last_updated_timestamp = proto.meta.last_updated_timestamp.ToDatetime()
def get_request_data_schema(self) -> dict[str, ValueType]:
schema: dict[str, ValueType] = {}
for request_source in self.source_request_sources.values():
if isinstance(request_source.schema, list):
new_schema = {}
for field in request_source.schema:
new_schema[field.name] = field.dtype.to_value_type()
schema.update(new_schema)
elif isinstance(request_source.schema, dict):
schema.update(request_source.schema)
else:
raise TypeError(
f"Request source schema is not correct type: ${str(type(request_source.schema))}"
)
return schema
def _get_projected_feature_name(self, feature: str) -> str:
return f"{self.projection.name_to_use()}__{feature}"
def transform_ibis(
self,
ibis_table,
full_feature_names: bool = False,
):
from ibis.expr.types import Table
if not isinstance(ibis_table, Table):
raise TypeError("transform_ibis only accepts ibis.expr.types.Table")
if not isinstance(self.feature_transformation, SubstraitTransformation):
raise TypeError(
"The feature_transformation is not SubstraitTransformation type while calling transform_ibis()."
)
# Apply common preprocessing to ensure both full and short feature names exist
ibis_table, columns_to_cleanup = self._preprocess_ibis_table(ibis_table)
# Apply the transformation
transformed_table = self.feature_transformation.transform_ibis(ibis_table)
# Clean up temporary columns
if columns_to_cleanup:
transformed_table = transformed_table.drop(*columns_to_cleanup)
# Apply final column renaming based on full_feature_names preference
return self._postprocess_ibis_table(transformed_table, full_feature_names)
def _preprocess_ibis_table(self, ibis_table):
"""
Preprocess ibis table to ensure both full and short feature names exist.
Returns the modified table and columns that need cleanup.
"""
columns_to_cleanup = []
for source_fv_projection in self.source_feature_view_projections.values():
for feature in source_fv_projection.features:
full_feature_ref = f"{source_fv_projection.name}__{feature.name}"
if full_feature_ref in ibis_table.columns:
# Make sure the partial feature name is always present
ibis_table = ibis_table.mutate(
**{feature.name: ibis_table[full_feature_ref]}
)
columns_to_cleanup.append(feature.name)
elif feature.name in ibis_table.columns:
# Make sure the full feature name is always present
ibis_table = ibis_table.mutate(
**{full_feature_ref: ibis_table[feature.name]}
)
columns_to_cleanup.append(full_feature_ref)
return ibis_table, columns_to_cleanup
def _postprocess_ibis_table(self, transformed_table, full_feature_names: bool):
"""
Apply final column renaming to match the desired naming convention.
"""
rename_columns: dict[str, str] = {}
for feature in self.features:
short_name = feature.name
long_name = self._get_projected_feature_name(feature.name)
if short_name in transformed_table.columns and full_feature_names:
rename_columns[short_name] = long_name
elif long_name in transformed_table.columns and not full_feature_names:
rename_columns[long_name] = short_name
# Apply renamings
for rename_from, rename_to in rename_columns.items():
if rename_from in transformed_table.columns:
transformed_table = transformed_table.rename(**{rename_to: rename_from})
return transformed_table
def transform_arrow(
self,
pa_table: pyarrow.Table,
full_feature_names: bool = False,
) -> pyarrow.Table:
if not isinstance(pa_table, pyarrow.Table):
raise TypeError("transform_arrow only accepts pyarrow.Table")
# Apply common preprocessing to ensure both full and short feature names exist
pa_table, columns_to_cleanup = self._preprocess_arrow_table(pa_table)
# Apply the transformation
transformed_table = self.feature_transformation.transform_arrow(
pa_table, self.features
)
# Clean up temporary columns and apply final renaming
return self._postprocess_arrow_table(
transformed_table, columns_to_cleanup, full_feature_names
)
def _preprocess_arrow_table(self, pa_table: pyarrow.Table):
"""
Preprocess pyarrow table to ensure both full and short feature names exist.
Returns the modified table and columns that need cleanup.
"""
columns_to_cleanup = []
for source_fv_projection in self.source_feature_view_projections.values():
for feature in source_fv_projection.features:
full_feature_ref = f"{source_fv_projection.name}__{feature.name}"
if full_feature_ref in pa_table.column_names:
# Make sure the partial feature name is always present
pa_table = pa_table.append_column(
feature.name, pa_table[full_feature_ref]
)
columns_to_cleanup.append(feature.name)
elif feature.name in pa_table.column_names:
# Make sure the full feature name is always present
pa_table = pa_table.append_column(
full_feature_ref, pa_table[feature.name]
)
columns_to_cleanup.append(full_feature_ref)
return pa_table, columns_to_cleanup
def _postprocess_arrow_table(
self,
transformed_table: pyarrow.Table,
columns_to_cleanup: list[str],
full_feature_names: bool,
) -> pyarrow.Table:
"""
Clean up temporary columns and apply final column renaming.
"""
# Determine final column names
rename_columns: dict[str, str] = {}
for feature in self.features:
short_name = feature.name
long_name = self._get_projected_feature_name(feature.name)
if short_name in transformed_table.column_names and full_feature_names:
rename_columns[short_name] = long_name
elif long_name in transformed_table.column_names and not full_feature_names:
rename_columns[long_name] = short_name
# Clean up temporary columns
for col in columns_to_cleanup:
if col in transformed_table.column_names:
transformed_table = transformed_table.drop(col)
# Apply column renaming
final_column_names = [
rename_columns.get(c, c) for c in transformed_table.column_names
]
return transformed_table.rename_columns(final_column_names)
def transform_dict(
self,
feature_dict: dict[str, Any], # type: ignore
) -> dict[str, Any]:
"""
Transform a dictionary of features using the configured transformation.
Handles both singleton and batch transformations.
Args:
feature_dict: Dictionary containing input features
Returns:
Dictionary with transformed features
"""
# Preprocess to ensure both full and short feature names exist
preprocessed_dict, columns_to_cleanup = self._preprocess_feature_dict(
feature_dict
)
# Apply the appropriate transformation based on mode
if self.singleton and self.mode == "python":
output_dict = self.feature_transformation.transform_singleton(
preprocessed_dict
)
else:
output_dict = self.feature_transformation.transform(preprocessed_dict)
# Clean up temporary columns
for feature_name in columns_to_cleanup:
if feature_name in output_dict:
del output_dict[feature_name]
return output_dict
def _preprocess_feature_dict(
self, feature_dict: dict[str, Any]