-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathtest_feature_materialization.py
More file actions
429 lines (358 loc) · 16.3 KB
/
Copy pathtest_feature_materialization.py
File metadata and controls
429 lines (358 loc) · 16.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
import os
from datetime import datetime, timedelta
from pathlib import Path
from feathr.client import FeathrClient
from feathr.utils.job_utils import get_result_df
from pyspark.sql import DataFrame
from pyspark.sql.functions import col
from feathr import BOOLEAN, FLOAT, INT32, ValueType
from feathr import (
BackfillTime,
MaterializationSettings,
FeatureQuery,
ObservationSettings,
SparkExecutionConfiguration,
ConflictsAutoCorrection,
)
from feathr import Feature
from feathr import FeatureAnchor
from feathr import INPUT_CONTEXT, HdfsSource
from feathr import RedisSink, HdfsSink, AerospikeSink
from feathr import TypedKey
from feathr.definition._materialization_utils import _to_materialization_config
from test_fixture import basic_test_setup, conflicts_auto_correction_setup
from test_fixture import get_online_test_table_name
from test_utils.constants import Constants
from logging import raiseExceptions
import pytest
def test_feature_materialization_config():
backfill_time = BackfillTime(start=datetime(2020, 5, 20), end=datetime(2020, 5, 20), step=timedelta(days=1))
redisSink = RedisSink(table_name="nycTaxiDemoFeature")
settings = MaterializationSettings(
"nycTaxiTable",
sinks=[redisSink],
feature_names=["f_location_avg_fare", "f_location_max_fare"],
backfill_time=backfill_time,
)
config = _to_materialization_config(settings)
expected_config = """
operational: {
name: nycTaxiTable
endTime: "2020-05-20 00:00:00"
endTimeFormat: "yyyy-MM-dd HH:mm:ss"
resolution: DAILY
output:[
{
name: REDIS
params: {
table_name: "nycTaxiDemoFeature"
features: [f_location_avg_fare,f_location_max_fare]
}
}
]
}
features: [f_location_avg_fare, f_location_max_fare]
"""
assert "".join(config.split()) == "".join(expected_config.split())
def test_feature_materialization_offline_config():
backfill_time = BackfillTime(start=datetime(2020, 5, 20), end=datetime(2020, 5, 20), step=timedelta(days=1))
offlineSink = HdfsSink(
output_path="abfss://feathrazuretest3fs@feathrazuretest3storage.dfs.core.windows.net/demo_data/output/hdfs_test.avro"
)
settings = MaterializationSettings(
"nycTaxiTable",
sinks=[offlineSink],
feature_names=["f_location_avg_fare", "f_location_max_fare"],
backfill_time=backfill_time,
)
config = _to_materialization_config(settings)
expected_config = """
operational: {
name: nycTaxiTable
endTime: "2020-05-20 00:00:00"
endTimeFormat: "yyyy-MM-dd HH:mm:ss"
resolution: DAILY
enableIncremental = true
output:[
{
name: HDFS
outputFormat: RAW_DATA
params: {
path: "abfss://feathrazuretest3fs@feathrazuretest3storage.dfs.core.windows.net/demo_data/output/hdfs_test.avro"
features: [f_location_avg_fare,f_location_max_fare]
storeName: "df0"
}
}
]
}
features: [f_location_avg_fare, f_location_max_fare]
"""
assert "".join(config.split()) == "".join(expected_config.split())
def test_feature_materialization_aerospike_sink_config():
as_sink = AerospikeSink(name="aerospike", seedhost="20.57.186.153", port=3000, namespace="test", setname="test")
backfill_time = BackfillTime(start=datetime(2020, 5, 20), end=datetime(2020, 5, 20), step=timedelta(days=1))
settings = MaterializationSettings(
"nycTaxiTable", sinks=[as_sink], feature_names=["avgfare", "maxfare"], backfill_time=backfill_time
)
os.environ[f"aerospike_USER"] = "feathruser"
os.environ[f"aerospike_PASSWORD"] = "feathrpwd"
expected_config = """
operational: {
name: nycTaxiTable
endTime: "2020-05-20 00:00:00"
endTimeFormat: "yyyy-MM-dd HH:mm:ss"
resolution: DAILY
output:[
{
"name": "HDFS",
"params": {
"aerospike__seedhost": "20.57.186.153",
"aerospike__port": "3000",
"aerospike__namespace": "test",
"aerospike__user": "${AEROSPIKE_USER}",
"aerospike__password": "${AEROSPIKE_PASSWORD}",
"aerospike__set": "test",
"type": "generic",
"format": "aerospike",
"mode": "APPEND"
}
}
]
}
features: [avgfare, maxfare]
"""
config = _to_materialization_config(settings)
assert "".join(config.split()) == "".join(expected_config.split())
def test_feature_materialization_daily_schedule():
"""Test back fill cutoff time for a daily range"""
backfill_time = BackfillTime(start=datetime(2022, 3, 1), end=datetime(2022, 3, 5), step=timedelta(days=1))
settings = MaterializationSettings("", [], [], backfill_time)
expected = [datetime(2022, 3, day) for day in range(1, 6)]
assert settings.get_backfill_cutoff_time() == expected
def test_feature_materialization_hourly_schedule():
"""Test back fill cutoff time for a hourly range"""
backfill_time = BackfillTime(start=datetime(2022, 3, 1, 1), end=datetime(2022, 3, 1, 5), step=timedelta(hours=1))
settings = MaterializationSettings("", [], [], backfill_time)
expected = [datetime(2022, 3, 1, hour) for hour in range(1, 6)]
assert settings.get_backfill_cutoff_time() == expected
def test_feature_materialization_now_schedule():
"""Test back fill cutoff time without backfill."""
settings = MaterializationSettings("", [], [])
date = settings.get_backfill_cutoff_time()[0]
expected = datetime.now()
assert expected.year == date.year
assert expected.month == date.month
assert expected.day == date.day
def test_build_feature_verbose():
"""
Test verbose for pretty printing features
"""
test_workspace_dir = Path(__file__).parent.resolve() / "test_user_workspace"
client = basic_test_setup(os.path.join(test_workspace_dir, "feathr_config.yaml"))
# An anchor feature
features = [
Feature(name="trip_distance", feature_type=FLOAT),
Feature(name="f_is_long_trip_distance", feature_type=BOOLEAN, transform="cast_float(trip_distance)>30"),
Feature(name="f_day_of_week", feature_type=INT32, transform="dayofweek(lpep_dropoff_datetime)"),
]
anchor = FeatureAnchor(name="request_features", source=INPUT_CONTEXT, features=features)
# Check pretty print
client.build_features(anchor_list=[anchor], verbose=True)
def test_get_offline_features_verbose():
"""
Test verbose for pretty printing feature query
"""
test_workspace_dir = Path(__file__).parent.resolve() / "test_user_workspace"
client = basic_test_setup(os.path.join(test_workspace_dir, "feathr_config.yaml"))
location_id = TypedKey(key_column="DOLocationID", key_column_type=ValueType.INT32)
feature_query = FeatureQuery(feature_list=["f_location_avg_fare"], key=location_id)
settings = ObservationSettings(
observation_path="wasbs://public@azurefeathrstorage.blob.core.windows.net/sample_data/green_tripdata_2020-04",
event_timestamp_column="lpep_dropoff_datetime",
timestamp_format="yyyy-MM-dd HH:mm:ss",
)
now = datetime.now()
# set output folder based on different runtime
if client.spark_runtime == "databricks":
output_path = "".join(["dbfs:/feathrazure_cijob", "_", str(now.minute), "_", str(now.second), ".parquet"])
else:
output_path = "".join(
[
"abfss://feathrazuretest3fs@feathrazuretest3storage.dfs.core.windows.net/demo_data/output",
"_",
str(now.minute),
"_",
str(now.second),
".parquet",
]
)
# Check pretty print
client.get_offline_features(
observation_settings=settings,
feature_query=feature_query,
output_path=output_path,
execution_configurations=SparkExecutionConfiguration(
{"spark.feathr.inputFormat": "parquet", "spark.feathr.outputFormat": "parquet"}
),
verbose=True,
)
def test_get_offline_features_auto_correct_dataset():
test_workspace_dir = Path(__file__).parent.resolve() / "test_user_workspace"
client = conflicts_auto_correction_setup(os.path.join(test_workspace_dir, "feathr_config.yaml"))
now = datetime.now()
location_id = TypedKey(
key_column="DOLocationID",
key_column_type=ValueType.INT32,
description="location id in NYC",
full_name="nyc_taxi.location_id",
)
feature_query = FeatureQuery(feature_list=["tip_amount", "total_amount"], key=location_id)
settings = ObservationSettings(
observation_path="wasbs://public@azurefeathrstorage.blob.core.windows.net/sample_data/green_tripdata_2020-04_with_index.csv",
event_timestamp_column="lpep_dropoff_datetime",
timestamp_format="yyyy-MM-dd HH:mm:ss",
conflicts_auto_correction=ConflictsAutoCorrection(rename_features=False, suffix="test"),
)
# set output folder based on different runtime
if client.spark_runtime == "databricks":
output_path = "".join(["dbfs:/feathrazure_cijob", "_", str(now.minute), "_", str(now.second), ".avro"])
else:
output_path = "".join(
[
"abfss://feathrazuretest3fs@feathrazuretest3storage.dfs.core.windows.net/demo_data/output",
"_",
str(now.minute),
"_",
str(now.second),
".avro",
]
)
client.get_offline_features(observation_settings=settings, feature_query=feature_query, output_path=output_path)
client.wait_job_to_finish(timeout_sec=500)
res_df = get_result_df(client, data_format="avro", res_url=output_path)
assert res_df.shape[0] > 0
def test_get_offline_features_auto_correct_features():
test_workspace_dir = Path(__file__).parent.resolve() / "test_user_workspace"
client = conflicts_auto_correction_setup(os.path.join(test_workspace_dir, "feathr_config.yaml"))
now = datetime.now()
location_id = TypedKey(
key_column="DOLocationID",
key_column_type=ValueType.INT32,
description="location id in NYC",
full_name="nyc_taxi.location_id",
)
feature_query = FeatureQuery(feature_list=["tip_amount", "total_amount"], key=location_id)
settings = ObservationSettings(
observation_path="wasbs://public@azurefeathrstorage.blob.core.windows.net/sample_data/green_tripdata_2020-04_with_index.csv",
event_timestamp_column="lpep_dropoff_datetime",
timestamp_format="yyyy-MM-dd HH:mm:ss",
conflicts_auto_correction=ConflictsAutoCorrection(rename_features=True, suffix="test"),
)
# set output folder based on different runtime
if client.spark_runtime == "databricks":
output_path = "".join(["dbfs:/feathrazure_cijob", "_", str(now.minute), "_", str(now.second), ".avro"])
else:
output_path = "".join(
[
"abfss://feathrazuretest3fs@feathrazuretest3storage.dfs.core.windows.net/demo_data/output",
"_",
str(now.minute),
"_",
str(now.second),
".avro",
]
)
client.get_offline_features(observation_settings=settings, feature_query=feature_query, output_path=output_path)
client.wait_job_to_finish(timeout_sec=500)
res_df = get_result_df(client, data_format="avro", res_url=output_path)
assert res_df.shape[0] > 0
def test_materialize_features_verbose():
online_test_table = get_online_test_table_name("nycTaxiCITableMaterializeVerbose")
test_workspace_dir = Path(__file__).parent.resolve() / "test_user_workspace"
client: FeathrClient = basic_test_setup(os.path.join(test_workspace_dir, "feathr_config.yaml"))
backfill_time = BackfillTime(start=datetime(2020, 5, 20), end=datetime(2020, 5, 20), step=timedelta(days=1))
redisSink = RedisSink(table_name=online_test_table)
settings = MaterializationSettings(
"nycTaxiTable",
sinks=[redisSink],
feature_names=["f_location_avg_fare", "f_location_max_fare"],
backfill_time=backfill_time,
)
client.materialize_features(settings, verbose=True)
client._clean_test_data(online_test_table)
def add_new_fare_amount(df: DataFrame) -> DataFrame:
df = df.withColumn("fare_amount_new", col("fare_amount") + 8000000)
return df
def test_delete_feature_from_redis():
"""
Test FeathrClient() delete_feature_from_redis to remove feature from Redis.
"""
test_workspace_dir = Path(__file__).parent.resolve() / "test_user_workspace"
client: FeathrClient = basic_test_setup(os.path.join(test_workspace_dir, "feathr_config.yaml"))
batch_source = HdfsSource(
name="nycTaxiBatchSource_add_new_fare_amount",
path="wasbs://public@azurefeathrstorage.blob.core.windows.net/sample_data/green_tripdata_2020-04.csv",
preprocessing=add_new_fare_amount,
event_timestamp_column="lpep_dropoff_datetime",
timestamp_format="yyyy-MM-dd HH:mm:ss",
)
pickup_time_as_id = TypedKey(
key_column="lpep_pickup_datetime",
key_column_type=ValueType.INT32,
description="location id in NYC",
full_name="nyc_taxi.location_id",
)
features = [
Feature(name="f_is_long_trip_distance", key=pickup_time_as_id, feature_type=FLOAT, transform="fare_amount_new"),
Feature(
name="f_day_of_week",
key=pickup_time_as_id,
feature_type=INT32,
transform="dayofweek(lpep_dropoff_datetime)",
),
]
regular_anchor = FeatureAnchor(
name="request_features_add_new_fare_amount",
source=batch_source,
features=features,
)
client.build_features(anchor_list=[regular_anchor])
online_test_table = get_online_test_table_name("nycTaxiCITableDeletion")
backfill_time = BackfillTime(start=datetime(2020, 5, 20), end=datetime(2020, 5, 20), step=timedelta(days=1))
redisSink = RedisSink(table_name=online_test_table)
settings = MaterializationSettings(
name="py_udf",
sinks=[redisSink],
feature_names=["f_is_long_trip_distance", "f_day_of_week"],
backfill_time=backfill_time,
)
client.materialize_features(settings, allow_materialize_non_agg_feature=True)
client.wait_job_to_finish(timeout_sec=Constants.SPARK_JOB_TIMEOUT_SECONDS)
res = client.get_online_features(
online_test_table, "2020-04-01 07:21:51", ["f_is_long_trip_distance", "f_day_of_week"]
)
assert len(res) == 2
assert res[0] != None
assert res[1] != None
# Delete online feature stored in Redis
client.delete_feature_from_redis(online_test_table, "2020-04-01 07:21:51", "f_is_long_trip_distance")
# Check if the online feature is deleted successfully
res = client.get_online_features(online_test_table, "265", ["f_location_avg_fare"])
assert len(res) == 1
assert res[0] == None
client._clean_test_data(online_test_table)
def test_feature_list_on_input_context():
with pytest.raises(RuntimeError) as e_info:
test_workspace_dir = Path(__file__).parent.resolve() / "test_user_workspace"
client: FeathrClient = basic_test_setup(os.path.join(test_workspace_dir, "feathr_config.yaml"))
online_test_table = get_online_test_table_name("nycTaxiCITableDeletion")
redisSink = RedisSink(table_name=online_test_table)
settings = MaterializationSettings(
name="py_udf", sinks=[redisSink], feature_names=["f_location_avg_fare", "f_day_of_week"]
)
client.materialize_features(settings, allow_materialize_non_agg_feature=True)
assert e_info is not None
assert (
e_info.value.args[0]
== "Materializing features that are defined on INPUT_CONTEXT is not supported. f_day_of_week is defined on INPUT_CONTEXT so you should remove it from the feature list in MaterializationSettings."
)