forked from feast-dev/feast
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsorted_feature_view.py
More file actions
312 lines (272 loc) · 11.3 KB
/
sorted_feature_view.py
File metadata and controls
312 lines (272 loc) · 11.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
import copy
import logging
import warnings
from datetime import timedelta
from typing import Dict, List, Optional, Tuple, Type
from google.protobuf.message import Message
from typeguard import typechecked
from feast import utils
from feast.data_source import DataSource
from feast.entity import Entity
from feast.feature_view import FeatureView
from feast.feature_view_projection import FeatureViewProjection
from feast.field import Field
from feast.protos.feast.core.SortedFeatureView_pb2 import (
SortedFeatureView as SortedFeatureViewProto,
)
from feast.protos.feast.core.SortedFeatureView_pb2 import (
SortedFeatureViewSpec as SortedFeatureViewSpecProto,
)
from feast.sort_key import SortKey
warnings.simplefilter("ignore", DeprecationWarning)
logger = logging.getLogger(__name__)
@typechecked
class SortedFeatureView(FeatureView):
"""
SortedFeatureView extends FeatureView by adding support for range queries
via sort keys.
"""
sort_keys: List[SortKey]
def __init__(
self,
*,
name: str,
source: DataSource,
schema: Optional[List[Field]] = None,
entities: Optional[List[Entity]] = None,
ttl: Optional[timedelta] = timedelta(days=0),
online: bool = True,
description: str = "",
tags: Optional[Dict[str, str]] = None,
owner: str = "",
sort_keys: Optional[List[SortKey]] = None,
use_write_time_for_ttl: bool = False,
_skip_validation: bool = False, # only skipping validation for proto creation, internal use only
):
super().__init__(
name=name,
source=source,
schema=schema,
entities=entities,
ttl=ttl,
online=online,
description=description,
tags=tags,
owner=owner,
)
self.sort_keys = sort_keys if sort_keys is not None else []
self.use_write_time_for_ttl = use_write_time_for_ttl
if not _skip_validation:
self.ensure_valid()
def __hash__(self):
return super().__hash__()
def __copy__(self):
sfv = SortedFeatureView(
name=self.name,
source=self.stream_source if self.stream_source else self.batch_source,
schema=self.schema,
entities=self.original_entities,
ttl=self.ttl,
online=self.online,
description=self.description,
tags=copy.deepcopy(self.tags),
owner=self.owner,
sort_keys=copy.copy(self.sort_keys),
use_write_time_for_ttl=self.use_write_time_for_ttl,
)
sfv.entities = self.entities
sfv.features = copy.copy(self.features)
sfv.entity_columns = copy.copy(self.entity_columns)
sfv.projection = copy.copy(self.projection)
return sfv
def __eq__(self, other):
if not isinstance(other, SortedFeatureView):
return NotImplemented
if not super().__eq__(other):
return False
# Compare sort_keys lists
return self.sort_keys == other.sort_keys
def ensure_valid(self):
"""
Validates this SortedFeatureView. In addition to the base FeatureView validations.
"""
super().ensure_valid()
reserved_columns = {"event_ts", "created_ts", "entity_key"}
feature_map = {}
for field in self.features:
if field.name in reserved_columns:
raise ValueError(
f"For SortedFeatureView: {self.name}: Field name '{field.name}' is reserved and cannot be used as "
f"a feature name."
)
if field.name in self.entities:
raise ValueError(
f"For SortedFeatureView: {self.name}: Feature name '{field.name}' is an entity name and cannot be "
f"used as a feature."
)
if field.name in feature_map:
raise ValueError(
f"For SortedFeatureView: {self.name}: Duplicate feature name found: '{field.name}'."
)
feature_map[field.name] = field
valid_feature_names = list(feature_map.keys())
if not self.sort_keys:
raise ValueError(
f"For SortedFeatureView: {self.name}, must have at least one sort key defined."
)
seen_sort_keys = set()
for sort_key in self.sort_keys:
# Check for duplicate sort keys
if sort_key.name in seen_sort_keys:
raise ValueError(
f"Duplicate sort key found: '{sort_key.name}' in SortedFeatureView: {self.name}."
)
seen_sort_keys.add(sort_key.name)
# Sort keys should not conflict with entity names.
if sort_key.name in self.entities:
raise ValueError(
f"For SortedFeatureView: {self.name}, Sort key '{sort_key.name}' refers to an entity column and cannot be used as a sort key. "
f"Valid sort key names are feature names: {valid_feature_names}"
)
# Validate that the sort key corresponds to a feature.
if sort_key.name not in feature_map:
raise ValueError(
f"Sort key '{sort_key.name}' does not match any feature name in SortedFeatureView: {self.name}. "
f"Valid options are: {valid_feature_names}"
)
expected_value_type = feature_map[sort_key.name].dtype.to_value_type()
if sort_key.value_type != expected_value_type:
raise ValueError(
f"Sort key '{sort_key.name}' has value type {sort_key.value_type} which does not match "
f"the expected feature value type {expected_value_type} for feature '{sort_key.name}' in "
f"SortedFeatureView: {self.name}."
)
def is_update_compatible_with(self, updated) -> Tuple[bool, List[str]]:
"""
Checks if updating this SortedFeatureView to `updated` is compatible.
Returns (True, []) if compatible; otherwise (False, [reasons...]).
"""
reasons: List[str] = []
# Base FeatureView compatibility
base_ok, base_reasons = super().is_update_compatible_with(updated) # type: ignore
if not base_ok:
reasons.extend(base_reasons)
# Sort key check
old_keys = [sk.name for sk in self.sort_keys]
new_keys = [sk.name for sk in updated.sort_keys]
if old_keys != new_keys:
reasons.append(
f"sort keys cannot change (old: {old_keys}, new: {new_keys})"
)
for old_sk, new_sk in zip(self.sort_keys, updated.sort_keys):
if old_sk.default_sort_order != new_sk.default_sort_order:
reasons.append(
f"sort key '{old_sk.name}' sort order changed "
f"({old_sk.default_sort_order} to {new_sk.default_sort_order})"
)
return len(reasons) == 0, reasons
@property
def proto_class(self) -> Type[Message]:
return SortedFeatureViewProto
def to_proto(self):
"""
Converts this SortedFeatureView to its protobuf representation.
"""
meta = self.to_proto_meta()
ttl_duration = self.get_ttl_duration()
# Convert batch and stream sources.
batch_source_proto = self.batch_source.to_proto()
batch_source_proto.data_source_class_type = (
f"{self.batch_source.__class__.__module__}."
f"{self.batch_source.__class__.__name__}"
)
stream_source_proto = None
if self.stream_source:
stream_source_proto = self.stream_source.to_proto()
stream_source_proto.data_source_class_type = (
f"{self.stream_source.__class__.__module__}."
f"{self.stream_source.__class__.__name__}"
)
original_entities = [entity.to_proto() for entity in self.original_entities]
spec = SortedFeatureViewSpecProto(
name=self.name,
entities=self.entities,
features=[field.to_proto() for field in self.features],
entity_columns=[field.to_proto() for field in self.entity_columns],
sort_keys=[sk.to_proto() for sk in self.sort_keys],
description=self.description,
tags=self.tags,
owner=self.owner,
ttl=(ttl_duration if ttl_duration is not None else None),
batch_source=batch_source_proto,
stream_source=stream_source_proto,
online=self.online,
original_entities=original_entities,
use_write_time_for_ttl=self.use_write_time_for_ttl,
)
return SortedFeatureViewProto(spec=spec, meta=meta)
@classmethod
def from_proto(cls, sfv_proto):
"""
Creates a SortedFeatureView from its protobuf representation.
"""
spec = sfv_proto.spec
batch_source = DataSource.from_proto(spec.batch_source)
stream_source = (
DataSource.from_proto(spec.stream_source)
if spec.HasField("stream_source")
else None
)
# Create the SortedFeatureView instance.
sorted_feature_view = cls(
name=spec.name,
description=spec.description,
tags=dict(spec.tags),
owner=spec.owner,
online=spec.online,
ttl=(
timedelta(days=0)
if spec.ttl.ToNanoseconds() == 0
else spec.ttl.ToTimedelta()
),
source=batch_source,
schema=None,
entities=None,
sort_keys=[SortKey.from_proto(sk) for sk in spec.sort_keys],
use_write_time_for_ttl=spec.use_write_time_for_ttl,
_skip_validation=True,
)
if stream_source:
sorted_feature_view.stream_source = stream_source
sorted_feature_view.entities = list(spec.entities)
sorted_feature_view.original_entities = [
Entity.from_proto(e) for e in spec.original_entities
]
sorted_feature_view.features = [Field.from_proto(f) for f in spec.features]
sorted_feature_view.entity_columns = [
Field.from_proto(f) for f in spec.entity_columns
]
sorted_feature_view.original_schema = (
sorted_feature_view.entity_columns + sorted_feature_view.features
)
sorted_feature_view.projection = FeatureViewProjection.from_definition(
sorted_feature_view
)
if sfv_proto.meta.HasField("created_timestamp"):
sorted_feature_view.created_timestamp = (
sfv_proto.meta.created_timestamp.ToDatetime()
)
if sfv_proto.meta.HasField("last_updated_timestamp"):
sorted_feature_view.last_updated_timestamp = (
sfv_proto.meta.last_updated_timestamp.ToDatetime()
)
for interval in sfv_proto.meta.materialization_intervals:
sorted_feature_view.materialization_intervals.append(
(
utils.make_tzaware(interval.start_time.ToDatetime()),
utils.make_tzaware(interval.end_time.ToDatetime()),
)
)
# Run validation after attributes are set
sorted_feature_view.ensure_valid()
return sorted_feature_view